Linux中一个驱动往往需要管理多个设备,驱动程序中需要跟踪每个设备。链表在此就发挥了很强的作用,内核中实现的是循环双链表,这个结构可以满足FIFO和LIFO的需要。内核需要保持最少的代码,不宜实现冗余的数据结构。
下面我将该数据结构分为节点和对节点的操作API两大部分去讲解。
Node
一个链表节点包含数据域和指针域,内核帮我们设计好了指针域struct list_head
,这个结构体往往被包含在其他需要被链表管理的结构内。
举个例子:
我们需要管理许多个汽车设备,汽车结构体的定义如下:
struct car {
int door_number;
char *color;
char *model;
};
这里面目前只有数据域,想要用链表管理,需要嵌入指针域:
struct car {
int door_number;
char *color;
char *model;
struct list_head list; /*内核的表结构 */
};
这样,一个设备节点也就制作出来了。
有了数据结构还需要在其上的操作,也就是API。
API0 — Init
首先需要的是链表初始化操作,内核使用宏定义和函数分别设计出一个双链表的初始化操作。
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
如果使用LIST_HEAD宏定义去初始化:
LIST_HEAD(carlist)
//这个操作等于
struct list_head carlist = LIST_HEAD_INIT(carlist)
struct list_head carlist = {&carlist , &carlist};
这就定义了一个struct list_head类型的变量carlist,并且对其做了经典的初始化,next指针和prev指针都回指向自己。
有了初始化操作,在我们创建好节点实例后皆可以直接初始化嵌入在其中的list_head成员了
struct car *pinkcar = kzalloc(sizeof(struct car),GPF_KERNEL);
LIST_HEAD_INIT(pinkcar->list);
API1 — Add
内核设计了list_add操作用于向双链表中插入新节点
/**
* list_add - add a new entry
* @new: new entry to be added
* @head: list head to add it after
*
* Insert a new entry after the specified head.
* This is good for implementing stacks.
*/
static inline void list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
/*
* Insert a new entry between two known consecutive entries.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
if (!__list_add_valid(new, prev, next))
return;
next->prev = new;
new->next = next;
new->prev = prev;
WRITE_ONCE(prev->next, new);
}
可见这是头插法
当然也实现了尾插法:
/**
* list_add_tail - add a new entry
* @new: new entry to be added
* @head: list head to add it before
*
* Insert a new entry before the specified head.
* This is useful for implementing queues.
*/
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
API2 — Del
删除节点使用list_del
static inline void list_del(struct list_head *entry)
{
__list_del_entry(entry);
entry->next = LIST_POISON1;
entry->prev = LIST_POISON2;
}
/*
* Delete a list entry by making the prev/next entries
* point to each other.
*
* This is only for internal list manipulation where we know
* the prev/next entries already!
*/
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
WRITE_ONCE(prev->next, next);
}
/**
* list_del - deletes entry from list.
* @entry: the element to delete from the list.
* Note: list_empty() on entry does not return true after this, the entry is
* in an undefined state.
*/
static inline void __list_del_entry(struct list_head *entry)
{
if (!__list_del_entry_valid(entry))
return;
__list_del(entry->prev, entry->next);
}