#include "k-userhash.h" #include /*定义大小为HASH_SIZE的hashtable */ static struct list_head hash_array[HASH_SIZE]; /*init hashtable */ void init_hashMap(void) { int i; for(i = 0; i < HASH_SIZE; i++) INIT_LIST_HEAD(&hash_array[i]); } /*获取hashtable位置索引 */ int get_hash_index(uint32_t ip) { unsigned int val = ip % HASH_SIZE; return val; } /* search node */ USERINFO *search_user(uint32_t ip) { int index; struct list_head *pos; USERINFO *pNode; index = get_hash_index(ip); /*判断表中该单元是否为NLL */ /* list_empty - tests whether a list is empty*/ /* @head: the list to test.*/ if( list_empty(&hash_array[index])) { return NULL; } /*查找用户IP */ list_for_each(pos, &hash_array[index]) { /* list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type:the type of the struct this is embedded in. * @member: the name of the list_head within the struct. */ pNode = list_entry(pos, USERINFO, hnode); if(pNode != NULL) printk("user ip:%d user id:%d\n", pNode->user_ip, pNode->user_id); return pNode; } return NULL; } /*add user */ int add_user(uint32_t ip, int id) { int index; USERINFO *pNode = NULL; /*获取hashtable位置索引 */ index = get_hash_index(ip); pNode = search_user(ip); if( NULL == pNode) { /*分配存储空间——GFP_KERNEL内核内存的正常分配. 可能睡眠. */ pNode = (USERINFO *)kmalloc(sizeof(USERINFO), GFP_KERNEL); if (pNode == NULL) { return -1; } pNode->user_ip = ip; } printk("IP ALEADY EXISTED\n"); pNode->user_id = id; return 0; } /*delete a node */ void del_user(uint32_t ip) { int index; struct list_head *pos; USERINFO *pNode; index = get_hash_index(ip); /*判断hashtable中该单元是否为空 */ if( list_empty(&hash_array[index])) { printk("node is NULL\n"); return; } /*查找用户ip */ list_for_each(pos, &hash_array[index]) { pNode = list_entry(pos, USERINFO, hnode); if(pNode->user_ip == ip) list_del(&pNode->hnode); kfree(pNode); } return; } /*delete all node */ void free_all_user(void) { int i; struct list_head *pos, *n; USERINFO *pNode; /*判断hashtable单元是否为NULL */ for(i = 0; i < HASH_SIZE; i++) { if(list_empty(&hash_array[i])) continue; list_for_each_safe(pos, n, &hash_array[i]) { pNode = list_entry(pos, USERINFO, hnode); list_del(&pNode->hnode); kfree(pNode); } } } /*printf all nodes */ void printk_all_user(void) { int i; struct list_head *pos, *n; USERINFO * pNode; for(i = 0; i < HASH_SIZE; i++) continue; list_for_each_safe(pos, n, &hash_array[i]) { pNode = list_entry(pos, USERINFO, hnode); printk("user ip:%d user id:%d\n", pNode->user_ip, pNode->user_id); } }