寒小咸 发表于 2016-9-29 14:43:34

Linux设备驱动模型-Kobject

本帖最后由 寒小咸 于 2016-9-29 14:50 编辑

概述
Kobject是linux设备驱动模型的基础,也是设备模型中抽象的一部分。如果想了解设备驱动模型就需要明白Kobject的构成或原理。linux内核为了兼容各种形形色色的设备,就需要对各种设备的共性进行抽象,抽象出一个基类,其余的设备只需要继承此基类就可以了。而此基类就是kobject,但是C语言没有面向对象语法,这时候就需要将此基类(Kobject)嵌入到具体的结构体中,从而就可以访问控制此设备的操作。通常驱动程序员很少使用到kobject结构及其相关接口,而是使用封装之后的更高层的接口函数。

Kobject结构体
struct kobject {
        const char                *name;
        struct list_head        entry;
        struct kobject                *parent;
        struct kset                *kset;
        struct kobj_type        *ktype;
        struct kernfs_node        *sd;
        struct kref                kref;
#ifdef CONFIG_DEBUG_KOBJECT_RELEASE
        struct delayed_work        release;
#endif
        unsigned int state_initialized:1;
        unsigned int state_in_sysfs:1;
        unsigned int state_add_uevent_sent:1;
        unsigned int state_remove_uevent_sent:1;
        unsigned int uevent_suppress:1;
};
name:   用来表示内核对象的名称,如果该内核对象加入到系统,那么它的name就会出现在sys目录下。
entry:    用来将一系列的内核对象kobject连接成链表
parent:用来指向该内核对象的上层节点,从而可以实现内核对象的层次化结构
kset:      用来执行内核对象所属的kset。kset对象用来容纳一系列同类型的kobject
ktype:    用来定义该内核对象的sys文件系统的相关操作函数和属性。
sd:         用来表示该内核对象在sys文件系统中的目录项实例
kref:       其核心是原子操作变量,用来表示该内核对象的引用计数。
state_initialized: 用来表示该内核对象的初始化状态,1表示已经初始化,0表示未初始化。
state_in_sysfs:   用来表示该内核对象是否在sys中已经存在。
state_add_uevent_sent: 用来表示该内核对象是否向用户空间发送了ADD uevent事件
state_remove_uevent_sent:用来表示该内核对象是否向用户空间发送了Remove uevent事件
uevent_suppress: 用来表示该内核对象状态发生改变时,时候向用户空间发送uevent事件,1表示不发送。

kobject数据结构通常的用法就是嵌入到某一个对象的数据结构中,比如struct device结构
struct device {
        struct device                *parent;

        struct device_private        *p;

        struct kobject kobj;
        const char                *init_name; /* initial name of the device */
        const struct device_type *type;

Kobject相关操作函数
kobject相关的操作函数一般驱动程序员是不会直接操作的。
1.kobject_init
void kobject_init(struct kobject *kobj, struct kobj_type *ktype)
{
        char *err_str;

        if (!kobj) {                                       //合法性检测
                err_str = "invalid kobject pointer!";
                goto error;
        }
        if (!ktype) {                                       //kobject结构必须设置相应的属性
                err_str = "must have a ktype to be initialized properly!\n";
                goto error;
        }
        if (kobj->state_initialized) {                      //如果已经初始化,在打印log
                /* do not error out as sometimes we can recover */
                printk(KERN_ERR "kobject (%p): tried to init an initialized "
                     "object, something is seriously wrong.\n", kobj);
                dump_stack();
        }

        kobject_init_internal(kobj);
        kobj->ktype = ktype;                                       
        return;

error:
        printk(KERN_ERR "kobject (%p): %s\n", kobj, err_str);
        dump_stack();
}
除了ktype成员外,真正的初始化在kobject_init_internal函数中实现
static void kobject_init_internal(struct kobject *kobj)
{
        if (!kobj)
                return;
        kref_init(&kobj->kref);                         //原子变量初始化
        INIT_LIST_HEAD(&kobj->entry);                   //初始化链表
        kobj->state_in_sysfs = 0;                     //没有出现在sys目录中
        kobj->state_add_uevent_sent = 0;               
        kobj->state_remove_uevent_sent = 0;
        kobj->state_initialized = 1;                  //已经初始化
}

2.kobject_set_name: 用于设置kobject中的name成员
int kobject_set_name(struct kobject *kobj, const char *fmt, ...)
{
        va_list vargs;
        int retval;

        va_start(vargs, fmt);
        retval = kobject_set_name_vargs(kobj, fmt, vargs);
        va_end(vargs);

        return retval;
}
如果kobject已经被加入到系统当中,就必须使用kobject_rename函数
int kobject_set_name_vargs(struct kobject *kobj, const char *fmt,
                                  va_list vargs)
{
        const char *old_name = kobj->name;
        char *s;

        if (kobj->name && !fmt)                  //名字存在返回
                return 0;

        kobj->name = kvasprintf(GFP_KERNEL, fmt, vargs);
        if (!kobj->name) {
                kobj->name = old_name;
                return -ENOMEM;
        }

        /* ewww... some of these buggers have '/' in the name ... */
        while ((s = strchr(kobj->name, '/')))   //除掉name中存在“/”
                s = '!';

        kfree(old_name);
        return 0;
}

3. kobject_get(增加kobject的引用计数)
/**
* kobject_get - increment refcount for object.
* @kobj: object.
*/
struct kobject *kobject_get(struct kobject *kobj)
{
        if (kobj)
                kref_get(&kobj->kref);      //原子加1操作
        return kobj;
}

4. kobject_put(减少kobject的引用计数)
/**
* kobject_put - decrement refcount for object.
* @kobj: object.
*
* Decrement the refcount, and if 0, call kobject_cleanup().
*/
void kobject_put(struct kobject *kobj)
{
        if (kobj) {
                if (!kobj->state_initialized)             //如果没有初始化,调用put函数,打印log
                        WARN(1, KERN_WARNING "kobject: '%s' (%p): is not "
                             "initialized, yet kobject_put() is being "
                             "called.\n", kobject_name(kobj), kobj);
                kref_put(&kobj->kref, kobject_release);
        }
}

5.kobject_add(增加一个kobject到sys目录下)
int kobject_add(struct kobject *kobj, struct kobject *parent,
                const char *fmt, ...)
{
        va_list args;
        int retval;

        if (!kobj)
                return -EINVAL;

        if (!kobj->state_initialized) {       //没有初始化的kobject,返回错误
                printk(KERN_ERR "kobject '%s' (%p): tried to add an "
                     "uninitialized object, something is seriously wrong.\n",
                     kobject_name(kobj), kobj);
                dump_stack();
                return -EINVAL;
        }
        va_start(args, fmt);
        retval = kobject_add_varg(kobj, parent, fmt, args);    //核心的实现代码
        va_end(args);

        return retval;
}
static int kobject_add_varg(struct kobject *kobj, struct kobject *parent,
                          const char *fmt, va_list vargs)
{
        int retval;

        retval = kobject_set_name_vargs(kobj, fmt, vargs);         //设置kobject的name
        if (retval) {
                printk(KERN_ERR "kobject: can not set name properly!\n");
                return retval;
        }
        kobj->parent = parent;                   //设置parent成员
        return kobject_add_internal(kobj);       //调用此函数进行进一步add操作
}
static int kobject_add_internal(struct kobject *kobj)
{
        int error = 0;
        struct kobject *parent;

        if (!kobj)
                return -ENOENT;

        if (!kobj->name || !kobj->name) {                  //尝试注册一个name为空的kobject
                WARN(1, "kobject: (%p): attempted to be registered with empty "
                       "name!\n", kobj);
                return -EINVAL;
        }

        parent = kobject_get(kobj->parent);                  //kobj的parent的引用计数加1,返回parent

        /* join kset if set, use it as parent if we do not already have one */
        if (kobj->kset) {                           
                if (!parent)                              //在kset存在的前提下,如果kobj的parent节点为NULL,就将kobj的kset中的kobj设置为kobj的parent
                        parent = kobject_get(&kobj->kset->kobj);
                kobj_kset_join(kobj);                     //添加kobj到kset的list链表中
                kobj->parent = parent;                      //设置kobj的parent
        }

        pr_debug("kobject: '%s' (%p): %s: parent: '%s', set: '%s'\n",
               kobject_name(kobj), kobj, __func__,
               parent ? kobject_name(parent) : "<NULL>",
               kobj->kset ? kobject_name(&kobj->kset->kobj) : "<NULL>");

        error = create_dir(kobj);                        //在sys下创建目录
        if (error) {
                kobj_kset_leave(kobj);
                kobject_put(parent);
                kobj->parent = NULL;

                /* be noisy on error issues */
                if (error == -EEXIST)
                        WARN(1, "%s failed for %s with "
                             "-EEXIST, don't try to register things with "
                             "the same name in the same directory.\n",
                             __func__, kobject_name(kobj));
                else
                        WARN(1, "%s failed for %s (error: %d parent: %s)\n",
                             __func__, kobject_name(kobj), error,
                             parent ? kobject_name(parent) : "'none'");
        } else
                kobj->state_in_sysfs = 1;                  //设置state_in_sysfs为1,代表obj已经初始化在sys中

        return error;
}
下来大概看看create_dir的过程,也就是创建目录的过程。
static int create_dir(struct kobject *kobj)
{
        const struct kobj_ns_type_operations *ops;
        int error;

        error = sysfs_create_dir_ns(kobj, kobject_namespace(kobj));                     //为kobject创建目录
        if (error)
                return error;

        error = populate_dir(kobj);                                           //填充kobj的属性
        if (error) {
                sysfs_remove_dir(kobj);
                return error;
        }

        /*
       * @kobj->sd may be deleted by an ancestor going away.Hold an
       * extra reference so that it stays until @kobj is gone.
       */
        sysfs_get(kobj->sd);                                             //kobj->sd引用计数加1

        /*
       * If @kobj has ns_ops, its children need to be filtered based on
       * their namespace tags.Enable namespace support on @kobj->sd.
       */
        ops = kobj_child_ns_ops(kobj);                           //namespace的知识
        if (ops) {
                BUG_ON(ops->type <= KOBJ_NS_TYPE_NONE);
                BUG_ON(ops->type >= KOBJ_NS_TYPES);
                BUG_ON(!kobj_ns_type_registered(ops->type));

                sysfs_enable_ns(kobj->sd);
        }

        return 0;
}
主要是分析下sysfs_create_dir_ns函数的执行流程。
/**
* sysfs_create_dir_ns - create a directory for an object with a namespace tag
* @kobj: object we're creating directory for
* @ns: the namespace tag to use
*/
int sysfs_create_dir_ns(struct kobject *kobj, const void *ns)
{
        struct kernfs_node *parent, *kn;

        BUG_ON(!kobj);                            //如果执行到这里,kobj为NULL,就会panic

        if (kobj->parent)         
                parent = kobj->parent->sd;         //如果存在parent就在父目录下创建
        else
                parent = sysfs_root_kn;            //如果不存在parent,就在sys目录下创建

        if (!parent)
                return -ENOENT;

        kn = kernfs_create_dir_ns(parent, kobject_name(kobj),      //正真的创建函数,不是此节的重点,不再分析。
                                  S_IRWXU | S_IRUGO | S_IXUGO, kobj, ns);
        if (IS_ERR(kn)) {
                if (PTR_ERR(kn) == -EEXIST)
                        sysfs_warn_dup(parent, kobject_name(kobj));
                return PTR_ERR(kn);
        }

        kobj->sd = kn;
        return 0;
}

6.kobject_init_and_add(kobject_init函数和kobject_add函数的合并)
7.kobject_create(动态分析一个kobject)
struct kobject *kobject_create(void)
{
        struct kobject *kobj;

        kobj = kzalloc(sizeof(*kobj), GFP_KERNEL);            //分配一个kobject结构
        if (!kobj)
                return NULL;

        kobject_init(kobj, &dynamic_kobj_ktype);            //初始化kobject,kobj_type会在后面说到
        return kobj;
}

8.kobject_create_and_add(动态创建一个kobject然后注册到sys文件系统中,也就是kobject_create和kobject_add的结合体)
9.kobject_del(从sys删除对应的kobj)
void kobject_del(struct kobject *kobj)
{
        struct kernfs_node *sd;

        if (!kobj)
                return;         //如果不存在,直接返回。

        sd = kobj->sd;
        sysfs_remove_dir(kobj);    //从sys目录下删除kobj
        sysfs_put(sd);             //sd的引用技术减去1

        kobj->state_in_sysfs = 0;   //表示没有在sys中初始化
        kobj_kset_leave(kobj);      //如果存在于kset中,从kset中删除
        kobject_put(kobj->parent);//parent引用计数减1
        kobj->parent = NULL;
}

举例
在sys目录下创建一个123_test的文件夹。
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/init.h>
                                                                                                               
static struct kobject *kobj;

static int kobject_test_init(void)
{

    kobj = kobject_create_and_add("123_test", NULL);

    return 0;
}

static void kobject_test_exit(void)
{
    kobject_del(kobj);
}

module_init(kobject_test_init);
module_exit(kobject_test_exit);
MODULE_LICENSE("GPL v2");
测试结果如下:
root@test:/sys # ls -l
drwxr-xr-x root   root            2012-01-02 09:31 123_test
drwxr-xr-x root   root            2012-01-02 07:13 bcm-dhd
drwxr-xr-x root   root            2012-01-02 05:02 block
drwxr-xr-x root   root            2012-01-02 05:02 bus
drwxr-xr-x root   root            2012-01-02 05:02 class
....
接着在123_test目录下创建456_test目录,修改代码如下:
#include <linux/module.h>                                                                                    
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/init.h>

static struct kobject *kobj;
static struct kobject *ckobj;

static int kobject_test_init(void)
{

    kobj = kobject_create_and_add("123_test", NULL);
    ckobj = kobject_create_and_add("456_test", kobj);

    return 0;
}

static void kobject_test_exit(void)
{
    kobject_del(ckobj);
    kobject_del(kobj);
}

module_init(kobject_test_init);
module_exit(kobject_test_exit);
MODULE_LICENSE("GPL v2");

测试结果如下:
root@test:/sys/123_test # ls
456_test
而目前456_test目录下是不存在任何文件的,那是因为我们没有添加该obj的属性,此测试case将在下解完善。
页: [1]
查看完整版本: Linux设备驱动模型-Kobject