Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

深入 Linux 內核雙向鏈表:侵入式設計與 container_of 的奧妙

要理解 Linux 內核的資料組織方式,雙向鏈表是最好的起點。它幾乎無所不在——行程排程、模組管理、檔案系統快取,處處可見它的身影。只要到 free-electrons.com 上隨便檢索,就能感受到它被使用的密度。它的定義就在 include/linux/list.h 裡。

一個「沒有資料」的鏈表節點

先看最基礎的結構,它定義在 include/linux/types.h:

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

如果你熟悉 glib 的實作,會立刻發現差異。glib 的 GList 把資料放進節點裡:

struct GList {
    gpointer data;
    GList *next;
    GList *prev;
};

一般鏈表節點都有一個指向資料的指標,但內核版本偏偏沒有。那麼資料存在哪裡?答案是:內核採用的侵入式鏈表(intrusive list)。節點本身只保存前後指標,資料並不是「放進」節點,而是「掛」在節點上——換句話說,你要管理的結構體自己內嵌一個 list_head 成員。這樣一來,鏈表就不需要知道資料的型別,通用性極高。

例如:

struct nmi_desc {
    spinlock_t lock;
    struct list_head head;
};

從 misc 驅動看 list_head 的實際用法

內核裡使用鏈表的地方多到數不完,我們挑一個好懂的例子:drivers/char/misc.c 中的雜項字元驅動框架。這個框架專門服務那些小型的、不必獨佔主設備號的硬體或虛擬裝置,它們共用同一個主號:

#define MISC_MAJOR 10

並各自分配不同的次號,在 /dev 下可以清楚看到這種「大雜燴」:

ls -l /dev | grep 10
crw------- 1 root root 10,235 Mar 21 12:01 autofs
crw-rw-rw- 1 root root 10,229 Mar 21 12:01 fuse
crw------- 1 root root 10,228 Mar 21 12:01 hpet
crw-rw----+ 1 root kvm  10,232 Mar 21 12:01 kvm
crw------- 1 root root 10,137 Mar 21 12:01 vhci

對應的結構體是 miscdevice:

struct miscdevice {
    int minor;
    const char *name;
    const struct file_operations *fops;
    struct list_head list;
    struct device *parent;
    struct device *this_device;
    const char *nodename;
    mode_t mode;
};

第四個成員 list 就是鏈表節點。原始碼開頭定義了鏈表頭:

static LIST_HEAD(misc_list);

LIST_HEAD 只是把 list_head 變數宣告與初始化合併的糖衣:

#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

#define LIST_HEAD_INIT(name) { &(name), &(name) }

注意初始化的結果:prev 與 next 都指向自己,形成一個空的環。執行期則用 INIT_LIST_HEAD 達到同樣效果:

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}

在 misc_register 中,先初始化節點,等 device_create 完成裝置建立後,再把它掛進全域鏈表:

INIT_LIST_HEAD(&misc->list);
...
list_add(&misc->list, &misc_list);

list_add 與 __list_add

list_add 本身只是轉手呼叫內部函數:

static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

三個參數的意義分別是:新節點 new、作為錨點的 head(新節點插在它後面),以及原本緊跟在 head 之後的節點 head->next。真正的 pointer 操作只有四行:

static inline void __list_add(struct list_head *new,
                              struct list_head *prev,
                              struct list_head *next)
{
    next->prev = new;
    new->next  = next;
    new->prev  = prev;
    prev->next = new;
}

也就是把原本相鄰的 prev 與 next 拆開,讓新節點插在兩者之間。由於 list_add 是「插入到 head 之後」,實際效果等同於頭插;若想要尾插,則使用 list_add_tail。

list_entry 與 container_of:如何取回真正的資料

鏈表節點裡沒有資料,那要怎麼從節點回到外層結構體?關鍵是這兩個巨集:

#define list_entry(ptr, type, member) \
    container_of(ptr, type, member)

三個參數:指向 list_head 的指標 ptr、外層結構體型別 type、以及該 list_head 成員的名字 member。使用起來像这样:

const struct miscdevice *p = list_entry(v, struct miscdevice, list);

之後就能用 p->minor、p->name 存取真正的裝置資訊。而 container_of 的實作乍看有點魔法:

#define container_of(ptr, type, member) ({ \
    const typeof(((type *)0)->member) *__mptr = (ptr); \
    (type *)((char *)__mptr - offsetof(type, member)); })

拆解一下這幾個語法。首先是那對大括號,這是 GNU C 的「陳述式運算式」擴充:編譯器會依序執行括號內所有陳述,並以最後一個運算式的值作為整體結果。例如:

#include <stdio.h>
int main() {
    int i = 0;
    printf("i = %d\n", ({ ++i; ++i; }));
    return 0;
}

輸出是 2。

再來是 typeof,顧名思義就是取出運算元的型別,讓 __mptr 的型別自動對齊成員,這一行的真正作用是型別檢查:它保證 type 裡確實有一個叫 member 的成員。

最容易被誤解的是 ((type *)0) 裡那個 0。它並不是要真的去讀位址 0,而是巧妙地以零偏移為基礎,算出成員在結構體中的位置:

#include <stdio.h>
struct s {
    int field1;
    char field2;
    char field3;
};
int main() {
    printf("%p\n", &((struct s *)0)->field3);
    return 0;
}

輸出 0x5,正是 field3 的偏移量。而 offsetof 做的就是同一件事:

#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE *)0)->MEMBER)

所以整個流程是:取得成員位址 → 減去成員偏移 → 得到結構體起始位址。這正是侵入式鏈表能「反查」資料的魔法所在。

list.h 提供的其他 API

list_add 與 list_entry 只是冰山一角,<linux/list.h> 還提供了完整的一套操作:

  • list_add、list_add_tail
  • list_del、list_replace、list_move
  • list_is_last、list_empty
  • list_cut_position、list_splice
  • list_for_each、list_for_each_entry

以及許多其他變體。其中 list_for_each_entry 尤其好用,它把 container_of 的計算藏在迭代器裡,讓你可以直接以「外層結構體」的視角遍歷整條鏈表。


原文來源:https://github.com/0xAX/linux-insides/blob/master/DataStructures/dlist.md

譯者:Ezio 校對:Mr小眼兒 本文由 LCTT 原創編譯,Linux 中國 榮譽推出

Copyright © Linux教程網 All Rights Reserved