linux device driver container_of理解

来源:互联网 发布:淘宝卖家评论回复 编辑:程序博客网 时间:2024/06/04 06:20

http://blog.csdn.net/yinkaizhong/article/details/4093795

这个博客写的挺详细,再写下自己总结。

inode结构中包含  struct cdev *i_cdev

struct cdev是表示字符设备的内核的内部结构。当inode指向一个字符设备文件时,该字段包含了指向struct cdev 结构的指针

对于某个有一个结构体来表示,例如在

scull内部,通过 struct scull_dev来表示每个设备。在该结构体中包含 struct cdev  cdev

inode中的 i_cdev指针即指向scull结构体中的cdev,

现在已知inode指针,要获得scull_dev结构的指针或者地址就要用到container_of宏来实现。

在<linux/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) );})

 

这个宏首先有个大括号{},里面有两个语句。当替换到程序中,是两行代码。

我自己刚开始,一直还在纳闷,这个分号怎么理解,基础不够扎实。剩下的就容易理解了。

关于offsetof见stddef.h中:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
TYPE是某struct的类型

0是一个假想TYPE类型struct,

MEMBER是该struct中的一个成员.

由于该struct的基地址为0, MEMBER的地址就是该成员相对与struct头地址的偏移量.
关于typeof,这是gcc的C语言扩展保留字,用于声明变量类型.
const typeof( ((type *)0->member ) *__mptr = (ptr);意思是声明一个与member同一个类型的指针常量 *__mptr,并初始化为ptr.
(type *)( (char *)__mptr - offsetof(type,member) );意思是__mptr的地址减去member在该struct中的偏移量得到的地址, 再转换成type型指针. 该指针就是member的入口地址了.