Exemplo n.º 1
0
long getCurrentTime() {
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
Exemplo n.º 2
0
int openServer() {
    pthread_t pthread_mirror, pthread_service[32];
    struct lws_context_creation_info info;
    unsigned int ms, oldms = 0;
    const char *iface = NULL;
    char interface_name[128] = "";
    char certificationPath[1024];
    char keyPath[1024];
    char resourcePath[1024];
    int threads = 1;
    int useSSL = 0;
    int opts = 0;
    int n = 0;
    void *retval;

#ifndef LWS_NO_DAEMONIZE
    int daemonize = 0;
#endif
    
    /*
     * take care to zero down the info struct, he contains random garbaage
     * from the stack otherwise
     */
    memset(&info, 0, sizeof info);
    info.port = PORT;

    pthread_mutex_init(&lock_established_conns, NULL);
    signal(SIGINT, sighandler);
    
    /* tell the library what debug level to emit and to send it to syslog */
    lws_set_log_level(DEBUG_LEVEL, lwsl_emit_syslog);

    /* Get resource path */
    if (getcwd(resourcePath, sizeof(resourcePath)) != NULL) {
        fprintf(stdout, "Current working dir: %s\n", resourcePath);
    } 
    else {
        perror("getcwd() error");
        return -1;
    }
    strcat(resourcePath, RESOURCE_PATH);
    RESOURCE_PATH = resourcePath;
    printf("Using resource path \"%s\"\n", RESOURCE_PATH);
    
#ifdef EXTERNAL_POLL
    max_poll_elements = getdtablesize();
    pollfds = malloc(max_poll_elements * sizeof (struct lws_pollfd));
    fd_lookup = malloc(max_poll_elements * sizeof (int));
    if (pollfds == NULL || fd_lookup == NULL) {
        lwsl_err("Out of memory pollfds=%d\n", max_poll_elements);
        return -1;
    }
#endif
    
    info.iface = iface;
    info.protocols = protocols;
    info.extensions = exts;
    info.ssl_cert_filepath = NULL;
    info.ssl_private_key_filepath = NULL;
    
    if (useSSL) {
        if (strlen(RESOURCE_PATH) > sizeof(certificationPath) - 32) {
            lwsl_err("resource path too long\n");
            return -1;
        }
        sprintf(certificationPath, "%s/libwebsockets-test-server.pem", RESOURCE_PATH);
        if (strlen(RESOURCE_PATH) > sizeof(keyPath) - 32) {
            lwsl_err("resource path too long\n");
            return -1;
        }
        sprintf(keyPath, "%s/libwebsockets-test-server.key.pem", RESOURCE_PATH);
        info.ssl_cert_filepath = certificationPath;
        info.ssl_private_key_filepath = keyPath;
    }

    info.gid = -1;
    info.uid = -1;
    info.options = opts | LWS_SERVER_OPTION_VALIDATE_UTF8;
    info.max_http_header_pool = 1;
    context = lws_create_context(&info);
    if (context == NULL) {
        lwsl_err("Server failed to initialize!\n");
        return -1;
    }
    
    /* start the dumb increment thread */
    n = pthread_create(&pthread_mirror, NULL, thread_lws_mirror, 0);
    if (n) {
        lwsl_err("Unable to create dumb thread\n");
        goto done;
    }

    /* stash original platform fops */
    fops_plat = *(lws_get_fops(context));

    /* override the active fops */
    lws_get_fops(context)->open = test_server_fops_open;
    
    n = 0;
    while (n >= 0 && !force_exit) {
        struct timeval tv;
        gettimeofday(&tv, NULL);
#ifdef EXTERNAL_POLL
        printf("ifdef EXTERNAL POLL");
        /*
         * this represents an existing server's single poll action
         * which also includes libwebsocket sockets
         */
        n = poll(pollfds, count_pollfds, 50);
        if (n < 0) continue;
        if (n)
            for (n = 0; n < count_pollfds; n++)
                if (pollfds[n].revents)
                /*
                 * returns immediately if the fd does not
                 * match anything under libwebsockets
                 * control
                 */
                    if (lws_service_fd(context, &pollfds[n]) < 0)
                        goto done;
#else
        /*
         * If libwebsockets sockets are all we care about,
         * you can use this api which takes care of the poll()
         * and looping through finding who needed service.
         *
         * If no socket needs service, it'll return anyway after
         * the number of ms in the second argument.
         */
        n = lws_service(context, 50);
#endif
    }
done:
    lws_context_destroy(context);
    pthread_mutex_destroy(&lock_established_conns);
    lwsl_notice("Server exited cleanly\n");
    return 0;
}
Exemplo n.º 3
0
static double myclockd(void){
    struct timeval tk;
    gettimeofday(&tk,NULL);
    return (double)tk.tv_sec+(double)tk.tv_usec*1e-6;
}
Exemplo n.º 4
0
/* ****************************************************

    Function that generates all files.

   **************************************************** */
long double make_generic_file(char * filepath, long double size, int depth, FILE * fp_log) {

    int header_size=0;
    char header[1024];
    char ext[3], full_filepath[1024], helperexec[1024];
    char cmd[1024], args[1024];
    int ext_number;
    
    __Ntime gettimeofday(&extension_start, NULL);

    /* Either the extension is specified directly
    by the user, or one is chosen according to the 
    count popularity */
    
    if(IMP_input->Flag[sf_ext] >=0)
        ext_number = IMP_input->Flag[sf_ext];
    else 
        ext_number = montecarlo_extension();
    

    __Ntime gettimeofday(&extension_end, NULL);
    __Ntime extension_total += diff_time(extension_start, extension_end);

    /* If the tail is chosen, generate a random extension */
    if(ext_number == NUM_EXTENSIONS - 1 ) { 
        get_random_ext(ext);
        print_debug(0, "Tail file selected %d %s\n", ext_number, ext);
    }
    else { 
        strcpy(ext, extension_array[ext_number]);
        print_debug(0, "Non Tail file selected %d %s\n", ext_number, ext);
    }

    if(IMP_input->Printwhat[pw_ext]==1) {
        print_debug(0,"Extension: %s\n", ext);
    }

    if(ext_number)
        sprintf(full_filepath, "%s.%s", filepath, ext); //extension_array[ext_number]);
    else if (ext_number ==0) {
        sprintf(full_filepath, "%s", filepath);
        
        /*If you want a ".nul" instead of just a file without any extension,
        use the following line instead*/
        //sprintf(full_filepath, "%s.%s", filepath, extension_array[ext_number]);
    }

    print_debug(0,"File: %s\n",full_filepath);
    
    if(ACTUAL_LOG_CREATION)
    {
        if(!fprintf(fp_log, "%s %d %Lf %d %s\n", ext, ext_number, size, depth, full_filepath))
            print_debug(0,"LOG FILE from impress not being written!\n");
    }
    
    /* If files and dirs are both being created on disk:
       Generate ascii, binary, or typed file according to file extension
    */
    if(IMP_input->Actualfilecreation == 1) {
        switch(ext_number) {
            case NUL: 
            case TXT: 
            case CPP: 
            case H:
                make_ascii_file(full_filepath, size, -1); 
                break;    
            case GIF:
                /* Create a gif file using the gif extension helper */
                __Ntime gettimeofday(&file_creation_start, NULL);
                sprintf(helperexec, "%s/%s",  EXT_HELPERS, "gif");
                sprintf(cmd, "%s/%s %s %d %d", EXT_HELPERS, "gif", full_filepath, 1000, 1000);
                size = 1757;
                if(access(helperexec, X_OK) == 0)
                    system(cmd);
                else {
                    print_debug(0, "EXT_HELPER: gif not available, resorting to binary file\n");
                    make_binary_file(full_filepath, size, -1);
                }
                __Ntime gettimeofday(&file_creation_end, NULL);
                __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end);
                break;
            case MP3:
                /* Create a mp3 file using the mp3 extension helper */
                make_binary_file(full_filepath, size, -1);
                __Ntime gettimeofday(&file_creation_start, NULL);
                sprintf(args, "-a \"Test Artist\" -A \"Test Album\" -t \"Test Song Title\" -c \" Impressions File MP3\" -g \"POP\" -y \"2007\" -T \"1\"");
                sprintf(helperexec, "%s/%s",  EXT_HELPERS, "mp3");
                sprintf(cmd, "%s/%s %s %s",EXT_HELPERS, "mp3", args, full_filepath);
                if(access(helperexec, X_OK) == 0)
                    system(cmd);
                else {
                    print_debug(0, "EXT_HELPER: mp3 not available, resorting to binary file\n");
                }
                __Ntime gettimeofday(&file_creation_end, NULL);
                __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end);
                break;
            case LIB:
            case VHD:
            case EXE:
            case PDB:
            case DLL:
            case TAL:   // tail file group, individual ext right now not factored
                make_binary_file(full_filepath, size, -1); // binary file
                break;
            case WMA:
            case PST:
            case PCH:
                // temporary solution, not creating a perfect PCH file
                make_binary_file(full_filepath, size, -1); // binary file
                break;
            case JPG:
                __Ntime gettimeofday(&file_creation_start, NULL);
                sprintf(helperexec, "%s/%s",  EXT_HELPERS, "gif");
                sprintf(cmd, "%s/%s %s %d %d", EXT_HELPERS, "gif", "temp.gif", 1000, 1000);
                size = 1757;
                if(access(helperexec, X_OK) == 0) {
                    system(cmd);
                    sprintf(cmd, "giftopnm temp.gif > temp.pnm");
                    system(cmd);
                    sprintf(cmd, "pnmtojpeg temp.pnm > %s", full_filepath);
                    system(cmd);
                }
                else {
                    print_debug(0, "EXT_HELPER: gif not available, resorting to binary file\n");
                    make_binary_file(full_filepath, size, -1);
                }
                __Ntime gettimeofday(&file_creation_end, NULL);
                __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end);
                break;
            case PDF:
                make_binary_file(full_filepath, size, 16); 
                break;
            case HTM:
                make_ascii_file(full_filepath, size, -1); 
        }
    }
    return size;
}
Exemplo n.º 5
0
/* ****************************************************

    Function that generates an ascii file.

   **************************************************** */
int make_ascii_file(char * filepath, long double size, int extension_num) {

    char buf[MY_BLOCK_SIZE], strerr[100];
    long double written = 0.0;
    long double blocks_written=0;
    int num_seeks=0, turn =0, seeker=0;
    long double * frag_schedule_array;
    int is_garbage =0, j=0;
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
    int fd=0;
    long double num_blocks = ceill(size/MY_BLOCK_SIZE);
    double min_blocks_needed=0.0;
    int write_iter =0;

    if(is_garbage ==1) {
        buf[0]='I';
        buf[1]='M';
        buf[2]='P';
        buf[3]='R';
        buf[4]='E';
        buf[5]='S';
        buf[6]='S';
    }
    
    // get data buffer once for non word-freq
    __Ntime gettimeofday(&filecontent_start, NULL);
    
    random_word_block(buf);
    
    __Ntime gettimeofday(&filecontent_end, NULL);
    __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end);
    
    if(IMP_input->Layoutscore < 1) {
        double fragment_degree = 1 - IMP_input->Layoutscore;
        min_blocks_needed = (double) ceil(1/fragment_degree);
        if(num_blocks>= min_blocks_needed) {
            num_seeks = (int) ((fragment_degree*num_blocks -floor(fragment_degree*num_blocks) <= 0.5) ? \
                        floor(fragment_degree*num_blocks):ceil(fragment_degree*num_blocks));
            if(num_seeks!=0){
                frag_schedule_array = (long double*) malloc(sizeof(long double)*num_seeks);
                
                #ifdef PRINT
                if(frag_schedule_array!=NULL) 
                    print_debug(0,"Allocated %d, numblocks %Lf, size %Lf\n", num_seeks, num_blocks, size);
                else 
                    print_debug(0,"Allocation error\n");
                #endif
            }
            
            for(int i = 0; i < num_seeks; i++) {
                frag_schedule_array[i] = (long double) (rand()%((int)num_blocks) + 1);
                print_debug(0, " - %Lf -", frag_schedule_array[i]);
            }
            
            qsort((void*) frag_schedule_array, (size_t) num_seeks, (size_t) sizeof(long double), compfunc);
            
            #ifdef PRINT 
            for(int j=0; j<num_seeks; j++) {
                print_debug(0," %Lf ", frag_schedule_array[j]);
            }
            #endif
        }
    }
       
    if((fd = pos_creat(filepath, mode)) <0) {
            strerror_r(errno, strerr, 100);
            print_debug(1,"Error: Unable to create file= %s %d\n", filepath, errno);
    }
    else { // write to file with size
        
        written = 0;
        
        // if filetype has a header, write it, e.g, PDF
        if (extension_num > 0){
            written += (long double) pos_write(fd, (void*)extension_header[extension_num],sizeof(extension_header[extension_num]));
        }
            
        while(written < size) {
          
            // get new random block everytime for wordfreq, else we already got it once above
            if(IMP_input->Flag[sf_wordfreq] >=1) {
                __Ntime gettimeofday(&filecontent_start, NULL);
                random_word_block(buf);
                __Ntime gettimeofday(&filecontent_end, NULL);
                __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end);
           }
           
            print_debug(0, "Write iteration %d\n", write_iter++);
          
           __Ntime gettimeofday(&file_creation_start, NULL);
           print_debug(0,"random block : %s\n", buf);
            if (size - written < MY_BLOCK_SIZE) {
                print_debug(0,"%s, %f, %f\n", filepath, size - written, size);
                written+=(long double)pos_write(fd,(void*)buf,(size_t)(size-written));
                blocks_written+=1; // assumes previous pos_write wrote an entire block as issued

                print_debug(0,"Blocks to file %s,%f,%d\n",filepath,written,MY_BLOCK_SIZE);
            }
            else {
                written += (long double) pos_write(fd, (void*) buf, MY_BLOCK_SIZE);
                blocks_written+=1; // assumes previous pos_write wrote an entire block as issued
                print_debug(0,"Blocks to file %s, %f\n", filepath, written);
            }
           __Ntime gettimeofday(&file_creation_end, NULL);
           __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end);
                
            /* Fragment the file in this loop */
           __Ntime gettimeofday(&aging_start, NULL);
            if(num_seeks!=0 && seeker < num_seeks) {
                
                print_debug(0,"sch %Lf written %Lf\n", frag_schedule_array[seeker], blocks_written); 

                while(frag_schedule_array[seeker]==frag_schedule_array[seeker+1])
                    seeker++; // throw away duplicates
                
                if(seeker < num_seeks && frag_schedule_array[seeker]==blocks_written) {
                    fragment(turn);
                    turn++;
                    seeker++;
                }
            }
           __Ntime gettimeofday(&aging_end, NULL);
           __Ntime aging_total += diff_time(aging_start, aging_end);
        }
        
        //cleanup
        if(num_seeks > 0 && turn%2==1) 
            fragment(-1);       
        pos_close(fd);
    }
    if(num_seeks!=0) 
        free(frag_schedule_array);
}
Exemplo n.º 6
0
void NS_CLASS log(int type, int errnum, const char *function, char *format, ...)
{
    va_list ap;
    static char buffer[256] = "";
    static char log_buf[1024];
    char *msg;
    struct timeval now;
    struct tm *time;
    int len = 0;

/* NS_PORT: Include IP address in log */
#ifdef NS_PORT
    if (DEV_NR(NS_DEV_NR).enabled == 1) {
	len += sprintf(log_buf + len, "%s: ",
		       ip_to_str(DEV_NR(NS_DEV_NR).ipaddr));
    }
#endif				/* NS_PORT */

    va_start(ap, format);

    if (type == LOG_WARNING)
	msg = &buffer[9];
    else
	msg = buffer;

    vsprintf(msg, format, ap);
    va_end(ap);

    if (!debug && !log_to_file)
	goto syslog;

    gettimeofday(&now, NULL);

#ifdef NS_PORT
    time = gmtime(&now.tv_sec);
#else
    time = localtime(&now.tv_sec);
#endif

    /*   if (type <= LOG_NOTICE) */
/* 	len += sprintf(log_buf + len, "%s: ", progname); */

    len += sprintf(log_buf + len, "%02d:%02d:%02d.%03ld %s: %s", time->tm_hour,
		   time->tm_min, time->tm_sec, now.tv_usec / 1000, function,
		   msg);

    if (errnum == 0)
	len += sprintf(log_buf + len, "\n");
    else
	len += sprintf(log_buf + len, ": %s\n", strerror(errnum));

    if (len > 1024) {
	fprintf(stderr, "log(): buffer to small! len = %d\n", len);
	goto syslog;
    }

    /* OK, we are clear to write the buffer to the aodv log file... */
    if (log_to_file)
	write_to_log_file(log_buf, len);

    /* If we have the debug option set, also write to stdout */
    if (debug)
	printf(log_buf);

    /* Syslog all messages that are of severity LOG_NOTICE or worse */
  syslog:
    if (type <= LOG_NOTICE) {
	if (errnum != 0) {
	    errno = errnum;
	    syslog(type, "%s: %s: %m", function, msg);
	} else
	    syslog(type, "%s: %s", function, msg);
    }
    /* Exit on error */
    if (type <= LOG_ERR)
	exit(-1);
}
void print_stats() {
  static u_int64_t lastPkts[MAX_NUM_THREADS] = { 0 };
  static u_int64_t lastRXPkts = 0, lastTXPkts = 0, lastRXProcPkts = 0;
  static struct timeval lastTime;
  pfring_stat pfringStat;
  struct timeval endTime;
  double delta, deltaABS;
  u_int64_t diff;
  u_int64_t RXdiff, TXdiff, RXProcdiff;
  pfring_dna_cluster_stat cluster_stats;
  char buf1[32], buf2[32], buf3[32];
  int i;

  if(startTime.tv_sec == 0) {
    gettimeofday(&startTime, NULL);
    return;
  }

  gettimeofday(&endTime, NULL);
  deltaABS = delta_time(&endTime, &startTime);

  delta = delta_time(&endTime, &lastTime);

  for(i=0; i < num_threads; i++) {
    if(pfring_stats(thread_stats[i].ring, &pfringStat) >= 0) {
      double thpt = ((double)8*thread_stats[i].numBytes)/(deltaABS*1000);

      fprintf(stderr, "=========================\n"
              "Thread %d\n"
	      "Absolute Stats: [%u pkts rcvd][%lu bytes rcvd]\n"
	      "                [%u total pkts][%u pkts dropped (%.1f %%)]\n"
              "                [%s pkt/sec][%.2f Mbit/sec]\n", i,
	      (unsigned int) thread_stats[i].numPkts,
	      (long unsigned int)thread_stats[i].numBytes,
	      (unsigned int) (thread_stats[i].numPkts+pfringStat.drop),
	      (unsigned int) pfringStat.drop,
	      thread_stats[i].numPkts == 0 ? 0 : (double)(pfringStat.drop*100)/(double)(thread_stats[i].numPkts+pfringStat.drop),
              pfring_format_numbers(((double)(thread_stats[i].numPkts*1000)/deltaABS), buf1, sizeof(buf1), 1),
	      thpt);

      if(lastTime.tv_sec > 0) {
	// double pps;
	
	diff = thread_stats[i].numPkts-lastPkts[i];
	// pps = ((double)diff/(double)(delta/1000));
	fprintf(stderr, "Actual   Stats: [%llu pkts][%.1f ms][%s pkt/sec]\n",
		(long long unsigned int) diff, 
		delta,
		pfring_format_numbers(((double)diff/(double)(delta/1000)), buf1, sizeof(buf1), 1));
      }

      lastPkts[i] = thread_stats[i].numPkts;
    }
  }
 
  if(dna_cluster_stats(dna_cluster_handle, &cluster_stats) == 0) {
    if(lastTime.tv_sec > 0) {
      RXdiff = cluster_stats.tot_rx_packets - lastRXPkts; 
      RXProcdiff = cluster_stats.tot_rx_processed - lastRXProcPkts;
      TXdiff = cluster_stats.tot_tx_packets - lastTXPkts; 

      fprintf(stderr, "=========================\n"
                      "Aggregate Actual Stats: [Captured %s pkt/sec][Processed %s pkt/sec][Sent %s pkt/sec]\n",
              pfring_format_numbers(((double)RXdiff/(double)(delta/1000)), buf1, sizeof(buf1), 1),
              pfring_format_numbers(((double)RXProcdiff/(double)(delta/1000)), buf2, sizeof(buf2), 1),
              pfring_format_numbers(((double)TXdiff/(double)(delta/1000)), buf3, sizeof(buf3), 1));
    }

    lastRXPkts = cluster_stats.tot_rx_packets;
    lastRXProcPkts = cluster_stats.tot_rx_processed;
    lastTXPkts = cluster_stats.tot_tx_packets;
  }

  if (print_interface_stats) {
    pfring_stat if_stats;
    fprintf(stderr, "=========================\nInterface Absolute Stats\n");
    for (i = 0; i < num_dev; i++)
      if (pfring_stats(pd[i], &if_stats) >= 0)
        fprintf(stderr, "%s RX [%" PRIu64 " pkts rcvd][%" PRIu64 " pkts dropped (%.1f %%)]\n",
	        pd[i]->device_name, if_stats.recv, if_stats.drop,
		if_stats.recv == 0 ? 0 : ((double)(if_stats.drop*100)/(double)(if_stats.recv + if_stats.drop)));
  }


  fprintf(stderr, "=========================\n\n");
  
  lastTime.tv_sec = endTime.tv_sec, lastTime.tv_usec = endTime.tv_usec;
}
Exemplo n.º 8
0
AnovaTest::AnovaTest(mv_Method *mm, gsl_matrix *Y, gsl_matrix *X, gsl_matrix *isXvarIn):mmRef(mm), Yref(Y), Xref(X), inRef(isXvarIn)
{
    unsigned int hid, aid;
    unsigned int i, j, count;
    nModels=inRef->size1, nParam=Xref->size2;
    nRows=Yref->size1, nVars=Yref->size2; 

//  printf("initialize public variables: stats\n");
    multstat=(double *)malloc((nModels-1)*sizeof(double));
    Pmultstat = (double *)malloc((nModels-1)*sizeof(double));
    for (j=0; j<nModels-1; j++) *(Pmultstat+j)=0.0; 
    dfDiff = (unsigned int *)malloc((nModels-1)*sizeof(unsigned int));

    statj = gsl_matrix_alloc(nModels-1, nVars);
    Pstatj = gsl_matrix_alloc(nModels-1, nVars);
    gsl_matrix_set_zero(Pstatj);

    bStatj = gsl_vector_alloc(nVars);
    Hats = (mv_mat *)malloc(nModels*sizeof(mv_mat)); 
    sortid = (gsl_permutation **)malloc((nModels-1)*sizeof(gsl_permutation *));
    
    for (i=0; i<nModels; i++ ) {
        // Hats[i]
        Hats[i].mat=gsl_matrix_alloc(nRows, nRows);
        Hats[i].SS=gsl_matrix_alloc(nVars, nVars);
        Hats[i].R=gsl_matrix_alloc(nVars, nVars);
        Hats[i].Res=gsl_matrix_alloc(nRows, nVars);
        Hats[i].Y = gsl_matrix_alloc(nRows, nVars);
        Hats[i].sd = gsl_vector_alloc(nVars);
	count = 0;
	for (j=0; j<nParam; j++){
	    count+=(unsigned int)gsl_matrix_get(inRef, i, j);
	}
//	printf("count=%d \n", count);
	Hats[i].X = gsl_matrix_alloc(nRows, count);
	Hats[i].Coef=gsl_matrix_alloc(count, nVars);
        gsl_vector_view refi=gsl_matrix_row(inRef, i);
	subX(Xref, &refi.vector, Hats[i].X);
        calcSS(Yref, &(Hats[i]), mmRef);
//	displaymatrix(Hats[i].SS, "SS");
    }

    for (i=1; i<nModels; i++) {
        hid = i; aid = i-1;
        if ( mmRef->resamp != CASEBOOT ) {
            // fit = Y- resi 
            gsl_matrix_memcpy (Hats[i].Y, Yref);
            gsl_matrix_sub (Hats[i].Y, Hats[i].Res);
        } 
        gsl_vector_view statij = gsl_matrix_row(statj, aid);
        testStatCalc(&(Hats[hid]), &(Hats[aid]), mmRef, TRUE, (multstat+aid), &statij.vector); 
	dfDiff[aid] = Hats[aid].X->size2-Hats[hid].X->size2;
        // sortid
        sortid[aid] = gsl_permutation_alloc(nVars);
        gsl_sort_vector_index (sortid[aid], &statij.vector); 
        // rearrange sortid in descending order
        gsl_permutation_reverse (sortid[aid]);
    }  

    // initialize resampling indices 
//    getBootID(); done in R
    bootID = NULL;


    // Initialize GSL rnd environment variables
    const gsl_rng_type *T;
    gsl_rng_env_setup();
    T = gsl_rng_default;
    // an mt19937 generator with a seed of 0
    rnd = gsl_rng_alloc(T);
    if (mmRef->reprand!=TRUE){
       struct timeval tv;  // seed generation based on time
       gettimeofday(&tv, 0);
       unsigned long mySeed=tv.tv_sec + tv.tv_usec;
       gsl_rng_set(rnd, mySeed);  // reset seed
    }

//    printf("Anova test initialized.\n");

}
int main(int ac, char **av)
{
	const char *progname = av[0];
	int opt;
	const char *name, *defconfig_file = NULL /* gcc uninit */;
	struct stat tmpstat;

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	while ((opt = getopt_long(ac, av, "", long_opts, NULL)) != -1) {
		input_mode = (enum input_mode)opt;
		switch (opt) {
		case silentoldconfig:
			sync_kconfig = 1;
			break;
		case defconfig:
		case savedefconfig:
			defconfig_file = optarg;
			break;
		case randconfig:
		{
			struct timeval now;
			unsigned int seed;

			/*
			 * Use microseconds derived seed,
			 * compensate for systems where it may be zero
			 */
			gettimeofday(&now, NULL);

			seed = (unsigned int)((now.tv_sec + 1) * (now.tv_usec + 1));
			srand(seed);
			break;
		}
		case oldaskconfig:
		case oldconfig:
		case allnoconfig:
		case allyesconfig:
		case allmodconfig:
		case alldefconfig:
		case listnewconfig:
		case oldnoconfig:
			break;
		case '?':
			conf_usage(progname);
			exit(1);
			break;
		}
	}
	if (ac == optind) {
		printf(_("%s: Kconfig file missing\n"), av[0]);
		conf_usage(progname);
		exit(1);
	}
	name = av[optind];
	conf_parse(name);
	//zconfdump(stdout);
	if (sync_kconfig) {
		name = conf_get_configname();
		if (stat(name, &tmpstat)) {
			fprintf(stderr, _("***\n"
				"*** Configuration file \"%s\" not found!\n"
				"***\n"
				"*** Please run some configurator (e.g. \"make oldconfig\" or\n"
				"*** \"make menuconfig\" or \"make xconfig\").\n"
				"***\n"), name);
			exit(1);
		}
	}

	switch (input_mode) {
	case defconfig:
		if (!defconfig_file)
			defconfig_file = conf_get_default_confname();
		if (conf_read(defconfig_file)) {
			printf(_("***\n"
				"*** Can't find default configuration \"%s\"!\n"
				"***\n"), defconfig_file);
			exit(1);
		}
                name = getenv("KCONFIG_SELINUX");
                printf("KCONFIG_SELINUX(%s)\n", name);
                if (name) {
                        if (conf_read_simple(name, S_DEF_USER, false)) {
                                printf(_("***\n"
                                        "*** Can't find selinux configuration \"%s\"!\n"
                                        "***\n"), name);
                                exit(1);
                        }
                }
                name = getenv("KCONFIG_LOG_SELINUX");
                printf("KCONFIG_LOG_SELINUX(%s)\n", name);
                if (name) {
                        if (conf_read_simple(name, S_DEF_USER, false)) {
                                printf(_("***\n"
                                        "*** Can't find selinux log configuration \"%s\"!\n"
                                        "***\n"), name);
                                exit(1);
                        }
                }
                name = getenv("KCONFIG_TIMA");
                printf("KCONFIG_TIMA(%s)\n", name);
                if (name) {
                        if (conf_read_simple(name, S_DEF_USER, false)) {
                                printf(_("***\n"
                                        "*** Can't find tima log configuration \"%s\"!\n"
                                        "***\n"), name);
                                exit(1);
                        }
                }
		name = getenv("KCONFIG_VARIANT");
		printf("KCONFIG_VARIANT(%s)\n", name);
		if (name) {
			if (conf_read_simple(name, S_DEF_USER, false)) {
				printf(_("***\n"
					"*** Can't find variant configuration \"%s\"!\n"
					"***\n"), name);
				exit(1);
			}
		} 
		name = getenv("KCONFIG_DEBUG");
		printf("KCONFIG_DEBUG(%s)\n", name);
		if (name) {
			if (conf_read_simple(name, S_DEF_USER, false)) {
				printf(_("***\n"
					"*** Can't find debug configuration \"%s\"!\n"
					"***\n"), name);
				exit(1);
			}
		}
		break;
	case savedefconfig:
	case silentoldconfig:
	case oldaskconfig:
	case oldconfig:
	case listnewconfig:
	case oldnoconfig:
		conf_read(NULL);
		break;
	case allnoconfig:
	case allyesconfig:
	case allmodconfig:
	case alldefconfig:
	case randconfig:
		name = getenv("KCONFIG_ALLCONFIG");
		if (name && !stat(name, &tmpstat)) {
			conf_read_simple(name, S_DEF_USER, true);
			break;
		}
		switch (input_mode) {
		case allnoconfig:	name = "allno.config"; break;
		case allyesconfig:	name = "allyes.config"; break;
		case allmodconfig:	name = "allmod.config"; break;
		case alldefconfig:	name = "alldef.config"; break;
		case randconfig:	name = "allrandom.config"; break;
		default: break;
		}
		if (!stat(name, &tmpstat))
			conf_read_simple(name, S_DEF_USER, true);
		else if (!stat("all.config", &tmpstat))
			conf_read_simple("all.config", S_DEF_USER, true);
		break;
	default:
		break;
	}

	if (sync_kconfig) {
		if (conf_get_changed()) {
			name = getenv("KCONFIG_NOSILENTUPDATE");
			if (name && *name) {
				fprintf(stderr,
					_("\n*** The configuration requires explicit update.\n\n"));
				return 1;
			}
		}
		valid_stdin = isatty(0) && isatty(1) && isatty(2);
	}

	switch (input_mode) {
	case allnoconfig:
		conf_set_all_new_symbols(def_no);
		break;
	case allyesconfig:
		conf_set_all_new_symbols(def_yes);
		break;
	case allmodconfig:
		conf_set_all_new_symbols(def_mod);
		break;
	case alldefconfig:
		conf_set_all_new_symbols(def_default);
		break;
	case randconfig:
		conf_set_all_new_symbols(def_random);
		break;
	case defconfig:
		conf_set_all_new_symbols(def_default);
		break;
	case savedefconfig:
		break;
	case oldaskconfig:
		rootEntry = &rootmenu;
		conf(&rootmenu);
		input_mode = silentoldconfig;
		/* fall through */
	case oldconfig:
	case listnewconfig:
	case oldnoconfig:
	case silentoldconfig:
		/* Update until a loop caused no more changes */
		do {
			conf_cnt = 0;
			check_conf(&rootmenu);
		} while (conf_cnt &&
			 (input_mode != listnewconfig &&
			  input_mode != oldnoconfig));
		break;
	}

	if (sync_kconfig) {
		/* silentoldconfig is used during the build so we shall update autoconf.
		 * All other commands are only used to generate a config.
		 */
		if (conf_get_changed() && conf_write(NULL)) {
			fprintf(stderr, _("\n*** Error during writing of the configuration.\n\n"));
			exit(1);
		}
		if (conf_write_autoconf()) {
			fprintf(stderr, _("\n*** Error during update of the configuration.\n\n"));
			return 1;
		}
	} else if (input_mode == savedefconfig) {
		if (conf_write_defconfig(defconfig_file)) {
			fprintf(stderr, _("n*** Error while saving defconfig to: %s\n\n"),
			        defconfig_file);
			return 1;
		}
	} else if (input_mode != listnewconfig) {
		if (conf_write(NULL)) {
			fprintf(stderr, _("\n*** Error during writing of the configuration.\n\n"));
			exit(1);
		}
	}
	return 0;
}
Exemplo n.º 10
0
void SDL_StartTicks(void)
{
	/* Set first ticks value */
	gettimeofday(&start, NULL);
}
Exemplo n.º 11
0
static int send_probe(int ifindex, __u32 addr)
{
	struct ifreq ifr = { .ifr_ifindex = ifindex };
	struct sockaddr_in dst = {
		.sin_family = AF_INET,
		.sin_port = htons(1025),
		.sin_addr.s_addr = addr,
	};
	socklen_t len;
	unsigned char buf[256];
	struct arphdr *ah = (struct arphdr *)buf;
	unsigned char *p = (unsigned char *)(ah+1);
	struct sockaddr_ll sll = {
		.sll_family = AF_PACKET,
		.sll_ifindex = ifindex,
		.sll_protocol = htons(ETH_P_ARP),
	};

	if (ioctl(udp_sock, SIOCGIFNAME, &ifr))
		return -1;
	if (ioctl(udp_sock, SIOCGIFHWADDR, &ifr))
		return -1;
	if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER)
		return -1;
	if (setsockopt(udp_sock, SOL_SOCKET, SO_BINDTODEVICE, ifr.ifr_name, strlen(ifr.ifr_name)+1) < 0)
		return -1;

	if (connect(udp_sock, (struct sockaddr *)&dst, sizeof(dst)) < 0)
		return -1;
	len = sizeof(dst);
	if (getsockname(udp_sock, (struct sockaddr *)&dst, &len) < 0)
		return -1;

	ah->ar_hrd = htons(ifr.ifr_hwaddr.sa_family);
	ah->ar_pro = htons(ETH_P_IP);
	ah->ar_hln = 6;
	ah->ar_pln = 4;
	ah->ar_op  = htons(ARPOP_REQUEST);

	memcpy(p, ifr.ifr_hwaddr.sa_data, ah->ar_hln);
	p += ah->ar_hln;

	memcpy(p, &dst.sin_addr, 4);
	p += 4;

	memset(sll.sll_addr, 0xFF, sizeof(sll.sll_addr));
	memcpy(p, &sll.sll_addr, ah->ar_hln);
	p += ah->ar_hln;

	memcpy(p, &addr, 4);
	p += 4;

	if (sendto(pset[0].fd, buf, p-buf, 0, (struct sockaddr *)&sll, sizeof(sll)) < 0)
		return -1;
	stats.probes_sent++;
	return 0;
}

/* Be very tough on sending probes: 1 per second with burst of 3. */

static int queue_active_probe(int ifindex, __u32 addr)
{
	static struct timeval prev;
	static int buckets;
	struct timeval now;

	gettimeofday(&now, NULL);
	if (prev.tv_sec) {
		int diff = (now.tv_sec-prev.tv_sec)*1000+(now.tv_usec-prev.tv_usec)/1000;

		buckets += diff;
	} else {
		buckets = broadcast_burst;
	}
	if (buckets > broadcast_burst)
		buckets = broadcast_burst;
	if (buckets >= broadcast_rate && !send_probe(ifindex, addr)) {
		buckets -= broadcast_rate;
		prev = now;
		return 0;
	}
	stats.probes_suppressed++;
	return -1;
}

static int respond_to_kernel(int ifindex, __u32 addr, char *lla, int llalen)
{
	struct {
		struct nlmsghdr	n;
		struct ndmsg		ndm;
		char			buf[256];
	} req = {
		.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg)),
		.n.nlmsg_flags = NLM_F_REQUEST,
		.n.nlmsg_type = RTM_NEWNEIGH,
		.ndm.ndm_family = AF_INET,
		.ndm.ndm_state = NUD_STALE,
		.ndm.ndm_ifindex = ifindex,
		.ndm.ndm_type = RTN_UNICAST,
	};

	addattr_l(&req.n, sizeof(req), NDA_DST, &addr, 4);
	addattr_l(&req.n, sizeof(req), NDA_LLADDR, lla, llalen);
	return rtnl_send(&rth, &req, req.n.nlmsg_len) <= 0;
}

static void prepare_neg_entry(__u8 *ndata, __u32 stamp)
{
	ndata[0] = 0xFF;
	ndata[1] = 0;
	ndata[2] = stamp>>24;
	ndata[3] = stamp>>16;
	ndata[4] = stamp>>8;
	ndata[5] = stamp;
}


static int do_one_request(struct nlmsghdr *n)
{
	struct ndmsg *ndm = NLMSG_DATA(n);
	int len = n->nlmsg_len;
	struct rtattr *tb[NDA_MAX+1];
	struct dbkey key;
	DBT dbkey, dbdat;
	int do_acct = 0;

	if (n->nlmsg_type == NLMSG_DONE) {
		dbase->sync(dbase, 0);

		/* Now we have at least mirror of kernel db, so that
		 * may start real resolution.
		 */
		do_sysctl_adjustments();
		return 0;
	}

	if (n->nlmsg_type != RTM_GETNEIGH && n->nlmsg_type != RTM_NEWNEIGH)
		return 0;

	len -= NLMSG_LENGTH(sizeof(*ndm));
	if (len < 0)
		return -1;

	if (ndm->ndm_family != AF_INET ||
	    (ifnum && !handle_if(ndm->ndm_ifindex)) ||
	    ndm->ndm_flags ||
	    ndm->ndm_type != RTN_UNICAST ||
	    !(ndm->ndm_state&~NUD_NOARP))
		return 0;

	parse_rtattr(tb, NDA_MAX, NDA_RTA(ndm), len);

	if (!tb[NDA_DST])
		return 0;

	key.iface = ndm->ndm_ifindex;
	memcpy(&key.addr, RTA_DATA(tb[NDA_DST]), 4);
	dbkey.data = &key;
	dbkey.size = sizeof(key);

	if (dbase->get(dbase, &dbkey, &dbdat, 0) != 0) {
		dbdat.data = 0;
		dbdat.size = 0;
	}

	if (n->nlmsg_type == RTM_GETNEIGH) {
		if (!(n->nlmsg_flags&NLM_F_REQUEST))
			return 0;

		if (!(ndm->ndm_state&(NUD_PROBE|NUD_INCOMPLETE))) {
			stats.app_bad++;
			return 0;
		}

		if (ndm->ndm_state&NUD_PROBE) {
			/* If we get this, kernel still has some valid
			 * address, but unicast probing failed and host
			 * is either dead or changed its mac address.
			 * Kernel is going to initiate broadcast resolution.
			 * OK, we invalidate our information as well.
			 */
			if (dbdat.data && !IS_NEG(dbdat.data))
				stats.app_neg++;

			dbase->del(dbase, &dbkey, 0);
		} else {
			/* If we get this kernel does not have any information.
			 * If we have something tell this to kernel. */
			stats.app_recv++;
			if (dbdat.data && !IS_NEG(dbdat.data)) {
				stats.app_success++;
				respond_to_kernel(key.iface, key.addr, dbdat.data, dbdat.size);
				return 0;
			}

			/* Sheeit! We have nothing to tell. */
			/* If we have recent negative entry, be silent. */
			if (dbdat.data && NEG_VALID(dbdat.data)) {
				if (NEG_CNT(dbdat.data) >= active_probing) {
					stats.app_suppressed++;
					return 0;
				}
				do_acct = 1;
			}
		}

		if (active_probing &&
		    queue_active_probe(ndm->ndm_ifindex, key.addr) == 0 &&
		    do_acct) {
			NEG_CNT(dbdat.data)++;
			dbase->put(dbase, &dbkey, &dbdat, 0);
		}
	} else if (n->nlmsg_type == RTM_NEWNEIGH) {
		if (n->nlmsg_flags&NLM_F_REQUEST)
			return 0;

		if (ndm->ndm_state&NUD_FAILED) {
			/* Kernel was not able to resolve. Host is dead.
			 * Create negative entry if it is not present
			 * or renew it if it is too old. */
			if (!dbdat.data ||
			    !IS_NEG(dbdat.data) ||
			    !NEG_VALID(dbdat.data)) {
				__u8 ndata[6];

				stats.kern_neg++;
				prepare_neg_entry(ndata, time(NULL));
				dbdat.data = ndata;
				dbdat.size = sizeof(ndata);
				dbase->put(dbase, &dbkey, &dbdat, 0);
			}
		} else if (tb[NDA_LLADDR]) {
			if (dbdat.data && !IS_NEG(dbdat.data)) {
				if (memcmp(RTA_DATA(tb[NDA_LLADDR]), dbdat.data, dbdat.size) == 0)
					return 0;
				stats.kern_change++;
			} else {
				stats.kern_new++;
			}
			dbdat.data = RTA_DATA(tb[NDA_LLADDR]);
			dbdat.size = RTA_PAYLOAD(tb[NDA_LLADDR]);
			dbase->put(dbase, &dbkey, &dbdat, 0);
		}
	}
	return 0;
}

static void load_initial_table(void)
{
	if (rtnl_wilddump_request(&rth, AF_INET, RTM_GETNEIGH) < 0) {
		perror("dump request failed");
		exit(1);
	}

}

static void get_kern_msg(void)
{
	int status;
	struct nlmsghdr *h;
	struct sockaddr_nl nladdr = {};
	struct iovec iov;
	char   buf[8192];
	struct msghdr msg = {
		(void *)&nladdr, sizeof(nladdr),
		&iov,	1,
		NULL,	0,
		0
	};

	iov.iov_base = buf;
	iov.iov_len = sizeof(buf);

	status = recvmsg(rth.fd, &msg, MSG_DONTWAIT);

	if (status <= 0)
		return;

	if (msg.msg_namelen != sizeof(nladdr))
		return;

	if (nladdr.nl_pid)
		return;

	for (h = (struct nlmsghdr *)buf; status >= sizeof(*h); ) {
		int len = h->nlmsg_len;
		int l = len - sizeof(*h);

		if (l < 0 || len > status)
			return;

		if (do_one_request(h) < 0)
			return;

		status -= NLMSG_ALIGN(len);
		h = (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len));
	}
}
Exemplo n.º 12
0
int64_t getMilisegundos()
{
    struct timeval tempo;
    gettimeofday(&tempo, NULL);
    return (int64_t) tempo.tv_sec * 1000 + tempo.tv_usec / 1000;
 }
Exemplo n.º 13
0
double gettime(void) {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec + 1e-6*tv.tv_usec;
}
Exemplo n.º 14
0
static void log_line(const int priority, const char *DebugBuffer)
{
	if (DEBUGLOG_SYSLOG_DEBUG == LogMsgType)
		syslog(LOG_INFO, "%s", DebugBuffer);
	else
	{
		static struct timeval last_time = { 0, 0 };
		struct timeval new_time = { 0, 0 };
		struct timeval tmp;
		int delta;

		gettimeofday(&new_time, NULL);
		if (0 == last_time.tv_sec)
			last_time = new_time;

		tmp.tv_sec = new_time.tv_sec - last_time.tv_sec;
		tmp.tv_usec = new_time.tv_usec - last_time.tv_usec;
		if (tmp.tv_usec < 0)
		{
			tmp.tv_sec--;
			tmp.tv_usec += 1000000;
		}
		if (tmp.tv_sec < 100)
			delta = tmp.tv_sec * 1000000 + tmp.tv_usec;
		else
			delta = 99999999;

		last_time = new_time;

		if (LogDoColor)
		{
			const char *color_pfx = "", *color_sfx = "\33[0m";
			const char *time_pfx = "\33[36m", *time_sfx = color_sfx;

			switch (priority)
			{
				case PCSC_LOG_CRITICAL:
					color_pfx = "\33[01;31m"; /* bright + Red */
					break;

				case PCSC_LOG_ERROR:
					color_pfx = "\33[35m"; /* Magenta */
					break;

				case PCSC_LOG_INFO:
					color_pfx = "\33[34m"; /* Blue */
					break;

				case PCSC_LOG_DEBUG:
					color_pfx = ""; /* normal (black) */
					color_sfx = "";
					break;
			}

			printf("%s%.8d%s %s%s%s\n", time_pfx, delta, time_sfx,
				color_pfx, DebugBuffer, color_sfx);
		}
		else
		{
			printf("%.8d %s\n", delta, DebugBuffer);
		}
		fflush(stdout);
	}
} /* log_msg */
Exemplo n.º 15
0
/**
 * This function is added in order to simulate arduino millis() function
 */
void __start_timer()
{
	gettimeofday(&start, NULL);
}
Exemplo n.º 16
0
 /***********************************
  * MAIN
  * *********************************/
int main(int argc, char *argv[]){

	Connection connection;
	write_error_ptr = &write_error;  //initialize the function pointer to write error
	
	//parse arguments	
	if(argc == 4){
		//first argument is always name of program or empty string
		connection.planebone_ip=argv[1];
		connection.port_number_server_to_planebone=atoi(argv[2]);	
		connection.port_number_planebone_to_server=atoi(argv[3]);
	}else{
			printf("wrong parameters: planebone ip - send port number - receive port number\n");
			exit(EXIT_FAILURE);		
	}
		
	pthread_t thread_server_to_planebone;

	//create a second thread which executes server_to_planebone
	if(pthread_create(&thread_server_to_planebone, NULL, server_to_planebone,&connection)) {
		error_write(FILENAME,"error creating lisa thread");
		exit(EXIT_FAILURE);
	}	
	
	/*-------------------------START OF FIRST THREAD: PLANEBONE TO SERVER------------------------*/
	
	static UDP udp_server;
	uint8_t input_stream[MAX_INPUT_STREAM_SIZE];
	timeval tv_now;

	UDP_err_handler(openUDPServerSocket(&udp_server,connection.port_number_planebone_to_server,UDP_SOCKET_TIMEOUT),write_error_ptr);
	
	//init the data decode pointers
	init_decoding();
	
	/*
	 * WHAT WE EXPECT:
	 * IMU_ACCEL_RAW 204
	 * IMU_GYRO_RAW 203
	 * IMU_MAG_RAW 205
	 * BARO_RAW 221
	 * GPS_INT 155
	 * AIRSPEED_ETS 57
	 * SYSMON 33
	 * UART_ERROR 208
	 * ACTUATORS_received 105
	 * */
	 
	int IMU_ACCEL_RAW_received=0;
	int IMU_GYRO_RAW_received=0;	
	int IMU_MAG_RAW_received=0;
	int BARO_RAW_received=0;
	int GPS_INT_received=0;
	int AIRSPEED_received=0;
	int SVINFO_received=0;
	int SYSMON_received=0;
	int UART_ERROR_received=0;
	int ACTUATORS_received=0;
	int NMEA_IIMWV_received = 0;
	int NMEA_WIXDR_received = 0;
	int err;
	
	#if ANALYZE
		Analyze an_imu_accel_raw_freq,an_imu_accel_raw_lat;
		int an_imu_accel_freq_done=0,an_imu_accel_lat_done=0;
		init_analyze(&an_imu_accel_raw_freq,2000);
		init_analyze(&an_imu_accel_raw_lat,2000);

		Analyze an_imu_gyro_raw_freq,an_imu_gyro_raw_lat;
		int an_imu_gyro_freq_done=0,an_imu_gyro_lat_done=0;
		init_analyze(&an_imu_gyro_raw_freq,2000);
		init_analyze(&an_imu_gyro_raw_lat,2000);
		
		Analyze an_imu_mag_raw_freq,an_imu_mag_raw_lat;
		int an_imu_mag_freq_done=0,an_imu_mag_lat_done=0;
		init_analyze(&an_imu_mag_raw_freq,2000);
		init_analyze(&an_imu_mag_raw_lat,2000);
		
		Analyze an_baro_raw_freq,an_baro_raw_lat;
		int an_baro_raw_freq_done=0,an_baro_raw_lat_done=0;
		init_analyze(&an_baro_raw_freq,2000);
		init_analyze(&an_baro_raw_lat,2000);
		
		Analyze an_gps_int_freq,an_gps_int_lat;
		int an_gps_int_freq_done=0,an_gps_int_lat_done=0;
		init_analyze(&an_gps_int_freq,40);
		init_analyze(&an_gps_int_lat,40);
		
		Analyze an_airspeed_ets_freq,an_airspeed_ets_lat;
		int an_airspeed_ets_freq_done=0,an_airspeed_ets_lat_done=0;
		init_analyze(&an_airspeed_ets_freq,100);
		init_analyze(&an_airspeed_ets_lat,100);
		
		Analyze an_actuators_freq,an_actuators_lat;
		int an_actuators_freq_done=0,an_actuators_lat_done=0;
		init_analyze(&an_actuators_freq,500);
		init_analyze(&an_actuators_lat,500);
		
		Analyze an_UART_errors_freq,an_UART_errors_lat;
		int an_UART_errors_freq_done=0,an_UART_errors_lat_done=0;
		init_analyze(&an_UART_errors_freq,50);
		init_analyze(&an_UART_errors_lat,50);
		
		Analyze an_sys_mon_freq,an_sys_mon_lat;
		int an_sys_mon_freq_done=0,an_sys_mon_lat_done=0;
		init_analyze(&an_sys_mon_freq,50);
		init_analyze(&an_sys_mon_lat,50);

	#endif


	int recv_len;
	size_t data_len = sizeof(input_stream);

	while (1){
		// err = receiveUDPServerData(&udp_server,(void *)&input_stream, sizeof(input_stream)); //blocking !!!
		//1. retreive UDP data form planebone from ethernet port.
		err = receiveUDPServerData(&udp_server,(void *)&input_stream, data_len, &recv_len); //blocking !!!

		if (recv_len != 30) {
			printf("Wrong number of bytes in received UDP packet!\n");
                	printf("Expected 30 bytes, Received %d bytes!\n", recv_len);
                	err = UDP_ERR_RECV;
		}

		UDP_err_handler(err,write_error_ptr); 
	
		if(err == UDP_ERR_NONE){
			gettimeofday(&tv_now,NULL); //timestamp from receiving to calculate latency
			
			#if DEBUG > 0
			
				printf("message raw: ");
				int i;
				for(i=0;i<input_stream[1];i++){
						printf("%d ",input_stream[i]);
				}
				printf("\n");
				
				printf("start hex: %x\n", input_stream[0]);
				printf("length: %d\n", input_stream[1]);
				printf("send id: %d\n", input_stream[2]);
				printf("message id: %d\n", input_stream[3]);
				printf("checksum1: %d\n", input_stream[input_stream[1]-2]);
				printf("checksum2: %d\n", input_stream[input_stream[1]-1]);
				// printf("%d", input_stream[3]);
				printf("\n");
			
			#endif
			
			//2. decode data 		
			int err  = data_decode(input_stream);
			DEC_err_handler(err,write_error_ptr);
	
			if(err==DEC_ERR_NONE){ 
			
				switch_read_write(); //only switch read write if data decoding was succesfull
				Data* data = get_read_pointer();

				if(input_stream[3]==IMU_GYRO_RAW){
					IMU_GYRO_RAW_received=1;
				}else if(input_stream[3]==IMU_ACCEL_RAW){
					IMU_ACCEL_RAW_received=1;
				}else if(input_stream[3]==IMU_MAG_RAW){
					IMU_MAG_RAW_received=1;
				}else if(input_stream[3]==BARO_RAW){
					BARO_RAW_received=1;
				}else if(input_stream[3]==GPS_INT){
					GPS_INT_received=1;
				}else if(input_stream[3]==AIRSPEED_ETS){
					AIRSPEED_received=1;
				}else if(input_stream[3]==SVINFO){
					SVINFO_received=1;
				}else if(input_stream[3]==SYSMON){
					SYSMON_received=1;
				}else if(input_stream[3]==UART_ERRORS){
					UART_ERROR_received=1;
				}else if(input_stream[3]==ACTUATORS){
					ACTUATORS_received=1;
				}else if(input_stream[3]==NMEA_IIMWV_ID){
					NMEA_IIMWV_received=1;
				}else if(input_stream[3]==NMEA_WIXDR_ID){
					NMEA_WIXDR_received=1;
				}
				
				/*printf("IMU_GYRO_RAW_received %d\n",IMU_GYRO_RAW_received);
				printf("IMU_ACCEL_RAW_received %d\n",IMU_ACCEL_RAW_received);
				printf("IMU_MAG_RAW_received %d\n",IMU_MAG_RAW_received);
				printf("BARO_RAW_received %d\n",BARO_RAW_received);
				printf("GPS_INT_received %d\n",GPS_INT_received);			
				printf("AIRSPEED_received %d\n",AIRSPEED_received);			
				printf("SVINFO_received %d\n",SVINFO_received);	
				printf("SYSMON_received %d\n",SYSMON_received);	
				printf("UART_ERROR_received %d\n",UART_ERROR_received);	
				printf("ACTUATORS_received %d\n",ACTUATORS_received);
				printf("NMEA_IIMWV_received %d\n",NMEA_IIMWV_received);	
				printf("NMEA_WIXDR_received %d\n",NMEA_WIXDR_received);	
				printf("\n");*/

				if(input_stream[3]==BARO_RAW){
					#if ANALYZE
						if(calculate_frequency(&an_baro_raw_freq,data->lisa_plane.baro_raw.tv)==1){
							an_baro_raw_freq_done=1;
						}

						if(calculate_latency(&an_baro_raw_lat,data->lisa_plane.baro_raw.tv,tv_now)==1){
							an_baro_raw_lat_done=1;
						}
					#endif
					/*int i;
					printf("Baro_raw content:");	
					print_mem((void *)&data->lisa_plane.baro_raw,sizeof(Baro_raw));
	
					printf("abs %d\n",data->lisa_plane.baro_raw.abs);
					printf("diff %d\n",data->lisa_plane.baro_raw.diff);	
					
									 
					printf("\n\n\n");*/
				}
				
				if(input_stream[3]==IMU_GYRO_RAW){
					
					#if ANALYZE
						if(calculate_frequency(&an_imu_gyro_raw_freq,data->lisa_plane.imu_gyro_raw.tv)==1){
							an_imu_gyro_freq_done=1;
						}
						

						if(calculate_latency(&an_imu_gyro_raw_lat,data->lisa_plane.imu_gyro_raw.tv,tv_now)==1){
							an_imu_gyro_lat_done=1;
						}
					#endif
					
				/*	int i;
					printf("Imu_gyro_raw content:");
					print_mem((void *)&data->lisa_plane.imu_gyro_raw,sizeof(Imu_gyro_raw));
				
					printf("\n");
					printf("gp %d\n",data->lisa_plane.imu_gyro_raw.gp);
					printf("gq %d\n",data->lisa_plane.imu_gyro_raw.gq);
					printf("gr %d\n",data->lisa_plane.imu_gyro_raw.gr);
					
					print_latency(data->lisa_plane.imu_gyro_raw.tv);
				 
					printf("\n\n\n");*/

				}
				
				if(input_stream[3]==IMU_ACCEL_RAW){
					
					#if ANALYZE
						if(calculate_frequency(&an_imu_accel_raw_freq,data->lisa_plane.imu_accel_raw.tv)==1){
							an_imu_accel_freq_done=1;
						}
						

						if(calculate_latency(&an_imu_accel_raw_lat,data->lisa_plane.imu_accel_raw.tv,tv_now)==1){
							an_imu_accel_lat_done=1;
						}
					#endif
					
					
					/*int i;
					printf("Imu_accel_raw content:");
					print_mem((void *)&data->lisa_plane.imu_accel_raw,sizeof(Imu_accel_raw));


					printf("\n");
					printf("ax %d\n",data->lisa_plane.imu_accel_raw.ax);
					printf("ay %d\n",data->lisa_plane.imu_accel_raw.ay);
					printf("az %d\n",data->lisa_plane.imu_accel_raw.az);
					printf("\n");
					
			 
					printf("\n\n\n");*/

				}
				
				if(input_stream[3]==IMU_MAG_RAW){
					
					#if ANALYZE
						if(calculate_frequency(&an_imu_mag_raw_freq,data->lisa_plane.imu_mag_raw.tv)==1){
							an_imu_mag_freq_done=1;
						}

						if(calculate_latency(&an_imu_mag_raw_lat,data->lisa_plane.imu_mag_raw.tv,tv_now)==1){
							an_imu_mag_lat_done=1;
						}
					#endif
						

				}
				
				if(input_stream[3]==AIRSPEED_ETS){
					
					#if ANALYZE
						if(calculate_frequency(&an_airspeed_ets_freq,data->lisa_plane.airspeed_ets.tv)==1){
							an_airspeed_ets_freq_done=1;
						}

						if(calculate_latency(&an_airspeed_ets_lat,data->lisa_plane.airspeed_ets.tv,tv_now)==1){
							an_airspeed_ets_lat_done=1;
						}
					#endif
					
					/*int i;
					printf("airspeed content:");
					print_mem((void *)&data->lisa_plane.airspeed_ets,sizeof(Airspeed_ets));
					
					char temp[64];
					timestamp_to_timeString(data->lisa_plane.airspeed_ets.tv,temp);
					printf("send time %s\n",temp);

					printf("adc %d\n",data->lisa_plane.airspeed_ets.adc);
					printf("offset %d\n",data->lisa_plane.airspeed_ets.offset);
					printf("scaled %f\n",data->lisa_plane.airspeed_ets.scaled);*/
				}
				
				
				if(input_stream[3]==GPS_INT){
					#if ANALYZE
						if(calculate_frequency(&an_gps_int_freq,data->lisa_plane.gps_int.tv)==1){
							an_gps_int_freq_done=1;
						}

						if(calculate_latency(&an_gps_int_lat,data->lisa_plane.gps_int.tv,tv_now)==1){
							an_gps_int_lat_done=1;
						}
					#endif
				
					/*int i;
					printf("Gps_int_message content:");
					print_mem((void *)&data->lisa_plane.gps_int,sizeof(Gps_int));

					printf("\n");
					printf("ecef_x %d\n",data->lisa_plane.gps_int.ecef_x);
					printf("ecef_y %d\n",data->lisa_plane.gps_int.ecef_y);
					printf("ecef_z %d\n",data->lisa_plane.gps_int.ecef_z);
					printf("lat %d\n",data->lisa_plane.gps_int.lat);
					printf("lon %d\n",data->lisa_plane.gps_int.lon);
					printf("alt %d\n",data->lisa_plane.gps_int.alt);
					printf("hmsl %d\n",data->lisa_plane.gps_int.hmsl);
					printf("ecef_xd %d\n",data->lisa_plane.gps_int.ecef_xd);
					printf("ecef_yd %d\n",data->lisa_plane.gps_int.ecef_yd);
					printf("ecef_zd %d\n",data->lisa_plane.gps_int.ecef_zd);
					printf("pacc %d\n",data->lisa_plane.gps_int.pacc);
					printf("sacc %d\n",data->lisa_plane.gps_int.sacc);
					printf("tow %d\n",data->lisa_plane.gps_int.tow);
					printf("pdop %d\n",data->lisa_plane.gps_int.pdop);
					printf("numsv %d\n",data->lisa_plane.gps_int.numsv);
					printf("fix %d\n",data->lisa_plane.gps_int.fix);
					print_latency(data->lisa_plane.gps_int.tv);*/

					
				}
				
		
				if(input_stream[3]==SYSMON){
					
					#if ANALYZE
						if(calculate_frequency(&an_sys_mon_freq,data->lisa_plane.sys_mon.tv)==1){
							an_sys_mon_freq_done=1;
						}

						if(calculate_latency(&an_sys_mon_lat,data->lisa_plane.sys_mon.tv,tv_now)==1){
							an_sys_mon_lat_done=1;
						}
					#endif	
					
				/*	int i;
					printf("sysmon content:");
					print_mem((void *)&data->lisa_plane.sys_mon,sizeof(Sys_mon));

					printf("\n");
					printf("periodic_time %d\n",data->lisa_plane.sys_mon.periodic_time);
					printf("periodic_cycle %d\n",data->lisa_plane.sys_mon.periodic_cycle);
					printf("periodic_cycle_min %d\n",data->lisa_plane.sys_mon.periodic_cycle_min);
					printf("periodic_cycle_max %d\n",data->lisa_plane.sys_mon.periodic_cycle_max);
					printf("event_number %d\n",data->lisa_plane.sys_mon.event_number);
					printf("cpu_load %d\n",data->lisa_plane.sys_mon.cpu_load);
					print_latency(data->lisa_plane.sys_mon.tv);*/

				}
			if(input_stream[3]==UART_ERRORS){
				
				#if ANALYZE
					if(calculate_frequency(&an_UART_errors_freq,data->lisa_plane.uart_errors.tv)==1){
						an_UART_errors_freq_done=1;
					}

					if(calculate_latency(&an_UART_errors_lat,data->lisa_plane.uart_errors.tv,tv_now)==1){
						an_UART_errors_lat_done=1;
					}
				#endif
				/*	int i;
					printf("uart error content:");
					print_mem((void *)&data->lisa_plane.uart_errors,sizeof(UART_errors));

					printf("overrun_cnt %d\n",data->lisa_plane.uart_errors.overrun_cnt);
					printf("noise_err_cnt %d\n",data->lisa_plane.uart_errors.noise_err_cnt);
					printf("framing_err_cnt %d\n",data->lisa_plane.uart_errors.framing_err_cnt);
					printf("bus_number %d\n",data->lisa_plane.uart_errors.bus_number);
					print_latency(data->lisa_plane.uart_errors.tv);*/

				}
				if(input_stream[3]==ACTUATORS){
					#if ANALYZE
						if(calculate_frequency(&an_actuators_freq,data->lisa_plane.actuators.tv)==1){
							an_actuators_freq_done=1;
						}

						if(calculate_latency(&an_actuators_lat,data->lisa_plane.actuators.tv,tv_now)==1){
							an_actuators_lat_done=1;
						}
					#endif
					
					/*int i;
					printf("actuators content:");
					print_mem((void *)&data->lisa_plane.actuators,sizeof(Actuators));

					printf("arr_length %d\n",data->lisa_plane.actuators.arr_length);
					for(i=0;i<data->lisa_plane.actuators.arr_length;i++){
						printf("servo_%d %d\n",i,data->lisa_plane.actuators.values[i]);
					}
					print_latency(data->lisa_plane.actuators.tv);*/

				}
				
				if(input_stream[3]==BEAGLE_ERROR){
					//printf("beagle bone error content:");
					//print_mem((void *)&data->bone_plane.error,sizeof(Beagle_error));
										
					switch(data->bone_plane.error.library){
						case UDP_L:
							UDP_err_handler(data->bone_plane.error.error_code,write_error_ptr);
						break;
						case UART_L:
							UART_err_handler(data->bone_plane.error.error_code,write_error_ptr);
						break;
						case DECODE_L:
							DEC_err_handler(data->bone_plane.error.error_code,write_error_ptr);
						break;
						case LOG_L:
							LOG_err_handler(data->bone_plane.error.error_code,write_error_ptr);
						break;
					}
				}
				
				if(input_stream[3]==NMEA_IIMWV_ID){
					
					printf("NMEA_IIMWV_ID content:");
					print_mem((void *)&data->bone_wind.nmea_iimmwv,sizeof(NMEA_IIMWV));

					printf("wind angle %lf\n",data->bone_wind.nmea_iimmwv.wind_angle);
					printf("relative %c\n",data->bone_wind.nmea_iimmwv.relative);
					printf("wind speed %lf\n",data->bone_wind.nmea_iimmwv.wind_speed);
					printf("wind speed unit %c\n",data->bone_wind.nmea_iimmwv.wind_speed_unit);
					printf("status %c\n",data->bone_wind.nmea_iimmwv.status);
					char temp[64];
					timestamp_to_timeString16(data->bone_wind.nmea_iimmwv.tv,temp);
					printf("send time: %s\n",temp);
					printf("\n");

				}
				
				if(input_stream[3]==NMEA_WIXDR_ID){
					
					printf("NMEA_WIXDR_ID content:");
					print_mem((void *)&data->bone_wind.nmea_wixdr,sizeof(NMEA_WIXDR));
					
					printf("Temperature %lf\n",data->bone_wind.nmea_wixdr.temperature);
					printf("unit %c\n",data->bone_wind.nmea_wixdr.unit);
					char temp[64];
					timestamp_to_timeString16(data->bone_wind.nmea_wixdr.tv,temp);
					printf("send time: %s\n",temp);
					printf("\n");
				}
				
				if(input_stream[3]==LINE_ANGLE_ID){
					// Send a character (to gpio of arduino)
					// to stop the arduino-timer
					/*
					FILE *myFile;
					myFile = fopen("/dev/ttyUSB0", "w");
					fputs ("a", myFile);
					fclose (myFile);
					*/
					

					printf("LINE_ANGLE_ID content:");
					print_mem((void *)&data->bone_arm.line_angle,sizeof(LINE_ANGLE));
					
					printf("Azimuth %i\n",data->bone_arm.line_angle.azimuth_raw);
					printf("Elevation %i\n",data->bone_arm.line_angle.elevation_raw);
					// printf("unit %c\n",data->bone_wind.nmea_wixdr.unit);
					//char temp[64];
					//timestamp_to_timeString16(data->bone_arm.line_angle.tv,temp);
					//printf("send time: %s\n",temp);
					printf("\n");
				}
									
			}else{
					printf("UNKNOW PACKAGE with id %d\n",input_stream[3]);
					exit(1);
			}
		}
		#if ANALYZE
			if(an_imu_accel_freq_done==1 && 
					an_imu_accel_lat_done==1 && 
					an_imu_gyro_freq_done==1 && 
					an_imu_gyro_lat_done==1 && 
					an_imu_mag_freq_done==1 && 
					an_imu_mag_lat_done==1 && 
					an_baro_raw_lat_done==1 && 
					an_baro_raw_freq_done==1 && 
					an_airspeed_ets_lat_done==1 && 
					an_airspeed_ets_freq_done==1 && 
					an_actuators_lat_done==1 && 
					an_actuators_freq_done==1 && 
					an_UART_errors_lat_done==1 && 
					an_UART_errors_freq_done==1 && 
					an_sys_mon_lat_done==1 && 
					an_sys_mon_freq_done==1)
			{
				printf("ANALYZE RESULTS - IMU_ACCEL_RAW:\n");
				printf("avg period:\t %0.4f ms\n",(get_avg(&an_imu_accel_raw_freq)));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_imu_accel_raw_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_imu_accel_raw_lat));
				printf("\n");
				dump_buffer_to_file(&an_imu_accel_raw_freq,"analyze/imu_accel_raw_per.csv");
				dump_buffer_to_file(&an_imu_accel_raw_lat,"analyze/imu_accel_raw_lat.csv");
				destroy_analyze(&an_imu_accel_raw_freq);
				destroy_analyze(&an_imu_accel_raw_lat);
				
				printf("ANALYZE RESULTS - IMU_GYRO_RAW:\n");
				printf("avg period:\t %0.4f ms\n",(get_avg(&an_imu_gyro_raw_freq)));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_imu_gyro_raw_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_imu_gyro_raw_lat));
				printf("\n");
				dump_buffer_to_file(&an_imu_gyro_raw_freq,"analyze/imu_gyro_raw_per.csv");
				dump_buffer_to_file(&an_imu_gyro_raw_lat,"analyze/imu_gyro_raw_lat.csv");
				destroy_analyze(&an_imu_gyro_raw_freq);
				destroy_analyze(&an_imu_gyro_raw_lat);
				
				printf("ANALYZE RESULTS - IMU_MAG_RAW:\n");
				printf("avg period:\t %0.4f ms\n",(get_avg(&an_imu_mag_raw_freq)));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_imu_mag_raw_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_imu_mag_raw_lat));
				printf("\n");
				dump_buffer_to_file(&an_imu_mag_raw_freq,"analyze/imu_mag_raw_per.csv");
				dump_buffer_to_file(&an_imu_mag_raw_lat,"analyze/imu_mag_raw_lat.csv");
				destroy_analyze(&an_imu_mag_raw_freq);
				destroy_analyze(&an_imu_mag_raw_lat);
				
				printf("ANALYZE RESULTS - BARO_RAW:\n");
				printf("avg period:\t %0.4f ms\n",(get_avg(&an_baro_raw_freq)));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_baro_raw_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_baro_raw_lat));
				printf("\n");
				dump_buffer_to_file(&an_baro_raw_freq,"analyze/baro_raw_per.csv");
				dump_buffer_to_file(&an_baro_raw_lat,"analyze/baro_raw_lat.csv");
				destroy_analyze(&an_baro_raw_freq);
				destroy_analyze(&an_baro_raw_lat);
				
				printf("ANALYZE RESULTS - GPS_INT:\n");
				printf("avg period:\t %0.4f ms\n",get_avg(&an_gps_int_freq));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_gps_int_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_gps_int_lat));
				printf("\n");
				dump_buffer_to_file(&an_gps_int_freq,"analyze/gps_int_per.csv");
				dump_buffer_to_file(&an_gps_int_lat,"analyze/gps_int_lat.csv");
				destroy_analyze(&an_gps_int_freq);
				destroy_analyze(&an_gps_int_lat);
				
				printf("ANALYZE RESULTS - AIRSPEED_ETS:\n");
				printf("avg period:\t %0.4f ms\n",get_avg(&an_airspeed_ets_freq));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_airspeed_ets_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_airspeed_ets_lat));
				printf("\n");
				dump_buffer_to_file(&an_airspeed_ets_freq,"analyze/airspeed_ets_per.csv");
				dump_buffer_to_file(&an_airspeed_ets_lat,"analyze/airspeed_ets_lat.csv");
				destroy_analyze(&an_airspeed_ets_freq);
				destroy_analyze(&an_airspeed_ets_lat);
				
				printf("ANALYZE RESULTS - ACTUATORS:\n");
				printf("avg period:\t %0.4f ms\n",get_avg(&an_actuators_freq));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_actuators_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_actuators_lat));
				printf("\n");
				dump_buffer_to_file(&an_actuators_freq,"analyze/actuators_per.csv");
				dump_buffer_to_file(&an_actuators_lat,"analyze/actuators_lat.csv");
				destroy_analyze(&an_actuators_freq);
				destroy_analyze(&an_actuators_lat);
				
				printf("ANALYZE RESULTS - UART_ERRORS:\n");
				printf("avg period:\t %0.4f ms\n",get_avg(&an_UART_errors_freq));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_UART_errors_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_UART_errors_lat));
				printf("\n");
				dump_buffer_to_file(&an_UART_errors_freq,"analyze/UART_errors_per.csv");
				dump_buffer_to_file(&an_UART_errors_lat,"analyze/UART_errors_lat.csv");
				destroy_analyze(&an_UART_errors_freq);
				destroy_analyze(&an_UART_errors_lat);
			
				printf("ANALYZE RESULTS - SYS_MON:\n");
				printf("avg period:\t %0.4f ms\n",get_avg(&an_sys_mon_freq));
				printf("avg freq:\t %0.4f hz\n",1/(get_avg(&an_sys_mon_freq))*1e3);
				printf("avg latency\t %0.4f ms\n",get_avg(&an_sys_mon_lat));
				printf("\n");
				dump_buffer_to_file(&an_sys_mon_freq,"analyze/sys_mon_per.csv");
				dump_buffer_to_file(&an_sys_mon_lat,"analyze/sys_mon_lat.csv");
				destroy_analyze(&an_sys_mon_freq);
				destroy_analyze(&an_sys_mon_lat);

				exit(1);
			}
		#endif
		
	}
	
	UDP_err_handler(closeUDPServerSocket(&udp_server),write_error_ptr);

	/*------------------------END OF FIRST THREAD------------------------*/

	//wait for the second thread to finish
	if(pthread_join(thread_server_to_planebone, NULL)) {
		error_write(FILENAME,"error joining thread_lisa_to_pc");
		exit(EXIT_FAILURE);
	}

	return 0;
}
Exemplo n.º 17
0
int main(void)
{
	struct sockaddr_in servaddr, cliaddr;
	struct timeval tv, start;
    
	socklen_t cliaddr_len;
	int listenfd, new_fd;
	char buf[MAXLINE], buf_client[MAXLINE];
	int i, j, n, x, on,ret;
	fd_set clientfd;
	int maxsock, timeuse[FDCOUNT];
	
/* ===========socket============== */
	listenfd = Socket(AF_INET, SOCK_STREAM, 0);
/* ==========允许地址立即使用======== */
	on = 1;
	setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);
/* ==============bind============= */
	Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
/* ============listen============= */
	Listen(listenfd, 20);

	printf("~~~listen connections:\n");
	int conn_amount = 0;
	int fd_a[FDCOUNT];
	maxsock = listenfd;
	for(i=0;i<FDCOUNT;i++) {
		gettimeofday(&start, NULL);
		fd_a[i] = -1;
		timeuse[i] = start.tv_sec;
	}
	
	while(1) {
		FD_ZERO(&clientfd);
		FD_SET(listenfd, &clientfd);
		tv.tv_sec = TIME_SEC;
		tv.tv_usec = TIME_USEC;

		for(i=0;i<FDCOUNT;i++) {
			if(fd_a[i] != -1)
				FD_SET(fd_a[i], &clientfd);
		}
		cliaddr_len = sizeof(cliaddr);
		ret = select(maxsock+1, &clientfd, NULL, NULL, &tv);
		/* check timeout */
		for(i=0;i<FDCOUNT;i++) {
			gettimeofday(&start, NULL);
			timeuse[i] = start.tv_sec - timeuse[i];
			if(fd_a[i] !=-1 && timeuse[i] > TIME_SEC) {
				printf("***Client Timeout, id = %d\n", fd_a[i]);
				close(fd_a[i]);
				FD_CLR(fd_a[i], &clientfd);
				fd_a[i] = -1;
				timeuse[i] = 0;
			}
		}
		if(ret<0) {
			perror("select:");
			break;
		}
		else if(ret == 0) {
			for(i=0;i<FDCOUNT;i++) {
				if(fd_a[i] != -1) {
					printf("***Timeout, connection canceled, id = %d***\n", fd_a[i]);
					close(fd_a[i]);
					FD_CLR(fd_a[i], &clientfd);
					fd_a[i] = -1;
				}
			}
			conn_amount = 0;
			continue;
		}
		else if(FD_ISSET(listenfd, &clientfd)){
			new_fd=Accept(listenfd,(struct sockaddr*)&cliaddr, cliaddr_len) ;
			if(new_fd>0) {
				for(i=0;i<FDCOUNT;i++) {
					if(fd_a[i] != -1)
						continue;
					gettimeofday(&start, NULL); /* Record the time when connect. */
					timeuse[i] = start.tv_sec;

					fd_a[i] = new_fd;
					break;
				}
				
				if(conn_amount<FDCOUNT) {
					FD_SET(new_fd, &clientfd);
					printf("new connection client %d\n", new_fd);
					if(new_fd>maxsock)
						maxsock = new_fd;
					conn_amount++;
				}
				else {
					printf("***max connections arrive, disconnect***\n");
					close(new_fd);
					continue;
				}
			}
		}
		else {
			for(i=0;i<FDCOUNT;i++) {
				if(fd_a[i] == -1)
					continue;
				if(!FD_ISSET(fd_a[i], &clientfd))
					continue;
				memset(buf, 0, MAXLINE);
				n = read(fd_a[i], buf, MAXLINE);

				if(n<=0 || !strcmp(buf, EXIT_MSG)) {
					printf("client exit.id = %d\n", fd_a[i]);
					close(fd_a[i]);
					FD_CLR(fd_a[i], &clientfd);
					fd_a[i] = -1;
					conn_amount--;
					continue;
				}
				printf("\n---message from client---%d\n%s\n", fd_a[i], buf);

				gettimeofday(&start, NULL); /* get active time for client */
				timeuse[i] = start.tv_sec - timeuse[i];
/*

				if(timeuse[i] > TIME_SEC) {
					printf("***Client Timeout, id = %d\n", fd_a[i]);
					close(fd_a[i]);
					FD_CLR(fd_a[i], &clientfd);
					fd_a[i] = -1;
					timeuse[i] = 0;
					break;
				}
				else 
					timeuse[i] = start.tv_sec;
*/
				x = strlen(buf);
				memset(buf_client, 0, MAXLINE);
				for (j = 0; x>=0; x--, j++)
					buf_client[j] = buf[x];
				if((write(fd_a[i], buf_client, n)) == -1) {
					perror("write_1:");
					exit(1);
				}
				memset(buf, 0, MAXLINE);
				memset(buf_client, 0, MAXLINE);
			}
		}
	}
	close(listenfd);
	exit(0);
}
Exemplo n.º 18
0
/** program entry point */
int
main(int argc, char *argv[])
{
	int		 ch, fd;
	const char	*fmt = NULL;
	time_t		 f, t;
	struct timeb	 tb;
	extern int	 optind;
	extern char	*optarg;

	tzset();

	time(&curr_time);
	localtime_r(&curr_time, &curr_tm);

	memset(&tb, 0, sizeof(tb));
	tb.time = curr_time;
#if defined(__GLIBC__) || defined(__CYGWIN__)
	{
	struct timeval tv;
	struct timezone tz;

	gettimeofday(&tv, &tz);
	tb.timezone = tz.tz_minuteswest;
	}
#else
	/*
	 * as localtime_r(3) 
	 *	tm_gmtoff is the offset (in seconds) of the time represented
	 *	from UTC, with positive values indicating east of the Prime
	 *	Meridian.
	 * on the other hands tb.tb_timezone is minutes *west* of CUT.
	 */
	tb.timezone = -1 * (curr_tm.tm_gmtoff / 60);
#endif
	f = -1;
	t = curr_time;

	while ((ch = getopt(argc, argv, "iawhF:f:t:")) != -1)
		switch (ch) {
		case 'i':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = ISO_FMT;
			break;
		case 'a':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = ANSI_FMT;
			break;
		case 'w':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = APACHE_FMT;
			break;
		case 't':
			if ((t = get_date(optarg, &tb)) < 0) {
				fprintf(stderr, "parse error: %s\n", optarg);
				exit(1);
			}
			break;
		case 'f':
			if ((f = get_date(optarg, &tb)) < 0) {
				fprintf(stderr, "parse error: %s\n", optarg);
				exit(1);
			}
			break;
		case 'F':
			if (fmt != NULL) {
		fmt_redef:
				fprintf(stderr,
				    "Format is already specified: %s\n", fmt);
				exit(1);
			}
			fmt = optarg;
			break;
		default:
		case 'h':
			usage();
			exit(1);
		}

	argc -= optind;
	if (f == -1) {
		usage();
		exit(1);
	}
	if (fmt == NULL)
		fmt = ANSI_FMT;
	argv += optind;

	if (argc <= 0) {
		usage();
		exit(1);
	}
	while (argc > 0) {
		if ((fd = open(argv[0], O_RDONLY)) < 0)
			err(1, "open(%s)", argv[0]);
		if (cut_file(fd, STDOUT_FILENO, fmt, f, t) != 0)
			err(1, "cut_file(%s)", argv[0]);
		
		close(fd);
		argv++;
		argc--;
	}

	exit(0);
}
Exemplo n.º 19
0
void NS_CLASS print_rt_table(void *arg)
{
    char rt_buf[2048], ifname[64], seqno_str[11];
    int len = 0;
    int i = 0;
    rt_table_t *entry;
    precursor_t *pr;
    struct timeval now;
    struct tm *time;

    if (rt_tbl.num_entries == 0)
	goto schedule;

    gettimeofday(&now, NULL);

#ifdef NS_PORT
    time = gmtime(&now.tv_sec);
#else
    time = localtime(&now.tv_sec);
#endif

    len +=
	sprintf(rt_buf,
		"# Time: %02d:%02d:%02d.%03ld IP: %s seqno: %u entries/active: %u/%u\n",
		time->tm_hour, time->tm_min, time->tm_sec, now.tv_usec / 1000,
		devs_ip_to_str(), this_host.seqno, rt_tbl.num_entries,
		rt_tbl.num_active);
    len +=
	sprintf(rt_buf + len,
		"%-15s %-15s %-3s %-3s %-5s %-6s %-5s %-5s %-15s\n",
		"Destination", "Next hop", "HC", "St.", "Seqno", "Expire",
		"Flags", "Iface", "Precursors");

    write(log_rt_fd, rt_buf, len);
    len = 0;

    for (i = 0; i < RT_TABLESIZE; i++) {
	entry = rt_tbl.tbl[i];
	while (entry != NULL) {

	    if (entry->flags & RT_INV_SEQNO)
		sprintf(seqno_str, "-");
	    else
		sprintf(seqno_str, "%u", entry->dest_seqno);

	    /* Print routing table entries one by one... */
	    if (entry->precursors == NULL)
		len += sprintf(rt_buf + len,
			       "%-15s %-15s %-3d %-3s %-5s %-6lu %-5s %-5s\n",
			       ip_to_str(entry->dest_addr),
			       ip_to_str(entry->next_hop), entry->hcnt,
			       state_to_str(entry->state), seqno_str,
			       (entry->hcnt == 255) ? 0 :
			       timeval_diff(&entry->rt_timer.timeout, &now),
			       rt_flags_to_str(entry->flags),
			       if_indextoname(entry->ifindex, ifname));

	    else {
		len += sprintf(rt_buf + len,
			       "%-15s %-15s %-3d %-3s %-5s %-6lu %-5s %-5s %-15s\n",
			       ip_to_str(entry->dest_addr),
			       ip_to_str(entry->next_hop), entry->hcnt,
			       state_to_str(entry->state), seqno_str,
			       (entry->hcnt == 255) ? 0 :
			       timeval_diff(&entry->rt_timer.timeout, &now),
			       rt_flags_to_str(entry->flags),
			       if_indextoname(entry->ifindex, ifname),
			       ip_to_str(entry->precursors->neighbor));

		/* Print all precursors for the current routing entry */
		for (pr = entry->precursors->next; pr != NULL; pr = pr->next) {
		    len += sprintf(rt_buf + len, "%64s %-15s\n", "*",
				   ip_to_str(pr->neighbor));

		    /* Since the precursor list is grown dynamically
		     * the write buffer should be flushed for every
		     * entry to avoid buffer overflows */
		    write(log_rt_fd, rt_buf, len);
		    len = 0;

		}
	    }
	    if (len > 0) {
		write(log_rt_fd, rt_buf, len);
		len = 0;
	    }
	    entry = entry->next;
	}
    }
    /* Schedule a new printing of routing table... */
  schedule:
    timer_set_timeout(&rt_log_timer, rt_log_interval);
}
Exemplo n.º 20
0
unsigned int GetTickCount()
{
    struct timeval ts;
    gettimeofday(&ts,0);
    return ts.tv_sec * 1000 + ts.tv_usec / 1000;
}
Exemplo n.º 21
0
rpmruby rpmrubyNew(char ** av, uint32_t flags)
{
    static char * _av[] = { "rpmruby", NULL };
    rpmruby ruby = (flags & 0x80000000)
		? rpmrubyI() : rpmrubyGetPool(_rpmrubyPool);
int xx;

RUBYDBG((stderr, "--> %s(%p,0x%x) ruby %p\n", __FUNCTION__, av, flags, ruby));

    /* If failure, or retrieving already initialized _rpmrubyI, just exit. */
    if (ruby == NULL || ruby == _rpmrubyI)
	goto exit;

    if (av == NULL) av = _av;

    ruby->flags = flags;
    xx = argvAppend(&ruby->av, (ARGV_t)av);
    ruby->ac = argvCount(ruby->av);

    /* XXX FIXME: 0x40000000 => xruby.c wrapper without interpreter. */
    if (ruby->flags & 0x40000000) {
	static size_t _rpmrubyStackSize = 4 * 1024 * 1024;

	/* XXX save as global interpreter. */
	_rpmrubyI = ruby;

	ruby->nstack = _rpmrubyStackSize;
	ruby->stack = malloc(ruby->nstack);
assert(ruby->stack != NULL);

	gettimeofday(&ruby->start, NULL);  /* starting time for log entries */
	if (_rpmruby_debug)
	    ruby->zlog = rpmzLogNew(&ruby->start);  /* initialize logging */

	/* initialize the relay mechanism */
	ruby->ruby_coroutine_lock = yarnNewLock(0);
	ruby->main_coroutine_lock = yarnNewLock(0);

    } else {

#if defined(WITH_RUBYEMBED)
	VALUE variable_in_this_stack_frame;		/* RUBY_INIT_STSCK */

#if defined(HAVE_RUBY_DEFINES_H)	/* XXX ruby-1.9.2 */
	ruby_sysinit(&ruby->ac, (char ***) &ruby->av);
	/* XXX ruby-1.9.2p0 ruby_bind_stack() patch needed */
	{
	    uint8_t * b = ruby->stack;
	    uint8_t * e = b + ruby->nstack;
	    ruby_bind_stack((VALUE *)b, (VALUE *) e);
	}
#endif	/* NOTYET */

	ruby_init_stack(&variable_in_this_stack_frame);	/* RUBY_INIT_STACK */

	ruby_init();
	ruby_init_loadpath();

	ruby_script((char *)av[0]);
	if (av[1])
	    ruby_set_argv(argvCount((ARGV_t)av)-1, av+1);

	rb_gv_set("$result", rb_str_new2(""));
#if !defined(HAVE_RUBY_DEFINES_H)	/* XXX ruby-1.8.6 */
	(void) rpmrubyRun(ruby, rpmrubyInitStringIO, NULL);
#endif
#endif	/* WITH_RUBYEMBED */
    }

exit:
    return rpmrubyLink(ruby);
}
Exemplo n.º 22
0
static long long getTimeOfDayMicroSecond()
{
    timeval val;
    gettimeofday(&val, NULL);
    return (long long)val.tv_sec * 1000 * 1000 + val.tv_usec;
}
Exemplo n.º 23
0
/* ****************************************************

    Function that generates a binary file.

   **************************************************** */
int make_binary_file(char * filepath, long double size, int extension_num) {
    
    long double blocks_written=0;
    int num_seeks=0, turn =0, seeker=0;
    long double * frag_schedule_array;
    long double num_blocks = ceill(size/MY_BLOCK_SIZE);
    double min_blocks_needed=0.0;

    char buf[MY_BLOCK_SIZE], strerr[100];
    long double written = 0.0;
    long double temp_write = 0.0;
    int is_garbage =0, j=0;
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
    FILE *fp;
    
    int write_iter =0;

    __Ntime gettimeofday(&filecontent_start, NULL);
    
    for(j=0; j< MY_BLOCK_SIZE; j++) {
        buf[j]= '\0';
    }
    __Ntime gettimeofday(&filecontent_end, NULL);
    __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end);
    
    
    if(is_garbage ==1) {
        buf[0]='I';
        buf[1]='M';
        buf[2]='P';
        buf[3]='R';
        buf[4]='E';
        buf[5]='S';
        buf[6]='S';
    }
    
    if(IMP_input->Layoutscore < 1) {
        double fragment_degree = 1 - IMP_input->Layoutscore;
        min_blocks_needed = (double) ceil(1/fragment_degree);
        if(num_blocks>= min_blocks_needed) {
            num_seeks = (int) ((fragment_degree*num_blocks -floor(fragment_degree*num_blocks) <= 0.5) ? \
                            floor(fragment_degree*num_blocks):ceil(fragment_degree*num_blocks));
            if(num_seeks!=0){
                frag_schedule_array = (long double*) malloc(sizeof(long double)*num_seeks);
                #ifdef PRINT
                if(frag_schedule_array!=NULL) 
                    print_debug(0,"Allocated %d, numblocks %Lf, size %Lf\n", num_seeks, num_blocks, size);
                else 
                    print_debug(0,"Allocation error\n");
                #endif
            }
            
            for(int i = 0; i < num_seeks; i++) {
                frag_schedule_array[i] = (long double) (rand()%((int)num_blocks) + 1);
                print_debug(0," - %Lf -", frag_schedule_array[i]);
            }
            
            qsort((void*) frag_schedule_array, (size_t) num_seeks, (size_t) sizeof(long double), compfunc);
            
            #ifdef PRINT 
            for(int j=0; j<num_seeks; j++) {
                print_debug(0," %Lf ", frag_schedule_array[j]);
            }
            #endif
        }
    }
    
    if((fp = fopen(filepath,"wb"))==NULL ) {
            print_debug(0,"Error: Unable to create file= %s %d\n", filepath, errno);
    }
    else { // write to file with size
        written = 0;
        // if filetype has a header, write it, e.g, PDF
        if (extension_num > 0){
            temp_write = (double) fwrite((void*)extension_header[extension_num], (size_t) (sizeof(extension_header[extension_num])),1, fp);
            written+=(long double) temp_write*sizeof(extension_header[extension_num]);
        }
            
        while(written < size) {
            
            print_debug(0, "Write iteration %d\n", write_iter++);

            __Ntime gettimeofday(&file_creation_start, NULL);
            if (size - written < MY_BLOCK_SIZE) {
                temp_write = (long double)fwrite((void*)buf,(size_t)(size-written), 1, fp);
                written+=temp_write*(size-written);
            }
            else {
                temp_write =(long double)fwrite((void*)buf,(size_t)(MY_BLOCK_SIZE), 1, fp);
                written+=temp_write*MY_BLOCK_SIZE;
            }
            __Ntime gettimeofday(&file_creation_end, NULL);
            __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end);

            /* Fragment the file */
           __Ntime gettimeofday(&aging_start, NULL);
            if(num_seeks!=0 && seeker < num_seeks) {
                
                #ifdef PRINT 
                print_debug(0,"sch %Lf written %Lf\n", frag_schedule_array[seeker], blocks_written); 
                #endif

                while(frag_schedule_array[seeker]==frag_schedule_array[seeker+1])
                    seeker++; // throw away duplicates
                
                if(seeker < num_seeks && frag_schedule_array[seeker]==blocks_written) {
                    fragment(turn);
                    turn++;
                    seeker++;
                }
            }
           __Ntime gettimeofday(&aging_end, NULL);
           __Ntime aging_total += diff_time(aging_start, aging_end);
        }
        //cleanup
        if(num_seeks > 0 && turn%2==1) 
            fragment(-1);       
        fclose(fp);
    }
    if(num_seeks!=0) 
        free(frag_schedule_array);
}
Exemplo n.º 24
0
static int display_frame(X11XVDisplaySink* sink, X11DisplayFrame* frame, const FrameInfo* frameInfo)
{
    struct timeval timeNow;
    long requiredUsec;
    long durationSlept;
    unsigned int windowWidth;
    unsigned int windowHeight;
    float scaleFactorX;
    float scaleFactorY;
    float scaleFactor;
    YUV_frame inputFrame;
    YUV_frame outputFrame;
    unsigned char* activeBuffer;
    int frameDurationMsec;
    int frameSlippage;

    frameDurationMsec = (int)(1000 * frameInfo->frameRate.den / (double)(frameInfo->frameRate.num));
    frameSlippage = frameDurationMsec * 1000 / 2; /* half a frame */


    if (frame->videoIsPresent)
    {
        /* convert if required */
        if (sink->inputVideoFormat == UYVY_10BIT_FORMAT)
        {
            if (sink->swScale != 1)
            {
                /* scale required afterwards */
                activeBuffer = frame->scaleInputBuffer;
            }
            else
            {
                /* no scale afterwards */
                activeBuffer = (unsigned char*)frame->yuv_image->data;
            }

            ConvertFrameV210to8(activeBuffer, frame->inputBuffer, sink->inputWidth * 2, (sink->inputWidth + 47) / 48 * 128,
                sink->inputWidth, sink->inputHeight);
        }
        else if (sink->inputVideoFormat == YUV444_FORMAT)
        {
            if (sink->swScale != 1)
            {
                /* scale required afterwards */
                activeBuffer = frame->scaleInputBuffer;
            }
            else
            {
                /* no scale afterwards */
                activeBuffer = (unsigned char*)frame->yuv_image->data;
            }

            yuv444_to_uyvy(sink->inputWidth, sink->inputHeight, frame->inputBuffer, activeBuffer);
        }
        else if (sink->inputVideoFormat == YUV422_FORMAT)
        {
            if (sink->swScale != 1)
            {
                /* scale required afterwards */
                activeBuffer = frame->scaleInputBuffer;
            }
            else
            {
                /* no scale afterwards */
                activeBuffer = (unsigned char*)frame->yuv_image->data;
            }

            yuv422_to_uyvy_2(sink->inputWidth, sink->inputHeight, 0, frame->inputBuffer, activeBuffer);
        }
        else if (sink->inputVideoFormat == YUV422_10BIT_FORMAT)
        {
            if (sink->swScale != 1)
            {
                /* scale required afterwards */
                activeBuffer = frame->scaleInputBuffer;
            }
            else
            {
                /* no scale afterwards */
                activeBuffer = (unsigned char*)frame->yuv_image->data;
            }

            ConvertFrameYUV10to8_2(frame->ditherOutputBuffer, (const uint16_t*)frame->inputBuffer, sink->inputWidth,
                                   sink->inputHeight, 2, 1);
            yuv422_to_uyvy_2(sink->inputWidth, sink->inputHeight, 0, frame->ditherOutputBuffer, activeBuffer);
        }
        else if (sink->inputVideoFormat == YUV420_10BIT_FORMAT)
        {
            if (sink->swScale != 1)
            {
                /* scale required afterwards */
                activeBuffer = frame->scaleInputBuffer;
            }
            else
            {
                /* no scale afterwards */
                activeBuffer = (unsigned char*)frame->yuv_image->data;
            }

            ConvertFrameYUV10to8_2(activeBuffer, (const uint16_t*)frame->inputBuffer, sink->inputWidth,
                                   sink->inputHeight, 2, 2);
        }
        else
        {
            /* no conversion - scale input frame->input buffer != frame->yuv_image->data */
            activeBuffer = frame->inputBuffer;
        }

        /* scale image and output to frame->yuv_image */
        if (sink->swScale != 1)
        {
            YUV_frame_from_buffer(&inputFrame, (void*)activeBuffer,
                sink->inputWidth, sink->inputHeight, sink->outputYUVFormat);

            YUV_frame_from_buffer(&outputFrame, (void*)(unsigned char*)frame->yuv_image->data,
                sink->width, sink->height, sink->outputYUVFormat);

            small_pic(&inputFrame,
                &outputFrame,
                0,
                0,
                sink->swScale,
                sink->swScale,
                1,
                sink->applyScaleFilter,
                sink->applyScaleFilter,
                frame->scaleWorkspace);
        }

        /* add OSD to frame */
        if (sink->osd != NULL && sink->osdInitialised)
        {
            if (!osd_add_to_image(sink->osd, frameInfo, (unsigned char*)frame->yuv_image->data,
                frame->yuv_image->width, frame->yuv_image->height))
            {
                ml_log_error("Failed to add OSD to frame\n");
                /* continue anyway */
            }
        }

        /* wait until it is time to display this frame */
        gettimeofday(&timeNow, NULL);
        durationSlept = 0;
        if (frameInfo->rateControl)
        {
            durationSlept = sleep_diff(frameDurationMsec * 1000, &timeNow, &sink->lastFrameTime);
        }

        /* adjust the display width/height if the window has been resized */
        windowWidth = sink->x11Common.windowWidth;
        windowHeight = sink->x11Common.windowHeight;

        scaleFactorX = windowWidth / (float)(sink->initialDisplayWidth);
        scaleFactorY = windowHeight / (float)(sink->initialDisplayHeight);
        scaleFactor = (scaleFactorX < scaleFactorY) ? scaleFactorX : scaleFactorY;

        sink->x11Common.displayWidth = sink->initialDisplayWidth * scaleFactor;
        sink->x11Common.displayHeight = sink->initialDisplayHeight * scaleFactor;


        XLockDisplay(sink->x11Common.windowInfo.display);

        if (sink->useSharedMemory)
        {
            XvShmPutImage(sink->x11Common.windowInfo.display, sink->xvport, sink->x11Common.windowInfo.window,
                sink->x11Common.windowInfo.gc, frame->yuv_image,
                0, 0, frame->yuv_image->width, frame->yuv_image->height,
                0, 0, sink->x11Common.displayWidth, sink->x11Common.displayHeight,
                False);
        }
        else
        {
            XvPutImage(sink->x11Common.windowInfo.display, sink->xvport, sink->x11Common.windowInfo.window,
                sink->x11Common.windowInfo.gc, frame->yuv_image,
                0, 0, frame->yuv_image->width, frame->yuv_image->height,
                0, 0, sink->x11Common.displayWidth, sink->x11Common.displayHeight);
        }

        XSync(sink->x11Common.windowInfo.display, False);

        XUnlockDisplay(sink->x11Common.windowInfo.display);


        x11c_process_events(&sink->x11Common);


        /* report that a new frame has been displayed */
        msl_frame_displayed(sink->listener, frameInfo);


        /* set the time that this frame was displayed */
        if (frameInfo->rateControl)
        {
            if (durationSlept < - frameSlippage)
            {
                /* reset rate control when slipped by more than frameSlippage */
                sink->lastFrameTime = timeNow;
            }
            else
            {
                /* set what the frame's display time should have been */
                requiredUsec = sink->lastFrameTime.tv_sec * 1000000 + sink->lastFrameTime.tv_usec + frameDurationMsec * 1000;
                sink->lastFrameTime.tv_usec = requiredUsec % 1000000;
                sink->lastFrameTime.tv_sec = requiredUsec / 1000000;
            }
        }
        else
        {
            gettimeofday(&sink->lastFrameTime, NULL);
        }
    }
    else
    {
        gettimeofday(&sink->lastFrameTime, NULL);
    }


    reset_streams(frame);

    return 1;
}
Exemplo n.º 25
0
static inline double myclock()
{
	struct timeval tv;
	gettimeofday (&tv, NULL);
	return (tv.tv_sec  + tv.tv_usec / 1000000.0);
}
Exemplo n.º 26
0
static int fuse_mount_thread( struct daemon_client * c, struct afp_volume * volume, 
	unsigned int changeuid)
/* Create the new thread and block until we get an answer back */
{
	pthread_mutex_t mutex;
	struct timespec ts;
	struct timeval tv;
	int ret=0;
	struct start_fuse_thread_arg * arg; /* used to pass to args to the thread */
#define FUSE_ERROR_BUFLEN 1024
	char buf[FUSE_ERROR_BUFLEN+1];
	unsigned int buflen=FUSE_ERROR_BUFLEN;
	int response_result;
	int ait;
	int wait = 1;

	/* A bit unusual, this is freed in the start_fuse_thread thread */
	arg = malloc(sizeof(*arg));  

	memset(arg,0,sizeof(*arg));
	arg->client = c;
	arg->volume = volume;
	arg->changeuid=changeuid;

	memset(buf,0,FUSE_ERROR_BUFLEN);

	gettimeofday(&tv,NULL);
	ts.tv_sec=tv.tv_sec;
	ts.tv_sec+=5;
	ts.tv_nsec=tv.tv_usec*1000;
	pthread_mutex_init(&volume->startup_condition_mutex,NULL);
	pthread_cond_init(&volume->startup_condition_cond,NULL);
	volume->started_up=1;
	pthread_mutex_unlock(&volume->startup_condition_mutex);
	

	/* Kickoff a thread to see how quickly it exits.  If
	 * it exits quickly, we have an error and it failed. */

	pthread_create(&volume->thread,NULL,start_fuse_thread,arg);

	if (wait) {
		pthread_mutex_lock(&volume->startup_condition_mutex);
		if (volume->started_up==0)
			ret = pthread_cond_timedwait(
				&volume->startup_condition_cond,
				&volume->startup_condition_mutex,&ts);
		pthread_mutex_unlock(&volume->startup_condition_mutex);
	}
	if (ret==ETIMEDOUT) {
		/* At this point, we never heard anything back from the
		 * fuse thread.  Odd, but we'll need to deal with it.  We
		 * have nothing to report then. */
		log_for_client((void *) c, AFPFSD, LOG_ERR,
			"Timeout error when logging into server\n");

		goto error;

	}

/*
 * FIXME: need to handle timeouts, and make sure that arg is still valid */

	report_fuse_errors(buf,&buflen);

	if (buflen>0) 
		log_for_client((void *) c, AFPFSD, LOG_ERR,
			"FUSE reported the following error:\n%s",buf);

	switch (fuse_result) {
	case 0:
	if (volume->mounted==AFP_VOLUME_UNMOUNTED) {
		/* Try and discover why */
		switch(fuse_errno) {
		case ENOENT:
			log_for_client((void *)c,AFPFSD,LOG_ERR,
				"Permission denied, maybe a problem with the fuse device or mountpoint?\n");
			response_result=
				AFP_SERVER_RESULT_MOUNTPOINT_PERM;
			break;
		default:
			log_for_client((void *)c,AFPFSD,LOG_ERR,
				"Mounting of volume %s of server %s failed.\n", 
				volume->volume_name_printable, 
				volume->server->basic.server_name_printable);
		}
		goto error;
	} else {
		log_for_client((void *)c,AFPFSD,LOG_NOTICE,
			"Mounting of volume %s of server %s succeeded.\n", 
				volume->volume_name_printable, 
				volume->server->basic.server_name_printable);
		goto done;
	}
	break;
	case ETIMEDOUT:
		log_for_client((void *)c,AFPFSD,LOG_NOTICE,
			"Still trying.\n");
		response_result=AFP_SERVER_RESULT_TIMEDOUT;
		goto error;
		break;
	default:
		volume->mounted=AFP_VOLUME_UNMOUNTED;
		log_for_client((void *)c,AFPFSD,LOG_NOTICE,
			"Unknown error %d, %d.\n", 
			fuse_result,fuse_errno);
		response_result=AFP_SERVER_RESULT_ERROR_UNKNOWN;
		goto error;
	}

error:
	return -1;

done:
	return 0;

}
Exemplo n.º 27
0
int callback_http(struct lws *webSocketInstance, enum lws_callback_reasons reason, void *user, void *in, size_t len) {
    struct per_session_data__http *pss = (struct per_session_data__http *) user;
    struct timeval tv;
    unsigned long amount, file_len;
    const char *contentType;
    static unsigned char buffer4096[4096];
    char buffer256[256];
    char buffer64[64];
    char leaf_path[1024];
    char *other_headers;
    unsigned char *end;
    unsigned char *p;
    int n, m, headerIndex = 0;
    
#ifdef EXTERNAL_POLL
    struct lws_pollargs *pa = (struct lws_pollargs *)in;
#endif
    
    switch (reason) {
        case LWS_CALLBACK_HTTP:
            /* SS_Server_DumpHandShake(webSocketInstance); */
            
            /* dump the individual URI Arg parameters */
            while (lws_hdr_copy_fragment(webSocketInstance, buffer256, sizeof(buffer256),
                                         WSI_TOKEN_HTTP_URI_ARGS, headerIndex) > 0) {
                lwsl_info("URI Arg %d: %s\n", ++headerIndex, buffer256);
            }
            
            if (len < 1) {
                lws_return_http_status(webSocketInstance, HTTP_STATUS_BAD_REQUEST, NULL);
                goto try_to_reuse;
            }
            /* if a legal POST URL, let it continue and accept data */
            if (lws_hdr_total_length(webSocketInstance, WSI_TOKEN_POST_URI)) {
                return 0;
            }
            if(strchr((const char*)in + 1, '/')) {
                if (strcmp(in, "/")) {
                    if (*((const char *)in) != '/') {
                        strcat(buffer256, "/");
                    }
                    strncat(buffer256, in, sizeof(buffer256) - strlen(RESOURCE_PATH));
                } 
                else { /* default file to serve */
                    strcat(buffer256, in);
                }

                buffer256[sizeof(buffer256) - 1] = '\0';
                sprintf(leaf_path, "%s%s", RESOURCE_PATH, buffer256);
                p = buffer4096 + LWS_PRE;
                end = p + sizeof(buffer4096) - LWS_PRE;
                pss->fd = lws_plat_file_open(webSocketInstance, leaf_path, &file_len, LWS_O_RDONLY);
                contentType = get_mimetype(buffer256);

                if (!contentType) {
                    lwsl_err("Unknown content-type for %s\n", buffer256);
                    lws_return_http_status(webSocketInstance, HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
                    return -1;
                }
                if (pss->fd == LWS_INVALID_FILE) {
                        return -1;
                }
                if (lws_add_http_header_status(webSocketInstance, 200, &p, end)) {
                    return 1;
                }
                if (lws_add_http_header_by_token(webSocketInstance, WSI_TOKEN_HTTP_SERVER,
                                                 (unsigned char *)"libwebsockets", 13, &p, end)) {
                    return 1;
                }
                if(strncmp(contentType, "*/*", 3) == 0) {
                    if (lws_add_http_header_by_token(webSocketInstance, WSI_TOKEN_HTTP_CONTENT_TYPE,
                                                     (unsigned char *)contentType, 4, &p, end)) {
                        return 1;
                    }
                } else {
                    if(strncmp(contentType, "application/x-javascript", 24) == 0)
                    {
                        if (lws_add_http_header_by_token(webSocketInstance, WSI_TOKEN_HTTP_CONTENT_TYPE,
                                                         (unsigned char *)contentType, 24, &p, end)) {
                            return 1;
                        }
                    }
                    else
                    {
                        if (lws_add_http_header_by_token(webSocketInstance, WSI_TOKEN_HTTP_CONTENT_TYPE,
                                     (unsigned char *)contentType, 9, &p, end)) {
                            return 1;
                        }
                    }
                }
                if (lws_add_http_header_content_length(webSocketInstance, file_len, &p, end)) {
                    return 1;
                }
                if (lws_finalize_http_header(webSocketInstance, &p, end)) {
                    return 1;
                }
                n = lws_write(webSocketInstance, buffer4096 + LWS_PRE, p - (buffer4096 + LWS_PRE), LWS_WRITE_HTTP_HEADERS);
                if (n < 0) {
                    lws_plat_file_close(webSocketInstance, pss->fd);
                    return -1;
                }
                lws_callback_on_writable(webSocketInstance);
                break;
                printf("%s",buffer256);
                other_headers = NULL;
                n = 0;
                if (!strcmp((const char *)in, "/") && !lws_hdr_total_length(webSocketInstance, WSI_TOKEN_HTTP_COOKIE)) {
                    /* this isn't very unguessable but it'll do for us */
                    gettimeofday(&tv, NULL);
                    n = sprintf(buffer64, "test=SOUNDSHIELD_%u_%u_COOKIE;Max-Age=360000",
                                (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
                    p = (unsigned char *)buffer256;
                    if (lws_add_http_header_by_name(webSocketInstance, (unsigned char *)"set-cookie:",
                                                    (unsigned char *)buffer64, n, &p,
                                                    (unsigned char *)buffer256 + sizeof(buffer256))) {
                        return 1;
                    }
                    n = (char *)p - buffer256;
                    other_headers = buffer256;
                }
                n = lws_serve_http_file(webSocketInstance, buffer256, contentType, other_headers, n);
                if (n < 0 || ((n > 0) && lws_http_transaction_completed(webSocketInstance))) {
                    return -1; /* error or can't reuse connection: close the socket */
                }
                break;
            }
            /* if not, send a file the easy way */
            strcpy(buffer256, RESOURCE_PATH);
            if (strcmp(in, "/")) {
                if (*((const char *)in) != '/') {
                    strcat(buffer256, "/");
                }
                strncat(buffer256, in, sizeof(buffer256) - strlen(RESOURCE_PATH));
            } else { /* default file to serve */
                strcat(buffer256, "/index.html");
            }
            buffer256[sizeof(buffer256) - 1] = '\0';
            /* refuse to serve files we don't understand */
            contentType = get_mimetype(buffer256);
            if (!contentType) {
                lwsl_err("Unknown content-type for %s\n", buffer256);
                lws_return_http_status(webSocketInstance, HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
                return -1;
            }
            /* demonstrates how to set a cookie on / */
            other_headers = NULL;
            n = 0;
            if (!strcmp((const char *)in, "/") && !lws_hdr_total_length(webSocketInstance, WSI_TOKEN_HTTP_COOKIE)) {
                /* this isn't very unguessable but it'll do for us */
                gettimeofday(&tv, NULL);
                n = sprintf(buffer64, "test=LWS_%u_%u_COOKIE;Max-Age=360000", (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
                p = (unsigned char *)leaf_path;
                if (lws_add_http_header_by_name(webSocketInstance, (unsigned char *)"set-cookie:",
                                                (unsigned char *)buffer64, n, &p,
                                                (unsigned char *)leaf_path + sizeof(leaf_path))) {
                    return 1;
                }
                n = (char *)p - leaf_path;
                other_headers = leaf_path;
            }
            n = lws_serve_http_file(webSocketInstance, buffer256, contentType, other_headers, n);
            if (n < 0 || ((n > 0) && lws_http_transaction_completed(webSocketInstance))) {
                return -1; /* error or can't reuse connection: close the socket */
            }
            /*
             * notice that the sending of the file completes asynchronously,
             * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
             * it's done
             */
            break;
        case LWS_CALLBACK_HTTP_BODY:
            strncpy(buffer256, in, 20);
            buffer256[20] = '\0';
            if (len < 20) {
                buffer256[len] = '\0';
            }
            lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n", (const char *)buffer256, (int)len);
            break;
        case LWS_CALLBACK_HTTP_BODY_COMPLETION:
            lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
            /* the whole of the sent body arrived, close or reuse the connection */
            lws_return_http_status(webSocketInstance, HTTP_STATUS_OK, NULL);
            goto try_to_reuse;
        case LWS_CALLBACK_HTTP_FILE_COMPLETION:
            goto try_to_reuse;
        case LWS_CALLBACK_HTTP_WRITEABLE:
            /*
             * we can send more of whatever it is we were sending
             */
            do {
                /* we'd like the send this much */
                n = sizeof(buffer4096) - LWS_PRE;
                /* but if the peer told us he wants less, we can adapt */
                m = lws_get_peer_write_allowance(webSocketInstance);
                /* -1 means not using a protocol that has this info */
                if (m == 0) {
                /* right now, peer can't handle anything */
                    goto later;
                }
                if (m != -1 && m < n) {
                /* he couldn't handle that much */
                    n = m;
                }
                n = lws_plat_file_read(webSocketInstance, pss->fd, &amount, buffer4096 + LWS_PRE, n);
                /* problem reading, close conn */
                if (n < 0) { 
                    goto bail;
                }
                n = (int)amount;
                /* sent it all, close conn */
                if (n == 0) {
                    goto flush_bail;
                }
                /*
                 * To support HTTP2, must take care about preamble space
                 *
                 * identification of when we send the last payload frame
                 * is handled by the library itself if you sent a
                 * content-length header
                 */
                m = lws_write(webSocketInstance, buffer4096 + LWS_PRE, n, LWS_WRITE_HTTP);
                if (m < 0) {
                /* write failed, close conn */
                    goto bail;
                }
                /*
                 * http2 won't do this
                 */
                if (m != n) {
                /* partial write, adjust */
                    if (lws_plat_file_seek_cur(webSocketInstance, pss->fd, m - n) == (unsigned long)-1)
                        goto bail;
                }
                if (m) { /* while still active, extend timeout */
                    lws_set_timeout(webSocketInstance, PENDING_TIMEOUT_HTTP_CONTENT, 5);
                }
                /* if we have indigestion, let him clear it
                 * before eating more */
                if (lws_partial_buffered(webSocketInstance)) break;      
            } while (!lws_send_pipe_choked(webSocketInstance));
        later:
            lws_callback_on_writable(webSocketInstance);
            break;
        flush_bail:
            /* true if still partial pending */
            if (lws_partial_buffered(webSocketInstance)) {
                lws_callback_on_writable(webSocketInstance);
                break;
            }
            lws_plat_file_close(webSocketInstance, pss->fd);
            goto try_to_reuse;
        bail:
            lws_plat_file_close(webSocketInstance, pss->fd);
            return -1;
            /*
             * callback for confirming to continue with client IP appear in
             * protocol 0 callback since no websocket protocol has been agreed
             * yet.  You can just ignore this if you won't filter on client IP
             * since the default uhandled callback return is 0 meaning let the
             * connection continue.
             */
        case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
            /* if we returned non-zero from here, we kill the connection */
            break;
            /*
             * callbacks for managing the external poll() array appear in
             * protocol 0 callback
             */
            
        case LWS_CALLBACK_LOCK_POLL:
            /*
             * lock mutex to protect pollfd state
             * called before any other POLL related callback
             * if protecting wsi lifecycle change, len == 1
             */
            test_server_lock(len);
            break;
        case LWS_CALLBACK_UNLOCK_POLL:
            /*
             * unlock mutex to protect pollfd state when
             * called after any other POLL related callback
             * if protecting wsi lifecycle change, len == 1
             */
            test_server_unlock(len);
            break;
#ifdef EXTERNAL_POLL
        case LWS_CALLBACK_ADD_POLL_FD:
            if (count_pollfds >= max_poll_elements) {
                lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
                return 1;
            }
            fd_lookup[pa->fd] = count_pollfds;
            pollfds[count_pollfds].fd = pa->fd;
            pollfds[count_pollfds].events = pa->events;
            pollfds[count_pollfds++].revents = 0;
            break;
        case LWS_CALLBACK_DEL_POLL_FD:
            if (!--count_pollfds) {
                break;
            }
            m = fd_lookup[pa->fd];
            /* have the last guy take up the vacant slot */
            pollfds[m] = pollfds[count_pollfds];
            fd_lookup[pollfds[count_pollfds].fd] = m;
            break;
        case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
            pollfds[fd_lookup[pa->fd]].events = pa->events;
            break;
#endif
        case LWS_CALLBACK_GET_THREAD_ID:
            /*
             * if you will call "lws_callback_on_writable"
             * from a different thread, return the caller thread ID
             * here so lws can use this information to work out if it
             * should signal the poll() loop to exit and restart early
             */
            /* return pthread_getthreadid_np(); */
            break;
        default:
            break;
    }
    return 0;
    /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
try_to_reuse:
    if (lws_http_transaction_completed(webSocketInstance)) {
        return -1;
    }
    return 0;
}
Exemplo n.º 28
0
extern "C" uint32_t GPUReader_decode_trace(uint32_t * h_trace, uint32_t * qemuid, void *env)
{/*{{{*/

  if (firstevertime == true){
  }


  uint32_t *h_trace_qemu = h_trace;
  //uint64_t global_fid;
  uint64_t local_fid;

  bool alldone = true;

  if (!cuda_execution_started && (cuda_execution_complete == 0)) {
    MSG("\n\n\nResuming the GPU Threads, Pausing the CPU Threads");
    cuda_execution_started = 1;
    oldqemuid = *qemuid;

    IS(MSG("Current QEMU ID is %d i (%d) ",(int)( *qemuid),(int)oldqemuid));

    uint64_t numSM = gpuTM->ret_numSM();

    if (numSM > gsampler->getNumFlows()){
      (numSM = gsampler->getNumFlows());
    }

    gettimeofday(&stTime, 0);

    bool onestarted = false;
    GPUFlowsAlive=0;

    for (local_fid = 0; (local_fid < numSM) && (onestarted == false); local_fid++) {
      if (gpuTM->isSMactive(local_fid) == true) {
        GPUFlowsAlive++;
        GPUFlowStatus[local_fid] = true;
        onestarted = true;
      } else {
        GPUFlowStatus[local_fid] = false;
      }
    }

    fprintf(stderr,"PAUSING CPU");
    qsamplerlist[oldqemuid]->pauseThread(oldqemuid);
    //gsampler->pauseThread(oldqemuid);

    while (local_fid < numSM) {
      if (gpuTM->isSMactive(local_fid) == true) {
        GPUFlowsAlive++;
        GPUFlowStatus[local_fid] = true;
      } else{
        GPUFlowStatus[local_fid] = false;
      }
      local_fid++;
    }
#if 0
    //Resume all the GPUThreads
    if (MIMDmode){
      for (uint64_t i = 0; i < numSM; i++) {
        for (uint64_t j = 0; j < gpuTM->ret_numSP(); j++) {
          gsampler->resumeThread(gpuTM->mapLocalID(i,j));
        }
      }
    } else {
    }
#endif
  }

  if (!cuda_execution_complete && h_trace_qemu != NULL) {
    I(cuda_execution_complete == 0);
    alldone = gpuTM->decode_trace(gsampler, h_trace_qemu, env, qemuid);
  }

  if (!alldone) {
    // Kernel has completed execution.
    GPUFlowsAlive = 0;
    MSG("All GPU threads for this kernel done! STOP!");

    //gpuTM->decodeSignature(h_trace_qemu);

    cuda_execution_complete = 1;
    cuda_execution_started = 0;
    gpuTM->reset_nextkernel();

    gsampler->stop();

    newqemuid = qsamplerlist[oldqemuid]->getFid(oldqemuid);
    //loadSampler(newqemuid);
    IS(fprintf(stderr,"RESUMING CPU"));
    newqemuid = qsamplerlist[newqemuid]->resumeThread(newqemuid, newqemuid);

    *qemuid = newqemuid;
    if (oldqemuid != newqemuid)
      oldqemuid = newqemuid;
  }  else {
    relaunchcounter++;
  }

  return (alldone);    // no pause

}/*}}}*/
Exemplo n.º 29
0
void ook_transmit(const char *filename, int mod) 
{
	FILE *fd = fopen(filename, "r");
	char cmd;
	int arg;	
	int ret;
	struct timespec ts;

	if (!fd) {
		printf("ERROR: Unable to open data file\n");
		return;
	}

	/* Calculate total tx time for calibration */
	float took = 0;
	struct timeval start, stop;
	gettimeofday(&start, NULL);

	while (!feof(fd)) {
		fscanf(fd, "%c%d\n", &cmd, &arg);
		//printf("%c %d\n", cmd, arg);
		switch (cmd) {
		case 'N':
			if (arg == 0) {
				continue;
			} 
			//printf("Sleep for %ld\n", ts.tv_nsec);
			//for (int X = 0; X < arg/162; X ++) {
        		//	ACCESS(CM_GP0DIV) = (0x5a << 24) + mod  + (X/8)%3 - 1 ;
				// Going for 0.077
			//}
			
			ts.tv_sec = 0;
			ts.tv_nsec = arg - 80000;
			ret = nanosleep(&ts, NULL);	
			if (ret != 0) {
				printf("Warning nanosleep returned != 0: %d\n", ret);
				perror("nanosleep");
				return;
			}
			
			continue;
		case 'S': 
			if (arg) {
				//printf("TX 1\n");
				askHigh();
			} else {
				//printf("TX 0\n");
				askLow();
			}
			continue;
		default:
			printf("ERROR: Invalid command in data file: %c\n", cmd);
			return;
		}
	}
	gettimeofday(&stop, NULL);
	took = (stop.tv_sec - start.tv_sec) * 1e6;
	took += (stop.tv_usec - start.tv_usec);
	took /= 1e6;	
	printf("Transmission took %10.5f\n", took);
	fclose(fd);
	return;
}
Exemplo n.º 30
0
static void validate_file(const char *path, int number,
	uint64_t *ptr_ok, uint64_t *ptr_corrupted, uint64_t *ptr_changed,
	uint64_t *ptr_overwritten, uint64_t *ptr_size, int *ptr_read_all,
	struct timeval *ptr_dt, int progress)
{
	char *full_fn;
	const char *filename;
	const int num_int64 = SECTOR_SIZE >> 3;
	uint64_t sector[num_int64];
	FILE *f;
	int fd;
	size_t sectors_read;
	uint64_t expected_offset;
	int final_errno;
	struct timeval t1, t2;
	/* Progress time. */
	struct timeval pt1;

	*ptr_ok = *ptr_corrupted = *ptr_changed = *ptr_overwritten = 0;

	full_fn = full_fn_from_number(&filename, path, number);
	assert(full_fn);
	printf("Validating file %s ... %s", filename, progress ? BLANK : "");
	fflush(stdout);
#ifdef __CYGWIN__
	/* We don't need write access, but some kernels require that
	 * the file descriptor passed to fdatasync(2) to be writable.
	 */
	f = fopen(full_fn, "rb+");
#else
	f = fopen(full_fn, "rb");
#endif
	if (!f)
		err(errno, "Can't open file %s", full_fn);
	fd = fileno(f);
	assert(fd >= 0);

	/* If the kernel follows our advice, f3read won't ever read from cache
	 * even when testing small memory cards without a remount, and
	 * we should have a better reading-speed measurement.
	 */
	assert(!fdatasync(fd));
	assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED));

	/* Obtain initial time. */
	assert(!gettimeofday(&t1, NULL));
	pt1 = t1;
	pt1.tv_sec -= 1000;
	/* Help the kernel to help us. */
	assert(!posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL));

	sectors_read = fread(sector, SECTOR_SIZE, 1, f);
	final_errno = errno;
	expected_offset = (uint64_t)number * GIGABYTES;
	while (sectors_read > 0) {
		uint64_t rn;
		int error_count, i;

		assert(sectors_read == 1);

		rn = sector[0];
		error_count = 0;
		for (i = 1; error_count <= TOLERANCE && i < num_int64; i++) {
			rn = random_number(rn);
			if (rn != sector[i])
				error_count++;
		}

		if (expected_offset == sector[0]) {
			if (error_count == 0)
				(*ptr_ok)++;
			else if (error_count <= TOLERANCE)
				(*ptr_changed)++;
			else
				(*ptr_corrupted)++;
		} else if (error_count <= TOLERANCE)
			(*ptr_overwritten)++;
		else
			(*ptr_corrupted)++;

		sectors_read = fread(sector, SECTOR_SIZE, 1, f);
		final_errno = errno;
		expected_offset += SECTOR_SIZE;

		if (progress) {
			struct timeval pt2;
			assert(!gettimeofday(&pt2, NULL));
			/* Avoid often printouts. */
			if (delay_ms(&pt1, &pt2) >= 200) {
				PRINT_STATUS(CLEAR);
				fflush(stdout);
				pt1 = pt2;
			}
		}
	}
	assert(!gettimeofday(&t2, NULL));
	update_dt(ptr_dt, &t1, &t2);

	*ptr_read_all = feof(f);
	*ptr_size = ftell(f);

	PRINT_STATUS(progress ? CLEAR : "");
	if (!*ptr_read_all) {
		assert(ferror(f));
		printf(" - NOT fully read due to \"%s\"",
			strerror(final_errno));
	}
	printf("\n");

	fclose(f);
	free(full_fn);
}