本文简单看看linux kernel 中的 hlist
长什么样
- API
// include/linux/types.h
struct hlist_head {
struct hlist_node *first;
};
struct hlist_node {
struct hlist_node *next, **pprev;
};
敲十几遍记住;
#define DEFINE_HASHTABLE(name, bits) \
struct hlist_head name[1 << (bits)] = \
{ [0 ... ((1 << (bits)) - 1)] = HLIST_HEAD_INIT }
#define HLIST_HEAD_INIT { .first = NULL }
解析上面两个macro
DEFINE_HASHTABLE(htable, 3);
// =>
struct hlist_head htable[8] = {[0 ... 7] = {.first=NULL} };
// 初始化一个hlist_head数组,大小为8,每个成员htable[i]初始化为:
htable[i] = {
.first = NULL;
};
看看初始化后的样子
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/hashtable.h>
#include <linux/vmalloc.h>
#define HBITS 3
DEFINE_HASHTABLE(test_htable, HBITS);
void hlist_t(void){
char *buff, *pos;
int i;
buff = vmalloc(4096);
if(!buff){
pr_err("[!] vmalloc failed!\n");
return;
}
pos = buff;
for(i = 0; i < 1<<HBITS; i++){
pos += sprintf(pos, "<%px> test_htable[%d].first: %px\n", &test_htable[i], i, test_htable[i].first);
}
pr_info("%s\n", buff);
vfree(buff);
}
static int __init hlist_t_init(void)
{
printk(KERN_INFO "Hello hlist_t\n");
hlist_t();
return 0;
}
static void __exit hlist_t_exit(void)
{
printk(KERN_INFO "Goodbye hlist_t\n");
}
module_init(hlist_t_init);
module_exit(hlist_t_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("X++0");
MODULE_DESCRIPTION("Kernel xxx Module.");
MODULE_VERSION("0.1");
obj-m += hlist-t.o
KDIR := /lib/modules/$(shell uname -r)/build
all:
make -C $(KDIR) M=$(PWD) modules
clean:
@rm -rf *.o *.mod.c *.mod.o *.order *.symvers .*.cmd *.mod .tmp_versions
clean_all:
@rm -rf *.o *.mod.c *.mod.o *.order *.symvers .*.cmd *.mod *.ko .tmp_versions
$ dmesg
...
[ 412.576930] <ffffffffa0002340> test_htable[0].first: 0000000000000000
[ 412.576930] <ffffffffa0002348> test_htable[1].first: 0000000000000000
[ 412.576930] <ffffffffa0002350> test_htable[2].first: 0000000000000000
[ 412.576930] <ffffffffa0002358> test_htable[3].first: 0000000000000000
[ 412.576930] <ffffffffa0002360> test_htable[4].first: 0000000000000000
[ 412.576930] <ffffffffa0002368> test_htable[5].first: 0000000000000000
[ 412.576930] <ffffffffa0002370> test_htable[6].first: 0000000000000000
[ 412.576930] <ffffffffa0002378> test_htable[7].first: 0000000000000000
...