androidlinux-kernellinux-device-driversysfs

How to create a folder within a folder in sysfs


I am trying to create a sysfs for an implementation of mine in android and stuck at creating a folder of my own in CLASS.

My requirement:

/sys/class/example_class/my_sysfs_directory/file_one.

Code:

    #include<linux/module.h>
    #include<linux/kernel.h>
    #include<linux/device.h>
    #include <linux/err.h>

    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Manoj");

    static ssize_t sysfs_demo_show(struct class *class,
        struct class_attribute *attr, char *buf)
    {
    pr_info("%s [%d]: \n", __func__, __LINE__);
    return sprintf(buf, "%s \n", __func__);
    }

    static ssize_t sysfs_demo_store(struct class *class,
    struct class_attribute *attr, const char *buf, size_t size)
    {
    pr_info("%s [%d]: \n", __func__, __LINE__);
    return size;
    }

    static CLASS_ATTR(file_one, 0777, sysfs_demo_show, sysfs_demo_store);
    int  sysfs_my_dev_uevent(struct device *dev, struct kobj_uevent_env *env)
    {
    pr_info("%s [%d]: \n", __func__, __LINE__);
    return 0;
    }

    struct class *example_class;

    int sysfs_demo_init(void)
    {
    int ret;
    pr_info("%s [%d]: \n", __func__, __LINE__);
    example_class = class_create(THIS_MODULE, "demo");
    if (IS_ERR(example_class)) {
    pr_err("Failed to create sys_class\n");
    return -1;
    }
    example_class->dev_uevent = sysfs_my_dev_uevent;
    ret = class_create_file(example_class, &class_attr_file_one);
    if (ret) {
    pr_err("Failed to create class file @ parent class dirs\n");
    return -1;
    }
    return 0;
    }

    void sysfs_demo_exit(void)
    {
    pr_info("%s [%d]: \n", __func__, __LINE__);
    class_remove_file(example_class, &class_attr_file_one);
    class_destroy(example_class);
    }


    module_init(sysfs_demo_init);
    module_exit(sysfs_demo_exit);

I have pasted my code here, Please help me in this regard.


Solution

  • It is not raccomended to create sysfs directory/file "manually".

    Every sysfs attribute should be associated to a device. If your aim is a driver for a device, sooner or later you will use the structure device. Here a related answer