1、前言
Linux內核中有大量的驅動,而這些驅動往往具有類似的結構,根據面向對象的思想,可以將共同的部分提取為父類,而這個父類就是kobject,kobject結構體中包含了大量設備的必須信息,而三大類設備驅動都需要包含這個kobject結構,運用面向對象的思想來看問題,也就是繼承來自kobject,一個kobject對象往往就對應sysfs中的一個目錄,kobject是組成設備模型的基本結構,kobject需要處理的基本任務有如下:
(1)對象的引用計數
當一個內核對象被創建時,不可能知道對象的存活時間,跟蹤該對象的的生命周期的一個方法就是使用引用計數,當內核中沒有代碼持有該對象的引用時,說明該對象可以被銷毀了;
(2)sysfs表述
一個kobject對象往往對應sysfs中的一個目錄,kobject被用來與內核交互並創建它的sysfs可見表述;
(3)數據結構關聯
從整體上看,設備模型是一個友好而復雜的數據結構,通過kobject對象實現了大量的連接而構成了一個多層次的體系結構;
(4)熱拔插事件處理
當系統中的硬件被熱插拔時,在kobject子系統的控制下,將產生事件以通知用戶空間。
2、kobject以及相關結構體
Linux內核源碼中對kobject結構體的定義在include/linux/kobject.h文件中,實現在lib/kobjet.c,struct kobject結構體的定義如下所示:
struct kobject { const char *name; struct list_head entry; struct kobject *parent; struct kset *kset; struct kobj_type *ktype; struct kernfs_node *sd; /* sysfs directory entry */ 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:表示kobject對象的名字,對應sysfs下的一個目錄;
entry:在kobject中嵌入雙向鏈表list_head結構;
parent:指向當前kobject父對象的指針;
kset:表示當前kobject對象所屬的集合;
ktype:表示當前kobject對象所屬類型;
sd:用於VFS文件系統的目錄項,是設備與文件之間的橋梁,sysfs中的符號鏈接就是通過kernfs_node內的聯合體實現的;
kref:是對kobject的引用計數,當引用計數為0時,就回調之前注冊的release函數釋放該對象;
state_initialized:1:初始化的標志位,在對象被初始化時置位,用於表示對象已被初始化;
state_in_sysfs:1:表示kobject對象在sysfs中的狀態,在對應目錄中被創建則置1,否則為0;
state_add_uevent_sent:1:添加設備的uevent事件是否發送標志,添加設備時會向用戶空間發送uevent事件,請求新增設備;
state_remove_uevent_sent:1:刪除設備的uevent事件是否發送標志,刪除設備時會向用戶空間發送uevent事件,請求卸載設備。
struct kobj_type定義了kobject的類型,該結構體既有操作的函數,也有默認的公共屬性,該結構體定義如下:
struct kobj_type { void (*release)(struct kobject *kobj); const struct sysfs_ops *sysfs_ops; struct attribute **default_attrs; const struct kobj_ns_type_operations *(*child_ns_type)(struct kobject *kobj); const void *(*namespace)(struct kobject *kobj); void (*get_ownership)(struct kobject *kobj, kuid_t *uid, kgid_t *gid); };
結構體常用成員解釋:
release:函數指針,當引用計數為0時,在kobject釋放時調用;
sysfs_ops:定義了讀寫屬性文件時調用的函數;
default_attrs:定義了這類kobject默認屬性,指向attribute數組的指針。
struct sysfs_ops結構體是用於實現屬性的的函數操作集,其定義如下所示:
struct sysfs_ops { ssize_t (*show)(struct kobject *, struct attribute *, char *); ssize_t (*store)(struct kobject *, struct attribute *, const char *, size_t); };
show:函數用於讀取一個屬性到用戶空間,函數的第一個參數是要讀取的kobject指針,它對應要讀的目錄,第二個參數是要讀的屬性,第三個參數存放讀到的屬性的緩沖區,當函數調用成功后,返回實際讀取的數據長度;
store:函數用於將屬性寫入到內核,函數第一個參數是與寫相關的kobject指針,它對應要寫的目錄,第二個參數是要寫的屬性,第三個參數是要寫入的數據,第四個參數是要寫入的參數長度,這個長度不能超過PAGESIZE個字節大小,只有當擁有屬性寫權限時,才能調用store()函數。
struct attribute定義了kobject的屬性,該結構體定義如下:
struct attribute { const char *name; umode_t mode; #ifdef CONFIG_DEBUG_LOCK_ALLOC bool ignore_lockdep:1; struct lock_class_key *key; struct lock_class_key skey; #endif };
常用結構體成員解釋:
name:屬性文件的名稱,屬性文件將在kobject的sysfs目錄中顯示;
mode:屬性文件的讀寫權限。
struct kset可以看成是在kobject上的拓展,它包含了一個kobject的鏈表,可以方便地表示sysfs中目錄與子目錄的關系,該結構體定義如下:
/** * struct kset - a set of kobjects of a specific type, belonging to a specific subsystem. * * A kset defines a group of kobjects. They can be individually * different "types" but overall these kobjects all want to be grouped * together and operated on in the same manner. ksets are used to * define the attribute callbacks and other common events that happen to * a kobject. * * @list: the list of all kobjects for this kset * @list_lock: a lock for iterating over the kobjects * @kobj: the embedded kobject for this kset (recursion, isn't it fun...) * @uevent_ops: the set of uevent operations for this kset. These are * called whenever a kobject has something happen to it so that the kset * can add new environment variables, or filter out the uevents if so * desired. */ struct kset { struct list_head list; spinlock_t list_lock; struct kobject kobj; const struct kset_uevent_ops *uevent_ops; };
結構體常用成員解釋:
list:用來掛在鏈表上的結構,包含在一個kset的所有kobject構成了一個雙向循壞鏈表,list_head是這個鏈表的頭部,這個鏈表用來連接第一個和最后一個kobject對象,第一個kobject使用entry連接kset集合以及第二個kobject對象,第二個kobject對象使用entry連接第一個kobject對象和第三個kobject對象,最終形成一個kobject對象的鏈表;
list_lock:用於迭代kobjects的鎖;
kobj:歸屬於該kset的所有的kobject的共有parent,這個parent就是體現內核設備組織結構的關鍵,同時,kset的引用計數就是內嵌的kobject對象的引用計數;
uevent_ops:此kset的uevent操作函數集。
struct kobj_attribute是kobject在attribute上的拓展,添加了專門讀寫kobject_attribute屬性的函數,結構體定義如下:
struct kobj_attribute { struct attribute attr; ssize_t (*show)(struct kobject *kobj, struct kobj_attribute *attr, char *buf); ssize_t (*store)(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count); };
結構體成員解釋:
attr:kobject的公共屬性,包括名稱和讀寫權限;
show:函數指針,用於讀取屬性到用戶空間;
store:函數指針,用於用戶空間寫屬性到內核。
注意:無論是kobjec還是kset(說到底是kset內部的kobject),都提供了使用kobj_attribute的快速創建方法。
3、kobject實現操作
在Linux內核中提供了一系列kobject的實現方法,接下來,進行簡要分析:
/* * populate_dir - populate directory with attributes. * @kobj: object we're working on. * * Most subsystems have a set of default attributes that are associated * with an object that registers with them. This is a helper called during * object registration that loops through the default attributes of the * subsystem and creates attributes files for them in sysfs. */ static int populate_dir(struct kobject *kobj) { struct kobj_type *t = get_ktype(kobj); struct attribute *attr; int error = 0; int i; if (t && t->default_attrs) { for (i = 0; (attr = t->default_attrs[i]) != NULL; i++) { error = sysfs_create_file(kobj, attr);//在sysfs目錄創建屬性文件 if (error) break; } } return error; } 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));//創建sysfs目錄 if (error) return error; error = populate_dir(kobj);//在sysfs目錄中填充屬性文件 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);//引用計數加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); 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; }
上面兩個函數中,create_dir()用於在sysfs中創建kobj相應的目錄,populate_dir()創建kobj中默認屬性對應的文件,create_dir()函數就是調用populate_dir()實現的。
static int get_kobj_path_length(struct kobject *kobj) { int length = 1; struct kobject *parent = kobj; /* walk up the ancestors until we hit the one pointing to the * root. * Add 1 to strlen for leading '/' of each level. */ do { if (kobject_name(parent) == NULL) return 0; length += strlen(kobject_name(parent)) + 1; parent = parent->parent; } while (parent); return length; } static void fill_kobj_path(struct kobject *kobj, char *path, int length) { struct kobject *parent; --length; for (parent = kobj; parent; parent = parent->parent) { int cur = strlen(kobject_name(parent)); /* back up enough to print this name with '/' */ length -= cur; strncpy(path + length, kobject_name(parent), cur); *(path + --length) = '/'; } pr_debug("kobject: '%s' (%p): %s: path = '%s'\n", kobject_name(kobj), kobj, __func__, path); } /** * kobject_get_path - generate and return the path associated with a given kobj and kset pair. * * @kobj: kobject in question, with which to build the path * @gfp_mask: the allocation type used to allocate the path * * The result must be freed by the caller with kfree(). */ char *kobject_get_path(struct kobject *kobj, gfp_t gfp_mask) { char *path; int len; len = get_kobj_path_length(kobj); if (len == 0) return NULL; path = kzalloc(len, gfp_mask); if (!path) return NULL; fill_kobj_path(kobj, path, len); return path; }
在上面的三個函數中,前面兩個函數是內部函數,get_kobj_path_length()函數用於獲得kobj路徑名的長度,fill_kobj_path()函數用於將kobj路徑名填充到path緩沖區,然后將指針返回,kobject_get_path()函數就是調用這兩個函數進行實現的。
/* add the kobject to its kset's list */ static void kobj_kset_join(struct kobject *kobj) { if (!kobj->kset) return; kset_get(kobj->kset);//引用計數加1 spin_lock(&kobj->kset->list_lock); list_add_tail(&kobj->entry, &kobj->kset->list);//在鏈表尾部插入節點 spin_unlock(&kobj->kset->list_lock); } /* remove the kobject from its kset's list */ static void kobj_kset_leave(struct kobject *kobj) { if (!kobj->kset) return; spin_lock(&kobj->kset->list_lock); list_del_init(&kobj->entry);//鏈表刪除節點 spin_unlock(&kobj->kset->list_lock); kset_put(kobj->kset);//引用計數減1 }
上面兩個函數的功能是相對的,kobj_kset_join()用於將kobj加入到kobj->kset的鏈表中,kobj_kset_leave()用於將kobj從kobj->kset的鏈表中刪除。
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; kobj->state_add_uevent_sent = 0; kobj->state_remove_uevent_sent = 0; kobj->state_initialized = 1; } static int kobject_add_internal(struct kobject *kobj) { int error = 0; struct kobject *parent; if (!kobj) return -ENOENT; if (!kobj->name || !kobj->name[0]) { WARN(1, "kobject: (%p): attempted to be registered with empty " "name!\n", kobj); return -EINVAL; } parent = kobject_get(kobj->parent);//父kobject引用計數加1 /* join kset if set, use it as parent if we do not already have one */ if (kobj->kset) { if (!parent) parent = kobject_get(&kobj->kset->kobj); kobj_kset_join(kobj); kobj->parent = parent;//設置kobject的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);//在sysfs中創建目錄 if (error) { kobj_kset_leave(kobj); kobject_put(parent); kobj->parent = NULL; /* be noisy on error issues */ if (error == -EEXIST) pr_err("%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 pr_err("%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; return error; }
kobject_init_internal()函數用來初始化kobj,kobject_add_internal()函數用來將kobj加入已有的結構中去,這兩個函數有密切的聯系,在kobject結構體中有很多變量,但是重要的只有兩個,一個是kset,一個是parent,這兩個變量表示了kobject在整個體系中的位置,決不能自行決定,需要外部參與設置,kobject的創建過程分為init和add兩個階段。kobject_init_internal()把一些結構體變量進行初始化后,等外界設置了parent和kset后,再調用kobject_add_internal()把kobject添加到適當的位置,並創建相應的sysfs目錄及文件。
/** * kobject_set_name_vargs - Set the name of an kobject * @kobj: struct kobject to set the name of * @fmt: format string used to build the name * @vargs: vargs to format the string. */ int kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list vargs) { const char *s; if (kobj->name && !fmt) return 0; s = kvasprintf_const(GFP_KERNEL, fmt, vargs); if (!s) return -ENOMEM; /* * ewww... some of these buggers have '/' in the name ... If * that's the case, we need to make sure we have an actual * allocated copy to modify, since kvasprintf_const may have * returned something from .rodata. */ if (strchr(s, '/')) { char *t; t = kstrdup(s, GFP_KERNEL); kfree_const(s); if (!t) return -ENOMEM; strreplace(t, '/', '!'); s = t; } kfree_const(kobj->name); kobj->name = s; return 0; } /** * kobject_set_name - Set the name of a kobject * @kobj: struct kobject to set the name of * @fmt: format string used to build the name * * This sets the name of the kobject. If you have already added the * kobject to the system, you must call kobject_rename() in order to * change the name of the kobject. */ 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_set_name()函數的作用是設置kobj的名稱,它通過調用kobject_set_name_vargs()來實現,需要注意的時,kobject_set_name()僅限於kobject添加到體系之前使用,因為該函數只是修改了名字,並未通知到用戶空間。
/** * kobject_init - initialize a kobject structure * @kobj: pointer to the kobject to initialize * @ktype: pointer to the ktype for this kobject. * * This function will properly initialize a kobject such that it can then * be passed to the kobject_add() call. * * After this function is called, the kobject MUST be cleaned up by a call * to kobject_put(), not by a call to kfree directly to ensure that all of * the memory is cleaned up properly. */ void kobject_init(struct kobject *kobj, struct kobj_type *ktype) { char *err_str; if (!kobj) { err_str = "invalid kobject pointer!"; goto error; } if (!ktype) { err_str = "must have a ktype to be initialized properly!\n"; goto error; } if (kobj->state_initialized) { /* 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(); }
kobject_init()函數就是調用了kobject_init_internal()函數進行一些結構體變量初始化,然后又設置了ktype結構體成員,ktype的作用是管理一些默認屬性。
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); if (retval) { printk(KERN_ERR "kobject: can not set name properly!\n"); return retval; } kobj->parent = parent; return kobject_add_internal(kobj); } /** * kobject_add - the main kobject add function * @kobj: the kobject to add * @parent: pointer to the parent of the kobject. * @fmt: format to name the kobject with. * * The kobject name is set and added to the kobject hierarchy in this * function. * * If @parent is set, then the parent of the @kobj will be set to it. * If @parent is NULL, then the parent of the @kobj will be set to the * kobject associated with the kset assigned to this kobject. If no kset * is assigned to the kobject, then the kobject will be located in the * root of the sysfs tree. * * If this function returns an error, kobject_put() must be called to * properly clean up the memory associated with the object. * Under no instance should the kobject that is passed to this function * be directly freed with a call to kfree(), that can leak memory. * * Note, no "add" uevent will be created with this call, the caller should set * up all of the necessary sysfs files for the object and then call * kobject_uevent() with the UEVENT_ADD parameter to ensure that * userspace is properly notified of this kobject's creation. */ 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) { 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; }
kobject_add()函數用於將kobj添加到體系中去,但是該函數還有一個附加的功能,設置kobj的名字,parent作為參數被傳進來。
/** * 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); va_start(args, fmt); retval = kobject_add_varg(kobj, parent, fmt, args); va_end(args); return retval; }
kobject_init_and_add()其實是kobjec_init()和kobject_add()的合並,將kobject初始化后並添加到kobject的層次結構中去。
/** * kobject_rename - change the name of an object * @kobj: object in question. * @new_name: object's new name * * It is the responsibility of the caller to provide mutual * exclusion between two different calls of kobject_rename * on the same kobject and to ensure that new_name is valid and * won't conflict with other kobjects. */ int kobject_rename(struct kobject *kobj, const char *new_name) { int error = 0; const char *devpath = NULL; const char *dup_name = NULL, *name; char *devpath_string = NULL; char *envp[2]; kobj = kobject_get(kobj); if (!kobj) return -EINVAL; if (!kobj->parent) return -EINVAL; devpath = kobject_get_path(kobj, GFP_KERNEL); if (!devpath) { error = -ENOMEM; goto out; } devpath_string = kmalloc(strlen(devpath) + 15, GFP_KERNEL); if (!devpath_string) { error = -ENOMEM; goto out; } sprintf(devpath_string, "DEVPATH_OLD=%s", devpath); envp[0] = devpath_string; envp[1] = NULL; name = dup_name = kstrdup_const(new_name, GFP_KERNEL); if (!name) { error = -ENOMEM; goto out; } error = sysfs_rename_dir_ns(kobj, new_name, kobject_namespace(kobj)); if (error) goto out; /* Install the new kobject name */ dup_name = kobj->name; kobj->name = name; /* This function is mostly/only used for network interface. * Some hotplug package track interfaces by their name and * therefore want to know when the name is changed by the user. */ kobject_uevent_env(kobj, KOBJ_MOVE, envp); out: kfree_const(dup_name); kfree(devpath_string); kfree(devpath); kobject_put(kobj); return error; }
kobject_rename()函數實現的功能為,當kobj已經添加到系統后,可以使用此函數調用實現更改kobject的名字,它除了能完成kobject_set_name()的功能以外,還向用戶空間通知這一消息。
/** * kobject_move - move object to another parent * @kobj: object in question. * @new_parent: object's new parent (can be NULL) */ int kobject_move(struct kobject *kobj, struct kobject *new_parent) { int error; struct kobject *old_parent; const char *devpath = NULL; char *devpath_string = NULL; char *envp[2]; kobj = kobject_get(kobj); if (!kobj) return -EINVAL; new_parent = kobject_get(new_parent); if (!new_parent) { if (kobj->kset) new_parent = kobject_get(&kobj->kset->kobj); } /* old object path */ devpath = kobject_get_path(kobj, GFP_KERNEL); if (!devpath) { error = -ENOMEM; goto out; } devpath_string = kmalloc(strlen(devpath) + 15, GFP_KERNEL); if (!devpath_string) { error = -ENOMEM; goto out; } sprintf(devpath_string, "DEVPATH_OLD=%s", devpath); envp[0] = devpath_string; envp[1] = NULL; error = sysfs_move_dir_ns(kobj, new_parent, kobject_namespace(kobj)); if (error) goto out; old_parent = kobj->parent; kobj->parent = new_parent; new_parent = NULL; kobject_put(old_parent); kobject_uevent_env(kobj, KOBJ_MOVE, envp); out: kobject_put(new_parent); kobject_put(kobj); kfree(devpath_string); kfree(devpath); return error; }
kobjec_move()函數實現的功能是在kobj添加到系統后,調用此函數能將kobj移動到新的parent下,同時會通知用戶空間。
/** * kobject_del - unlink kobject from hierarchy. * @kobj: object. */ void kobject_del(struct kobject *kobj) { struct kernfs_node *sd; if (!kobj) return; sd = kobj->sd; sysfs_remove_dir(kobj); sysfs_put(sd); kobj->state_in_sysfs = 0; kobj_kset_leave(kobj); kobject_put(kobj->parent); kobj->parent = NULL; }
kobject_del()函數用於將kobj從系統中刪除,和kobject_add()是相對的操作。
/** * kobject_get - increment refcount for object. * @kobj: object. */ struct kobject *kobject_get(struct kobject *kobj) { if (kobj) { if (!kobj->state_initialized) WARN(1, KERN_WARNING "kobject: '%s' (%p): is not " "initialized, yet kobject_get() is being " "called.\n", kobject_name(kobj), kobj); kref_get(&kobj->kref); } return kobj; } /* * kobject_cleanup - free kobject resources. * @kobj: object to cleanup */ static void kobject_cleanup(struct kobject *kobj) { struct kobj_type *t = get_ktype(kobj); const char *name = kobj->name; pr_debug("kobject: '%s' (%p): %s, parent %p\n", kobject_name(kobj), kobj, __func__, kobj->parent); if (t && !t->release) pr_debug("kobject: '%s' (%p): does not have a release() " "function, it is broken and must be fixed.\n", kobject_name(kobj), kobj); /* send "remove" if the caller did not do it but sent "add" */ if (kobj->state_add_uevent_sent && !kobj->state_remove_uevent_sent) { pr_debug("kobject: '%s' (%p): auto cleanup 'remove' event\n", kobject_name(kobj), kobj); kobject_uevent(kobj, KOBJ_REMOVE); } /* remove from sysfs if the caller did not do it */ if (kobj->state_in_sysfs) { pr_debug("kobject: '%s' (%p): auto cleanup kobject_del\n", kobject_name(kobj), kobj); kobject_del(kobj); } if (t && t->release) { pr_debug("kobject: '%s' (%p): calling ktype release\n", kobject_name(kobj), kobj); t->release(kobj); } /* free name if we allocated it */ if (name) { pr_debug("kobject: '%s': free name\n", name); kfree_const(name); } } #ifdef CONFIG_DEBUG_KOBJECT_RELEASE static void kobject_delayed_cleanup(struct work_struct *work) { kobject_cleanup(container_of(to_delayed_work(work), struct kobject, release)); } #endif static void kobject_release(struct kref *kref) { struct kobject *kobj = container_of(kref, struct kobject, kref); #ifdef CONFIG_DEBUG_KOBJECT_RELEASE unsigned long delay = HZ + HZ * (get_random_int() & 0x3); pr_info("kobject: '%s' (%p): %s, parent %p (delayed %ld)\n", kobject_name(kobj), kobj, __func__, kobj->parent, delay); INIT_DELAYED_WORK(&kobj->release, kobject_delayed_cleanup); schedule_delayed_work(&kobj->release, delay); #else kobject_cleanup(kobj); #endif } /** * 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) 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); } }
kobject_get()和kobject_put()函數完成的是kobject的引用計數功能,kobject_put()函數在當引用計數為0時,撤銷整個kobject的存在:向用戶空間發送REMOVE信息,從sysfs中刪除相應的目錄,並調用ktype中定義的release函數,並釋放name所占用的空間。kobject_cleanup()函數用來釋放kobject創建時所分配的資源。
上述提到到API接口,基本上概括了kobject從創建到刪除,包括kobject的名字修改、位置修改以及引用計數的變動等功能。但是,kobject的創建仍然比較麻煩,因為ktype需要自己去實現,下面是Linux內核中為kobject提供的一種快速創建的方法:
首先是kobject的屬性文件的讀寫函數定義:
/* default kobject attribute operations */ static ssize_t kobj_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct kobj_attribute *kattr; ssize_t ret = -EIO; kattr = container_of(attr, struct kobj_attribute, attr); if (kattr->show) ret = kattr->show(kobj, kattr, buf); return ret; } static ssize_t kobj_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t count) { struct kobj_attribute *kattr; ssize_t ret = -EIO; kattr = container_of(attr, struct kobj_attribute, attr); if (kattr->store) ret = kattr->store(kobj, kattr, buf, count); return ret; } const struct sysfs_ops kobj_sysfs_ops = { .show = kobj_attr_show, .store = kobj_attr_store, };
然后是,kobject的釋放函數,以及kobj_type結構體變量的定義,如下:
static void dynamic_kobj_release(struct kobject *kobj) { pr_debug("kobject: (%p): %s\n", kobj, __func__); kfree(kobj); } static struct kobj_type dynamic_kobj_ktype = { .release = dynamic_kobj_release, .sysfs_ops = &kobj_sysfs_ops, };
這是Linux內核里面為kobject自身提供的一種kobj_type,名稱叫做dynamic_kobj_type,它並沒有提供默認的屬性,但是提供了release函數和訪問屬性的方法。
/** * kobject_create - create a struct kobject dynamically * * This function creates a kobject structure dynamically and sets it up * to be a "dynamic" kobject with a default release function set up. * * If the kobject was not able to be created, NULL will be returned. * The kobject structure returned from here must be cleaned up with a * call to kobject_put() and not kfree(), as kobject_init() has * already been called on this structure. */ struct kobject *kobject_create(void) { struct kobject *kobj; kobj = kzalloc(sizeof(*kobj), GFP_KERNEL); if (!kobj) return NULL; kobject_init(kobj, &dynamic_kobj_ktype); return kobj; } /** * kobject_create_and_add - create a struct kobject dynamically and register it with sysfs * * @name: the name for the kobject * @parent: the parent kobject of this kobject, if any. * * This function creates a kobject structure dynamically and registers it * with sysfs. When you are finished with this structure, call * kobject_put() and the structure will be dynamically freed when * it is no longer being used. * * If the kobject was not able to be created, NULL will be returned. */ struct kobject *kobject_create_and_add(const char *name, struct kobject *parent) { struct kobject *kobj; int retval; kobj = kobject_create(); if (!kobj) return NULL; retval = kobject_add(kobj, parent, "%s", name); if (retval) { printk(KERN_WARNING "%s: kobject_add error: %d\n", __func__, retval); kobject_put(kobj); kobj = NULL; } return kobj; }
在kobject_create()和kobject_create_add()函數中,使用了dynamic_kobj_ktype這個結構體變量,這是一種很好的偷懶方式,因為release()函數會釋放掉kobj,所以這里的kobj必須是動態創建的,這里的kobject_create()和kobject_init()相對,kobject_create_and_add()和kobject_init_and_add()相對。需要注意的是,這里創建的kobject無法嵌入到其它結構,是獨立存在的,所以用到的地方很少。
/** * kset_init - initialize a kset for use * @k: kset */ void kset_init(struct kset *k) { kobject_init_internal(&k->kobj); INIT_LIST_HEAD(&k->list); spin_lock_init(&k->list_lock); }
kset_init()函數用於將kset結構體初始化,和kobject初始化類似。
/** * kset_register - initialize and add a kset. * @k: kset. */ int kset_register(struct kset *k) { int err; if (!k) return -EINVAL; kset_init(k); err = kobject_add_internal(&k->kobj); if (err) return err; kobject_uevent(&k->kobj, KOBJ_ADD); return 0; }
kset_register()函數用來初始化並添加到kset,函數比較簡單,它負責將kset中的kobject添加到系統,並向用戶空間發布KOBJ_ADD消息,所以在調用之前,需要先設置好k->kobj.name、k->kobj.parent和k->kobj.kset這些成員。
/** * kset_unregister - remove a kset. * @k: kset. */ void kset_unregister(struct kset *k) { if (!k) return; kobject_del(&k->kobj); kobject_put(&k->kobj); }
kset_unregister()和kset_register()函數功能是相對的,用於移除kset,並減少引用計數。
/** * kset_find_obj - search for object in kset. * @kset: kset we're looking in. * @name: object's name. * * Lock kset via @kset->subsys, and iterate over @kset->list, * looking for a matching kobject. If matching object is found * take a reference and return the object. */ struct kobject *kset_find_obj(struct kset *kset, const char *name) { struct kobject *k; struct kobject *ret = NULL; spin_lock(&kset->list_lock); list_for_each_entry(k, &kset->list, entry) { if (kobject_name(k) && !strcmp(kobject_name(k), name)) { ret = kobject_get_unless_zero(k); break; } } spin_unlock(&kset->list_lock); return ret; }
kset_find_obj()函數功能為通過從kset的鏈表中尋找名為name的kobject,實現了鏈表的遍歷。
與kobject類似,kset也提供看一種kobj_type,名稱為kset_ktype,實現如下:
static void kset_release(struct kobject *kobj) { struct kset *kset = container_of(kobj, struct kset, kobj); pr_debug("kobject: '%s' (%p): %s\n", kobject_name(kobj), kobj, __func__); kfree(kset); } void kset_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid) { if (kobj->parent) kobject_get_ownership(kobj->parent, uid, gid); } static struct kobj_type kset_ktype = { .sysfs_ops = &kobj_sysfs_ops, .release = kset_release, .get_ownership = kset_get_ownership, }; /** * kset_create - create a struct kset dynamically * * @name: the name for the kset * @uevent_ops: a struct kset_uevent_ops for the kset * @parent_kobj: the parent kobject of this kset, if any. * * This function creates a kset structure dynamically. This structure can * then be registered with the system and show up in sysfs with a call to * kset_register(). When you are finished with this structure, if * kset_register() has been called, call kset_unregister() and the * structure will be dynamically freed when it is no longer being used. * * If the kset was not able to be created, NULL will be returned. */ static struct kset *kset_create(const char *name, const struct kset_uevent_ops *uevent_ops, struct kobject *parent_kobj) { struct kset *kset; int retval; kset = kzalloc(sizeof(*kset), GFP_KERNEL); if (!kset) return NULL; retval = kobject_set_name(&kset->kobj, "%s", name); if (retval) { kfree(kset); return NULL; } kset->uevent_ops = uevent_ops; kset->kobj.parent = parent_kobj; /* * The kobject of this kset will have a type of kset_ktype and belong to * no kset itself. That way we can properly free it when it is * finished being used. */ kset->kobj.ktype = &kset_ktype; kset->kobj.kset = NULL; return kset; } /** * kset_create_and_add - create a struct kset dynamically and add it to sysfs * * @name: the name for the kset * @uevent_ops: a struct kset_uevent_ops for the kset * @parent_kobj: the parent kobject of this kset, if any. * * This function creates a kset structure dynamically and registers it * with sysfs. When you are finished with this structure, call * kset_unregister() and the structure will be dynamically freed when it * is no longer being used. * * If the kset was not able to be created, NULL will be returned. */ struct kset *kset_create_and_add(const char *name, const struct kset_uevent_ops *uevent_ops, struct kobject *parent_kobj) { struct kset *kset; int error; kset = kset_create(name, uevent_ops, parent_kobj); if (!kset) return NULL; error = kset_register(kset); if (error) { kfree(kset); return NULL; } return kset; }
kset_create()和kset_create_and_add()就是使用kset_type來快速創建kset的函數,當需要在sysfs中創建單純的目錄時,可以使用這兩個函數進行創建。
static inline struct kset *to_kset(struct kobject *kobj) { return kobj ? container_of(kobj, struct kset, kobj) : NULL; } static inline struct kset *kset_get(struct kset *k) { return k ? to_kset(kobject_get(&k->kobj)) : NULL; } static inline void kset_put(struct kset *k) { kobject_put(&k->kobj); } static inline struct kobj_type *get_ktype(struct kobject *kobj) { return kobj->ktype; }
上面這些函數是在kobject.h文件里面的內聯函數,to_kset()函數通過kobj的指針獲取kset結構體的首地址,kset_get()和kset_put()為引用計數操作,get_ktype()函數用於獲取kobject的ktype類型。
4、 kobject的層次結構
內核用kobject結構將各個對象連接起來組成一個分層的結構體系,從而與模型化的子系統相匹配。kobject結構體中的parent指針成員、kset指針成員和鏈表list_head實現了kobject的層次結構,parent指針最重要的用途是在sysfs分層結構中定位對象,下圖是一個簡單的kobject、kset的分層結構圖:
5、小節
本文主要對kobject結構體以及相關的結構體以及Linux內核提供的相關API做了簡要介紹,kobject結構體和設備驅動模型和sysfs的實現密切相關,必須深刻理解。
參考:
https://blog.csdn.net/yuanmengliang/article/details/52700529
https://blog.csdn.net/qb_2008/article/details/6846779
https://www.cnblogs.com/xiaojiang1025/p/6193959.html
《LINUX設備驅動程序(第三版)》