secgateway/Product/modules/userhash/k-userhash.c

161 lines
3.3 KiB
C

#include "k-userhash.h"
#include <linux/slab.h>
#include <asm/errno.h>
#include <linux/kthread.h>
/*声明读写锁 */
DEFINE_RWLOCK(g_obj_lock);
/*定义大小为HASH_SIZE的hashtable */
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)
{
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);
/*查找用户IP */
read_lock(&g_obj_lock);
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:%ld user id:%d\n", pNode->user_ip, pNode->user_id);
return pNode;
}
read_unlock(&g_obj_lock);
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 ENOMEM;
}
pNode->user_ip = ip;
list_add_tail(&pNode->hnode,&hash_array[index]);
}
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, *n;
USERINFO *pNode;
index = get_hash_index(ip);
/*判断hashtable中该单元是否为空 */
if( list_empty(&hash_array[index]))
{
printk("node is NULL\n");
return;
}
/*查找用户ip */
write_lock(&g_obj_lock);
list_for_each_safe(pos, n, &hash_array[index])
{
pNode = list_entry(pos, USERINFO, hnode);
if(pNode->user_ip == ip)
list_del(&pNode->hnode);
kfree(pNode);
}
write_unlock(&g_obj_lock);
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;
write_lock(&g_obj_lock);
list_for_each_safe(pos, n, &hash_array[i])
{
pNode = list_entry(pos, USERINFO, hnode);
list_del(&pNode->hnode);
kfree(pNode);
}
write_unlock(&g_obj_lock);
}
}
/*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;
read_lock(&g_obj_lock);
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);
}
read_unlock(&g_obj_lock);
}