kobject是Linux设备模型的最底层数据结构,它代表一个内核对象。
kobject结构体定义在include/linux/kobject.h文件中:
struct kobject {
const char *name; //这个内核对象的名字,在sysfs文件系统中,name将以一个目录的形式出现
struct list_head entry; //用于将该内核对象链接进其所属的kset的内核对象链表
struct kobject *parent;//代表该内核对象的父对象,用于构建内核对象的层次结构
struct kset *kset; //kset是该内核对象所属的“内核对象集合”
struct kobj_type *ktype; //ktype是该内核对象的sysfs文件系统相关的操作函数和属性。
struct kernfs_node *sd; /* sysfs directory entrysd表示该内核对象对应的sysfs目录项。 */
struct kref kref;//kref的核心数据是一个原子型变量,用于表示该内核对象的引用计数
#ifdef CONFIG_DEBUG_KOBJECT_RELEASE
struct delayed_work release;
#endif
unsigned int state_initialized:1;//表示该内核对象是否已经进行过了初始化,1表示已经初始化过了
unsigned int state_in_sysfs:1;//表示该内核对象是否已经在sysfs文件系统中建立一个入口点
unsigned int state_add_uevent_sent:1;//表示加入内核对象时是否发送uevent事件
unsigned int state_remove_uevent_sent:1;//表示删除内核对象时是否发送uevent事件
unsigned int uevent_suppress:1;//表示内核对象状态发生变化时,是否发送uevent事件
};
kobject初始化分析,从kobject_init_and_add
函数开始看,该函数完成对kobject的初始化,建立kobject的层次结构,并将kobject添加到sysfs文件系统中,该函数定义在lib/kobject.c文件中,其内容如下:
/**
* kobject_init_and_add - initialize a kobject structure and add it to the kobject hierarchy
* @kobj: pointer to the kobject to initialize
* @ktype: pointer to the ktype for this kobject.
* @parent: pointer to the parent of this kobject.
* @fmt: the name of the kobject.
*
* This function combines the call to kobject_init() and
* kobject_add(). The same type of error handling after a call to
* kobject_add() and kobject lifetime rules are the same here.
*/
int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,
struct kobject *parent, const char *fmt, ...)
{
va_list args;
int retval;
kobject_init(kobj, ktype); //对kobject进行初始化
va_start(args, fmt); //va_start用于处理可变参数
retval = kobject_add_varg(kobj, parent, fmt, args); //将kobject添加到kobject层次结构中
va_end(args);
return retval;
}
其中,kobject_init
函数,其定义如下:
/**
* kobject_init - initialize a kobject structure
* @kobj: pointer to the kobject to initialize
* @ktype: pointer to the ktype for this kobject.
*
* This