Kobject reference counting
Each kobject has a member struct kref, which is a reference counter. Whenever any module wishes to use the kobject already created, this reference count is incremented, and whenever that module wishes to stop using kobject, the reference count is decremented to maintain the number of modules using the kobject or the sysfs directory represented by the kobject. Whenever the reference count reaches 0, the memory related to the kobject which was allotted by kobject_create_and_add is released, and whenever a kobject is created using kobject_create_and_add, it internally initialises the kref reference counter by one. This indicates the kobject is being used by the current module, and then kobject_create_and_add internally creates the directory for the kobject. Whenever any new module wishes to use the directory represented by that kobject, the reference counter has to be incremented.
The reference count is maintained in the kobject using the following functions:
…where, attr is the attribute representing the file to be created, show is the pointer to the function that will be called when the file is read in sysfs, and store is the pointer to the function which will be called when the file is written in sysfs.
Suppose we need to create our example_info file in the /sysfs/ kernel/example_dev directory that was created as an example; then the following method is the way to define the attribute: