Search code examples
linuxlinux-kernelsysfs

Writing a Sysfs module


I'm attempting to learn how to write a sysfs module, and am confused at the basic initialization. In this document looking at the kobject.h file, there are several different functions related to creating a sysfs entry.

From the looks of it, the function "kobject_init_and_add" seems like the right thing to use, which takes the following:

 90 int kobject_init_and_add(struct kobject *kobj,
 91                          struct kobj_type *ktype, struct kobject *parent,
 92                          const char *fmt, ...);

struct kobject and struct kobj_type are straightforward enough, but I don't understand what the *parent kobject and *fmt cstring are supposed to be.

Further, after initializing these objects, I would need to remove them at the exit_module function, but there are two options that seem possible: kobject_del and kobject_puts. What are the differences between these?

Part of my confusion comes from the fact that while googling for the answer, I see tutorials which says to use functions like kobject_register instead, but that function doesn't actually exist.


Solution

  • Yes there are lot of example on mainline kernel which you can refers for your implementatin. For Your doubts I am adding the some example code"

    Module Probe/init function

    static struct kobject   *module_kobject;
    module_kobject=kobject_create_and_add("module_status",NULL);
    sysfs_create_group(module_kobject,&module_attr);
    

    Module Remove/exit function

    sysfs_remove_group(module_kobject,&module_attr);
    kobject_put(module_kobject);
    

    If you want to expose more than one attribute on the user space; than you need to define the group as well

    static struct attribute_group module_attr={
    .attrs = module_attribute,
    };
    

    There is some more implementation and function you may need like:

    static ssize_t module_show_status(struct kobject *kobj,struct kobj_attribute *attr,char *buf);
    static ssize_t module_store__status(struct kobject *kobj,struct kobj_attribute *attr,const char *buf,size_t len);
    

    I think you can start your sysfs module implementation based on the above code and Feel free for any help.