如何使用kernel中的list结构来保存自定义数据
1.首先定义自己所需的结构体。
struct my_mapping_struct { struct list_head list; int file; void *virt; struct my_data *md; }
2.定义并初始化一个全局的list head与一把mutex。
static DEFINE_MUTEX(my_mutex); static LIST_HEAD(my_list_head);
3.向list head中添加新元素。
static int my_list_add(int file, void *virt, struct my_data *md) { struct my_mapping_struct *node; node = kmalloc(sizeof(struct my_mapping_struct), GFP_KERNEL); if (!node) return -NOMEM; node->file = file; node->virt = virt; node->md = md; mutex_lock(&my_mutex); list_add(&node->list, &my_list_head); mutex_unlock(&my_mutex); return 0; }
4.向list head中删除指定md元素。
static int my_list_del(struct my_data *md) { struct list_head *pos; struct my_mapping_struct *node; int is_found = 0; mutex_lock(&my_mutex); list_for_each(pos, &my_list_head) { node = container_of(pos, struct my_mapping_struct, list); if (node->md == md) { list_del(&node->list); kfree(node); is_found = 1; break; } } mutex_unlock(&my_mutex); return is_found?0:1; }
5.在list head中查找特定md的元素。
static struct my_data *my_find_node(void *virt) { struct list_head *pos; struct my_mapping_struct *node; struct my_data *md = NULL; mutex_lock(&my_mutex); list_for_each(pos, &my_list_head) { node = container_of(pos, struct my_mapping_struct, list); if (node->virt == virt) { md = node->md; break; } } mutex_unlock(&my_mutex); return md; }