示例#1
0
/*
 * _prop_object_internalize_map_file --
 *	Map a file for the purpose of internalizing it.
 */
struct _prop_object_internalize_mapped_file *
_prop_object_internalize_map_file(const char *fname)
{
	struct stat sb;
	struct _prop_object_internalize_mapped_file *mf;
	size_t pgsize = (size_t)sysconf(_SC_PAGESIZE);
	size_t pgmask = pgsize - 1;
	bool need_guard = false;
	int fd;

	mf = _PROP_MALLOC(sizeof(*mf), M_TEMP);
	if (mf == NULL)
		return (NULL);
	
	fd = open(fname, O_RDONLY, 0400);
	if (fd == -1) {
		_PROP_FREE(mf, M_TEMP);
		return (NULL);
	}

	if (fstat(fd, &sb) == -1) {
		(void) close(fd);
		_PROP_FREE(mf, M_TEMP);
		return (NULL);
	}
	mf->poimf_mapsize = ((size_t)sb.st_size + pgmask) & ~pgmask;
	if (mf->poimf_mapsize < (size_t)sb.st_size) {
		(void) close(fd);
		_PROP_FREE(mf, M_TEMP);
		return (NULL);
	}

	/*
	 * If the file length is an integral number of pages, then we
	 * need to map a guard page at the end in order to provide the
	 * necessary NUL-termination of the buffer.
	 */
	if ((sb.st_size & pgmask) == 0)
		need_guard = true;

	mf->poimf_xml = mmap(NULL, need_guard ? mf->poimf_mapsize + pgsize
			    		      : mf->poimf_mapsize,
			    PROT_READ, MAP_FILE|MAP_SHARED, fd, (off_t)0);
	(void) close(fd);
	if (mf->poimf_xml == MAP_FAILED) {
		_PROP_FREE(mf, M_TEMP);
		return (NULL);
	}
	(void) madvise(mf->poimf_xml, mf->poimf_mapsize, MADV_SEQUENTIAL);

	if (need_guard) {
		if (mmap(mf->poimf_xml + mf->poimf_mapsize,
			 pgsize, PROT_READ,
			 MAP_ANON|MAP_PRIVATE|MAP_FIXED, -1,
			 (off_t)0) == MAP_FAILED) {
			(void) munmap(mf->poimf_xml, mf->poimf_mapsize);
			_PROP_FREE(mf, M_TEMP);
			return (NULL);
		}
		mf->poimf_mapsize += pgsize;
	}

	return (mf);
}
示例#2
0
static inline size_t
page_align(size_t size)
{
	size_t page_size = sysconf(_SC_PAGE_SIZE);
	return (size + page_size - 1) & ~(page_size - 1);
}
示例#3
0
void create_same_memory(int size, int num, int unit)
{
	char buf[BUFSIZ];
	int i, j, k;
	int status;
	int *child;
	long ps, pages;

	ps = sysconf(_SC_PAGE_SIZE);
	pages = 1024 * 1024 / ps;

	child = malloc(num);
	if (child == NULL)
		tst_brkm(TBROK | TERRNO, cleanup, "malloc");

	memory = malloc(num * sizeof(**memory));
	if (memory == NULL)
		tst_brkm(TBROK | TERRNO, cleanup, "malloc");

	/* Don't call cleanup in those children. Instead, do a cleanup from the
	   parent after fetched children's status. */
	switch (child[0] = fork()) {
	case -1:
		tst_brkm(TBROK | TERRNO, cleanup, "fork");
	case 0:
		tst_resm(TINFO, "child 0 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");

		tst_resm(TINFO, "child 0 continues...");
		tst_resm(TINFO, "child 0 allocates %d MB filled with 'c'.",
			 size);
		memory[0] = malloc(size / unit * sizeof(*memory));
		if (memory[0] == NULL)
			tst_brkm(TBROK | TERRNO, tst_exit, "malloc");
		for (j = 0; j * unit < size; j++) {
			memory[0][j] = mmap(NULL, unit * MB,
					    PROT_READ | PROT_WRITE,
					    MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
			if (memory[0][j] == MAP_FAILED)
				tst_brkm(TBROK | TERRNO, tst_exit, "mmap");

#ifdef HAVE_MADV_MERGEABLE
			if (madvise(memory[0][j], unit * MB, MADV_MERGEABLE)
			    == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "madvise");
#endif
			for (i = 0; i < unit * MB; i++)
				memory[0][j][i] = 'c';
		}
		tst_resm(TINFO, "child 0 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");

		tst_resm(TINFO, "child 0 continues...");
		_verify('c', 0, 0, size / unit, 0, unit * MB);
		tst_resm(TINFO, "child 0 changes memory content to 'd'.");
		for (j = 0; j < size / unit; j++) {
			for (i = 0; i < unit * MB; i++)
				memory[0][j][i] = 'd';
		}
		/* Unmerge. */
		tst_resm(TINFO, "child 0 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");

		tst_resm(TINFO, "child 0 continues...");
		_verify('d', 0, 0, size / unit, 0, unit * MB);
		/* Stop. */
		tst_resm(TINFO, "child 0 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 0 continues...");
		exit(0);
	}
	switch (child[1] = fork()) {
	case -1:
		tst_brkm(TBROK | TERRNO, cleanup, "fork");
	case 0:
		tst_resm(TINFO, "child 1 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 1 continues...");
		tst_resm(TINFO, "child 1 allocates %d MB filled with 'a'.",
			 size);
		memory[1] = malloc(size / unit * sizeof(*memory));
		if (memory[1] == NULL)
			tst_brkm(TBROK | TERRNO, tst_exit, "malloc");
		for (j = 0; j < size / unit; j++) {
			memory[1][j] = mmap(NULL, unit * MB,
					    PROT_READ | PROT_WRITE,
					    MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
			if (memory[1][j] == MAP_FAILED)
				tst_brkm(TBROK | TERRNO, tst_exit, "mmap");
#ifdef HAVE_MADV_MERGEABLE
			if (madvise(memory[1][j], unit * MB, MADV_MERGEABLE)
			    == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "madvise");
#endif
			for (i = 0; i < unit * MB; i++)
				memory[1][j][i] = 'a';
		}
		tst_resm(TINFO, "child 1 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 1 continues...");
		_verify('a', 1, 0, size / unit, 0, unit * MB);
		tst_resm(TINFO, "child 1 changes memory content to 'b'.");
		for (j = 0; j < size / unit; j++) {
			for (i = 0; i < unit * MB; i++)
				memory[1][j][i] = 'b';
		}
		tst_resm(TINFO, "child 1 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 1 continues...");
		_verify('b', 1, 0, size / unit, 0, unit * MB);
		tst_resm(TINFO, "child 1 changes memory content to 'd'");
		for (j = 0; j < size / unit; j++) {
			for (i = 0; i < unit * MB; i++)
				memory[1][j][i] = 'd';
		}
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");

		tst_resm(TINFO, "child 1 continues...");
		_verify('d', 1, 0, size / unit, 0, unit * MB);
		tst_resm(TINFO, "child 1 changes one page to 'e'.");
		memory[1][size / unit - 1][unit * MB - 1] = 'e';

		/* Unmerge. */
		tst_resm(TINFO, "child 1 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 1 continues...");
		_verify('e', 1, size / unit - 1, size / unit,
			unit * MB - 1, unit * MB);
		_verify('d', 1, 0, size / unit - 1, 0, unit * MB - 1);

		/* Stop. */
		tst_resm(TINFO, "child 1 stops.");
		if (raise(SIGSTOP) == -1)
			tst_brkm(TBROK | TERRNO, tst_exit, "kill");
		tst_resm(TINFO, "child 1 continues...");
		exit(0);
	}
	for (k = 2; k < num; k++) {
		switch (child[k] = fork()) {
		case -1:
			tst_brkm(TBROK | TERRNO, cleanup, "fork");
		case 0:
			tst_resm(TINFO, "child %d stops.", k);
			if (raise(SIGSTOP) == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "kill");
			tst_resm(TINFO, "child %d continues...", k);
			tst_resm(TINFO, "child %d allocates %d "
				 "MB filled with 'a'.", k, size);
			memory[k] = malloc(size / unit * sizeof(*memory));
			if (memory[k] == NULL)
				tst_brkm(TBROK | TERRNO, tst_exit, "malloc");
			for (j = 0; j < size / unit; j++) {
				memory[k][j] = mmap(NULL, unit * MB,
						    PROT_READ | PROT_WRITE,
						    MAP_ANONYMOUS
						    | MAP_PRIVATE, -1, 0);
				if (memory[k][j] == MAP_FAILED)
					tst_brkm(TBROK | TERRNO, cleanup,
						 "mmap");
#ifdef HAVE_MADV_MERGEABLE
				if (madvise(memory[k][j], unit * MB,
					    MADV_MERGEABLE) == -1)
					tst_brkm(TBROK | TERRNO, cleanup,
						 "madvise");
#endif
				for (i = 0; i < unit * MB; i++)
					memory[k][j][i] = 'a';
			}
			tst_resm(TINFO, "child %d stops.", k);
			if (raise(SIGSTOP) == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "kill");
			tst_resm(TINFO, "child %d continues...", k);
			tst_resm(TINFO, "child %d changes memory content to "
				 "'d'", k);
			for (j = 0; j < size / unit; j++) {
				for (i = 0; i < unit * MB; i++)
					memory[k][j][i] = 'd';
			}
			/* Unmerge. */
			tst_resm(TINFO, "child %d stops.", k);
			if (raise(SIGSTOP) == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "kill");
			tst_resm(TINFO, "child %d continues...", k);

			/* Stop. */
			tst_resm(TINFO, "child %d stops.", k);
			if (raise(SIGSTOP) == -1)
				tst_brkm(TBROK | TERRNO, tst_exit, "kill");
			tst_resm(TINFO, "child %d continues...", k);
			exit(0);
		}
	}
	tst_resm(TINFO, "KSM merging...");
	write_file(PATH_KSM "run", "1");
	snprintf(buf, BUFSIZ, "%ld", size * pages * num);
	write_file(PATH_KSM "pages_to_scan", buf);
	write_file(PATH_KSM "sleep_millisecs", "0");

	tst_resm(TINFO, "wait for all children to stop.");
	for (k = 0; k < num; k++) {
		if (waitpid(child[k], &status, WUNTRACED) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
		if (!WIFSTOPPED(status))
			tst_brkm(TBROK, cleanup, "child %d was not stopped.",
				 k);
	}
	tst_resm(TINFO, "resume all children.");
	for (k = 0; k < num; k++) {
		if (kill(child[k], SIGCONT) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "kill child[%d]", k);
	}
	_group_check(1, 2, size * num * pages - 2, 0, 0, 0, size * pages * num);

	tst_resm(TINFO, "wait for child 1 to stop.");
	if (waitpid(child[1], &status, WUNTRACED) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
	if (!WIFSTOPPED(status))
		tst_brkm(TBROK, cleanup, "child 1 was not stopped.");

	/* Child 1 changes all pages to 'b'. */
	tst_resm(TINFO, "resume child 1.");
	if (kill(child[1], SIGCONT) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "kill");
	_group_check(1, 3, size * num * pages - 3, 0, 0, 0, size * pages * num);

	tst_resm(TINFO, "wait for child 1 to stop.");
	if (waitpid(child[1], &status, WUNTRACED) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
	if (!WIFSTOPPED(status))
		tst_brkm(TBROK, cleanup, "child 1 was not stopped.");

	/* All children change pages to 'd'. */
	tst_resm(TINFO, "resume all children.");
	for (k = 0; k < num; k++) {
		if (kill(child[k], SIGCONT) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "kill child[%d]", k);
	}
	_group_check(1, 1, size * num * pages - 1, 0, 0, 0, size * pages * num);

	tst_resm(TINFO, "wait for all children to stop.");
	for (k = 0; k < num; k++) {
		if (waitpid(child[k], &status, WUNTRACED) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
		if (!WIFSTOPPED(status))
			tst_brkm(TBROK, cleanup, "child %d was not stopped.",
				 k);
	}
	/* Child 1 changes pages to 'e'. */
	tst_resm(TINFO, "resume child 1.");
	if (kill(child[1], SIGCONT) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "kill");
	_group_check(1, 1, size * num * pages - 2, 0, 1, 0, size * pages * num);

	tst_resm(TINFO, "wait for child 1 to stop.");
	if (waitpid(child[1], &status, WUNTRACED) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
	if (!WIFSTOPPED(status))
		tst_brkm(TBROK, cleanup, "child 1 was not stopped.");

	tst_resm(TINFO, "resume all children.");
	for (k = 0; k < num; k++) {
		if (kill(child[k], SIGCONT) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "kill child[%d]", k);
	}
	tst_resm(TINFO, "KSM unmerging...");
	write_file(PATH_KSM "run", "2");
	_group_check(2, 0, 0, 0, 0, 0, size * pages * num);

	tst_resm(TINFO, "wait for all children to stop.");
	for (k = 0; k < num; k++) {
		if (waitpid(child[k], &status, WUNTRACED) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "waitpid");
		if (!WIFSTOPPED(status))
			tst_brkm(TBROK, cleanup, "child %d was not stopped.",
				 k);
	}
	tst_resm(TINFO, "resume all children.");
	for (k = 0; k < num; k++) {
		if (kill(child[k], SIGCONT) == -1)
			tst_brkm(TBROK | TERRNO, cleanup, "kill child[%d]", k);
	}
	tst_resm(TINFO, "stop KSM.");
	write_file(PATH_KSM "run", "0");
	_group_check(0, 0, 0, 0, 0, 0, size * pages * num);
	while (waitpid(-1, &status, WUNTRACED | WCONTINUED) > 0)
		if (WEXITSTATUS(status) != 0)
			tst_resm(TFAIL, "child exit status is %d",
				 WEXITSTATUS(status));
}
示例#4
0
int main(void)
{
  char c;
  int err, shmid;
  char *shm, *s;
  long pgsz;

  if ((pgsz = sysconf(_SC_PAGESIZE)) == -1) {
    perror("sysconf");
    abort();
  } else if (pgsz != PGSIZE) {
    fprintf(stderr, "Unsupported page size! (%ld)\n", pgsz);
    abort();
  }

  /*
   * Open shared memory fd.
   */
  shmid = fd_file();

  /*
   * Size the segment.
   */
  if (ftruncate(shmid, SHMSZ) < 0) {
    perror("ftruncate");
    abort();
  }

  /*
   * Map into address space.
   */
  if ((shm = mmap(BASEADR, SHMSZ,
                  PROT_READ | PROT_WRITE,
                  MAP_FILE | MAP_SHARED | MAP_FIXED,
                  shmid, 0)) == MAP_FAILED) {
    perror("mmap");
    abort();
  }

  if (shm != BASEADR) {
    printf("Address: %p\n", (void *) shm);
    abort();
  }

  /*
   * Check if first time using region?
   */
  if (!shm[0]) {
    printf("First time with memory!\n");
  } else {
    printf("Re-using memory!\n");
    struct T * tptr = (struct T *) (shm+1);
    printf("T1{ %d, %d, %p }\n", tptr->x, *tptr->y, tptr->t);
    printf("T2{ %d, %p, %p }\n", tptr->t->x, tptr->t->y, tptr->t->t);
    memset(shm, 0, 100);
  }

  /*
   * Mark region as active!
   */
  shm[0] = 1;

  /*
   * Store structure.
   */
  struct T * t1 = (struct T *) (shm + 1);
  t1->x = 10;
  t1->y = shm;
  struct T * t2 = (struct T *) t1 + 1;
  t2->x = 20;
  t2->y = shm;
  t2->t = NULL;
  t1->t = t2;

  /*
   * Loop writing.
   */
  s = (char *) (t2 + 1);
  unsigned int i, j;
  for (i = 0; i < 1024*1024*1024; i++) {
    for (j = 0; j < i; j++) {
      s[j] = (char) i;
    }
  }

  /*
   * Close file descriptor for segment.
   */
  if (close(shmid) < 0) {
    perror("close");
    abort();
  }

  return EXIT_SUCCESS;
}
示例#5
0
int main(int argc, char *argv[])
{
	char errbuf[PCAP_ERRBUF_SIZE];
	char *dev;
	struct iface_config *ifc;
	int optind;
	int i;


	bzero(&cfg, sizeof(cfg));

	/* Default configuration */
//	cfg.ratelimit = 0;
	cfg.hashsize = 1;
//	cfg.quiet = 0;
	cfg.promisc_flag = 1;
//	cfg.ratelimit = 0;
//	cfg.sqlite_file = NULL;
//	cfg.uname = NULL;
#if HAVE_LIBSQLITE3
	cfg.sqlite_table = PACKAGE;
#endif
#if HAVE_LIBMYSQLCLIENT
//	cfg.mysql_db = NULL;
	cfg.mysql_table = PACKAGE;
#endif

	argp_parse(&argp, argc, argv, 0, &optind, 0);

	if (!cfg.hostname) {
		cfg.hostname_len = sysconf(_SC_HOST_NAME_MAX);
		cfg.hostname = (char *)calloc(cfg.hostname_len, sizeof(char));
		gethostname(cfg.hostname, cfg.hostname_len);
	}

	daemonize();
	save_pid();

	log_open();
	libevent_init();


	if (cfg.ratelimit > 0)
		log_msg(LOG_DEBUG, "Ratelimiting duplicate entries to 1 per %d seconds", cfg.ratelimit);
	else if (cfg.ratelimit == -1)
		log_msg(LOG_DEBUG, "Duplicate entries supressed indefinitely");
	else
		log_msg(LOG_DEBUG, "Duplicate entries ratelimiting disabled");

	if (cfg.promisc_flag)
		log_msg(LOG_DEBUG, "PROMISC mode enabled");
	else
		log_msg(LOG_DEBUG, "PROMISC mode disabled");

	if (argc > optind) {
		for (i = optind; i < argc; i++)
			add_iface(argv[i]);
	} else {
		dev = pcap_lookupdev(errbuf);
		if (dev != NULL)
			add_iface(dev);
	}

	if (!cfg.interfaces)
		log_msg(LOG_ERR, "No suitable interfaces found!");

	if (cfg.uname)
		drop_root(cfg.uname);

	output_flatfile_init();
	output_sqlite_init();
	output_mysql_init();

	/* main loop */
#if HAVE_LIBEVENT2
	event_base_dispatch(cfg.eb);
#else
	event_dispatch();
#endif

	output_mysql_close();
	output_sqlite_close();
	output_flatfile_close();

	for (ifc = cfg.interfaces; ifc != NULL; ifc = del_iface(ifc));


	libevent_close();
	log_close();

	del_pid();
	blacklist_free();

	free(cfg.hostname);

	return 0;
}
int pageinout_test(int test_runs, unsigned long long file_size) {
    int fd;
    char tmpname[] = "pageinoutXXXXXX";
    unsigned char *vec;
    int i;
    long long j;
    volatile char *buf;
    int ret = -1;
    int rc;
    struct timeval begin_time, end_time, elapsed_time, total_time_in, total_time_out;
    long pagesize = sysconf(_SC_PAGE_SIZE);

    timerclear(&total_time_in);
    timerclear(&total_time_out);

    fd = create_tmp_file(tmpname, file_size);
    if (fd < 0) {
        return -1;
    }

    vec = alloc_mincore_vec(file_size);
    if (vec == NULL) {
        goto err_alloc;
    }

    buf = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (buf == ((void *)-1)) {
        fprintf(stderr, "Failed to mmap file: %s\n", strerror(errno));
        goto err_mmap;
    }

    if (!check_caching((void *)buf, vec, file_size, false)) {
        goto err;
    }

    for (i = 0; i < test_runs; i++) {
        gettimeofday(&begin_time, NULL);
        //Read backwards to prevent mmap prefetching
        for (j = ((file_size - 1) & ~(pagesize - 1)); j >= 0; j -= pagesize) {
            buf[j];
        }
        gettimeofday(&end_time, NULL);

        timersub(&end_time, &begin_time, &elapsed_time);
        timeradd(&total_time_in, &elapsed_time, &total_time_in);

        if (!check_caching((void *)buf, vec, file_size, true)) {
            goto err;
        }

        gettimeofday(&begin_time, NULL);
        rc = madvise((void *)buf, file_size, MADV_DONTNEED) ||
               posix_fadvise(fd, 0, file_size, POSIX_FADV_DONTNEED);
        gettimeofday(&end_time, NULL);
        if (rc) {
            fprintf(stderr, "posix_fadvise/madvise DONTNEED failed\n");
            goto err;
        }

        timersub(&end_time, &begin_time, &elapsed_time);
        timeradd(&total_time_out, &elapsed_time, &total_time_out);

        if (!check_caching((void *)buf, vec, file_size, false)) {
            goto err;
        }
    }

    printf("page-in: %llu MB/s\n", (file_size * test_runs * USEC_PER_SEC) /
             (1024 * 1024 * (total_time_in.tv_sec * USEC_PER_SEC + total_time_in.tv_usec)));
    printf("page-out (clean): %llu MB/s\n", (file_size * test_runs * USEC_PER_SEC) /
             (1024 * 1024 * (total_time_out.tv_sec * USEC_PER_SEC + total_time_out.tv_usec)));

    ret = 0;

err:
    munmap((void *)buf, file_size);
err_mmap:
    free(vec);
err_alloc:
    close(fd);
    return ret;
}
示例#7
0
void
get_cpu_time_counters(cpu_time_counters_t *res,
		      struct timeval *timestamp,
		      test_t *test)
{

  int i,records;
  char *p = proc_stat_buf;
  char cpunam[64];
  uint64_t nicetime;
  netsysstat_data_t *tsd = GET_TEST_DATA(test);
  double elapsed;                   /* well, it isn't really "elapsed" */
  FILE *proc_intr_file = NULL;
  uint64_t irq;

  NETPERF_DEBUG_ENTRY(test->debug,test->where);

  gettimeofday(timestamp,NULL);
  elapsed = (double)timestamp->tv_sec + 
    ((double)timestamp->tv_usec / (double)1000000);
  if (test->debug) {
    fprintf(test->where,
	    "func: %s res %p timeptr %p test %p tsd %p\n",
	    __func__,
	    res,
	    timestamp,
	    test,
	    tsd);
    fflush(test->where);
  }
  lseek (proc_stat_fd, 0, SEEK_SET);
  read (proc_stat_fd, p, proc_stat_buflen);
  
  if (test->debug) {
    fprintf(test->where,"proc_stat_buf %s\n",p);
    fflush(test->where);
  }
  /* Skip first line (total) on SMP */
  if (tsd->num_cpus > 1) p = strchr (p, '\n');
  
  for (i = 0; i < tsd->num_cpus; i++) {

    /* PN: 
     * p points to a '\n'. Move to the next char for cpu info
     */
    p = p + 1;
    
    /* records = sscanf(proc_stat_buf, */
    /* PN: Scanning a few more cpu counters. 
     */
    records = sscanf(p, 
		     "%s %lld %lld %lld %lld %lld %lld %lld",
		     cpunam,
		     &(res[i].user),
		     &(res[i].nice),
		     &(res[i].kernel),
		     &(res[i].idle),
		     &(res[i].iowait),
		     &(res[i].interrupt),
		     &(res[i].softirq)
		     );

    res[i].calibrate = (uint64_t)(elapsed * (double)sysconf(_SC_CLK_TCK));

    /* PN: Nothing goes into other stats. 
     */
    /*
    res[i].user += nicetime;
    res[i].interrupt = 0;
    res[i].other     = res[i].calibrate;
    res[i].other    -= res[i].idle;
    res[i].other    -= res[i].user;
    res[i].other    -= res[i].kernel;
    res[i].other    -= res[i].interrupt;
    */
    if (test->debug) {
      fprintf(test->where,
              "\tcalibrate[%d] = 0x%"PRIx64" ",
              i,
              res[i].calibrate);
      fprintf(test->where,
              "\tidle[%d] = 0x%"PRIx64" ",
              i,
              res[i].idle);
      fprintf(test->where,
              "user[%d] = 0x%"PRIx64" ",
              i,
              res[i].user);
      fprintf(test->where,
              "kern[%d] = 0x%"PRIx64" ",
              i,
              res[i].kernel);
      fflush(test->where);
      fprintf(test->where,
              "intr[%d] = 0x%"PRIx64"\n",
              i,
              res[i].interrupt);
      fprintf(test->where,
 	      "nice[%d] = %x"PRIx64" ",
 	      i,
 	      res[i].nice);
      fprintf(test->where,
 	      "iowait[%d] = %x"PRIx64" ",
 	      i,
 	      res[i].iowait);
      fprintf(test->where,
 	      "softirq[%d] = %x"PRIx64"\n",
 	      i,
 	      res[i].softirq);
      fflush(test->where);
    }

    p = strchr(p, '\n');

  }
  /* PN: 07/11/2007.
   * Get the total interrupts serviced so far.
   */
  if (!proc_intr_file) {
    proc_intr_file = fopen(PROC_INTR_FILE_NAME, "r");
    if (!proc_intr_file) {
      fprintf (stderr, "Cannot open %s!\n", PROC_INTR_FILE_NAME);
      exit(-1);
    }
  }
  
  /* PN: Read /proc/interrupts */
  memset(proc_stat_buf, 0, proc_stat_buflen);
  while (fgets(proc_stat_buf, proc_stat_buflen, proc_intr_file) != NULL) {
    
    if (isdigit(proc_stat_buf[2])) {
      for (i = 0; i < tsd->num_cpus; i++) {
	sscanf(proc_stat_buf + 4 + 11 * i, " %lld", &irq);
	res[i].total_intr += irq;
	if (test->debug) {
	  fprintf(test->where, "cpu: %d, irq: %"PRIu64", total_intr: %"PRIu64"\n",
		  i, irq, res[i].total_intr);
	  fflush(test->where);
	}
      }
    }
  }
  
  fclose(proc_intr_file);
}
示例#8
0
static void
TestSuite_PrintJsonSystemHeader (FILE *stream)
{
#ifdef _WIN32
#  define INFO_BUFFER_SIZE 32767

   SYSTEM_INFO si;
   DWORD version = 0;
   DWORD major_version = 0;
   DWORD minor_version = 0;
   DWORD build = 0;

   GetSystemInfo(&si);
   version = GetVersion();

   major_version = (DWORD)(LOBYTE(LOWORD(version)));
   minor_version = (DWORD)(HIBYTE(LOWORD(version)));

   if (version < 0x80000000) {
      build = (DWORD)(HIWORD(version));
   }

   fprintf (stream,
            "  \"host\": {\n"
            "    \"sysname\": \"Windows\",\n"
            "    \"release\": \"%ld.%ld (%ld)\",\n"
            "    \"machine\": \"%ld\",\n"
            "    \"memory\": {\n"
            "      \"pagesize\": %ld,\n"
            "      \"npages\": %d\n"
            "    }\n"
            "  },\n",
            major_version, minor_version, build,
            si.dwProcessorType,
            si.dwPageSize,
            0
   );
#else
   struct utsname u;
   uint64_t pagesize;
   uint64_t npages = 0;

   if (uname (&u) == -1) {
      perror ("uname()");
      return;
   }

   pagesize = sysconf (_SC_PAGE_SIZE);

#  if defined(_SC_PHYS_PAGES)
   npages = sysconf (_SC_PHYS_PAGES);
#  endif
   fprintf (stream,
            "  \"host\": {\n"
            "    \"sysname\": \"%s\",\n"
            "    \"release\": \"%s\",\n"
            "    \"machine\": \"%s\",\n"
            "    \"memory\": {\n"
            "      \"pagesize\": %"PRIu64",\n"
            "      \"npages\": %"PRIu64"\n"
            "    }\n"
            "  },\n",
            u.sysname,
            u.release,
            u.machine,
            pagesize,
            npages
   );
#endif
}
示例#9
0
int main(int argc, char * argv[])
{
	pid_t child;
	
	
	pthread_mutex_t  mtx;
	pthread_mutexattr_t ma[4];
	pthread_mutexattr_t *pma[5];
	
	int ret=0;
	int i;
	int retini[5] = {-1,-1,-1,-1,-1};
	int retdtr[5]= {-1,-1,-1,-1,-1};
	
	void * ptr, *ptr_prev=NULL;
	
	int sz = 0;
	struct rlimit rl;
	
	int status=0;
	
	output_init();

	child = fork();
	
	if (child == (pid_t)-1)
	{ UNRESOLVED(errno, "Fork failed"); }
	
	if (child != 0) /* We are the father */
	{
		if (child != waitpid(child, &status, 0))
		{  UNRESOLVED(errno, "Waitpid failed"); }

		if (WIFSIGNALED(status))
		{ UNRESOLVED(WTERMSIG(status), 
			"The child process was killed."); }

		if (WIFEXITED(status))
			return WEXITSTATUS(status);
		
		UNRESOLVED(0, "Child process neither returned nor was killed.");
	}
	
	/* Only the child goes further */
	
	/* We initialize the different mutex attributes */
	for (i=0; (i<4) && (ret == 0); i++)
	{
		pma[i] = &ma[i];
		ret = pthread_mutexattr_init(pma[i]);
	}
	if (ret)
	{ UNRESOLVED(ret, "Mutex attribute init failed"); }
	pma[4] = (pthread_mutexattr_t *) NULL;
	
	if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_NORMAL)))
	{ UNRESOLVED(ret, "Mutex attribute NORMAL failed"); }
	if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_DEFAULT)))
	{ UNRESOLVED(ret, "Mutex attribute DEFAULT failed"); }
	if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_RECURSIVE)))
	{ UNRESOLVED(ret, "Mutex attribute RECURSIVE failed"); }
	if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_ERRORCHECK)))
	{ UNRESOLVED(ret, "Mutex attribute ERRORCHECK failed"); }
	
	sz = sysconf(_SC_PAGESIZE);
	
	
	/* Limit the process memory to a small value (64Mb for example). */
	rl.rlim_max=1024*1024*64;
	rl.rlim_cur=1024*1024*64;
	if ((ret = setrlimit(RLIMIT_AS,  &rl)))
	{ UNRESOLVED(ret, "Memory limitation failed"); }


	#if VERBOSE > 1
	output("Ready to take over memory. Page size is %d\n", sz);
	#endif
	
	/* Allocate all available memory */
	while (1)
	{
		ptr = malloc( sz ); /* Allocate one page of memory */
		if (ptr == NULL)
			break;
		#if VERBOSE > 1
		ret++;
		#endif
		*(void **)ptr = ptr_prev; /* Write into the allocated page */
		ptr_prev = ptr;
	}
	#if VERBOSE > 1
	output("%d pages were allocated before failure\n", ret);
	ret = 0;
	#endif
	
	while (1)
	{
		ptr = malloc( sizeof(void*) ); /* Allocate every remaining bits of memory */
		if (ptr == NULL)
			break;
		#if VERBOSE > 1
		ret++;
		#endif
		*(void **)ptr = ptr_prev; /* Keep track of allocated memory */
		ptr_prev = ptr;
	}
	#if VERBOSE > 1
	output("%d additional spaces were allocated before failure\n", ret);
	ret = 0;
	#endif
	if (errno != ENOMEM)
		UNRESOLVED(errno, "Memory not full");
	
	/* Now that memory is full, we try to initialize a mutex */
	for (i=0; i<5; i++)
	{
		retini[i] = pthread_mutex_init(&mtx, pma[i]);
		if (!retini[i]) /* If mutex has been initialized, we destroy it */
			retdtr[i] = pthread_mutex_destroy(&mtx);
	}
	
	/* We can now free the memory */
	while (ptr_prev != NULL)
	{
		ptr = ptr_prev;
		ptr_prev = *(void **)ptr;
		free(ptr);
	}

	#if VERBOSE > 1
	output("Memory is released\n");
	#endif
	
	for (i=0; i<4; i++)
		pthread_mutexattr_destroy(pma[i]);

	
	for (i=0; i<5; i++)
	{
		if (retini[i] != 0 && retini[i] !=ENOMEM)
		{  FAILED("Mutex init returned a wrong error code when no memory was left"); }
	
		if (retini[i] == 0)
		{
			#if VERBOSE > 0
			output("Mutex initialization for attribute %d succeeds when memory is full\n", i);
			#endif
			if (retdtr[i] != 0)
			{  UNRESOLVED( retdtr[i],  "Mutex destroy failed on mutex inilialized under heavy loaded memory"); }
		}
		#if VERBOSE > 0
		else
		{
			output("Mutex initialization for attribute %d fails with ENOMEM when memory is full\n", i);
		}
		#endif
	}
	PASSED;
}
示例#10
0
static void *
MapPhysAddress(unsigned long address, unsigned long size)
{
    unsigned long offset, delta;
    int pagesize = -1;
    void *vaddr;
    MapPtr mp;
#if defined(ISC) && defined(HAS_SVR3_MMAP)
    struct kd_memloc mloc;
#elif defined(__EMX__)
    APIRET rc;
    ULONG action;
    HFILE hfd;
#endif

    if ((mp = FindMap(address, size))) {
	mp->refcount++;
	return (void *)((unsigned long)mp->vaddr + mp->delta);
    }

#if defined(_SC_PAGESIZE) && defined(HAS_SC_PAGESIZE)
    pagesize = sysconf(_SC_PAGESIZE);
#endif
#ifdef _SC_PAGE_SIZE
    if (pagesize == -1)
	pagesize = sysconf(_SC_PAGE_SIZE);
#endif
#ifdef HAS_GETPAGESIZE
    if (pagesize == -1)
	pagesize = getpagesize();
#endif
#ifdef PAGE_SIZE
    if (pagesize == -1)
	pagesize = PAGE_SIZE;
#endif
    if (pagesize == -1)
	pagesize = 4096;

   delta = address % pagesize;
   offset = address - delta;

#if defined(ISC) && defined(HAS_SVR3_MMAP)
    if (mapFd < 0) {
	if ((mapFd = open("/dev/mmap", O_RDWR)) < 0)
	    return NULL;
    }
    mloc.vaddr = (char *)0;
    mloc.physaddr = (char *)offset;
    mloc.length = size + delta;
    mloc.ioflg=1;

    if ((vaddr = (void *)ioctl(mapFd, MAP, &mloc)) == (void *)-1)
	return NULL;
#elif defined (__EMX__)
    /*
     * Dragon warning here! /dev/pmap$ is never closed, except on progam exit.
     * Consecutive calling of this routine will make PMAP$ driver run out
     * of memory handles. Some umap/close mechanism should be provided
     */

    rc = DosOpen("/dev/pmap$", &hfd, &action, 0, FILE_NORMAL, FILE_OPEN,
		 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE, (PEAOP2)NULL);
    if (rc != 0)
	return NULL;
    {
	struct map_ioctl {
		union {
			ULONG phys;
			void* user;
		} a;
		ULONG size;
	} pmap,dmap;
	ULONG plen,dlen;
#define XFREE86_PMAP	0x76
#define PMAP_MAP	0x44

	pmap.a.phys = offset;
	pmap.size = size + delta;
	rc = DosDevIOCtl(hfd, XFREE86_PMAP, PMAP_MAP,
			 (PULONG)&pmap, sizeof(pmap), &plen,
			 (PULONG)&dmap, sizeof(dmap), &dlen);
	if (rc == 0) {
		vaddr = dmap.a.user;
	}
   }
   if (rc != 0)
	return NULL;
#elif defined (Lynx)
    vaddr = (void *)smem_create("XF86DGA", (char *)offset, 
				size + delta, SM_READ|SM_WRITE);
#else
#ifndef MAP_FILE
#define MAP_FILE 0
#endif
    if (mapFd < 0) {
	if ((mapFd = open(DEV_MEM, O_RDWR)) < 0)
	    return NULL;
    }
    vaddr = (void *)mmap(NULL, size + delta, PROT_READ | PROT_WRITE,
                        MAP_FILE | MAP_SHARED, mapFd, (off_t)offset);
    if (vaddr == (void *)-1)
	return NULL;
#endif

    if (!vaddr) {
	if (!(mp = AddMap()))
	    return NULL;
	mp->physaddr = address;
	mp->size = size;
	mp->delta = delta;
	mp->vaddr = vaddr;
	mp->refcount = 1;
    }
    return (void *)((unsigned long)vaddr + delta);
}
示例#11
0
void
print_affinity (struct place p)
{
  static unsigned long size;
  if (size == 0)
    {
      if (min_cpusetsize)
	size = min_cpusetsize;
      else
	{
	  size = sysconf (_SC_NPROCESSORS_CONF);
	  size = CPU_ALLOC_SIZE (size);
	  if (size < sizeof (cpu_set_t))
	    size = sizeof (cpu_set_t);
	}
    }
  cpu_set_t *cpusetp = (cpu_set_t *) __builtin_alloca (size);
  if (pthread_getaffinity_np (pthread_self (), size, cpusetp) == 0)
    {
      unsigned long i, len, max = 8 * size;
      int notfirst = 0, unexpected = 1;

      printf (" bound to {");
      for (i = 0, len = 0; i < max; i++)
	if (CPU_ISSET_S (i, size, cpusetp))
	  {
	    if (len == 0)
	      {
		if (notfirst)
		  {
		    unexpected = 1;
		    printf (",");
		  }
		else if (i == (unsigned long) p.start)
		  unexpected = 0;
		notfirst = 1;
		printf ("%lu", i);
	      }
	    ++len;
	  }
	else
	  {
	    if (len && len != (unsigned long) p.len)
	      unexpected = 1;
	    if (len > 1)
	      printf (":%lu", len);
	    len = 0;
	  }
      if (len && len != (unsigned long) p.len)
	unexpected = 1;
      if (len > 1)
	printf (":%lu", len);
      printf ("}");
      if (p.start != -1 && unexpected)
	{
	  printf (", expected {%d", p.start);
	  if (p.len != 1)
	    printf (":%d", p.len);
	  printf ("} instead");
	}
      else if (p.start != -1)
	printf (", verified");
    }
}
示例#12
0
文件: process.c 项目: AMV007/FreeRDP
BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
		LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
		LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
		LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int flags;
	int numArgs;
	LPSTR* pArgs = NULL;
	char** envp = NULL;
	char* filename = NULL;
	HANDLE thread;
	HANDLE process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;
	BOOL ret = FALSE;

	pid = 0;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;

	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);

	flags = 0;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();
		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}

	filename = FindApplicationPath(pArgs[0]);
	if (NULL == filename)
		goto finish;

	/* fork and exec */

	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		goto finish;
	}

	if (pid == 0)
	{
		/* child process */
#ifdef __sun
	closefrom(3);
#else
	int maxfd;
#ifdef F_MAXFD // on some BSD derivates
	maxfd = fcntl(0, F_MAXFD);
#else
	maxfd = sysconf(_SC_OPEN_MAX);
#endif
	int fd;
	for(fd=3; fd<maxfd; fd++)
		close(fd);
#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				int rc = setgid((gid_t) token->GroupId);
				if (rc < 0)
				{
				}
				else
				{
					initgroups(token->Username, (gid_t) token->GroupId);
				}
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);

			/* TODO: add better cwd handling and error checking */
			if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0)
				chdir(lpCurrentDirectory);
		}

		if (execve(filename, pArgs, envp) < 0)
		{
			/* execve failed - end the process */
			_exit(1);
		}
	}
	else
	{
		/* parent process */
	}

	process = CreateProcessHandle(pid);

	if (!process)
	{
		goto finish;
	}

	thread = CreateNoneHandle();

	if (!thread)
	{
		ProcessHandleCloseHandle(process);
		goto finish;
	}

	lpProcessInformation->hProcess = process;
	lpProcessInformation->hThread = thread;
	lpProcessInformation->dwProcessId = (DWORD) pid;
	lpProcessInformation->dwThreadId = (DWORD) pid;

	ret = TRUE;

finish:
	if (filename)
	{
		free(filename);
	}

	if (pArgs)
	{
		HeapFree(GetProcessHeap(), 0, pArgs);
	}

	if (lpszEnvironmentBlock)
		FreeEnvironmentStrings(lpszEnvironmentBlock);

	if (envp)
	{
		int i = 0;

		while (envp[i])
		{
			free(envp[i]);
			i++;
		}

		free(envp);
	}

	return ret;
}
示例#13
0
static void INET_setroute(int action, char **args)
{
	struct rtentry rt;
	const char *netmask;
	int skfd, isnet, xflag;

	assert((action == RTACTION_ADD) || (action == RTACTION_DEL));

	/* Grab the -net or -host options.  Remember they were transformed. */
	xflag = kw_lookup(tbl_hash_net_host, &args);

	/* If we did grab -net or -host, make sure we still have an arg left. */
	if (*args == NULL) {
		bb_show_usage();
	}

	/* Clean out the RTREQ structure. */
	memset((char *) &rt, 0, sizeof(struct rtentry));

	{
		const char *target = *args++;

		/* Prefer hostname lookup is -host flag (xflag==1) was given. */
 		isnet = INET_resolve(target, (struct sockaddr_in *) &rt.rt_dst,
							 (xflag & HOST_FLAG));
		if (isnet < 0) {
			bb_error_msg_and_die("resolving %s", target);
		}

	}

	if (xflag) {		/* Reinit isnet if -net or -host was specified. */
		isnet = (xflag & NET_FLAG);
	}

	/* Fill in the other fields. */
	rt.rt_flags = ((isnet) ? RTF_UP : (RTF_UP | RTF_HOST));

	netmask = bb_INET_default;

	while (*args) {
		int k = kw_lookup(tbl_ipvx, &args);
		const char *args_m1 = args[-1];

		if (k & KW_IPVx_FLAG_ONLY) {
			rt.rt_flags |= flags_ipvx[k & 3];
			continue;
		}

#if HAVE_NEW_ADDRT
		if (k == KW_IPVx_METRIC) {
			rt.rt_metric = bb_xgetularg10(args_m1) + 1;
			continue;
		}
#endif

		if (k == KW_IPVx_NETMASK) {
			struct sockaddr mask;

			if (mask_in_addr(rt)) {
				bb_show_usage();
			}

			netmask = args_m1;
			isnet = INET_resolve(netmask, (struct sockaddr_in *) &mask, 0);
			if (isnet < 0) {
				bb_error_msg_and_die("resolving %s", netmask);
			}
			rt.rt_genmask = full_mask(mask);
			continue;
		}

		if (k == KW_IPVx_GATEWAY) {
			if (rt.rt_flags & RTF_GATEWAY) {
				bb_show_usage();
			}

			isnet = INET_resolve(args_m1,
								 (struct sockaddr_in *) &rt.rt_gateway, 1);
			rt.rt_flags |= RTF_GATEWAY;

			if (isnet) {
				if (isnet < 0) {
					bb_error_msg_and_die("resolving %s", args_m1);
				}
				bb_error_msg_and_die("gateway %s is a NETWORK", args_m1);
			}
			continue;
		}

		if (k == KW_IPVx_MSS) {	/* Check valid MSS bounds. */
			rt.rt_flags |= RTF_MSS;
			rt.rt_mss = bb_xgetularg10_bnd(args_m1, 64, 32768);
			continue;
		}

		if (k == KW_IPVx_WINDOW) {	/* Check valid window bounds. */
			rt.rt_flags |= RTF_WINDOW;
			rt.rt_window = bb_xgetularg10_bnd(args_m1, 128, INT_MAX);
			continue;
		}

#ifdef RTF_IRTT
		if (k == KW_IPVx_IRTT) {
			rt.rt_flags |= RTF_IRTT;
			rt.rt_irtt = bb_xgetularg10(args_m1);
			rt.rt_irtt *= (sysconf(_SC_CLK_TCK) / 100);	/* FIXME */
#if 0					/* FIXME: do we need to check anything of this? */
			if (rt.rt_irtt < 1 || rt.rt_irtt > (120 * HZ)) {
				bb_error_msg_and_die("bad irtt");
			}
#endif
			continue;
		}
#endif

		/* Device is special in that it can be the last arg specified
		 * and doesn't requre the dev/device keyword in that case. */
		if (!rt.rt_dev && ((k == KW_IPVx_DEVICE) || (!k && !*++args))) {
			/* Don't use args_m1 here since args may have changed! */
			rt.rt_dev = args[-1];
			continue;
		}

		/* Nothing matched. */
		bb_show_usage();
	}

#ifdef RTF_REJECT
	if ((rt.rt_flags & RTF_REJECT) && !rt.rt_dev) {
		rt.rt_dev = "lo";
	}
#endif

	/* sanity checks.. */
	if (mask_in_addr(rt)) {
		unsigned long mask = mask_in_addr(rt);

		mask = ~ntohl(mask);
		if ((rt.rt_flags & RTF_HOST) && mask != 0xffffffff) {
			bb_error_msg_and_die("netmask %.8x and host route conflict",
								 (unsigned int) mask);
		}
		if (mask & (mask + 1)) {
			bb_error_msg_and_die("bogus netmask %s", netmask);
		}
		mask = ((struct sockaddr_in *) &rt.rt_dst)->sin_addr.s_addr;
		if (mask & ~mask_in_addr(rt)) {
			bb_error_msg_and_die("netmask and route address conflict");
		}
	}

	/* Fill out netmask if still unset */
	if ((action == RTACTION_ADD) && (rt.rt_flags & RTF_HOST)) {
		mask_in_addr(rt) = 0xffffffff;
	}

	/* Create a socket to the INET kernel. */
	if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		bb_perror_msg_and_die("socket");
	}

	if (ioctl(skfd, ((action==RTACTION_ADD) ? SIOCADDRT : SIOCDELRT), &rt)<0) {
		bb_perror_msg_and_die("SIOC[ADD|DEL]RT");
	}

	/* Don't bother closing, as we're exiting after we return anyway. */
	/* close(skfd); */
}
示例#14
0
static int become_daemon(int flags)
{
	// 프로세스 리더인 부모를 종료시키고 자식은 init로 편입되어 백그라운드 프로세스가 된다.
	// 부모로부터 프로세스 그룹을 분리
	switch(fork()) {
	case -1:
		return -1;
	// 자식인 경우 계속 진행
	case 0:
		break;
	// 부모는 종료
	default:
		printf("[parent] pid = %d, pgid = %d, sid = %d\n", getpid(), getpgid(0), getsid(0));
		printf("parent pid = %d is terminated\n", getpid());
		_exit(EXIT_SUCCESS);
	}

	printf("[child] pid = %d, pgid = %d, sid = %d\n", getpid(), getpgid(0), getsid(0));

	// 자식 프로세스를 새로운 세션의 리더가 되어 부모의 제어 터미널과의 연관성을 제거한다.
	// 부모로부터 세션 분리
	if(setsid() == -1)
		return -1;

	// 손자를 생성하고 자식을 종료시켜서 손자는 세션 리더가 아니게 됨.
	// 따라서 손자는 절대 제어 터미널을 재획득할 수 없게 됨.
	switch(fork()) {
	case -1:
		return -1;
	// 손자인 경우 계속 진행
	case 0:
		break;
	// 자식은 종료
	default:
		printf("child pid = %d is terminated\n", getpid());
		_exit(EXIT_SUCCESS);
	}

	printf("[grandchild] pid = %d, pgid = %d, sid = %d\n", getpid(), getpgid(0), getsid(0));

	// 손자의 mask를 지움으로써 파일과 디렉토리를 자유롭게 생성할 권한을 가진다.
	if(!(flags & BD_NO_UMASK0))
		umask(0);

	// CWD를 루트 디렉토리로 변경
	if(!(flags & BD_NO_CHDIR))
		chdir("/");

	// 모든 열린 파일을 종료
	int fd, maxfds;
	if(!(flags & BD_NO_CLOSE_FILES)) {
		maxfds = sysconf(_SC_OPEN_MAX); // 프로세스의 최대 FD 한도값
		if(maxfds == -1) // 얻을 수 없는 경우
			maxfds = BD_MAX_CLOSE;

		for (fd = 0; fd < maxfds; ++fd)
			close(fd);
	}

	// 표준 입출력, 에러를 /dev/null로 리다이렉션한다( 0>/dev/null, 1>/dev/null 2>/dev/null)
	if(!(flags & BD_NO_REOPEN_STD_FDS)) {
		// 파일 디스크립터 0을 얻기 위해 표준입력(=0)을 닫는다.
		close(STDIN_FILENO);
		// /dev/null을 열고 파일 디스크립터를 얻는다. 위에서 표준입력(0)이 닫혔기 때문에 fd는 0이어야 한다.
		fd = open("/dev/null", O_RDWR);

		// 0번 디스크립터를 얻지 못하면 종료
		if(fd != STDIN_FILENO)
			return -1;
		// 이제, STDIN_FILENO는 /dev/null이다.

		// STDOUT_FILENO(=1)도 /dev/null로 리다이렉션한다.
		if(dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO)
			return -1;
		// STDERR_FILENO(=2)도 /dev/null로 리다이렉션한다.
		if(dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO)
			return -1;
	}

//	// 데몬의 정보 확인을 위해 만들어진 데몬이 60초 동안 생존해 있도록 한다.
//	sleep(60);

	return 0;
}
示例#15
0
文件: main.c 项目: JF3/placement
int main (int argc, char* argv[])
{
	int impi, iomp;

	int myProc;
	int nProcs;
	
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myProc);
	MPI_Comm_size(MPI_COMM_WORLD, &nProcs);


	int nCoresInSystem;
	nCoresInSystem = sysconf( _SC_NPROCESSORS_ONLN );
	
	if (myProc == 0)
	{
		printf("Checking the placement of your job.\n");
		printf("by JFEngels (software (at) jfengels . de)\n\n");
		printf("This system seems to have %d cores.\n", nCoresInSystem);
		printf("mpi\tomp\tcore\n");
		printf("rank\tthread\n");
	}
	for (impi = 0; impi < nProcs; impi++)
	{
		MPI_Barrier( MPI_COMM_WORLD );

		if (impi != myProc)
			continue;

		char hostname[512];
		hostname[511] = '\0';
		gethostname(hostname, 511);
		printf("#hostname for mpi task %d: %s\n", impi, hostname);

		for (iomp = 0; iomp < omp_get_max_threads(); iomp++)
		{
			#pragma omp parallel 
			{
				#pragma omp barrier
				if (iomp == omp_get_thread_num())
				{
	
					cpu_set_t cpuSet;
					sched_getaffinity(0, sizeof(cpu_set_t), &cpuSet);
				
					int i=0;

					printf("%d\t%d\t", impi, iomp);

					if (CPU_COUNT(&cpuSet) == nCoresInSystem)
					{
						printf("any");
					}
					else
					{
						for (i=0; i < CPU_SETSIZE; i++)
						{
							if (CPU_ISSET(i, &cpuSet))
							{
								printf("%2d ", i);
							}
						}
					}
					printf("\n");
				
					fflush(stdout);
				}
			}
		}
	}
	MPI_Barrier( MPI_COMM_WORLD );
	
	MPI_Finalize();
	exit(0);

}
示例#16
0
int
tap_ctl_stats_fwrite(pid_t pid, int minor, FILE *stream)
{
	tapdisk_message_t message;
	int sfd = -1, prot, flags, err;
	size_t len, bufsz;
	char *buf = MAP_FAILED;

	prot  = PROT_READ|PROT_WRITE;
	flags = MAP_ANONYMOUS|MAP_PRIVATE;
	bufsz = sysconf(_SC_PAGE_SIZE);

	buf = mmap(NULL, bufsz, prot, flags, -1, 0);
	if (buf == MAP_FAILED) {
		buf = NULL;
		err = -ENOMEM;
		goto out;
	}

	sfd = _tap_ctl_stats_connect_and_send(pid, minor);
	if (sfd < 0) {
		err = sfd;
		goto out;
	}

	err = tap_ctl_read_message(sfd, &message, NULL);
	if (err)
		goto out;

	len = message.u.info.length;
	err = len;
	if (len < 0)
		goto out;

	while (len) {
		fd_set rfds;
		size_t in, out;
		int n;

		FD_ZERO(&rfds);
		FD_SET(sfd, &rfds);

		n = select(sfd + 1, &rfds, NULL, NULL, NULL);
		err = n;
		if (n < 0)
			goto out;

		in = read(sfd, buf, bufsz);
		err = in;
		if (in <= 0)
			goto out;

		len -= in;

		out = fwrite(buf, in, 1, stream);
		if (out != in) {
			err = -errno;
			goto out;
		}
	}

out:
	if (sfd >= 0)
		close(sfd);
	if (buf != MAP_FAILED)
		munmap(buf, bufsz);

	return err;
}
示例#17
0
int epollx::getcpunum()
{
    return sysconf(_SC_NPROCESSORS_ONLN);
}
示例#18
0
int _tmain(int argc, char* argv[])
{
// determine my process name
_splitpath(argv[0],NULL,NULL,gszProcName,NULL);
#else
int
main(int argc, const char** argv)
{
// determine my process name
CUtility::splitpath((char *)argv[0],NULL,gszProcName);
#endif

int iFileLogLevel;			// level of file diagnostics
int iScreenLogLevel;		// level of file diagnostics
char szLogFile[_MAX_PATH];	// write diagnostics to this file

int Rslt = 0;   			// function result code >= 0 represents success, < 0 on failure
int Idx;

etPMode PMode;				// processing mode

int MinCovBases;				// accept SNPs with at least this number covering bases
double MaxPValue;				// accept SNPs with at most this P-value
int MinSpeciesTotCntThres;		// individual species must have at least this number of total bases at SNP loci to count as SNP - 0 if no threshold
int AltSpeciesMaxCnt;			// only report markers if no other species has more than this number of counts at the putative SNP loci
int MinSpeciesWithCnts;			// only report markers where at least this number of species has SNP at the SNP loci


char szRefGenome[cMaxLenName+1];	// reference genome against which other relative genomes were aligned

int NumRelGenomes;			// number of relative genome names
char *pszRelGenomes[cRRMaxInFileSpecs];  // names of relative genome names

int NumSNPFiles;			// number of input SNP files
char *pszSNPFiles[cRRMaxInFileSpecs];  // input SNP files

int NumAlignFiles;			// number of input alignment files
char *pszAlignFiles[cRRMaxInFileSpecs];  // input alignment files

char szMarkerFile[_MAX_PATH];		// write markers to this file

int NumberOfProcessors;		// number of installed CPUs
int NumThreads;				// number of threads (0 defaults to number of CPUs)

// command line args
struct arg_lit  *help    = arg_lit0("hH","help",                "print this help and exit");
struct arg_lit  *version = arg_lit0("v","version,ver",			"print version information and exit");
struct arg_int *FileLogLevel=arg_int0("f", "FileLogLevel",		"<int>","Level of diagnostics written to logfile 0=fatal,1=errors,2=info,3=diagnostics,4=debug");
struct arg_file *LogFile = arg_file0("F","log","<file>",		"diagnostics log file");

struct arg_int *pmode = arg_int0("m","mode","<int>",		    "Marker processing mode: 0 - default");
struct arg_int *mincovbases=arg_int0("b", "MinCovBases","<int>","Filter out SNPs with less than this number of covering bases (default 5)");
struct arg_dbl *maxpvalue=arg_dbl0("p", "MaxPValue","<dbl>",	"Filter out SNPs with P-Value higher (default 0.05)");

struct arg_int *mintotcntthres = arg_int0("z","mintotcntthres","<int>",	"Species must have at least this number of total bases covering marker loci");
struct arg_int *mincovspecies=arg_int0("Z", "mincovspecies","<int>","Do not report markers unless this minimum number of species have SNP at same loci");
struct arg_int *altspeciesmaxcnt = arg_int0("a","altspeciesmaxcnt","<int>",	"Only report markers if no other species has more than this number of counts at the putative SNP loci (defaults to 1)");

struct arg_str *refgenome=arg_str1("r", "refgenome","<str>",	 "alignments and SNPs of relative genomes were against this genome assembly (default 'RefGenome')");
struct arg_str *relgenomes = arg_strn("R","relgenomes","<relgenomes>",1,cRRMaxInFileSpecs,"alignments and SNPs from these genomes");
struct arg_file *snpfiles = arg_filen("i","insnps","<file>",1,cRRMaxInFileSpecs,"Load SNPs from file(s)");
struct arg_file *alignfiles = arg_filen("I","inaligns","<file>",1,cRRMaxInFileSpecs,"Load alignments from file(s)");

struct arg_file *markerfile = arg_file1("o","out","<file>",		"Output markers to this file");

struct arg_int *threads = arg_int0("T","threads","<int>",		"number of processing threads 0..128 (defaults to 0 which sets threads to number of CPU cores)");
struct arg_end *end = arg_end(100);

void *argtable[] = {help,version,FileLogLevel,LogFile,
	pmode,mincovbases,maxpvalue,mintotcntthres,altspeciesmaxcnt,mincovspecies,refgenome,relgenomes,snpfiles,alignfiles,markerfile,threads,
	end};
char **pAllArgs;
int argerrors;
argerrors = CUtility::arg_parsefromfile(argc,(char **)argv,&pAllArgs);
if(argerrors >= 0)
	argerrors = arg_parse(argerrors,pAllArgs,argtable);

/* special case: '--help' takes precedence over error reporting */
if (help->count > 0)
        {
		printf("\n%s Generate Markers, Version %s\nOptions ---\n", gszProcName,cpszProgVer);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
		printf("\nNote: Parameters can be entered into a parameter file, one parameter per line.");
		printf("\n      To invoke this parameter file then precede its name with '@'");
		printf("\n      e.g. %s @myparams.txt\n",gszProcName);
		printf("\nPlease report any issues regarding usage of %s at https://github.com/csiro-crop-informatics/biokanga/issues\n\n",gszProcName);
		exit(1);
        }

    /* special case: '--version' takes precedence error reporting */
if (version->count > 0)
        {
		printf("\n%s Version %s\n",gszProcName,cpszProgVer);
		exit(1);
        }

if (!argerrors)
	{
	if(FileLogLevel->count && !LogFile->count)
		{
		printf("\nError: FileLogLevel '-f%d' specified but no logfile '-F<logfile>\n'",FileLogLevel->ival[0]);
		exit(1);
		}

	iScreenLogLevel = iFileLogLevel = FileLogLevel->count ? FileLogLevel->ival[0] : eDLInfo;
	if(iFileLogLevel < eDLNone || iFileLogLevel > eDLDebug)
		{
		printf("\nError: FileLogLevel '-l%d' specified outside of range %d..%d\n",iFileLogLevel,eDLNone,eDLDebug);
		exit(1);
		}

	if(LogFile->count)
		{
		strncpy(szLogFile,LogFile->filename[0],_MAX_PATH);
		szLogFile[_MAX_PATH-1] = '\0';
		}
	else
		{
		iFileLogLevel = eDLNone;
		szLogFile[0] = '\0';
		}

	// now that log parameters have been parsed then initialise diagnostics log system
	if(!gDiagnostics.Open(szLogFile,(etDiagLevel)iScreenLogLevel,(etDiagLevel)iFileLogLevel,true))
		{
		printf("\nError: Unable to start diagnostics subsystem\n");
		if(szLogFile[0] != '\0')
			printf(" Most likely cause is that logfile '%s' can't be opened/created\n",szLogFile);
		exit(1);
		}

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Version: %s",cpszProgVer);

	PMode = (etPMode)(pmode->count ? pmode->ival[0] : ePMdefault);
	if(PMode < ePMdefault || PMode >= ePMplaceholder)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Processing mode '-m%d' specified outside of range %d..%d\n",PMode,ePMdefault,(int)ePMplaceholder-1);
		exit(1);
		}

#ifdef _WIN32
	SYSTEM_INFO SystemInfo;
	GetSystemInfo(&SystemInfo);
	NumberOfProcessors = SystemInfo.dwNumberOfProcessors;
#else
	NumberOfProcessors = sysconf(_SC_NPROCESSORS_CONF);
#endif
	int MaxAllowedThreads = min(cMaxWorkerThreads,NumberOfProcessors);	// limit to be at most cMaxWorkerThreads
	if((NumThreads = threads->count ? threads->ival[0] : MaxAllowedThreads)==0)
		NumThreads = MaxAllowedThreads;
	if(NumThreads < 0 || NumThreads > MaxAllowedThreads)
		{
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Number of threads '-T%d' specified was outside of range %d..%d",NumThreads,1,MaxAllowedThreads);
		gDiagnostics.DiagOut(eDLWarn,gszProcName,"Warning: Defaulting number of threads to %d",MaxAllowedThreads);
		NumThreads = MaxAllowedThreads;
		}

	MinCovBases = mincovbases->count ? mincovbases->ival[0] : 5;
	if(MinCovBases < 1 || MinCovBases > 10000)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum covering bases '-b%d' must be in range 1..1000",MinCovBases);
		exit(1);
		}

	AltSpeciesMaxCnt = altspeciesmaxcnt->count ? altspeciesmaxcnt->ival[0] : 1;
	if(AltSpeciesMaxCnt < 1 || AltSpeciesMaxCnt > 10000)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Max alternative species coverage '-a%d' at putative marker loci must be in range 1..1000",AltSpeciesMaxCnt);
		exit(1);
		}


	MaxPValue = maxpvalue->count ? maxpvalue->dval[0] : 0.05;
	if(MaxPValue < 0.0 || MaxPValue > 0.25)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Maximum P-Value '-p%1.4f' must be in range 0.0..0.25",MaxPValue);
		exit(1);
		}

	if(refgenome->count)
		{
		strncpy(szRefGenome,refgenome->sval[0],cMaxLenName);
		szRefGenome[cMaxLenName-1]= '\0';
		}
	else
		strcpy(szRefGenome,"RefGenome");

	if(!relgenomes->count)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: No alignment from genome name(s) specified with with '-R<relgenomes>' option)");
		exit(1);
		}
	for(NumRelGenomes=Idx=0;NumRelGenomes < cRRMaxInFileSpecs && Idx < relgenomes->count; Idx++)
		{
		pszRelGenomes[Idx] = NULL;
		if(pszRelGenomes[NumRelGenomes] == NULL)
			pszRelGenomes[NumRelGenomes] = new char [_MAX_PATH];
		strncpy(pszRelGenomes[NumRelGenomes],relgenomes->sval[Idx],_MAX_PATH);
		pszRelGenomes[NumRelGenomes][_MAX_PATH-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(pszRelGenomes[NumRelGenomes]);
		if(pszRelGenomes[NumRelGenomes][0] != '\0')
			NumRelGenomes++;
		}


	strncpy(szMarkerFile,markerfile->filename[0],_MAX_PATH);
	szMarkerFile[_MAX_PATH-1] = '\0';

	if(!snpfiles->count)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: No input SNP file(s) specified with with '-i<filespec>' option)");
		exit(1);
		}

	for(NumSNPFiles=Idx=0;NumSNPFiles < cRRMaxInFileSpecs && Idx < snpfiles->count; Idx++)
		{
		pszSNPFiles[Idx] = NULL;
		if(pszSNPFiles[NumSNPFiles] == NULL)
			pszSNPFiles[NumSNPFiles] = new char [_MAX_PATH];
		strncpy(pszSNPFiles[NumSNPFiles],snpfiles->filename[Idx],_MAX_PATH);
		pszSNPFiles[NumSNPFiles][_MAX_PATH-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(pszSNPFiles[NumSNPFiles]);
		if(pszSNPFiles[NumSNPFiles][0] != '\0')
			NumSNPFiles++;
		}

	if(!NumSNPFiles)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input SNP file(s) specified with '-i<filespec>' option");
		exit(1);
		}

	if(!alignfiles->count)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: No input alignment file(s) specified with with '-I<filespec>' option)");
		exit(1);
		}

	for(NumAlignFiles=Idx=0;NumAlignFiles < cRRMaxInFileSpecs && Idx < alignfiles->count; Idx++)
		{
		pszAlignFiles[Idx] = NULL;
		if(pszAlignFiles[NumAlignFiles] == NULL)
			pszAlignFiles[NumAlignFiles] = new char [_MAX_PATH];
		strncpy(pszAlignFiles[NumAlignFiles],alignfiles->filename[Idx],_MAX_PATH);
		pszAlignFiles[NumAlignFiles][_MAX_PATH-1] = '\0';
		CUtility::TrimQuotedWhitespcExtd(pszAlignFiles[NumAlignFiles]);
		if(pszAlignFiles[NumAlignFiles][0] != '\0')
			NumAlignFiles++;
		}

	if(!NumAlignFiles)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: After removal of whitespace, no input alignment file(s) specified with '-I<filespec>' option");
		exit(1);
		}

	// number of alignment files must be same as the number of SNP files and genome names!
	if(NumAlignFiles != NumSNPFiles && NumAlignFiles != NumRelGenomes)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Expected same number of genome names, alignment files and SNP files, %d genome names, %d alignment files, %d SNP files",NumRelGenomes,NumAlignFiles,NumSNPFiles);
		exit(1);
		}
	
	MinSpeciesTotCntThres = mincovspecies->count ? mincovspecies->ival[0] : 1;
	if(MinSpeciesTotCntThres < 1 || MinSpeciesTotCntThres > 10000)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum species total bases '-z%d' must be in range 1..10000",MinSpeciesTotCntThres);
		exit(1);
		}

	MinSpeciesWithCnts = mincovspecies->count ? mincovspecies->ival[0] : 1;
	if(MinSpeciesWithCnts < 1 || MinSpeciesWithCnts > NumAlignFiles)
		{
		gDiagnostics.DiagOut(eDLFatal,gszProcName,"Error: Minimum species to call marker '-Z%d' must be in range 1..%d",NumAlignFiles);
		exit(1);
		}

// show user current resource limits
#ifndef _WIN32
	gDiagnostics.DiagOut(eDLInfo, gszProcName, "Resources: %s",CUtility::ReportResourceLimits());
#endif

	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing parameters:");
	const char *pszDescr;

	switch(PMode) {
		case ePMdefault:
			pszDescr = "Default marker processing";
			break;
		}

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Processing mode is : '%s'",pszDescr);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum coverage : %d",MinCovBases);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum P-Value : %1.4f'",MaxPValue);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Reference genome assembly name : '%s'",szRefGenome);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum total bases for species at SNP call loci : %d",MinSpeciesTotCntThres);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Maximum alternative species coverage at SNP call loci : %d",AltSpeciesMaxCnt);
	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Minimum number of species with SNP call at same loci : %d",MinSpeciesWithCnts);

	for(Idx=0; Idx < NumRelGenomes; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Alignments and SNPs from this genome (%d) : '%s'",Idx+1,pszRelGenomes[Idx]);

	for(Idx=0; Idx < NumSNPFiles; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input SNP file (%d) : '%s'",Idx+1,pszSNPFiles[Idx]);

	for(Idx=0; Idx < NumAlignFiles; Idx++)
		gDiagnostics.DiagOutMsgOnly(eDLInfo,"Input alignment file (%d) : '%s'",Idx+1,pszAlignFiles[Idx]);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"Output markers to file : '%s'",szMarkerFile);

	gDiagnostics.DiagOutMsgOnly(eDLInfo,"number of threads : %d",NumThreads);

	#ifdef _WIN32
	SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS);
#endif
	gStopWatch.Start();
	Rslt = Process(PMode,MinCovBases,MaxPValue,MinSpeciesTotCntThres,MinSpeciesWithCnts,AltSpeciesMaxCnt,szRefGenome,NumRelGenomes,pszRelGenomes,NumThreads,NumSNPFiles,pszSNPFiles,NumAlignFiles,pszAlignFiles,szMarkerFile);
	gStopWatch.Stop();
	Rslt = Rslt >=0 ? 0 : 1;
	gDiagnostics.DiagOut(eDLInfo,gszProcName,"Exit code: %d Total processing time: %s",Rslt,gStopWatch.Read());
	exit(Rslt);
	}
else
	{
	printf("\n%s Generate Markers, Version %s\n",gszProcName,cpszProgVer);
	arg_print_errors(stdout,end,gszProcName);
	arg_print_syntax(stdout,argtable,"\nUse '-h' to view option and parameter usage\n");
	exit(1);
	}
return 0;
}
示例#19
0
void SimInit(const char* configFile, const char* outputDir, uint32_t shmid) {
    Config config(configFile);

    zinfo = gm_calloc<GlobSimInfo>();
    zinfo->outputDir = gm_strdup(outputDir);

    //Debugging
    //NOTE: This should be as early as possible, so that we can attach to the debugger before initialization.
    zinfo->attachDebugger = config.get<bool>("sim.attachDebugger", false);
    zinfo->harnessPid = getppid();
    getLibzsimAddrs(&zinfo->libzsimAddrs);

    if (zinfo->attachDebugger) {
        gm_set_secondary_ptr(&zinfo->libzsimAddrs);
        notifyHarnessForDebugger(zinfo->harnessPid);
    }

    PreInitStats();

    //Get the number of cores
    //TODO: There is some duplication with the core creation code. This should be fixed eventually.
    uint32_t numCores = 0;
    vector<const char*> groups;
    config.subgroups("sys.cores", groups);
    for (const char* group : groups) {
        uint32_t cores = config.get<uint32_t>(string("sys.cores.") + group + ".cores", 1);
        numCores += cores;
    }

    if (numCores == 0) panic("Config must define some core classes in sys.cores; sys.numCores is deprecated");
    zinfo->numCores = numCores;
    assert(numCores <= MAX_THREADS); //TODO: Is there any reason for this limit?

    zinfo->numDomains = config.get<uint32_t>("sim.domains", 1);
    uint32_t numSimThreads = config.get<uint32_t>("sim.contentionThreads", MAX((uint32_t)1, zinfo->numDomains/2)); //gives a bit of parallelism, TODO tune
    zinfo->contentionSim = new ContentionSim(zinfo->numDomains, numSimThreads);
    zinfo->contentionSim->initStats(zinfo->rootStat);
    zinfo->eventRecorders = gm_calloc<EventRecorder*>(numCores);

    // Global simulation values
    zinfo->numPhases = 0;

    zinfo->phaseLength = config.get<uint32_t>("sim.phaseLength", 10000);
    zinfo->statsPhaseInterval = config.get<uint32_t>("sim.statsPhaseInterval", 100);
    zinfo->freqMHz = config.get<uint32_t>("sys.frequency", 2000);

    //Maxima/termination conditions
    zinfo->maxPhases = config.get<uint64_t>("sim.maxPhases", 0);
    zinfo->maxMinInstrs = config.get<uint64_t>("sim.maxMinInstrs", 0);
    zinfo->maxTotalInstrs = config.get<uint64_t>("sim.maxTotalInstrs", 0);

    uint64_t maxSimTime = config.get<uint32_t>("sim.maxSimTime", 0);
    zinfo->maxSimTimeNs = maxSimTime*1000L*1000L*1000L;

    zinfo->maxProcEventualDumps = config.get<uint32_t>("sim.maxProcEventualDumps", 0);
    zinfo->procEventualDumps = 0;

    zinfo->skipStatsVectors = config.get<bool>("sim.skipStatsVectors", false);
    zinfo->compactPeriodicStats = config.get<bool>("sim.compactPeriodicStats", false);

    //Fast-forwarding and magic ops
    zinfo->ignoreHooks = config.get<bool>("sim.ignoreHooks", false);
    zinfo->ffReinstrument = config.get<bool>("sim.ffReinstrument", false);
    if (zinfo->ffReinstrument) warn("sim.ffReinstrument = true, switching fast-forwarding on a multi-threaded process may be unstable");

    zinfo->registerThreads = config.get<bool>("sim.registerThreads", false);
    zinfo->globalPauseFlag = config.get<bool>("sim.startInGlobalPause", false);

    zinfo->eventQueue = new EventQueue(); //must be instantiated before the memory hierarchy

    //Build the scheduler
    uint32_t parallelism = config.get<uint32_t>("sim.parallelism", 2*sysconf(_SC_NPROCESSORS_ONLN));
    if (parallelism < zinfo->numCores) info("Limiting concurrent threads to %d", parallelism);
    assert(parallelism > 0); //jeez...

    uint32_t schedQuantum = config.get<uint32_t>("sim.schedQuantum", 10000); //phases
    zinfo->sched = new Scheduler(EndOfPhaseActions, parallelism, zinfo->numCores, schedQuantum);

    zinfo->blockingSyscalls = config.get<bool>("sim.blockingSyscalls", false);

    if (zinfo->blockingSyscalls) {
        warn("sim.blockingSyscalls = True, will likely deadlock with multi-threaded apps!");
    }

    InitGlobalStats();

    //Core stats (initialized here for cosmetic reasons, to be above cache stats)
    AggregateStat* allCoreStats = new AggregateStat(false);
    allCoreStats->init("core", "Core stats");
    zinfo->rootStat->append(allCoreStats);

    //Process tree needs this initialized, even though it is part of the memory hierarchy
    zinfo->lineSize = config.get<uint32_t>("sys.lineSize", 64);
    assert(zinfo->lineSize > 0);

    //Port virtualization
    for (uint32_t i = 0; i < MAX_PORT_DOMAINS; i++) zinfo->portVirt[i] = new PortVirtualizer();

    //Process hierarchy
    //NOTE: Due to partitioning, must be done before initializing memory hierarchy
    CreateProcessTree(config);
    zinfo->procArray[0]->notifyStart(); //called here so that we can detect end-before-start races

    zinfo->pinCmd = new PinCmd(&config, NULL /*don't pass config file to children --- can go either way, it's optional*/, outputDir, shmid);

    //Caches, cores, memory controllers
    InitSystem(config);

    //Sched stats (deferred because of circular deps)
    zinfo->sched->initStats(zinfo->rootStat);

    zinfo->processStats = new ProcessStats(zinfo->rootStat);

    //It's a global stat, but I want it to be last...
    zinfo->profHeartbeats = new VectorCounter();
    zinfo->profHeartbeats->init("heartbeats", "Per-process heartbeats", zinfo->lineSize);
    zinfo->rootStat->append(zinfo->profHeartbeats);

    bool perProcessDir = config.get<bool>("sim.perProcessDir", false);
    PostInitStats(perProcessDir, config);

    zinfo->perProcessCpuEnum = config.get<bool>("sim.perProcessCpuEnum", false);

    //Odds and ends
    bool printMemoryStats = config.get<bool>("sim.printMemoryStats", false);
    if (printMemoryStats) {
        gm_stats();
    }

    //HACK: Read all variables that are read in the harness but not in init
    //This avoids warnings on those elements
    config.get<uint32_t>("sim.gmMBytes", (1 << 10));
    if (!zinfo->attachDebugger) config.get<bool>("sim.deadlockDetection", true);
    config.get<bool>("sim.aslr", false);

    // profiling
    zinfo->profileOutputName = config.get<const char*>("sim.profileOutputName", nullptr);
    if (zinfo->profileOutputName)
        zinfo->profileOutputName = gm_strdup(zinfo->profileOutputName);

    //Write config out
    bool strictConfig = config.get<bool>("sim.strictConfig", true); //if true, panic on unused variables
    config.writeAndClose((string(zinfo->outputDir) + "/out.cfg").c_str(), strictConfig);

    zinfo->contentionSim->postInit();

    AppProfiler::init();

    info("Initialization complete");

    //Causes every other process to wake up
    gm_set_glob_ptr(zinfo);
}
示例#20
0
int main(int argc,char** argv)
{
  int n;
  char icon[200];
  char title[30];

  blind=0;
  for( n=1;n<argc;n++) 
  {
    if(strcmp(argv[n],"--version")==0)  {  printf("%s\n",VERSION_); exit(0); }
    if(strcmp(argv[n],"-blind")==0&& n<argc-1 )
    { blind=1;     
      inkeyString=argv[++n];
    } else  if (strcmp(argv[n],"+blind")==0 ) blind=2;
  }

  if(!writeLockFile(".lock"))
  { fprintf(stderr,"locked by other n_calchep. See .lock\n");
    exit(100);
  }
                 
  setenv("CALCHEP",rootDir,0);
  sprintf(pathtocalchep,"%s%c",rootDir,f_slash);
  sprintf(pathtohelp,"%shelp%c",pathtocalchep,f_slash);
  sprintf(icon,"%s/include/icon",pathtocalchep);
  sprintf(title,"CalcHEP_%s/num", VERSION);

  f3_key[2]=f5_key_prog;   f3_mess[2]="Options";
  f3_key[3]=f6_key_prog;   f3_mess[3]="Results";
  f3_key[5]=f8_key_prog;   f3_mess[5]="Calc";
  f3_key[6]=f9_key_prog;   f3_mess[6]="Ref";
  f3_key[7]=f10_key_prog;  f3_mess[7]="Quit";
  
  { int size=100;
     for(;;)
     {  compDir=realloc(compDir,size+20);
        if(getcwd(compDir,size)) break; else size*=2;
     }
     strcat(compDir,"/aux");
     libDir=malloc(strlen(compDir)+20);
     sprintf(libDir,"%s/so_generated",compDir);
     modelNum=1;
     calchepDir=getenv("CALCHEP");
     if(!calchepDir) calchepDir=interface_ext.CALCHEP;
     ForceUG=interface_ext.forceUG;
  }
  

/* **  initialization of the session */
  link_process(PtrInterface_ext);  


  start1(title,icon,"calchep.ini;../calchep.ini",&xw_error);
  nPROCSS=sysconf(_SC_NPROCESSORS_ONLN); 

  if(r_sess__(NULL)==-1)
  { 
     char buff[200];
     int pdg[11]={21,1,-1,2,-2,3,-3,4,-4,5,-5};  
     int k,ok=0;
     strcpy(buff,"{p*\\09");
     for(k=0;k<11;k++)
     {  char*ch=pdg2name(pdg[k]);
        if(ch)
        {  if(ok) strcat(buff,",");
           strcat(buff,ch);
           ok=1;
        }   
     }
     strcat(buff,"}");
     if(ok)
     {  int  blind0=blind;
        char*inkeyString0=inkeyString;    
        inkeyString=buff;
        blind=1;
        edittable(1,4,&compTab,1,"n_comp",0);
        blind=blind0;
        inkeyString=inkeyString0;
        fillCompositeArray();
        
        strcpy(buff,"{%\\09T(p*)\\09 50{%\\09J(p*,p*)\\09 0.5}");
        inkeyString=buff;
        blind=1;
        edittable(1,4,&cutTab,1,"n_cut",0);
        blind=blind0;
        inkeyString=inkeyString0;
     }   
  }
  { char *ch=getenv("nParProc");
    if(ch) sscanf(ch,"%d",&nPROCSS);
  }  
  goto_xy(10,10); print("Calculation of constraints.  Please, be patient.");
  escpressed();
  n_comphep();
  finish();  
  sortie(0);
}
示例#21
0
int
getrusage (int who, struct rusage *usage_p)
{
  if (who == RUSAGE_SELF || who == RUSAGE_CHILDREN)
    {
      /* Clear all unsupported members of 'struct rusage'.  */
      memset (usage_p, '\0', sizeof (struct rusage));

#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
      if (who == RUSAGE_SELF)
        {
          /* Fill in the ru_utime and ru_stime members.  */
          FILETIME creation_time;
          FILETIME exit_time;
          FILETIME kernel_time;
          FILETIME user_time;

          if (GetProcessTimes (GetCurrentProcess (),
                               &creation_time, &exit_time,
                               &kernel_time, &user_time))
            {
              /* Convert to microseconds, rounding.  */
              uint64_t kernel_usec =
                ((((uint64_t) kernel_time.dwHighDateTime << 32)
                  | (uint64_t) kernel_time.dwLowDateTime)
                 + 5) / 10;
              uint64_t user_usec =
                ((((uint64_t) user_time.dwHighDateTime << 32)
                  | (uint64_t) user_time.dwLowDateTime)
                 + 5) / 10;

              usage_p->ru_utime.tv_sec = user_usec / 1000000U;
              usage_p->ru_utime.tv_usec = user_usec % 1000000U;
              usage_p->ru_stime.tv_sec = kernel_usec / 1000000U;
              usage_p->ru_stime.tv_usec = kernel_usec % 1000000U;
            }
        }
#else
      /* Fill in the ru_utime and ru_stime members.  */
      {
        struct tms time;

        if (times (&time) != (clock_t) -1)
          {
            /* Number of clock ticks per second.  */
            unsigned int clocks_per_second = sysconf (_SC_CLK_TCK);

            if (clocks_per_second > 0)
              {
                clock_t user_ticks;
                clock_t system_ticks;

                uint64_t user_usec;
                uint64_t system_usec;

                if (who == RUSAGE_CHILDREN)
                  {
                    user_ticks   = time.tms_cutime;
                    system_ticks = time.tms_cstime;
                  }
                else
                  {
                    user_ticks   = time.tms_utime;
                    system_ticks = time.tms_stime;
                  }

                user_usec =
                  (((uint64_t) user_ticks * (uint64_t) 1000000U)
                   + clocks_per_second / 2) / clocks_per_second;
                system_usec =
                  (((uint64_t) system_ticks * (uint64_t) 1000000U)
                   + clocks_per_second / 2) / clocks_per_second;

                usage_p->ru_utime.tv_sec = user_usec / 1000000U;
                usage_p->ru_utime.tv_usec = user_usec % 1000000U;
                usage_p->ru_stime.tv_sec = system_usec / 1000000U;
                usage_p->ru_stime.tv_usec = system_usec % 1000000U;
              }
          }
      }
#endif

      return 0;
    }
  else
    {
      errno = EINVAL;
      return -1;
    }
}
示例#22
0
文件: os_linux.cpp 项目: fibx/fibjs
result_t os_base::CPUInfo(v8::Local<v8::Array> &retVal)
{
    Isolate* isolate = Isolate::current();
    retVal = v8::Array::New(isolate->m_isolate);

    v8::Local<v8::Object> cpuinfo;
    v8::Local<v8::Object> cputimes;
    uint32_t ticks = (uint32_t) sysconf(_SC_CLK_TCK), multiplier =
                         ((uint64_t) 1000L / ticks), cpuspeed;
    int32_t numcpus = 0, i = 0;
    unsigned long long ticks_user, ticks_sys, ticks_idle, ticks_nice,
             ticks_intr;
    char line[512], speedPath[256], model[512] = "";
    FILE *fpStat = fopen("/proc/stat", "r");
    FILE *fpModel = fopen("/proc/cpuinfo", "r");
    FILE *fpSpeed;

    if (fpModel)
    {
        while (fgets(line, 511, fpModel) != NULL)
        {
            if (strncmp(line, "processor", 9) == 0)
                numcpus++;
            else if (strncmp(line, "model name", 10) == 0)
            {
                if (numcpus == 1)
                {
                    char *p = strchr(line, ':') + 2;
                    strcpy(model, p);
                    model[strlen(model) - 1] = 0;
                }
            }
            else if (strncmp(line, "cpu MHz", 7) == 0)
            {
                if (numcpus == 1)
                    sscanf(line, "%*s %*s : %u", &cpuspeed);
            }
        }
        fclose(fpModel);
    }

    if (fpStat)
    {
        while (fgets(line, 511, fpStat) != NULL)
        {
            if (strncmp(line, "cpu ", 4) == 0)
                continue;
            else if (strncmp(line, "cpu", 3) != 0)
                break;

            sscanf(line, "%*s %llu %llu %llu %llu %*llu %llu", &ticks_user,
                   &ticks_nice, &ticks_sys, &ticks_idle, &ticks_intr);
            snprintf(speedPath, sizeof(speedPath),
                     "/sys/devices/system/cpu/cpu%u/cpufreq/cpuinfo_max_freq",
                     i);

            fpSpeed = fopen(speedPath, "r");

            if (fpSpeed)
            {
                if (fgets(line, 511, fpSpeed) != NULL)
                {
                    sscanf(line, "%u", &cpuspeed);
                    cpuspeed /= 1000;
                }
                fclose(fpSpeed);
            }

            cpuinfo = v8::Object::New(isolate->m_isolate);
            cputimes = v8::Object::New(isolate->m_isolate);
            cputimes->Set(isolate->NewFromUtf8("user"),
                          v8::Number::New(isolate->m_isolate, ticks_user * multiplier));
            cputimes->Set(isolate->NewFromUtf8("nice"),
                          v8::Number::New(isolate->m_isolate, ticks_nice * multiplier));
            cputimes->Set(isolate->NewFromUtf8("sys"),
                          v8::Number::New(isolate->m_isolate, ticks_sys * multiplier));
            cputimes->Set(isolate->NewFromUtf8("idle"),
                          v8::Number::New(isolate->m_isolate, ticks_idle * multiplier));
            cputimes->Set(isolate->NewFromUtf8("irq"),
                          v8::Number::New(isolate->m_isolate, ticks_intr * multiplier));

            if (model[0])
                cpuinfo->Set(isolate->NewFromUtf8("model"), isolate->NewFromUtf8(model));
            cpuinfo->Set(isolate->NewFromUtf8("speed"), v8::Number::New(isolate->m_isolate, cpuspeed));

            cpuinfo->Set(isolate->NewFromUtf8("times"), cputimes);
            retVal->Set(i++, cpuinfo);
        }
        fclose(fpStat);
    }

    return 0;
}
示例#23
0
文件: 19-19.c 项目: shubmit/shub-ltp
/* main function */
int main()
{
	int ret;
	long rts;

	struct sigaction sa;

	/* Initialize output */
	output_init();

	/* Test the RTS extension */
	rts = sysconf(_SC_REALTIME_SIGNALS);

	if (rts < 0L)
	{
		UNTESTED("This test needs the RTS extension");
	}

	/* Set the signal handler */
	sa.sa_flags = SA_SIGINFO;

	sa.sa_sigaction = handler;

	ret = sigemptyset(&sa.sa_mask);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to empty signal set");
	}

	/* Install the signal handler for SIGALRM */
	ret = sigaction(SIGNAL, &sa, 0);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to set signal handler");
	}

	if (called)
	{
		FAILED("The signal handler has been called when no signal was raised");
	}

	ret = raise(SIGNAL);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to raise SIGALRM");
	}

	if (!called)
	{
		FAILED("the sa_handler was not called whereas SA_SIGINFO was not set");
	}

	/* Test passed */
#if VERBOSE > 0

	output("Test passed\n");

#endif

	PASSED;
}
示例#24
0
文件: os_linux.cpp 项目: fibx/fibjs
result_t os_base::freemem(int64_t &retVal)
{
    retVal = sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
    return 0;
}
示例#25
0
	unsigned int SystemInfo::get_page_size(){
#ifdef __TPERF_PLATFORM_ANDROID__
	    return sysconf(_SC_PAGE_SIZE);
#endif
	    return 4*1024;
	}
示例#26
0
sg_mem_stats *sg_get_mem_stats(){

	static sg_mem_stats mem_stat;

#ifdef SOLARIS
	kstat_ctl_t *kc;
	kstat_t *ksp;
	kstat_named_t *kn;
	long totalmem;
	int pagesize;
#endif
#if defined(LINUX) || defined(CYGWIN)
	char *line_ptr;
	unsigned long long value;
	FILE *f;
#endif
#if defined(FREEBSD) || defined(DFBSD)
	int mib[2];
	u_long physmem;
	size_t size;
	u_int free_count;
	u_int cache_count;
	u_int inactive_count;
	int pagesize;
#endif
#if defined(NETBSD) || defined(OPENBSD)
	struct uvmexp *uvm;
#endif

#ifdef SOLARIS
	if((pagesize=sysconf(_SC_PAGESIZE)) == -1){
		sg_set_error_with_errno(SG_ERROR_SYSCONF, "_SC_PAGESIZE");
		return NULL;	
	}

	if((totalmem=sysconf(_SC_PHYS_PAGES)) == -1){
		sg_set_error_with_errno(SG_ERROR_SYSCONF, "_SC_PHYS_PAGES");
		return NULL;
	}

	if ((kc = kstat_open()) == NULL) {
		sg_set_error(SG_ERROR_KSTAT_OPEN, NULL);
		return NULL;
	}
	if((ksp=kstat_lookup(kc, "unix", 0, "system_pages")) == NULL){
		sg_set_error(SG_ERROR_KSTAT_LOOKUP, "unix,0,system_pages");
		return NULL;
	}
	if (kstat_read(kc, ksp, 0) == -1) {
		sg_set_error(SG_ERROR_KSTAT_READ, NULL);
		return NULL;
	}
	if((kn=kstat_data_lookup(ksp, "freemem")) == NULL){
		sg_set_error(SG_ERROR_KSTAT_DATA_LOOKUP, "freemem");
		return NULL;
	}
	kstat_close(kc);

	mem_stat.total = (long long)totalmem * (long long)pagesize;
	mem_stat.free = ((long long)kn->value.ul) * (long long)pagesize;
	mem_stat.used = mem_stat.total - mem_stat.free;
#endif

#if defined(LINUX) || defined(CYGWIN)
	if ((f = fopen("/proc/meminfo", "r")) == NULL) {
		sg_set_error_with_errno(SG_ERROR_OPEN, "/proc/meminfo");
		return NULL;
	}

	while ((line_ptr = sg_f_read_line(f, "")) != NULL) {
		if (sscanf(line_ptr, "%*s %llu kB", &value) != 1) {
			continue;
		}
		value *= 1024;

		if (strncmp(line_ptr, "MemTotal:", 9) == 0) {
			mem_stat.total = value;
		} else if (strncmp(line_ptr, "MemFree:", 8) == 0) {
			mem_stat.free = value;
		} else if (strncmp(line_ptr, "Cached:", 7) == 0) {
			mem_stat.cache = value;
		}
	}

	fclose(f);
	mem_stat.used = mem_stat.total - mem_stat.free;
#endif

#if defined(FREEBSD) || defined(DFBSD)
	/* Returns bytes */
	mib[0] = CTL_HW;
	mib[1] = HW_PHYSMEM;
	size = sizeof physmem;
	if (sysctl(mib, 2, &physmem, &size, NULL, 0) < 0) {
		sg_set_error_with_errno(SG_ERROR_SYSCTL, "CTL_HW.HW_PHYSMEM");
		return NULL;
	}
	mem_stat.total = physmem;

	/*returns pages*/
	size = sizeof free_count;
	if (sysctlbyname("vm.stats.vm.v_free_count", &free_count, &size, NULL, 0) < 0){
		sg_set_error_with_errno(SG_ERROR_SYSCTLBYNAME,
		                        "vm.stats.vm.v_free_count");
		return NULL;
	}

	size = sizeof inactive_count;
	if (sysctlbyname("vm.stats.vm.v_inactive_count", &inactive_count , &size, NULL, 0) < 0){
		sg_set_error_with_errno(SG_ERROR_SYSCTLBYNAME,
		                        "vm.stats.vm.v_inactive_count");
		return NULL;
	}

	size = sizeof cache_count;
	if (sysctlbyname("vm.stats.vm.v_cache_count", &cache_count, &size, NULL, 0) < 0){
		sg_set_error_with_errno(SG_ERROR_SYSCTLBYNAME,
		                        "vm.stats.vm.v_cache_count");
		return NULL;
	}

	/* Because all the vm.stats returns pages, I need to get the page size.
	 * After that I then need to multiple the anything that used vm.stats to
	 * get the system statistics by pagesize 
	 */
	pagesize = getpagesize();
	mem_stat.cache=cache_count*pagesize;

	/* Of couse nothing is ever that simple :) And I have inactive pages to
	 * deal with too. So I'm going to add them to free memory :)
	 */
	mem_stat.free=(free_count*pagesize)+(inactive_count*pagesize);
	mem_stat.used=physmem-mem_stat.free;
#endif

#if defined(NETBSD) || defined(OPENBSD)
	if ((uvm = sg_get_uvmexp()) == NULL) {
		return NULL;
	}

	mem_stat.total = uvm->pagesize * uvm->npages;
#ifdef NETBSD
	mem_stat.cache = uvm->pagesize * (uvm->filepages + uvm->execpages);
#else
	/* Can't find cache memory on OpenBSD */
	mem_stat.cache = 0;
#endif
	mem_stat.free = uvm->pagesize * (uvm->free + uvm->inactive);
	mem_stat.used = mem_stat.total - mem_stat.free;
#endif

	return &mem_stat;
}
示例#27
0
文件: bandwidth.c 项目: heechul/misc
int main(int argc, char *argv[])
{
	long sum = 0;
	unsigned finish = 5;
	int prio = 0;        
	int num_processors;
	int acc_type = READ;
	int opt;
	cpu_set_t cmask;
	int use_mmap = 0;
	int iterations = 0;
	int i;

	/*
	 * get command line options 
	 */
	while ((opt = getopt(argc, argv, "m:a:n:t:c:i:p:f:l:xh")) != -1) {
		switch (opt) {
		case 'm': /* set memory size */
			g_mem_size = 1024 * strtol(optarg, NULL, 0);
			break;
		case 'a': /* set access type */
			if (!strcmp(optarg, "read"))
				acc_type = READ;
			else if (!strcmp(optarg, "write"))
				acc_type = WRITE;
			else if (!strcmp(optarg, "rdwr"))
				acc_type = RDWR;
			else
				exit(1);
			break;
			
		case 'n': /* set access pattern */
			/* sequential */
			if( strcmp(optarg,"Seq") == 0 ) {
				g_indx = 0;
				g_next = (CACHE_LINE_SIZE/4);				
			}
			/* same bank */
#if P4080_MCTRL_INTRV_NONE
			else if( strcmp(optarg,"Row") == 0 ) {
				g_indx = 0;
				g_next = (CACHE_LINE_SIZE/4) * 1024;

			}
			/* diff bank */
			else if( strcmp(optarg,"Bank") == 0 ) {
				g_indx = 128*(CACHE_LINE_SIZE/4);
				g_next = (CACHE_LINE_SIZE/4) * 1024;
			}
#elif P4080_MCTRL_INTRV_CLCS
			else if( strcmp(optarg,"Row") == 0 ) {
				g_indx = 0;
				g_next = (CACHE_LINE_SIZE/4) * 1024 * 8;// 2^19
			}
			/* diff bank */
			else if( strcmp(optarg,"Bank") == 0 ) {
				g_indx = 256*(CACHE_LINE_SIZE/4); // 2^16
				g_next = (CACHE_LINE_SIZE/4) * 1024 * 8;// 2^19
			}
#endif
			else
				exit(1);
			break;

		case 't': /* set time in secs to run */
			finish = strtol(optarg, NULL, 0);
			break;
			
		case 'c': /* set CPU affinity */
			cpuid = strtol(optarg, NULL, 0);
			num_processors = sysconf(_SC_NPROCESSORS_CONF);
			CPU_ZERO(&cmask);
			CPU_SET(cpuid % num_processors, &cmask);
			if (sched_setaffinity(0, num_processors, &cmask) < 0)
				perror("error");
			else
				fprintf(stderr, "assigned to cpu %d\n", cpuid);
			break;
			
		case 'p': /* set priority */
			prio = strtol(optarg, NULL, 0);
			if (setpriority(PRIO_PROCESS, 0, prio) < 0)
				perror("error");
			else
				fprintf(stderr, "assigned priority %d\n", prio);
			break;
		case 'i': /* iterations */
			iterations = strtol(optarg, NULL, 0);
			break;
		case 'l': /* set label */
			g_label = strdup(optarg);
			break;
			
		case 'f': /* set file descriptor */
			g_fd = fopen(optarg, "a+");
			if (g_fd == NULL) 
				perror("error");
			break;
		case 'x': /* mapping to /dev/mem. !! DANGEROUS !! */
			use_mmap = 1;
			break;
		case 'h': 
			usage(argc, argv);
			break;
		}
	}

	g_indx *= cpuid;

	/*
	 * allocate contiguous region of memory 
	 */ 
	if (use_mmap) {
		/* open /dev/mem for accessing memory in physical addr. */
		int fd = -1;
		unsigned long offset;

		fprintf(stderr, "Use mmap| g_indx: 0x%x g_next: 0x%x\n", g_indx, g_next);
		fd = open("/dev/mem", O_RDWR | O_SYNC);
		if(fd == -1) {
			fprintf(stderr, "ERROR Opening /dev/mem\n");	
			exit(1);
		} 
		/* offset variable is used to allocate each cpu to a different offset 
		   from each other */
		offset = ADDR_2ND_RANK; /*  + cpuid*g_mem_size;*/
		fprintf(stderr, "offset: %p\n", (void *)offset);
		/* use mmap to allocate each cpu to the specific address in memory */
		g_mem_ptr = (int *)mmap(NULL, g_mem_size, PROT_READ|PROT_WRITE, 
					MAP_SHARED, fd, offset);
		if(g_mem_ptr == NULL) {
			fprintf(stderr, "could not allocate memarea");
			exit(1);
		}
		fprintf(stderr, "mmap was successful: addr=%p\n", g_mem_ptr);
	} else {
		printf("Use standard malloc\n");
		g_mem_ptr = (int *)malloc(g_mem_size);
	}

	for (i = 0; i < g_mem_size / sizeof(int); i++)
		g_mem_ptr[i] = i;

	memset((char *)g_mem_ptr, 1, g_mem_size);
	fprintf(stderr, "VADDR: %p-%p\n", (char *)g_mem_ptr, (char *)g_mem_ptr + g_mem_size);

	/* print experiment info before starting */
	printf("memsize=%d KB, type=%s, cpuid=%d\n",
	       g_mem_size/1024,
	       ((acc_type==READ) ?"read":
		(acc_type==WRITE)? "write" :
		(acc_type==RDWR) ? "rdwr" : "worst"),
		cpuid);
	printf("stop at %d\n", finish);

	/* set signals to terminate once time has been reached */
	signal(SIGINT, &quit);
	if (finish > 0) {
		signal(SIGALRM, &quit);
		alarm(finish);
	}

	/*
	 * actual memory access
	 */
	g_start = get_usecs();
	for (i=0;; i++) {
		switch (acc_type) {
		case READ:
			sum += bench_read();
			break;
		case WRITE:
			sum += bench_write();
			break;
		case RDWR:
			sum += bench_rdwr();
			break;
		}

		if (iterations > 0 && i >= iterations)
			break;
	}
	printf("total sum = %ld\n", sum);
	quit(0);
}
示例#28
0
文件: httpd.c 项目: Pferd/ribs2
int main(int argc, char *argv[]) {
    static struct option long_options[] = {
        {"port", 1, 0, 'p'},
        {"daemonize", 0, 0, 'd'},
        {"forks", 1, 0, 'f'},
        {0, 0, 0, 0}
    };

    int port = 8080;
    int daemon_mode = 0;
    long forks = 0;
    while (1) {
        int option_index = 0;
        int c = getopt_long(argc, argv, "p:f:d", long_options, &option_index);
        if (c == -1)
            break;
        switch (c) {
        case 'p':
            port = atoi(optarg);
            break;
        case 'd':
            daemon_mode = 1;
            break;
        case 'f':
            forks = atoi(optarg);
            break;
        }
    }

    /* server config */
    struct http_server server = {
        /* port number */
        .port = port,

        /* call simple_file_server upon receiving http request */
        .user_func = simple_file_server,

        /* set idle connection timeout to 60 seconds */
        .timeout_handler.timeout = 60000,

        /* set fiber's stack size to automatic (0) */
        .stack_size = 0,

        /* start the server with 100 stacks */
        /* more stacks will be created if necessary */
        .num_stacks =  100,

        /* we expect most of our requests to be less than 8K */
        .init_request_size = 8192,

        /* we expect most of our response headers to be less than
           8K */
        .init_header_size = 8192,

        /* we expect most of our response payloads to be less than
           8K */
        .init_payload_size = 8192,

        /* no limit on the request size, this should be set to
           something reasonable if you want to protect your server
           against denial of service attack */
        .max_req_size = 0,

        /* no additional space is needed in the context to store app
           specified data (fiber local storage) */
        .context_size = 0
    };

    /* initialize server, but don't accept connections yet */
    if (0 > http_server_init(&server))
        exit(EXIT_FAILURE);

    /* run as daemon if specified */
    if (daemon_mode)
        daemonize(), daemon_finalize();

    if (0 >= forks) {
        forks = sysconf(_SC_NPROCESSORS_CONF);
        if (0 > forks)
            exit(EXIT_FAILURE);
    }

    for(;forks > 1;--forks){
        if (0 >= fork()) {
            break;
        }
    }

    /* initialize the event loop */
    if (epoll_worker_init() < 0)
        exit(EXIT_FAILURE);

    /* start accepting connections, must be called after initializing
       epoll worker */
    if (0 > http_server_init_acceptor(&server))
        exit(EXIT_FAILURE);

    epoll_worker_loop();
    return 0;
}
示例#29
0
文件: mem.c 项目: JanyHuang/ltp
void create_same_memory(int size, int num, int unit)
{
	int i, j, status, *child;
	unsigned long ps, pages;
	struct ksm_merge_data **ksm_data;

	struct ksm_merge_data ksm_data0[] = {
	       {'c', size*MB}, {'c', size*MB}, {'d', size*MB}, {'d', size*MB},
	};
	struct ksm_merge_data ksm_data1[] = {
	       {'a', size*MB}, {'b', size*MB}, {'d', size*MB}, {'d', size*MB-1},
	};
	struct ksm_merge_data ksm_data2[] = {
	       {'a', size*MB}, {'a', size*MB}, {'d', size*MB}, {'d', size*MB},
	};

	ps = sysconf(_SC_PAGE_SIZE);
	pages = MB / ps;

	ksm_data = malloc((num - 3) * sizeof(struct ksm_merge_data *));
	/* Since from third child, the data is same with the first child's */
	for (i = 0; i < num - 3; i++) {
		ksm_data[i] = malloc(4 * sizeof(struct ksm_merge_data));
		for (j = 0; j < 4; j++) {
			ksm_data[i][j].data = ksm_data0[j].data;
			ksm_data[i][j].mergeable_size =
				ksm_data0[j].mergeable_size;
		}
	}

	child = malloc(num * sizeof(int));
	if (child == NULL)
		tst_brkm(TBROK | TERRNO, cleanup, "malloc");

	for (i = 0; i < num; i++) {
		fflush(stdout);
		switch (child[i] = fork()) {
		case -1:
			tst_brkm(TBROK|TERRNO, cleanup, "fork");
		case 0:
			if (i == 0) {
				create_ksm_child(i, size, unit, ksm_data0);
				exit(0);
			} else if (i == 1) {
				create_ksm_child(i, size, unit, ksm_data1);
				exit(0);
			} else if (i == 2) {
				create_ksm_child(i, size, unit, ksm_data2);
				exit(0);
			} else {
				create_ksm_child(i, size, unit, ksm_data[i-3]);
				exit(0);
			}
		}
	}

	stop_ksm_children(child, num);

	tst_resm(TINFO, "KSM merging...");
	SAFE_FILE_PRINTF(cleanup, PATH_KSM "run", "1");
	SAFE_FILE_PRINTF(cleanup, PATH_KSM "pages_to_scan", "%ld",
			 size * pages *num);
	SAFE_FILE_PRINTF(cleanup, PATH_KSM "sleep_millisecs", "0");

	resume_ksm_children(child, num);
	group_check(1, 2, size * num * pages - 2, 0, 0, 0, size * pages * num);

	stop_ksm_children(child, num);
	resume_ksm_children(child, num);
	group_check(1, 3, size * num * pages - 3, 0, 0, 0, size * pages * num);

	stop_ksm_children(child, num);
	resume_ksm_children(child, num);
	group_check(1, 1, size * num * pages - 1, 0, 0, 0, size * pages * num);

	stop_ksm_children(child, num);
	resume_ksm_children(child, num);
	group_check(1, 1, size * num * pages - 2, 0, 1, 0, size * pages * num);

	stop_ksm_children(child, num);

	tst_resm(TINFO, "KSM unmerging...");
	SAFE_FILE_PRINTF(cleanup, PATH_KSM "run", "2");

	resume_ksm_children(child, num);
	group_check(2, 0, 0, 0, 0, 0, size * pages * num);

	tst_resm(TINFO, "stop KSM.");
	SAFE_FILE_PRINTF(cleanup, PATH_KSM "run", "0");
	group_check(0, 0, 0, 0, 0, 0, size * pages * num);

	while (waitpid(-1, &status, WUNTRACED | WCONTINUED) > 0)
		if (WEXITSTATUS(status) != 0)
			tst_resm(TFAIL, "child exit status is %d",
				 WEXITSTATUS(status));
}
示例#30
0
static unsigned
vmstat(int iindex)
{
    double          duse, dsys, didl, ddiv, divo2;
    double          druse, drnic, drsys, dridl;
    unsigned int    hertz;
    double          ddiv2;

    netsnmp_cpu_info *cpu;
    netsnmp_cpu_load();
    cpu = netsnmp_cpu_get_byIdx( -1, 0 );

    duse = cpu->user_ticks + cpu->nice_ticks;
    dsys = cpu->sys_ticks;
    didl = cpu->idle_ticks;
    ddiv = duse + dsys + didl;
    hertz = sysconf(_SC_CLK_TCK);  /* get ticks/s from system */
    divo2 = ddiv / 2;
    druse = cpu->user_ticks;
    drnic = cpu->nice_ticks;
    drsys = cpu->sys_ticks;
    dridl = cpu->idle_ticks;

    ddiv2 = ddiv + cpu->wait_ticks
                 + cpu->intrpt_ticks
                 + cpu->sirq_ticks;
    if (cpu->history) {
        duse  -= (cpu->history[0].user_hist + cpu->history[0].nice_hist);
        dsys  -=  cpu->history[0].sys_hist;
        didl  -=  cpu->history[0].idle_hist;
        ddiv2 -=  cpu->history[0].total_hist;
    }
    if (!ddiv) ddiv=1;   /* Protect against division-by-0 */
 
    switch (iindex) {
    case swapin:
        return (cpu->swapIn  * 4 * hertz + divo2) / ddiv;
    case swapout:
        return (cpu->swapOut * 4 * hertz + divo2) / ddiv;
    case iosent:
        return (cpu->pageIn      * hertz + divo2) / ddiv;
    case ioreceive:
        return (cpu->pageOut     * hertz + divo2) / ddiv;
    case sysinterrupts:
        return (cpu->nInterrupts  * hertz + divo2) / ddiv;
    case syscontext:
        return (cpu->nCtxSwitches * hertz + divo2) / ddiv;
    case cpuuser:
        return (ddiv2 ? 100 * duse / ddiv2 : 0);
    case cpusystem:
        return (ddiv2 ? 100 * dsys / ddiv2 : 0);
    case cpuidle:
        return (ddiv2 ? 100 * didl / ddiv2 : 0);
    case cpurawuser:
        return druse;
    case cpurawnice:
        return drnic;
    case cpurawsystem:
        return drsys;
    case cpurawidle:
        return dridl;
    case rawinterrupts:
        return cpu->nInterrupts;
    case rawcontext:
        return cpu->nCtxSwitches;
    case cpurawwait:
	return cpu->wait_ticks;
    case cpurawinter:
	return cpu->intrpt_ticks;
    case cpurawsoft:
	return cpu->sirq_ticks;
    case rawiosent:
	return cpu->pageOut*2;
    case rawioreceive:
	return cpu->pageIn*2;
    case rawswapin:
	return cpu->swapIn;
    case rawswapout:
	return cpu->swapOut;
    default:
        return -1;
    }
}