int pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, struct timespec* abstime) { DWORD timeout = get_milliseconds(abstime); if (!SleepConditionVariableCS(cond, mutex, timeout)) return ETIMEDOUT; return 0; }
PUBLIC int save_attack_state() { int db_result; if(is_benchmark) return TRUE; key_providers[batch[current_attack_index].provider_index].save_resume_arg(batch[current_attack_index].resume_arg); db_result = BEGIN_TRANSACTION; //if(db_result != SQLITE_OK) return FALSE; sqlite3_reset(save_state_update); sqlite3_bind_int (save_state_update, 1, seconds_since_start(TRUE)); sqlite3_bind_int64(save_state_update, 2, batch[current_attack_index].attack_db_id); sqlite3_bind_text (save_state_update, 3, batch[current_attack_index].resume_arg, -1, SQLITE_STATIC); sqlite3_bind_int64(save_state_update, 4, get_num_keys_served()); sqlite3_step(save_state_update); HS_ENTER_MUTEX(&found_keys_mutex); save_passwords_found(); HS_LEAVE_MUTEX(&found_keys_mutex); END_TRANSACTION; save_time = get_milliseconds(); //num_keys_served_from_start += num_keys_served_from_save; //num_keys_served_from_save = 0; add_num_keys_from_save_to_start(); return TRUE; }
void animation_timer_trigger(void* data) { #ifdef PROFILE uint32_t paint_start_time = get_milliseconds(); #endif paint(); #ifdef PROFILE uint32_t paint_time = get_milliseconds() - paint_start_time; min_time = min_time > paint_time ? paint_time : min_time; max_time = max_time < paint_time ? paint_time : max_time; total_time += paint_time; samples++; APP_LOG(APP_LOG_LEVEL_DEBUG, "PAINT %ums (min %ums, max %ums, avg %ums)", (unsigned) paint_time, (unsigned) min_time, (unsigned) max_time, (unsigned)(total_time / samples)); #endif layer_mark_dirty((Layer*) frameBufferLayer); g_timer = app_timer_register(c_refreshTimer, animation_timer_trigger, NULL); }
void draw_map(int cx, int cy) { int x, y, symcount, attr, cursx, cursy; unsigned int frame; struct curses_symdef syms[4]; if (!display_buffer || !mapwin) return; getyx(mapwin, cursy, cursx); frame = 0; if (settings.blink) frame = get_milliseconds() / 666; for (y = 0; y < ROWNO; y++) { for (x = 1; x < COLNO; x++) { int bg_color = 0; /* set the position for each character to prevent incorrect positioning due to charset issues (IBM chars on a unicode term or vice versa) */ wmove(mapwin, y, x - 1); symcount = mapglyph(&display_buffer[y][x], syms, &bg_color); attr = A_NORMAL; if (!(COLOR_PAIRS >= 113 || (COLORS < 16 && COLOR_PAIRS >= 57))) { /* we don't have background colors available */ bg_color = 0; if (((display_buffer[y][x].monflags & MON_TAME) && settings.hilite_pet) || ((display_buffer[y][x].monflags & MON_DETECTED) && settings.use_inverse)) attr |= A_REVERSE; } else if (bg_color == 0) { /* we do have background colors available */ if ((display_buffer[y][x].monflags & MON_DETECTED) && settings.use_inverse) bg_color = CLR_MAGENTA; if ((display_buffer[y][x].monflags & MON_PEACEFUL) && settings.hilite_pet) bg_color = CLR_BROWN; if ((display_buffer[y][x].monflags & MON_TAME) && settings.hilite_pet) bg_color = CLR_BLUE; } print_sym(mapwin, &syms[frame % symcount], attr, bg_color); } } wmove(mapwin, cursy, cursx); wnoutrefresh(mapwin); }
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { if (have_native_conditions) { DWORD timeout= get_milliseconds(abstime); if (!my_SleepConditionVariableCS(&cond->native_cond, mutex, timeout)) return ETIMEDOUT; return 0; } else return legacy_cond_timedwait(cond, mutex, abstime); }
//---------------------------------------------------------------------------------------------------------------------------------- // Create and allocate a new context with profile specific data // Param state: pointer to decompressor // Param with_cid: context-id (not used for now) // Param profile: profile to be assigned with context // Return: pointer to new context if allocatable, else NULL //---------------------------------------------------------------------------------------------------------------------------------- struct sd_context * context_create(struct sd_rohc * state, int with_cid, struct s_profile * profile) { struct sd_context * pnew = (struct sd_context*)kmalloc(sizeof(struct sd_context), GFP_ATOMIC); if(!pnew) { rohc_debugf(0,"[ERROR] context_create(): unable to allocate memory!\n"); return(NULL); } pnew->profile = profile; pnew->mode = ROHC_U_MODE; pnew->state = ROHC_NO_CONTEXT; pnew->data = profile->allocate_decode_data(); if(!pnew->data) { kfree(pnew); return(NULL); } pnew->curval = 0; pnew->num_recv_packets = 0; pnew->total_uncompressed_size = 0; pnew->total_compressed_size = 0; pnew->header_uncompressed_size = 0; pnew->header_compressed_size = 0; pnew->num_recv_ir = 0; pnew->num_recv_ir_dyn = 0; pnew->num_sent_feedbacks = 0; pnew->num_decomp_failures = 0; pnew->num_decomp_repairs = 0; pnew->first_used = get_milliseconds(); pnew->latest_used = get_milliseconds(); pnew->total_16_uncompressed = c_create_wlsb(32, 16, 0); // create a window with 16 entries.. pnew->total_16_compressed = c_create_wlsb(32, 16, 0); pnew->header_16_uncompressed = c_create_wlsb(32, 16, 0); pnew->header_16_compressed = c_create_wlsb(32, 16, 0); return(pnew); }
static int func_time_start(struct sip_msg *msg, char *key) { int_str avp_key, avp_val; char unix_time[20]; get_milliseconds(unix_time); avp_key.s.s = key; avp_key.s.len = strlen(avp_key.s.s); avp_val.s.s = unix_time; avp_val.s.len = strlen(avp_val.s.s); if (add_avp(AVP_NAME_STR|AVP_VAL_STR, avp_key, avp_val) < 0) { LM_ERR("Statsd: time start failed to create AVP\n"); return -1; } return 1; }
static int legacy_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime) { int result; DWORD timeout; timeout= get_milliseconds(abstime); /* Block access if previous broadcast hasn't finished. This is just for safety and should normally not affect the total time spent in this function. */ WaitForSingleObject(cond->broadcast_block_event, INFINITE); EnterCriticalSection(&cond->lock_waiting); cond->waiting++; LeaveCriticalSection(&cond->lock_waiting); LeaveCriticalSection(mutex); result= WaitForMultipleObjects(2, cond->events, FALSE, timeout); EnterCriticalSection(&cond->lock_waiting); cond->waiting--; if (cond->waiting == 0) { /* We're the last waiter to be notified or to stop waiting, so reset the manual event. */ /* Close broadcast gate */ ResetEvent(cond->events[BROADCAST]); /* Open block gate */ SetEvent(cond->broadcast_block_event); } LeaveCriticalSection(&cond->lock_waiting); EnterCriticalSection(mutex); return result == WAIT_TIMEOUT ? ETIMEDOUT : 0; }
int main( int argc, char **argv ) { cairo_surface_t *surface; int j; surface = output_create_surface (argv [0], WIDTH, HEIGHT); fprintf (stderr, "Testing lines...\n"); test (surface); cairo_surface_write_to_png (surface, "lines-out.png"); for (j = 0; j < NUM_RUNS; j++) { int cur = test (surface); fprintf (stderr, "\t%d: %d (%.2f ms)\n", j, cur, get_milliseconds (cur)); } cairo_surface_destroy( surface ); output_cleanup (); return 0; }
static int func_time_end(struct sip_msg *msg, char *key) { char unix_time[20]; char *endptr; long int start_time; int result; struct search_state st; get_milliseconds(unix_time); LM_DBG("Statsd: statsd_stop at %s\n",unix_time); avp_t* prev_avp; int_str avp_value, avp_name; avp_name.s.s = key; avp_name.s.len = strlen(avp_name.s.s); prev_avp = search_first_avp( AVP_NAME_STR|AVP_VAL_STR, avp_name, &avp_value, &st); if(avp_value.s.len == 0){ LM_ERR("Statsd: statsd_stop not valid key(%s)\n",key); return 1; } start_time = strtol(avp_value.s.s, &endptr,10); if(strlen(endptr) >0){ LM_DBG( "Statsd:statsd_stop not valid key(%s) it's not a number value=%s\n", key, avp_value.s.s); return 0; } result = atol(unix_time) - start_time; LM_DBG( "Statsd: statsd_stop Start_time=%ld unix_time=%ld (%i)\n", start_time, atol(unix_time), result); destroy_avp(prev_avp); return statsd_timing(key, result); }
EVQ_API int evq_init (struct event_queue *evq) { evq->events = malloc(NEVENT * sizeof(void *)); if (!evq->events) return -1; evq->fdset = malloc(NEVENT * sizeof(struct pollfd)); if (!evq->fdset) { free(evq->events); return -1; } pthread_mutex_init(&evq->cs, NULL); { fd_t *sig_fd = evq->sig_fd; struct pollfd *fdp; sig_fd[0] = sig_fd[1] = (fd_t) -1; if (pipe(sig_fd) || fcntl(sig_fd[0], F_SETFL, O_NONBLOCK)) goto err; fdp = &evq->fdset[0]; fdp->fd = sig_fd[0]; fdp->events = POLLIN; fdp->revents = 0; } evq->npolls++; evq->max_polls = NEVENT; evq->now = get_milliseconds(); return 0; err: evq_done(evq); return -1; }
PRIVATE void begin_crack(void* pset_start_time) { unsigned int i, j; int thread_id = 0; int set_start_time = (int)pset_start_time; // Find best implementations. Assume there is at least one compatible perform_crypt_funtion* perform_crypt = NULL; generate_key_funtion* generate = NULL; #ifdef HS_OPENCL_SUPPORT // For GPU compilation and then execution create_gpu_crypt_funtion* create_gpu_crypt = NULL; gpu_crypt_funtion** crypt_ptr_func = NULL; #endif if(is_benchmark) load_hashes_benchmark(batch[current_attack_index].format_index); else load_hashes(batch[current_attack_index].format_index); continue_attack = TRUE; //num_keys_served_from_save = 0; //num_keys_served_from_start += batch[current_attack_index].num_keys_served; set_num_keys_save_add_start(0, batch[current_attack_index].num_keys_served); key_providers[batch[current_attack_index].provider_index].resume(batch[current_attack_index].min_lenght, batch[current_attack_index].max_lenght, batch[current_attack_index].params, batch[current_attack_index].resume_arg, batch[current_attack_index].format_index); // GPUs num_threads = 0; #ifdef HS_OPENCL_SUPPORT for(j = 0; j < LENGHT(formats[batch[current_attack_index].format_index].opencl_impls); j++) { create_gpu_crypt = formats[batch[current_attack_index].format_index].opencl_impls[j].perform_crypt; for(i = 0; i < LENGHT(key_providers[batch[current_attack_index].provider_index].impls); i++) { generate = key_providers[batch[current_attack_index].provider_index].impls[i].generate; if(formats[batch[current_attack_index].format_index].opencl_impls[j].protocol == key_providers[batch[current_attack_index].provider_index].impls[i].protocol) goto out_opencl; else generate = NULL; } } out_opencl: if(generate) { // For GPU first create all params to execution (create opencl code, compile...) ocl_crypt_ptr_params = (OpenCL_Param**)calloc(num_gpu_devices, sizeof(OpenCL_Param*)); crypt_ptr_func = (gpu_crypt_funtion**)malloc(sizeof(gpu_crypt_funtion*)*num_gpu_devices); for(i = 0; i < num_gpu_devices; i++) if (gpu_devices[i].flags & GPU_FLAG_IS_USED) { ocl_crypt_ptr_params[i] = (OpenCL_Param*)calloc(1, sizeof(OpenCL_Param)); create_gpu_crypt(ocl_crypt_ptr_params[i], i, generate, &(crypt_ptr_func[i])); } } #endif // CPU num_threads += app_num_threads; perform_crypt = NULL; generate = NULL; for(j = 0; j < LENGHT(formats[batch[current_attack_index].format_index].impls); j++) { perform_crypt = formats[batch[current_attack_index].format_index].impls[j].perform_crypt; for(i = 0; i < LENGHT(key_providers[batch[current_attack_index].provider_index].impls); i++) { generate = key_providers[batch[current_attack_index].provider_index].impls[i].generate; if(current_cpu.capabilites[formats[batch[current_attack_index].format_index].impls[j].needed_cap] && formats[batch[current_attack_index].format_index].impls[j].protocol == key_providers[batch[current_attack_index].provider_index].impls[i].protocol) goto out; } } out: #ifdef HS_OPENCL_SUPPORT // Count total threads----------------------------- if(ocl_crypt_ptr_params && crypt_ptr_func) for(i = 0; i < num_gpu_devices; i++) if ((gpu_devices[i].flags & GPU_FLAG_IS_USED) && ocl_crypt_ptr_params[i]) num_threads++; #endif // If is LM charset not implemented in GPU->use CPU if(!app_num_threads && batch[current_attack_index].format_index == LM_INDEX && batch[current_attack_index].provider_index == CHARSET_INDEX) num_threads++; // Create per thread data num_thread_params = num_threads; thread_params = calloc(num_threads, key_providers[batch[current_attack_index].provider_index].per_thread_data_size); crypto_params = (CryptParam*)calloc(num_threads, sizeof(CryptParam)); #ifdef HS_OPENCL_SUPPORT // Then execute the GPU kernels if(ocl_crypt_ptr_params && crypt_ptr_func) { for(i = 0; i < num_gpu_devices; i++) if ((gpu_devices[i].flags & GPU_FLAG_IS_USED) && ocl_crypt_ptr_params[i]) { ocl_crypt_ptr_params[i]->thread_id = thread_id; HS_NEW_THREAD(crypt_ptr_func[i], ocl_crypt_ptr_params[i]); thread_id++; } free(crypt_ptr_func); } #endif // If is LM charset not implemented in GPU->use CPU if(!app_num_threads && batch[current_attack_index].format_index == LM_INDEX && batch[current_attack_index].provider_index == CHARSET_INDEX) { crypto_params[thread_id].gen = generate; crypto_params[thread_id].thread_id = thread_id; HS_NEW_THREAD(perform_crypt, crypto_params+thread_id); thread_id++; } else for (i = 0; i < app_num_threads; i++, thread_id++) { crypto_params[thread_id].gen = generate; crypto_params[thread_id].thread_id = thread_id; HS_NEW_THREAD(perform_crypt, crypto_params+thread_id); } save_time = get_milliseconds(); if (set_start_time) start_time = get_milliseconds(); send_message_gui(MESSAGE_ATTACK_INIT_COMPLETE); }
void set_request_time() { request_time = get_milliseconds(); };
/* * Returns: milliseconds (number) */ static int sys_msec (lua_State *L) { lua_pushnumber(L, get_milliseconds()); return 1; }
PUBLIC uint32_t seconds_since_start(int isTotal) { return (uint32_t)((get_milliseconds() - start_time+500) / 1000 + (isTotal ? batch[current_attack_index].secs_before_this_attack : 0)); }
//---------------------------------------------------------------------------------------------------------------------------------- // Main function for decompressing a ROHC-packet. // Param state: pointer to decompressor // Param ibuf: pointer to incoming packet // Param isize: size of incoming packet // Param obuf: pointer to output buffer // Param osize: size of output buffer // Param ddata: struct that holds important information to pass between several functions // Return: size of decompressed packet //---------------------------------------------------------------------------------------------------------------------------------- int d_decode_header(struct sd_rohc * state, unsigned char * ibuf, int isize, unsigned char * obuf, int osize, struct sd_decode_data * ddata) { int largecid=0, size, irdynvar=0, casenew=0; struct s_profile * profile; unsigned char * walk = ibuf; if(isize < 2) return(ROHC_ERROR_NO_CONTEXT); ddata->cid = d_decode_feedback_first(state, &walk, isize); if(ddata->cid == ROHC_FEEDBACK_ONLY || ddata->cid == ROHC_ERROR_NO_CONTEXT) return(ddata->cid); if(ddata->cid > 0 && state->medium->cid_type == ROHC_SMALL_CID) ddata->addcidUsed=1; if(!ddata->addcidUsed && state->medium->cid_type == ROHC_LARGE_CID) { // check if large cids are used largecid = d_sdvalue_size(walk+1); if(largecid >0 && largecid < 3) { ddata->cid = d_sdvalue_decode(walk+1); ddata->largecidUsed=1; } else return(ROHC_ERROR_NO_CONTEXT); } if(d_is_ir(walk)) { profile = find_profile(walk[largecid+1]); if(!rohc_ir_packet_crc_ok(walk, largecid, ddata->addcidUsed, profile)) return(ROHC_ERROR_CRC); if(ddata->cid >= state->context_array_size) context_array_increase(state, ddata->cid); if(state->context[ddata->cid] && state->context[ddata->cid]->profile == profile) { ddata->active = state->context[ddata->cid]; state->context[ddata->cid] = NULL; } else { casenew=1; ddata->active = context_create(state, ddata->cid, profile); if(!ddata->active) return(ROHC_ERROR_NO_CONTEXT); } ddata->active->num_recv_ir ++; size = ddata->active->profile->decode_ir(state, ddata->active, walk+largecid+3, (isize-(walk-ibuf))-3-largecid, GET_BIT_0(walk), obuf); if(size>0) { context_free(state->context[ddata->cid]); state->context[ddata->cid] = ddata->active; return(size); } if(casenew) context_free(ddata->active); else state->context[ddata->cid] = ddata->active; return(size); } else { ddata->active = find_context(state, ddata->cid); // find context if(ddata->active && ddata->active->profile) { // context is valid ddata->active->latest_used = get_milliseconds(); if(d_is_irdyn(walk)) { ddata->active->num_recv_ir_dyn ++; profile = find_profile(walk[largecid+1]); if(profile != ddata->active->profile) { // if IR-DYN changes profile, make comp. transit to NO_CONTEXT-state state->curval = state->maxval; rohc_debugf(2,"IR-DYN changed profile, sending S-NACK.\n"); return(ROHC_ERROR_NO_CONTEXT); } if(!rohc_ir_dyn_packet_crc_ok(walk, largecid, ddata->addcidUsed, profile, ddata->active)) return(ROHC_ERROR_CRC); irdynvar += 2; } return(ddata->active->profile->decode(state, ddata->active, walk, (isize-(walk-ibuf)), (ddata->largecidUsed ? (1+largecid+irdynvar) : 1+irdynvar), obuf)); } else return(ROHC_ERROR_NO_CONTEXT); } return(ROHC_ERROR_NO_CONTEXT); }
//---------------------------------------------------------------------------------------------------------------------------------- // Decompressor Contexts // Param decomp: pointer to the decompressor // Param index: // Param buffer: //---------------------------------------------------------------------------------------------------------------------------------- int rohc_d_context(struct sd_rohc *decomp, int index, char *buffer) { char *modes[4]= {"error", "U-mode", "O-mode", "R-mode"}; char *states[4] = {"error", "NC", "SC", "FC"}; char *save; struct sd_context *c; int v; if (index >= decomp->context_array_size) return -2; c = decomp->context[index]; if (!c || !c->profile) return -1; save = buffer; buffer += strlen(buffer); sprintf(buffer, "\n---Context\n"); buffer += strlen(buffer); sprintf(buffer, "CONTEXTTYPE:Decompressor\n"); buffer += strlen(buffer); sprintf(buffer, "CID:%d\n", index); buffer += strlen(buffer); sprintf(buffer, "CID_STATE:%s\n", "USED"); buffer += strlen(buffer); sprintf(buffer, "STATE:%s\n", states[c->state]); buffer += strlen(buffer); sprintf(buffer, "MODE:%s\n", modes[c->mode]); buffer += strlen(buffer); sprintf(buffer, "PROFILE:%s\n", c->profile->description); buffer += strlen(buffer); if (c->total_uncompressed_size != 0) v = (100*c->total_compressed_size) / c->total_uncompressed_size; else v = 0; if (v < 0) { rohc_debugf(0, "decomp: total_compressed_size=%d total_uncompressed_size=%d\n", c->total_compressed_size, c->total_uncompressed_size); } sprintf(buffer, "TOTALCOMPRATIOALLPACK:%d%%\n", v); buffer += strlen(buffer); if (c->header_uncompressed_size != 0) v = (100*c->header_compressed_size) / c->header_uncompressed_size; else v = 0; sprintf(buffer, "TOTALCOMPRATIOALLPACKHEAD:%d%%\n", v); buffer += strlen(buffer); v = c->total_compressed_size/c->num_recv_packets; sprintf(buffer, "MEANCOMPPACKSIZEALLPACK:%d\n", v); buffer += strlen(buffer); v = c->header_compressed_size/c->num_recv_packets; sprintf(buffer, "MEANHEADSIZEALLCOMPHEAD:%d\n", v); buffer += strlen(buffer); v = c_sum_wlsb(c->total_16_uncompressed); if (v != 0) v = (100 * c_sum_wlsb(c->total_16_compressed)) / v; sprintf(buffer, "COMPRATIOLAST16PACK:%d%%\n", v); buffer += strlen(buffer); v = c_sum_wlsb(c->header_16_uncompressed); if (v != 0) v = (100 * c_sum_wlsb(c->header_16_compressed)) / v; sprintf(buffer, "COMPRATIOLAST16PACKHEAD:%d%%\n", v); buffer += strlen(buffer); v = c_mean_wlsb(c->total_16_compressed); sprintf(buffer, "MEANCOMPPACKSIZELAST16PACK:%d\n", v); buffer += strlen(buffer); v = c_mean_wlsb(c->header_16_compressed); sprintf(buffer, "MEANHEADSIZELAST16COMPHEAD:%d\n", v); buffer += strlen(buffer); sprintf(buffer, "CONTEXTACTIVATIONTIME:%d\n", (get_milliseconds() - c->first_used) / 1000 ); buffer += strlen(buffer); sprintf(buffer, "CONTEXTIDLETIME:%d\n", (get_milliseconds() - c->latest_used) / 1000); buffer += strlen(buffer); sprintf(buffer, "NORECVPACKETS:%d\n", c->num_recv_packets); buffer += strlen(buffer); sprintf(buffer, "NORECVIRPACKETS:%d\n", c->num_recv_ir); buffer += strlen(buffer); sprintf(buffer, "NORECVIRDYNPACKETS:%d\n", c->num_recv_ir_dyn); buffer += strlen(buffer); sprintf(buffer, "NOSENTFEEDBACKS:%d\n", c->num_sent_feedbacks); buffer += strlen(buffer); sprintf(buffer, "NODECOMPFAILURES:%d\n", c->num_decomp_failures); buffer += strlen(buffer); sprintf(buffer, "NODECOMPREPAIRS:%d\n", c->num_decomp_repairs); buffer += strlen(buffer); return strlen(save); }
EVQ_API int evq_wait (struct event_queue *evq, msec_t timeout) { struct event *ev_ready; struct event **events = evq->events; struct pollfd *fdset = evq->fdset; const int npolls = evq->npolls; int i, nready; if (timeout != 0L) { timeout = timeout_get(evq->tq, timeout, evq->now); if (timeout == 0L) { ev_ready = timeout_process(evq->tq, NULL, evq->now); goto end; } } sys_vm_leave(); nready = poll(fdset, npolls, (int) timeout); sys_vm_enter(); evq->now = get_milliseconds(); if (nready == -1) return (errno == EINTR) ? 0 : EVQ_FAILED; if (timeout != TIMEOUT_INFINITE) { if (!nready) { ev_ready = !evq->tq ? NULL : timeout_process(evq->tq, NULL, evq->now); if (ev_ready) goto end; return EVQ_TIMEOUT; } timeout = evq->now; } ev_ready = NULL; if (fdset[0].revents & POLLIN) { fdset[0].revents = 0; ev_ready = signal_process_interrupt(evq, ev_ready, timeout); --nready; } for (i = 1; i < npolls; i++) { const int revents = fdset[i].revents; struct event *ev; unsigned int res; if (!revents) continue; fdset[i].revents = 0; ev = events[i]; res = EVENT_ACTIVE; if ((revents & POLLFD_READ) && (ev->flags & EVENT_READ)) res |= EVENT_READ_RES; if ((revents & POLLFD_WRITE) && (ev->flags & EVENT_WRITE)) res |= EVENT_WRITE_RES; if (revents & POLLHUP) res |= EVENT_EOF_RES; ev->flags |= res; if (ev->flags & EVENT_ONESHOT) evq_del(ev, 1); else if (ev->tq && !(ev->flags & EVENT_TIMEOUT_MANUAL)) timeout_reset(ev, timeout); ev->next_ready = ev_ready; ev_ready = ev; if (!--nready) break; } if (!ev_ready) return 0; end: evq->ev_ready = ev_ready; return 0; }
int sample_main(int argc, char *argv[]) { VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Pipeline Cache"; const bool depthPresent = true; process_command_line_args(info, argc, argv); init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_window_size(info, 500, 500); init_connection(info); init_window(info); init_swapchain_extension(info); init_device(info); init_command_pool(info); init_command_buffer(info); execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); init_depth_buffer(info); init_texture(info, "blue.ppm"); init_uniform_buffer(info); init_descriptor_and_pipeline_layouts(info, true); init_renderpass(info, depthPresent); init_shaders(info, vertShaderText, fragShaderText); init_framebuffers(info, depthPresent); init_vertex_buffer(info, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), true); init_descriptor_pool(info, true); init_descriptor_set(info, true); /* VULKAN_KEY_START */ // Check disk for existing cache data size_t startCacheSize = 0; void *startCacheData = nullptr; std::string directoryName = get_file_directory(); std::string readFileName = directoryName + "pipeline_cache_data.bin"; FILE *pReadFile = fopen(readFileName.c_str(), "rb"); if (pReadFile) { // Determine cache size fseek(pReadFile, 0, SEEK_END); startCacheSize = ftell(pReadFile); rewind(pReadFile); // Allocate memory to hold the initial cache data startCacheData = (char *)malloc(sizeof(char) * startCacheSize); if (startCacheData == nullptr) { fputs("Memory error", stderr); exit(EXIT_FAILURE); } // Read the data into our buffer size_t result = fread(startCacheData, 1, startCacheSize, pReadFile); if (result != startCacheSize) { fputs("Reading error", stderr); free(startCacheData); exit(EXIT_FAILURE); } // Clean up and print results fclose(pReadFile); printf(" Pipeline cache HIT!\n"); printf(" cacheData loaded from %s\n", readFileName.c_str()); } else { // No cache found on disk printf(" Pipeline cache miss!\n"); } if (startCacheData != nullptr) { // clang-format off // // Check for cache validity // // TODO: Update this as the spec evolves. The fields are not defined by the header. // // The code below supports SDK 0.10 Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 a device ID equal to VkPhysicalDeviceProperties::DeviceId written // as a stream of bytes, with the least significant byte first // // 4 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // // // The code must be updated for latest Vulkan spec, which contains the following table: // // Offset Size Meaning // ------ ------------ ------------------------------------------------------------------ // 0 4 length in bytes of the entire pipeline cache header written as a // stream of bytes, with the least significant byte first // 4 4 a VkPipelineCacheHeaderVersion value written as a stream of bytes, // with the least significant byte first // 8 4 a vendor ID equal to VkPhysicalDeviceProperties::vendorID written // as a stream of bytes, with the least significant byte first // 12 4 a device ID equal to VkPhysicalDeviceProperties::deviceID written // as a stream of bytes, with the least significant byte first // 16 VK_UUID_SIZE a pipeline cache ID equal to VkPhysicalDeviceProperties::pipelineCacheUUID // // clang-format on uint32_t headerLength = 0; uint32_t cacheHeaderVersion = 0; uint32_t vendorID = 0; uint32_t deviceID = 0; uint8_t pipelineCacheUUID[VK_UUID_SIZE] = {}; memcpy(&headerLength, (uint8_t *)startCacheData + 0, 4); memcpy(&cacheHeaderVersion, (uint8_t *)startCacheData + 4, 4); memcpy(&vendorID, (uint8_t *)startCacheData + 8, 4); memcpy(&deviceID, (uint8_t *)startCacheData + 12, 4); memcpy(pipelineCacheUUID, (uint8_t *)startCacheData + 16, VK_UUID_SIZE); // Check each field and report bad values before freeing existing cache bool badCache = false; if (headerLength <= 0) { badCache = true; printf(" Bad header length in %s.\n", readFileName.c_str()); printf(" Cache contains: 0x%.8x\n", headerLength); } if (cacheHeaderVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE) { badCache = true; printf(" Unsupported cache header version in %s.\n", readFileName.c_str()); printf(" Cache contains: 0x%.8x\n", cacheHeaderVersion); } if (vendorID != info.gpu_props.vendorID) { badCache = true; printf(" Vendor ID mismatch in %s.\n", readFileName.c_str()); printf(" Cache contains: 0x%.8x\n", vendorID); printf(" Driver expects: 0x%.8x\n", info.gpu_props.vendorID); } if (deviceID != info.gpu_props.deviceID) { badCache = true; printf(" Device ID mismatch in %s.\n", readFileName.c_str()); printf(" Cache contains: 0x%.8x\n", deviceID); printf(" Driver expects: 0x%.8x\n", info.gpu_props.deviceID); } if (memcmp(pipelineCacheUUID, info.gpu_props.pipelineCacheUUID, sizeof(pipelineCacheUUID)) != 0) { badCache = true; printf(" UUID mismatch in %s.\n", readFileName.c_str()); printf(" Cache contains: "); print_UUID(pipelineCacheUUID); printf("\n"); printf(" Driver expects: "); print_UUID(info.gpu_props.pipelineCacheUUID); printf("\n"); } if (badCache) { // Don't submit initial cache data if any version info is incorrect free(startCacheData); startCacheSize = 0; startCacheData = nullptr; // And clear out the old cache file for use in next run printf(" Deleting cache entry %s to repopulate.\n", readFileName.c_str()); if (remove(readFileName.c_str()) != 0) { fputs("Reading error", stderr); exit(EXIT_FAILURE); } } } // Feed the initial cache data into pipeline creation VkPipelineCacheCreateInfo pipelineCache; pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; pipelineCache.pNext = NULL; pipelineCache.initialDataSize = startCacheSize; pipelineCache.pInitialData = startCacheData; pipelineCache.flags = 0; res = vkCreatePipelineCache(info.device, &pipelineCache, nullptr, &info.pipelineCache); assert(res == VK_SUCCESS); // Free our initialData now that pipeline has been created free(startCacheData); // Time (roughly) taken to create the graphics pipeline timestamp_t start = get_milliseconds(); init_pipeline(info, depthPresent); timestamp_t elapsed = get_milliseconds() - start; printf(" vkCreateGraphicsPipeline time: %0.f ms\n", (double)elapsed); // Begin standard draw stuff init_presentable_image(info); VkClearValue clear_values[2]; init_clear_color_and_depth(info, clear_values); VkRenderPassBeginInfo rp_begin; init_render_pass_begin_info(info, rp_begin); rp_begin.clearValueCount = 2; rp_begin.pClearValues = clear_values; vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline); vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS, info.desc_set.data(), 0, NULL); const VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets); init_viewports(info); init_scissors(info); vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0); vkCmdEndRenderPass(info.cmd); execute_pre_present_barrier(info); res = vkEndCommandBuffer(info.cmd); assert(res == VK_SUCCESS); VkFence drawFence = {}; init_fence(info, drawFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submit_info = {}; init_submit_info(info, submit_info, pipe_stage_flags); /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, &submit_info, drawFence); assert(res == VK_SUCCESS); /* Now present the image in the window */ VkPresentInfoKHR present = {}; init_present_info(info, present); /* Make sure command buffer is finished before presenting */ do { res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); } while (res == VK_TIMEOUT); assert(res == VK_SUCCESS); res = vkQueuePresentKHR(info.queue, &present); assert(res == VK_SUCCESS); wait_seconds(1); if (info.save_images) write_ppm(info, "pipeline_cache"); // End standard draw stuff if (startCacheData) { // TODO: Create another pipeline, preferably different from the first // one and merge it here. Then store the merged one. } // Store away the cache that we've populated. This could conceivably happen // earlier, depends on when the pipeline cache stops being populated // internally. size_t endCacheSize = 0; void *endCacheData = nullptr; // Call with nullptr to get cache size res = vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, nullptr); assert(res == VK_SUCCESS); // Allocate memory to hold the populated cache data endCacheData = (char *)malloc(sizeof(char) * endCacheSize); if (!endCacheData) { fputs("Memory error", stderr); exit(EXIT_FAILURE); } // Call again with pointer to buffer res = vkGetPipelineCacheData(info.device, info.pipelineCache, &endCacheSize, endCacheData); assert(res == VK_SUCCESS); // Write the file to disk, overwriting whatever was there FILE *pWriteFile; std::string writeFileName = directoryName + "pipeline_cache_data.bin"; pWriteFile = fopen(writeFileName.c_str(), "wb"); if (pWriteFile) { fwrite(endCacheData, sizeof(char), endCacheSize, pWriteFile); fclose(pWriteFile); printf(" cacheData written to %s\n", writeFileName.c_str()); } else { // Something bad happened printf(" Unable to write cache data to disk!\n"); } /* VULKAN_KEY_END */ vkDestroyFence(info.device, drawFence, NULL); vkDestroySemaphore(info.device, info.presentCompleteSemaphore, NULL); destroy_pipeline(info); destroy_pipeline_cache(info); destroy_textures(info); destroy_descriptor_pool(info); destroy_vertex_buffer(info); destroy_framebuffers(info); destroy_shaders(info); destroy_renderpass(info); destroy_descriptor_and_pipeline_layouts(info); destroy_uniform_buffer(info); destroy_depth_buffer(info); destroy_swap_chain(info); destroy_command_buffer(info); destroy_command_pool(info); destroy_device(info); destroy_window(info); destroy_instance(info); return 0; }
void GL_draw_frame( void * vp ) { static float rot; static int t0; float s; glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLineWidth(1.f); set_camera_view(); if ( t0 == 0 ) { init_VBO(); t0 = 1; } int now = get_milliseconds(); /* while ( now - t0 > 20 ) { rot += 1.0f; t0 += 20; if ( rot > 360.f ) rot -= 360.f; if ( rot < 0.f ) rot += 360.f; } */ // hack to get rotation timer right const float p180 = 0.017453126f; const float c180p = 57.295776f; const float c2pi = 6.2831854f; const int ms_per_frame = 20; // milliseconds per frame const float rot_per_frame = 1.0f * p180; /* while ( now - t0 > ms_per_frame ) { rot += 1.0f; t0 += ms_per_frame; } */ static int set = 0; if ( t0 <= 0 ) t0 = 1; if ( now - t0 > 0 ) { int diff = now - t0; /* the rotation is incremented 1 rot_per_frame each 1 ms_per_frame */ float newrot = rot + (rot_per_frame/(float)ms_per_frame) * ((float)diff); if ( set < 20 ) core.printf( "hiccup > 2pi: before: %f, %f ", rot, sinf(rot) ); rot = newrot; // catch it up t0 = now; if ( set < 20 ) core.printf( "after: %f, %f\n", rot, sinf( rot ) ); // clamp if ( rot > c2pi ) { rot = rot - c2pi; set = 1; // no more print core.printf( " --> MARK <-- \n" ); } if ( set != 0 ) ++set; } const float rotdeg = rot * c180p; /// -- DRAW --- // rotating wire spiral glColor4ub( 255,255,255,255 ); glPushMatrix(); glRotatef( rotdeg, 0, 1, 0 ); draw_spiral( 24.0f, 10.f, 0.05f ); glPopMatrix(); // rotating circle glEnable(GL_TEXTURE_2D); glBindTexture( GL_TEXTURE_2D, core.materials.findByName( "jr_bob" )->img->texhandle ); glPushMatrix(); glTranslatef( 60.f, 60.f, -60.f ); glRotatef( rotdeg, 0, 1, 0 ); draw_circle( 0, 0, 10.f ); GL_TEX_SQUARE( -10.f, 30.f, 0.f, 20.f ); glRotatef( 180, 0, 1, 0 ); draw_circle( 0, 0, 10.f ); GL_TEX_SQUARE( -10.f, 30.f, 0.f, 20.f ); glBegin(GL_LINES); glVertex3f( 0, -30.f, 0 ); glVertex3f( 0, 30.f, 0 ); glEnd(); glPopMatrix(); glDisable( GL_TEXTURE_2D ); // FIXME : obviously move, later. tessellatedPlane_t& tes = *(tessellatedPlane_t*)vp; // heightmap triangles glInterleavedArrays( GL_C3F_V3F, 0, tes.array ); glDrawArrays( GL_TRIANGLE_STRIP, 0, tes.num_verts ); //glDrawArrays( GL_LINE_STRIP, 0, tes->num_verts ); // gazillion boxes core.drawer.drawLists(); // serpinski glColor4ub( 255,255,0,255 ); glPushMatrix(); glTranslatef( 250.f, 100.f, -250.f ); glRotatef( rotdeg * 1.618f, 0, 1, 0 ); glRotatef( rotdeg , 0.707, 0, -0.707 ); glDisable( GL_CULL_FACE ); draw_serpinski( 3, 40.f ); glEnable( GL_CULL_FACE ); glPopMatrix(); glColor4ub( 255,255,255,255 ); // icosahedron glPushMatrix(); glTranslatef( 500.f, 100.f, -250.f ); trans_spiral_f( rot, 50.f /*radius*/, 1.0f/*rot rate*/, 1.0f/*climb rate*/, 50.f /*ceiling*/ ); s = 14.f; s = (sinf( rot * 2.718f ) + 1.1f) * 14.f; glScalef( s, s, s ); glRotatef( rotdeg * 5.f, 0, 1, 0 ); glRotatef( rotdeg * 3.f , 0.707, 0, -0.707 ); glColor4ub( 230, 100, 0, 255 ); draw_icosahedron(); glColor4ub( 255, 255, 255, 255 ); draw_icosahedron_wire(); glPopMatrix(); // axis marker float l = 100.f; glColor3f( 1.f, 0.f, 1.f ); glLineWidth(2.f); glBegin( GL_LINES ); glVertex3i( 0,0,0 ); glVertex3i( 0,l,0); glVertex3i( 0,0,0 ); glVertex3i( l,0,0 ); glVertex3i( 0,0,0 ); glVertex3i( 0,0,-l ); glEnd(); // 4-sided glPushMatrix(); glTranslatef( 300, 100, 0 ); s = 20.f; glScalef( s, s, s ); glRotatef( rotdeg, 0, 1, 0 ); glColor4ub( 0, 255, 255, 128 ); draw_triangle4(0); glColor4ub( 255, 255, 255, 255 ); draw_triangle4(1); glPopMatrix(); // 4-sided, 2nd type glPushMatrix(); glTranslatef( 340, 100, 0 ); s = 20.f; glScalef( s, s, s ); glRotatef( rotdeg, 0, 1, 0 ); glColor4ub( 100, 0, 100, 128 ); draw_triangle4_2(0); glColor4ub( 255, 255, 255, 255 ); draw_triangle4(1); // inner lines don't draw right, so use first form glPopMatrix(); // 5-sided glPushMatrix(); glTranslatef( 100, 100, -50 ); s = 20.f; glScalef( s, s, s ); glRotatef( rotdeg, 1, 0, 0 ); glColor4ub( 100, 50, 0, 200 ); draw_triangle5(0); glColor4ub( 255, 255, 255, 255 ); draw_triangle5(1); glPopMatrix(); // unit-cube w/ tri glPushMatrix(); glTranslatef( 150.f, 130.f, -800.f ); glTranslatef( 0.f, 0.f, sinf(rot)*1600.f ); s = 20.f; glScalef( s, s, s ); glRotatef( 90, 1, 0, 0 ); glRotatef( sinf(rotdeg*0.03f)*180.f, 0, 1, 0 ); glColor4ub( 128,128,128,255 ); draw_unitcube(0); glColor4ub( 255,255,255,255 ); draw_unitcube(1); glTranslatef( 0, 1.f, 0.f ); glColor4ub( 128,128,128,255 ); draw_triangle5(0); glColor4ub( 255,255,255,255 ); draw_triangle5(1); glPopMatrix(); // test model //glEnable(GL_LIGHTING); glPushMatrix(); glTranslatef( 300.f, 75.f, 200.f ); glRotatef( 315.f, 0,1,0 ); glEnable(GL_LIGHT0); s = 550.f; glScalef( s, s, s ); glColor4ub( 255,255,255,255); //draw_test_model_Vertex_Arrays(); draw_test_model_VBO(); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4ub( 128,128,168,255 ); //draw_test_model_Vertex_Arrays(); draw_test_model_VBO(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPopMatrix(); glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glFlush(); SDL_GL_SwapBuffers(); }