#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
/* 包含内核链表头问题件 */
#include <linux/list.h>
/* 使用kmalloc kfree */
#include <linux/slab.h>
/* 定义一个链表头 */
LIST_HEAD(uhead);
/* 定义使用链表的数据结构 */
struct mydata {
int32_t data;
struct list_head l;
};
static int __init _module_init(void)
{
int32_t i = 0;
struct mydata *p = NULL;
/* 生成数据到链表 */
for(i = 0; i < 10; i++) {
p = kzalloc(sizeof(*p), GFP_KERNEL);
if(!p) {
/* null */
} else {
printk("%d add to list\n", i);
list_add_tail(&p->l, &uhead);
}
}
return 0;
}
static void __exit _module_exit(void)
{
struct list_head *pos = NULL;
struct list_head *n = NULL;
struct mydata *p = NULL;
list_for_each_safe(pos, n, &uhead)
{
p = list_entry(pos, struct mydata, l);
list_del(&p->l);
printk("%d remove from list\n", p->data);
kfree(p);
}
}
module_init(_module_init);
module_exit(_module_exit);
MODULE_LICENSE("GPL");
Makefile
export ARCH=arm64
export CROSS_COMPILE=aarch64-linux-gnu-
KERNEL_DIR ?= $(realpath ../../linux/)
obj-m := kernel_list.o
modules:
$(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KERNEL_DIR) M=$(PWD) clean
install:
cp *.ko $(KERNEL_DIR)/kmodules
生成kernel_list.ko放到qemu共享目录,执行加载和卸载
# insmod kernel_list.ko
[ 164.811892] kernel_list: loading out-of-tree module taints kernel.
[ 164.856807] 0 add to list
[ 164.868501] 1 add to list
[ 164.869326] 2 add to list
[ 164.869434] 3 add to list
[ 164.869552] 4 add to list
[ 164.869648] 5 add to list
[ 164.869737] 6 add to list
[ 164.869821] 7 add to list
[ 164.876161] 8 add to list
[ 164.876667] 9 add to list
#
# rm[ 168.518968] random: fast init done
# rmmod kernel_list.ko
[ 173.339468] 0 remove from list
[ 173.343232] 0 remove from list
[ 173.345058] 0 remove from list
[ 173.345582] 0 remove from list
[ 173.346051] 0 remove from list
[ 173.362709] 0 remove from list
[ 173.363465] 0 remove from list
[ 173.363984] 0 remove from list
[ 173.364446] 0 remove from list
[ 173.364917] 0 remove from list
#