kobject.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. Everything you never wanted to know about kobjects, ksets, and ktypes
  2. Greg Kroah-Hartman <gregkh@linuxfoundation.org>
  3. Based on an original article by Jon Corbet for lwn.net written October 1,
  4. 2003 and located at http://lwn.net/Articles/51437/
  5. Last updated December 19, 2007
  6. Part of the difficulty in understanding the driver model - and the kobject
  7. abstraction upon which it is built - is that there is no obvious starting
  8. place. Dealing with kobjects requires understanding a few different types,
  9. all of which make reference to each other. In an attempt to make things
  10. easier, we'll take a multi-pass approach, starting with vague terms and
  11. adding detail as we go. To that end, here are some quick definitions of
  12. some terms we will be working with.
  13. - A kobject is an object of type struct kobject. Kobjects have a name
  14. and a reference count. A kobject also has a parent pointer (allowing
  15. objects to be arranged into hierarchies), a specific type, and,
  16. usually, a representation in the sysfs virtual filesystem.
  17. Kobjects are generally not interesting on their own; instead, they are
  18. usually embedded within some other structure which contains the stuff
  19. the code is really interested in.
  20. No structure should EVER have more than one kobject embedded within it.
  21. If it does, the reference counting for the object is sure to be messed
  22. up and incorrect, and your code will be buggy. So do not do this.
  23. - A ktype is the type of object that embeds a kobject. Every structure
  24. that embeds a kobject needs a corresponding ktype. The ktype controls
  25. what happens to the kobject when it is created and destroyed.
  26. - A kset is a group of kobjects. These kobjects can be of the same ktype
  27. or belong to different ktypes. The kset is the basic container type for
  28. collections of kobjects. Ksets contain their own kobjects, but you can
  29. safely ignore that implementation detail as the kset core code handles
  30. this kobject automatically.
  31. When you see a sysfs directory full of other directories, generally each
  32. of those directories corresponds to a kobject in the same kset.
  33. We'll look at how to create and manipulate all of these types. A bottom-up
  34. approach will be taken, so we'll go back to kobjects.
  35. Embedding kobjects
  36. It is rare for kernel code to create a standalone kobject, with one major
  37. exception explained below. Instead, kobjects are used to control access to
  38. a larger, domain-specific object. To this end, kobjects will be found
  39. embedded in other structures. If you are used to thinking of things in
  40. object-oriented terms, kobjects can be seen as a top-level, abstract class
  41. from which other classes are derived. A kobject implements a set of
  42. capabilities which are not particularly useful by themselves, but which are
  43. nice to have in other objects. The C language does not allow for the
  44. direct expression of inheritance, so other techniques - such as structure
  45. embedding - must be used.
  46. (As an aside, for those familiar with the kernel linked list implementation,
  47. this is analogous as to how "list_head" structs are rarely useful on
  48. their own, but are invariably found embedded in the larger objects of
  49. interest.)
  50. So, for example, the UIO code in drivers/uio/uio.c has a structure that
  51. defines the memory region associated with a uio device:
  52. struct uio_map {
  53. struct kobject kobj;
  54. struct uio_mem *mem;
  55. };
  56. If you have a struct uio_map structure, finding its embedded kobject is
  57. just a matter of using the kobj member. Code that works with kobjects will
  58. often have the opposite problem, however: given a struct kobject pointer,
  59. what is the pointer to the containing structure? You must avoid tricks
  60. (such as assuming that the kobject is at the beginning of the structure)
  61. and, instead, use the container_of() macro, found in <linux/kernel.h>:
  62. container_of(pointer, type, member)
  63. where:
  64. * "pointer" is the pointer to the embedded kobject,
  65. * "type" is the type of the containing structure, and
  66. * "member" is the name of the structure field to which "pointer" points.
  67. The return value from container_of() is a pointer to the corresponding
  68. container type. So, for example, a pointer "kp" to a struct kobject
  69. embedded *within* a struct uio_map could be converted to a pointer to the
  70. *containing* uio_map structure with:
  71. struct uio_map *u_map = container_of(kp, struct uio_map, kobj);
  72. For convenience, programmers often define a simple macro for "back-casting"
  73. kobject pointers to the containing type. Exactly this happens in the
  74. earlier drivers/uio/uio.c, as you can see here:
  75. struct uio_map {
  76. struct kobject kobj;
  77. struct uio_mem *mem;
  78. };
  79. #define to_map(map) container_of(map, struct uio_map, kobj)
  80. where the macro argument "map" is a pointer to the struct kobject in
  81. question. That macro is subsequently invoked with:
  82. struct uio_map *map = to_map(kobj);
  83. Initialization of kobjects
  84. Code which creates a kobject must, of course, initialize that object. Some
  85. of the internal fields are setup with a (mandatory) call to kobject_init():
  86. void kobject_init(struct kobject *kobj, struct kobj_type *ktype);
  87. The ktype is required for a kobject to be created properly, as every kobject
  88. must have an associated kobj_type. After calling kobject_init(), to
  89. register the kobject with sysfs, the function kobject_add() must be called:
  90. int kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...);
  91. This sets up the parent of the kobject and the name for the kobject
  92. properly. If the kobject is to be associated with a specific kset,
  93. kobj->kset must be assigned before calling kobject_add(). If a kset is
  94. associated with a kobject, then the parent for the kobject can be set to
  95. NULL in the call to kobject_add() and then the kobject's parent will be the
  96. kset itself.
  97. As the name of the kobject is set when it is added to the kernel, the name
  98. of the kobject should never be manipulated directly. If you must change
  99. the name of the kobject, call kobject_rename():
  100. int kobject_rename(struct kobject *kobj, const char *new_name);
  101. kobject_rename does not perform any locking or have a solid notion of
  102. what names are valid so the caller must provide their own sanity checking
  103. and serialization.
  104. There is a function called kobject_set_name() but that is legacy cruft and
  105. is being removed. If your code needs to call this function, it is
  106. incorrect and needs to be fixed.
  107. To properly access the name of the kobject, use the function
  108. kobject_name():
  109. const char *kobject_name(const struct kobject * kobj);
  110. There is a helper function to both initialize and add the kobject to the
  111. kernel at the same time, called surprisingly enough kobject_init_and_add():
  112. int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,
  113. struct kobject *parent, const char *fmt, ...);
  114. The arguments are the same as the individual kobject_init() and
  115. kobject_add() functions described above.
  116. Uevents
  117. After a kobject has been registered with the kobject core, you need to
  118. announce to the world that it has been created. This can be done with a
  119. call to kobject_uevent():
  120. int kobject_uevent(struct kobject *kobj, enum kobject_action action);
  121. Use the KOBJ_ADD action for when the kobject is first added to the kernel.
  122. This should be done only after any attributes or children of the kobject
  123. have been initialized properly, as userspace will instantly start to look
  124. for them when this call happens.
  125. When the kobject is removed from the kernel (details on how to do that are
  126. below), the uevent for KOBJ_REMOVE will be automatically created by the
  127. kobject core, so the caller does not have to worry about doing that by
  128. hand.
  129. Reference counts
  130. One of the key functions of a kobject is to serve as a reference counter
  131. for the object in which it is embedded. As long as references to the object
  132. exist, the object (and the code which supports it) must continue to exist.
  133. The low-level functions for manipulating a kobject's reference counts are:
  134. struct kobject *kobject_get(struct kobject *kobj);
  135. void kobject_put(struct kobject *kobj);
  136. A successful call to kobject_get() will increment the kobject's reference
  137. counter and return the pointer to the kobject.
  138. When a reference is released, the call to kobject_put() will decrement the
  139. reference count and, possibly, free the object. Note that kobject_init()
  140. sets the reference count to one, so the code which sets up the kobject will
  141. need to do a kobject_put() eventually to release that reference.
  142. Because kobjects are dynamic, they must not be declared statically or on
  143. the stack, but instead, always allocated dynamically. Future versions of
  144. the kernel will contain a run-time check for kobjects that are created
  145. statically and will warn the developer of this improper usage.
  146. If all that you want to use a kobject for is to provide a reference counter
  147. for your structure, please use the struct kref instead; a kobject would be
  148. overkill. For more information on how to use struct kref, please see the
  149. file Documentation/kref.txt in the Linux kernel source tree.
  150. Creating "simple" kobjects
  151. Sometimes all that a developer wants is a way to create a simple directory
  152. in the sysfs hierarchy, and not have to mess with the whole complication of
  153. ksets, show and store functions, and other details. This is the one
  154. exception where a single kobject should be created. To create such an
  155. entry, use the function:
  156. struct kobject *kobject_create_and_add(char *name, struct kobject *parent);
  157. This function will create a kobject and place it in sysfs in the location
  158. underneath the specified parent kobject. To create simple attributes
  159. associated with this kobject, use:
  160. int sysfs_create_file(struct kobject *kobj, struct attribute *attr);
  161. or
  162. int sysfs_create_group(struct kobject *kobj, struct attribute_group *grp);
  163. Both types of attributes used here, with a kobject that has been created
  164. with the kobject_create_and_add(), can be of type kobj_attribute, so no
  165. special custom attribute is needed to be created.
  166. See the example module, samples/kobject/kobject-example.c for an
  167. implementation of a simple kobject and attributes.
  168. ktypes and release methods
  169. One important thing still missing from the discussion is what happens to a
  170. kobject when its reference count reaches zero. The code which created the
  171. kobject generally does not know when that will happen; if it did, there
  172. would be little point in using a kobject in the first place. Even
  173. predictable object lifecycles become more complicated when sysfs is brought
  174. in as other portions of the kernel can get a reference on any kobject that
  175. is registered in the system.
  176. The end result is that a structure protected by a kobject cannot be freed
  177. before its reference count goes to zero. The reference count is not under
  178. the direct control of the code which created the kobject. So that code must
  179. be notified asynchronously whenever the last reference to one of its
  180. kobjects goes away.
  181. Once you registered your kobject via kobject_add(), you must never use
  182. kfree() to free it directly. The only safe way is to use kobject_put(). It
  183. is good practice to always use kobject_put() after kobject_init() to avoid
  184. errors creeping in.
  185. This notification is done through a kobject's release() method. Usually
  186. such a method has a form like:
  187. void my_object_release(struct kobject *kobj)
  188. {
  189. struct my_object *mine = container_of(kobj, struct my_object, kobj);
  190. /* Perform any additional cleanup on this object, then... */
  191. kfree(mine);
  192. }
  193. One important point cannot be overstated: every kobject must have a
  194. release() method, and the kobject must persist (in a consistent state)
  195. until that method is called. If these constraints are not met, the code is
  196. flawed. Note that the kernel will warn you if you forget to provide a
  197. release() method. Do not try to get rid of this warning by providing an
  198. "empty" release function; you will be mocked mercilessly by the kobject
  199. maintainer if you attempt this.
  200. Note, the name of the kobject is available in the release function, but it
  201. must NOT be changed within this callback. Otherwise there will be a memory
  202. leak in the kobject core, which makes people unhappy.
  203. Interestingly, the release() method is not stored in the kobject itself;
  204. instead, it is associated with the ktype. So let us introduce struct
  205. kobj_type:
  206. struct kobj_type {
  207. void (*release)(struct kobject *kobj);
  208. const struct sysfs_ops *sysfs_ops;
  209. struct attribute **default_attrs;
  210. const struct kobj_ns_type_operations *(*child_ns_type)(struct kobject *kobj);
  211. const void *(*namespace)(struct kobject *kobj);
  212. };
  213. This structure is used to describe a particular type of kobject (or, more
  214. correctly, of containing object). Every kobject needs to have an associated
  215. kobj_type structure; a pointer to that structure must be specified when you
  216. call kobject_init() or kobject_init_and_add().
  217. The release field in struct kobj_type is, of course, a pointer to the
  218. release() method for this type of kobject. The other two fields (sysfs_ops
  219. and default_attrs) control how objects of this type are represented in
  220. sysfs; they are beyond the scope of this document.
  221. The default_attrs pointer is a list of default attributes that will be
  222. automatically created for any kobject that is registered with this ktype.
  223. ksets
  224. A kset is merely a collection of kobjects that want to be associated with
  225. each other. There is no restriction that they be of the same ktype, but be
  226. very careful if they are not.
  227. A kset serves these functions:
  228. - It serves as a bag containing a group of objects. A kset can be used by
  229. the kernel to track "all block devices" or "all PCI device drivers."
  230. - A kset is also a subdirectory in sysfs, where the associated kobjects
  231. with the kset can show up. Every kset contains a kobject which can be
  232. set up to be the parent of other kobjects; the top-level directories of
  233. the sysfs hierarchy are constructed in this way.
  234. - Ksets can support the "hotplugging" of kobjects and influence how
  235. uevent events are reported to user space.
  236. In object-oriented terms, "kset" is the top-level container class; ksets
  237. contain their own kobject, but that kobject is managed by the kset code and
  238. should not be manipulated by any other user.
  239. A kset keeps its children in a standard kernel linked list. Kobjects point
  240. back to their containing kset via their kset field. In almost all cases,
  241. the kobjects belonging to a kset have that kset (or, strictly, its embedded
  242. kobject) in their parent.
  243. As a kset contains a kobject within it, it should always be dynamically
  244. created and never declared statically or on the stack. To create a new
  245. kset use:
  246. struct kset *kset_create_and_add(const char *name,
  247. struct kset_uevent_ops *u,
  248. struct kobject *parent);
  249. When you are finished with the kset, call:
  250. void kset_unregister(struct kset *kset);
  251. to destroy it. This removes the kset from sysfs and decrements its reference
  252. count. When the reference count goes to zero, the kset will be released.
  253. Because other references to the kset may still exist, the release may happen
  254. after kset_unregister() returns.
  255. An example of using a kset can be seen in the
  256. samples/kobject/kset-example.c file in the kernel tree.
  257. If a kset wishes to control the uevent operations of the kobjects
  258. associated with it, it can use the struct kset_uevent_ops to handle it:
  259. struct kset_uevent_ops {
  260. int (*filter)(struct kset *kset, struct kobject *kobj);
  261. const char *(*name)(struct kset *kset, struct kobject *kobj);
  262. int (*uevent)(struct kset *kset, struct kobject *kobj,
  263. struct kobj_uevent_env *env);
  264. };
  265. The filter function allows a kset to prevent a uevent from being emitted to
  266. userspace for a specific kobject. If the function returns 0, the uevent
  267. will not be emitted.
  268. The name function will be called to override the default name of the kset
  269. that the uevent sends to userspace. By default, the name will be the same
  270. as the kset itself, but this function, if present, can override that name.
  271. The uevent function will be called when the uevent is about to be sent to
  272. userspace to allow more environment variables to be added to the uevent.
  273. One might ask how, exactly, a kobject is added to a kset, given that no
  274. functions which perform that function have been presented. The answer is
  275. that this task is handled by kobject_add(). When a kobject is passed to
  276. kobject_add(), its kset member should point to the kset to which the
  277. kobject will belong. kobject_add() will handle the rest.
  278. If the kobject belonging to a kset has no parent kobject set, it will be
  279. added to the kset's directory. Not all members of a kset do necessarily
  280. live in the kset directory. If an explicit parent kobject is assigned
  281. before the kobject is added, the kobject is registered with the kset, but
  282. added below the parent kobject.
  283. Kobject removal
  284. After a kobject has been registered with the kobject core successfully, it
  285. must be cleaned up when the code is finished with it. To do that, call
  286. kobject_put(). By doing this, the kobject core will automatically clean up
  287. all of the memory allocated by this kobject. If a KOBJ_ADD uevent has been
  288. sent for the object, a corresponding KOBJ_REMOVE uevent will be sent, and
  289. any other sysfs housekeeping will be handled for the caller properly.
  290. If you need to do a two-stage delete of the kobject (say you are not
  291. allowed to sleep when you need to destroy the object), then call
  292. kobject_del() which will unregister the kobject from sysfs. This makes the
  293. kobject "invisible", but it is not cleaned up, and the reference count of
  294. the object is still the same. At a later time call kobject_put() to finish
  295. the cleanup of the memory associated with the kobject.
  296. kobject_del() can be used to drop the reference to the parent object, if
  297. circular references are constructed. It is valid in some cases, that a
  298. parent objects references a child. Circular references _must_ be broken
  299. with an explicit call to kobject_del(), so that a release functions will be
  300. called, and the objects in the former circle release each other.
  301. Example code to copy from
  302. For a more complete example of using ksets and kobjects properly, see the
  303. example programs samples/kobject/{kobject-example.c,kset-example.c},
  304. which will be built as loadable modules if you select CONFIG_SAMPLE_KOBJECT.