GnomeVFSResult 
_gnome_vfs_monitor_do_cancel (GnomeVFSMonitorHandle *handle)
{
	GnomeVFSResult result;

	init_hash_table ();

	if (!VFS_METHOD_HAS_FUNC(handle->uri->method, monitor_cancel)) {
		return GNOME_VFS_ERROR_NOT_SUPPORTED;
	}

	result = handle->uri->method->monitor_cancel (handle->uri->method,
						      handle->method_handle);

	if (result == GNOME_VFS_OK) {
		G_LOCK (handle_hash);
		/* mark this monitor as cancelled */
		handle->cancelled = TRUE;

		/* we might be in the unlocked part of actually_dispatch_callback,
		 * in that case, don't free the handle now.
		 * Instead we do it in actually_dispatch_callback.
		 */
		if (!handle->in_dispatch) {
			destroy_monitor_handle (handle);
		}
		G_UNLOCK (handle_hash);
	}

	return result;
}
Beispiel #2
0
void cacheex_init_hitcache(void)
{
	init_hash_table(&ht_hitcache, &ll_hitcache);
	if (pthread_rwlock_init(&hitcache_lock,NULL) != 0)
		cs_log("Error creating lock hitcache_lock!");
	cacheex_running = true;
}
Beispiel #3
0
static PyObject* hash_init_hash_table(PyObject*self, PyObject*args
                                     //   PyObject*Name, 
                                      //  PyObject*UserName,
                                      //  PyObject*UserPassword
                                        )
{
    int res;
    char* DBName;
    char* DBUserName;
    char* DBUserPassword;
    PyObject*retu;  
    res = PyArg_ParseTuple(args,
                            //Name,
                            //UserName,
                            //UserPassword,
                            "sss",
                            &DBName,
                            &DBUserName,
                            &DBUserPassword);
    if(!res)
    {
        return NULL;
    }
    res = init_hash_table(DBName, DBUserName, DBUserPassword);
    retu = (PyObject*)Py_BuildValue("i", res);
    return retu;
}
Beispiel #4
0
static void
make_forward_references_hash1(void) {
	int n;

	init_hash_table();

	/* set up the forward references using the last_index hash table */
	for (n = 0; n < Number_Of_Texts; n++) {
		struct text *txt = &Text[n];
		size_t j;

		for (	/* all pos'ns in txt except the last Min_Run_Size-1 */
			j = txt->tx_start;			/* >= 1 */
			j + Min_Run_Size - 1 < txt->tx_limit;
			j++
		) {
			if (May_Be_Start_Of_Run(Token_Array[j])) {
				size_t h = hash1(&Token_Array[j]);

				if (last_index[h]) {
					forward_reference[last_index[h]] = j;
				}
				last_index[h] = j;
			}
		}
	}
	Free((char *)last_index);

#ifdef	DB_FORW_REF
	db_forward_references("first hashing");
#endif	/* DB_FORW_REF */
}
Beispiel #5
0
int main()
{

	hash_table_t * table = NULL;
	init_hash_table(&table,10,10);
	int * num = NULL;
	int i = 0;
	char iNum[40];
	bzero(iNum,40);
	for (i=0;i<64;i++) {
		sprintf(iNum,"%d",i);
		num = (int *) malloc(sizeof(int));
		*num = i;
		insert_hash_elem(*table,iNum,num);
	}

	void * element  = NULL;

	sprintf(iNum,"%d",20);	
	get_value(*table,iNum,&element);
	if (element) {
		printf("%d\n", *((int*)element));
	}

	destroy_hash_table(&table,10);
	return 0;
}
Beispiel #6
0
struct file * file_entry_init(char *filename){
	struct file * rtn = (struct file *)malloc(sizeof(struct file));
	rtn->filename = string_init(filename);
	rtn->type_table = init_hash_table();
	rtn->definition_list = NULL;
	rtn->next = NULL;
	return rtn;
}
Beispiel #7
0
int init_symbol_table(Symbol_Table **table)
{
    *table = malloc(sizeof(Symbol_Table));
    if (table == NULL)
        return 1;
    (*table)->sp = 0;
    (*table)->next_scope = 1;
    return init_hash_table(&(*table)->table);
}
Beispiel #8
0
//初始化数据库连接及xml
void init_library()
{
	//连接数据库
	mysql_handle = new_mysql_connect(MYSQL_HOST,MYSQL_USERNAME,MYSQL_USERPASS,MYSQL_DBNAME);
	//初始化xml解析器
	xmlInitParser();
	//初始化事件hash表
	init_hash_table();
}
Beispiel #9
0
void test_labels(void) {
    init_hash_table();
    Instruction* i = new_instruction_label("test", 1);
    TEST_ASSERT_EQUAL_STRING("test", i->opcode);
    TEST_ASSERT(i->type = I_TYPE_LABEL);
    set_label_address("test", 34);
    Address* a = addr_from_label(strdup("test"));
    resolve_address(a);
    TEST_ASSERT_EQUAL_INT_MESSAGE(34, a->immediate, "Incorrect label address");
    free(a);
    free(i);
}
cc_xid_table_t*
cc_init_xid_table(void)
{
    cc_xid_table_t *new_xid_table;

    new_xid_table = malloc(sizeof(cc_xid_table_t));
    if(new_xid_table == NULL)
        return NULL;
    new_xid_table->hash_table = init_hash_table();
    if(new_xid_table->hash_table == NULL)
        return NULL;

    new_xid_table->count = 0;
    return new_xid_table;
}
Beispiel #11
0
int main(int argc, char*argv[])
{
    int ret;
    ret = init_hash_table();//初始化hash表;
    if(ret)
    {
        printf("init_hash_table error!\n");
    }
    
    evutil_socket_t listener;//定义套接字描述符变量;
    listener = socket(AF_INET, SOCK_STREAM, 0);//建立套接字;
    assert(listener > 0);
    
    evutil_make_listen_socket_reuseable(listener);//
    
    //定义地址族结构;
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;   
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons(LISTEN_PORT);//设定端口号;
    
    if(bind(listener,(struct sockaddr*)&sin, sizeof(sin))<0)//绑定;
    {
        perror("bind");
        return 1;
    }
    
    if(listen(listener, LISTEN_BACKLOG) < 0)//监听;
    {
        perror("listen error\n");
        return 1;
    }
    printf("Listening...\n");
    
    evutil_make_socket_nonblocking(listener);//设置套接字为不阻塞;
    
    struct event_base *base = event_base_new();//创建event_base对象;
    assert(base != NULL);
    
    //创建并绑定event;
    struct event *listen_event;
    listen_event = event_new(base, listener, EV_READ|EV_PERSIST, do_accept, (void*)base);
    event_add(listen_event, NULL);//添加对象,NULL表示无超时设置;
    event_base_dispatch(base);//启用循环;
    
    printf("The End.");
    return 0;
}
Beispiel #12
0
int init_pool_object(PoolObject *pool, size_t size_table){
    pool->arrays.used = 0;
    pool->arrays.alloced_ptr = INIT_QUANTITY_ARRAYS;
    pool->arrays.arr = malloc(INIT_QUANTITY_ARRAYS * sizeof(Array_inode));
    if (pool->arrays.arr == NULL){
        errno = ENOMEM;
        return -1;
    }
    init_empty_list(&pool->free_list);
    init_empty_ilist(&pool->list_zero);
    if (init_hash_table(&pool->table, size_table) < 0){
        free(pool->arrays.arr);
        errno = ENOMEM;
        return -1;
    }
    return 0;
}
Beispiel #13
0
int main(int argc, char* const argv[]) {
    FILE* o = NULL;
    FILE* in = NULL;
    opterr = 0;
    int c;
    setenv("POSIXLY_CORRECT", "1", 1);
    while (optind < argc) {
        if ((c = getopt(argc, argv, "o:bh")) != -1) {
            switch (c) {
                case 'o':
                    o = fopen(optarg, "wb");
                    break;
                case 'b':
                    binary_mode = true;
                    break;
                case 'h':
                    puts("Usage: d16 [-bh] -o [outputfile] [input]\n");
                    exit(0);
                    break;
            }
        } else {
            if (in == NULL) {
                in = fopen(argv[optind], "r");
            }
            optind++;
        }
    }

    if (in == NULL) {
        fprintf(stderr, "d16: No input files specified\n");
        exit(-1);
    }
    if (o == NULL) {
        o = fopen("a.out", "wb");
    }
    GString* input = read_replace_macros(in);
    struct yy_buffer_state* yystate = read_string(input->str);
    init_hash_table();
    yyparse(o);
    yy_delete_buffer(yystate);
    g_string_free(input, true);
    fclose(o);
    return 0;
}
Beispiel #14
0
END_TEST

START_TEST (ut_hash_table_insert_and_delete)
{
  init_hash_table(test_hash_table, DEFAULT_SIZE);
  wchar_t c;
  int i;
  Node *result;
  for (c = L'a'; c <= L'z'; c++)
  {
    insert_node_hash_table(test_hash_table, c);
  }
  for (c = L'a'; c <= L'z'; c++)
  {
    delete_node_hash_table(test_hash_table, c);
  }
  ck_assert_msg(test_hash_table->array->total == 0, "%d\n", test_hash_table->array->total);
  ck_assert_msg(test_hash_table->array->size == 2, "%d\n", test_hash_table->array->size);
  clear_hash_table(test_hash_table);
}
GnomeVFSResult
_gnome_vfs_monitor_do_add (GnomeVFSMethod *method,
			  GnomeVFSMonitorHandle **handle,
			  GnomeVFSURI *uri,
                          GnomeVFSMonitorType monitor_type,
			  GnomeVFSMonitorCallback callback,
			  gpointer user_data)
{
	GnomeVFSResult result;
	GnomeVFSMonitorHandle *monitor_handle = 
		g_new0(GnomeVFSMonitorHandle, 1);

	init_hash_table ();
	gnome_vfs_uri_ref (uri);
	monitor_handle->uri = uri;

	monitor_handle->type = monitor_type;
	monitor_handle->callback = callback;
	monitor_handle->user_data = user_data;
	monitor_handle->pending_callbacks = g_queue_new ();
	monitor_handle->min_send_at = 0;

	result = uri->method->monitor_add (uri->method, 
			&monitor_handle->method_handle, uri, monitor_type);

	if (result != GNOME_VFS_OK) {
		gnome_vfs_uri_unref (uri);
		g_free (monitor_handle);
		monitor_handle = NULL;
	} else {
		G_LOCK (handle_hash);
		g_hash_table_insert (handle_hash, 
				     monitor_handle->method_handle,
				     monitor_handle);
		G_UNLOCK (handle_hash);
	}

	*handle = monitor_handle;

	return result;
}
Beispiel #16
0
int main()
{
	HT = init_hash_table(HASH_TABLE_STARTING_SIZE);
	char command;
	char line[MAXSIZE];

	while ((command = getchar()))
	{
		getchar();
		switch (command)
		{
			case 'a':
				fgets(line, MAXSIZE, stdin);
				command_a(line);
				break;

			case 's':
				command_s();
				break;

			case 'm':
				command_m();
				break;

			case 'l':

				command_l();
				break;

			case 'x':
				command_x();
				return 0;

			default:
				printf("unknown command: %c\n", command);
		}
	}
	return 0;
}
Beispiel #17
0
static Node *get_compute(Node *head, hist_t *hist_list, unsigned int hist_len)
{
	int i;
	Node *node;
	Node *to_free;
	Node **hash_table;
	Node *compute = NULL;

	hash_table = (Node **)malloc(sizeof(Node *) * HASH_TABLE_SIZE);
	if(!hash_table) {
		printf("Malloc failed\n");
		return NULL;
	}

	init_hash_table(hash_table, HASH_TABLE_SIZE);

	for(i = 0; i < hist_len; i++) {
		add_entry(hash_table, HASH_TABLE_SIZE, hist_list[i].fname);
	}

	node = head;
	while(node) {
		if(exists_in_hash(hash_table, HASH_TABLE_SIZE, node->name)) {
			to_free = node;
			node = node->next;
			free(to_free);
		} else {
			/* Add to compute list */
			to_free = node->next;
			node->next = compute;
			compute = node;
			node = to_free;
		}
	}
	purge_hash_table(hash_table, HASH_TABLE_SIZE);
	free(hash_table);
	return compute;
}
Beispiel #18
0
OS *os_new(uns num_pages, uns num_threads)
{
    OS *os = (OS *) calloc (1, sizeof (OS));

    os->num_pages      = num_pages;
    os->num_threads    = num_threads;
    os->lines_in_page  = OS_PAGESIZE/CACHE_LINE_SIZE;

    os->pt     = (PageTable *) calloc (1, sizeof (PageTable));
    os->pt->entries     = (Hash_Table *) calloc (1, sizeof(Hash_Table));
    init_hash_table(os->pt->entries, "PageTableEntries", 4315027, sizeof( PageTableEntry ));
    os->pt->max_entries = os->num_pages;

    os->ipt     = (InvPageTable *) calloc (1, sizeof (InvPageTable));
    os->ipt->entries = (InvPageTableEntry *) calloc (os->num_pages, sizeof (InvPageTableEntry));
    os->ipt->num_entries = os->num_pages;

    assert(os->pt->entries);
    assert(os->ipt->entries);

    printf("Initialized OS for %u pages\n", num_pages);

    //TLB
    os->tlb = (TLB *) calloc(1,sizeof (TLB));
    os->tlb->num_entries = 0;
    os->tlb->last_vpn = 0;
    os->tlb->TLB_access = 0;
    os->tlb->TLB_same_page_hit = 0;
    os->tlb->TLB_hit = 0;
    os->tlb->TLB_miss = 0;
    os->tlb->TLB_eviction = 0;
    os->tlb->TLB_L3_hit = 0;
    os->tlb->TLB_Memory_Access = 0;
    os->tlb->TLB_HDD_Access = 0;
    printf("Initialized TLB for %u entires\n", TLB_SIZE);

    return os;
}
Beispiel #19
0
END_TEST

START_TEST (ut_hash_table_insert_and_lookup)
{
  init_hash_table(test_hash_table, DEFAULT_SIZE);
  wchar_t c;
  int i;
  Node *result;
  for (c = L'a'; c <= L'z'; c++)
  {
    insert_node_hash_table(test_hash_table, c);
  }

  for (c = L'a'; c <= L'z'; c++)
  {
    result = lookup_node_hash_table(test_hash_table, c);
    if (result != NULL) ck_assert_msg(result->key == c, "%c != %c", result->key, c);
    else ck_abort_msg("Couldn't find character %c", c);
  }
  ck_assert_msg(test_hash_table->array->total == 26);
  ck_assert_msg(test_hash_table->array->size == 32);
  clear_hash_table(test_hash_table);
}
Beispiel #20
0
int main(int argc, char **argv){
	int option;
	int interval;
	int count;
	int i;
	int num_of_rec;			// records the number of records
	perfstat_disk_t *pstat_disk; 
	opterr = 0;
	interval = 5;
	count = -1;
	while((option = getopt(argc, argv, "i:c:f:o:p:h")) != -1){
		switch(option){
		case 'i':
			interval = atoi(optarg);
			break;
		case 'c':
			count = atoi(optarg);
			break;
		case 'f':
			strncpy(conf, optarg, strlen(optarg));
			break;
		case 'o':
			strncpy(target, optarg, strlen(optarg));
			w_to_file = 1;
			break;
		case 'p':
			linepool = atoi(optarg)	;
			break;
		case 'h':
		case '?':
			usage();
		}
	}
	// read configs from conf file
	init_hash_table();
	init_records();
	num_of_rec = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0);
	pstat_disk = (perfstat_disk_t *)malloc(num_of_rec*sizeof(perfstat_disk_t));
	if(pstat_disk == NULL){
		perror("pstat_disk malloc fail");
		return -1;
	}
	perfstat_id_t first_disk = {.name = FIRST_DISK};
	i = 0;
	if(!w_to_file)
		fprintf(stdout, "TIME,VGNAME,IOPS,RIOPS,WIOPS,RTRAFFIC,WTRAFFIC,RSIZE,WSIZE,RSERV,WSERV,UTIL\n");
	while(i < count || count < 0){
		clear_the_record_list(&root_curr);
		if(collect_disk_info(pstat_disk, num_of_rec) < 0) {
			perror("perfstat disk error");
			return -1;
		}
		merge_disk(pstat_disk, num_of_rec);
		print_vginfo(w_to_file, &root_curr, &root_last, interval);
		rotate_record_list(&root_curr, &root_last);
		sleep(interval);
		++i;
	}
	//FIXme:
	free(pstat_disk);
	//free_records();
	return 0;
}
Beispiel #21
0
static int mod_init(void)
{

	DBG( "TM - initializing...\n");
	/* checking if we have sufficient bitmap capacity for given
	   maximum number of  branches */
	if (MAX_BRANCHES+1>31) {
		LOG(L_CRIT, "Too many max UACs for UAC branch_bm_t bitmap: %d\n",
			MAX_BRANCHES );
		return -1;
	}

	if (init_callid() < 0) {
		LOG(L_CRIT, "Error while initializin Call-ID generator\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_uac, "t_uac_dlg", 0) < 0) {
		LOG(L_CRIT, "cannot register fifo t_uac\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_hash, "t_hash", 0)<0) {
		LOG(L_CRIT, "cannot register hash\n");
		return -1;
	}

	if (!init_hash_table()) {
		LOG(L_ERR, "ERROR: mod_init: initializing hash_table failed\n");
		return -1;
	}


	/* init static hidden values */
	init_t();

	if (!tm_init_timers()) {
		LOG(L_ERR, "ERROR: mod_init: timer init failed\n");
		return -1;
	}
	/* register the timer function */
	register_timer( timer_routine , 0 /* empty attr */, 1 );

	/* init_tm_stats calls process_count, which should
	 * NOT be called from mod_init, because one does not
	 * now, if a timer is used and thus how many processes
	 * will be started; however we started already our
	 * timers, so we know and process_count should not
	 * change any more
	 */	
	if (init_tm_stats()<0) {
		LOG(L_CRIT, "ERROR: mod_init: failed to init stats\n");
		return -1;
	}

	/* building the hash table*/

	if (uac_init()==-1) {
		LOG(L_ERR, "ERROR: mod_init: uac_init failed\n");
		return -1;
	}
	/* register post-script clean-up function */
	register_script_cb( w_t_unref, POST_SCRIPT_CB, 
			0 /* empty param */ );
	register_script_cb( script_init, PRE_SCRIPT_CB , 
			0 /* empty param */ );

	tm_init_tags();

	return 0;
}
Beispiel #22
0
int main(int argc, char **argv)
{
  program_name = argv[0];
  static char stderr_buf[BUFSIZ];
  setbuf(stderr, stderr_buf);
  
  const char *base_name = 0;
  typedef int (*parser_t)(const char *);
  parser_t parser = do_file;
  const char *directory = 0;
  const char *foption = 0;
  int opt;
  static const struct option long_options[] = {
    { "help", no_argument, 0, CHAR_MAX + 1 },
    { "version", no_argument, 0, 'v' },
    { NULL, 0, 0, 0 }
  };
  while ((opt = getopt_long(argc, argv, "c:o:h:i:k:l:t:n:c:d:f:vw",
			    long_options, NULL))
	 != EOF)
    switch (opt) {
    case 'c':
      common_words_file = optarg;
      break;
    case 'd':
      directory = optarg;
      break;
    case 'f':
      foption = optarg;
      break;
    case 'h':
      check_integer_arg('h', optarg, 1, &hash_table_size);
      if (!is_prime(hash_table_size)) {
	while (!is_prime(++hash_table_size))
	  ;
	warning("%1 not prime: using %2 instead", optarg, hash_table_size);
      }
      break;
    case 'i':
      ignore_fields = optarg;
      break;
    case 'k':
      check_integer_arg('k', optarg, 1, &max_keys_per_item);
      break;
    case 'l':
      check_integer_arg('l', optarg, 0, &shortest_len);
      break;
    case 'n':
      check_integer_arg('n', optarg, 0, &n_ignore_words);
      break;
    case 'o':
      base_name = optarg;
      break;
    case 't':
      check_integer_arg('t', optarg, 1, &truncate_len);
      break;
    case 'w':
      parser = do_whole_file;
      break;
    case 'v':
      printf("GNU indxbib (groff) version %s\n", Version_string);
      exit(0);
      break;
    case CHAR_MAX + 1: // --help
      usage(stdout);
      exit(0);
      break;
    case '?':
      usage(stderr);
      exit(1);
      break;
    default:
      assert(0);
      break;
    }
  if (optind >= argc && foption == 0)
    fatal("no files and no -f option");
  if (!directory) {
    char *path = get_cwd();
    store_filename(path);
    a_delete path;
  }
  else
    store_filename(directory);
  init_hash_table();
  store_filename(common_words_file);
  store_filename(ignore_fields);
  key_buffer = new char[truncate_len];
  read_common_words_file();
  if (!base_name)
    base_name = optind < argc ? argv[optind] : DEFAULT_INDEX_NAME;
  const char *p = strrchr(base_name, DIR_SEPS[0]), *p1;
  const char *sep = &DIR_SEPS[1];
  while (*sep) {
    p1 = strrchr(base_name, *sep);
    if (p1 && (!p || p1 > p))
      p = p1;
    sep++;
  }
  size_t name_max;
  if (p) {
    char *dir = strsave(base_name);
    dir[p - base_name] = '\0';
    name_max = file_name_max(dir);
    a_delete dir;
  }
  else
    name_max = file_name_max(".");
  const char *filename = p ? p + 1 : base_name;
  if (strlen(filename) + sizeof(INDEX_SUFFIX) - 1 > name_max)
    fatal("`%1.%2' is too long for a filename", filename, INDEX_SUFFIX);
  if (p) {
    p++;
    temp_index_file = new char[p - base_name + sizeof(TEMP_INDEX_TEMPLATE)];
    memcpy(temp_index_file, base_name, p - base_name);
    strcpy(temp_index_file + (p - base_name), TEMP_INDEX_TEMPLATE);
  }
  else {
    temp_index_file = strsave(TEMP_INDEX_TEMPLATE);
  }
  catch_fatal_signals();
  int fd = mkstemp(temp_index_file);
  if (fd < 0)
    fatal("can't create temporary index file: %1", strerror(errno));
  indxfp = fdopen(fd, FOPEN_WB);
  if (indxfp == 0)
    fatal("fdopen failed");
  if (fseek(indxfp, sizeof(index_header), 0) < 0)
    fatal("can't seek past index header: %1", strerror(errno));
  int failed = 0;
  if (foption) {
    FILE *fp = stdin;
    if (strcmp(foption, "-") != 0) {
      errno = 0;
      fp = fopen(foption, "r");
      if (!fp)
	fatal("can't open `%1': %2", foption, strerror(errno));
    }
    string path;
    int lineno = 1;
    for (;;) {
      int c;
      for (c = getc(fp); c != '\n' && c != EOF; c = getc(fp)) {
	if (c == '\0')
	  error_with_file_and_line(foption, lineno,
				   "nul character in pathname ignored");
	else
	  path += c;
      }
      if (path.length() > 0) {
	path += '\0';
	if (!(*parser)(path.contents()))
	  failed = 1;
	path.clear();
      }
      if (c == EOF)
	break;
      lineno++;
    }
    if (fp != stdin)
      fclose(fp);
  }
  for (int i = optind; i < argc; i++)
    if (!(*parser)(argv[i]))
      failed = 1;
  write_hash_table();
  if (fclose(indxfp) < 0)
    fatal("error closing temporary index file: %1", strerror(errno));
  char *index_file = new char[strlen(base_name) + sizeof(INDEX_SUFFIX)];    
  strcpy(index_file, base_name);
  strcat(index_file, INDEX_SUFFIX);
#ifdef HAVE_RENAME
#ifdef __EMX__
  if (access(index_file, R_OK) == 0)
    unlink(index_file);
#endif /* __EMX__ */
  if (rename(temp_index_file, index_file) < 0) {
#ifdef __MSDOS__
    // RENAME could fail on plain MSDOS filesystems because
    // INDEX_FILE is an invalid filename, e.g. it has multiple dots.
    char *fname = p ? index_file + (p - base_name) : 0;
    char *dot = 0;

    // Replace the dot with an underscore and try again.
    if (fname
        && (dot = strchr(fname, '.')) != 0
        && strcmp(dot, INDEX_SUFFIX) != 0)
      *dot = '_';
    if (rename(temp_index_file, index_file) < 0)
#endif
    fatal("can't rename temporary index file: %1", strerror(errno));
  }
#else /* not HAVE_RENAME */
  ignore_fatal_signals();
  if (unlink(index_file) < 0) {
    if (errno != ENOENT)
      fatal("can't unlink `%1': %2", index_file, strerror(errno));
  }
  if (link(temp_index_file, index_file) < 0)
    fatal("can't link temporary index file: %1", strerror(errno));
  if (unlink(temp_index_file) < 0)
    fatal("can't unlink temporary index file: %1", strerror(errno));
#endif /* not HAVE_RENAME */
  temp_index_file = 0;
  return failed;
}
Beispiel #23
0
static int mod_init(void)
{
	DBG( "TM - (size of cell=%ld, sip_msg=%ld) initializing...\n", 
			(long)sizeof(struct cell), (long)sizeof(struct sip_msg));
	/* checking if we have sufficient bitmap capacity for given
	   maximum number of  branches */
	if (MAX_BRANCHES+1>31) {
		LOG(L_CRIT, "Too many max UACs for UAC branch_bm_t bitmap: %d\n",
			MAX_BRANCHES );
		return -1;
	}

	if (init_callid() < 0) {
		LOG(L_CRIT, "Error while initializing Call-ID generator\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_uac, "t_uac_dlg", 0) < 0) {
		LOG(L_CRIT, "cannot register fifo t_uac\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_uac_cancel, "t_uac_cancel", 0) < 0) {
		LOG(L_CRIT, "cannot register fifo t_uac_cancel\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_hash, "t_hash", 0)<0) {
		LOG(L_CRIT, "cannot register hash\n");
		return -1;
	}

	if (register_fifo_cmd(fifo_t_reply, "t_reply", 0)<0) {
		LOG(L_CRIT, "cannot register t_reply\n");
		return -1;
	}

	if (unixsock_register_cmd("t_uac_dlg", unixsock_uac) < 0) {
		LOG(L_CRIT, "cannot register t_uac with the unix server\n");
		return -1;
	}

	if (unixsock_register_cmd("t_uac_cancel", unixsock_uac_cancel) < 0) {
		LOG(L_CRIT, "cannot register t_uac_cancel with the unix server\n");
		return -1;
	}

	if (unixsock_register_cmd("t_hash", unixsock_hash) < 0) {
		LOG(L_CRIT, "cannot register t_hash with the unix server\n");
		return -1;
	}

	if (unixsock_register_cmd("t_reply", unixsock_t_reply) < 0) {
		LOG(L_CRIT, "cannot register t_reply with the unix server\n");
		return -1;
	}

	/* building the hash table*/
	if (!init_hash_table()) {
		LOG(L_ERR, "ERROR: mod_init: initializing hash_table failed\n");
		return -1;
	}

	/* init static hidden values */
	init_t();

	if (!tm_init_timers()) {
		LOG(L_ERR, "ERROR: mod_init: timer init failed\n");
		return -1;
	}
	/* register the timer function */
	register_timer( timer_routine , 0 /* empty attr */, 1 );

	/* init_tm_stats calls process_count, which should
	 * NOT be called from mod_init, because one does not
	 * now, if a timer is used and thus how many processes
	 * will be started; however we started already our
	 * timers, so we know and process_count should not
	 * change any more
	 */
	if (init_tm_stats()<0) {
		LOG(L_CRIT, "ERROR: mod_init: failed to init stats\n");
		return -1;
	}

	if (uac_init()==-1) {
		LOG(L_ERR, "ERROR: mod_init: uac_init failed\n");
		return -1;
	}

	if (init_tmcb_lists()!=1) {
		LOG(L_CRIT, "ERROR:tm:mod_init: failed to init tmcb lists\n");
		return -1;
	}

	tm_init_tags();
	init_twrite_lines();
	if (init_twrite_sock() < 0) {
		LOG(L_ERR, "ERROR:tm:mod_init: Unable to create socket\n");
		return -1;
	}

	/* register post-script clean-up function */
	if (register_script_cb( w_t_unref, POST_SCRIPT_CB|REQ_TYPE_CB, 0)<0 ) {
		LOG(L_ERR,"ERROR:tm:mod_init: failed to register POST request "
			"callback\n");
		return -1;
	}
	if (register_script_cb( script_init, PRE_SCRIPT_CB|REQ_TYPE_CB , 0)<0 ) {
		LOG(L_ERR,"ERROR:tm:mod_init: failed to register PRE request "
			"callback\n");
		return -1;
	}

	if ( init_avp_params( fr_timer_param, fr_inv_timer_param)<0 ){
		LOG(L_ERR,"ERROR:tm:mod_init: failed to process timer AVPs\n");
		return -1;
	}

	if ( init_gf_mask( bf_mask_param )<0 ) {
		LOG(L_ERR,"ERROR:tm:mod_init: failed to process "
			"\"branch_flag_mask\" param\n");
		return -1;
	}
	return 0;
}
Beispiel #24
0
static int __init test_init(void){
   
    unsigned mask = 0x7FFFFFFF;
    
    printk(KERN_INFO "test_init() starts\n");

    struct hash_table* table = malloc(sizeof(struct hash_table));

    if (init_hash_table(table, 20) < 0){
        printk(KERN_ERR "Error!\n");
    }


    unsigned i;

    unsigned keys[30];

    // add 30 random key value pairs
    printk(KERN_INFO "Adding 30 random key value pairs...\n");
    for (i = 0; i < 30; i++){
        unsigned key = 0;

        get_random_bytes(&key, sizeof(unsigned));
        key = key & mask;

        keys[i] = key;
        int value = -key;
        put(table, key, value);
    }

    // print them out
    printk(KERN_INFO "Printing those 30 newly added key value pairs...\n");
    for (i = 0; i < 30; i++){
        int* map = get(table, keys[i]);
        if (!map){
            printk(KERN_INFO "key %u does not exist\n", keys[i]);
            continue;
        }
        printk(KERN_INFO "%u : %d\n", keys[i], *map);
    }

    // print 10 random keys
    printk(KERN_INFO "Printing 10 random key value pairs...\n");
    for (i = 0; i < 10; i++){
        unsigned key = 0;
        
        get_random_bytes(&key, sizeof(unsigned));
        key = key & mask;

        int* map = get(table, key);
        if (!map){
            printk(KERN_INFO "key %u does not exist\n", key);
            continue;
        }
        printk(KERN_INFO "%u : %d\n", key, *map);
    }

    // remove the first 10 key
    printk(KERN_INFO "Removing the first 10 keys...\n");
    for (i = 0; i < 10; i++){
        if (erase(table, keys[i]) < 0){
            printk(KERN_ERR "erase(): key %u does not exist\n", keys[i]);
        }
    }

    // print all out
    printk(KERN_INFO "Printing all key value pairs...\n");
    for (i = 0; i < 30; i++){
        int* map = get(table, keys[i]);
        if (!map){
            printk(KERN_INFO "key %u does not exist\n", keys[i]);
            continue;
        }
        printk(KERN_INFO "%u : %d\n", keys[i], *map);
    }

    // remove 10 random keys
    printk(KERN_INFO "Removing 10 random key value pairs...\n");
    for (i = 0; i < 10; i++){
        unsigned key = 0;
        
        get_random_bytes(&key, sizeof(unsigned));
        key = key & mask;

        if (erase(table, key) < 0){
            printk(KERN_ERR "erase(): key %u does not exist\n", key);
        }
    }

     // print all out
    printk(KERN_INFO "Printing all key value pairs...\n");
    for (i = 0; i < 30; i++){
        int* map = get(table, keys[i]);
        if (!map){
            printk(KERN_INFO "key %u does not exist\n", keys[i]);
            continue;
        }
        printk(KERN_INFO "%u : %d\n", keys[i], *map);
    }


    free_hash_table(table);
    free(table);

    printk(KERN_INFO "test_init() ends\n");
    return 0;
}
Beispiel #25
0
int find_path( int in_room_vnum, int out_room_vnum, CHAR_DATA *ch, 
	       int depth, int in_zone )
{
  struct room_q		*tmp_q, *q_head, *q_tail;
  struct hash_header	x_room;
  int			i, tmp_room, count=0, thru_doors;
  ROOM_INDEX_DATA	*herep;
  ROOM_INDEX_DATA	*startp;
  EXIT_DATA		*exitp;

  if ( depth <0 )
    {
      thru_doors = TRUE;
      depth = -depth;
    }
  else
    {
      thru_doors = FALSE;
    }

  startp = get_room_index( in_room_vnum );

  init_hash_table( &x_room, sizeof(int), 2048 );
  hash_enter( &x_room, in_room_vnum, (void *) - 1 );

  /* initialize queue */
  q_head = (struct room_q *) malloc(sizeof(struct room_q));
  q_tail = q_head;
  q_tail->room_nr = in_room_vnum;
  q_tail->next_q = 0;

  while(q_head)
    {
      herep = get_room_index( q_head->room_nr );
      /* for each room test all directions */
      if( herep->area == startp->area || !in_zone )
	{
	  /* only look in this zone...
	     saves cpu time and  makes world safer for players  */
	  for( i = 0; i <= 5; i++ )
	    {
	      exitp = herep->exit[i];
	      if( exit_ok(exitp) && ( thru_doors ? GO_OK_SMARTER : GO_OK ) )
		{
		  /* next room */
		  tmp_room = herep->exit[i]->to_room->vnum;
		  if( tmp_room != out_room_vnum )
		    {
		      /* shall we add room to queue ?
			 count determines total breadth and depth */
		      if( !hash_find( &x_room, tmp_room )
			 && ( count < depth ) )
			/* && !IS_SET( RM_FLAGS(tmp_room), DEATH ) ) */
			{
			  count++;
			  /* mark room as visted and put on queue */
			  
			  tmp_q = (struct room_q *)
			    malloc(sizeof(struct room_q));
			  tmp_q->room_nr = tmp_room;
			  tmp_q->next_q = 0;
			  q_tail->next_q = tmp_q;
			  q_tail = tmp_q;
	      
			  /* ancestor for first layer is the direction */
			  hash_enter( &x_room, tmp_room,
				     ((int)hash_find(&x_room,q_head->room_nr)
				      == -1) ? (void*)(i+1)
				     : hash_find(&x_room,q_head->room_nr));
			}
		    }
		  else
		    {
		      /* have reached our goal so free queue */
		      tmp_room = q_head->room_nr;
		      for(;q_head;q_head = tmp_q)
			{
			  tmp_q = q_head->next_q;
			  free(q_head);
			}
		      /* return direction if first layer */
		      if ((int)hash_find(&x_room,tmp_room)==-1)
			{
			  if (x_room.buckets)
			    {
			      /* junk left over from a previous track */
			      destroy_hash_table(&x_room, donothing);
			    }
			  return(i);
			}
		      else
			{
			  /* else return the ancestor */
			  int i;
			  
			  i = (int)hash_find(&x_room,tmp_room);
			  if (x_room.buckets)
			    {
			      /* junk left over from a previous track */
			      destroy_hash_table(&x_room, donothing);
			    }
			  return( -1+i);
			}
		    }
		}
	    }
	}
      
      /* free queue head and point to next entry */
      tmp_q = q_head->next_q;
      free(q_head);
      q_head = tmp_q;
    }

  /* couldn't find path */
  if( x_room.buckets )
    {
      /* junk left over from a previous track */
      destroy_hash_table( &x_room, donothing );
    }
  return -1;
}
Beispiel #26
0
int spai
(matrix *A, matrix **spai_mat,
 FILE *messages_arg,   /* file for warning messages */
 double epsilon_arg,   /* tolerance */
 int nbsteps_arg,      /* max number of "improvement" steps per line */
 int max_arg,          /* max dimensions of I, q, etc. */
 int maxnew_arg,       /* max number of new entries per step */
 int cache_size_arg,   /* one of (1,2,3,4,5,6) indicting size of cache */
                       /* cache_size == 0 indicates no caching */
 int verbose_arg,
 int spar_arg,
 int lower_diag_arg,
 int upper_diag_arg,
 double tau_arg)
{
  matrix *M;
  int col,ierr;

  int cache_sizes[6];

  /* Only create resplot for the numprocs=1 case. */
  if (debug && (A->numprocs == 1)) {
    resplot_fptr = fopen("resplot","w");
    fprintf(resplot_fptr,
	    "ep=%5.5lf ns=%d mn=%d bs=%d\n",
	    epsilon_arg,nbsteps_arg,maxnew_arg,A->bs);
    fprintf(resplot_fptr,"\n");
    fprintf(resplot_fptr,"scol: scalar column number\n");
    fprintf(resplot_fptr,"srn:  scalar resnorm\n");
    fprintf(resplot_fptr,"bcol: block column number\n");
    fprintf(resplot_fptr,"brn:  block resnorm\n");
    fprintf(resplot_fptr,"* indicates epsilon not attained\n");
    fprintf(resplot_fptr,"\n");
    fprintf(resplot_fptr,"   scol   srn       bcol   brn\n");
  }


  start_col = 0;
  num_bad_cols = 0;

  cache_sizes[0] = 101;
  cache_sizes[1] = 503;
  cache_sizes[2] = 2503;
  cache_sizes[3] = 12503;
  cache_sizes[4] = 62501;
  cache_sizes[5] = 104743;



  if (verbose_arg && !A->myid) {
    if (spar_arg == 0)
       printf("\n\nComputing SPAI: epsilon = %f\n",epsilon_arg);
    else if (spar_arg == 1)
       printf("\n\nComputing SPAI: tau = %f\n",tau_arg);
    else if (spar_arg == 2)
       printf("\n\nComputing SPAI: # diagonals = %d\n",
       lower_diag_arg+upper_diag_arg+1);
    fflush(stdout);
  }

  epsilon = epsilon_arg;
  message = messages_arg;
  maxnew = maxnew_arg;
  max_dim = max_arg;

  /* Determine maximum number of scalar nonzeros
     for any column of M */
  if (spar_arg == 0)
    {
     nbsteps = nbsteps_arg;
     maxapi = A->max_block_size * (1 + maxnew*nbsteps);
    }
  else if(spar_arg == 1)
    {
     nbsteps = A->maxnz;
     maxapi = A->max_block_size * (1 + nbsteps);
    }
  else
    {
     nbsteps = lower_diag_arg+upper_diag_arg+1;
     maxapi = A->max_block_size * (1 + nbsteps);
    }
  allocate_globals(A);

#ifdef MPI
  MPI_Barrier(A->comm);
#endif

  if ((cache_size_arg < 0) || (cache_size_arg > 6)) {
    fprintf(stderr,"illegal cache size in spai\n");
    exit(1);
  }

  if (cache_size_arg > 0)
    ht = init_hash_table(cache_sizes[cache_size_arg-1]);

  M = clone_matrix(A);

  ndone = 0;
  Im_done = 0;
  all_done = 0;
  next_line = 0;

  /* Timing of SPAI starts here.
     In a "real production" code everything before this could be static.
  */
  if (verbose_arg) start_timer(ident_spai);

  if ((ierr = precompute_column_square_inverses(A)) != 0)  return ierr;

#ifdef MPI
  MPI_Barrier(A->comm);
#endif

  for (;;) {

    col = grab_Mline(A, M, A->comm);

    if (debug && col >= 0) {
      fprintf(fptr_dbg,"col=%d of %d\n",col,A->n);
      fflush(fptr_dbg);
    }

    if (col < 0 ) break;
    if ((ierr =
         spai_line(A,col,spar_arg,lower_diag_arg,upper_diag_arg,tau_arg,M)) != 0)  return ierr;

  }

#ifdef MPI

  say_Im_done(A,M);

  do {
    com_server(A,M);
  }
  while (! all_done);
  MPI_Barrier(A->comm);

#endif

#ifdef MPI
  MPI_Barrier(A->comm);
#endif

  if (verbose_arg) {
    stop_timer(ident_spai);
    report_times(ident_spai,"spai",0,A->comm);
  }

  free_globals(nbsteps);
  free_hash_table(ht);

  if (resplot_fptr) fclose(resplot_fptr);

  *spai_mat = M;
  return 0;

}
Beispiel #27
0
int
main(int argc, char **argv)
{
    int i, len, timeout, controlfd, alarm_tick;
    double sptime, eptime, last_tick_time;
    unsigned long delay;
    struct cfg cf;
    char buf[256];

    memset(&cf, 0, sizeof(cf));

    init_config(&cf, argc, argv);

    seedrandom();

    init_hash_table(&cf.stable);
    init_port_table(&cf);

    controlfd = init_controlfd(&cf);

    if (cf.stable.nodaemon == 0) {
	if (rtpp_daemon(0, 0) == -1)
	    err(1, "can't switch into daemon mode");
	    /* NOTREACHED */
    }

    glog = cf.stable.glog = rtpp_log_open(&cf.stable, "rtpproxy", NULL, LF_REOPEN);
    atexit(ehandler);
    rtpp_log_write(RTPP_LOG_INFO, cf.stable.glog, "rtpproxy started, pid %d", getpid());

    if (cf.timeout_socket != NULL) {
	cf.timeout_handler = rtpp_notify_init(glog, cf.timeout_socket);
	if (cf.timeout_handler == NULL) {
	    rtpp_log_ewrite(RTPP_LOG_ERR, glog, "can't start notification thread");
	    exit(1);
	}
    }

    i = open(pid_file, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
    if (i >= 0) {
	len = sprintf(buf, "%u\n", (unsigned int)getpid());
	write(i, buf, len);
	close(i);
    } else {
	rtpp_log_ewrite(RTPP_LOG_ERR, cf.stable.glog, "can't open pidfile for writing");
    }

    signal(SIGHUP, fatsignal);
    signal(SIGINT, fatsignal);
    signal(SIGKILL, fatsignal);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTERM, fatsignal);
    signal(SIGXCPU, fatsignal);
    signal(SIGXFSZ, fatsignal);
    signal(SIGVTALRM, fatsignal);
    signal(SIGPROF, fatsignal);
    signal(SIGUSR1, fatsignal);
    signal(SIGUSR2, fatsignal);

    if (cf.stable.run_uname != NULL || cf.stable.run_gname != NULL) {
	if (drop_privileges(&cf) != 0) {
	    rtpp_log_ewrite(RTPP_LOG_ERR, cf.stable.glog,
	      "can't switch to requested user/group");
	    exit(1);
	}
    }

    cf.stable.controlfd = controlfd;

    cf.sessinfo.sessions[0] = NULL;
    cf.sessinfo.nsessions = 0;
    cf.rtp_nsessions = 0;

    rtpp_command_async_init(&cf);

    sptime = 0;
    last_tick_time = 0;
    for (;;) {
        pthread_mutex_lock(&cf.glock);
        pthread_mutex_lock(&cf.sessinfo.lock);
	if (cf.rtp_nsessions > 0 || cf.sessinfo.nsessions > 0) {
	    timeout = RTPS_TICKS_MIN;
	} else {
	    timeout = TIMETICK * 1000;
        }
        pthread_mutex_unlock(&cf.sessinfo.lock);
        pthread_mutex_unlock(&cf.glock);
	eptime = getdtime();
	delay = (eptime - sptime) * 1000000.0;
	if (delay < (1000000 / POLL_LIMIT)) {
	    usleep((1000000 / POLL_LIMIT) - delay);
	    sptime = getdtime();
	} else {
	    sptime = eptime;
	}
        pthread_mutex_lock(&cf.sessinfo.lock);
        if (cf.sessinfo.nsessions > 0) {
	    i = poll(cf.sessinfo.pfds, cf.sessinfo.nsessions, timeout);
            pthread_mutex_unlock(&cf.sessinfo.lock);
	    if (i < 0 && errno == EINTR)
	        continue;
        } else {
            pthread_mutex_unlock(&cf.sessinfo.lock);
            usleep(timeout * 1000);
        }
	eptime = getdtime();
        pthread_mutex_lock(&cf.glock);
	if (cf.rtp_nsessions > 0) {
	    process_rtp_servers(&cf, eptime);
	}
        pthread_mutex_unlock(&cf.glock);
	if (eptime > last_tick_time + TIMETICK) {
	    alarm_tick = 1;
	    last_tick_time = eptime;
	} else {
	    alarm_tick = 0;
	}
        pthread_mutex_lock(&cf.glock);
	process_rtp(&cf, eptime, alarm_tick);
        pthread_mutex_unlock(&cf.glock);
    }

    exit(0);
}
Beispiel #28
0
static int mod_init(void)
{
	DBG( "TM - (sizeof cell=%ld, sip_msg=%ld) initializing...\n",
			(long)sizeof(struct cell), (long)sizeof(struct sip_msg));
	/* checking if we have sufficient bitmap capacity for given
	   maximum number of  branches */
	if (MAX_BRANCHES+1>31) {
		LOG(L_CRIT, "Too many max UACs for UAC branch_bm_t bitmap: %d\n",
			MAX_BRANCHES );
		return -1;
	}

	if (init_callid() < 0) {
		LOG(L_CRIT, "Error while initializing Call-ID generator\n");
		return -1;
	}

	/* building the hash table*/
	if (!init_hash_table()) {
		LOG(L_ERR, "ERROR: mod_init: initializing hash_table failed\n");
		return -1;
	}

	/* init static hidden values */
	init_t();

	if (tm_init_selects()==-1) {
		LOG(L_ERR, "ERROR: mod_init: select init failed\n");
		return -1;
	}
	
	if (tm_init_timers()==-1) {
		LOG(L_ERR, "ERROR: mod_init: timer init failed\n");
		return -1;
	}

	     /* First tm_stat initialization function only allocates the top level stat
	      * structure in shared memory, the initialization will complete in child
	      * init with init_tm_stats_child when the final value of estimated_process_count is
	      * known
	      */
	if (init_tm_stats() < 0) {
		LOG(L_CRIT, "ERROR: mod_init: failed to init stats\n");
		return -1;
	}

	if (uac_init()==-1) {
		LOG(L_ERR, "ERROR: mod_init: uac_init failed\n");
		return -1;
	}

	if (init_tmcb_lists()!=1) {
		LOG(L_CRIT, "ERROR:tm:mod_init: failed to init tmcb lists\n");
		return -1;
	}
	
	tm_init_tags();
	init_twrite_lines();
	if (init_twrite_sock() < 0) {
		LOG(L_ERR, "ERROR:tm:mod_init: Unable to create socket\n");
		return -1;
	}

	/* register post-script clean-up function */
	if (register_script_cb( w_t_unref, POST_SCRIPT_CB|REQ_TYPE_CB, 0)<0 ) {
		LOG(L_ERR,"ERROR:tm:mod_init: failed to register POST request "
			"callback\n");
		return -1;
	}
	if (register_script_cb( script_init, PRE_SCRIPT_CB|REQ_TYPE_CB , 0)<0 ) {
		LOG(L_ERR,"ERROR:tm:mod_init: failed to register PRE request "
			"callback\n");
		return -1;
	}

	if (init_avp_params( fr_timer_param, fr_inv_timer_param)<0 ){
		LOG(L_ERR,"ERROR:tm:mod_init: failed to process timer AVPs\n");
		return -1;
	}

	tm_init = 1;
	return 0;
}
Beispiel #29
0
void show_info_from_system_file(char *file, meminfo_p meminfo, int meminfo_rows, int tok_offset) {
	// Setup and init table
	vtab_t table;
	int header_rows = 2 - compatibility_mode;
	int header_cols = 1;
	// Add an extra data column for a total column
	init_table(&table, header_rows, header_cols, meminfo_rows, num_nodes + 1);
	int total_col_ix = header_cols + num_nodes;
	// Insert token mapping in hash table and assign left header column label for each row in table
	init_hash_table();
	for (int row = 0; (row < meminfo_rows); row++) {
		hash_insert(meminfo[row].token, meminfo[row].index);
		if (compatibility_mode) {
			string_assign(&table, (header_rows + row), 0, meminfo[row].token);
		} else {
			string_assign(&table, (header_rows + row), 0, meminfo[row].label);
		}
	}
	// printf("There are %d table hash collisions.\n", hash_collisions);
	// Set left header column width and left justify it
	set_col_width(&table, 0, 16);
	set_col_justification(&table, 0, COL_JUSTIFY_LEFT);
	// Open /sys/devices/system/node/node?/<file> for each node and store data
	// in table.  If not compatibility_mode, do approximately first third of
	// this loop also for (node_ix == num_nodes) to get "Total" column header.
	for (int node_ix = 0; (node_ix < (num_nodes + (1 - compatibility_mode))); node_ix++) {
		int col = header_cols + node_ix;
		// Assign header row label and horizontal line for this column...
		string_assign(&table, 0, col, node_header[node_ix]);
		if (!compatibility_mode) {
			repchar_assign(&table, 1, col, '-');
			int decimal_places = 2;
			if (compress_display) {
				decimal_places = 0;
			}
			set_col_decimal_places(&table, col, decimal_places);
		}
		// Set column width and right justify data
		set_col_width(&table, col, 16);
		set_col_justification(&table, col, COL_JUSTIFY_RIGHT);
		if (node_ix == num_nodes) {
			break;
		}
		// Open /sys/.../node<N>/numstast file for this node...
		char buf[SMALL_BUF_SIZE];
		char fname[64];
		snprintf(fname, sizeof(fname), "/sys/devices/system/node/node%d/%s", node_ix_map[node_ix], file);
		FILE *fs = fopen(fname, "r");
		if (!fs) {
			sprintf(buf, "cannot open %s", fname);
			perror(buf);
			exit(EXIT_FAILURE);
		}
		// Get table values for this node...
		while (fgets(buf, SMALL_BUF_SIZE, fs)) {
			char *tok[64];
			int tokens = 0;
			const char *delimiters = " \t\r\n:";
			char *p = strtok(buf, delimiters);
			if (p == NULL) {
				continue;	// Skip blank lines;
			}
			while (p) {
				tok[tokens++] = p;
				p = strtok(NULL, delimiters);
			}
			// example line from numastat file: "numa_miss 16463"
			// example line from meminfo  file: "Node 3 Inactive:  210680 kB"
			int index = hash_lookup(tok[0 + tok_offset]);
			if (index < 0) {
				printf("Token %s not in hash table.\n", tok[0]);
			} else {
				double value = (double)atol(tok[1 + tok_offset]);
				if (!compatibility_mode) {
					double multiplier = 1.0;
					if (tokens < 4) {
						multiplier = page_size_in_bytes;
					} else if (!strncmp("HugePages", tok[2], 9)) {
						multiplier = huge_page_size_in_bytes;
					} else if (!strncmp("kB", tok[4], 2)) {
						multiplier = KILOBYTE;
					}
					value *= multiplier;
					value /= (double)MEGABYTE;
				}
				double_assign(&table, header_rows + index, col, value);
				double_addto(&table, header_rows + index, total_col_ix, value);
			}
		}
		fclose(fs);
	}
	// Crompress display column widths, if requested
	if (compress_display) {
		for (int col = 0; (col < header_cols + num_nodes + 1); col++) {
			auto_set_col_width(&table, col, 4, 16);
		}
	}
	// Optionally sort the table data
	if (sort_table) {
		int sort_col;
		if ((sort_table_node < 0) || (sort_table_node >= num_nodes)) {
			sort_col = total_col_ix;
		} else {
			sort_col = header_cols + node_ix_map[sort_table_node];
		}
		sort_rows_descending_by_col(&table, header_rows, header_rows + meminfo_rows - 1, sort_col);
	}
	// Actually display the table now, doing line-folding as necessary
	display_table(&table, screen_width, 0, 0, show_zero_data, show_zero_data);
	free_table(&table);
}
Beispiel #30
0
static int mod_init(void)
{
	unsigned int timer_sets,set;
	unsigned int roundto_init;

	LM_INFO("TM - initializing...\n");

	/* checking if we have sufficient bitmap capacity for given
	   maximum number of  branches */
	if (MAX_BRANCHES+1>31) {
		LM_CRIT("Too many max UACs for UAC branch_bm_t bitmap: %d\n",
			MAX_BRANCHES );
		return -1;
	}

	fix_flag_name(minor_branch_flag_str, minor_branch_flag);

	minor_branch_flag =
		get_flag_id_by_name(FLAG_TYPE_BRANCH, minor_branch_flag_str);

	if (minor_branch_flag!=-1) {
		if (minor_branch_flag > (8*sizeof(int)-1)) {
			LM_CRIT("invalid minor branch flag\n");
			return -1;
		}
		minor_branch_flag = 1<<minor_branch_flag;
	} else {
		minor_branch_flag = 0;
	}

	/* if statistics are disabled, prevent their registration to core */
	if (tm_enable_stats==0)
#ifdef STATIC_TM
		tm_exports.stats = 0;
#else
		exports.stats = 0;
#endif

	if (init_callid() < 0) {
		LM_CRIT("Error while initializing Call-ID generator\n");
		return -1;
	}

	/* how many timer sets do we need to create? */
	timer_sets = (timer_partitions<=1)?1:timer_partitions ;

	/* try first allocating all the structures needed for syncing */
	if (lock_initialize( timer_sets )==-1)
		return -1;

	/* building the hash table*/
	if (!init_hash_table( timer_sets )) {
		LM_ERR("initializing hash_table failed\n");
		return -1;
	}

	/* init static hidden values */
	init_t();

	if (!tm_init_timers( timer_sets ) ) {
		LM_ERR("timer init failed\n");
		return -1;
	}

	/* the ROUNDTO macro taken from the locking interface */
#ifdef ROUNDTO
	roundto_init = ROUNDTO;
#else
	roundto_init = sizeof(void *);
#endif
	while (roundto_init != 1) {
		tm_timer_shift++;
		roundto_init >>= 1;
	}

	LM_DBG("timer set shift is %d\n", tm_timer_shift);


	/* register the timer functions */
	for ( set=0 ; set<timer_sets ; set++ ) {
		if (register_timer( "tm-timer", timer_routine,
		(void*)(long)set, 1, TIMER_FLAG_DELAY_ON_DELAY) < 0 ) {
			LM_ERR("failed to register timer for set %d\n",set);
			return -1;
		}
		if (register_utimer( "tm-utimer", utimer_routine,
		(void*)(long)set, 100*1000, TIMER_FLAG_DELAY_ON_DELAY)<0) {
			LM_ERR("failed to register utimer for set %d\n",set);
			return -1;
		}
	}

	if (uac_init()==-1) {
		LM_ERR("uac_init failed\n");
		return -1;
	}

	if (init_tmcb_lists()!=1) {
		LM_CRIT("failed to init tmcb lists\n");
		return -1;
	}

	tm_init_tags();
	init_twrite_lines();
	if (init_twrite_sock() < 0) {
		LM_ERR("failed to create socket\n");
		return -1;
	}

	/* register post-script clean-up function */
	if (register_script_cb( do_t_cleanup, POST_SCRIPT_CB|REQ_TYPE_CB, 0)<0 ) {
		LM_ERR("failed to register POST request callback\n");
		return -1;
	}
	if (register_script_cb( script_init, PRE_SCRIPT_CB|REQ_TYPE_CB , 0)<0 ) {
		LM_ERR("failed to register PRE request callback\n");
		return -1;
	}

	if(register_pv_context("request", tm_pv_context_request)< 0) {
		LM_ERR("Failed to register pv contexts\n");
		return -1;
	}

	if(register_pv_context("reply", tm_pv_context_reply)< 0) {
		LM_ERR("Failed to register pv contexts\n");
		return -1;
	}

	if ( parse_avp_spec( &uac_ctx_avp, &uac_ctx_avp_id)<0 ) {
		LM_ERR("failed to register AVP name <%s>\n",uac_ctx_avp.s);
		return -1;
	}

	if ( register_async_script_handlers( t_handle_async, t_resume_async )<0 ) {
		LM_ERR("failed to register async handler to core \n");
		return -1;
	}

	return 0;
}