|
| 1 | +#include <linux/init.h> |
| 2 | +#include <linux/module.h> |
| 3 | +#include <linux/slab.h> |
| 4 | +#include <linux/string.h> |
| 5 | + |
| 6 | +/* refercence with kernel module zd1201 */ |
| 7 | +/* https://zhuanlan.zhihu.com/p/82375193 */ |
| 8 | +struct AAAAA { |
| 9 | + /* hash table implement in list address */ |
| 10 | + struct hlist_head nodelist; |
| 11 | +}; |
| 12 | + |
| 13 | +struct AAAAA_node { |
| 14 | + struct hlist_node fnode; |
| 15 | + char name[20]; |
| 16 | +}; |
| 17 | + |
| 18 | +struct AAAAA *module5a; |
| 19 | +static int hlist_test_init(void) |
| 20 | +{ |
| 21 | + struct AAAAA_node *node1; |
| 22 | + struct AAAAA_node *node2; |
| 23 | + struct AAAAA_node *pos; |
| 24 | + |
| 25 | + /* another hlist_node to use as temporary storage */ |
| 26 | + struct hlist_node *tmp_node; |
| 27 | + |
| 28 | + module5a = kmalloc(sizeof(struct AAAAA), GFP_ATOMIC); |
| 29 | + if (!module5a) |
| 30 | + return -1; |
| 31 | + |
| 32 | + node1 = kmalloc(sizeof(*node1), GFP_ATOMIC); |
| 33 | + if (!node1) |
| 34 | + return -1; |
| 35 | + strcpy(node1->name, "Node1"); |
| 36 | + |
| 37 | + node2 = kmalloc(sizeof(*node2), GFP_ATOMIC); |
| 38 | + if (!node2) |
| 39 | + return -1; |
| 40 | + strcpy(node2->name, "Node2"); |
| 41 | + |
| 42 | + /* init hash table */ |
| 43 | + INIT_HLIST_HEAD(&module5a->nodelist); |
| 44 | + |
| 45 | + /* add node to hash table */ |
| 46 | + hlist_add_head(&node1->fnode, &module5a->nodelist); |
| 47 | + hlist_add_head(&node2->fnode, &module5a->nodelist); |
| 48 | + |
| 49 | + hlist_for_each_entry_safe(pos, tmp_node, &module5a->nodelist, fnode) { |
| 50 | + printk(KERN_ALERT"Iter node : %s\n", pos->name); |
| 51 | + } |
| 52 | + |
| 53 | + return 0; |
| 54 | +} |
| 55 | + |
| 56 | +static void hlist_test_exit(void) |
| 57 | +{ |
| 58 | + struct AAAAA_node *pos; |
| 59 | + struct hlist_node *tmp_node; |
| 60 | + |
| 61 | + hlist_for_each_entry_safe(pos, tmp_node, &module5a->nodelist, fnode) { |
| 62 | + printk(KERN_ALERT"Delete node : %s\n", pos->name); |
| 63 | + hlist_del_init(&pos->fnode); |
| 64 | + kfree(pos); |
| 65 | + } |
| 66 | + kfree(module5a); |
| 67 | +} |
| 68 | + |
| 69 | +MODULE_LICENSE("Dual BSD/GPL"); |
| 70 | +module_init(hlist_test_init); |
| 71 | +module_exit(hlist_test_exit); |
0 commit comments