Linux內核的Container_of機制

在內核的原碼文件 kernel.h文件中,定義了一個宏container_of,如下:

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({			\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
	(type *)( (char *)__mptr - offsetof(type,member) );})

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)  //這個宏不是在kernel.h文件中定義的。


container_of 宏的作用只有一個:根據結構的成員來獲取包含這個成員的結構實例指針。宏中的參數爲:

ptr:指向成員的指針。

type:需要返回的結構實例類型。

member:成員在結構實例內部的名稱,如果爲數組,需要指定下標。


下面分析一下這個宏,舉個例子:

假設下面的這個結構:

struct pid
{
	atomic_t count;
	/* lists of tasks that use this pid */
	struct hlist_head tasks[PIDTYPE_MAX];
	struct rcu_head rcu;
	int level;
	struct upid numbers[4];
};
最後一個本來不是4,而是1,我爲了便於理解,將其改成4。

我們的需求是:根據結構體內的struct upid number[2]來獲取這個結構實例的指針,假設已經知道struct upid number[2]的指針是pnr,如下定義:

按照這個宏的定義目標,我們可以這麼實現:

struct upid *pnr;
struct pid *_pid = container_of(pnr, struct pid,numbers[ns->level]); //根據struct upid numbers[ns->level]來返回struct pid的實例指針。

offsetof宏:先將空指針0轉換爲一個指向struct pid的指針,然後獲取成員的地址,因爲是從0開始的,所以這個地址就是成員相對於struct pid結構的偏移量。

因爲內存的使用是往上增長的,所以成員自己的地址減去成員在結構中的偏移量就是結構實例的地址了。

這個宏是內核的一個使用技巧,很多地方都是這樣根據成員的地址然後找到結構實例的地址。

發佈了65 篇原創文章 · 獲贊 27 · 訪問量 58萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章