玩轉內核鏈表list_head,3個超級哇塞的的例子


在Linux內核中,提供了一個用來創建雙向循環鏈表的結構 list_head。雖然linux內核是用C語言寫的,但是list_head的引入,使得內核數據結構也可以擁有面向對象的特性,通過使用操作list_head 的通用接口很容易實現代碼的重用,有點類似於C++的繼承機制(希望有機會寫篇文章研究一下C語言的面向對象機制)。

首先找到list_head結構體定義,kernel/inclue/linux/types.h 如下:

1 struct list_head {
2   struct list_head *next, *prev;
3 };
4 #define LIST_HEAD_INIT(name) { &(name), &(name) }

 

需要注意的一點是,頭結點head是不使用的,這點需要注意。
使用list_head組織的鏈表的結構如下圖所示:

在這里插入圖片描述

然后就開始圍繞這個結構開始構建鏈表,然后插入、刪除節點 ,遍歷整個鏈表等等,其實內核已經提供好了現成的接口,接下來就讓我們進入 kernel/include/linux/list.h中:

一. 創建鏈表

內核提供了下面的這些接口來初始化鏈表:

 1 #define LIST_HEAD_INIT(name) { &(name), &(name) }
 2 
 3 #define LIST_HEAD(name) \
 4   struct list_head name = LIST_HEAD_INIT(name)
 5 
 6 static inline void INIT_LIST_HEAD(struct list_head *list)
 7 {
 8   WRITE_ONCE(list->next, list);
 9   list->prev = list;
10 }

 

如: 可以通過 LIST_HEAD(mylist) 進行初始化一個鏈表,mylist的prev 和 next 指針都是指向自己。

1 structlist_head mylist = {&mylist, &mylist} ;

 

但是如果只是利用mylist這樣的結構體實現鏈表就沒有什么實際意義了,因為正常的鏈表都是為了遍歷結構體中的其它有意義的字段而創建的,而我們mylist中只有 prev和next指針,卻沒有實際有意義的字段數據,所以毫無意義。

綜上,我們可以創建一個宿主結構,然后在此結構中再嵌套mylist字段,宿主結構又有其它的字段(進程描述符 task_struct,頁面管理的page結構,等就是采用這種方法創建鏈表的)。為簡便理解,定義如下:

1 struct  mylist{
2     int type;
3     char name[MAX_NAME_LEN];
4     struct list_head list;
5 }

 

創建鏈表,並初始化

1 structlist_head myhead; 
2 INIT_LIST_HEAD(&myhead);

 

這樣我們的鏈表就初始化完畢,鏈表頭的myhead就prev 和 next指針分別指向myhead自己了,如下圖:
在這里插入圖片描述

二. 添加節點

內核已經提供了添加節點的接口了

1. list_add

如下所示。根據注釋可知,是在鏈表頭head后方插入一個新節點new。
 1 /**
 2  * list_add - add a new entry
 3  * @new: new entry to be added
 4  * @head: list head to add it after
 5  *
 6  * Insert a new entry after the specified head.
 7  * This is good for implementing stacks.
 8  */
 9 static inline void list_add(struct list_head *new, struct list_head *head)
10 {
11   __list_add(new, head, head->next);
12 }

 

list_add再調用__list_add接口

 1 /*
 2  * Insert a new entry between two known consecutive entries.
 3  *
 4  * This is only for internal list manipulation where we know
 5  * the prev/next entries already!
 6  */
 7 static inline void __list_add(struct list_head *new,
 8             struct list_head *prev,
 9             struct list_head *next)
10 {
11   if (!__list_add_valid(new, prev, next))
12     return;
13 
14   next->prev = new;
15   new->next = next;
16   new->prev = prev;
17   WRITE_ONCE(prev->next, new);
18 }

 

其實就是在myhead鏈表頭后和鏈表頭后第一個節點之間插入一個新節點。然后這個新的節點就變成了鏈表頭后的第一個節點了。

接着上面步驟創建1個節點然后插入到myhead之后

1 struct mylist node1;
2 node1.type = I2C_TYPE;
3 strcpy(node1.name,"yikoulinux");
4 list_add(&node1.list,&myhead);

 

在這里插入圖片描述

然后在創建第二個節點,同樣把它插入到header_task之后

1 struct mylist node2;
2 node2.type = I2C_TYPE;
3 strcpy(node2.name,"yikoupeng");
4 list_add(&node2.list,&myhead);

 

在這里插入圖片描述

以此類推,每次插入一個新節點,都是緊靠着header節點,而之前插入的節點依次排序靠后,那最后一個節點則是第一次插入header后的那個節點。最終可得出:先來的節點靠后,而后來的節點靠前,“先進后出,后進先出”。所以此種結構類似於 stack“堆棧”, 而header_task就類似於內核stack中的棧頂指針esp,它都是緊靠着最后push到棧的元素。

2. list_add_tail 接口

上面所講的list_add接口是從鏈表頭header后添加的節點。同樣,內核也提供了從鏈表尾處向前添加節點的接口list_add_tail.讓我們來看一下它的具體實現。

 1 /**
 2  * list_add_tail - add a new entry
 3  * @new: new entry to be added
 4  * @head: list head to add it before
 5  *
 6  * Insert a new entry before the specified head.
 7  * This is useful for implementing queues.
 8  */
 9 static inline void list_add_tail(struct list_head *new, struct list_head *head)
10 {
11   __list_add(new, head->prev, head);
12 }

 

從注釋可得出:
(1)在一個特定的鏈表頭前面插入一個節點

(2)這個方法很適用於隊列的實現(why?)

進一步把__list_add()展開如下:

 1 /*
 2  * Insert a new entry between two known consecutive entries.
 3  *
 4  * This is only for internal list manipulation where we know
 5  * the prev/next entries already!
 6  */
 7 static inline void __list_add(struct list_head *new,
 8             struct list_head *prev,
 9             struct list_head *next)
10 {
11   if (!__list_add_valid(new, prev, next))
12     return;
13 
14   next->prev = new;
15   new->next = next;
16   new->prev = prev;
17   WRITE_ONCE(prev->next, new);
18 }

 

所以,很清楚明了, list_add_tail就相當於在鏈表頭前方依次插入新的節點(也可理解為在鏈表尾部開始插入節點,此時,header節點既是為節點,保持不變)

利用上面分析list_add接口的方法可畫出數據結構圖形如下。

(1)創建一個鏈表頭(實際上應該是表尾)代碼參考第一節;

在這里插入圖片描述

(2)插入第一個節點 node1.list , 調用

1 struct mylist node1;
2  node1.type = I2C_TYPE;
3  strcpy(node1.name,"yikoulinux");
4  list_add_tail(&node1.list,&myhead);

 

在這里插入圖片描述

(3) 插入第二個節點node2.list,調用

1 struct mylist node2;
2  node2.type = I2C_TYPE;
3  strcpy(node2.name,"yikoupeng");
4  list_add_tail(&node2.list,&myhead);

 

在這里插入圖片描述
依此類推,每次插入的新節點都是緊挨着 header_task表尾,而插入的第一個節點my_first_task排在了第一位,my_second_task排在了第二位,可得出:先插入的節點排在前面,后插入的節點排在后面,“先進先出,后進后出”,這不正是隊列的特點嗎(First in First out)!

三. 刪除節點

內核同樣在list.h文件中提供了刪除節點的接口 list_del(), 讓我們看一下它的實現流程

 1 static inline void list_del(struct list_head *entry)
 2 {
 3   __list_del_entry(entry);
 4   entry->next = LIST_POISON1;
 5   entry->prev = LIST_POISON2;
 6 }
 7 /*
 8  * Delete a list entry by making the prev/next entries
 9  * point to each other.
10  *
11  * This is only for internal list manipulation where we know
12  * the prev/next entries already!
13  */
14 static inline void __list_del(struct list_head * prev, struct list_head * next)
15 {
16   next->prev = prev;
17   WRITE_ONCE(prev->next, next);
18 }
19 
20 /**
21  * list_del - deletes entry from list.
22  * @entry: the element to delete from the list.
23  * Note: list_empty() on entry does not return true after this, the entry is
24  * in an undefined state.
25  */
26 static inline void __list_del_entry(struct list_head *entry)
27 {
28   if (!__list_del_entry_valid(entry))
29     return;
30 
31   __list_del(entry->prev, entry->next);
32 }

 

利用list_del(struct list_head *entry) 接口就可以刪除鏈表中的任意節點了,但需注意,前提條件是這個節點是已知的,既在鏈表中真實存在,切prev,next指針都不為NULL。

四. 鏈表遍歷

內核是同過下面這個宏定義來完成對list_head鏈表進行遍歷的,如下 :

1 /**
2  * list_for_each  -  iterate over a list
3  * @pos:  the &struct list_head to use as a loop cursor.
4  * @head:  the head for your list.
5  */
6 #define list_for_each(pos, head) \
7   for (pos = (head)->next; pos != (head); pos = pos->next)

 

上面這種方式是從前向后遍歷的,同樣也可以使用下面的宏反向遍歷:

1 /**
2  * list_for_each_prev  -  iterate over a list backwards
3  * @pos:  the &struct list_head to use as a loop cursor.
4  * @head:  the head for your list.
5  */
6 #define list_for_each_prev(pos, head) \
7   for (pos = (head)->prev; pos != (head); pos = pos->prev)

 

而且,list.h 中也提供了list_replace(節點替換) list_move(節點移位) ,翻轉,查找等接口,這里就不在一一分析了。

五. 宿主結構

1.找出宿主結構 list_entry(ptr, type, member)

上面的所有操作都是基於list_head這個鏈表進行的,涉及的結構體也都是:

1 struct list_head {
2   struct list_head *next, *prev;
3 };

 

其實,正如文章一開始所說,我們真正更關心的是包含list_head這個結構體字段的宿主結構體,因為只有定位到了宿主結構體的起始地址,我們才能對對宿主結構體中的其它有意義的字段進行操作。

1 struct mylist
2 { 
3     int type;
4     char name[MAX_NAME_LEN];
5   struct list_head list;  
6 };

 

那我們如何根據list這個字段的地址而找到宿主結構node1的位置呢?list.h中定義如下:

1 /**
2  * list_entry - get the struct for this entry
3  * @ptr:  the &struct list_head pointer.
4  * @type:  the type of the struct this is embedded in.
5  * @member:  the name of the list_head within the struct.
6  */
7 #define list_entry(ptr, type, member) \
8   container_of(ptr, type, member)

 

list.h中提供了list_entry宏來實現對應地址的轉換,但最終還是調用了container_of宏,所以container_of宏的偉大之處不言而喻。

2 container_of

做linux驅動開發的同學是不是想到了LDD3這本書中經常使用的一個非常經典的宏定義!

1 container_of(ptr, type, member)

 

在LDD3這本書中的第三章字符設備驅動,以及第十四章驅動設備模型中多次提到,我覺得這個宏應該是內核最經典的宏之一。那接下來讓我們揭開她的面紗:

此宏在內核代碼 kernel/include/linux/kernel.h中定義(此處kernel版本為3.10;新版本4.13之后此宏定義改變,但實現思想保持一致)
在這里插入圖片描述

而offsetof定義在 kernel/include/linux/stddef.h ,如下:
在這里插入圖片描述

舉個例子,來簡單分析一下container_of內部實現機制。

例如:

 1 struct   test
 2 {
 3     int       a;
 4     short   b;
 5     char    c;
 6 };
 7 struct  test  *p = (struct test *)malloc(sizeof(struct  test));
 8 test_function(&(p->b));
 9 
10 int  test_function(short *addr_b)
11 {
12       //獲取struct test結構體空間的首地址
13      struct  test *addr;
14      addr =   container_of(addr_b,struct test,b);
15 }

 

展開container_of宏,探究內部的實現:

1 typeof (  ( (struct test   *)0 )->b ) ;                        (1)
2 typeof (  ( (struct test   *)0 )->b )   *__mptr =  addr_b ;    (2)
3 (struct test *)( (char *)__mptr  -  offsetof(struct test,b))   (3)

 

(1) 獲取成員變量b的類型 ,這里獲取的就是short 類型。這是GNU_C的擴展語法。

(2) 用獲取的變量類型,定義了一個指針變量 __mptr ,並且將成員變量 b的首地址賦值給它

(3) 這里的offsetof(struct test,b)是用來計算成員b在這個struct test 結構體的偏移。__mptr

是成員b的首地址, 現在 減去成員b在結構體里面的偏移值,算出來的是不是這個結構體的

首地址呀 。

3. 宿主結構的遍歷

我們可以根據結構體中成員變量的地址找到宿主結構的地址,並且我們可以對成員變量所建立的鏈表進行遍歷,那我們是不是也可以通過某種方法對宿主結構進行遍歷呢?

答案肯定是可以的,內核在list.h中提供了下面的宏:

 1 /**
 2  * list_for_each_entry  -  iterate over list of given type
 3  * @pos:  the type * to use as a loop cursor.
 4  * @head:  the head for your list.
 5  * @member:  the name of the list_head within the struct.
 6  */
 7 #define list_for_each_entry(pos, head, member)        \
 8   for (pos = list_first_entry(head, typeof(*pos), member);  \
 9        &pos->member != (head);          \
10        pos = list_next_entry(pos, member))

 

其中,list_first_entry 和 list_next_entry宏都定義在list.h中,分別代表:獲取第一個真正的宿主結構的地址;獲取下一個宿主結構的地址。它們的實現都是利用list_entry宏。

/**
 * list_first_entry - get the first element from a list
 * @ptr:  the list head to take the element from.
 * @type:  the type of the struct this is embedded in.
 * @member:  the name of the list_head within the struct.
 *
 * Note, that list is expected to be not empty.
 */
#define list_first_entry(ptr, type, member) \
  list_entry((ptr)->next, type, member)

/**
 * list_next_entry - get the next element in list
 * @pos:  the type * to cursor
 * @member:  the name of the list_head within the struct.
 */
#define list_next_entry(pos, member) \
  list_entry((pos)->member.next, typeof(*(pos)), member)

 

最終實現了宿主結構的遍歷

1 #define list_for_each_entry(pos, head, member)      \
2   for (pos = list_first_entry(head, typeof(*pos), member);  \
3        &pos->member != (head);          \
4        pos = list_next_entry(pos, member))

 

首先pos定位到第一個宿主結構地址,然后循環獲取下一個宿主結構地址,如果查到宿主結構中的member成員變量(宿主結構中struct list_head定義的字段)地址為head,則退出,從而實現了宿主結構的遍歷。如果要循環對宿主結構中的其它成員變量進行操作,這個遍歷操作就顯得特別有意義了。

我們用上面的 nod結構舉個例子:

1 struct my_list *pos_ptr = NULL ; 
2 list_for_each_entry (pos_ptr, &myhead, list ) 
3 { 
4          printk ("val =  %d\n" , pos_ptr->val); 
5 }

 

實例1 一個簡單的鏈表的實現

為方便起見,本例把內核的list.h文件單獨拷貝出來,這樣就可以獨立於內核來編譯測試。

功能描述:

本例比較簡單,僅僅實現了單鏈表節點的創建、刪除、遍歷。

 1 #include "list.h" 
 2 #include <stdio.h> 
 3 #include <string.h>
 4 
 5 #define MAX_NAME_LEN 32
 6 #define MAX_ID_LEN 10
 7 
 8 struct list_head myhead;
 9 
10 #define I2C_TYPE 1
11 #define SPI_TYPE 2
12 
13 char *dev_name[]={
14   "none",
15   "I2C",
16   "SPI"
17 };
18 
19 struct mylist
20 { 
21     int type;
22     char name[MAX_NAME_LEN];
23   struct list_head list;  
24 };
25 
26 void display_list(struct list_head *list_head)
27 {
28   int i=0;
29   struct list_head *p;
30   struct mylist *entry;
31   printf("-------list---------\n");
32   list_for_each(p,list_head)
33   {
34     printf("node[%d]\n",i++);
35     entry=list_entry(p,struct mylist,list);
36     printf("\ttype: %s\n",dev_name[entry->type]);
37     printf("\tname: %s\n",entry->name);
38   }
39   printf("-------end----------\n");
40 }
41 
42 int main(void)
43 {
44 
45   struct mylist node1;
46   struct mylist node2;
47 
48   INIT_LIST_HEAD(&myhead);
49 
50   node1.type = I2C_TYPE;
51   strcpy(node1.name,"yikoulinux");
52 
53   node2.type = I2C_TYPE;
54   strcpy(node2.name,"yikoupeng");
55 
56   list_add(&node1.list,&myhead);
57   list_add(&node2.list,&myhead);
58 
59   display_list(&myhead);
60 
61   list_del(&node1.list);
62 
63   display_list(&myhead);
64   return 0;
65 }

 

運行結果
在這里插入圖片描述

實例2 如何在一個鏈表上管理不同類型的節點

功能描述:

本實例主要實現在同一個鏈表上管理兩個不同類型的節點,實現增刪改查的操作。

結構體定義

一個鏈表要想區分節點的不同類型,那么節點中必須要有信息能夠區分該節點類型,為了方便節點擴展,我們參考Linux內核,定義一個統一類型的結構體:

1 struct device
2 {
3     int type;
4     char name[MAX_NAME_LEN];
5     struct list_head list;
6 };

 

其中成員type表示該節點的類型:

1 #defineI2C_TYPE 1 
2 #define SPI_TYPE 2

 

有了該結構體,我們要定義其他類型的結構體只需要包含該結構體即可,這個思想有點像面向對象語言的基類,后續派生出新的屬性叫子類,說到這,一口君又忍不住想挖個坑,寫一篇如何用C語言實現面向對象思想的繼承、多態、interface。

下面我們定義2種類型的結構體:
i2c這種類型設備的專用結構體:

1 struct i2c_node
2 {
3   int data;
4   unsigned int reg;
5   struct device dev;
6 };

 

spi這種類型設備的專用結構體:

1 struct spi_node
2 {  
3   unsigned int reg;
4   struct device dev;
5 };

 

我特意讓兩個結構體大小類型不一致。

結構類型

鏈表頭結點定義

1 structlist_head device_list;

 

根據之前我們講解的思想,這個鏈表鏈接起來后,應該是以下這種結構:

在這里插入圖片描述

節點的插入

我們定義的節點要插入鏈表仍然是要依賴list_add(),既然我們定義了struct device這個結構體,那么我們完全可以參考linux內核,針對不同的節點封裝函數,要注冊到這個鏈表只需要調用該函數即可。

實現如下:

設備i2c的注冊函數如下:

1 void i2c_register_device(struct device*dev)
2 {
3   dev.type = I2C_TYPE;
4   strcpy(dev.name,"yikoulinux");
5   list_add(&dev->list,&device_list);  
6 }

 

設備spi的注冊函數如下:

1 void spi_register_device(struct device*dev)
2 {
3   dev.type = SPI_TYPE;
4   strcpy(dev.name,"yikoupeng");
5   list_add(&dev->list,&device_list);  
6 }

 

我們可以看到注冊函數功能是填充了struct device 的type和name成員,然后再調用list_add()注冊到鏈表中。這個思想很重要,因為Linux內核中許許多多的設備節點也是這樣添加到其他的鏈表中的。要想讓自己的C語言編程能力得到質的提升,一定要多讀內核代碼,即使看不懂也要堅持看,古人有雲:代碼讀百遍其義自見。

節點的刪除

同理,節點的刪除,我們也統一封裝成函數,同樣只傳遞參數device即可:

 1 void i2c_unregister_device(struct device *device)
 2 {
 3 //  struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);
 4   list_del(&device->list);
 5 }
 6 void spi_unregister_device(struct device *device)
 7 {
 8 //  struct spi_node *spi_device=container_of(dev, struct spi_node, dev);
 9   list_del(&device->list);
10 }

 

在函數中,可以用container_of提取出了設備節點的首地址,實際使用中可以根據設備的不同釋放不同的資源。

宿主結構的遍歷

節點的遍歷,在這里我們通過設備鏈表device_list開始遍歷,假設該節點名是node,通過list_for_each()可以得到node->dev->list的地址,然后利用container_of 可以得到node->dev、node的地址。

 1 void display_list(struct list_head *list_head)
 2 {
 3   int i=0;
 4   struct list_head *p;
 5   struct device *entry;
 6 
 7   printf("-------list---------\n");
 8   list_for_each(p,list_head)
 9   {
10     printf("node[%d]\n",i++);
11     entry=list_entry(p,struct device,list);
12 
13     switch(entry->type)
14     {
15       case I2C_TYPE:
16                            display_i2c_device(entry);
17         break;
18       case SPI_TYPE:
19         display_spi_device(entry);
20         break;
21       default:
22         printf("unknown device type!\n");
23         break;
24     }
25     display_device(entry);
26   }
27   printf("-------end----------\n");
28 }

 

由以上代碼可知,利用內核鏈表的統一接口,找個每一個節點的list成員,然后再利用container_of 得到我們定義的標准結構體struct device,進而解析出節點的類型,調用對應節點顯示函數,這個地方其實還可以優化,就是我們可以在struct device中添加一個函數指針,在xxx_unregister_device()函數中可以將該函數指針直接注冊進來,那么此處代碼會更精簡高效一些。如果在做項目的過程中,寫出這種面向對象思想的代碼,那么你的地址是肯定不一樣的。讀者有興趣可以自己嘗試一下。

 1 void display_i2c_device(struct device *device)
 2 {
 3   struct i2c_node *i2c_device=container_of(device, struct i2c_node, dev);
 4   printf("\t  i2c_device->data: %d\n",i2c_device->data);
 5   printf("\t  i2c_device->reg: %#x\n",i2c_device->reg);
 6 }
 7 
 8 void display_spi_device(struct device *device)
 9 {
10   struct spi_node *spi_device=container_of(device, struct spi_node, dev);
11   printf("\t  spi_device->reg: %#x\n",spi_device->reg);
12 }

 



上述代碼提取出來宿主節點的信息。

實例代碼

  1 #include "list.h" 
  2 #include <stdio.h> 
  3 #include <string.h>
  4 
  5 #define MAX_NAME_LEN 32
  6 #define MAX_ID_LEN 10
  7 
  8 struct list_head device_list;
  9 
 10 #define I2C_TYPE 1
 11 #define SPI_TYPE 2
 12 
 13 char *dev_name[]={
 14   "none",
 15   "I2C",
 16   "SPI"
 17 };
 18 
 19 struct device
 20 {
 21   int type;
 22   char name[MAX_NAME_LEN];
 23   struct list_head list;
 24 };
 25 
 26 struct i2c_node
 27 {
 28   int data;
 29   unsigned int reg;
 30   struct device dev;
 31 };
 32 struct spi_node
 33 {  
 34   unsigned int reg;
 35   struct device dev;
 36 };
 37 void display_i2c_device(struct device *device)
 38 {
 39   struct i2c_node *i2c_device=container_of(device, struct i2c_node, dev);
 40 
 41   printf("\t  i2c_device->data: %d\n",i2c_device->data);
 42   printf("\t  i2c_device->reg: %#x\n",i2c_device->reg);
 43 }
 44 void display_spi_device(struct device *device)
 45 {
 46   struct spi_node *spi_device=container_of(device, struct spi_node, dev);
 47 
 48   printf("\t  spi_device->reg: %#x\n",spi_device->reg);
 49 }
 50 void display_device(struct device *device)
 51 {
 52     printf("\t  dev.type: %d\n",device->type);
 53     printf("\t  dev.type: %s\n",dev_name[device->type]);
 54     printf("\t  dev.name: %s\n",device->name);
 55 }
 56 void display_list(struct list_head *list_head)
 57 {
 58   int i=0;
 59   struct list_head *p;
 60   struct device *entry;
 61 
 62   printf("-------list---------\n");
 63   list_for_each(p,list_head)
 64   {
 65     printf("node[%d]\n",i++);
 66     entry=list_entry(p,struct device,list);
 67 
 68     switch(entry->type)
 69     {
 70       case I2C_TYPE:
 71         display_i2c_device(entry);
 72         break;
 73       case SPI_TYPE:
 74         display_spi_device(entry);
 75         break;
 76       default:
 77         printf("unknown device type!\n");
 78         break;
 79     }
 80     display_device(entry);
 81   }
 82   printf("-------end----------\n");
 83 }
 84 void i2c_register_device(struct device*dev)
 85 {
 86   struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);
 87 
 88   i2c_device->dev.type = I2C_TYPE;
 89   strcpy(i2c_device->dev.name,"yikoulinux");
 90 
 91   list_add(&dev->list,&device_list);  
 92 }
 93 void spi_register_device(struct device*dev)
 94 {
 95   struct spi_node *spi_device=container_of(dev, struct spi_node, dev);
 96 
 97   spi_device->dev.type = SPI_TYPE;
 98   strcpy(spi_device->dev.name,"yikoupeng");
 99 
100   list_add(&dev->list,&device_list);  
101 }
102 void i2c_unregister_device(struct device *device)
103 {
104   struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);
105 
106   list_del(&device->list);
107 }
108 void spi_unregister_device(struct device *device)
109 {
110   struct spi_node *spi_device=container_of(dev, struct spi_node, dev);
111 
112   list_del(&device->list);
113 }
114 int main(void)
115 {
116 
117   struct i2c_node dev1;
118   struct spi_node dev2;
119 
120   INIT_LIST_HEAD(&device_list);
121   dev1.data = 1;
122   dev1.reg = 0x40009000;
123   i2c_register_device(&dev1.dev);
124   dev2.reg  = 0x40008000;
125   spi_register_device(&dev2.dev);  
126   display_list(&device_list);
127   unregister_device(&dev1.dev);
128   display_list(&device_list);  
129   return 0;
130 }

 

代碼主要功能:

117-118          :定義兩個不同類型的節點dev1,dev2;
120                 :初始化設備鏈表;
121-122、124:初始化節點數據;
123/125          :向鏈表device_list注冊這兩個節點;
126                :顯示該鏈表;
127                :刪除節點dev1;
128                 :顯示該鏈表。

 

程序運行截圖
在這里插入圖片描述

讀者可以試試如何管理更多類型的節點。

實例3 實現節點在兩個鏈表上自由移動

功能描述:

初始化兩個鏈表,實現兩個鏈表上節點的插入和移動。每個節點維護大量的臨時內存數據。

節點創建

節點結構體創建如下:

1 struct mylist{
2   int number;
3   char type;
4     char *pmem;  //內存存放地址,需要malloc
5   struct list_head list;
6 };

 

需要注意成員pmem,因為要維護大量的內存,我們最好不要直定義個很大的數組,因為定義的變量位於棧中,而一般的系統給棧的空間是有限的,如果定義的變量占用空間太大,會導致棧溢出,一口君曾經就遇到過這個bug。

鏈表定義和初始化

鏈表定義如下:

1 structlist_head active_head; 
2 struct list_head free_head;

 

初始化

1 INIT_LIST_HEAD(&free_head);
2 INIT_LIST_HEAD(&active_head);

 

這兩個鏈表如下:

在這里插入圖片描述

關於節點,因為該實例是從實際項目中剝離出來,節點啟示是起到一個緩沖去的作用,數量不是無限的,所以在此我們默認最多10個節點。

我們不再動態創建節點,而是先全局創建指針數組,存放這10個節點的地址,然后將這10個節點插入到對應的隊列中。

數組定義:

1 structmylist*list_array[BUFFER_NUM];

 

這個數組只用於存放指針,所以定義之后實際情況如下:

在這里插入圖片描述

初始化這個數組對應的節點:

 1 static ssize_t buffer_ring_init()
 2 {
 3   int i=0;
 4   for(i=0;i<BUFFER_NUM;i++){
 5     list_array[i]=malloc(sizeof(struct mylist));
 6     INIT_LIST_HEAD(&list_array[i]->list);
 7     list_array[i]->pmem=kzalloc(DATA_BUFFER_SIZE,GFP_KERNEL);
 8   }
 9   return 0;
10 }

 

5:為下標為i的節點分配實際大小為sizeof(structmylist)的內存
6:初始化該節點的鏈表
7:為pmem成員從堆中分配一塊內存

初始化完畢,鏈表實際情況如下:

節點插入

1 static ssize_t insert_free_list_all()
2 {
3   int i=0;
4 
5   for(i=0;i<BUFFER_NUM;i++){
6     list_add(&list_array[i]->list,&free_head);
7   }
8   return 0;
9 }

6:用頭插法將所有節點插入到free_head鏈表中

所有節點全部插入free鏈表后,結構圖如下:

在這里插入圖片描述

遍歷鏈表

雖然可以通過數組遍歷鏈表,但是實際在操作過程中,在鏈表中各個節點的位置是錯亂的。所以最好從借助list節點來查找各個節點。

1 show_list(&free_head);
2 show_list(&active_head);

 

代碼實現如下:

 1 void show_list(struct list_head *list_head)
 2 {
 3   int i=0;
 4   struct mylist*entry,*tmp;
 5   //判斷節點是否為空
 6   if(list_empty(list_head)==true)
 7   {
 8     return;
 9   }
10   list_for_each_entry_safe(entry,tmp,list_head,list)
11   {
12     printf("[%d]=%d\t",i++,entry->number);
13     if(i%4==0)
14     {
15       printf("\n");
16     }
17   }  
18 }

 

節點移動

將節點從active_head鏈表移動到free_head鏈表,有點像生產者消費者模型中的消費者,吃掉資源后,就要把這個節點放置到空閑鏈表,讓生產者能夠繼續生產數據,所以這兩個函數我起名eat、spit,意為吃掉和吐,希望你們不要覺得很怪異。

 1 int eat_node()
 2 {
 3   struct mylist*entry=NULL;
 4 
 5   if(list_empty(&active_head)==true)
 6   {
 7     printf("list active_head is empty!-----------\n");
 8   }
 9   entry=list_first_entry(&active_head,struct mylist,list);
10   printf("\t eat node=%d\n",entry->number);
11   list_move_tail(&entry->list,&free_head);
12 }

 

節點移動的思路是:

  1. 利用list_empty判斷該鏈表是否為空
  2. 利用list_first_entry從active_head鏈表中查找到一個節點,並用指針entry指向該節點
  3. 利用list_move_tail將該節點移入到free_head鏈表,注意此處不能用list_add,因為這個節點我要從原鏈表把他刪除掉,然后插入到新鏈表。

將節點從free_head鏈表移動到active_head鏈表。

 1 spit_node()
 2 {
 3   struct mylist*entry=NULL;
 4 
 5   if(list_empty(&free_head)==true)
 6   {
 7     printf("list free_head is empty!-----------\n");
 8   }
 9   entry=list_first_entry(&free_head,struct mylist,list);
10   printf("\t spit node=%d\n",entry->number);
11   list_move_tail(&entry->list,&active_head);
12 }

 

大部分功能講解完了,下面我們貼下完整代碼。

代碼實例

  1 #include <stdint.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #include <unistd.h>
  5 #include <byteswap.h>
  6 #include <string.h>
  7 #include <errno.h>
  8 #include <signal.h>
  9 #include <fcntl.h>
 10 #include <ctype.h>
 11 #include <termios.h>
 12 #include <sys/types.h>
 13 #include <sys/mman.h>
 14 #include <sys/ioctl.h>
 15 #include "list.h"     //  linux-3.14/scripts/kconfig/list.h
 16 
 17 #undef NULL
 18 #define NULL ((void *)0)
 19 
 20 enum {
 21   false  = 0,
 22   true  = 1
 23 };
 24 
 25 #define DATA_TYPE 0x14
 26 #define SIG_TYPE 0x15
 27 
 28 struct mylist{
 29   int number;
 30   char type;
 31   char *pmem;
 32   struct list_head list;
 33 };
 34 #define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n",__LINE_,__FILE__,errno,strerror(errno));exit(1);}while(0)
 35 struct list_head active_head;
 36 struct list_head free_head;
 37 #define BUFFER_NUM 10
 38 #define DATA_BUFFER_SIZE 512
 39 struct mylist*list_array[BUFFER_NUM];
 40 
 41 
 42 int born_number(int number)
 43 {
 44   struct mylist *entry=NULL;
 45 
 46   if(list_empty(&free_head)==true)
 47   {
 48     printf("list free_head is empty!----------------\n");
 49   }
 50   entry = list_first_entry(&free_head,struct mylist,list);
 51   entry->type = DATA_TYPE;
 52   entry->number=number;
 53   list_move_tail(&entry->list,&active_head);  
 54 }
 55 
 56 int eat_node()
 57 {
 58   struct mylist*entry=NULL;
 59 
 60   if(list_empty(&active_head)==true)
 61   {
 62     printf("list active_head is empty!-----------\n");
 63   }
 64   entry=list_first_entry(&active_head,struct mylist,list);
 65   printf("\t eat node=%d\n",entry->number);
 66   list_move_tail(&entry->list,&free_head);
 67 }
 68 spit_node()
 69 {
 70   struct mylist*entry=NULL;
 71 
 72   if(list_empty(&free_head)==true)
 73   {
 74     printf("list free_head is empty!-----------\n");
 75   }
 76   entry=list_first_entry(&free_head,struct mylist,list);
 77   printf("\t spit node=%d\n",entry->number);
 78   list_move_tail(&entry->list,&active_head);
 79 }
 80 
 81 void show_list(struct list_head *list_head)
 82 {
 83   int i=0;
 84   struct mylist*entry,*tmp;
 85 
 86   if(list_empty(list_head)==true)
 87   {
 88     return;
 89   }
 90   list_for_each_entry_safe(entry,tmp,list_head,list)
 91   {
 92     printf("[%d]=%d\t",i++,entry->number);
 93     if(i%4==0)
 94     {
 95       printf("\n");
 96     }
 97   }  
 98 }
 99 int list_num(struct list_head *list_head)
100 {
101   int i=0;
102   struct mylist *entry,*tmp;
103 //  printf("----------show free list-------------\n");
104   list_for_each_entry_safe(entry,tmp,list_head,list)
105   {
106     i++;
107   }
108   return i;
109 }
110 static ssize_t buffer_ring_init()
111 {
112   int i=0;
113 
114   for(i=0;i<BUFFER_NUM;i++){
115     list_array[i]=malloc(sizeof(struct mylist));
116     INIT_LIST_HEAD(&list_array[i]->list);
117     list_array[i]->pmem=kzalloc(DATA_BUFFER_SIZE,GFP_KERNEL);
118     list_add_tail(&list_array[i]->list,&free_head);
119   }
120   return 0;
121 }
122 static ssize_t insert_free_list_all()
123 {
124   int i=0;
125 
126   for(i=0;i<BUFFER_NUM;i++){
127     list_add_tail(&list_array[i]->list,&free_head);
128   }
129   return 0;
130 }
131 static ssize_t buffer_ring_free()
132 {
133   int buffer_count=0;
134   struct mylist*entry=NULL;
135   for(;buffer_count<BUFFER_NUM;buffer_count++)
136   {
137     free(list_array[buffer_count]->pmem);
138     free(list_array[buffer_count]);
139   }
140   return 0;
141 }
142 
143 int main(int argc,char**argv)
144 {
145   INIT_LIST_HEAD(&free_head);
146   INIT_LIST_HEAD(&active_head);
147   buffer_ring_init();
148   insert_free_list_all();
149   born_number(1);
150   born_number(2);
151   born_number(3);
152   born_number(4);
153   born_number(5);
154   born_number(6);
155   born_number(7);
156   born_number(8);
157   born_number(9);
158   born_number(10);
159 
160   printf("\n----------active list[%d]------------\n",list_num(&active_head));
161   show_list(&active_head);
162   printf("\n--------------end-----------------\n");
163 
164   printf("\n----------free list[%d]------------\n",list_num(&free_head));  
165   show_list(&free_head);
166   printf("\n--------------end-----------------\n");
167 
168   printf("\n\n    active list----------> free list \n");
169 
170   eat_node();
171   eat_node();
172   eat_node();
173 
174   printf("\n----------active list[%d]------------\n",list_num(&active_head));
175   show_list(&active_head);
176   printf("\n--------------end-----------------\n");
177 
178   printf("\n----------free list[%d]------------\n",list_num(&free_head));  
179   show_list(&free_head);
180   printf("\n--------------end-----------------\n");
181 
182 
183   printf("\n\n    free list----------> active list \n");
184 
185   spit_node();
186   spit_node();
187 
188   printf("\n----------active list[%d]------------\n",list_num(&active_head));
189   show_list(&active_head);
190   printf("\n--------------end-----------------\n");
191 
192   printf("\n----------free list[%d]------------\n",list_num(&free_head));  
193   show_list(&free_head);
194   printf("\n--------------end-----------------\n");
195 
196 }

 

運行結果如下:

在這里插入圖片描述

在這里插入圖片描述

list_head短小精悍,讀者可以借鑒此文實現其他功能。

參考文檔:https://kernelnewbies.org/FAQ/LinkedLists

           《Understanding linux kernel》

            《Linux device drivers》

list.h比較長,就不在此貼出源碼,如果讀者想獲取這個文件,關注公眾號:一口Linux,一口君這還有大量的Linux學習資料。


  在Linux內核中,提供了一個用來創建雙向循環鏈表的結構 list_head。雖然linux內核是用C語言寫的,但是list_head的引入,使得內核數據結構也可以擁有面向對象的特性,通過使用操作list_head 的通用接口很容易實現代碼的重用,有點類似於C++的繼承機制(希望有機會寫篇文章研究一下C語言的面向對象機制)。

 

首先找到list_head結構體定義,kernel/inclue/linux/types.h  如下:

```c
struct list_head {
  struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
```

 

需要注意的一點是,頭結點head是不使用的,這點需要注意。
使用list_head組織的鏈表的結構如下圖所示:

![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3czB5eko5U0RkZ1F1TDRNbVI2dWh3SzFLMVlLOEVxTEZ1OVFmVVpNV1pMWkliY0xxWHFnTTBBLzY0MA?x-oss-process=image/format,png#pic_center)


然后就開始圍繞這個結構開始構建鏈表,然后插入、刪除節點 ,遍歷整個鏈表等等,其實內核已經提供好了現成的接口,接下來就讓我們進入 kernel/include/linux/list.h中:

## 一. 創建鏈表

內核提供了下面的這些接口來初始化鏈表:

```c
#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)
{
  WRITE_ONCE(list->next, list);
  list->prev = list;
}
```


如:  可以通過 LIST_HEAD(mylist) 進行初始化一個鏈表,mylist的prev 和 next 指針都是指向自己。

```c
structlist_head mylist = {&mylist, &mylist} ;
```
     
但是如果只是利用mylist這樣的結構體實現鏈表就沒有什么實際意義了,因為正常的鏈表都是為了遍歷結構體中的其它有意義的字段而創建的,而我們mylist中只有 prev和next指針,卻沒有實際有意義的字段數據,所以毫無意義。

綜上,我們可以創建一個宿主結構,然后在此結構中再嵌套mylist字段,宿主結構又有其它的字段(進程描述符 task_struct,頁面管理的page結構,等就是采用這種方法創建鏈表的)。為簡便理解,定義如下:

```c
struct  mylist{
    int type;
    char name[MAX_NAME_LEN];
    struct list_head list;
}
```

創建鏈表,並初始化

```c
structlist_head myhead;
INIT_LIST_HEAD(&myhead);
```


這樣我們的鏈表就初始化完畢,鏈表頭的myhead就prev 和 next指針分別指向myhead自己了,如下圖:
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3YTRnOGFJOVl2OFk3Y0FjNUZtS1p4aFF4NWQzVExXWE1ZM2liVXc0N0xpYlFQSnQ2bkpHRWM3UVEvNjQw?x-oss-process=image/format,png#pic_center)

## 二. 添加節點

內核已經提供了添加節點的接口了


### 1.  list_add

    如下所示。根據注釋可知,是在鏈表頭head后方插入一個新節點new。

```c
/**
 * 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);
}
```

list_add再調用__list_add接口

```c
/*
 * 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);
}
```


其實就是在myhead鏈表頭后和鏈表頭后第一個節點之間插入一個新節點。然后這個新的節點就變成了鏈表頭后的第一個節點了。

接着上面步驟創建1個節點然后插入到myhead之后

```c
struct mylist node1;
node1.type = I2C_TYPE;
strcpy(node1.name,"yikoulinux");
list_add(&node1.list,&myhead);
```
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3dnNHWlBpYkFkdW40SmlhTnBqcWd0elhGVEtNanRwTjRLQnd3cXhrNHAxN3prVEhUWGNOMmFmTncvNjQw?x-oss-process=image/format,png#pic_center)


然后在創建第二個節點,同樣把它插入到header_task之后

```c
struct mylist node2;
node2.type = I2C_TYPE;
strcpy(node2.name,"yikoupeng");
list_add(&node2.list,&myhead);
```
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3SVRTSHhVdFAwYWRLVGdNaWNCM3Vqd01pYnlGa1FSVFVjSHQydmt4d1FPM3Iyb0tNNHRnWjZpYkNBLzY0MA?x-oss-process=image/format,png#pic_center)


以此類推,每次插入一個新節點,都是緊靠着header節點,而之前插入的節點依次排序靠后,那最后一個節點則是第一次插入header后的那個節點。最終可得出:先來的節點靠后,而后來的節點靠前,“先進后出,后進先出”。所以此種結構類似於 stack“堆棧”, 而header_task就類似於內核stack中的棧頂指針esp,它都是緊靠着最后push到棧的元素。


### 2. list_add_tail 接口

上面所講的list_add接口是從鏈表頭header后添加的節點。同樣,內核也提供了從鏈表尾處向前添加節點的接口list_add_tail.讓我們來看一下它的具體實現。

```c
/**
 * 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);
}
```


從注釋可得出:
(1)在一個特定的鏈表頭前面插入一個節點

(2)這個方法很適用於隊列的實現(why?)

進一步把__list_add()展開如下:

```c
/*
 * 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就相當於在鏈表頭前方依次插入新的節點(也可理解為在鏈表尾部開始插入節點,此時,header節點既是為節點,保持不變)

    利用上面分析list_add接口的方法可畫出數據結構圖形如下。

(1)創建一個鏈表頭(實際上應該是表尾)代碼參考第一節;   

  ![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3YTRnOGFJOVl2OFk3Y0FjNUZtS1p4aFF4NWQzVExXWE1ZM2liVXc0N0xpYlFQSnQ2bkpHRWM3UVEvNjQw?x-oss-process=image/format,png#pic_center)


(2)插入第一個節點 node1.list , 調用

 

```c
struct mylist node1;
 node1.type = I2C_TYPE;
 strcpy(node1.name,"yikoulinux");
 list_add_tail(&node1.list,&myhead);
```
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3TzQ1MEo0bUZjOUh0dHJ4RUpJQ3hKekFjTFBneGRjZ2tSQUppYzJJRDZOVVJDMWRDSnNVR0pVZy82NDA?x-oss-process=image/format,png#pic_center)


    

(3) 插入第二個節點node2.list,調用

```c
struct mylist node2;
 node2.type = I2C_TYPE;
 strcpy(node2.name,"yikoupeng");
 list_add_tail(&node2.list,&myhead);
```
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3a2dhTjYwVFBsREh1aWJ3MHJRMTJVaWFVb3NSRGxnVVY0M0pYeDVJQmFHbEViWE9QMDZRZExXa3cvNjQw?x-oss-process=image/format,png#pic_center)
依此類推,每次插入的新節點都是緊挨着 header_task表尾,而插入的第一個節點my_first_task排在了第一位,my_second_task排在了第二位,可得出:先插入的節點排在前面,后插入的節點排在后面,“先進先出,后進后出”,這不正是隊列的特點嗎(First in First out)!

 
### 三. 刪除節點

內核同樣在list.h文件中提供了刪除節點的接口 list_del(), 讓我們看一下它的實現流程

```c
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);
}
```

利用list_del(struct list_head *entry) 接口就可以刪除鏈表中的任意節點了,但需注意,前提條件是這個節點是已知的,既在鏈表中真實存在,切prev,next指針都不為NULL。

   
### 四. 鏈表遍歷

內核是同過下面這個宏定義來完成對list_head鏈表進行遍歷的,如下 :

```c
/**
 * list_for_each  -  iterate over a list
 * @pos:  the &struct list_head to use as a loop cursor.
 * @head:  the head for your list.
 */
#define list_for_each(pos, head) \
  for (pos = (head)->next; pos != (head); pos = pos->next)
```

   上面這種方式是從前向后遍歷的,同樣也可以使用下面的宏反向遍歷:

```c
/**
 * list_for_each_prev  -  iterate over a list backwards
 * @pos:  the &struct list_head to use as a loop cursor.
 * @head:  the head for your list.
 */
#define list_for_each_prev(pos, head) \
  for (pos = (head)->prev; pos != (head); pos = pos->prev)
```

  而且,list.h 中也提供了list_replace(節點替換)  list_move(節點移位) ,翻轉,查找等接口,這里就不在一一分析了。

 
### 五. 宿主結構
1.找出宿主結構  list_entry(ptr, type, member)

   上面的所有操作都是基於list_head這個鏈表進行的,涉及的結構體也都是:

```c
struct list_head {
  struct list_head *next, *prev;
};
```

其實,正如文章一開始所說,我們真正更關心的是包含list_head這個結構體字段的宿主結構體,因為只有定位到了宿主結構體的起始地址,我們才能對對宿主結構體中的其它有意義的字段進行操作。

```c
struct mylist
{
    int type;
    char name[MAX_NAME_LEN];
  struct list_head list;  
};
```

   那我們如何根據list這個字段的地址而找到宿主結構node1的位置呢?list.h中定義如下:

```c
/**
 * list_entry - get the struct for this entry
 * @ptr:  the &struct list_head pointer.
 * @type:  the type of the struct this is embedded in.
 * @member:  the name of the list_head within the struct.
 */
#define list_entry(ptr, type, member) \
  container_of(ptr, type, member)
```


   list.h中提供了list_entry宏來實現對應地址的轉換,但最終還是調用了container_of宏,所以container_of宏的偉大之處不言而喻。

 
### 2 container_of

做linux驅動開發的同學是不是想到了LDD3這本書中經常使用的一個非常經典的宏定義!

```c
container_of(ptr, type, member)
```

在LDD3這本書中的第三章字符設備驅動,以及第十四章驅動設備模型中多次提到,我覺得這個宏應該是內核最經典的宏之一。那接下來讓我們揭開她的面紗:

   此宏在內核代碼 kernel/include/linux/kernel.h中定義(此處kernel版本為3.10;新版本4.13之后此宏定義改變,但實現思想保持一致)
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3TU04TW15Q2ljTHlHdVcwaHllZ0xpYUVDSU1zaWFRNE1zUWV6U2duank1V1hRZlFNbVhwWWppYVFYdy82NDA?x-oss-process=image/format,png#pic_center)而offsetof定義在 kernel/include/linux/stddef.h ,如下:
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3VWZpYk5KcFRjZ2lhU0hTT1YyalBtbFVpYkVUT1JyVk5oWkpqNFNBNXhpYmljMHphcnM3TFdZRlhOQkEvNjQw?x-oss-process=image/format,png#pic_center)

舉個例子,來簡單分析一下container_of內部實現機制。

 

例如:

```c
struct   test
{
    int       a;
    short   b;
    char    c;
};
struct  test  *p = (struct test *)malloc(sizeof(struct  test));
test_function(&(p->b));

int  test_function(short *addr_b)
{
      //獲取struct test結構體空間的首地址
     struct  test *addr;
     addr =   container_of(addr_b,struct test,b);
}
```

展開container_of宏,探究內部的實現:

```c
typeof (  ( (struct test   *)0 )->b ) ;                        (1)
typeof (  ( (struct test   *)0 )->b )   *__mptr =  addr_b ;    (2)
(struct test *)( (char *)__mptr  -  offsetof(struct test,b))   (3)
```

(1) 獲取成員變量b的類型 ,這里獲取的就是short 類型。這是GNU_C的擴展語法。

(2) 用獲取的變量類型,定義了一個指針變量 __mptr ,並且將成員變量 b的首地址賦值給它

(3) 這里的offsetof(struct test,b)是用來計算成員b在這個struct test 結構體的偏移。__mptr

是成員b的首地址, 現在 減去成員b在結構體里面的偏移值,算出來的是不是這個結構體的

首地址呀 。

 
### 3. 宿主結構的遍歷

我們可以根據結構體中成員變量的地址找到宿主結構的地址,並且我們可以對成員變量所建立的鏈表進行遍歷,那我們是不是也可以通過某種方法對宿主結構進行遍歷呢?   

答案肯定是可以的,內核在list.h中提供了下面的宏:

```c
/**
 * list_for_each_entry  -  iterate over list of given type
 * @pos:  the type * to use as a loop cursor.
 * @head:  the head for your list.
 * @member:  the name of the list_head within the struct.
 */
#define list_for_each_entry(pos, head, member)        \
  for (pos = list_first_entry(head, typeof(*pos), member);  \
       &pos->member != (head);          \
       pos = list_next_entry(pos, member))
```

 其中,list_first_entry 和  list_next_entry宏都定義在list.h中,分別代表:獲取第一個真正的宿主結構的地址;獲取下一個宿主結構的地址。它們的實現都是利用list_entry宏。

```c
/**
 * list_first_entry - get the first element from a list
 * @ptr:  the list head to take the element from.
 * @type:  the type of the struct this is embedded in.
 * @member:  the name of the list_head within the struct.
 *
 * Note, that list is expected to be not empty.
 */
#define list_first_entry(ptr, type, member) \
  list_entry((ptr)->next, type, member)

/**
 * list_next_entry - get the next element in list
 * @pos:  the type * to cursor
 * @member:  the name of the list_head within the struct.
 */
#define list_next_entry(pos, member) \
  list_entry((pos)->member.next, typeof(*(pos)), member)
```

最終實現了宿主結構的遍歷

```c
#define list_for_each_entry(pos, head, member)      \
  for (pos = list_first_entry(head, typeof(*pos), member);  \
       &pos->member != (head);          \
       pos = list_next_entry(pos, member))
```

首先pos定位到第一個宿主結構地址,然后循環獲取下一個宿主結構地址,如果查到宿主結構中的member成員變量(宿主結構中struct list_head定義的字段)地址為head,則退出,從而實現了宿主結構的遍歷。如果要循環對宿主結構中的其它成員變量進行操作,這個遍歷操作就顯得特別有意義了。

我們用上面的 nod結構舉個例子:

```c
struct my_list *pos_ptr = NULL ;
list_for_each_entry (pos_ptr, &myhead, list )
{
         printk ("val =  %d\n" , pos_ptr->val);
}
```



# 實例1 一個簡單的鏈表的實現

為方便起見,本例把內核的list.h文件單獨拷貝出來,這樣就可以獨立於內核來編譯測試。

 
### 功能描述:

本例比較簡單,僅僅實現了單鏈表節點的創建、刪除、遍歷。

 

```c
#include "list.h"
#include <stdio.h>
#include <string.h>

#define MAX_NAME_LEN 32
#define MAX_ID_LEN 10

struct list_head myhead;

#define I2C_TYPE 1
#define SPI_TYPE 2

char *dev_name[]={
  "none",
  "I2C",
  "SPI"
};

struct mylist
{
    int type;
    char name[MAX_NAME_LEN];
  struct list_head list;  
};

void display_list(struct list_head *list_head)
{
  int i=0;
  struct list_head *p;
  struct mylist *entry;
  printf("-------list---------\n");
  list_for_each(p,list_head)
  {
    printf("node[%d]\n",i++);
    entry=list_entry(p,struct mylist,list);
    printf("\ttype: %s\n",dev_name[entry->type]);
    printf("\tname: %s\n",entry->name);
  }
  printf("-------end----------\n");
}

int main(void)
{

  struct mylist node1;
  struct mylist node2;

  INIT_LIST_HEAD(&myhead);

  node1.type = I2C_TYPE;
  strcpy(node1.name,"yikoulinux");

  node2.type = I2C_TYPE;
  strcpy(node2.name,"yikoupeng");

  list_add(&node1.list,&myhead);
  list_add(&node2.list,&myhead);

  display_list(&myhead);

  list_del(&node1.list);

  display_list(&myhead);
  return 0;
}
```

運行結果
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3STZBTmJlaWJYS2RiWmRGaWN1aWFHTDVFeDc0UlpPeGljSmlhMzlRR0NyMVp5aWJUdEtoc2xMR21NeVFnLzY0MA?x-oss-process=image/format,png#pic_center)

 

 
# 實例2  如何在一個鏈表上管理不同類型的節點

 
## 功能描述:

本實例主要實現在同一個鏈表上管理兩個不同類型的節點,實現增刪改查的操作。
## 結構體定義

一個鏈表要想區分節點的不同類型,那么節點中必須要有信息能夠區分該節點類型,為了方便節點擴展,我們參考Linux內核,定義一個統一類型的結構體:

```c
struct device
{
    int type;
    char name[MAX_NAME_LEN];
    struct list_head list;
};
```


其中成員type表示該節點的類型:

```c
#defineI2C_TYPE 1
#define SPI_TYPE 2
```

有了該結構體,我們要定義其他類型的結構體只需要包含該結構體即可,這個思想有點像面向對象語言的基類,后續派生出新的屬性叫子類,說到這,一口君又忍不住想挖個坑,寫一篇如何用C語言實現面向對象思想的繼承、多態、interface。

 

下面我們定義2種類型的結構體:
i2c這種類型設備的專用結構體:

```c
struct i2c_node
{
  int data;
  unsigned int reg;
  struct device dev;
};
```

spi這種類型設備的專用結構體:

```c
struct spi_node
{  
  unsigned int reg;
  struct device dev;
};
```

我特意讓兩個結構體大小類型不一致。

 
# 結構類型


鏈表頭結點定義

```c
structlist_head device_list;
```

根據之前我們講解的思想,這個鏈表鏈接起來后,應該是以下這種結構:

![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3bkN1VndLcVdJVzFVZWY4ZU5Pd2lhWXhmOGV1NjdKbndsYlc2OGRlTXl4dldTZVBDbGFEWmhwZy82NDA?x-oss-process=image/format,png#pic_center)

 
## 節點的插入

我們定義的節點要插入鏈表仍然是要依賴list_add(),既然我們定義了struct device這個結構體,那么我們完全可以參考linux內核,針對不同的節點封裝函數,要注冊到這個鏈表只需要調用該函數即可。

實現如下:

設備i2c的注冊函數如下:

```c
void i2c_register_device(struct device*dev)
{
  dev.type = I2C_TYPE;
  strcpy(dev.name,"yikoulinux");
  list_add(&dev->list,&device_list);  
}
```

設備spi的注冊函數如下:

```c
void spi_register_device(struct device*dev)
{
  dev.type = SPI_TYPE;
  strcpy(dev.name,"yikoupeng");
  list_add(&dev->list,&device_list);  
}
```


  我們可以看到注冊函數功能是填充了struct device 的type和name成員,然后再調用list_add()注冊到鏈表中。這個思想很重要,因為Linux內核中許許多多的設備節點也是這樣添加到其他的鏈表中的。要想讓自己的C語言編程能力得到質的提升,一定要多讀內核代碼,即使看不懂也要堅持看,古人有雲:代碼讀百遍其義自見。

 
## 節點的刪除

同理,節點的刪除,我們也統一封裝成函數,同樣只傳遞參數device即可:

```c
void i2c_unregister_device(struct device *device)
{
//  struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);
  list_del(&device->list);
}
void spi_unregister_device(struct device *device)
{
//  struct spi_node *spi_device=container_of(dev, struct spi_node, dev);
  list_del(&device->list);
}
```


在函數中,可以用container_of提取出了設備節點的首地址,實際使用中可以根據設備的不同釋放不同的資源。

 
## 宿主結構的遍歷

節點的遍歷,在這里我們通過設備鏈表device_list開始遍歷,假設該節點名是node,通過list_for_each()可以得到node->dev->list的地址,然后利用container_of 可以得到node->dev、node的地址。

```c
void display_list(struct list_head *list_head)
{
  int i=0;
  struct list_head *p;
  struct device *entry;

  printf("-------list---------\n");
  list_for_each(p,list_head)
  {
    printf("node[%d]\n",i++);
    entry=list_entry(p,struct device,list);

    switch(entry->type)
    {
      case I2C_TYPE:
                           display_i2c_device(entry);
        break;
      case SPI_TYPE:
        display_spi_device(entry);
        break;
      default:
        printf("unknown device type!\n");
        break;
    }
    display_device(entry);
  }
  printf("-------end----------\n");
}
```

由以上代碼可知,利用內核鏈表的統一接口,找個每一個節點的list成員,然后再利用container_of 得到我們定義的標准結構體struct device,進而解析出節點的類型,調用對應節點顯示函數,這個地方其實還可以優化,就是我們可以在struct device中添加一個函數指針,在xxx_unregister_device()函數中可以將該函數指針直接注冊進來,那么此處代碼會更精簡高效一些。如果在做項目的過程中,寫出這種面向對象思想的代碼,那么你的地址是肯定不一樣的。讀者有興趣可以自己嘗試一下。

```c
void display_i2c_device(struct device *device)
{
  struct i2c_node *i2c_device=container_of(device, struct i2c_node, dev);
  printf("\t  i2c_device->data: %d\n",i2c_device->data);
  printf("\t  i2c_device->reg: %#x\n",i2c_device->reg);
}
```


```c
void display_spi_device(struct device *device)
{
  struct spi_node *spi_device=container_of(device, struct spi_node, dev);
  printf("\t  spi_device->reg: %#x\n",spi_device->reg);
}
```

上述代碼提取出來宿主節點的信息。

 
## 實例代碼

 

```c
#include "list.h"
#include <stdio.h>
#include <string.h>

#define MAX_NAME_LEN 32
#define MAX_ID_LEN 10

struct list_head device_list;

#define I2C_TYPE 1
#define SPI_TYPE 2

char *dev_name[]={
  "none",
  "I2C",
  "SPI"
};

struct device
{
  int type;
  char name[MAX_NAME_LEN];
  struct list_head list;
};

struct i2c_node
{
  int data;
  unsigned int reg;
  struct device dev;
};
struct spi_node
{  
  unsigned int reg;
  struct device dev;
};
void display_i2c_device(struct device *device)
{
  struct i2c_node *i2c_device=container_of(device, struct i2c_node, dev);

  printf("\t  i2c_device->data: %d\n",i2c_device->data);
  printf("\t  i2c_device->reg: %#x\n",i2c_device->reg);
}
void display_spi_device(struct device *device)
{
  struct spi_node *spi_device=container_of(device, struct spi_node, dev);

  printf("\t  spi_device->reg: %#x\n",spi_device->reg);
}
void display_device(struct device *device)
{
    printf("\t  dev.type: %d\n",device->type);
    printf("\t  dev.type: %s\n",dev_name[device->type]);
    printf("\t  dev.name: %s\n",device->name);
}
void display_list(struct list_head *list_head)
{
  int i=0;
  struct list_head *p;
  struct device *entry;

  printf("-------list---------\n");
  list_for_each(p,list_head)
  {
    printf("node[%d]\n",i++);
    entry=list_entry(p,struct device,list);

    switch(entry->type)
    {
      case I2C_TYPE:
        display_i2c_device(entry);
        break;
      case SPI_TYPE:
        display_spi_device(entry);
        break;
      default:
        printf("unknown device type!\n");
        break;
    }
    display_device(entry);
  }
  printf("-------end----------\n");
}
void i2c_register_device(struct device*dev)
{
  struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);

  i2c_device->dev.type = I2C_TYPE;
  strcpy(i2c_device->dev.name,"yikoulinux");

  list_add(&dev->list,&device_list);  
}
void spi_register_device(struct device*dev)
{
  struct spi_node *spi_device=container_of(dev, struct spi_node, dev);

  spi_device->dev.type = SPI_TYPE;
  strcpy(spi_device->dev.name,"yikoupeng");

  list_add(&dev->list,&device_list);  
}
void i2c_unregister_device(struct device *device)
{
  struct i2c_node *i2c_device=container_of(dev, struct i2c_node, dev);

  list_del(&device->list);
}
void spi_unregister_device(struct device *device)
{
  struct spi_node *spi_device=container_of(dev, struct spi_node, dev);

  list_del(&device->list);
}
int main(void)
{

  struct i2c_node dev1;
  struct spi_node dev2;

  INIT_LIST_HEAD(&device_list);
  dev1.data = 1;
  dev1.reg = 0x40009000;
  i2c_register_device(&dev1.dev);
  dev2.reg  = 0x40008000;
  spi_register_device(&dev2.dev);  
  display_list(&device_list);
  unregister_device(&dev1.dev);
  display_list(&device_list);  
  return 0;
}
```

代碼主要功能:

    117-118          :定義兩個不同類型的節點dev1,dev2;
    120                 :初始化設備鏈表;
    121-122、124:初始化節點數據;
    123/125          :向鏈表device_list注冊這兩個節點;
    126                :顯示該鏈表;
    127                :刪除節點dev1;
    128                 :顯示該鏈表。
 

程序運行截圖
![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3TlpKZFlPNDJ5YXBVcjB2QVZJYmt1OXhvaWNwTjNNSWliaWEyRVJjUDhQNUU5TzFCQ3N0WklNeE93LzY0MA?x-oss-process=image/format,png#pic_center)


讀者可以試試如何管理更多類型的節點。


 
# 實例3  實現節點在兩個鏈表上自由移動

 
## 功能描述:

初始化兩個鏈表,實現兩個鏈表上節點的插入和移動。每個節點維護大量的臨時內存數據。
 
## 節點創建

節點結構體創建如下:

```c
struct mylist{
  int number;
  char type;
    char *pmem;  //內存存放地址,需要malloc
  struct list_head list;
};
```

需要注意成員pmem,因為要維護大量的內存,我們最好不要直定義個很大的數組,因為定義的變量位於棧中,而一般的系統給棧的空間是有限的,如果定義的變量占用空間太大,會導致棧溢出,一口君曾經就遇到過這個bug。
 
## 鏈表定義和初始化

鏈表定義如下:

```c
structlist_head active_head;
struct list_head free_head;
```

初始化

```c
INIT_LIST_HEAD(&free_head);
INIT_LIST_HEAD(&active_head);
```

這兩個鏈表如下:

![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3amJSaWN0UmNQSkRuaWJmOHA4WVBkMmF2UU1oWUljRzVrbDdTbzhCaElLV212bERYaG1YRndYaHcvNjQw?x-oss-process=image/format,png#pic_center)

關於節點,因為該實例是從實際項目中剝離出來,節點啟示是起到一個緩沖去的作用,數量不是無限的,所以在此我們默認最多10個節點。

我們不再動態創建節點,而是先全局創建指針數組,存放這10個節點的地址,然后將這10個節點插入到對應的隊列中。

數組定義:

```c
structmylist*list_array[BUFFER_NUM];
```

 這個數組只用於存放指針,所以定義之后實際情況如下:

![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3WU81bGFRUkZTUDhLZ0R2UFdZeUR6R0ROUlZpY2ljOTlLaWJpY0pzTm1FV1RSNUZTZjllNDJNR0xzZy82NDA?x-oss-process=image/format,png#pic_center)



初始化這個數組對應的節點:

```c
static ssize_t buffer_ring_init()
{
  int i=0;
  for(i=0;i<BUFFER_NUM;i++){
    list_array[i]=malloc(sizeof(struct mylist));
    INIT_LIST_HEAD(&list_array[i]->list);
    list_array[i]->pmem=kzalloc(DATA_BUFFER_SIZE,GFP_KERNEL);
  }
  return 0;
}
```

5:為下標為i的節點分配實際大小為sizeof(structmylist)的內存
6:初始化該節點的鏈表
7:為pmem成員從堆中分配一塊內存
 

 初始化完畢,鏈表實際情況如下:

## 節點插入


```c
static ssize_t insert_free_list_all()
{
  int i=0;

  for(i=0;i<BUFFER_NUM;i++){
    list_add(&list_array[i]->list,&free_head);
  }
  return 0;
}
```


8:用頭插法將所有節點插入到free_head鏈表中

所有節點全部插入free鏈表后,結構圖如下:

![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3elB3ejEzSTJZSzVnQWhJeGp2SHg2TVF2ZGxVSXpONlZXOEZsTFRIU0IwZjBvN1dUNHNVaWJMUS82NDA?x-oss-process=image/format,png#pic_center)


 

 
遍歷鏈表

雖然可以通過數組遍歷鏈表,但是實際在操作過程中,在鏈表中各個節點的位置是錯亂的。所以最好從借助list節點來查找各個節點。

```c
show_list(&free_head);
show_list(&active_head);
```

代碼實現如下:

```c
void show_list(struct list_head *list_head)
{
  int i=0;
  struct mylist*entry,*tmp;
  //判斷節點是否為空
  if(list_empty(list_head)==true)
  {
    return;
  }
  list_for_each_entry_safe(entry,tmp,list_head,list)
  {
    printf("[%d]=%d\t",i++,entry->number);
    if(i%4==0)
    {
      printf("\n");
    }
  }  
}
```


## 節點移動

 

將節點從active_head鏈表移動到free_head鏈表,有點像生產者消費者模型中的消費者,吃掉資源后,就要把這個節點放置到空閑鏈表,讓生產者能夠繼續生產數據,所以這兩個函數我起名eat、spit,意為吃掉和吐,希望你們不要覺得很怪異。

```c
int eat_node()
{
  struct mylist*entry=NULL;

  if(list_empty(&active_head)==true)
  {
    printf("list active_head is empty!-----------\n");
  }
  entry=list_first_entry(&active_head,struct mylist,list);
  printf("\t eat node=%d\n",entry->number);
  list_move_tail(&entry->list,&free_head);
}
```


節點移動的思路是:

1. 利用list_empty判斷該鏈表是否為空
2. 利用list_first_entry從active_head鏈表中查找到一個節點,並用指針entry指向該節點
3. 利用list_move_tail將該節點移入到free_head鏈表,注意此處不能用list_add,因為這個節點我要從原鏈表把他刪除掉,然后插入到新鏈表。

 

將節點從free_head鏈表移動到active_head鏈表。

```c
spit_node()
{
  struct mylist*entry=NULL;

  if(list_empty(&free_head)==true)
  {
    printf("list free_head is empty!-----------\n");
  }
  entry=list_first_entry(&free_head,struct mylist,list);
  printf("\t spit node=%d\n",entry->number);
  list_move_tail(&entry->list,&active_head);
}
```

大部分功能講解完了,下面我們貼下完整代碼。

 
代碼實例

 

```c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <byteswap.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include "list.h"     //  linux-3.14/scripts/kconfig/list.h

#undef NULL
#define NULL ((void *)0)

enum {
  false  = 0,
  true  = 1
};

#define DATA_TYPE 0x14
#define SIG_TYPE 0x15

struct mylist{
  int number;
  char type;
  char *pmem;
  struct list_head list;
};
#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n",__LINE_,__FILE__,errno,strerror(errno));exit(1);}while(0)
struct list_head active_head;
struct list_head free_head;
#define BUFFER_NUM 10
#define DATA_BUFFER_SIZE 512
struct mylist*list_array[BUFFER_NUM];


int born_number(int number)
{
  struct mylist *entry=NULL;

  if(list_empty(&free_head)==true)
  {
    printf("list free_head is empty!----------------\n");
  }
  entry = list_first_entry(&free_head,struct mylist,list);
  entry->type = DATA_TYPE;
  entry->number=number;
  list_move_tail(&entry->list,&active_head);  
}

int eat_node()
{
  struct mylist*entry=NULL;

  if(list_empty(&active_head)==true)
  {
    printf("list active_head is empty!-----------\n");
  }
  entry=list_first_entry(&active_head,struct mylist,list);
  printf("\t eat node=%d\n",entry->number);
  list_move_tail(&entry->list,&free_head);
}
spit_node()
{
  struct mylist*entry=NULL;

  if(list_empty(&free_head)==true)
  {
    printf("list free_head is empty!-----------\n");
  }
  entry=list_first_entry(&free_head,struct mylist,list);
  printf("\t spit node=%d\n",entry->number);
  list_move_tail(&entry->list,&active_head);
}

void show_list(struct list_head *list_head)
{
  int i=0;
  struct mylist*entry,*tmp;

  if(list_empty(list_head)==true)
  {
    return;
  }
  list_for_each_entry_safe(entry,tmp,list_head,list)
  {
    printf("[%d]=%d\t",i++,entry->number);
    if(i%4==0)
    {
      printf("\n");
    }
  }  
}
int list_num(struct list_head *list_head)
{
  int i=0;
  struct mylist *entry,*tmp;
//  printf("----------show free list-------------\n");
  list_for_each_entry_safe(entry,tmp,list_head,list)
  {
    i++;
  }
  return i;
}
static ssize_t buffer_ring_init()
{
  int i=0;

  for(i=0;i<BUFFER_NUM;i++){
    list_array[i]=malloc(sizeof(struct mylist));
    INIT_LIST_HEAD(&list_array[i]->list);
    list_array[i]->pmem=kzalloc(DATA_BUFFER_SIZE,GFP_KERNEL);
    list_add_tail(&list_array[i]->list,&free_head);
  }
  return 0;
}
static ssize_t insert_free_list_all()
{
  int i=0;

  for(i=0;i<BUFFER_NUM;i++){
    list_add_tail(&list_array[i]->list,&free_head);
  }
  return 0;
}
static ssize_t buffer_ring_free()
{
  int buffer_count=0;
  struct mylist*entry=NULL;
  for(;buffer_count<BUFFER_NUM;buffer_count++)
  {
    free(list_array[buffer_count]->pmem);
    free(list_array[buffer_count]);
  }
  return 0;
}

int main(int argc,char**argv)
{
  INIT_LIST_HEAD(&free_head);
  INIT_LIST_HEAD(&active_head);
  buffer_ring_init();
  insert_free_list_all();
  born_number(1);
  born_number(2);
  born_number(3);
  born_number(4);
  born_number(5);
  born_number(6);
  born_number(7);
  born_number(8);
  born_number(9);
  born_number(10);

  printf("\n----------active list[%d]------------\n",list_num(&active_head));
  show_list(&active_head);
  printf("\n--------------end-----------------\n");

  printf("\n----------free list[%d]------------\n",list_num(&free_head));  
  show_list(&free_head);
  printf("\n--------------end-----------------\n");

  printf("\n\n    active list----------> free list \n");

  eat_node();
  eat_node();
  eat_node();

  printf("\n----------active list[%d]------------\n",list_num(&active_head));
  show_list(&active_head);
  printf("\n--------------end-----------------\n");

  printf("\n----------free list[%d]------------\n",list_num(&free_head));  
  show_list(&free_head);
  printf("\n--------------end-----------------\n");


  printf("\n\n    free list----------> active list \n");

  spit_node();
  spit_node();

  printf("\n----------active list[%d]------------\n",list_num(&active_head));
  show_list(&active_head);
  printf("\n--------------end-----------------\n");

  printf("\n----------free list[%d]------------\n",list_num(&free_head));  
  show_list(&free_head);
  printf("\n--------------end-----------------\n");

}
```

運行結果如下:

 ![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3V2liaWJzZlBabWNDeXdyUndkdVJtdVVoaWNTSWRWTVFMSW53a3BoREZIUkZmS2FpYk9qRm1nVXFuQS82NDA?x-oss-process=image/format,png#pic_center)![在這里插入圖片描述](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9pY1J4Y01CZUpmY2ljcEZwcGJ1d3c5VjNZVXhvN1JOMmR3NU1vR3VMYjN2WHB1OXlnVDZqVm5iN3pQQmpuOGhMV3RRZmozM3JKMVEwS3hBTGRIaWJFcnVmdy82NDA?x-oss-process=image/format,png#pic_center)



 

list_head短小精悍,讀者可以借鑒此文實現其他功能。


參考文檔:https://kernelnewbies.org/FAQ/LinkedLists

               《Understanding linux kernel》

                《Linux device drivers》

 

list.h比較長,就不在此貼出源碼,如果讀者想獲取這個文件,可以識別下面的二維碼填加一口君好友,索取該文件,一口君這還有大量的Linux學習資料。









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM