int solve_PCA(const size_t P, const gsl_matrix * knm, const gsl_matrix * U, gsl_matrix * alpha, gsl_matrix * knmt) { int status = 0; const size_t nt = knm->size2; /* number of time stamps */ const size_t nnm = U->size1; gsl_matrix *R; /* R = knm - U*alpha */ struct timeval tv0, tv1; double residual; /* || knm - U*alpha || */ int rank; /* select largest P eigenvectors of SDM */ gsl_matrix_const_view Uv = gsl_matrix_const_submatrix(U, 0, 0, nnm, P); /* solve: U*alpha = Q */ fprintf(stderr, "solve_PCA: solving PCA problem for alpha..."); gettimeofday(&tv0, NULL); status = lapack_lls(&Uv.matrix, knm, alpha, &rank); gettimeofday(&tv1, NULL); /* compute: knm~ = U*alpha */ gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &Uv.matrix, alpha, 0.0, knmt); /* compute: R = knm - knm~ */ R = gsl_matrix_alloc(nnm, nt); gsl_matrix_memcpy(R, knm); gsl_matrix_sub(R, knmt); residual = norm_fro(R); fprintf(stderr, "done (%g seconds, status = %d, rank = %d, residual = %.12e)\n", time_diff(tv0, tv1), status, rank, residual); gsl_matrix_free(R); return status; }
//static void main_rawlog_dump(uint8_t data_valid) { static void main_rawlog_dump(struct AutopilotMessageVIUp* current_message) { struct timespec now; clock_gettime(TIMER, &now); struct raw_log_entry e; e.time = absTime(time_diff(now, start)); memcpy(&e.message, current_message, sizeof(*current_message)); write(raw_log_fd, &e, sizeof(e)); /*struct raw_log_entry e; e.time = absTime(time_diff(now, start)); e.message = current_message; RATES_COPY(e.gyro, imu_float.gyro); VECT3_COPY(e.accel, imu_float.accel); VECT3_COPY(e.mag, imu_float.mag); VECT3_COPY(e.ecef_pos, imu_ecef_pos); VECT3_COPY(e.ecef_vel, imu_ecef_vel); e.pressure_absolute = baro_measurement; e.data_valid = data_valid; write(raw_log_fd, &e, sizeof(e)); */ }
/* * This is a watchdog timer that checks to see when we're idle enough to * turn on CPU SAVER mode. The above timers may honor what we do here but * they're not required to. */ int cpu_saver_timer (void *schedule_only) { double interval; double been_idlin; if (cpu_saver) return 0; get_time(&now); been_idlin = time_diff(idle_time, now); interval = get_int_var(CPU_SAVER_AFTER_VAR) * 60; if (interval < 1) return 0; if (been_idlin > interval) cpu_saver_on(0, NULL); else add_timer(1, cpu_saver_timeref, interval - been_idlin, 1, cpu_saver_timer, NULL, NULL, -1); return 0; }
void delete_todelete( ) // delete chs from the todelete list { TODELETE_DATA *todelete; // declare the todelete variable for ( todelete = todelete_list; todelete; todelete = todelete->next ) // parse the todelete list { if ( time_diff( todelete->timestamp, current_time, ' ' ) < 0 ) // if the time is up { CHAR_DATA *dch; // declare the ch variable for ( dch = char_list; dch; dch = dch->next ) // parse the currently playing ch list { if ( !strcmp( dch->name, todelete->name ) ) // if found the ch { break; // exit the find ch loop } } if ( !dch ) // if no ch found { if ( !( dch = load_char_remote( todelete->name ) ) ) // if can't load the ch from file { char buf[MSL]; // declare a char array sprintf( buf, "delete_todelete: can't find player: %s", todelete->name ); // prepare an error message bug( buf, 0 ); // send the error message to the bug channel remove_todelete( todelete->name ); // fix the todelete list return; // exit the function } } do_function( dch, &do_delete, "" ); // delete the ch } } return; // exit the function }
/* * Must be called with interrupts disabled, * and with the CPU time counter counting. */ void cpustats_tick() { struct timestamp ts; struct timestamp diff; int usec; if(enter_count == 0) { printf("cpustats_tick() called with enter_count == 0!\n"); return; } time_get(&ts); time_diff(&diff, &ts, &first_enter); time_add(&acc, &diff); usec = acc.sec*1000000+acc.usec; load = usec/10000; first_enter.sec = ts.sec; first_enter.usec = ts.usec; acc.sec = 0; acc.usec = 0; }
static int schedule_timer (Timer *ntimer) { Timer *tmp, *prev; /* we've created it, now put it in order */ for (tmp = PendingTimers; tmp; tmp = tmp->next) { if (time_diff(tmp->time, ntimer->time) < 0) break; } if (tmp == PendingTimers) { ntimer->prev = NULL; ntimer->next = PendingTimers; if (PendingTimers) PendingTimers->prev = ntimer; PendingTimers = ntimer; } else if (tmp) { prev = tmp->prev; ntimer->next = tmp; ntimer->prev = prev; tmp->prev = ntimer; prev->next = ntimer; } else /* XXX! */ { for (tmp = PendingTimers; tmp->next; tmp = tmp->next) ; tmp->next = ntimer; ntimer->prev = tmp; } return 0; }
/* * Wait for the top of a clock tick by reading /dev/rtc in a busy loop until * we see it. */ static int busywait_for_rtc_clock_tick(const int rtc_fd) { struct tm start_time; /* The time when we were called (and started waiting) */ struct tm nowtime; int rc; struct timeval begin, now; if (debug) printf(_("Waiting in loop for time from %s to change\n"), rtc_dev_name); rc = do_rtc_read_ioctl(rtc_fd, &start_time); if (rc) return 1; /* * Wait for change. Should be within a second, but in case * something weird happens, we have a time limit (1.5s) on this loop * to reduce the impact of this failure. */ gettimeofday(&begin, NULL); do { rc = do_rtc_read_ioctl(rtc_fd, &nowtime); if (rc || start_time.tm_sec != nowtime.tm_sec) break; gettimeofday(&now, NULL); if (time_diff(now, begin) > 1.5) { warnx(_("Timed out waiting for time change.")); return 2; } } while (1); if (rc) return 3; return 0; }
void routine_action(t_data *data) { t_tlist *team; t_plist *list; t_timeval now; // // printf("starting action routine\n"); gettimeofday(&now, NULL); team = data->teams; while (team) { list = team->list; while (list) { if (!list->player->spell && list->player->actions && !list->player->actions->timer) list->player->actions->action(data, list->player->cs, list->player->actions->cmd, &list->player->actions->timer); else if (!list->player->spell && list->player->actions && time_diff(list->player->actions->timer, &now) >= 0) { list->player->actions->action(data, list->player->cs, list->player->actions->cmd, &list->player->actions->timer); action_delfirst(&list->player->actions); } list = list->next; } team = team->next; } (void)now; // // printf("ending action routine\n"); }
tracker_t * tracker_new (void) { tracker_t *tracker = g_new0 (tracker_t, 1); GTimeVal before, after; tracker->n_event_bytes = 0; tracker->n_allocated_bytes = DEFAULT_SIZE; tracker->events = g_malloc (DEFAULT_SIZE); tracker->stash = stack_stash_new (NULL); g_get_current_time (&before); populate_from_proc (tracker); g_get_current_time (&after); #if 0 g_print ("Time to populate %f\n", time_diff (&after, &before)); #endif return tracker; }
gettimeofday(&pre_time, NULL); /* use a simple matmul routine to produce control result */ matmul(A, B, control_matrix, a_dim1, a_dim2, b_dim2); /* record starting time */ gettimeofday(&start_time, NULL); /* perform matrix multiplication */ team_matmul(A, B, C, a_dim1, a_dim2, b_dim2); /* record finishing time */ gettimeofday(&stop_time, NULL); /* compute elapsed times and speedup factor */ control_time = time_diff(&pre_time, &start_time); mul_time = time_diff(&start_time, &stop_time); speedup = (float) control_time / mul_time; printf("Matmul time: %lld microseconds\n", mul_time); printf("control time : %lld microseconds\n", control_time); if (mul_time > 0 && control_time > 0) { printf("speedup: %.2fx\n", speedup); } /* now check that the team's matmul routine gives the same answer as the known working version */ check_result(C, control_matrix, a_dim1, b_dim2); /* free all matrices */ free_matrix(A);
char * win32_ls_file(const char *name, LPWIN32_FIND_DATA file, int remote, int si_units) { int ulen, glen, sz = 0; //struct tm *ltime = localtime(&st->st_mtime); char *user, *group; char buf[1024], mode[11+1], tbuf[12+1], ubuf[11+1], gbuf[11+1]; char sbuf[FMT_SCALED_STRSIZE]; SYSTEMTIME now; SYSTEMTIME ftime; time_t mtime = filetime_to_time_t( file->ftLastWriteTime ); BOOL time_conv_ok = FileTimeToSystemTime( &file->ftLastWriteTime, &ftime); struct tm *ltime = localtime( &mtime ); if (!time_conv_ok) { error("Failed to convert file time to localtime"); } strmode(0644, mode); if (!remote) { user = user_from_uid(0, 0); } else { snprintf(ubuf, sizeof ubuf, "%u", 0); user = ubuf; } if (!remote) { group = group_from_gid(0, 0); } else { snprintf(gbuf, sizeof gbuf, "%u", 0); group = gbuf; } if (time_conv_ok) { //now = time(NULL); GetSystemTime(&now); if ( (time_diff(now, ftime) / 10000000ULL) < (365*24*60*60) ) { //if (now - (365*24*60*60)/2 < st->st_mtime && // now >= st->st_mtime) sz = strftime(tbuf, sizeof tbuf, "%b %e %H:%M", ltime); } else { sz = strftime(tbuf, sizeof tbuf, "%b %e %Y", ltime); } } if (sz == 0) tbuf[0] = '\0'; ulen = MAX(strlen(user), 8); glen = MAX(strlen(group), 8); long long size = (file->nFileSizeHigh * (MAXDWORD+1)) + file->nFileSizeLow; if (si_units) { fmt_scaled(size, sbuf); snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8s %s %s", mode, 1 /*nlink -- FIXME */, ulen, user, glen, group, sbuf, tbuf, name); } else { snprintf(buf, sizeof buf, "%s %3u %-*s %-*s %8llu %s %s", mode, 1 /*nlink -- FIXME */, ulen, user, glen, group, size, tbuf, name); } return xstrdup(buf); }
double cccost(int outer_iter_num, int inner_iter_num) { int i, j; int rows_in_group; int cols_in_group; uint64_t num1, num0; double cost = 0; uint64_t num_in_submatrix; struct timeval stime, etime; double sec_elapsed = 0; gettimeofday(&stime, NULL); bs_msg("[cccost.%d.%d] %d row / %d col: ", outer_iter_num, inner_iter_num, global_rnum, global_cnum); if((rows_in_each_group_sorted=(unsigned int*)malloc(sizeof(unsigned int)*global_rnum))==NULL) { perror("rows_in_each_group_sorted malloc()"); exit(EXIT_FAILURE); } for(i=0; i<global_rnum; i++) rows_in_each_group_sorted[i] = rows_in_each_group[i]; if((cols_in_each_group_sorted=(unsigned int*)malloc(sizeof(unsigned int)*global_cnum))==NULL) { perror("cols_in_each_group_sorted malloc()"); exit(EXIT_FAILURE); } for(j=0; j<global_cnum; j++) cols_in_each_group_sorted[j] = cols_in_each_group[j]; cost = logstar2(global_rnum) + logstar2(global_cnum); qsort(rows_in_each_group_sorted, global_rnum, sizeof(unsigned int), compare); qsort(cols_in_each_group_sorted, global_cnum, sizeof(unsigned int), compare); for(i=0; i<global_rnum-1; i++) cost += ceil(log2(rows_in_each_group_bar(i))); for(j=0; j<global_cnum-1; j++) cost += ceil(log2(cols_in_each_group_bar(j))); for(i=0; i<global_rnum; i++) { rows_in_group = rows_in_each_group[i]; for(j=0; j<global_cnum; j++) { cols_in_group = cols_in_each_group[j]; num_in_submatrix = (uint64_t)rows_in_group*cols_in_group; cost += ceil(log2(num_in_submatrix+1)); num1 = global_g[i*global_cnum+j]; num0 = num_in_submatrix - num1; if (num1!=0 && num0!=0) cost += num1*log2((num1+num0)/(double)num1) + num0*log2((num1+num0)/(double)num0); } } bs_msg("%.2f", cost); gettimeofday(&etime, NULL); sec_elapsed = time_diff(etime, stime); bs_msg(" @ %um %.1fs\n", ((unsigned int)sec_elapsed / 60), ((sec_elapsed-(unsigned int)sec_elapsed)+(unsigned int)sec_elapsed%60)); free(rows_in_each_group_sorted); free(cols_in_each_group_sorted); return cost; }
/* * Prepare a report. type is either INTERVAL or FINAL */ static void report_flow(struct _flow* flow, int type) { DEBUG_MSG(LOG_DEBUG, "report_flow called for flow %d (type %d)", flow->id, type); struct _report* report = (struct _report*)malloc(sizeof(struct _report)); report->id = flow->id; report->type = type; if (type == INTERVAL) report->begin = flow->last_report_time; else report->begin = flow->first_report_time; gettime(&report->end); flow->last_report_time = report->end; /* abort if we were scheduled way to early for a interval report */ if (time_diff(&report->begin,&report->end) < 0.2 * flow->settings.reporting_interval && type == INTERVAL){ free(report); return; } report->bytes_read = flow->statistics[type].bytes_read; report->bytes_written = flow->statistics[type].bytes_written; report->request_blocks_read = flow->statistics[type].request_blocks_read; report->response_blocks_read = flow->statistics[type].response_blocks_read; report->request_blocks_written = flow->statistics[type].request_blocks_written; report->response_blocks_written = flow->statistics[type].response_blocks_written; report->rtt_min = flow->statistics[type].rtt_min; report->rtt_max = flow->statistics[type].rtt_max; report->rtt_sum = flow->statistics[type].rtt_sum; report->iat_min = flow->statistics[type].iat_min; report->iat_max = flow->statistics[type].iat_max; report->iat_sum = flow->statistics[type].iat_sum; report->delay_min = flow->statistics[type].delay_min; report->delay_max = flow->statistics[type].delay_max; report->delay_sum = flow->statistics[type].delay_sum; /* Currently this will only contain useful information on Linux * and FreeBSD */ report->tcp_info = flow->statistics[type].tcp_info; if (flow->fd != -1) { /* Get latest MTU */ flow->pmtu = get_pmtu(flow->fd); report->pmtu = flow->pmtu; if (type == FINAL) report->imtu = get_imtu(flow->fd); else report->imtu = 0; } else { report->imtu = 0; report->pmtu = 0; } /* Add status flags to report */ report->status = 0; if (flow->statistics[type].bytes_read == 0) { if (flow_in_delay(&report->end, flow, READ)) report->status |= 'd'; else if (flow_sending(&report->end, flow, READ)) report->status |= 'l'; else if (flow->settings.duration[READ] == 0) report->status |= 'o'; else report->status |= 'f'; } else { if (!flow_sending(&report->end, flow, READ) && !flow->finished) report->status |= 'c'; else report->status |= 'n'; } report->status <<= 8; if (flow->statistics[type].bytes_written == 0) { if (flow_in_delay(&report->end, flow, WRITE)) report->status |= 'd'; else if (flow_sending(&report->end, flow, WRITE)) report->status |= 'l'; else if (flow->settings.duration[WRITE] == 0) report->status |= 'o'; else report->status |= 'f'; } else { if (!flow_sending(&report->end, flow, WRITE) && !flow->finished) report->status |= 'c'; else report->status |= 'n'; } /* New report interval, reset old data */ if (type == INTERVAL) { flow->statistics[INTERVAL].bytes_read = 0; flow->statistics[INTERVAL].bytes_written = 0; flow->statistics[INTERVAL].request_blocks_read = 0; flow->statistics[INTERVAL].response_blocks_read = 0; flow->statistics[INTERVAL].request_blocks_written = 0; flow->statistics[INTERVAL].response_blocks_written = 0; flow->statistics[INTERVAL].rtt_min = FLT_MAX; flow->statistics[INTERVAL].rtt_max = FLT_MIN; flow->statistics[INTERVAL].rtt_sum = 0.0F; flow->statistics[INTERVAL].iat_min = FLT_MAX; flow->statistics[INTERVAL].iat_max = FLT_MIN; flow->statistics[INTERVAL].iat_sum = 0.0F; flow->statistics[INTERVAL].delay_min = FLT_MAX; flow->statistics[INTERVAL].delay_max = FLT_MIN; flow->statistics[INTERVAL].delay_sum = 0.0F; } add_report(report); DEBUG_MSG(LOG_DEBUG, "report_flow finished for flow %d (type %d)", flow->id, type); }
int main(int argc, char *argv[]) { final_data_t hist_vals; int i; struct timeval begin, end; hist_data_t hist_data; get_time (&begin); // We use this global variable arrays to store the "key" for each histogram // bucket. This is to prevent memory leaks in the mapreduce scheduler for (i = 0; i < 256; i++) { blue_keys[i] = i; green_keys[i] = 1000 + i; red_keys[i] = 2000 + i; } i = map_reduce_init(&argc, &argv); CHECK_ERROR (i < 0); hist_data.fname = argv[1]; printf("Histogram: Running...\n"); // Setup map reduce args map_reduce_args_t map_reduce_args; memset(&map_reduce_args, 0, sizeof(map_reduce_args_t)); map_reduce_args.task_data = &hist_data; map_reduce_args.task_data_size = sizeof(hist_data_t); map_reduce_args.prep = hist_prep; map_reduce_args.cleanup = hist_cleanup; map_reduce_args.map = hist_map; map_reduce_args.reduce = hist_reduce; map_reduce_args.combiner = hist_combiner; map_reduce_args.splitter = hist_splitter; map_reduce_args.key_cmp = myshortcmp; map_reduce_args.unit_size = 3; // 3 bytes per pixel hist_data.unit_size = 3; map_reduce_args.partition = NULL; // use default map_reduce_args.result = &hist_vals; map_reduce_args.L1_cache_size = atoi(GETENV("MR_L1CACHESIZE"));//1024 * 512; map_reduce_args.num_map_threads = atoi(GETENV("MR_NUMTHREADS"));//8; map_reduce_args.num_reduce_threads = atoi(GETENV("MR_NUMTHREADS"));//16; map_reduce_args.num_merge_threads = atoi(GETENV("MR_NUMTHREADS"));//8; map_reduce_args.num_procs = atoi(GETENV("MR_NUMPROCS"));//16; map_reduce_args.key_match_factor = (float)atof(GETENV("MR_KEYMATCHFACTOR"));//2; fprintf(stderr, "Histogram: Calling MapReduce Scheduler\n"); get_time (&end); #ifdef TIMING fprintf (stderr, "initialize: %u\n", time_diff (&end, &begin)); #endif get_time (&begin); CHECK_ERROR( map_reduce (&map_reduce_args) < 0); get_time (&end); #ifdef TIMING fprintf (stderr, "library: %u\n", time_diff (&end, &begin)); #endif get_time (&begin); short pix_val; intptr_t freq; short prev = 0; dprintf("\n\nBlue\n"); dprintf("----------\n\n"); for (i = 0; i < hist_vals.length; i++) { keyval_t * curr = &((keyval_t *)hist_vals.data)[i]; pix_val = *((short *)curr->key); freq = (intptr_t)curr->val; if (pix_val - prev > 700) { if (pix_val >= 2000) { dprintf("\n\nRed\n"); dprintf("----------\n\n"); } else if (pix_val >= 1000) { dprintf("\n\nGreen\n"); dprintf("----------\n\n"); } } dprintf("%hd - %" PRIdPTR "\n", pix_val % 1000, freq); prev = pix_val; } map_reduce_cleanup(&map_reduce_args); CHECK_ERROR (map_reduce_finalize ()); get_time (&end); #ifdef TIMING fprintf (stderr, "finalize: %u\n", time_diff (&end, &begin)); #endif return 0; }
void pseudo_tcp_socket_notify_clock(PseudoTcpSocket *self) { PseudoTcpSocketPrivate *priv = self->priv; guint32 now = get_current_time (); if (priv->state == TCP_CLOSED) return; // Check if it's time to retransmit a segment if (priv->rto_base && (time_diff(priv->rto_base + priv->rx_rto, now) <= 0)) { if (g_list_length (priv->slist) == 0) { g_assert_not_reached (); } else { // Note: (priv->slist.front().xmit == 0)) { // retransmit segments guint32 nInFlight; guint32 rto_limit; DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "timeout retransmit (rto: %d) " "(rto_base: %d) (now: %d) (dup_acks: %d)", priv->rx_rto, priv->rto_base, now, (guint) priv->dup_acks); if (!transmit(self, priv->slist, now)) { closedown(self, ECONNABORTED); return; } nInFlight = priv->snd_nxt - priv->snd_una; priv->ssthresh = max(nInFlight / 2, 2 * priv->mss); //LOG(LS_INFO) << "priv->ssthresh: " << priv->ssthresh << " nInFlight: " << nInFlight << " priv->mss: " << priv->mss; priv->cwnd = priv->mss; // Back off retransmit timer. Note: the limit is lower when connecting. rto_limit = (priv->state < TCP_ESTABLISHED) ? DEF_RTO : MAX_RTO; priv->rx_rto = min(rto_limit, priv->rx_rto * 2); priv->rto_base = now; } } // Check if it's time to probe closed windows if ((priv->snd_wnd == 0) && (time_diff(priv->lastsend + priv->rx_rto, now) <= 0)) { if (time_diff(now, priv->lastrecv) >= 15000) { closedown(self, ECONNABORTED); return; } // probe the window packet(self, priv->snd_nxt - 1, 0, 0, 0); priv->lastsend = now; // back off retransmit timer priv->rx_rto = min(MAX_RTO, priv->rx_rto * 2); } // Check if it's time to send delayed acks if (priv->t_ack && (time_diff(priv->t_ack + ACK_DELAY, now) <= 0)) { packet(self, priv->snd_nxt, 0, 0, 0); } }
static void do_it( void ) { int i; double d; gettimeofday( &now_time , NULL ); d = time_diff( now_time , time_store_sec ); if( d >= 1.0 ){ fprintf( stderr, "W:%9.0f(%9.0f/sec) R:%9.0f(%9.0f/sec)\n", write_total , write_total / time_diff( now_time , time_store_sec ), read_total , read_total / time_diff( now_time, time_store_sec ) ); write_total = read_total = 0.0F; time_store_sec = time_store; } time_store = now_time; for(i=0;i<MAXCON;i++){ fd_set fds; struct timeval t; if(!so[i].use )continue; /*read */ FD_ZERO( &fds ); FD_SET( so[i].fd, &fds ); t.tv_sec = t.tv_usec = 0; select(MAXCON+1,&fds, (fd_set*)NULL, (fd_set*)NULL,&t); if( FD_ISSET( so[i].fd, &fds ) ){ char buf[4096]; int ret; ret = read( so[i].fd, buf,sizeof( buf)); if(ret <= 0 ){ close(so[i].fd ); so[i].use =0; fprintf( stderr, "read error!closed\n" ); exit(1); } else { so[i].read_total += ret; read_total += ret; } } #if 1 /* write */ FD_ZERO( &fds ); FD_SET( so[i].fd, &fds ); t.tv_sec = t.tv_usec = 0; select( MAXCON +1, (fd_set*)NULL, &fds, (fd_set*)NULL,&t ); if( FD_ISSET( so[i].fd, &fds )){ int wlen = 5; int ret; char buf[4096]; memset(buf,0,sizeof(buf)); ret = write( so[i].fd, buf, wlen ); if( ret <= 0 ){ fprintf( stderr, "write error close\n "); close(so[i].fd ); so[i].use=0; } else { so[i].write_total += ret; write_total += ret; } } #endif /* ex */ FD_ZERO( &fds ); FD_SET( so[i].fd, &fds ); t.tv_sec = t.tv_usec = 0; select( MAXCON +1, (fd_set*)NULL, (fd_set*)NULL, &fds,&t ); if( FD_ISSET( so[i].fd, &fds )){ close(so[i].fd ); so[i].use=0; fprintf( stderr, "EXception close\n "); exit(1); } } }
static void attempt_send(PseudoTcpSocket *self, SendFlags sflags) { PseudoTcpSocketPrivate *priv = self->priv; guint32 now = get_current_time(); gboolean bFirst = TRUE; if (time_diff(now, priv->lastsend) > (long) priv->rx_rto) { priv->cwnd = priv->mss; } while (TRUE) { guint32 cwnd; guint32 nWindow; guint32 nInFlight; guint32 nUseable; guint32 nAvailable; GList *iter; cwnd = priv->cwnd; if ((priv->dup_acks == 1) || (priv->dup_acks == 2)) { // Limited Transmit cwnd += priv->dup_acks * priv->mss; } nWindow = min(priv->snd_wnd, cwnd); nInFlight = priv->snd_nxt - priv->snd_una; nUseable = (nInFlight < nWindow) ? (nWindow - nInFlight) : 0; nAvailable = min(priv->slen - nInFlight, priv->mss); if (nAvailable > nUseable) { if (nUseable * 4 < nWindow) { // RFC 813 - avoid SWS nAvailable = 0; } else { nAvailable = nUseable; } } if (bFirst) { bFirst = FALSE; DEBUG (PSEUDO_TCP_DEBUG_VERBOSE, "[cwnd: %d nWindow: %d nInFlight: %d " "nAvailable: %d nQueued: %d nEmpty: %d ssthresh: %d]", priv->cwnd, nWindow, nInFlight, nAvailable, priv->slen - nInFlight, sizeof(priv->sbuf) - priv->slen, priv->ssthresh); } if (nAvailable == 0) { if (sflags == sfNone) return; // If this is an immediate ack, or the second delayed ack if ((sflags == sfImmediateAck) || priv->t_ack) { packet(self, priv->snd_nxt, 0, 0, 0); } else { priv->t_ack = get_current_time(); } return; } // Nagle algorithm if ((priv->snd_nxt > priv->snd_una) && (nAvailable < priv->mss)) { return; } // Find the next segment to transmit iter = priv->slist; while (((SSegment*)iter->data)->xmit > 0) { iter = g_list_next (iter); g_assert(iter); } // If the segment is too large, break it into two if (((SSegment*)iter->data)->len > nAvailable) { SSegment *subseg = g_slice_new0 (SSegment); subseg->seq = ((SSegment*)iter->data)->seq + nAvailable; subseg->len = ((SSegment*)iter->data)->len - nAvailable; subseg->bCtrl = ((SSegment*)iter->data)->bCtrl; ((SSegment*)iter->data)->len = nAvailable; priv->slist = g_list_insert_before(priv->slist, iter->next, subseg); } if (!transmit(self, iter, now)) { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "transmit failed"); // TODO: consider closing socket return; } sflags = sfNone; } }
static void handle_touch(struct wl_input_event *ev) { //int offset,offset_count, int article_link_number=-1; int enter_touch_y_pos_record; //int time_diff_search; int mode; struct keyboard_key * key; static int last_5_y[5]; static unsigned long last_5_y_time_ticks[5]; int i; DP(DBG_WL, ("%s() touch event @%d,%d val %d\n", __func__, ev->touch_event.x, ev->touch_event.y, ev->touch_event.value)); mode = keyboard_get_mode(); if (display_mode == DISPLAY_MODE_INDEX && (mode == KEYBOARD_CHAR || mode == KEYBOARD_NUM)) { article_buf_pointer = NULL; key = keyboard_get_data(ev->touch_event.x, ev->touch_event.y); if (ev->touch_event.value == 0) { keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_DELAY); // reset invert with delay enter_touch_y_pos_record = enter_touch_y_pos; enter_touch_y_pos = -1; touch_search = 0; press_delete_button = false; pre_key = NULL; if (key) { if (!touch_down_on_keyboard) { touch_down_on_keyboard = 0; touch_down_on_list = 0; goto out; } handle_search_key(key->key); } else { if (!touch_down_on_list || ev->touch_event.y < RESULT_START - RESULT_HEIGHT) { touch_down_on_keyboard = 0; touch_down_on_list = 0; goto out; } if(search_result_count()==0) goto out; //search_set_selection(last_selection); //search_open_article(last_selection); if(search_result_selected()>=0) { display_mode = DISPLAY_MODE_ARTICLE; last_display_mode = DISPLAY_MODE_INDEX; search_open_article(search_result_selected()); } } touch_down_on_keyboard = 0; touch_down_on_list = 0; } else { if(enter_touch_y_pos<0) //record first touch y pos enter_touch_y_pos = ev->touch_event.y; last_index_y_pos = ev->touch_event.y; start_search_time = ev->touch_event.ticks; last_delete_time = start_search_time; if (key) { if(key->key==8)//press "<" button { press_delete_button = true; } else if(key->key == -42) { mode = keyboard_get_mode(); if(mode == KEYBOARD_CHAR) keyboard_set_mode(KEYBOARD_NUM); else if(mode == KEYBOARD_NUM) keyboard_set_mode(KEYBOARD_CHAR); guilib_fb_lock(); keyboard_paint(); guilib_fb_unlock(); } if (!touch_down_on_keyboard && !touch_down_on_list) touch_down_on_keyboard = 1; if (pre_key && pre_key->key == key->key) goto out; if (touch_down_on_keyboard) { keyboard_key_invert(key); pre_key = key; } } else { if (!touch_down_on_keyboard && !touch_down_on_list) touch_down_on_list = 1; keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_DELAY); // reset invert with delay pre_key = NULL; if (!search_result_count()) goto out; if(touch_search == 0) { //last_search_y_pos = ev->touch_event.y; touch_search = 1; } else { if(search_result_selected()>=0 && abs(ev->touch_event.y-search_touch_pos_y_last)>5) { invert_selection(search_result_selected(),-1, RESULT_START, RESULT_HEIGHT); search_set_selection(-1); } goto out; } int new_selection; if((ev->touch_event.y - RESULT_START)<0) new_selection = -1; else new_selection = ((unsigned int)ev->touch_event.y - RESULT_START) / RESULT_HEIGHT; if (new_selection == search_result_selected()) goto out; unsigned int avail_count = keyboard_get_mode() == KEYBOARD_NONE ? NUMBER_OF_FIRST_PAGE_RESULTS : NUMBER_OF_RESULTS_KEYBOARD; avail_count = search_result_count() > avail_count ? avail_count : search_result_count(); if (new_selection >= avail_count) goto out; if (touch_down_on_keyboard) goto out; //invert_selection(search_result_selected(), new_selection, RESULT_START, RESULT_HEIGHT); invert_selection(-1, new_selection, RESULT_START, RESULT_HEIGHT); last_selection = new_selection ; search_set_selection(new_selection); search_touch_pos_y_last = ev->touch_event.y; } } } else if (display_mode == DISPLAY_MODE_HISTORY && mode == KEYBOARD_CLEAR_HISTORY) { key = keyboard_get_data(ev->touch_event.x, ev->touch_event.y); if (ev->touch_event.value == 0) { #ifdef INCLUDED_FROM_KERNEL delay_us(100000 * 2); #endif keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_NOW); enter_touch_y_pos_record = enter_touch_y_pos; enter_touch_y_pos = -1; touch_search = 0; press_delete_button = false; pre_key = NULL; if (key) { if (!touch_down_on_keyboard) { touch_down_on_keyboard = 0; touch_down_on_list = 0; goto out; } if (key->key == 'Y') { history_clear(); keyboard_set_mode(KEYBOARD_NONE); history_reload(); } else if (key->key == 'N') { keyboard_set_mode(KEYBOARD_NONE); guilib_fb_lock(); draw_clear_history(1); guilib_fb_unlock(); } } else { touch_down_on_keyboard = 0; touch_down_on_list = 0; goto out; } } else { if(enter_touch_y_pos<0) //record first touch y pos enter_touch_y_pos = ev->touch_event.y; last_index_y_pos = ev->touch_event.y; if (key) { if (!touch_down_on_keyboard) touch_down_on_keyboard = 1; if (pre_key && pre_key->key == key->key) goto out; if (touch_down_on_keyboard) { keyboard_key_invert(key); pre_key = key; } } else { touch_down_on_keyboard = 0; keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_DELAY); // reset invert with delay pre_key = NULL; } } } else if (display_mode == DISPLAY_MODE_RESTRICTED) { key = keyboard_get_data(ev->touch_event.x, ev->touch_event.y); if (ev->touch_event.value == 0) { if (key->key == 'Y' || key->key == 'N' || key->key == 'P') { #ifdef INCLUDED_FROM_KERNEL delay_us(100000 * 2); #endif keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_NOW); } else keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_DELAY); // reset invert with delay enter_touch_y_pos_record = enter_touch_y_pos; enter_touch_y_pos = -1; touch_search = 0; press_delete_button = false; pre_key = NULL; if (key) { if (!touch_down_on_keyboard) { touch_down_on_keyboard = 0; goto out; } handle_password_key(key->key); } touch_down_on_keyboard = 0; } else { if(enter_touch_y_pos<0) //record first touch y pos enter_touch_y_pos = ev->touch_event.y; last_index_y_pos = ev->touch_event.y; start_search_time = ev->touch_event.ticks; last_delete_time = start_search_time; if (key) { if(key->key==8)//press "<" button { press_delete_button = true; } else if(key->key == -42) { mode = keyboard_get_mode(); if(mode == KEYBOARD_PASSWORD_CHAR) keyboard_set_mode(KEYBOARD_PASSWORD_NUM); else if(mode == KEYBOARD_PASSWORD_NUM) keyboard_set_mode(KEYBOARD_PASSWORD_CHAR); guilib_fb_lock(); keyboard_paint(); guilib_fb_unlock(); } if (!touch_down_on_keyboard) touch_down_on_keyboard = 1; if (pre_key && pre_key->key == key->key) goto out; if (touch_down_on_keyboard) { keyboard_key_invert(key); pre_key = key; } } else { keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_NOW); pre_key = NULL; search_touch_pos_y_last = ev->touch_event.y; } } } else { if (ev->touch_event.value == 0) { unsigned long diff_ticks = 0; long diff_y = 0; for (i = 4; i > 0; i--) { if (last_5_y[i]) { diff_y = ev->touch_event.y - last_5_y[i]; diff_ticks = time_diff(ev->touch_event.ticks, last_5_y_time_ticks[i]); break; } } if (diff_ticks <= 0 || abs(article_moved_pixels) > SMOOTH_SCROLL_ACTIVATION_OFFSET_HIGH_THRESHOLD || abs(article_moved_pixels) < SMOOTH_SCROLL_ACTIVATION_OFFSET_LOW_THRESHOLD) finger_move_speed = 0; else { // Event timesing is not good for short period due to the events are queued without timestamp finger_move_speed = -(float)diff_y * ((float)seconds_to_ticks(1) / (float)diff_ticks); if (abs(finger_move_speed) > SMOOTH_SCROLL_ACTIVATION_SPPED_THRESHOLD) { if (finger_move_speed > 0) { if (display_mode == DISPLAY_MODE_ARTICLE) finger_move_speed = ARTICLE_SMOOTH_SCROLL_SPEED_FACTOR * (finger_move_speed - SMOOTH_SCROLL_ACTIVATION_SPPED_THRESHOLD); else finger_move_speed = LIST_SMOOTH_SCROLL_SPEED_FACTOR * (finger_move_speed - SMOOTH_SCROLL_ACTIVATION_SPPED_THRESHOLD); } else { if (display_mode == DISPLAY_MODE_ARTICLE) finger_move_speed = ARTICLE_SMOOTH_SCROLL_SPEED_FACTOR * (finger_move_speed + SMOOTH_SCROLL_ACTIVATION_SPPED_THRESHOLD); else finger_move_speed = LIST_SMOOTH_SCROLL_SPEED_FACTOR * (finger_move_speed + SMOOTH_SCROLL_ACTIVATION_SPPED_THRESHOLD); } } else finger_move_speed = 0; } if (finger_move_speed != 0) { time_scroll_article_last = ev->touch_event.ticks; } article_moved = false; if (finger_move_speed == 0 && b_show_scroll_bar) { b_show_scroll_bar = 0; show_scroll_bar(0); // clear scroll bar } article_scroll_pixel = INITIAL_ARTICLE_SCROLL_PIXEL; article_moved_pixels = 0; touch_y_last_unreleased = 0; start_move_time = 0; article_link_number = get_activated_article_link_number(); if(article_link_number>=0) { if (link_to_be_inverted >= 0) { if (link_currently_inverted >= 0) invert_link(link_currently_inverted); invert_link(link_to_be_inverted); } if (finger_move_speed == 0) { init_invert_link(); last_display_mode = display_mode; display_mode = DISPLAY_MODE_ARTICLE; open_article_link_with_link_number(article_link_number); } else { if (link_currently_inverted >= 0) invert_link(link_currently_inverted); init_invert_link(); } return; } reset_article_link_number(); article_touch_down_handled = 0; } else { finger_move_speed = 0; if(touch_y_last_unreleased == 0) { touch_y_last_unreleased = ev->touch_event.y; last_unreleased_time = ev->touch_event.ticks; reset_article_link_number(); article_moved_pixels = 0; last_5_y[0] = ev->touch_event.y; last_5_y_time_ticks[0] = ev->touch_event.ticks; for (i = 1; i < 5; i++) last_5_y[i] = 0; } else { article_moved_pixels += touch_y_last_unreleased - ev->touch_event.y; if(abs(touch_y_last_unreleased - ev->touch_event.y) >=article_scroll_pixel) { if (finger_move_speed == 0) display_article_with_pcf(touch_y_last_unreleased - ev->touch_event.y); touch_y_last_unreleased = ev->touch_event.y; for (i = 4; i >= 1; i--) { last_5_y[i] = last_5_y[i-1]; last_5_y_time_ticks[i] = last_5_y_time_ticks[i-1]; } last_5_y[0] = ev->touch_event.y; last_5_y_time_ticks[0] = ev->touch_event.ticks; b_show_scroll_bar = 1; article_scroll_pixel = 1; } else if (article_moved_pixels < article_scroll_pixel && time_diff(get_time_ticks(), last_unreleased_time) > seconds_to_ticks(0.075)) { article_moved_pixels = 0; touch_y_last_unreleased = ev->touch_event.y; last_unreleased_time = ev->touch_event.ticks; last_5_y[0] = ev->touch_event.y; last_5_y_time_ticks[0] = ev->touch_event.ticks; for (i = 1; i < 5; i++) last_5_y[i] = 0; } if (abs(article_moved_pixels) > ARTICLE_MOVED_THRESHOLD) { article_moved = true; reset_article_link_number(); } } if (!article_moved) { article_link_number =isArticleLinkSelected(ev->touch_event.x,ev->touch_event.y); if (article_link_number >= 0) set_article_link_number(article_link_number, ev->touch_event.ticks); else reset_article_link_number(); } if (!article_touch_down_handled) { article_touch_down_pos.x = ev->touch_event.x; article_touch_down_pos.y = ev->touch_event.y; article_touch_down_handled = 1; } } } out: return; }
static gboolean process(PseudoTcpSocket *self, Segment *seg) { PseudoTcpSocketPrivate *priv = self->priv; guint32 now; SendFlags sflags = sfNone; gboolean bIgnoreData; gboolean bNewData; gboolean bConnect = FALSE; /* If this is the wrong conversation, send a reset!?! (with the correct conversation?) */ if (seg->conv != priv->conv) { //if ((seg->flags & FLAG_RST) == 0) { // packet(sock, tcb, seg->ack, 0, FLAG_RST, 0, 0); //} DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "wrong conversation"); return FALSE; } now = get_current_time(); priv->last_traffic = priv->lastrecv = now; priv->bOutgoing = FALSE; if (priv->state == TCP_CLOSED) { // !?! send reset? DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "closed"); return FALSE; } // Check if this is a reset segment if (seg->flags & FLAG_RST) { closedown(self, ECONNRESET); return FALSE; } // Check for control data bConnect = FALSE; if (seg->flags & FLAG_CTL) { if (seg->len == 0) { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "Missing control code"); return FALSE; } else if (seg->data[0] == CTL_CONNECT) { bConnect = TRUE; if (priv->state == TCP_LISTEN) { char buffer[1]; priv->state = TCP_SYN_RECEIVED; buffer[0] = CTL_CONNECT; queue(self, buffer, 1, TRUE); } else if (priv->state == TCP_SYN_SENT) { priv->state = TCP_ESTABLISHED; DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "State: TCP_ESTABLISHED"); adjustMTU(self); if (priv->callbacks.PseudoTcpOpened) priv->callbacks.PseudoTcpOpened(self, priv->callbacks.user_data); } } else { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "Unknown control code: %d", seg->data[0]); return FALSE; } } // Update timestamp if ((seg->seq <= priv->ts_lastack) && (priv->ts_lastack < seg->seq + seg->len)) { priv->ts_recent = seg->tsval; } // Check if this is a valuable ack if ((seg->ack > priv->snd_una) && (seg->ack <= priv->snd_nxt)) { guint32 nAcked; guint32 nFree; guint32 kIdealRefillSize; // Calculate round-trip time if (seg->tsecr) { long rtt = time_diff(now, seg->tsecr); if (rtt >= 0) { if (priv->rx_srtt == 0) { priv->rx_srtt = rtt; priv->rx_rttvar = rtt / 2; } else { priv->rx_rttvar = (3 * priv->rx_rttvar + abs((long)(rtt - priv->rx_srtt))) / 4; priv->rx_srtt = (7 * priv->rx_srtt + rtt) / 8; } priv->rx_rto = bound(MIN_RTO, priv->rx_srtt + max(1LU, 4 * priv->rx_rttvar), MAX_RTO); DEBUG (PSEUDO_TCP_DEBUG_VERBOSE, "rtt: %ld srtt: %d rto: %d", rtt, priv->rx_srtt, priv->rx_rto); } else { g_assert_not_reached (); } } priv->snd_wnd = seg->wnd; nAcked = seg->ack - priv->snd_una; priv->snd_una = seg->ack; priv->rto_base = (priv->snd_una == priv->snd_nxt) ? 0 : now; priv->slen -= nAcked; memmove(priv->sbuf, priv->sbuf + nAcked, priv->slen); //LOG(LS_INFO) << "PseudoTcp::process - priv->slen = " << priv->slen; for (nFree = nAcked; nFree > 0; ) { SSegment *data = (SSegment *) (g_list_first (priv->slist)->data); g_assert(g_list_length (priv->slist) > 0); if (nFree < data->len) { data->len -= nFree; nFree = 0; } else { if (data->len > priv->largest) { priv->largest = data->len; } nFree -= data->len; g_slice_free (SSegment, priv->slist->data); priv->slist = g_list_delete_link (priv->slist, priv->slist); } } if (priv->dup_acks >= 3) { if (priv->snd_una >= priv->recover) { // NewReno guint32 nInFlight = priv->snd_nxt - priv->snd_una; // (Fast Retransmit) priv->cwnd = min(priv->ssthresh, nInFlight + priv->mss); DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "exit recovery"); priv->dup_acks = 0; } else { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "recovery retransmit"); if (!transmit(self, priv->slist, now)) { closedown(self, ECONNABORTED); return FALSE; } priv->cwnd += priv->mss - min(nAcked, priv->cwnd); } } else { priv->dup_acks = 0; // Slow start, congestion avoidance if (priv->cwnd < priv->ssthresh) { priv->cwnd += priv->mss; } else { priv->cwnd += max(1LU, priv->mss * priv->mss / priv->cwnd); } } // !?! A bit hacky if ((priv->state == TCP_SYN_RECEIVED) && !bConnect) { priv->state = TCP_ESTABLISHED; DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "State: TCP_ESTABLISHED"); adjustMTU(self); if (priv->callbacks.PseudoTcpOpened) priv->callbacks.PseudoTcpOpened(self, priv->callbacks.user_data); } // If we make room in the send queue, notify the user // The goal it to make sure we always have at least enough data to fill the // window. We'd like to notify the app when we are halfway to that point. kIdealRefillSize = (sizeof(priv->sbuf) + sizeof(priv->rbuf)) / 2; if (priv->bWriteEnable && (priv->slen < kIdealRefillSize)) { priv->bWriteEnable = FALSE; if (priv->callbacks.PseudoTcpWritable) priv->callbacks.PseudoTcpWritable(self, priv->callbacks.user_data); } } else if (seg->ack == priv->snd_una) { /* !?! Note, tcp says don't do this... but otherwise how does a closed window become open? */ priv->snd_wnd = seg->wnd; // Check duplicate acks if (seg->len > 0) { // it's a dup ack, but with a data payload, so don't modify priv->dup_acks } else if (priv->snd_una != priv->snd_nxt) { guint32 nInFlight; priv->dup_acks += 1; if (priv->dup_acks == 3) { // (Fast Retransmit) DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "enter recovery"); DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "recovery retransmit"); if (!transmit(self, priv->slist, now)) { closedown(self, ECONNABORTED); return FALSE; } priv->recover = priv->snd_nxt; nInFlight = priv->snd_nxt - priv->snd_una; priv->ssthresh = max(nInFlight / 2, 2 * priv->mss); //LOG(LS_INFO) << "priv->ssthresh: " << priv->ssthresh << " nInFlight: " << nInFlight << " priv->mss: " << priv->mss; priv->cwnd = priv->ssthresh + 3 * priv->mss; } else if (priv->dup_acks > 3) { priv->cwnd += priv->mss; } } else { priv->dup_acks = 0; } } /* Conditions where acks must be sent: * 1) Segment is too old (they missed an ACK) (immediately) * 2) Segment is too new (we missed a segment) (immediately) * 3) Segment has data (so we need to ACK!) (delayed) * ... so the only time we don't need to ACK, is an empty segment * that points to rcv_nxt! */ if (seg->seq != priv->rcv_nxt) { sflags = sfImmediateAck; // (Fast Recovery) } else if (seg->len != 0) { sflags = sfDelayedAck; } if (sflags == sfImmediateAck) { if (seg->seq > priv->rcv_nxt) { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "too new"); } else if (seg->seq + seg->len <= priv->rcv_nxt) { DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "too old"); } } // Adjust the incoming segment to fit our receive buffer if (seg->seq < priv->rcv_nxt) { guint32 nAdjust = priv->rcv_nxt - seg->seq; if (nAdjust < seg->len) { seg->seq += nAdjust; seg->data += nAdjust; seg->len -= nAdjust; } else { seg->len = 0; } } if ((seg->seq + seg->len - priv->rcv_nxt) > (sizeof(priv->rbuf) - priv->rlen)) { guint32 nAdjust = seg->seq + seg->len - priv->rcv_nxt - (sizeof(priv->rbuf) - priv->rlen); if (nAdjust < seg->len) { seg->len -= nAdjust; } else { seg->len = 0; } } bIgnoreData = (seg->flags & FLAG_CTL) || (priv->shutdown != SD_NONE); bNewData = FALSE; if (seg->len > 0) { if (bIgnoreData) { if (seg->seq == priv->rcv_nxt) { priv->rcv_nxt += seg->len; } } else { guint32 nOffset = seg->seq - priv->rcv_nxt; memcpy(priv->rbuf + priv->rlen + nOffset, seg->data, seg->len); if (seg->seq == priv->rcv_nxt) { GList *iter = NULL; priv->rlen += seg->len; priv->rcv_nxt += seg->len; priv->rcv_wnd -= seg->len; bNewData = TRUE; iter = priv->rlist; while (iter && (((RSegment *)iter->data)->seq <= priv->rcv_nxt)) { RSegment *data = (RSegment *)(iter->data); if (data->seq + data->len > priv->rcv_nxt) { guint32 nAdjust = (data->seq + data->len) - priv->rcv_nxt; sflags = sfImmediateAck; // (Fast Recovery) DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "Recovered %d bytes (%d -> %d)", nAdjust, priv->rcv_nxt, priv->rcv_nxt + nAdjust); priv->rlen += nAdjust; priv->rcv_nxt += nAdjust; priv->rcv_wnd -= nAdjust; } g_slice_free (RSegment, priv->rlist->data); priv->rlist = g_list_delete_link (priv->rlist, priv->rlist); iter = priv->rlist; } } else { GList *iter = NULL; RSegment *rseg = g_slice_new0 (RSegment); DEBUG (PSEUDO_TCP_DEBUG_NORMAL, "Saving %d bytes (%d -> %d)", seg->len, seg->seq, seg->seq + seg->len); rseg->seq = seg->seq; rseg->len = seg->len; iter = priv->rlist; while (iter && (((RSegment*)iter->data)->seq < rseg->seq)) { iter = g_list_next (iter); } priv->rlist = g_list_insert_before(priv->rlist, iter, rseg); } } } attempt_send(self, sflags); // If we have new data, notify the user if (bNewData && priv->bReadEnable) { priv->bReadEnable = FALSE; if (priv->callbacks.PseudoTcpReadable) priv->callbacks.PseudoTcpReadable(self, priv->callbacks.user_data); } return TRUE; }
int wikilib_run(void) { int sleep; long time_now; struct wl_input_event ev; int more_events = 0; unsigned long last_event_time = 0; int rc; /* * test searching code... */ article_buf_pointer = NULL; search_init(); history_list_init(); malloc_status_simple(); print_intro(); #ifndef INCLUDED_FROM_KERNEL if (!load_init_article(idx_init_article)) { display_mode = DISPLAY_MODE_ARTICLE; last_display_mode = DISPLAY_MODE_INDEX; } #endif render_string(SUBTITLE_FONT_IDX, -1, 55, MESSAGE_TYPE_A_WORD, strlen(MESSAGE_TYPE_A_WORD), 0); for (;;) { if (more_events) sleep = 0; else sleep = 1; if (!more_events && display_mode == DISPLAY_MODE_ARTICLE && render_article_with_pcf()) sleep = 0; else if (!more_events && display_mode == DISPLAY_MODE_INDEX && render_search_result_with_pcf()) sleep = 0; else if (!more_events && display_mode == DISPLAY_MODE_HISTORY && render_history_with_pcf()) sleep = 0; if (finger_move_speed != 0) { scroll_article(); sleep = 0; } #ifdef INCLUDED_FROM_KERNEL time_now = get_time_ticks(); if(display_mode == DISPLAY_MODE_INDEX) { if (press_delete_button && get_search_string_len()>0) { sleep = 0; if(time_diff(time_now, start_search_time) > seconds_to_ticks(3.5)) { if (!clear_search_string()) { search_string_changed_remove = true; search_reload_ex(SEARCH_RELOAD_NORMAL); } press_delete_button = false; } else if (time_diff(time_now, start_search_time) > seconds_to_ticks(0.5) && time_diff(time_now, last_delete_time) > seconds_to_ticks(0.25)) { if (!search_remove_char(0)) { search_string_changed_remove = true; search_reload_ex(SEARCH_RELOAD_NO_POPULATE); } last_delete_time = time_now; } } } else if (display_mode == DISPLAY_MODE_RESTRICTED) { if (press_delete_button && get_password_string_len()>0) { sleep = 0; time_now = get_time_ticks(); if(time_diff(time_now, start_search_time) > seconds_to_ticks(3.5)) { clear_password_string(); press_delete_button = false; } else if (time_diff(time_now, start_search_time) > seconds_to_ticks(0.5) && time_diff(time_now, last_delete_time) > seconds_to_ticks(0.25)) { password_remove_char(); last_delete_time = time_now; } } } #endif if (!more_events && display_mode == DISPLAY_MODE_INDEX && fetch_search_result(0, 0, 0)) { sleep = 0; } if (keyboard_key_reset_invert(KEYBOARD_RESET_INVERT_CHECK)) // check if need to reset invert sleep = 0; if (check_invert_link()) // check if need to invert link sleep = 0; if (sleep) { if (time_diff(get_time_ticks(), last_event_time) > seconds_to_ticks(15)) rc = history_list_save(HISTORY_SAVE_POWER_OFF); else rc = history_list_save(HISTORY_SAVE_NORMAL); if (rc > 0) { #ifdef INCLUDED_FROM_KERNEL delay_us(200000); // for some reason, save may not work if no delay #endif } else if (rc < 0) sleep = 0; // waiting for last_event_time timeout to save the history } wl_input_wait(&ev, sleep); more_events = 1; switch (ev.type) { case WL_INPUT_EV_TYPE_CURSOR: handle_cursor(&ev); last_event_time = get_time_ticks(); break; case WL_INPUT_EV_TYPE_KEYBOARD: if (ev.key_event.value != 0) { b_show_scroll_bar = 0; handle_key_release(ev.key_event.keycode); } last_event_time = get_time_ticks(); break; case WL_INPUT_EV_TYPE_TOUCH: handle_touch(&ev); last_event_time = ev.touch_event.ticks; break; default: more_events = 0; break; } } /* never reached */ return 0; }
void *DoTxn(void *fd) { int rc; struct QItem TxnQItem; int QIndex; #ifdef GET_TIME struct timeval txn_start_time, txn_end_time; #endif /* GET_TIME */ int workersock; #ifndef _SIMDB /* This should be buried under a generic database initialization call. */ struct db_context_t dbc; /* connect to database */ rc = db_connect(&dbc); if (rc == ERROR) { LOG_ERROR_MESSAGE("db_connect error\n"); kill(0, SIGUSR1); pthread_exit(NULL); } #endif /* _SIMDB */ /* on Linux we have to init seed in each thread */ srand(time(NULL) + pthread_self()); if (mode_cache == 1) { /* connect to search_results_cache_hsot */ workersock = _connect(search_results_cache_host, search_results_cache_port); if (workersock == -1) { LOG_ERROR_MESSAGE("connect to cache failed\n"); kill(0, SIGUSR1); pthread_exit(NULL); } } /* wait on the TxnQSem. Its value is positive when the queue is not * empty, sem_wait returns. If the queue is empty, block until a job is * enqueued. */ while (1) { struct app_txn_array *data = NULL; sem_wait(&TxnQSem); /* lock the mutex of the TxnQ */ pthread_mutex_lock(&queue_mutex); if ((QIndex = dequeue(&TxnQItem, &TxnQ)) == -1) { LOG_ERROR_MESSAGE("TxnQ dequeue error"); pthread_mutex_unlock(&queue_mutex); kill(0, SIGUSR1); pthread_exit(NULL); } pthread_mutex_unlock(&queue_mutex); /* Point data to the proper transaction array. */ switch (TxnQItem.TxnType) { case ADMIN_CONFIRM: data = &app_admin_confirm_array; break; case ADMIN_REQUEST: data = &app_admin_request_array; break; case SEARCH_REQUEST: data = &app_search_request_array; break; case SEARCH_RESULTS: data = &app_search_results_array; break; case BEST_SELLERS: data = &app_best_sellers_array; break; case NEW_PRODUCTS: data = &app_new_products_array; break; case BUY_CONFIRM: data = &app_buy_confirm_array; break; case BUY_REQUEST: data = &app_buy_request_array; break; case HOME: data = &app_home_array; break; case ORDER_DISPLAY: data = &app_order_display_array; break; case ORDER_INQUIRY: data = &app_order_inquiry_array; break; case PRODUCT_DETAIL: data = &app_product_detail_array; break; case SHOPPING_CART: data = &app_shopping_cart_array; break; } #ifdef GET_TIME if (gettimeofday(&txn_start_time, NULL) == -1) LOG_ERROR_MESSAGE("gettimeofday failed"); #endif /* GET_TIME */ if (TxnQItem.TxnType == SEARCH_RESULTS && data->data_array[TxnQItem.SlotID].search_results_data.search_type != SEARCH_SUBJECT && mode_cache == 1) { /* author and title search results are cached */ rc = ERROR; /* retry if send fails */ while (rc != OK) { rc = send_search_results(workersock, &app_search_results_array.data_array[TxnQItem.SlotID].search_results_data); /* if send fails, reopen a new socket */ if (rc != OK) { LOG_ERROR_MESSAGE( "send search_results to cache host failed"); close(workersock); workersock = _connect(search_results_cache_host, search_results_cache_port); if (workersock==-1) { LOG_ERROR_MESSAGE("connect to cache failed\n"); kill(0, SIGUSR1); pthread_exit(NULL); } } } rc = receive_search_results(workersock, &app_search_results_array.data_array[TxnQItem.SlotID].search_results_data); if (rc != OK) { LOG_ERROR_MESSAGE( "receive search_results from cache host failed"); close(workersock); workersock = _connect(search_results_cache_host, search_results_cache_port); if (workersock == -1) { LOG_ERROR_MESSAGE("connect to cache failed\n"); kill(0, SIGUSR1); pthread_exit(NULL); } rc = ERROR; } } else { data->txn_result[TxnQItem.SlotID] = process_interaction(TxnQItem.TxnType, &dbc, &data->data_array[TxnQItem.SlotID]); } #ifdef GET_TIME if (gettimeofday(&txn_end_time, NULL) == -1) LOG_ERROR_MESSAGE("gettimeofday failed"); data->db_response_time[TxnQItem.SlotID] = time_diff(txn_start_time, txn_end_time); #endif /* GET_TIME */ set_txn_done_flag(&TxnQ, QIndex); } }
/** * Transaction 2 - T2 * * Read from Subscriber: * * Input: * SubscriberNumber * * Output: * Location * Changed by * Changed Timestamp * Name */ int T2(void * obj, const SubscriberNumber number, Location * readLocation, ChangedBy changed_by, ChangedTime changed_time, SubscriberName subscriberName, BenchmarkTime * transaction_time) { Ndb * pNDB = (Ndb *) obj; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T2: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T2: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, number); CHECK_MINUS_ONE(check, "T2: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)readLocation); CHECK_NULL(check2, "T2: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, changed_by); CHECK_NULL(check2, "T2: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, changed_time); CHECK_NULL(check2, "T2: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_NAME, subscriberName); CHECK_NULL(check2, "T2: getValue name", MyTransaction); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T2: Commit", MyTransaction); pNDB->closeTransaction(MyTransaction); get_time(transaction_time); time_diff(transaction_time, &start); return 0; }
int main() { bool finished = false; timestruct begin, end, *diff; clock_gettime(CLOCK_MONOTONIC, &begin); unsigned int count = 0; LockFreeQueue<message> q; omp_set_num_threads(4); #pragma omp parallel shared(finished, count) { #pragma omp sections { #pragma omp section { for( unsigned int i = 0; i < 999999 ; ++i ) { q.push(new message); } finished = true; } #pragma omp section { message* m; while((m = q.pop()) != NULL || !finished ) { if(m) { __sync_fetch_and_add(&count, 1); delete m; } } } #pragma omp section { message* m = NULL; while((m = q.pop()) != NULL || !finished ) { if(m) { __sync_fetch_and_add(&count, 1); delete m; } } } #pragma omp section { message* m = NULL; while((m = q.pop()) != NULL || !finished ) { if(m) { __sync_fetch_and_add(&count, 1); delete m; } } } } } clock_gettime(CLOCK_MONOTONIC, &end); diff = time_diff(&end, &begin); std::cout << "=========================" << std::endl; std::cout << "tv_sec: " << diff->tv_sec << std::endl << "tv_nsec: " << diff->tv_nsec << std::endl; std::cout << "count: " << count << std::endl; return 0; }
/** * Transaction 3 - T3 * * Read session details * * Input: * SubscriberNumber * ServerId * ServerBit * * Output: * BranchExecuted * SessionDetails * ChangedBy * ChangedTime * Location */ int T3(void * obj, const SubscriberNumber inNumber, const SubscriberSuffix inSuffix, const ServerId inServerId, const ServerBit inServerBit, SessionDetails outSessionDetails, ChangedBy outChangedBy, ChangedTime outChangedTime, Location * outLocation, BranchExecuted * outBranchExecuted, BenchmarkTime * outTransactionTime) { Ndb * pNDB = (Ndb *) obj; GroupId groupId; ActiveSessions sessions; Permission permission; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; NdbConnection * MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T3-1: startTranscation", pNDB->getNdbErrorString(), 0); NdbOperation *MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T3-1: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T3-1: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, inNumber); CHECK_MINUS_ONE(check, "T3-1: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)outLocation); CHECK_NULL(check2, "T3-1: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, outChangedBy); CHECK_NULL(check2, "T3-1: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, outChangedTime); CHECK_NULL(check2, "T3-1: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_GROUP, (char *)&groupId); CHECK_NULL(check2, "T3-1: getValue group", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_SESSIONS, (char *)&sessions); CHECK_NULL(check2, "T3-1: getValue sessions", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-1: NoCommit", MyTransaction); /* Operation 2 */ MyOperation = MyTransaction->getNdbOperation(GROUP_TABLE); CHECK_NULL(MyOperation, "T3-2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T3-2: readTuple", MyTransaction); check = MyOperation->equal(IND_GROUP_ID, (char*)&groupId); CHECK_MINUS_ONE(check, "T3-2: equal group", MyTransaction); check2 = MyOperation->getValue(IND_GROUP_ALLOW_READ, (char *)&permission); CHECK_NULL(check2, "T3-2: getValue allow_read", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-2: NoCommit", MyTransaction); DEBUG3("T3(%.*s, %.2d): ", SUBSCRIBER_NUMBER_LENGTH, inNumber, inServerId); if(((permission & inServerBit) == inServerBit) && ((sessions & inServerBit) == inServerBit)) { DEBUG("reading - "); /* Operation 3 */ MyOperation = MyTransaction->getNdbOperation(SESSION_TABLE); CHECK_NULL(MyOperation, "T3-3: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T3-3: readTuple", MyTransaction); check = MyOperation->equal(IND_SESSION_SUBSCRIBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T3-3: equal number", MyTransaction); check = MyOperation->equal(IND_SESSION_SERVER, (char*)&inServerId); CHECK_MINUS_ONE(check, "T3-3: equal server id", MyTransaction); check2 = MyOperation->getValue(IND_SESSION_DATA, (char *)outSessionDetails); CHECK_NULL(check2, "T3-3: getValue session details", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-3: NoCommit", MyTransaction); /* Operation 4 */ MyOperation = MyTransaction->getNdbOperation(SERVER_TABLE); CHECK_NULL(MyOperation, "T3-4: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T3-4: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SERVER_ID, (char*)&inServerId); CHECK_MINUS_ONE(check, "T3-4: equal serverId", MyTransaction); check = MyOperation->equal(IND_SERVER_SUBSCRIBER_SUFFIX, (char*)inSuffix); CHECK_MINUS_ONE(check, "T3-4: equal suffix", MyTransaction); check = MyOperation->incValue(IND_SERVER_READS, (uint32)1); CHECK_MINUS_ONE(check, "T3-4: inc value", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T3-4: NoCommit", MyTransaction); (* outBranchExecuted) = 1; } else { (* outBranchExecuted) = 0; } DEBUG("commit\n"); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T3: Commit", MyTransaction); pNDB->closeTransaction(MyTransaction); get_time(outTransactionTime); time_diff(outTransactionTime, &start); return 0; }
static int do_execute(int node, const char *app, struct pack *pak) { struct timeval start, end; unsigned long msec; struct pack *p = NULL; char *code; char *res; size_t code_size; size_t res_size; int e; log_debug(LOG_JOB, "Execute(%s,%s)\n", model_get_path(node), app); bk_app = strdup(app); bk_node = node; if (model_flags(node) & P_PACKAGE) { p = pack_dup(pak); } csl_setup(); if (0 != db_get_code(model_parent(node), app, &code, &code_size)) { send_result(CMD_NONE, "noapp", 5); return -1; } gettimeofday(&start, NULL); e = csl_execute(code, code_size, model_get_method(node), pak, &res, &res_size); gettimeofday(&end, NULL); if (e) { if (e == CSL_NOFUNC) send_result(CMD_NONE, "nomethod", 8); else send_result(CMD_ERROR, "err", 3); } else { send_result(CMD_RESULT, res, res_size); free(res); } msec = time_diff(&start, &end); if (msec > 60*1000) { log_info("Script %s took %d seconds for %s call.\n", bk_app, msec / 1000, model_get_path(node)); } else { log_debug(LOG_PERF, "Script %s took %d miliseconds for %s call.\n", bk_app, msec, model_get_path(node)); } if (model_flags(node) & P_PACKAGE) { if (0 == e) { if (model_flags(node) & P_DELETE) db_del_profile(node, bk_app, p); else db_put_profile(node, bk_app, p); } pack_delete(p); } csl_cleanup(); return e; }
/** * Transaction 5 - T5 * * Delete session * * Input: * SubscriberNumber * ServerId * ServerBit * DoRollback * Output: * ChangedBy * ChangedTime * Location * BranchExecuted */ int T5(void * obj, const SubscriberNumber inNumber, const SubscriberSuffix inSuffix, const ServerId inServerId, const ServerBit inServerBit, ChangedBy outChangedBy, ChangedTime outChangedTime, Location * outLocation, DoRollback inDoRollback, BranchExecuted * outBranchExecuted, BenchmarkTime * outTransactionTime) { Ndb * pNDB = (Ndb *) obj; NdbConnection * MyTransaction = 0; NdbOperation * MyOperation = 0; GroupId groupId; ActiveSessions sessions; Permission permission; BenchmarkTime start; get_time(&start); int check; NdbRecAttr * check2; MyTransaction = pNDB->startTransaction(); if (MyTransaction == NULL) error_handler("T5-1: startTranscation", pNDB->getNdbErrorString(), 0); MyOperation= MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T5-1: getNdbOperation", MyTransaction); check = MyOperation->readTupleExclusive(); CHECK_MINUS_ONE(check, "T5-1: readTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, inNumber); CHECK_MINUS_ONE(check, "T5-1: equal subscriber", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_LOCATION, (char *)outLocation); CHECK_NULL(check2, "T5-1: getValue location", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_BY, outChangedBy); CHECK_NULL(check2, "T5-1: getValue changed_by", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_CHANGED_TIME, outChangedTime); CHECK_NULL(check2, "T5-1: getValue changed_time", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_GROUP, (char *)&groupId); CHECK_NULL(check2, "T5-1: getValue group", MyTransaction); check2 = MyOperation->getValue(IND_SUBSCRIBER_SESSIONS, (char *)&sessions); CHECK_NULL(check2, "T5-1: getValue sessions", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-1: NoCommit", MyTransaction); /* Operation 2 */ MyOperation = MyTransaction->getNdbOperation(GROUP_TABLE); CHECK_NULL(MyOperation, "T5-2: getNdbOperation", MyTransaction); check = MyOperation->readTuple(); CHECK_MINUS_ONE(check, "T5-2: readTuple", MyTransaction); check = MyOperation->equal(IND_GROUP_ID, (char*)&groupId); CHECK_MINUS_ONE(check, "T5-2: equal group", MyTransaction); check2 = MyOperation->getValue(IND_GROUP_ALLOW_DELETE, (char *)&permission); CHECK_NULL(check2, "T5-2: getValue allow_delete", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-2: NoCommit", MyTransaction); DEBUG3("T5(%.*s, %.2d): ", SUBSCRIBER_NUMBER_LENGTH, inNumber, inServerId); if(((permission & inServerBit) == inServerBit) && ((sessions & inServerBit) == inServerBit)) { DEBUG("deleting - "); /* Operation 3 */ MyOperation = MyTransaction->getNdbOperation(SESSION_TABLE); CHECK_NULL(MyOperation, "T5-3: getNdbOperation", MyTransaction); check = MyOperation->deleteTuple(); CHECK_MINUS_ONE(check, "T5-3: deleteTuple", MyTransaction); check = MyOperation->equal(IND_SESSION_SUBSCRIBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T5-3: equal number", MyTransaction); check = MyOperation->equal(IND_SESSION_SERVER, (char*)&inServerId); CHECK_MINUS_ONE(check, "T5-3: equal server id", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-3: NoCommit", MyTransaction); /* Operation 4 */ MyOperation = MyTransaction->getNdbOperation(SUBSCRIBER_TABLE); CHECK_NULL(MyOperation, "T5-4: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T5-4: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SUBSCRIBER_NUMBER, (char*)inNumber); CHECK_MINUS_ONE(check, "T5-4: equal number", MyTransaction); check = MyOperation->subValue(IND_SUBSCRIBER_SESSIONS, (uint32)inServerBit); CHECK_MINUS_ONE(check, "T5-4: dec value", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-4: NoCommit", MyTransaction); /* Operation 5 */ MyOperation = MyTransaction->getNdbOperation(SERVER_TABLE); CHECK_NULL(MyOperation, "T5-5: getNdbOperation", MyTransaction); check = MyOperation->interpretedUpdateTuple(); CHECK_MINUS_ONE(check, "T5-5: interpretedUpdateTuple", MyTransaction); check = MyOperation->equal(IND_SERVER_ID, (char*)&inServerId); CHECK_MINUS_ONE(check, "T5-5: equal serverId", MyTransaction); check = MyOperation->equal(IND_SERVER_SUBSCRIBER_SUFFIX, (char*)inSuffix); CHECK_MINUS_ONE(check, "T5-5: equal suffix", MyTransaction); check = MyOperation->incValue(IND_SERVER_DELETES, (uint32)1); CHECK_MINUS_ONE(check, "T5-5: inc value", MyTransaction); check = MyTransaction->execute( NoCommit ); CHECK_MINUS_ONE(check, "T5-5: NoCommit", MyTransaction); (* outBranchExecuted) = 1; } else { DEBUG1("%s", ((permission & inServerBit) ? "permission - " : "no permission - ")); DEBUG1("%s", ((sessions & inServerBit) ? "in session - " : "no in session - ")); (* outBranchExecuted) = 0; } if(!inDoRollback) { DEBUG("commit\n"); check = MyTransaction->execute( Commit ); CHECK_MINUS_ONE(check, "T5: Commit", MyTransaction); } else { DEBUG("rollback\n"); check = MyTransaction->execute(Rollback); CHECK_MINUS_ONE(check, "T5:Rollback", MyTransaction); } pNDB->closeTransaction(MyTransaction); get_time(outTransactionTime); time_diff(outTransactionTime, &start); return 0; }
int exec_cmd(int *o_ordercode, int *etm) { char s[32]; int retn; char msisdn[16],stream[16],ocode[8]; int ordercode; char *src,*dest,*para; int beg,len; char *ptr, tmp[50]; struct timeval tt1,tt2; cmdackptr=(struct cmd_data_ack *)tcpbuf.data; printf("get_length(cmdackptr->retn,4)====%d\n",get_length(cmdackptr->retn,4)); switch(get_length(cmdackptr->retn,4)) { case 3001: if(++waitnum>30) { fprintf(logfp,"Now no datas[%ld][%d]\n",time(NULL),waitnum); waitnum=0; /*cusnd(enter,1); RcvFrmN(); */ /*连接空闲, 发送回车来保持连接*/ retn = sndcmd(sndid, "\r\n< ", "\r\n", 2, "\r\n< ", replystr, sizeof(replystr)); } fflush(logfp); sleep(5); cmdreqptr=(struct cmd_data_req *)tcpbuf.data; memcpy(cmdreqptr->retn,"0000",4); cmdreqptr->type=ONLY_GET; return 0; case 0001: fprintf(logfp,"GET_DATAS:\n"); waitnum=0; cmdackptr=(struct cmd_data_ack *)tcpbuf.data; cmdreqptr=(struct cmd_data_req *)tcpbuf.data; memcpy(msisdn,cmdackptr->phone_no,MSISDNLEN); memcpy(stream,cmdackptr->stream_id,16); ordercode=get_length(cmdackptr->ordercode,4); *o_ordercode = ordercode; fprintf(logfp,"--retn========%04d~\n",get_length(cmdackptr->retn,4)); fprintf(logfp,"--order=%s|%04d|%s|%s|%s|%s|%s|%ld\n", cmdackptr->stream_id, ordercode, cmdackptr->phone_no, cmdackptr->imsi_no, cmdackptr->ss_info1, cmdackptr->ss_info2, cmdackptr->ss_info3, time(NULL) ); /*** ORDER SND TO HLR ***/ orderptr=orderhead.next; while(orderptr) { if(orderptr->ordercode==ordercode) break; else orderptr=orderptr->next; } if(orderptr) { src=orderptr->orderinfo; dest=orderinfo; for(;*src;) { switch(*src) { case '$': src++; switch(*src) { case '1': para=cmdackptr->phone_no; break; case '2': para=cmdackptr->imsi_no; break; case '3': para=cmdackptr->ss_info1; break; case '4': para=cmdackptr->ss_info2; break; default: para=cmdackptr->ss_info3; break; } src++; beg=get_length(src,2); src+=2; len=get_length(src,2); if(len==0) len=strlen(para+beg); printf("beg==%d\n",beg); printf("len==%d\n",len); printf("para=%s~\n",para+beg); memcpy(dest,para+beg,len); src+=2; dest+=len; break; default: *dest=*src; src++; dest++; break; } } *dest='\r'; dest++; /* *dest='\n'; dest++; */ *dest=0x0; if( (dest = strstr(orderinfo, ":KI=")) != NULL && strstr(orderinfo, "ZMAC:IMSI=") != NULL) { /*对于加载KI的指令, nokia需要明文的, 所以先解密 ZMAC:IMSI=$20000:KI=$30014$40018,A3V=1,A8V=1:; */ char tmp[33]; des_11(dest+4, tmp); memcpy(dest+4, tmp, 32); } if( (dest = strstr(orderinfo, ",OPC=")) != NULL && strstr(orderinfo, "ZMAC:IMSI=") != NULL) { /*对于加载OPC的指令, nokia需要明文的, 所以先解密 ZMAC:IMSI=$20000:KI=$30014$40018,UV=99,OPC=$50032; */ char tmp[33]; des_11(dest+5, tmp); memcpy(dest+5, tmp, 32); } gettimeofday(&tt1, NULL); retn = sndcmd(sndid, "\r\n< \08 ", orderinfo, strlen(orderinfo), "_>\r\n< \08 ", replystr, sizeof(replystr)); gettimeofday(&tt2, NULL); *etm = time_diff(tt1, tt2); if(retn <= 0){ fprintf(logfp, "sndcmd failed, return:%d\n", retn); return -1; } retn=reply_parse(); fprintf(logfp,"RETN:%04d\n",retn); if(retn==0 && ordercode>9000) { memset(cmdreqptr->info,' ',sizeof(cmdreqptr->info)); /*memcpy(cmdreqptr->info, cmdackptr->queryinfo, QUERYINFOLEN); */ cal_query_cfg(replystr+STATION,cmdreqptr->info); fprintf(logfp,"INFO:%s~\n",cmdreqptr->info); } } else { fprintf(logfp,"UNKNOW ORDER_CODE!\n"); retn=21; } sprintf(cmdreqptr->retn,"%04d",retn); cmdreqptr->type=REPLY_GET; memcpy(cmdreqptr->stream_id,stream,16); memcpy(cmdreqptr->phone_no,msisdn,MSISDNLEN); sprintf(ocode,"%04d",ordercode); memcpy(cmdreqptr->ordercode,ocode,4); return 1; default: fprintf(logfp,"UNKNOW INFO[%04d]!\n",retn); fflush(logfp); return -1; } }
int main(int argc, char *argv[]) { char *infile = NULL; char *swarm_file = NULL; struct timeval tv0, tv1; euler_workspace *euler_workspace_p; double fday_start = 5090.0; double fday_end = 5715.0; double fday_step = 10.0; while (1) { int c; int option_index = 0; static struct option long_options[] = { { "start", required_argument, NULL, 'a' }, { "end", required_argument, NULL, 'b' }, { "input_file", required_argument, NULL, 'i' }, { "swarm_file", required_argument, NULL, 's' }, { 0, 0, 0, 0 } }; c = getopt_long(argc, argv, "a:b:i:s:", long_options, &option_index); if (c == -1) break; switch (c) { case 'a': fday_start = atof(optarg); break; case 'b': fday_end = atof(optarg); break; case 'i': infile = optarg; break; case 's': swarm_file = optarg; break; default: print_help(argv); exit(1); break; } } if (infile == NULL) { print_help(argv); exit(1); } fprintf(stderr, "main: reading %s...", infile); gettimeofday(&tv0, NULL); euler_workspace_p = euler_read(infile); gettimeofday(&tv1, NULL); fprintf(stderr, "done (%zu angles read, %g seconds)\n", euler_workspace_p->n, time_diff(tv0, tv1)); if (swarm_file) { fprintf(stderr, "main: writing Euler angles to %s...", swarm_file); euler_write_swarm(fday_start, fday_end, fday_step, swarm_file, euler_workspace_p); fprintf(stderr, "done\n"); } return 0; }
void main(int argc, char* argv[]) { // struct timespec tp1, tp2; long timp1, timp2, timp3; int i1,i2,x,y; int s1; long double s2; long double accum; long double accum1; float rb; float ra; struct timespec clock_resolution; int stat; unsigned int cycle1; unsigned int autoscale; wiringPiSetup () ; pinMode (tsl_pin, INPUT) ; cycle1=atoi(argv[1]); printf("Start\n"); //actual readout - gettime/ loop untill "cycles" counts are met / gettime again and make diff autoscale=2; ra=1; // autoscale till time is more than 300 ms then perform real readout while (ra<300000) { autoscale=autoscale*2; clock_gettime(CLOCK_REALTIME, &tp1); count_wait_tsl(autoscale); clock_gettime(CLOCK_REALTIME, &tp2); ra=time_diff(tp1,tp2)/1000; } cycle1=autoscale; // normal read clock_gettime(CLOCK_REALTIME, &tp1); count_wait_tsl(cycle1); clock_gettime(CLOCK_REALTIME, &tp2); printf(" Rezultat %ld \n",time_diff(tp1,tp2)); printf("Sec2 %d \n",tp2.tv_sec); printf("Sec1 %d \n",tp1.tv_sec); printf("NANO Sec2 %ld \n",tp2.tv_nsec); printf("NANO Sec1 %ld \n",tp1.tv_nsec); printf(" REZ %ld \n",tp2.tv_nsec-tp1.tv_nsec+1000000000*(tp2.tv_sec-tp1.tv_sec)); // here frequency should be computed and converted to uW/cm2 . 1khz = 1 uW/m2 // ra=time_diff(tp1,tp2)/1000; // rb=cycle1*500/(float)ra; printf("(-)Cycles = %d \n",cycle1); printf("(-)Frequency is : %.9f \n",(float)time_diff(tp1,tp2)/((float)cycle1*(float)1000)); printf("(-)Power is : %.9f uW/cm2\n",(float)cycle1*(float)(1000000)/(float)time_diff(tp1,tp2)); printf("(0)Cycles = %d \n",cycle1); printf("(0)Frequency is : %.9f \n",time_diff(tp1,tp2)/(cycle1*1000)); printf("(0)Power is : %.9f uW/cm2\n",cycle1*1000000/time_diff(tp1,tp2)); cycle1=autoscale; //---------------------------- //actual readout - gettime/ loop untill "cycles" counts are met / gettime again and make diff // cycle1=cycle1*2; clock_gettime(CLOCK_REALTIME, &tp1); count_wait_tsl(cycle1); clock_gettime(CLOCK_REALTIME, &tp2); // here frequency should be computed and converted to uW/cm2 . 1khz = 1 uW/m2 ra=time_diff(tp1,tp2)/1000; rb=cycle1*500/ra; // printf("(2)Cycles = %d \n",cycle1); // printf("(2)Frequency is : %.3f ms/cycle %.3f \n",ra,cycle1); // printf("(2)Power is : %.3f uW/cm2\n",rb*1000); printf("(2)Cycles = %d \n",cycle1); printf("(2)Frequency is : %.9f \n",(float)time_diff(tp1,tp2)/((float)cycle1*(float)1000)); printf("(2)Power is : %.9f uW/cm2\n",(float)cycle1*(float)(1000000)/(float)time_diff(tp1,tp2)); //Just verification prints // printf(" Rezultat %ld \n",time_diff(tp1,tp2)); // printf("Sec2 %d \n",tp2.tv_sec); // printf("Sec1 %d \n",tp1.tv_sec); // printf("NANO Sec2 %ld \n",tp2.tv_nsec); // printf("NANO Sec1 %ld \n",tp1.tv_nsec); // printf(" REZ %ld \n",tp2.tv_nsec-tp1.tv_nsec+1000000000*(tp2.tv_sec-tp1.tv_sec)); printf("Stop\n"); }
#ifdef HAVE_XSYNC if (!window->disable_sync && window->display->grab_sync_request_alarm != None) { if (window->sync_request_time.tv_sec != 0 || window->sync_request_time.tv_usec != 0) { double elapsed = time_diff (¤t_time, &window->sync_request_time); if (elapsed < 1000.0) { /* We want to be sure that the timeout happens at * a time where elapsed will definitely be * greater than 1000, so we can disable sync */ if (remaining) *remaining = 1000.0 - elapsed + 100; return FALSE; } else { /* We have now waited for more than a second for the * application to respond to the sync request */ window->disable_sync = TRUE; return TRUE; } } else