sysfs APIs and sample sysfs implementation in the Linux Kernel

The below table provides a sub-list of sysfs APIs that can be used to provide data to user space from a kernel module. For a more comprehensive list – refer sysfs.h file in the specific Linux Kernel version that you are working with.

Kernel API Description
struct kobject *kobject_create_and_add(const char *name, struct kobject *parent) This function creates a kobject structure dynamically and registers it with sysfs
void kobject_del(struct kobject *kobj) Remove an object added using kobject_add or kobject_create_and_add
int sysfs_create_dir(struct kobject *kobj); To create a directory in sysfs. The recent versions as of the day (Linux 5.14 has sysfs_create_dir_ns)  accepts a custom namespace tag as a parameter
void sysfs_remove_dir(struct kobject *kobj); To remove a directory in sysfs file system.
int sysfs_rename_dir(struct kobject *kobj. const char *new_name); To rename a directory in sysfs. The recent versions as of the day (Linux 5.14 has sysfs_rename_dir_ns) accepts a custom namespace tag as a parameter
int sysfs_create_file(struct kobject *kobj, const struct attribute *attr) Create a kobject attribute. The recent versions as of the day (Linux 5.14 has sysfs_create_file_ns) accepts a custom namespace tag as a parameter
void sysfs_remove_file(struct kobject *kobj,  const struct attribute *attr) Remove a file attribute. The recent versions as of the day (Linux 5.14 has sysfs_remove_file_ns) accepts a custom namespace tag as a parameter
int sysfs_create_group(struct kobject *kobj, const struct attribute_group *grp) Similar to sysfs_create_file, but allows to create a group of attributes

The Below code shows a sample implementation for Kernel 5.11. 

The Makefile for the code is shown below

The output of the sysfs example code is shown below. Modifying the value in sysfs_exmpl requires the shell to be “root”.

Linux Kernel – Debug File System

Comments

  1. Pingback: Sys File System (sysfs) in the Linux Kernel | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *