在Linux内核源码中,经常要对链表进行操作,其中一个很重要的宏是list_for_each_entry: 意思大体如下: 假设只有两个结点,则第一个member代表head, list_for_each_entry的作用就是循环遍历每一个pos中的member子项。 图1: pos: pos: ___________ ____________ | | | | | | | | | ........... | | ................ | | | | | | | | | | member: | _________|__> member | | { | | | { | | *prev; | | | *prev; | | *next;--|---------- | *next;------------- | } | | } | | |—^———— | |____________| | | | | | |_____________________________________________| 宏list_for_each_entry: list_entry((head)->next, typeof(*pos), member)返回(head)->next物理指针所处位置向前减去offsetof()个字节数据之后, 其父变量pos的物理地址,父变量的类型在编译时由typeof(*pos)自动返回. 所以list_for_each_entry遍历head下面挂接的类型为typeof(*pos)的childs结构体们,当然每个child结构体包含struct list_head node之类相似的双向链表list_head类型项,就这样通过循环pos将依次指向双向链表上的各个child.(member就是child类型中被定义的变量名) 其中用到了函数list_entry(): 这个函数的作用在图1中表示就是可以通过已知的指向member子项的指针,获得整个结构体的指针(地址) 和函数prefetch: 其中用到了builtin_prefetch: prefetch的含义是告诉cpu那些元素有可能马上就要用到,告诉cpu预取一下,这样可以提高速度 其中用到了函数container_of(): 下面这个链接讲container_of的作用,很详细了: http://blog.chinaunix.net/u1/58968/showart_461749.html 再附一个很好的测试container_of作用的链接: http://hi.baidu.com/xiquanlian/blog/item/a070d658642ea482810a18e3.html 其中又用到了offsetof()函数: lxr上找到的源码: 转一篇网上对它的分析: 原文链接在这: http://cutebunny.blog.51cto.com/301216/67517 offsetof(TYPE, MEMBER) 该宏在Linux内核代码(版本2.6.22)中定义如下: #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER); 分析: (TYPE *)0,将 0 强制转换为 TYPE 型指针,记 p = (TYPE *)0,p是指向TYPE的指针,它的值是0。那么 p->MEMBER 就是 MEMBER 这个元素了,而&(p->MEMBER)就是MENBER的地址,而基地址为0,这样就巧妙的转化为了TYPE中的偏移量。再把结果强制转 换为size_t型的就OK了,size_t其实也就是int。 typedef __kernel_size_t size_t; typedef unsigned int __kernel_size_t; 可见,该宏的作用就是求出MEMBER在TYPE中的偏移量。 |
linux内核学习笔记之——list_for_each_entry
最新推荐文章于 2023-02-08 18:11:51 发布