Table of Contents
1 Introduction" >1 Introduction
2. The relationship between sysfs and Kobject" >2. The relationship between sysfs and Kobject
3. attribute" >3. attribute
3.1 Function overview of attribute" >3.1 Function overview of attribute
3.2 Creation of attibute file" >3.2 Creation of attibute file
3.3 Read and write of attibute files" >3.3 Read and write of attibute files
4. sysfs在设备模型中的应用总结" >4. sysfs在设备模型中的应用总结
Home System Tutorial LINUX Detailed explanation of Linux device model (4)_sysfs

Detailed explanation of Linux device model (4)_sysfs

Feb 15, 2024 pm 05:00 PM
linux linux tutorial linux system linux command shell script overflow embeddedlinux Getting started with linux linux learning

1 Introduction

sysfs is a RAM-based file system that is used in conjunction with Kobject to export Kernel data structures and attributes to user space and provide access support for these data structures in the form of file directory structures.

Detailed explanation of Linux device model (4)_sysfs

sysfs has all the attributes of a file system, but this article focuses on its characteristics in the Linux device model. Therefore, we will not cover too many file system implementation details, but only introduce the role and use of sysfs in the device model. Specifically include:

  • The relationship between sysfs and Kobject
  • The concept of attribute
  • File system operation interface of sysfs

2. The relationship between sysfs and Kobject

In the article "Linux Device Model_Kobject", it is mentioned that each Kobject corresponds to a directory in sysfs. Therefore, when adding Kobject to the Kernel, the create_dir interface will call the create directory interface of the sysfs file system to create a directory corresponding to the Kobject. The relevant code is as follows:

 1: /* lib/kobject.c, line 47 */
 2: static int create_dir(struct kobject *kobj)
 3: {
 4:     int error = 0;
 5:     error = sysfs_create_dir(kobj);
 6:     if (!error) {
 7:         error = populate_dir(kobj);
 8:     if (error)
 9:         sysfs_remove_dir(kobj);
 10:     }   
 11:     return error;
 12: }
 13:  
 14: /* fs/sysfs/dir.c, line 736 */
 15: **
 16: *  sysfs_create_dir - create a directory for an object.
 17: *  @kobj:      object we're creating directory for. 
 18: */
 19: int sysfs_create_dir(struct kobject * kobj)
 20: {
 21:     enum kobj_ns_type type;
 22:     struct sysfs_dirent *parent_sd, *sd;
 23:     const void *ns = NULL;
 24:     int error = 0;
 25:     ...
 26: }
Copy after login

3. attribute

3.1 Function overview of attribute

In sysfs, why is there the concept of attribute? In fact, it corresponds to kobject, referring to the "attributes" of kobject. we know,

The directory in sysfs describes kobject, and kobject is the embodiment of a specific data type variable (such as struct device). Therefore, the attributes of kobject are the attributes of these variables. It can be anything, a name, an internal variable, a string, etc. Attributes are provided in the form of files in the sysfs file system, that is, all attributes of a kobject are presented in the form of files in its corresponding sysfs directory. These files are generally readable and writable, and the modules in the kernel that define these attributes will record and return the values ​​of these attributes based on the read and write operations in user space.

To summarize: the so-called attibute is a method for information interaction between kernel space and user space. For example, if a driver defines a variable and hopes that the user space program can modify the variable to control the driver's running behavior, the variable can be opened as a sysfs attribute.

In the Linux kernel, attributes are divided into ordinary attributes and binary attributes, as follows:

 1: /* include/linux/sysfs.h, line 26 */
 2: struct attribute {
 3:     const char *name;
 4:     umode_t         mode;
 5: #ifdef CONFIG_DEBUG_LOCK_ALLOC
 6:     bool ignore_lockdep:1;
 7:     struct lock_class_key   *key;
 8:     struct lock_class_key   skey;
 9: #endif
 10: };
 11:  
 12: /* include/linux/sysfs.h, line 100 */
 13: struct bin_attribute {
 14:     struct attribute    attr;
 15:     size_t          size;
 16:     void *private;
 17:     ssize_t (*read)(struct file *, struct kobject *, struct bin_attribute *,
 18:                     char *, loff_t, size_t);
 19:     ssize_t (*write)(struct file *,struct kobject *, struct bin_attribute *,
 20:                     char *, loff_t, size_t);
 21:     int (*mmap)(struct file *, struct kobject *, struct bin_attribute *attr,
 22:                     struct vm_area_struct *vma);
 23: };
Copy after login

The struct attribute is an ordinary attribute. The sysfs file generated using this attribute can only be read and written in the form of a string (I will explain why later). On the basis of struct attribute, struct bin_attribute adds read, write and other functions, so the sysfs file it generates can be read and written in any way.

After talking about the basic concepts, we have to ask two questions:

How does Kernel turn attributes into files in sysfs?

How to pass the read and write operations on sysfs files in user space to Kernel?

Let’s take a look at the process.

3.2 Creation of attibute file

In the Linux kernel, the creation of the attribute file is completed by the sysfs_create_file interface in fs/sysfs/file.c. There is nothing special about the implementation of this interface. Most of them are file system-related operations and have nothing to do with the device model. Many relationships will be omitted here.

3.3 Read and write of attibute files

When we see the prototype of struct attribute in Chapter 3.1, we may mutter that the structure is very simple. name represents the file name, mode represents the file mode, and other fields are used by the kernel to debug Kernel Lock. Then the file Where is the interface for operation?

Don’t worry, let’s go to the fs/sysfs directory to look at the sysfs-related code logic.

All file systems will define a struct file_operations variable to describe the operation interface of this file system, and sysfs is no exception:

 1: /* fs/sysfs/file.c, line 472 */
 2: const struct file_operations sysfs_file_operations = {
 3:     .read       = sysfs_read_file,
 4:     .write      = sysfs_write_file,
 5:     .llseek     = generic_file_llseek,
 6:     .open       = sysfs_open_file,
 7:     .release    = sysfs_release,
 8:     .poll       = sysfs_poll,
 9: };
Copy after login

The read operation of the attribute file will be transferred from VFS to the read (that is, sysfs_read_file) interface of sysfs_file_operations. Let us take a rough look at the processing logic of this interface.

 1: /* fs/sysfs/file.c, line 127 */
 2: static ssize_t
 3: sysfs_read_file(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 4: {
 5:     struct sysfs_buffer * buffer = file->private_data;
 6:     ssize_t retval = 0;
 7:  
 8:     mutex_lock(&buffer->mutex);
 9:     if (buffer->needs_read_fill || *ppos == 0) {
 10:        retval = fill_read_buffer(file->f_path.dentry,buffer);
 11:        if (retval)
 12:            goto out;
 13:    }
 14: ...
 15: }
 16: /* fs/sysfs/file.c, line 67 */
 17: static int fill_read_buffer(struct dentry * dentry, struct sysfs_buffer * buffer)
 18: {           
 19:    struct sysfs_dirent *attr_sd = dentry->d_fsdata;
 20:    struct kobject *kobj = attr_sd->s_parent->s_dir.kobj;
 21:    const struct sysfs_ops * ops = buffer->ops;
 22:    ...        
 23:    count = ops->show(kobj, attr_sd->s_attr.attr, buffer->page);
 24:    ...
 25: }
Copy after login

read处理看着很简单,sysfs_read_file从file指针中取一个私有指针(注:大家可以稍微留一下心,私有数据的概念,在VFS中使用是非常普遍的),转换为一个struct sysfs_buffer类型的指针,以此为参数(buffer),转身就调用fill_read_buffer接口。

而fill_read_buffer接口,直接从buffer指针中取出一个struct sysfs_ops指针,调用该指针的show函数,即完成了文件的read操作。

那么后续呢?当然是由ops->show接口接着处理咯。而具体怎么处理,就是其它模块(例如某个driver)的事了,sysfs不再关心(其实,Linux大多的核心代码,都是只提供架构和机制,具体的实现,也就是苦力,留给那些码农吧!这就是设计的魅力)。

不过还没完,这个struct sysfs_ops指针哪来的?好吧,我们再看看open(sysfs_open_file)接口吧。

 1: /* fs/sysfs/file.c, line 326 */
 2: static int sysfs_open_file(struct inode *inode, struct file *file)
 3: {
 4:     struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
 5:     struct kobject *kobj = attr_sd->s_parent->s_dir.kobj;
 6:     struct sysfs_buffer *buffer;
 7:     const struct sysfs_ops *ops;
 8:     int error = -EACCES;
 9:  
 10:    /* need attr_sd for attr and ops, its parent for kobj */
 11:    if (!sysfs_get_active(attr_sd))
 12:    return -ENODEV;
 13:  
 14:    /* every kobject with an attribute needs a ktype assigned */
 15:    if (kobj->ktype && kobj->ktype->sysfs_ops)
 16:        ops = kobj->ktype->sysfs_ops;
 17:    else {
 18:        WARN(1, KERN_ERR "missing sysfs attribute operations for "
 19:            "kobject: %s\n", kobject_name(kobj));
 20:        goto err_out;
 21:    }
 22:  
 23:    ...
 24:  
 25:    buffer = kzalloc(sizeof(struct sysfs_buffer), GFP_KERNEL);
 26:    if (!buffer)
 27:        goto err_out;
 28:  
 29:    mutex_init(&buffer->mutex);
 30:    buffer->needs_read_fill = 1;
 31:    buffer->ops = ops;
 32:    file->private_data = buffer;
 33:    ...
 34: }
Copy after login

哦,原来和ktype有关系。这个指针是从该attribute所从属的kobject中拿的。再去看一下”Linux设备模型_Kobject”中ktype的定义,还真有一个struct sysfs_ops的指针。

我们注意一下14行的注释以及其后代码逻辑,如果从属的kobject(就是attribute文件所在的目录)没有ktype,或者没有ktype->sysfs_ops指针,是不允许它注册任何attribute的!

经过确认后,sysfs_open_file从ktype中取出struct sysfs_ops指针,并在随后的代码逻辑中,分配一个struct sysfs_buffer类型的指针(buffer),并把struct sysfs_ops指针保存在其中,随后(注意哦),把buffer指针交给file的private_data,随后read/write等接口便可以取出使用。嗯!惯用伎俩!

顺便看一下struct sysfs_ops吧,我想你已经能够猜到了。

 1: /* include/linux/sysfs.h, line 124 */
 2: struct sysfs_ops {
 3:     ssize_t (*show)(struct kobject *, struct attribute *,char *);
 4:     ssize_t (*store)(struct kobject *,struct attribute *,const char *, size_t);
 5:     const void *(*namespace)(struct kobject *, const struct attribute *);
 6: };
Copy after login

attribute文件的write过程和read类似,这里就不再多说。另外,上面只分析了普通attribute的逻辑,而二进制类型的呢?也类似,去看看fs/sysfs/bin.c吧,这里也不说了。

讲到这里,应该已经结束了,事实却不是如此。上面read/write的数据流,只到kobject(也就是目录)级别哦,而真正需要操作的是attribute(文件)啊!这中间一定还有一层转换!确实,不过又交给其它模块了。 下面我们通过一个例子,来说明如何转换的。

4. sysfs在设备模型中的应用总结

让我们通过设备模型class.c中有关sysfs的实现,来总结一下sysfs的应用方式。

首先,在class.c中,定义了Class所需的ktype以及sysfs_ops类型的变量,如下:

 1: /* drivers/base/class.c, line 86 */
 2: static const struct sysfs_ops class_sysfs_ops = {
 3:     .show      = class_attr_show,
 4:     .store     = class_attr_store,
 5:     .namespace = class_attr_namespace,
 6: };  
 7: 
 8: static struct kobj_type class_ktype = {
 9:     .sysfs_ops  = &class_sysfs_ops,
 10:    .release    = class_release,
 11:    .child_ns_type  = class_child_ns_type,
 12: };
Copy after login

由前面章节的描述可知,所有class_type的Kobject下面的attribute文件的读写操作,都会交给class_attr_show和class_attr_store两个接口处理。以class_attr_show为例:

 1: /* drivers/base/class.c, line 24 */
 2: #define to_class_attr(_attr) container_of(_attr, struct class_attribute, attr)
 3:  
 4: static ssize_t class_attr_show(struct kobject *kobj, struct attribute *attr,
 5: char *buf)
 6: {   
 7:     struct class_attribute *class_attr = to_class_attr(attr);
 8:     struct subsys_private *cp = to_subsys_private(kobj);
 9:     ssize_t ret = -EIO;
 10:  
 11:    if (class_attr->show)
 12:    ret = class_attr->show(cp->class, class_attr, buf);
 13:    return ret;
 14: }
Copy after login

该接口使用container_of从struct attribute类型的指针中取得一个class模块的自定义指针:struct class_attribute,该指针中包含了class模块自身的show和store接口。下面是struct class_attribute的声明:

 1: /* include/linux/device.h, line 399 */
 2: struct class_attribute {
 3:     struct attribute attr;
 4:     ssize_t (*show)(struct class *class, struct class_attribute *attr,
 5:                     char *buf);
 6:     ssize_t (*store)(struct class *class, struct class_attribute *attr,
 7:                     const char *buf, size_t count);
 8:     const void *(*namespace)(struct class *class,
 9:                                 const struct class_attribute *attr); 
 10: };
Copy after login

因此,所有需要使用attribute的模块,都不会直接定义struct attribute变量,而是通过一个自定义的数据结构,该数据结构的一个成员是struct attribute类型的变量,并提供show和store回调函数。然后在该模块ktype所对应的struct sysfs_ops变量中,实现该本模块整体的show和store函数,并在被调用时,转接到自定义数据结构(struct class_attribute)

The above is the detailed content of Detailed explanation of Linux device model (4)_sysfs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Android TV Box gets unofficial Ubuntu 24.04 upgrade Android TV Box gets unofficial Ubuntu 24.04 upgrade Sep 05, 2024 am 06:33 AM

For many users, hacking an Android TV box sounds daunting. However, developer Murray R. Van Luyn faced the challenge of looking for suitable alternatives to the Raspberry Pi during the Broadcom chip shortage. His collaborative efforts with the Armbia

deepseek web version entrance deepseek official website entrance deepseek web version entrance deepseek official website entrance Feb 19, 2025 pm 04:54 PM

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

How to install deepseek How to install deepseek Feb 19, 2025 pm 05:48 PM

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

BitPie Bitpie wallet app download address BitPie Bitpie wallet app download address Sep 10, 2024 pm 12:10 PM

How to download BitPie Bitpie Wallet App? The steps are as follows: Search for "BitPie Bitpie Wallet" in the AppStore (Apple devices) or Google Play Store (Android devices). Click the "Get" or "Install" button to download the app. For the computer version, visit the official BitPie wallet website and download the corresponding software package.

BITGet official website installation (2025 beginner's guide) BITGet official website installation (2025 beginner's guide) Feb 21, 2025 pm 08:42 PM

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Detailed explanation: Shell script variable judgment parameter command Detailed explanation: Shell script variable judgment parameter command Sep 02, 2024 pm 03:25 PM

The system variable $n is the parameter passed to the script or function. n is a number indicating the number of parameters. For example, the first parameter is $1, and the second parameter is $2$? The exit status of the previous command, or the return value of the function. Returns 0 on success, 1 on failure $#Number of parameters passed to the script or function $* All these parameters are enclosed in double quotes. If a script receives two parameters, $* is equal to $1$2$0The name of the command being executed. For shell scripts, this is the path to the activated command. When $@ is enclosed in double quotes (""), it is slightly different from $*. If a script receives two parameters, $@ is equivalent to $1$2$$the process number of the current shell. For a shell script, this is the process I when it is executing

Zabbix 3.4 Source code compilation installation Zabbix 3.4 Source code compilation installation Sep 04, 2024 am 07:32 AM

1. Installation environment (Hyper-V virtual machine): $hostnamectlStatichostname:localhost.localdomainIconname:computer-vmChassis:vmMachineID:renwoles1d8743989a40cb81db696400BootID:renwoles272f4aa59935dcdd0d456501Virtualization:microsoftOperatingSystem:CentOS Linux7(Core)CPEOSName:cpe:

Ouyi okx installation package is directly included Ouyi okx installation package is directly included Feb 21, 2025 pm 08:00 PM

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

See all articles