sysfs 作为内核中的一种内存文件系统,现阶段很多子系统、设备驱动程序都使用sysfs实现内核空间和用户空间的交互。其挂载在/sys下。用户通过对设备节点的操作,进入到kernel空间,通过属性文件的读写操作(show store),操作硬件。
在内核中,sysfs的属性一般都是由_ATTR系列的宏来实现。对设备的使用 DEVICE_ATTR ,对总线使用 BUS_ATTR ,对驱动使用 DRIVER_ATTR ,对类别(class)使用 CLASS_ATTR。
以下源码分析是在kernel4.14上 。
一、 几个结构体
sysfs_create_file 里的传参是 struct attribute 结构体
sysfs_create_group 里的传参是 struct attribute_group 结构体
struct attribute {
const char *name;
umode_t mode;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
bool ignore_lockdep:1;
struct lock_class_key *key;
struct lock_class_key skey;
#endif
};
struct attribute_group {
const char *name;
umode_t (*is_visible)(struct kobject *, struct attribute *, int);
umode_t (*is_bin_visible)(struct kobject *, struct bin_attribute *, int);
struct attribute **attrs;
struct bin_attribute **bin_attrs;
};
struct attribute 和 struct attribute_group 区别:attribute_group 里可以有好几组 attribute 。
struct device_attribute {
struct attribute attr;
ssize_t (*show)(struct device *dev, struct device_attribute *attr,
char *buf);
ssize_t (*store)(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count);
};
struct device_attribute 是自定义decice属性结构,读写该属性的方法 show 和 store 会和自定义的属性方法关联起来。
二、 sysfs_create_file
static inline int __must_check sysfs_create_file(struct kobject *kobj,
const struct attribute *attr)</