int main() {
  // Example 1 [-1,1]
  a = -1.0;
  b = 1.0;
  n = 1000;
  int curr_num_threads[3] = {2, 50, 100};
  for (int i=0; i<3; i++)
  {
    approx = 0;
    thread_count = curr_num_threads[i];
    printf("\nRun with %d threads\n", thread_count);
    timerStart();
    run_threads();
    printf("Took %ld ms\n", timerStop());
    printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }

  // Example 2 [0,10]
  a = 0.0;
  b = 10.0;
  n = 1000;
  for (int i=0; i<3; i++)
  {
    approx = 0;
    thread_count = curr_num_threads[i];
    printf("\nRun with %d threads\n", thread_count);
    timerStart();
    run_threads();
    printf("Took %ld ms\n", timerStop());
    printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, ZERO_TO_POS_10, approx);
  }

  return 0;
}
示例#2
0
int 
main(int argc, char**argv)
{	
  // Scan options.
  char **args = &argv[1];
  while (*args)
  {
    char *opt = NULL;

    if ((opt = shift_option(&args, "--test_num=")))
      g_run_multiplier = atoi(opt);
  }

  printf("This test will run %d times.\n",
         ((1 << LG2_CAPACITY) * g_run_multiplier));
  
  // Make sure we have enough cpus.
  // if (tmc_cpus_get_dataplane_cpus(&cpus) != 0)
  if (tmc_cpus_get_my_affinity(&cpus) != 0)
    tmc_task_die("tmc_cpus_get_my_affinity() failed.");
  if (tmc_cpus_count(&cpus) < NUM_THREADS)
    tmc_task_die("Insufficient cpus available.");
    
  // Call the main thread function on each cpu, then wait for them all
  // to exit.
  run_threads(NUM_THREADS, thread_func);
  finish_threads(NUM_THREADS);
  
  return 0;
}
示例#3
0
int
main(void)
{
	char sfn[24];
	FILE *sfp;
	int fd, i;

	strlcpy(sfn, "/tmp/barnacles.XXXXXXXX", sizeof(sfn));
	if ((fd = mkstemp(sfn)) == -1 ||
	    (sfp = fdopen(fd, "w+")) == NULL) {
		int saved_errno = errno;
		if (fd != -1) {
			unlink(sfn);
			close(fd);
		}
		errc(1, saved_errno, "could not open temporary file");
	}

	for (i = 0; i < 4096 * THREAD_COUNT; i++)
		if (fwrite(TEXT_N, sizeof(char), strlen(TEXT_N), sfp) == 0)
			err(1, "Could not populate test file");

	run_threads(fgetln_thread, sfp);

	unlink(sfn);
	close(fd);

	exit(0);
}
示例#4
0
int
main(void)
{
	char sfn[24];
	char buf[sizeof(TEXT)];
	FILE *sfp;
	int fd;

	strlcpy(sfn, "/tmp/barnacles.XXXXXXXX", sizeof(sfn));
	if ((fd = mkstemp(sfn)) == -1 ||
	    (sfp = fdopen(fd, "w+")) == NULL) {
		int saved_errno = errno;
		if (fd != -1) {
			unlink(sfn);
			close(fd);
		}
		errc(1, saved_errno, "could not open temporary file");
	}

	run_threads(fwrite_thread, sfp);

	while (fread(buf, sizeof(char), strlen(TEXT), sfp))	/* verify */
		if (strncmp(buf, TEXT, sizeof(TEXT)))
			err(1, "Thread writes were not atomic!!!");

	unlink(sfn);
	close(fd);

	exit(0);
}
int main() {
  // Example 1 [-1,1]
  a = -1.0;
  b = 1.0;
  n = 1000000000;
  int current_number_of_threads[3] = {2, 50, 100};
  pthread_mutex_init(&approx_lock,NULL);
  
  int i = 0;
  for (i = 0; i<3; i++) {
     approx = 0;
     thread_amount = current_number_of_threadsi[i];
     printf("\nRan with %d threads\n", thread_amount);
     
     timerStart();
     run_threads();
     
     printf("Took %ld ms\n", timerStop());
     printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }
  
  
  // Example 2 [0,10]
  a = 0.0;
  b = 10.0;
  n = 1000000000;
  int i = 0;
  for (i = 0; i<3; i++) {
     approx = 0;
     thread_amount = current_number_of_threadsi[i];
     printf("\nRan with %d threads\n", thread_amount);
     
     timerStart();
     run_threads();
     
     printf("Took %ld ms\n", timerStop());
     printf("a:%f\t b:%f\t n:%d\t actual:%f\t approximation:%f\n", a, b, n, NEG_1_TO_POS_1, approx);
  }
  pthread_mutex_destroy(&approx_lock);
  return 0;
}
示例#6
0
int main()
{
	int pids[NTHREADS] = {0};

	/* a Matrix multiplying validity function may be needed depending on
	   how this is being tested A and B are both predetermined and
	   equivalent square matrices 
	*/
	run_threads(pids);

	return 0;
}
示例#7
0
int main(int argc, char * argv[]) {
    std::vector<int> numbers;
    std::string data;
    std::getline(std::cin, data);
    std::stringstream string_stream(data);
    int x;
    while(true){
        string_stream >> x;
        if (!string_stream) break;
        numbers.push_back(x);
    }
    int n = numbers.size();
    std::cout << run_threads(numbers.data(), n) << std::endl;
    return 0;
}
示例#8
0
int main(int argc, char **argv)
{
  // Defaults
  // pool size = 100
  size_t qlen = QLEN_DEFAULT;
  // 100 producers, 100 consumers
  size_t nproducers = NPROC_DEFAULT, nconsumers = NCONS_DEFAULT;
  // pass 1000000 messages
  size_t nmesgs = NMESG_DEFAULT;

  // use spinlock instead of mutex
  int use_spinlock = 0, use_mutexes = 0, use_yield = 0;

  // Read args
  int c;

  while ((c = getopt(argc, argv, "p:c:n:q:smy")) >= 0)
    if (c == 'p') nproducers = (size_t)atoi(optarg);
    else if (c == 'c') nconsumers = (size_t)atoi(optarg);
    else if (c == 'n') nmesgs = (size_t)atoi(optarg);
    else if (c == 'q') qlen = (size_t)atoi(optarg);
    else if (c == 's') use_spinlock = 1;
    else if (c == 'm') use_mutexes = 1;
    else if (c == 'y') use_yield = 1;
    else print_usage();

  if(optind < argc) print_usage();
  if(use_spinlock + use_mutexes + use_yield > 1) print_usage();
  if(use_spinlock + use_mutexes + use_yield == 0) use_spinlock = 1;

  // Create pool of ints of length qlen
  MsgPool q;
  if(use_spinlock)
    msgpool_alloc_spinlock(&q, qlen, sizeof(size_t));
  else if(use_mutexes)
    msgpool_alloc_mutex(&q, qlen, sizeof(size_t));
  else
    msgpool_alloc_yield(&q, qlen, sizeof(size_t));

  msgpool_iterate(&q, set_zero, NULL);

  bool pass = run_threads(&q, nmesgs, nproducers, nconsumers);

  msgpool_dealloc(&q);

  printf(pass ? "Done.\n" : "Fail.\n");
  return pass ? EXIT_SUCCESS : EXIT_FAILURE;
}
示例#9
0
DataSet *run_viewshed_terrain(DataSet *terrain, int nthread,
    unsigned int (*vcount) (DataSet *terrain, GridPoint p))
{
  static Rtimer rt;
  DataSet *vmap;
  Vector *thread_bands;
  ViewshedBand band;
  int i;
  float fNODATA;

  rt_start(rt);

  assert(nthread > 0);

  fNODATA = getNODATA(terrain);

  vmap = dInit(terrain->grid.nrow, terrain->grid.ncol, UINT);
  assert(vmap);
  vmap->grid.uiNODATA = 0;

  thread_bands = vinit2(sizeof(ViewshedBand), nthread);
  for (i = 0; i < nthread; i++) {
    band.nthread = nthread;
    band.index = i;
    band.terrain = terrain;
    band.vmap = vmap;
    band.fNODATA = fNODATA;
    band.vcount = vcount;
    vappend(thread_bands, &band);
  }

  run_threads(nthread, viewshed_terrain_sub, thread_bands);

  rt_stop(rt);
  static char buf[256];
  rt_sprint(buf, rt);
  printf("run_viewshed_terrain('%s'):\t%s\n",
         terrain->path, buf);

  return vmap;
}
示例#10
0
static void *run_method(hashpipe_thread_args_t * args)
{
	int rv = 0;
	easy_in_output_databuf_t *db_out = (easy_in_output_databuf_t *)args->obuf;
	hashpipe_status_t st = args->st;
	const char * status_key = args->thread_desc->skey;
	
	int idx_data = 0;
	char data = 'a';
	while (run_threads())
	{
		while ((rv=hashpipe_databuf_wait_free((hashpipe_databuf_t *)db_out, idx_data)) != HASHPIPE_OK) {
			if (rv==HASHPIPE_TIMEOUT) {
				hashpipe_status_lock_safe(&st);
				hputs(st.buf, status_key, "blocked_in");
				hashpipe_status_unlock_safe(&st);
				continue;
			} else {
				hashpipe_error(__FUNCTION__, "error waiting for free databuf");
				pthread_exit(NULL);
				break;
			}
		}
		#ifdef DEBUG
			fprintf(stdout,"easy_in_thread:\n");
			fprintf(stdout,"\tcount = %d\n",db_out->count);
			fprintf(stdout,"\tdata[%d] = %c\n",idx_data,'a' + (char)(db_out->count % 26));
		#endif
		db_out->data[idx_data] = 'a' + (char)(db_out->count % 26);
		db_out->count++;
		hashpipe_databuf_set_filled((hashpipe_databuf_t *)db_out, idx_data);
		idx_data = (idx_data + 1) % db_out->header.n_block;
		
		pthread_testcancel();
	}
	// Thread success!
	return NULL;
}
示例#11
0
int main(int argn, char **argv)
{
    int dram_refs;
    int nvm_refs;
    int interleaved_dram;
    int interleaved_nvm;
    int n_threads;

    if (argn != 6) {
        printf("INVALID ARGUMENTS:\n");
        printf("\t%s [# threads] [# total dram accesses] [# total nvm accesses] [# dram accesses in sequence] [# nvm accesses in sequence]\n", argv[0]);
        return -1;
    }

    n_threads = atoi(argv[1]);
    dram_refs = atoi(argv[2]);
    nvm_refs = atoi(argv[3]);
    interleaved_dram = atoi(argv[4]);
    interleaved_nvm = atoi(argv[5]);

    run_threads(n_threads, dram_refs, nvm_refs, interleaved_dram, interleaved_nvm);

    return 0;
}
示例#12
0
文件: server.c 项目: buzzcz/UPS
/*
 * Method that runs the server's main loop. It reads a message or waits for timeout, checks sent messages, and puts
 * received messages into buffer
 *
 *
 * server_socket: socket to be used for receiving and sending messages
 * */
void run_server(int server_socket) {

	signal(SIGINT, exit_handler);
	init_server(server_socket);

	run_threads();

	while (1) {
		struct message received;

		received = receive_message(server_socket);
		check_sent_messages(server_socket);
		if (received.type == -1) {
		} else if (received.type == -2) {
			printf("Can't parse message\n");
			number_of_unparseable++;
		} else {
			pthread_mutex_lock(&mutex);
			add_message(&buffer, received, NULL, 0);
			pthread_mutex_unlock(&mutex);
			sem_post(&sem);
		}
	}
}
示例#13
0
int main(int argc, char *const argv[])
{
        int detach = 1;
        const char *rtgconf_file = DEFAULT_RTGCONF_FILE;
        const char *targets_file = DEFAULT_TARGETS_FILE;
        int use_db = 1;
        int use_rate_column = 1;
        int allow_db_zero = 0;
        unsigned max_db_queue = DEFAULT_QUEUE_LENGTH;
        unsigned num_dbthreads = DEFAULT_NUM_DBTHREADS;
        int c;
        char *last_component;
        struct rtgtargets *targets;
        struct rtgtargets *old_targets = NULL;

        if (argc < 2) {
                help();
                exit(EXIT_FAILURE);
        }

        while ((c = getopt(argc, argv, "c:dt:vzDOOQ:W:")) != -1) {
                switch (c) {
                case 'c':
                        rtgconf_file = optarg;
                        break;
                case 'd':
                        use_db = 0;
                        break;
                case 't':
                        targets_file = optarg;
                        break;
                case 'v':
                        verbosity++;
                        break;
                case 'z':
                        allow_db_zero = 1;
                        break;
                case 'D':
                        detach = 0;
                        break;
                case 'O':
                        use_rate_column = 0;
                        break;
                case 'Q':
                        max_db_queue = (unsigned) strtol(optarg, NULL, 10);
                        break;
                case 'W':
                        num_dbthreads = (unsigned) strtol(optarg, NULL, 10);
                        break;

                case '?':
                default:
                        help();
                        exit(EXIT_FAILURE);
                }
        }

        if (argc != optind) {
                help();
                exit(EXIT_FAILURE);
        }

        if (max_db_queue < MIN_QUEUE_LENGTH) {
                fprintf(stderr, "Error: minimum queue length is %d.\n", MIN_QUEUE_LENGTH);
                help();
                exit(EXIT_FAILURE);
        }

        if (num_dbthreads < 1) {
                fprintf(stderr, "Error: you need at least one database thread.\n");
                help();
                exit(EXIT_FAILURE);
        }

        /* Convert given path names to full paths. */
        rtgconf_file = realpath(rtgconf_file, NULL);
        targets_file = realpath(targets_file, NULL);

        cllog(0, "clpoll v%s starting up", VERSION);

        if (detach) {
                /* Try to parse configuration and target files so we can give error messages before we detach. */
                struct rtgconf *config_test;
                struct rtgtargets *targets_test;

                config_test = rtgconf_create(rtgconf_file);
                if (!config_test || !rtgconf_verify(config_test)) {
                        cllog(0, "Missing or incorrect configuration file, so nothing to do.");
                        exit(EXIT_FAILURE);
                }
                rtgconf_free(config_test);

                targets_test = rtgtargets_parse(targets_file, config_test);
                if (targets_test->ntargets == 0) {
                        cllog(0, "No targets, so nothing to do.");
                        exit(EXIT_FAILURE);
                }
                rtgtargets_free(targets_test);

                /* Move to backgorund. */
                daemonize();
        }

        last_component = strrchr(argv[0], '/');
        if (last_component)
                last_component++;
        else
                last_component = argv[0];
        openlog(last_component, LOG_PID, LOG_USER);

        signal(SIGHUP, sighup_handler);
        signal(SIGTERM, sigterm_handler);

        clsnmp_global_init();

        while (!full_stop_requested) {
                /* Read rtg.conf */
                struct rtgconf *config = rtgconf_create(rtgconf_file);
                if (!config || !rtgconf_verify(config)) {
                        cllog(0, "Missing or incorrect configuration file, so nothing to do.");
                        exit(EXIT_FAILURE);
                }

                /* "Patch" rtgconf with command line values */
                config->use_db = use_db;
                config->use_rate_column = use_rate_column;
                config->allow_db_zero = allow_db_zero;
                config->max_db_queue = max_db_queue;
                config->num_dbthreads = num_dbthreads;

                /* Read targets.cfg */
                targets = rtgtargets_parse(targets_file, config);
                if (targets->ntargets == 0) {
                        cllog(0, "No targets, so nothing to do.");
                        exit(EXIT_FAILURE);
                }

                if (old_targets != NULL) {
                        rtgtargets_copy_cache(targets, old_targets);
                        rtgtargets_free(old_targets);
                        old_targets = NULL;
                }

                cllog(1, "Polling every %d seconds.", config->interval);

                run_threads(targets, config);

                rtgconf_free(config);
                old_targets = targets;
        }
        return 0;
}
示例#14
0
/* lock a byte range in a open file */
int main(int argc, char *argv[])
{
	int nprocs, i;
	char *tname = "ALL";
#define NREPEATS 10
	struct {
		const char *name;
		void *(*fn)(int );
	} tests[] = {
		{"noop", test_noop},
		{"malloc", test_malloc},
		{"setreuid", test_setreuid},
		{"readwrite", test_readwrite},
		{"stat", test_stat},
		{"fstat", test_fstat},
		{"dir", test_dir},
		{"dirsingle", test_dirsingle},
		{"create", test_create},
		{"lock", test_lock},
		{NULL, NULL}
	};

	if (argc <= 1) {
		printf("thread_perf NPROCS\n");
		exit(1);
	}

	nprocs = atoi(argv[1]);

	if (argc > 2) {
		tname = argv[2];
	}

	id_data = calloc(nprocs, sizeof(*id_data));
	if (!id_data) {
		exit(1);
	}

#ifndef NO_THREADS
	printf("NOTE! for accurate process results please compile with -DNO_THREADS and don't link to -lpthread\n\n");
#endif

	for (i=0;i<nprocs;i++) {
		char s[30];
		sprintf(s, "testd_%d", i);
		id_data[i].dname = strdup(s);

		sprintf(s, "%s/test.dat", id_data[i].dname);
		id_data[i].fname = strdup(s);

		rmdir(id_data[i].dname);
		if (mkdir(id_data[i].dname, 0777) != 0) {
			fprintf(stderr, "Failed to create %s\n", id_data[i].dname);
			exit(1);
		}

		unlink(id_data[i].fname);
	}

	for (i=0;tests[i].name;i++) {
		double t_threads[NREPEATS];
		double t_processes[NREPEATS];
		int j;

		if (strcasecmp(tname, "ALL") && strcasecmp(tests[i].name, tname)) {
			continue;
		}

		printf("Running test '%s' with %d tasks\n", tests[i].name, nprocs);

		for (j=0;j<NREPEATS;j++) {
#ifndef NO_THREADS
			t_threads[j]   = run_threads(nprocs, tests[i].fn);
#endif
			t_processes[j] = run_processes(nprocs, tests[i].fn);
		}
#ifndef NO_THREADS
		show_result("Threads  ", t_threads, NREPEATS);
#endif
		show_result("Processes", t_processes, NREPEATS);

		printf("\n");
		fflush(stdout);
	}

	for (i=0;i<nprocs;i++) {
		if (rmdir(id_data[i].dname) != 0) {
			fprintf(stderr, "Failed to delete %s\n", id_data[i].dname);
			exit(1);
		}
	}

	for (i=0;i<nprocs;i++) {
		free(id_data[i].dname);
		free(id_data[i].fname);
	}
	free(id_data);

	return 0;
}
示例#15
0
static void *run(hashpipe_thread_args_t * args)
{
    // Local aliases to shorten access to args fields
    // Our input buffer is a paper_input_databuf
    // Our output buffer is a paper_gpu_input_databuf
    paper_input_databuf_t *db_in = (paper_input_databuf_t *)args->ibuf;
    paper_gpu_input_databuf_t *db_out = (paper_gpu_input_databuf_t *)args->obuf;
    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

#ifdef DEBUG_SEMS
    fprintf(stderr, "s/tid %lu/                      FLUFf/\n", pthread_self());
#endif

    // Init status variables
    hashpipe_status_lock_safe(&st);
    hputi8(st.buf, "FLUFMCNT", 0);
    hashpipe_status_unlock_safe(&st);

    /* Loop */
    int rv;
    int curblock_in=0;
    int curblock_out=0;
    float gbps, min_gbps;

    struct timespec start, finish;

    while (run_threads()) {

        // Note waiting status,
        // query integrating status
        // and, if armed, start count
        hashpipe_status_lock_safe(&st);
        hputs(st.buf, status_key, "waiting");
        hashpipe_status_unlock_safe(&st);

        // Wait for new input block to be filled
        while ((rv=paper_input_databuf_wait_filled(db_in, curblock_in)) != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "blocked_in");
                hashpipe_status_unlock_safe(&st);
                continue;
            } else {
                hashpipe_error(__FUNCTION__, "error waiting for filled databuf");
                pthread_exit(NULL);
                break;
            }
        }

        // Wait for new gpu_input block (our output block) to be free
        while ((rv=paper_gpu_input_databuf_wait_free(db_out, curblock_out)) != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "blocked gpu input");
                hashpipe_status_unlock_safe(&st);
                continue;
            } else {
                hashpipe_error(__FUNCTION__, "error waiting for free databuf");
                pthread_exit(NULL);
                break;
            }
        }

        // Got a new data block, update status
        hashpipe_status_lock_safe(&st);
        hputs(st.buf, status_key, "fluffing");
        hputi4(st.buf, "FLUFBKIN", curblock_in);
        hputu8(st.buf, "FLUFMCNT", db_in->block[curblock_in].header.mcnt);
        hashpipe_status_unlock_safe(&st);

        // Copy header and call fluff function
        clock_gettime(CLOCK_MONOTONIC, &start);

        memcpy(&db_out->block[curblock_out].header, &db_in->block[curblock_in].header, sizeof(paper_input_header_t));

        paper_fluff(db_in->block[curblock_in].data, db_out->block[curblock_out].data);

        clock_gettime(CLOCK_MONOTONIC, &finish);

        // Note processing time
        hashpipe_status_lock_safe(&st);
        // Bits per fluff / ns per fluff = Gbps
        hgetr4(st.buf, "FLUFMING", &min_gbps);
        gbps = (float)(8*N_BYTES_PER_BLOCK)/ELAPSED_NS(start,finish);
        hputr4(st.buf, "FLUFGBPS", gbps);
        if(min_gbps == 0 || gbps < min_gbps) {
          hputr4(st.buf, "FLUFMING", gbps);
        }
        hashpipe_status_unlock_safe(&st);

        // Mark input block as free and advance
        paper_input_databuf_set_free(db_in, curblock_in);
        curblock_in = (curblock_in + 1) % db_in->header.n_block;

        // Mark output block as full and advance
        paper_gpu_input_databuf_set_filled(db_out, curblock_out);
        curblock_out = (curblock_out + 1) % db_out->header.n_block;

        /* Check for cancel */
        pthread_testcancel();
    }

    // Thread success!
    return NULL;
}
示例#16
0
文件: replika.c 项目: buytenh/replika
int main(int argc, char *argv[])
{
	static struct option long_options[] = {
		{ "block-size", required_argument, 0, 'b' },
		{ "hash-algo", required_argument, 0, 'h' },
		{ "hash-algorithm", required_argument, 0, 'h' },
		{ "max-iter", required_argument, 0, 'i' },
		{ "freeze", required_argument, 0, 'f' },
		{ "loop", no_argument, 0, 'l' },
		{ 0, 0, 0, 0 },
	};
	int i;
	int freeze_count = 0;

	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

	if (!gcry_check_version(GCRYPT_VERSION)) {
		fprintf(stderr, "libgcrypt version mismatch\n");
		return 1;
	}

	while (1) {
		int c;

		c = getopt_long(argc, argv, "b:h:i:f:l", long_options, NULL);
		if (c == -1)
			break;

		switch (c) {
		case 'b':
			if (sscanf(optarg, "%i", &block_size) != 1) {
				fprintf(stderr, "cannot parse block size: "
						"%s\n", optarg);
				return 1;
			}

			if ((block_size & 7) != 0) {
				fprintf(stderr, "error: block size must be "
						"a multiple of 8\n");
				return 1;
			}

			break;

		case 'h':
			hash_algo = gcry_md_map_name(optarg);
			if (hash_algo == 0) {
				fprintf(stderr, "unknown hash algorithm "
						"name: %s\n", optarg);
				return 1;
			}

			break;

		case 'i':
			if (sscanf(optarg, "%i", &max_iterations) != 1) {
				fprintf(stderr, "cannot parse iteration "
						"count: %s\n", optarg);
				return 1;
			}

			break;

		case 'f':
			if (freeze_count == MAX_FREEZE) {
				fprintf(stderr, "too many --freeze options\n");
				return 1;
			}

			freeze_fs[freeze_count++] = optarg;

			break;

		case 'l':
			loop = 1;
			break;

		case '?':
			return 1;

		default:
			abort();
		}
	}

	if (optind + 4 != argc) {
		fprintf(stderr, "%s: [opts] <src> <srchashmap> <dst> "
				"<dsthashmap>\n", argv[0]);
		fprintf(stderr, " -b, --block-size=SIZE    hash block size\n");
		fprintf(stderr, " -f, --freeze=MOUNTPOINT  freeze "
				"filesystem\n");
		fprintf(stderr, " -h, --hash-algo=ALGO     hash algorithm\n");
		fprintf(stderr, " -i, --max-iter=ITER      maximum number of "
				"iterations\n");
		fprintf(stderr, " -l, --loop               create consistent "
				"image copy\n");
		return 1;
	}

	hash_size = gcry_md_get_algo_dlen(hash_algo);

	fd_src = open(argv[optind], O_RDONLY);
	if (fd_src < 0) {
		perror("opening src");
		return 1;
	}

	sizeblocks = lseek(fd_src, 0, SEEK_END);
	if (sizeblocks < 0) {
		perror("lseek");
		return 1;
	}
	sizeblocks = (sizeblocks + block_size - 1) / block_size;

	if (strcmp(argv[optind + 1], "-")) {
		int fd_srchashmap;

		if (loop) {
			fprintf(stderr, "consistent image copy requested, "
					"but source hashmap specified\n");
			return 1;
		}

		fd_srchashmap = open(argv[optind + 1], O_RDONLY);
		if (fd_srchashmap < 0) {
			perror("opening srchashmap");
			return 1;
		}

		srchashmap = malloc(sizeblocks * hash_size);
		if (srchashmap == NULL) {
			fprintf(stderr, "out of memory allocating hash map\n");
			return 1;
		}

		if (read(fd_srchashmap, srchashmap, sizeblocks * hash_size)
		    != sizeblocks * hash_size) {
			fprintf(stderr, "error reading hash map\n");
			return 1;
		}

		close(fd_srchashmap);
	} else {
		srchashmap = NULL;
	}

	fd_dst = open(argv[optind + 2], O_CREAT | O_RDWR, 0666);
	if (fd_dst < 0) {
		perror("opening dst");
		return 1;
	}

	fd_dsthashmap = open(argv[optind + 3], O_CREAT | O_RDWR, 0666);
	if (fd_dsthashmap < 0) {
		perror("opening dsthashmap");
		return 1;
	}

	dsthashmap = malloc(sizeblocks * hash_size);
	if (dsthashmap == NULL) {
		fprintf(stderr, "out of memory allocating hash map\n");
		return 1;
	}

	if (read(fd_dsthashmap, dsthashmap, sizeblocks * hash_size)
	    != sizeblocks * hash_size) {
		fprintf(stderr, "error reading hash map\n");
		return 1;
	}

	setup_sig_handlers();

	if (freeze_count) {
		for (i = 0; i < MAX_FREEZE; i++)
			freeze_fd[i] = -1;

		atexit(thaw_fs);

		fprintf(stderr, "freezing filesystems\n");

		for (i = 0; i < freeze_count; i++) {
			int fd;

			fd = open(freeze_fs[i], O_RDONLY);
			if (fd < 0) {
				fprintf(stderr, "error opening freeze mount "
						"point %s (%s)\n", freeze_fs[i],
						strerror(errno));
				return 1;
			}

			if (ioctl(fd, FIFREEZE, 0) < 0) {
				fprintf(stderr, "error freezing fs %s (%s)\n",
						freeze_fs[i], strerror(errno));
				return 1;
			}

			freeze_fd[i] = fd;
		}
	}

	if (loop) {
		for (i = 0; i < max_iterations; i++) {
			fd_off = 0;
			again = 0;

			fprintf(stderr, "scanning for differences... ");
			run_threads(copy_thread_no_hashmap);
			if (!signal_quit_flag) {
				fprintf(stderr, "done                      "
						"                          \n");
			}

			if (!again)
				break;

			if (i == max_iterations - 1) {
				fprintf(stderr, "maximum iteration count "
						"reached, bailing out\n");
			} else {
				fprintf(stderr, "repeating scanning due to "
						"differences\n");
			}
		}
	} else {
		fd_off = 0;

		if (srchashmap == NULL) {
			fprintf(stderr, "scanning for differences... ");
			run_threads(copy_thread_no_hashmap);
		} else {
			off_t off;

			mismatch_idx = 0;

			mismatch_cnt = 0;
			for (off = 0; off < sizeblocks; off++) {
				if (memcmp(srchashmap + off * hash_size,
					   dsthashmap + off * hash_size,
					   hash_size)) {
					mismatch_cnt++;
				}
			}

			fprintf(stderr, "copying differences... ");
			run_threads(copy_thread_hashmap);
		}
		if (!signal_quit_flag) {
			fprintf(stderr, "done                      "
					"                          \n");
		}
	}

	fprintf(stderr, "flushing buffers... ");
	close(fd_src);
	close(fd_dst);
	close(fd_dsthashmap);
	fprintf(stderr, "done\n");

	return signal_quit_flag ? EXIT_FAILURE : EXIT_SUCCESS;
}
示例#17
0
static void *run(hashpipe_thread_args_t * args, int doCPU)
{
    // Local aliases to shorten access to args fields
    paper_gpu_input_databuf_t *db_in = (paper_gpu_input_databuf_t *)args->ibuf;
    paper_output_databuf_t *db_out = (paper_output_databuf_t *)args->obuf;
    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

#ifdef DEBUG_SEMS
    fprintf(stderr, "s/tid %lu/                      GPU/\n", pthread_self());
#endif

    // Init integration control status variables
    int gpu_dev = 0;
    hashpipe_status_lock_safe(&st);
    hputs(st.buf,  "INTSTAT", "off");
    hputi8(st.buf, "INTSYNC", 0);
    hputi4(st.buf, "INTCOUNT", N_SUB_BLOCKS_PER_INPUT_BLOCK);
    hputi8(st.buf, "GPUDUMPS", 0);
    hgeti4(st.buf, "GPUDEV", &gpu_dev); // No change if not found
    hputi4(st.buf, "GPUDEV", gpu_dev);
    hashpipe_status_unlock_safe(&st);

    /* Loop */
    int rv;
    char integ_status[17];
    uint64_t start_mcount, last_mcount=0;
    uint64_t gpu_dumps=0;
    int int_count; // Number of blocks to integrate per dump
    int xgpu_error = 0;
    int curblock_in=0;
    int curblock_out=0;

    struct timespec start, stop;
    uint64_t elapsed_gpu_ns  = 0;
    uint64_t gpu_block_count = 0;

    // Initialize context to point at first input and output memory blocks.
    // This seems redundant since we do this just before calling
    // xgpuCudaXengine, but we need to pass something in for array_h and
    // matrix_x to prevent xgpuInit from allocating memory.
    XGPUContext context;
    context.array_h = (ComplexInput *)db_in->block[0].data;
    context.array_len = (db_in->header.n_block * sizeof(paper_gpu_input_block_t) - sizeof(paper_input_header_t)) / sizeof(ComplexInput);
    context.matrix_h = (Complex *)db_out->block[0].data;
    context.matrix_len = (db_out->header.n_block * sizeof(paper_output_block_t) - sizeof(paper_output_header_t)) / sizeof(Complex);

    xgpu_error = xgpuInit(&context, gpu_dev);
    if (XGPU_OK != xgpu_error) {
        fprintf(stderr, "ERROR: xGPU initialization failed (error code %d)\n", xgpu_error);
        return THREAD_ERROR;
    }

    while (run_threads()) {

        // Note waiting status,
        // query integrating status
        // and, if armed, start count
        hashpipe_status_lock_safe(&st);
        hputs(st.buf, status_key, "waiting");
        hgets(st.buf,  "INTSTAT", 16, integ_status);
        hgeti8(st.buf, "INTSYNC", (long long*)&start_mcount);
        hashpipe_status_unlock_safe(&st);

        // Wait for new input block to be filled
        while ((rv=hashpipe_databuf_wait_filled((hashpipe_databuf_t *)db_in, curblock_in)) != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "blocked_in");
                hashpipe_status_unlock_safe(&st);
                continue;
            } else {
                hashpipe_error(__FUNCTION__, "error waiting for filled databuf");
                pthread_exit(NULL);
                break;
            }
        }

        // Got a new data block, update status and determine how to handle it
        hashpipe_status_lock_safe(&st);
        hputi4(st.buf, "GPUBLKIN", curblock_in);
        hputu8(st.buf, "GPUMCNT", db_in->block[curblock_in].header.mcnt);
        hashpipe_status_unlock_safe(&st);

        // If integration status "off"
        if(!strcmp(integ_status, "off")) {
            // Mark input block as free and advance
            hashpipe_databuf_set_free((hashpipe_databuf_t *)db_in, curblock_in);
            curblock_in = (curblock_in + 1) % db_in->header.n_block;
            // Skip to next input buffer
            continue;
        }

        // If integration status is "start"
        if(!strcmp(integ_status, "start")) {
            // If buffer mcount < start_mcount (i.e. not there yet)
            if(db_in->block[curblock_in].header.mcnt < start_mcount) {
              // Drop input buffer
              // Mark input block as free and advance
              hashpipe_databuf_set_free((hashpipe_databuf_t *)db_in, curblock_in);
              curblock_in = (curblock_in + 1) % db_in->header.n_block;
              // Skip to next input buffer
              continue;
            // Else if mcount == start_mcount (time to start)
            } else if(db_in->block[curblock_in].header.mcnt == start_mcount) {
              // Set integration status to "on"
              // Read integration count (INTCOUNT)
              fprintf(stderr, "--- integration on ---\n");
              strcpy(integ_status, "on");
              hashpipe_status_lock_safe(&st);
              hputs(st.buf,  "INTSTAT", integ_status);
              hgeti4(st.buf, "INTCOUNT", &int_count);
              hashpipe_status_unlock_safe(&st);
              // Compute last mcount
              last_mcount = start_mcount + (int_count-1) * N_SUB_BLOCKS_PER_INPUT_BLOCK;
            // Else (missed starting mcount)
            } else {
              // Handle missed start of integration
              // TODO!
              fprintf(stderr, "--- mcnt=%06lx > start_mcnt=%06lx ---\n",
                  db_in->block[curblock_in].header.mcnt, start_mcount);
            }
        }

        // Integration status is "on" or "stop"

        // Note processing status
        hashpipe_status_lock_safe(&st);
        hputs(st.buf, status_key, "processing gpu");
        hashpipe_status_unlock_safe(&st);


        // Setup for current chunk
        context.input_offset = curblock_in * sizeof(paper_gpu_input_block_t) / sizeof(ComplexInput);
        context.output_offset = curblock_out * sizeof(paper_output_block_t) / sizeof(Complex);

        // Call CUDA X engine function
        int doDump = 0;
        // Dump if this is the last block or we are doing both CPU and GPU
        // (GPU and CPU test mode always dumps every input block)
        if(db_in->block[curblock_in].header.mcnt >= last_mcount || doCPU) {
          doDump = 1;

          // Check whether we missed the end of integration.  If we get a block
          // whose mcnt is greater than last_mcount, then for some reason (e.g.
          // networking problems) we didn't see a block whose mcnt was
          // last_mcount.  This should "never" happen, but it has been seen to
          // occur when the 10 GbE links have many errors.
          if(db_in->block[curblock_in].header.mcnt > last_mcount) {
            // Can't do much error recovery, so just log it.
            fprintf(stderr, "--- mcnt=%06lx > last_mcnt=%06lx ---\n",
                db_in->block[curblock_in].header.mcnt, last_mcount);
          }

          // Wait for new output block to be free
          while ((rv=paper_output_databuf_wait_free(db_out, curblock_out)) != HASHPIPE_OK) {
              if (rv==HASHPIPE_TIMEOUT) {
                  hashpipe_status_lock_safe(&st);
                  hputs(st.buf, status_key, "blocked gpu out");
                  hashpipe_status_unlock_safe(&st);
                  continue;
              } else {
                  hashpipe_error(__FUNCTION__, "error waiting for free databuf");
                  pthread_exit(NULL);
                  break;
              }
          }
        }

        clock_gettime(CLOCK_MONOTONIC, &start);

        xgpuCudaXengine(&context, doDump ? SYNCOP_DUMP : SYNCOP_SYNC_TRANSFER);

        clock_gettime(CLOCK_MONOTONIC, &stop);
        elapsed_gpu_ns += ELAPSED_NS(start, stop);
        gpu_block_count++;

        if(doDump) {
          clock_gettime(CLOCK_MONOTONIC, &start);
          xgpuClearDeviceIntegrationBuffer(&context);
          clock_gettime(CLOCK_MONOTONIC, &stop);
          elapsed_gpu_ns += ELAPSED_NS(start, stop);

          // TODO Maybe need to subtract all or half the integration time here
          // depending on recevier's expectations.
          db_out->block[curblock_out].header.mcnt = last_mcount;
          // If integration status if "stop"
          if(!strcmp(integ_status, "stop")) {
            // Set integration status to "off"
            strcpy(integ_status, "off");
            hashpipe_status_lock_safe(&st);
            hputs(st.buf,  "INTSTAT", integ_status);
            hashpipe_status_unlock_safe(&st);
          } else {
            // Advance last_mcount for end of next integration
            last_mcount += int_count * N_SUB_BLOCKS_PER_INPUT_BLOCK;
          }

          // Mark output block as full and advance
          paper_output_databuf_set_filled(db_out, curblock_out);
          curblock_out = (curblock_out + 1) % db_out->header.n_block;
          // TODO Need to handle or at least check for overflow!

          // Update GPU dump counter and GPU Gbps
          gpu_dumps++;
          hashpipe_status_lock_safe(&st);
          hputi8(st.buf, "GPUDUMPS", gpu_dumps);
          hputr4(st.buf, "GPUGBPS", (float)(8*N_FLUFFED_BYTES_PER_BLOCK*gpu_block_count)/elapsed_gpu_ns);
          hashpipe_status_unlock_safe(&st);

          // Start new average
          elapsed_gpu_ns  = 0;
          gpu_block_count = 0;
        }

        if(doCPU) {

            /* Note waiting status */
            hashpipe_status_lock_safe(&st);
            hputs(st.buf, status_key, "waiting");
            hashpipe_status_unlock_safe(&st);

            // Wait for new output block to be free
            while ((rv=paper_output_databuf_wait_free(db_out, curblock_out)) != HASHPIPE_OK) {
                if (rv==HASHPIPE_TIMEOUT) {
                    hashpipe_status_lock_safe(&st);
                    hputs(st.buf, status_key, "blocked cpu out");
                    hashpipe_status_unlock_safe(&st);
                    continue;
                } else {
                    hashpipe_error(__FUNCTION__, "error waiting for free databuf");
                    pthread_exit(NULL);
                    break;
                }
            }

            // Note "processing cpu" status, current input block
            hashpipe_status_lock_safe(&st);
            hputs(st.buf, status_key, "processing cpu");
            hashpipe_status_unlock_safe(&st);

            /*
             * Call CPU X engine function
             */
            xgpuOmpXengine((Complex *)db_out->block[curblock_out].data, context.array_h);

            // Mark output block as full and advance
            paper_output_databuf_set_filled(db_out, curblock_out);
            curblock_out = (curblock_out + 1) % db_out->header.n_block;
            // TODO Need to handle or at least check for overflow!
        }

        // Mark input block as free and advance
        hashpipe_databuf_set_free((hashpipe_databuf_t *)db_in, curblock_in);
        curblock_in = (curblock_in + 1) % db_in->header.n_block;

        /* Check for cancel */
        pthread_testcancel();
    }

    xgpuFree(&context);

    // Thread success!
    return NULL;
}
static void *run(hashpipe_thread_args_t * args)
{
    s6_input_databuf_t *db  = (s6_input_databuf_t *)args->obuf;
    hashpipe_status_t *p_st = &(args->st);

    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

    //s6_input_block_t fake_data_block;

    /* Main loop */
    int i, rv;
    uint64_t mcnt = 0;
    uint64_t num_coarse_chan = N_COARSE_CHAN;
    uint64_t *data;
    int block_idx = 0;
    int error_count = 0, max_error_count = 0;
    float error, max_error = 0.0;
    int gen_fake = 0;

    hashpipe_status_lock_safe(&st);
    //hashpipe_status_lock_safe(p_st);
    hputi4(st.buf, "NUMCCHAN", N_COARSE_CHAN);
    hputi4(st.buf, "NUMFCHAN", N_FINE_CHAN);
    hputi4(st.buf, "NUMBBEAM", N_BYTES_PER_BEAM);
    hputi4(st.buf, "NUMBBLOC", sizeof(s6_input_block_t));
    hputi4(st.buf, "THRESHLD", POWER_THRESH);
    hgeti4(st.buf, "GENFAKE", &gen_fake);
    hashpipe_status_unlock_safe(&st);
    //hashpipe_status_unlock_safe(p_st);

    time_t t, prior_t;
    prior_t = time(&prior_t);

    while (run_threads()) {

        hashpipe_status_lock_safe(&st);
        //hashpipe_status_lock_safe(p_st);
        hputi4(st.buf, "NETBKOUT", block_idx);
        hputs(st.buf, status_key, "waiting");
        hashpipe_status_unlock_safe(&st);
        //hashpipe_status_unlock_safe(p_st);
 
        t = time(&t);
        fprintf(stderr, "elapsed seconds for block %d : %ld\n", block_idx, t - prior_t);
        prior_t = t;
        // Wait for data
        struct timespec sleep_dur, rem_sleep_dur;
        sleep_dur.tv_sec = 1;
        sleep_dur.tv_nsec = 0;
        //fprintf(stderr, "fake net thread sleeping for %7.5f seconds\n", 
        //        sleep_dur.tv_sec + (double)sleep_dur.tv_nsec/1000000000.0);
        nanosleep(&sleep_dur, &rem_sleep_dur);
	
        /* Wait for new block to be free, then clear it
         * if necessary and fill its header with new values.
         */
        while ((rv=s6_input_databuf_wait_free(db, block_idx)) 
                != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "blocked");
                hashpipe_status_unlock_safe(&st);
                continue;
            } else {
                hashpipe_error(__FUNCTION__, "error waiting for free databuf");
                pthread_exit(NULL);
                break;
            }
        }

        hashpipe_status_lock_safe(&st);
        hputs(st.buf, status_key, "receiving");
        hashpipe_status_unlock_safe(&st);
 
        // populate block header
        db->block[block_idx].header.mcnt = mcnt;
        db->block[block_idx].header.coarse_chan_id = 321;
        db->block[block_idx].header.num_coarse_chan = num_coarse_chan;
        memset(db->block[block_idx].header.missed_pkts, 0, sizeof(uint64_t) * N_BEAM_SLOTS);

        if(gen_fake) {
            gen_fake = 0;
            // gen fake data for all beams, all blocks   
            // TODO vary data by beam
            fprintf(stderr, "generating fake data to block 0 beam 0...");
            gen_fake_data(&(db->block[0].data[0]));
            fprintf(stderr, " done\n");
            fprintf(stderr, "copying to block 0 beam");
            for(int beam_i = 1; beam_i < N_BEAMS; beam_i++) {
                fprintf(stderr, " %d", beam_i);
                memcpy((void *)&db->block[0].data[beam_i*N_BYTES_PER_BEAM/sizeof(uint64_t)], 
                    (void *)&db->block[0].data[0], 
                    N_BYTES_PER_BEAM);
            }
            fprintf(stderr, " done\n");
            fprintf(stderr, "copying to block");
            for(int block_i = 1; block_i < N_INPUT_BLOCKS; block_i++) {
                fprintf(stderr, " %d", block_i);
                memcpy((void *)&db->block[block_i].data[0], 
                    (void *)&db->block[0].data[0], 
                    N_DATA_BYTES_PER_BLOCK);
            }
            fprintf(stderr, " done\n");
        }

        hashpipe_status_lock_safe(&st);
        hputr4(st.buf, "NETMXERR", max_error);
        hputi4(st.buf, "NETERCNT", error_count);
        hputi4(st.buf, "NETMXECT", max_error_count);
        hashpipe_status_unlock_safe(&st);

        // Mark block as full
        s6_input_databuf_set_filled(db, block_idx);

        // Setup for next block
        block_idx = (block_idx + 1) % db->header.n_block;
        mcnt++;
        // uncomment the following to test dynamic setting of num_coarse_chan
        //num_coarse_chan--;

        /* Will exit if thread has been cancelled */
        pthread_testcancel();
    }

    // Thread success!
    return THREAD_OK;
}
示例#19
0
int main (
  int	argc,
  char	*argv[]
)
{
  pwr_tStatus	sts;
  int		event;
  plc_sProcess	*pp;
  uid_t         ruid;
  struct passwd *pwd;
/*
  struct rlimit rlim;
  int i;
*/  
  /* Set core dump file size limit to infinite */
/*
  rlim.rlim_cur =  RLIM_INFINITY;
  rlim.rlim_max =  RLIM_INFINITY;
  sts = setrlimit(RLIMIT_CORE, &rlim);
  printf("%d\n", sts);
  i = 1/0;
  printf("%d\n", i);
*/
  pp = init_process();

  qcom_WaitAnd(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_newPlcInit, qcom_cTmoEternal);

  init_plc(pp);
  create_threads(pp);
  init_threads(pp);

  /* Once threads has set their priority don't run as root */
  
#if 0
  ruid = getuid();
  
  if (ruid == 0) {
    pwd = getpwnam("pwrp");
    if (pwd != NULL) {
      setreuid(pwd->pw_uid, pwd->pw_uid);
    }
  }
  else 
    setreuid(ruid, ruid);
#endif

  qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_newPlcInitDone);
  qcom_WaitAnd(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_newPlcStart, qcom_cTmoEternal);

//  proc_SetPriority(pp->PlcProcess->Prio);
  set_values(pp);
  start_threads(pp);
  run_threads(pp);
  time_Uptime(&sts, &pp->PlcProcess->StartTime, NULL);

  qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_newPlcStartDone);

#if 0
  /* Force the backup to take care initialized backup objects. */

  bck_ForceBackup(NULL);
#endif

  errh_SetStatus( PWR__SRUN);

  qcom_WaitOr(&sts, &pp->eventQ, &qcom_cQini, ini_mEvent_terminate | ini_mEvent_oldPlcStop, qcom_cTmoEternal, &event);

  switch ( event) {
  case ini_mEvent_terminate:
    errh_SetStatus( PWR__SRVTERM);

    stop_threads(pp);
    clean_all(pp);
    nmps_delete_lock( &sts);
    break;
  case ini_mEvent_oldPlcStop:
    errh_SetStatus( PWR__SRVTERM);

    time_Uptime(&sts, &pp->PlcProcess->StopTime, NULL);
    stop_threads(pp);
    save_values(pp);

    qcom_SignalOr(&sts, &qcom_cQini, ini_mEvent_oldPlcStopDone);

#if defined OS_ELN
    sts = proc_SetPriority(31);
#endif

    clean_all(pp);
    break;
  default: ;
  }

  exit(0);
}
示例#20
0
static void *run(hashpipe_thread_args_t * args)
{
    // Local aliases to shorten access to args fields
    // Our output buffer happens to be a paper_input_databuf
    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

    st_p = &st;	// allow global (this source file) access to the status buffer

    // Get inital value for crc32 function
    uint32_t init_crc = crc32(0,0,0);

    // Flag that holds off the crc thread
    int holdoff = 1;

    // Force ourself into the hold off state
    hashpipe_status_lock_safe(&st);
    hputi4(st.buf, "CRCHOLD", 1);
    hashpipe_status_unlock_safe(&st);

    while(holdoff) {
	// We're not in any hurry to startup
	sleep(1);
	hashpipe_status_lock_safe(&st);
	// Look for CRCHOLD value
	hgeti4(st.buf, "CRCHOLD", &holdoff);
	if(!holdoff) {
	    // Done holding, so delete the key
	    hdel(st.buf, "CRCHOLD");
	}
	hashpipe_status_unlock_safe(&st);
    }

    /* Read network params */
    struct hashpipe_udp_params up = {
	.bindhost = "0.0.0.0",
	.bindport = 8511,
	.packet_size = 8200
    };
    hashpipe_status_lock_safe(&st);
    // Get info from status buffer if present (no change if not present)
    hgets(st.buf, "BINDHOST", 80, up.bindhost);
    hgeti4(st.buf, "BINDPORT", &up.bindport);
    // Store bind host/port info etc in status buffer
    hputs(st.buf, "BINDHOST", up.bindhost);
    hputi4(st.buf, "BINDPORT", up.bindport);
    hputu4(st.buf, "CRCPKOK", 0);
    hputu4(st.buf, "CRCPKERR", 0);
    hputs(st.buf, status_key, "running");
    hashpipe_status_unlock_safe(&st);

    struct hashpipe_udp_packet p;

    /* Give all the threads a chance to start before opening network socket */
    sleep(1);


    /* Set up UDP socket */
    int rv = hashpipe_udp_init(&up);
    if (rv!=HASHPIPE_OK) {
        hashpipe_error("paper_crc_thread",
                "Error opening UDP socket.");
        pthread_exit(NULL);
    }
    pthread_cleanup_push((void *)hashpipe_udp_close, &up);

    /* Main loop */
    uint64_t packet_count = 0;
    uint64_t good_count = 0;
    uint64_t error_count = 0;
    uint64_t elapsed_wait_ns = 0;
    uint64_t elapsed_recv_ns = 0;
    uint64_t elapsed_proc_ns = 0;
    float ns_per_wait = 0.0;
    float ns_per_recv = 0.0;
    float ns_per_proc = 0.0;
    struct timespec start, stop;
    struct timespec recv_start, recv_stop;
    packet_header_t hdr;

    while (run_threads()) {

        /* Read packet */
	clock_gettime(CLOCK_MONOTONIC, &recv_start);
	do {
	    clock_gettime(CLOCK_MONOTONIC, &start);
	    p.packet_size = recv(up.sock, p.data, HASHPIPE_MAX_PACKET_SIZE, 0);
	    clock_gettime(CLOCK_MONOTONIC, &recv_stop);
	} while (p.packet_size == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && run_threads());

	// Break out of loop if stopping
	if(!run_threads()) break;

	// Increment packet count
	packet_count++;

	// Check CRC
        if(crc32(init_crc, (/*const?*/ uint8_t *)p.data, p.packet_size) == 0xffffffff) {
	    // CRC OK! Increment good counter
	    good_count++;
	} else {
	    // CRC error!  Increment error counter
	    error_count++;

	    // Log message
	    get_header(&p, &hdr);
	    hashpipe_warn("paper_crc", "CRC error mcnt %llu ; fid %u ; xid %u",
		    hdr.mcnt, hdr.fid, hdr.xid);
	}

	clock_gettime(CLOCK_MONOTONIC, &stop);
	elapsed_wait_ns += ELAPSED_NS(recv_start, start);
	elapsed_recv_ns += ELAPSED_NS(start, recv_stop);
	elapsed_proc_ns += ELAPSED_NS(recv_stop, stop);

        if(packet_count % 1000 == 0) {
	    // Compute stats
	    get_header(&p, &hdr);
            ns_per_wait = (float)elapsed_wait_ns / packet_count;
            ns_per_recv = (float)elapsed_recv_ns / packet_count;
            ns_per_proc = (float)elapsed_proc_ns / packet_count;

            // Update status
            hashpipe_status_lock_busywait_safe(&st);
            hputu8(st.buf, "CRCMCNT", hdr.mcnt);
	    // Gbps = bits_per_packet / ns_per_packet
	    // (N_BYTES_PER_PACKET excludes header, so +8 for the header)
            hputr4(st.buf, "CRCGBPS", 8*(N_BYTES_PER_PACKET+8)/(ns_per_recv+ns_per_proc));
            hputr4(st.buf, "CRCWATNS", ns_per_wait);
            hputr4(st.buf, "CRCRECNS", ns_per_recv);
            hputr4(st.buf, "CRCPRCNS", ns_per_proc);
	    // TODO Provide some way to recognize request to zero out the
	    // CRCERR and CRCOK fields.
	    hputu8(st.buf, "CRCPKOK",  good_count);
	    hputu8(st.buf, "CRCPKERR", error_count);
            hashpipe_status_unlock_safe(&st);

	    // Start new average
	    elapsed_wait_ns = 0;
	    elapsed_recv_ns = 0;
	    elapsed_proc_ns = 0;
	    packet_count = 0;
        }

        /* Will exit if thread has been cancelled */
        pthread_testcancel();
    }

    /* Have to close all push's */
    pthread_cleanup_pop(1); /* Closes push(hashpipe_udp_close) */

    return NULL;
}

static hashpipe_thread_desc_t crc_thread = {
    name: "paper_crc_thread",
    skey: "CRCSTAT",
    init: NULL,
    run:  run,
    ibuf_desc: {NULL},
示例#21
0
文件: blk_mt.c 项目: KaiZhang666/nvml
int
main(int argc, char *argv[])
{
	struct blk_arguments arguments;

	/* set the random seed value */
	srand(time(NULL));

	/* set default values */
	memset(&arguments, 0, sizeof (struct blk_arguments));
	arguments.block_size = 512;
	arguments.num_ops = 100;
	arguments.file_size = (PMEMBLK_MIN_POOL / 1024) / 1024;

	if (argp_parse(&argp, argc, argv, 0, 0, &arguments) != 0) {
		exit(1);
	}

	struct worker_info worker_params[arguments.thread_count];
	memset(worker_params, 0, sizeof (struct worker_info));

	/* set common values */
	worker_params[0].block_size = arguments.block_size;
	worker_params[0].num_ops = arguments.num_ops;
	worker_params[0].file_lanes = arguments.thread_count;

	/* file_size is provided in MB */
	unsigned long long file_size_bytes = arguments.file_size * 1024 * 1024;

	worker *thread_workers = NULL;

	/* prepare parameters specific for file/pmem */
	if (arguments.file_io) {
		/* prepare open flags */
		int flags = O_RDWR | O_CREAT | O_SYNC;
		/* create file on PMEM-aware file system */
		if ((worker_params[0].file_desc = open(arguments.file_path,
			flags, FILE_MODE)) < 0) {
			perror(arguments.file_path);
			exit(1);
		}

		/* pre-allocate file_size MB of persistent memory */
		if ((errno = posix_fallocate(worker_params[0].file_desc,
			(off_t)0, (off_t)file_size_bytes)) != 0) {
			warn("posix_fallocate");
			close(worker_params[0].file_desc);
			exit(1);
		}

		worker_params[0].num_blocks = file_size_bytes
				/ worker_params[0].block_size;
		thread_workers = file_workers;
	} else {
		worker_params[0].file_desc = -1;
		if (arguments.prep_blk_file) {
			if ((worker_params[0].handle = pmemblk_create(
				arguments.file_path,
				worker_params[0].block_size,
				(off_t)file_size_bytes, FILE_MODE)) == NULL) {
				err(1, "%s: pmemblk_open", argv[2]);
			}
		} else {
			if ((worker_params[0].handle = pmemblk_open(
					arguments.file_path,
					worker_params[0].block_size)) == NULL) {
				err(1, "%s: pmemblk_open", argv[2]);
			}

		}
		worker_params[0].num_blocks = pmemblk_nblock(
				worker_params[0].handle);
		thread_workers = pmem_workers;
	}

	/* propagate params to each info_t */
	for (int i = 1; i < arguments.thread_count; ++i) {
		memcpy(&worker_params[i], &worker_params[0],
				sizeof (struct worker_info));
		worker_params[i].thread_index = i;
		worker_params[i].seed = rand();
	}

	/* The blk mode file prep */
	if (arguments.prep_blk_file) {
		if (worker_params[0].file_desc >= 0)
			close(worker_params[0].file_desc);
		return run_threads(prep_worker, arguments.thread_count,
				worker_params);
	}

	struct measurements perf_meas;
	perf_meas.total_ops = arguments.thread_count
			* worker_params[0].num_ops;

	/* perform PMEMBLK warmup */
	if (!arguments.file_io) {
		if (run_threads(warmup_worker, arguments.thread_count,
				worker_params) != 0) {
			if (worker_params[0].file_desc >= 0)
				close(worker_params[0].file_desc);
			exit(1);
		}
	}

	for (int i = 0; i < WORKER_COUNT_MAX; ++i) {
		clock_gettime(CLOCK_MONOTONIC, &perf_meas.start_time);
		if (run_threads(thread_workers[i], arguments.thread_count,
				worker_params) != 0) {
			if (worker_params[0].file_desc >= 0)
				close(worker_params[0].file_desc);
			exit(1);
		}
		clock_gettime(CLOCK_MONOTONIC, &perf_meas.stop_time);

		calculate_stats(&perf_meas);
		printf("%f;%f;", perf_meas.total_run_time,
				perf_meas.ops_per_second);
	}

	printf("\n");

	if (worker_params[0].file_desc >= 0)
		close(worker_params[0].file_desc);

	/* cleanup and check pmem file */
	if (!arguments.file_io) {
		pmemblk_close(worker_params[0].handle);

		/* not really necessary, but check consistency */
		int result = pmemblk_check(arguments.file_path);
		if (result < 0) {
			warn("%s: pmemblk_check",
					arguments.file_path);
		} else if (result == 0) {
			warnx("%s: pmemblk_check: not consistent",
					arguments.file_path);
		}
	}

	exit(0);
}
示例#22
0
static void test_TDMB()
{
	int key, ret;
	int num_tbl;
	int i;
	unsigned int lock_mask, sub_ch_id, ch_freq_khz;
	E_RTV_COUNTRY_BAND_TYPE country_band_type; 
	IOCTL_TDMB_SUB_CH_INFO sub_ch_info;
	IOCTL_TDMB_SIGNAL_INFO dm_info;
//	BOOL power_on = FALSE;
	unsigned char fic_buf[384];
	char devname[32];	
	BOOL is_power_on = FALSE;
	
	num_tbl = sizeof(tdmb_korea_tbl) / sizeof(uint32_t);
	tv_mode = 1;

	sprintf(devname,"/dev/%s", RAONTV_DEV_NAME);
	fd_dmb_dev = open(devname, O_RDWR);
	if(fd_dmb_dev<0)
	{
		printf("Can't not open %s\n", devname);
		return;
	}

#if defined(RTV_IF_MPEG2_SERIAL_TSIF) || defined(RTV_IF_SPI_SLAVE) || defined(RTV_IF_QUALCOMM_TSIF) || defined(RTV_IF_MPEG2_PARALLEL_TSIF)
	sprintf(devname,"/dev/%s", "s3c-tsi");
	fd_tsif_dev = open(devname, O_RDWR);
	if(fd_tsif_dev<0)
	{
		printf("Can't not open %s\n",devname);
		return -1;
	}
#endif	

#ifdef  _TS_FILE_DUMP_ENABLE
	if((fd_tdmb_ts=fopen("./tdmb_ts.ts", "wb")) == NULL)
	{
		printf("tdmb_ts.ts file open error\n");
	}
#endif	

	tsif_run_flag = 0;

	if((ret=run_threads()) != 0)
	{
		printf("run_threads() failed: %d\n", ret);
	}

	while(1)
	{
		printf("===============================================\n");
		printf("\t0: TDMB Power ON\n");
		printf("\t1: TDMB Power OFF\n");
		printf("\t2: TDMB Scan freq\n");
		printf("\t3: TDMB Open Sub Channel\n");
		printf("\t4: TDMB Close Sub Channel\n");
		printf("\t5: TDMB Get Lockstatus\n");
		printf("\t6: TDMB Get Signal Info\n");
		printf("\t7: TDMB [TEST] Set Freq\n");
		printf("\t8: GPIO Write(Set) Test\n");
		printf("\t9: GPIO Read(Get) Test\n");
	
		printf("\tw: Write Reg\n");
		printf("\tr: Read Reg\n");
		printf("\ts: Stop TSIF\n");
		
		printf("\tq or Q: Quit\n");
		printf("===============================================\n");
   		
		//fflush(stdin);
		key = getc(stdin);				
		CLEAR_STDIN;
		
		switch( key )
		{
			case '0':
				printf("[T-DMB Power ON]\n");
			
				country_band_type = RTV_COUNTRY_BAND_KOREA;				
				if((ret=ioctl(fd_dmb_dev, IOCTL_TDMB_POWER_ON, &country_band_type)) < 0)
				{
					printf("IOCTL_TDMB_POWER_ON failed: %d\n", ret);
				}	
				is_power_on = TRUE;

#if 0
				////
				sub_ch_info.ch_freq_khz = 208736;
				sub_ch_info.sub_ch_id = 0;
				
				//sub_ch_info.ch_freq_khz = 184736;
				//sub_ch_info.sub_ch_id = 1;
				
				sub_ch_info.service_type = RTV_TDMB_SERVICE_VIDEO;
				if(ioctl(fd_dmb_dev, IOCTL_TDMB_OPEN_SUBCHANNEL, &sub_ch_info) < 0)
				{
					printf("IOCTL_TDMB_OPEN_SUBCHANNEL failed\n");
				}
				printf("\n");

//////////////////////////////////////test///////////////////////////////////////


#if 0
for(i=0;i < 400;i++)
{
/*
                            ioctl_register_access.Addr = 0x03;
			       ioctl_register_access.data[0] = 0x0f;
								
	 			if(ioctl(fd_dmb_dev, IOCTL_REGISTER_WRITE, &ioctl_register_access) < 0)
	 			{
	 				printf("IOCTL_REGISTER_WRITE failed\n");
	 			}			

*/								
				//ioctl_register_access.Addr = 0x00;
				
				if(ioctl(fd_dmb_dev, IOCTL_REGISTER_READ, &ioctl_register_access) < 0)
				{
					printf("IOCTL_REGISTER_READ failed\n");
				}

				printf("[%d] Address 0x%02x= 0x%02x\n", i, ioctl_register_access.Addr, ioctl_register_access.data[0]);				
				//printf("\n");	
	usleep(20000);
}
#endif
//////////////////////////////////////test///////////////////////////////////////			
#endif

				break;
				
			case '1':		
				printf("[T-DMB Power OFF]\n");
				if(ioctl(fd_dmb_dev, IOCTL_TDMB_POWER_OFF) < 0)
				{
					printf("IOCTL_TDMB_POWER_OFF failed\n");
				}	
				is_power_on = FALSE;
				break;

			case '2':
				printf("TDMB Scan freq\n");
				for(i=0; i<num_tbl; i++)
				{
					int k;
					
					printf("[TDMB Scan start] freq: %u\n", tdmb_korea_tbl[i]);

					if(ioctl(fd_dmb_dev, IOCTL_TDMB_SCAN_FREQ, &tdmb_korea_tbl[i]) < 0)
					{
						printf("scan failed on channel[%d]\n", tdmb_korea_tbl[i]);
					}	
					else
					{					
						// Add a channel to scaned list.
						printf("[TDMB Scan freq] CH DETECTED\n");	

						for(k=0; k<5; k++)
						{
							if((ret=ioctl(fd_dmb_dev, IOCTL_TDMB_READ_FIC, fic_buf)) < 0)
							{
								printf("read fic fail: %d\n", ret);
							}	
							else
							{
								printf("\tfic_buf[0]: 0x%02X, fic_buf[1]: 0x%02X, fic_buf[2]: 0x%02X\n", fic_buf[0], fic_buf[1], fic_buf[2]);
							}
						}		
					}

					printf("\n");
				}				
				break;

			case '3':
				printf("[T-DMB Open Sub Channel]\n");
				while(1)
				{
					printf("Input Channel freq(ex. 175280):");
					scanf("%u", &sub_ch_info.ch_freq_khz);   		
					CLEAR_STDIN;

					for(i=0; i<num_tbl; i++)
					{
						if(sub_ch_info.ch_freq_khz == tdmb_korea_tbl[i])
							goto call_tdmb_set_ch;
					}	

					if(i == num_tbl)
					{
						printf("Invalid T-DMB freq\n");
					}
				}
				
call_tdmb_set_ch	:
				printf("Input sub channel ID(ex. 0):");
				scanf("%u", &sub_ch_info.sub_ch_id);			
				CLEAR_STDIN;

				printf("Input service type(0: Video, 1:Audio, 2: Data):");
				scanf("%u", &sub_ch_info.service_type);			
				CLEAR_STDIN;

				if((ret=ioctl(fd_dmb_dev, IOCTL_TDMB_OPEN_SUBCHANNEL, &sub_ch_info)) < 0)
				{
					printf("IOCTL_TDMB_OPEN_SUBCHANNEL failed: %d\n", ret);
				}
				printf("\n");			
				break;

			case '4':
				printf("[TDMB Close Sub Channel]\n");
				
				printf("Input sub channel ID(ex. 0):");
				scanf("%u", &sub_ch_id);			
				CLEAR_STDIN;

				if(ioctl(fd_dmb_dev, IOCTL_TDMB_CLOSE_SUBCHANNEL, &sub_ch_id) < 0)
				{
					printf("IOCTL_TDMB_CLOSE_SUBCHANNEL failed\n");
				}
				printf("\n");			
				break;

			case '5':
				printf("[TDMB Get Lockstatus]\n");			
				if(ioctl(fd_dmb_dev, IOCTL_TDMB_GET_LOCK_STATUS, &lock_mask) < 0)
				{						
					printf("RTV_IOCTL_TDMB_GET_LOCK_STATUS failed\n");
				}

				printf("lock_mask = %d\n", lock_mask);			
				printf("\n");			
				break;

			case '6':
				printf("[TDMB Get Singal Info]\n");			
				if(ioctl(fd_dmb_dev, IOCTL_TDMB_GET_SIGNAL_INFO, &dm_info) < 0)
				{						
					printf("IOCTL_TDMB_GET_SIGNAL_INFO failed\n");
				}

				printf("ber = %f\n", (float)dm_info.ber/RTV_TDMB_BER_DIVIDER);
				printf("cer = %u\n", dm_info.cer);
				printf("cnr = %f\n", (float)dm_info.cnr/RTV_TDMB_CNR_DIVIDER);
				printf("rssi = %f\n", (float)dm_info.rssi/RTV_TDMB_RSSI_DIVIDER);
				printf("per = %u\n", dm_info.per);
				printf("\n");			
				break;

			case '7':
				printf("[T-DMB Set Freq]\n");
				while(1)
				{
					printf("Input Channel freq(ex. 175280):");
					scanf("%u", &ch_freq_khz);			
					CLEAR_STDIN;

					for(i=0; i<num_tbl; i++)
					{
						if(ch_freq_khz == tdmb_korea_tbl[i])
							goto call_tdmb_set_Freq;
					}	

					if(i == num_tbl)
					{
						printf("Invalid T-DMB freq\n");
					}
				}
				
call_tdmb_set_Freq	:
				if(ioctl(fd_dmb_dev, IOCTL_TEST_TDMB_SET_FREQ, &ch_freq_khz) < 0)
				{
					printf("IOCTL_TDMB_SET_FREQ failed\n");
				}
				printf("\n");			
				break;


			case '8':
				printf("[GPIO Write(Set) Test]\n");	

				printf("Select Pin Number:");
				scanf("%u" , &gpio_info.pin);	
				CLEAR_STDIN;

		retry_gpio_set:
				printf("Input Pin Level(0 or 1):");
				scanf("%u" , &gpio_info.value);	
				CLEAR_STDIN;
				if((gpio_info.value != 0) && (gpio_info.value != 1))
					goto retry_gpio_set;
				
				if(ioctl(fd_dmb_dev, IOCTL_TEST_GPIO_SET, &gpio_info) < 0)
				{						
					printf("IOCTL_TEST_GPIO_SET failed\n");
				}						
				break;

			case '9':
				printf("[GPIO Write(Set) Test]\n"); 
		
				printf("Select Pin Number:");
				scanf("%u" , &gpio_info.pin);	
				CLEAR_STDIN;

				if(ioctl(fd_dmb_dev, IOCTL_TEST_GPIO_GET, &gpio_info) < 0)
				{						
					printf("IOCTL_TEST_GPIO_GET failed\n");
				}		

				printf("Pin(%u): %u\n", gpio_info.pin, gpio_info.value);
				printf("\n");		
				break;
								
			case 'w':
				printf("[T-DMB] Register Write\n");
				printf("===============================================\n");
				printf("\t0: HOST_PAGE\n");
				printf("\t1: RF_PAGE\n");				
				printf("\t2: COMM_PAGE\n");
				printf("\t3: DD_PAGE\n");
				printf("\t4: MSC0_PAGE\n");
				printf("\t5: MSC1_PAGE\n");				
				printf("\t6: OFDM PAGE\n");
				printf("\t7: FEC_PAGE\n");
				printf("\t8: FIC_PAGE\n");
				printf("===============================================\n");
				
				printf("Select Page:");
				scanf("%x" , &ioctl_register_access.page);	
				CLEAR_STDIN;

				printf("Input Address(hex) :,  data(hex) : ");
				scanf("%x" , &ioctl_register_access.Addr);	
				CLEAR_STDIN;
				scanf("%x" , &ioctl_register_access.data[0]);
				CLEAR_STDIN;
				printf("Input Address: 0x%02x,  data: 0x%02x \n", ioctl_register_access.Addr, ioctl_register_access.data[0] );

				if(ioctl(fd_dmb_dev, IOCTL_REGISTER_WRITE, &ioctl_register_access) < 0)
				{
					printf("IOCTL_REGISTER_WRITE failed\n");
				}						
				break;
				
			case 'r':
				printf("[T-DMB] Register Read\n");
				printf("===============================================\n");
				printf("\t0: HOST_PAGE\n");
				printf("\t1: RF_PAGE\n");				
				printf("\t2: COMM_PAGE\n");
				printf("\t3: DD_PAGE\n");
				printf("\t4: MSC0_PAGE\n");
				printf("\t5: MSC1_PAGE\n");				
				printf("\t6: OFDM PAGE\n");
				printf("\t7: FEC_PAGE\n");
				printf("\t8: FIC_PAGE\n");
				printf("===============================================\n");
				
				printf("Select Page:");
				scanf("%x" , &ioctl_register_access.page);	
				CLEAR_STDIN;
				
				printf("Input Address(hex) : ");

				scanf("%x", &ioctl_register_access.Addr);
				CLEAR_STDIN;
				printf("Input Address: 0x%02x\n ", ioctl_register_access.Addr );

				if(ioctl(fd_dmb_dev, IOCTL_REGISTER_READ, &ioctl_register_access) < 0)
				{
					printf("IOCTL_REGISTER_READ failed\n");
				}

				printf("Address 0x%02x= 0x%02x\n",ioctl_register_access.Addr, ioctl_register_access.data[0]);				
				printf("\n");			
				break;

			case 's':
				break;

			case 'q':
			case 'Q':
				goto TDMB_EXIT;

			default:
				printf("[%c]\n", key);
		}
	} 

TDMB_EXIT:

#if 0
	
	exit_threads();

	//raise(SIGKILL);
//	raise(SIGUSR1);
#else
	if(is_power_on == TRUE)
	{
	//	printf("(TDMB_EXIT) IOCTL_TDMB_POWER_OFF\n");
		if(ioctl(fd_dmb_dev, IOCTL_TDMB_POWER_OFF) < 0)
		{
			printf("IOCTL_TDMB_POWER_OFF failed\n");
		}	
	}

	exit_threads();

#if defined(RTV_IF_MPEG2_SERIAL_TSIF) || defined(RTV_IF_SPI_SLAVE) || defined(RTV_IF_QUALCOMM_TSIF) || defined(RTV_IF_MPEG2_PARALLEL_TSIF)
	close(fd_tsif_dev);
#endif

//	printf("(TDMB_EXIT) close(fd_dmb_dev)\n");
	close(fd_dmb_dev);
//	printf("(TDMB_EXIT) close(fd_dmb_dev) END\n");

#ifdef _TS_FILE_DUMP_ENABLE
	fclose(fd_tdmb_ts);
#endif

#endif


	printf("TDMB_EXIT\n");
	
	return;
}
示例#23
0
文件: lab.cpp 项目: cscenter/hpcourse
int main() {
    std::cout << run_threads();
    return 0;
}
示例#24
0
// Run method for the thread
// It is meant to do the following:
// (1) Initialize status buffer
// (2) Set up network parameters and socket
// (3) Start main loop
//     (3a) Receive packet on socket
//     (3b) Error check packet (packet size, etc)
//     (3c) Call process_packet on received packet
// (4) Terminate thread cleanly
static void *run(hashpipe_thread_args_t * args) {

    fprintf(stdout, "N_INPUTS = %d\n", N_INPUTS);
    fprintf(stdout, "N_CHAN = %d\n", N_CHAN);
    fprintf(stdout, "N_CHAN_PER_X = %d\n", N_CHAN_PER_X);
    fprintf(stdout, "N_CHAN_PER_PACKET = %d\n", N_CHAN_PER_PACKET);
    fprintf(stdout, "N_TIME_PER_PACKET = %d\n", N_TIME_PER_PACKET);
    fprintf(stdout, "N_TIME_PER_BLOCK = %d\n", N_TIME_PER_BLOCK);
    fprintf(stdout, "N_BYTES_PER_BLOCK = %d\n", N_BYTES_PER_BLOCK);
    fprintf(stdout, "N_BYTES_PER_PACKET = %d\n", N_BYTES_PER_PACKET);
    fprintf(stdout, "N_PACKETS_PER_BLOCK = %d\n", N_PACKETS_PER_BLOCK);
    fprintf(stdout, "N_COR_MATRIX = %d\n", N_COR_MATRIX);

    // Local aliases to shorten access to args fields
    // Our output buffer happens to be a paper_input_databuf
    flag_input_databuf_t *db = (flag_input_databuf_t *)args->obuf;
    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

    st_p = &st;	// allow global (this source file) access to the status buffer

    /* Read network params */
    fprintf(stdout, "Setting up network parameters\n");
    struct hashpipe_udp_params up = {
	.bindhost = "0.0.0.0",
	.bindport = 8511,
	.packet_size = 8008
    };

    hashpipe_status_lock_safe(&st);
    	// Get info from status buffer if present (no change if not present)
    	hgets(st.buf, "BINDHOST", 80, up.bindhost);
    	hgeti4(st.buf, "BINDPORT", &up.bindport);
    
    	// Store bind host/port info etc in status buffer
    	hputs(st.buf, "BINDHOST", up.bindhost);
    	hputi4(st.buf, "BINDPORT", up.bindport);
    	hputu4(st.buf, "MISSEDFE", 0);
    	hputu4(st.buf, "MISSEDPK", 0);
    	hputs(st.buf, status_key, "running");
    hashpipe_status_unlock_safe(&st);

    struct hashpipe_udp_packet p;

    /* Give all the threads a chance to start before opening network socket */
    int netready = 0;
    int corready = 0;
    int checkready = 0;
    while (!netready) {
        sleep(1);
        // Check the correlator to see if it's ready yet
        hashpipe_status_lock_safe(&st);
        hgeti4(st.buf, "CORREADY",  &corready);
        hgeti4(st.buf, "SAVEREADY", &checkready);
        hashpipe_status_unlock_safe(&st);
        if (!corready) {
            continue;
        }
        //if (!checkready) {
        //    continue;
        //}

        // Check the other threads to see if they're ready yet
        // TBD

        // If we get here, then all threads are initialized
        netready = 1;
    }
    sleep(3);

    /* Set up UDP socket */
    fprintf(stderr, "NET: BINDHOST = %s\n", up.bindhost);
    fprintf(stderr, "NET: BINDPORT = %d\n", up.bindport);
    int rv = hashpipe_udp_init(&up);
    
    if (rv!=HASHPIPE_OK) {
        hashpipe_error("paper_net_thread",
                "Error opening UDP socket.");
        pthread_exit(NULL);
    }
    pthread_cleanup_push((void *)hashpipe_udp_close, &up);


    // Initialize first few blocks in the buffer
    int i;
    for (i = 0; i < 2; i++) {
        // Wait until block semaphore is free
        if (flag_input_databuf_wait_free(db, i) != HASHPIPE_OK) {
            if (errno == EINTR) { // Interrupt occurred
                hashpipe_error(__FUNCTION__, "waiting for free block interrupted\n");
                pthread_exit(NULL);
            } else {
                hashpipe_error(__FUNCTION__, "error waiting for free block\n");
                pthread_exit(NULL);
            }
        }
        initialize_block(db, i*Nm);
    }


    // Set correlator to "start" state
    hashpipe_status_lock_safe(&st);
    hputs(st.buf, "INTSTAT", "start");
    hashpipe_status_unlock_safe(&st);

    /* Main loop */
    uint64_t packet_count = 0;

    fprintf(stdout, "Net: Starting Thread!\n");
    
    while (run_threads()) {
        // Get packet
	do {
	    p.packet_size = recv(up.sock, p.data, HASHPIPE_MAX_PACKET_SIZE, 0);
	} while (p.packet_size == -1 && (errno == EAGAIN || errno == EWOULDBLOCK) && run_threads());
	if(!run_threads()) break;
        
        if (up.packet_size != p.packet_size && up.packet_size != p.packet_size-8) {
	    // If an error was returned instead of a valid packet size
            if (p.packet_size == -1) {
                fprintf(stderr, "uh oh!\n");
		// Log error and exit
                hashpipe_error("paper_net_thread",
                        "hashpipe_udp_recv returned error");
                perror("hashpipe_udp_recv");
                pthread_exit(NULL);
            } else {
		// Log warning and ignore wrongly sized packet
                hashpipe_warn("paper_net_thread", "Incorrect pkt size (%d)", p.packet_size);
                continue;
            }
	}
	packet_count++;
        process_packet(db, &p);

        /* Will exit if thread has been cancelled */
        pthread_testcancel();
    }

    pthread_cleanup_pop(1); /* Closes push(hashpipe_udp_close) */

    hashpipe_status_lock_busywait_safe(&st);
    hputs(st.buf, status_key, "terminated");
    hashpipe_status_unlock_safe(&st);
    return NULL;
}


static hashpipe_thread_desc_t net_thread = {
    name: "flag_net_thread",
    skey: "NETSTAT",
    init: NULL,
    run:  run,
    ibuf_desc: {NULL},
示例#25
0
int main(){

    std::cout << run_threads() << std::endl;

    return 0;
}
示例#26
0
文件: vmem_mt.c 项目: mdalecki/nvml
/*
 * main -- entry point, initializes allocated_mem and runs the tasks
 */
int
main(int argc, char *argv[])
{
	int i, fails = 0;
	double task_duration;
	void **arg = NULL;
	uint64_t pool_size;
	arguments_t arguments;
	int per_thread_args = 0;
	const int min_pool_size = 200;
	arguments.pool_per_thread = 0;
	arguments.allocator = ALLOCATOR_VMEM;
	arguments.dir_path = NULL;
	if (argp_parse(&argp, argc, argv, 0, 0, &arguments)) {
		fprintf(stderr, "argp_parse error");
		return EXIT_FAILURE;
	}
	int pools_count = arguments.pool_per_thread ?
			arguments.thread_count : 1;
	VMEM *pools[pools_count];
	void *pools_data[pools_count];
	allocated_mem = calloc(arguments.ops_count, sizeof (void*));

	if (allocated_mem == NULL) {
		perror("calloc");
		return EXIT_FAILURE;
	}

	if (arguments.allocator == ALLOCATOR_VMEM) {
		if (arguments.pool_per_thread &&
			arguments.thread_count > MAX_THREADS) {
			fprintf(stderr, "Maximum allowed thread count"
				" with pool per thread option enabled is %u\n",
				MAX_THREADS);
			return EXIT_FAILURE;
		}

		pools_count = arguments.pool_per_thread ?
			arguments.thread_count : 1;
		per_thread_args = arguments.pool_per_thread;
		pool_size = arguments.ops_count *
			arguments.allocation_size_max * 2u;

		pool_size /= pools_count;

		if (pool_size < min_pool_size * MB) {
			pool_size = min_pool_size * MB;
		}
		for (i = 0; i < pools_count; ++i) {
			if (arguments.dir_path == NULL) {
				pools_data[i] = malloc(pool_size);
				if (pools_data[i] == NULL) {
					free(allocated_mem);
					perror("malloc");
					return EXIT_FAILURE;
				}
				/* suppress valgrind warnings */
				memset(pools_data[i], 0xFF, pool_size);
				pools[i] = vmem_pool_create_in_region(
						pools_data[i], pool_size);
			} else {
				pools[i] = vmem_pool_create(arguments.dir_path,
						pool_size);
			}
			if (pools[i] == NULL) {
				perror("vmem_pool_create");
				free(allocated_mem);
				return EXIT_FAILURE;
			}
		}
		arg = (void **)pools;
	}

	/* Cache warmup. */
	for (i = 0; i < MAX_TASK; ++i) {
		fails += run_threads(&arguments, tasks[i],
			per_thread_args, arg, &task_duration);
	}

	for (i = 0; i < MAX_TASK; ++i) {
		fails += run_threads(&arguments, tasks[i],
			per_thread_args, arg, &task_duration);
		printf("%f;%f;",
			task_duration, arguments.ops_count/task_duration);
	}

	printf("\n");

	if (arguments.allocator == ALLOCATOR_VMEM) {
		for (i = 0; i < pools_count; ++i) {
			vmem_pool_delete(pools[i]);
			if (arguments.dir_path == NULL) {
				free(pools_data[i]);
			}
		}
	}

	free(allocated_mem);

	return (fails == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
示例#27
0
static void test_ISDBT(void)
{
	int key, ret;
	E_RTV_COUNTRY_BAND_TYPE country_band_type; 
	RTV_ISDBT_TMCC_INFO tmcc_info;
	IOCTL_ISDBT_SIGNAL_INFO dm_info;
	int num_tbl;
	int i;
	int ch;
	unsigned int lock_mask;
	char devname[32];

	tv_mode = 0;
	
	num_tbl = sizeof(gtISDBTFreqTable) / sizeof(TISDBTFREQ);

	sprintf(devname,"/dev/%s", RAONTV_DEV_NAME);
	fd_dmb_dev = open(devname, O_RDWR);
	if(fd_dmb_dev<0)
	{
		printf("Can't not open %s\n", devname);
		return;
	}

#if defined(RTV_IF_MPEG2_SERIAL_TSIF) || defined(RTV_IF_SPI_SLAVE) || defined(RTV_IF_QUALCOMM_TSIF) || defined(RTV_IF_MPEG2_PARALLEL_TSIF)
	sprintf(devname,"/dev/%s", "s3c-tsi");
	fd_tsif_dev = open(devname, O_RDWR);
	if(fd_tsif_dev<0)
	{
		printf("Can't not open %s\n",devname);
		return -1;
	}
#endif	

#ifdef  _TS_FILE_DUMP_ENABLE
	if((fd_isdbt_ts=fopen("./isdbt_ts.ts", "wb")) == NULL)
	{
		printf("isdbt_ts.ts file open error\n");
	}
#endif	

	tsif_run_flag = 0;

	
	while(1)
	{
		printf("===============================================\n");
		printf("\t0: 1seg Power ON\n");
		printf("\t1: 1seg Power OFF\n");
		printf("\t2: 1seg Scan freq\n");
		printf("\t3: 1seg Set Channel\n");
		printf("\t4: 1seg Get Lockstatus\n");
		printf("\t5: 1seg Get TMCC\n");
		printf("\t6: 1seg Get Signal Info\n");
		printf("\t7: 1seg Start TS\n");
		printf("\t8: 1seg Stop TS\n");
		
		printf("\tw: Write Reg\n");
		printf("\tr: Read Reg\n");
		
		printf("\tq or Q: Quit\n");
		printf("===============================================\n");
   		
		fflush(stdin);
		key = getc(stdin);				
		CLEAR_STDIN;
		
		switch( key )
		{
			case '0':
				printf("[ISDBT DTV Start]\n");

				if((ret=run_threads()) != 0)
				{
					printf("run_threads() failed: %d\n", ret);
				}
				
				country_band_type = RTV_COUNTRY_BAND_JAPAN;
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_POWER_ON, &country_band_type) != 0)
				{
					printf("IOCTL_ISDBT_POWER_ON error");
				}

	#if 0
				ch = 37;
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_SET_FREQ, &ch) < 0)
				{
					// scan fail
					printf("IOCTL_ISDBT_SET_FREQ failed\n");
				}	

				sleep(3);
				printf("After sleep()\n");

				ch = 37;
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_SET_FREQ, &ch) < 0)
				{
					// scan fail
					printf("IOCTL_ISDBT_SET_FREQ failed\n");
				}	
	#endif
				break;

			case '1':
				printf("[ISDBT DTV Stop]\n");
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_POWER_OFF) != 0)
				{
					printf("IOCTL_ISDBT_POWER_OFF error");
				}
				break;
		
			case '2':
				for(i=0; i<num_tbl; i++)
				{
					printf("[ISDB-T Scan start] (ch: %u), freq: %u\n", gtISDBTFreqTable[i].ch, gtISDBTFreqTable[i].freq);

					if(ioctl(fd_dmb_dev, IOCTL_ISDBT_SCAN_FREQ, &gtISDBTFreqTable[i].ch) < 0)
					{
						printf("scan failed on channel[%d]\n",gtISDBTFreqTable[i].ch);
					}		
					
					// Add a channel to scaned list.

					printf("\n");
				}				
				break;

			case '3':

				printf("Input Channel num(ex.13):");
				scanf("%d",&ch);
				CLEAR_STDIN;
				printf("[ISDBT Set Freq] (ch: %u)\n", ch);

#if defined(RTV_IF_MPEG2_SERIAL_TSIF) || defined(RTV_IF_SPI_SLAVE) || defined(RTV_IF_QUALCOMM_TSIF) || defined(RTV_IF_MPEG2_PARALLEL_TSIF)
		   		if(tsif_run_flag != 1)
					tsif_run(1); /*  Run TSI */
#endif

				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_SET_FREQ, &ch) < 0)
				{
					// scan fail
					printf("IOCTL_ISDBT_SET_FREQ failed\n");
				}								
				printf("\n");
				break;

			case '4':
				printf("[ISDB-T Get Lockstatus]\n");
				
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_GET_LOCK_STATUS, &lock_mask) < 0)
				{
					printf("IOCTL_ISDBT_GET_LOCK_STATUS failed\n");
				}

				printf("isdbt_lock_mask = %d\n", lock_mask);
				
				printf("\n");			
				break;

			case '5':
				printf("[ISDB-T Get Tmcc]\n");				
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_GET_TMCC, &tmcc_info) < 0)
				{
					printf("IOCTL_ISDBT_GET_TMCC failed\n");
				}

				printf("tmcc_info.eCodeRate = %d\n", tmcc_info.eCodeRate);
				printf("tmcc_info.eGuard = %d\n", tmcc_info.eGuard);
				printf("tmcc_info.eInterlv = %d\n", tmcc_info.eInterlv);
				printf("tmcc_info.eModulation = %d\n", tmcc_info.eModulation);
				printf("tmcc_info.eSeg = %d\n", tmcc_info.eSeg);
				printf("tmcc_info.eTvMode = %d\n", tmcc_info.eTvMode);
				printf("tmcc_info.fEWS = %d\n", tmcc_info.fEWS);
				
				printf("\n");			
				break;

			case '6':
				printf("[ISDB-T Get Singal Info]\n");			
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_GET_SIGNAL_INFO, &dm_info) < 0)
				{						
					printf("IOCTL_ISDBT_GET_SIGNAL_INFO failed\n");
				}

				printf("ber = %f\n", (float)dm_info.ber/(float)RTV_ISDBT_BER_DIVIDER);
				printf("cnr = %f\n", (float)dm_info.cnr/(float)RTV_ISDBT_CNR_DIVIDER);
				printf("rssi = %f\n", (float)dm_info.rssi/(float)RTV_ISDBT_RSSI_DIVIDER);
				printf("per = %u\n", dm_info.per);
				printf("\n");			
				break;

			case '7':
				printf("[ISDBT Start TS]\n");				
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_START_TS) != 0)
				{
					printf("IOCTL_ISDBT_START_TS error");
				}
				break;
				
			case '8':
				printf("[ISDBT Start TS]\n");				
				if(ioctl(fd_dmb_dev, IOCTL_ISDBT_STOP_TS) != 0)
				{
					printf("IOCTL_ISDBT_STOP_TS error");
				}
				break;

			case 'w':
				printf("[ISDB-T Register Write\n");
				printf("===============================================\n");
				printf("\t0: HOST_PAGE\n");
				printf("\t1: RF_PAGE\n");				
				printf("\t2: COMM_PAGE\n");
				printf("\t3: DD_PAGE\n");
				printf("\t4: MSC0_PAGE\n");
				printf("\t5: MSC1_PAGE\n");				
				printf("\t6: OFDM PAGE\n");
				printf("\t7: FEC_PAGE\n");
				printf("===============================================\n");
				
				printf("Select Page:");
				scanf("%x" , &ioctl_register_access.page);	
				CLEAR_STDIN;

				printf("Input Address(hex) :,  data(hex) : ");
				scanf("%x" , &ioctl_register_access.Addr);	
				CLEAR_STDIN;
				scanf("%x" , &ioctl_register_access.data[0]);
				CLEAR_STDIN;
				printf("Input Address: 0x%02x,  data: 0x%02x \n", ioctl_register_access.Addr, ioctl_register_access.data[0] );

				if(ioctl(fd_dmb_dev, IOCTL_REGISTER_WRITE, &ioctl_register_access) < 0)
				{
					printf("IOCTL_REGISTER_WRITE failed\n");
				}			
				
				break;
				
			case 'r':
				printf("[ISDB-T Register Read\n");
				printf("===============================================\n");
				printf("\t0: HOST_PAGE\n");
				printf("\t1: RF_PAGE\n");				
				printf("\t2: COMM_PAGE\n");
				printf("\t3: DD_PAGE\n");
				printf("\t4: MSC0_PAGE\n");
				printf("\t5: MSC1_PAGE\n");				
				printf("\t6: OFDM PAGE\n");
				printf("\t7: FEC_PAGE\n");
				printf("===============================================\n");
				
				printf("Select Page:");
				scanf("%x" , &ioctl_register_access.page);	
				CLEAR_STDIN;
				
				printf("Input Address(hex) : ");

				scanf("%x", &ioctl_register_access.Addr);
				CLEAR_STDIN;
				
				printf("Input Address: 0x%02x\n ", ioctl_register_access.Addr );
		
				if(ioctl(fd_dmb_dev, IOCTL_REGISTER_READ, &ioctl_register_access) < 0)
				{
					printf("IOCTL_REGISTER_READ failed\n");
				}

				printf("Address 0x%02x= 0x%02x\n",ioctl_register_access.Addr, ioctl_register_access.data[0]);
				
				printf("\n");			
				break;
				
			case 'q':
			case 'Q':
				goto ISDBT_EXIT;

			default:
				printf("[%c]\n", key);
		}
	} 

ISDBT_EXIT:

	if(ioctl(fd_dmb_dev, IOCTL_TDMB_POWER_OFF) < 0)
	{
		printf("IOCTL_TDMB_POWER_OFF failed\n");
	}	

#if defined(RTV_IF_MPEG2_SERIAL_TSIF) || defined(RTV_IF_SPI_SLAVE) || defined(RTV_IF_QUALCOMM_TSIF) || defined(RTV_IF_MPEG2_PARALLEL_TSIF)
	tsif_run(0); /*  Stop TSI */
	close(fd_tsif_dev);
#endif

	close(fd_dmb_dev);

	exit_threads();

#ifdef _TS_FILE_DUMP_ENABLE
	fclose(fd_isdbt_ts);
#endif


	return;	
}
示例#28
0
// Run method for the thread
static void *run(hashpipe_thread_args_t * args) {

    // Local aliases to shorten access to args fields
    // Our output buffer happens to be a paper_input_databuf
    grating_input_databuf_t *db_in = (grating_input_databuf_t *)args->ibuf;
    grating_gpu_input_databuf_t * db_out = (grating_gpu_input_databuf_t *)args->obuf;

    hashpipe_status_t st = args->st;
    const char * status_key = args->thread_desc->skey;

    st_p = &st;	// allow global (this source file) access to the status buffer

    // Set thread to "start" state
    hashpipe_status_lock_safe(&st);
    hputs(st.buf, "TRANREADY", "start");
    hashpipe_status_unlock_safe(&st);

    int rv;
    int curblock_in = 0;
    int curblock_out = 0;
    int mcnt;

    fprintf(stdout, "Tra: Starting Thread!\n");
    
    while (run_threads()) {
        while ((rv=grating_input_databuf_wait_filled(db_in, curblock_in)) != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "waiting for filled block");
                hashpipe_status_unlock_safe(&st);
            }
            else {
                hashpipe_error(__FUNCTION__, "error waiting for filled databuf block");
                pthread_exit(NULL);
                break;
            }
        }
        while ((rv=grating_gpu_input_databuf_wait_free(db_out, curblock_out)) != HASHPIPE_OK) {
            if (rv==HASHPIPE_TIMEOUT) {
                hashpipe_status_lock_safe(&st);
                hputs(st.buf, status_key, "waiting for free block");
                hashpipe_status_unlock_safe(&st);
            }
            else {
                hashpipe_error(__FUNCTION__, "error waiting for free databuf block");
                pthread_exit(NULL);
                break;
            }
        }
        mcnt = db_in->block[curblock_in].header.mcnt_start;

        int m;
        int f;
        int t;
        int c;
        uint64_t * in_p;
        uint64_t * out_p;
        uint64_t * block_in_p  = db_in->block[curblock_in].data;
        uint64_t * block_out_p = db_out->block[curblock_out].data;
        for (m = 0; m < Nm; m++) {
            for (t = 0; t < Nt; t++) {
                for (f = 0; f < Nf; f++) {
                    for (c = 0; c < Nc; c++) {
                        in_p = block_in_p + grating_input_databuf_idx(m,f,t,c);
                        out_p = block_out_p + grating_gpu_input_databuf_idx(m,f,t,c);
                        memcpy(out_p, in_p, 128/8);
                    }
                }
            }
        }
        
        db_out->block[curblock_out].header.mcnt = mcnt;

        grating_gpu_input_databuf_set_filled(db_out, curblock_out);
        curblock_out = (curblock_out + 1) % db_out->header.n_block;

        grating_input_databuf_set_free(db_in, curblock_in);
        curblock_in = (curblock_in + 1) % db_in->header.n_block;

        /* Will exit if thread has been cancelled */
        pthread_testcancel();
    }

    return NULL;
}