1. 设备类型

linux中主要由3种类型的设备,分别是:

设备类型 代表设备 特点 访问方式
块设备 硬盘,光盘 随机访问设备中的内容 一般都是把设备挂载为文件系统后再访问
字符设备 键盘,打印机 只能顺序访问(一个一个字符或者一个一个字节) 一般不挂载,直接和设备交互
网络设备 网卡 打破了Unix “所有东西都是文件” 的设计原则 通过套接字API来访问

除了以上3种典型的设备之外,其实Linux中还有一些其他的设备类型,其中见的较多的应该算是”伪设备“。所谓”伪设备”,其实就是一些虚拟的设备,仅提供访问内核功能而已,没有物理设备与之关联。典型的”伪设备”就是 /dev/random(内核随机数发生器), /dev/null(空设备), /dev/zero(零设备), /dev/full(满设备)

2. 内核模块

Linux内核是模块化组成的,内核中的模块可以按需加载,从而保证内核启动时不用加载所有的模块,即减少了内核的大小,也提高了效率。通过编写内核模块来给内核增加功能或者接口是个很好的方式(既不用重新编译内核,也方便调试和删除)。

2.1 带参数的内核模块

构造带参数的内核模块其实也不难,内核中已经提供了简单的框架来给我们声明参数。

2.1.1 module_param(name, type, perm)

  • 参数 name :: 既是用户可见的参数名,也是模块中存放模块参数的变量名
  • 参数 type :: 参数的类型(byte, short, int, uint, long, ulong, charp, bool…) byte型存放在char变量中,bool型存放在int变量中
  • 参数 perm :: 指定模块在 sysfs 文件系统中对应的文件权限(关于 sysfs 的内容后面介绍)
  1. static int stu_id = 0; // 默认id
  2. module_param(stu_id, int, 0644);

2.1.2 module_param_named(name, variable, type, perm)

  • 参数 name :: 用户可见的参数名
  • 参数 variable :: 模块中存放模块参数的变量名
  • 参数 type和perm :: 同 module_param 中的 type 和 perm
  1. static char* stu_name_in = "default name"; // 默认名字
  2. module_param_named(stu_name_out, stu_name_in ,charp, 0644);
  3. /* stu_name_out 是对用户开放的名称
  4. * stu_name_in 是内核模块内部使用的名称
  5. */

2.1.3 module_param_string(name, string, len, perm)

拷贝字符串到指定的字符数组

  • 参数 name :: 用户可见的参数名
  • 参数 string :: 模块中存放模块参数的变量名
  • 参数 len :: string 参数的缓冲区长度
  • 参数 perm :: 同 module_param 中的 perm
  1. static char str_in[BUF_LEN];
  2. module_param_string(str_out, str_in, BUF_LEN, 0);
  3. /* perm=0 表示完全禁止 sysfs 项 */

2.1.4 module_param_array(name, type, nump, perm)

定义数组类型的模块参数

  • 参数 name :: 同 module_param 中的 name
  • 参数 type :: 同 module_param 中的 type
  • 参数 nump :: 整型指针,存放数组的长度
  • 参数 perm :: 同 module_param 中的 perm
  1. #define MAX_ARR_LEN 5
  2. static int arr_len;
  3. static int arr_in[MAX_ARR_LEN];
  4. module_param_array(arr_in, int, &arr_len, 0644);

2.1.5 module_param_array_named(name, array, type, nump, perm)

  • 参数 name :: 数组参数对外的名称
  • 参数 array :: 数组参数对内的名称
  • 参数 type,nump,perm :: 同 module_param_array 中的 type,nump,perm
  1. #define MAX_ARR_LEN 5
  2. static int arr_len;
  3. static int arr_in[MAX_ARR_LEN];
  4. module_param_array_named(arr_out, arr_in, int, &arr_len, 0644);

2.1.6 参数描述宏

可以通过 MODULE_PARM_DESC() 来给内核模块的参数添加一些描述信息。这些描述信息在编译完内核模块后,可以通过 modinfo 命令查看。

  1. static int stu_id = 0; // 默认id
  2. module_param(stu_id, int, 0644);
  3. MODULE_PARM_DESC(stu_id, "学生ID,默认为 0"); // 这句就是描述内核模块参数 stu_id 的语句

2.2 带参数的内核模块的示例

示例代码:test_paramed_km.c。定义了3个内核模块参数,分别是 int型,char*型,数组型的。

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. MODULE_LICENSE("Dual BSD/GPL");
  5. struct student
  6. {
  7. int id;
  8. char* name;
  9. };
  10. static void print_student(struct student*);
  11. static int stu_id = 0; // 默认id
  12. module_param(stu_id, int, 0644); //int型参数
  13. MODULE_PARM_DESC(stu_id, "学生ID,默认为 0");
  14. static char* stu_name_in = "default name"; // 默认名字
  15. module_param_named(stu_name_out, stu_name_in ,charp, 0644);//char*参数
  16. MODULE_PARM_DESC(stu_name, "学生姓名,默认为 default name");
  17. #define MAX_ARR_LEN 5
  18. static int arr_len;
  19. static int arr_in[MAX_ARR_LEN];
  20. module_param_array_named(arr_out, arr_in, int, &arr_len, 0644);//数组参数
  21. MODULE_PARM_DESC(arr_in, "数组参数,默认为空");
  22. static int test_paramed_km_init(void)
  23. {
  24. struct student* stu1;
  25. int i;
  26. /* 进入内核模块 */
  27. printk(KERN_ALERT "*************************\n");
  28. printk(KERN_ALERT "test_paramed_km is inited!\n");
  29. printk(KERN_ALERT "*************************\n");
  30. // 根据参数生成 struct student 信息
  31. // 如果没有参数就用默认参数
  32. printk(KERN_ALERT "alloc one student....\n");
  33. stu1 = kmalloc(sizeof(*stu1), GFP_KERNEL);
  34. stu1->id = stu_id;
  35. stu1->name = stu_name_in;
  36. print_student(stu1);
  37. // 模块数组
  38. for (i = 0; i < arr_len; ++i) {
  39. printk(KERN_ALERT "arr_value[%d]: %d\n", i, arr_in[i]);
  40. }
  41. return 0;
  42. }
  43. static void test_paramed_km_exit(void)
  44. {
  45. /* 退出内核模块 */
  46. printk(KERN_ALERT "*************************\n");
  47. printk(KERN_ALERT "test_paramed_km is exited!\n");
  48. printk(KERN_ALERT "*************************\n");
  49. printk(KERN_ALERT "\n\n\n\n\n");
  50. }
  51. static void print_student(struct student *stu)
  52. {
  53. if (stu != NULL)
  54. {
  55. printk(KERN_ALERT "**********student info***********\n");
  56. printk(KERN_ALERT "student id is: %d\n", stu->id);
  57. printk(KERN_ALERT "student name is: %s\n", stu->name);
  58. printk(KERN_ALERT "*********************************\n");
  59. }
  60. else
  61. printk(KERN_ALERT "the student info is null!!\n");
  62. }
  63. module_init(test_paramed_km_init);
  64. module_exit(test_paramed_km_exit);

上面的示例对应的 Makefile 如下:

  1. obj-m := test_paramed_km.o
  2. #generate the path
  3. CURRENT_PATH:=$(shell pwd)
  4. #the current kernel version number
  5. LINUX_KERNEL:=$(shell uname -r)
  6. #the absolute path
  7. LINUX_KERNEL_PATH:=/usr/src/linux-headers-$(LINUX_KERNEL) #直接用发行版中的linux源码,不用再下载linux内核源码。注意,每个linux发行版的目录不一定一样
  8. #complie object
  9. all:
  10. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  11. clean:
  12. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean

内核模块运行方法:

  1. [root@vbox chap17] modinfo test_paramed_km.ko
  2. filename: paramed_km.ko
  3. license: Dual BSD/GPL
  4. srcversion: C52F97687B033738742800D
  5. depends:
  6. vermagic: 2.6.32-279.el6.x86_64 SMP mod_unload modversions
  7. parm: stu_id:学生ID,默认为 0 (int)
  8. parm: stu_name_out:charp
  9. parm: stu_name_in:学生姓名,默认为 default name
  10. parm: arr_out:array of int
  11. parm: arr_in:数组参数,默认为空
  12. <-- 3 个参数都是默认的
  13. [root@vbox chap17] insmod paramed_km.ko
  14. [root@vbox chap17] rmmod paramed_km.ko
  15. [root@vbox chap17] dmesg | tail -16 <-- 结果中显示2个默认参数,第3个数组参数默认为空,所以不显示
  16. *************************
  17. test_paramed_km is inited!
  18. *************************
  19. alloc one student....
  20. **********student info***********
  21. student id is: 0
  22. student name is: default name
  23. *********************************
  24. *************************
  25. test_paramed_km is exited!
  26. *************************
  27. <-- 3 个参数都被设置
  28. [root@vbox chap17] insmod paramed_km.ko stu_id=100 stu_name_out=myname arr_out=1,2,3,4,5
  29. [root@vbox chap17] rmmod paramed_km.ko
  30. [root@vbox chap17] dmesg | tail -21
  31. *************************
  32. test_paramed_km is inited!
  33. *************************
  34. alloc one student....
  35. **********student info***********
  36. student id is: 100
  37. student name is: myname
  38. *********************************
  39. arr_value[0]: 1
  40. arr_value[1]: 2
  41. arr_value[2]: 3
  42. arr_value[3]: 4
  43. arr_value[4]: 5
  44. *************************
  45. test_paramed_km is exited!
  46. ************************

2.3 内核模块的位置

  • 内核代码外:上面的例子,以及之前内核模块的例子都是把模块代码放在内核之外来运行的。
  • 内核代码中

内核模块的代码也可以直接放到内核代码树中。如果你开发了一种驱动,并且希望被加入到内核中,那么,可以在编写驱动的时候就将完成此驱动功能的内核模块加到内核代码树中 driver 的相应位置。将内核模块加入内核代码树中之后,不需要另外写 Makefile,修改内核代码树中的已有的 Makefile 就行。在编译内核的时候会将新的驱动以内核模块的方式编译出来。

2.4 内核模块相关操作

  • 模块安装
  1. make modules_install <-- 把随内核编译出来的模块安装到合适的目录中( /lib/modules/version/kernel )
  • 模块依赖性: linux中自动生产模块依赖性的命令:
  1. depmod <-- 产生内核依赖关系信息
  2. depmod -A <-- 只为新模块生成依赖信息(速度更快)
  • 模块的载入:
  1. insmod module.ko
  2. <-- 推荐使用以下的命令, 自动加载依赖的模块
  3. modprobe module [module parameters]
  • 模块的卸载:
  1. rmmod module.ko
  2. <-- 推荐使用以下的命令, 自动卸载依赖的模块
  3. modprobe -r module
  • 模块导出符号表: 内核模块被载入后,就动态的加载到内核中,为了能让其他内核模块使用其功能,需要将其中函数导出。内核模块中导出函数的方法:
  1. EXPORT_SYMBOL(函数名) <-- 接在要导出的函数后面即可
  2. EXPORT_SYMBOL_GPL(函数名) <-- EXPORT_SYMBOL一样,区别在于只对标记为GPL协议的模块可见

导出符号表示例:

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. MODULE_LICENSE("Dual BSD/GPL");
  5. static int test_export_A_init(void)
  6. {
  7. /* 进入内核模块 */
  8. printk(KERN_ALERT "*************************\n");
  9. printk(KERN_ALERT "ENTRY test_export_A!\n");
  10. printk(KERN_ALERT "*************************\n");
  11. printk(KERN_ALERT "\n\n\n\n\n");
  12. return 0;
  13. }
  14. static void test_export_A_exit(void)
  15. {
  16. /* 退出内核模块 */
  17. printk(KERN_ALERT "*************************\n");
  18. printk(KERN_ALERT "EXIT test_export_A!\n");
  19. printk(KERN_ALERT "*************************\n");
  20. printk(KERN_ALERT "\n\n\n\n\n");
  21. }
  22. /* 要导出的函数 */
  23. int export_add10(int param)
  24. {
  25. printk(KERN_ALERT "param from other module is : %d\n", param);
  26. return param + 10;
  27. }
  28. EXPORT_SYMBOL(export_add10);
  29. module_init(test_export_A_init);
  30. module_exit(test_export_A_exit);

Makefile

  1. must complile on customize kernel
  2. obj-m += export_A.o
  3. export_A-objs := test_export_A.o
  4. #generate the path
  5. CURRENT_PATH:=$(shell pwd)
  6. #the current kernel version number
  7. LINUX_KERNEL:=$(shell uname -r)
  8. #the absolute path
  9. LINUX_KERNEL_PATH:=/usr/src/kernels/$(LINUX_KERNEL)
  10. #complie object
  11. all:
  12. make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
  13. rm -rf modules.order .*.cmd *.o *.mod.c .tmp_versions *.unsigned
  14. #clean
  15. clean:
  16. rm -rf modules.order Module.symvers .*.cmd *.o *.mod.c *.ko .tmp_versions *.unsigned

再编写一个内核模块 module_B,使用 module_A 导出的函数 : test_module_B.c

  1. #include<linux/init.h>
  2. #include<linux/module.h>
  3. #include<linux/kernel.h>
  4. MODULE_LICENSE("Dual BSD/GPL");
  5. extern int export_add10(int); // 这个函数是 module_A 中实现的
  6. static int test_export_B_init(void)
  7. {
  8. /* 进入内核模块 */
  9. printk(KERN_ALERT "*************************\n");
  10. printk(KERN_ALERT "ENTRY test_export_B!\n");
  11. printk(KERN_ALERT "*************************\n");
  12. printk(KERN_ALERT "\n\n\n\n\n");
  13. /* 调用 module_A 导出的函数 */
  14. printk(KERN_ALERT "result from test_export_A: %d\n", export_add10(100));
  15. return 0;
  16. }
  17. static void test_export_B_exit(void)
  18. {
  19. /* 退出内核模块 */
  20. printk(KERN_ALERT "*************************\n");
  21. printk(KERN_ALERT "EXIT test_export_B!\n");
  22. printk(KERN_ALERT "*************************\n");
  23. printk(KERN_ALERT "\n\n\n\n\n");
  24. }
  25. module_init(test_export_B_init);
  26. module_exit(test_export_B_exit);

测试方法

  • 编译 module_A 中的 test_export_A.c
  • 将编译 module_A 后生成的 Module.symvers 拷贝到 module_B 文件夹中,否则在模块B找不到模块A导出的函数
  • 编译 module_B 中的 test_export_B.c
  • 先安装 模块A,再安装模块B
  • dmesg 查看log
  • 用 rmmod 卸载模块B 和 模块A (注意卸载顺序,先卸载B再卸载A)
  1. [root@vbox module_B] insmod ../module_A/export_A.ko
  2. [root@vbox module_B] insmod export_B.ko
  3. [root@vbox module_B] dmesg | tail -18
  4. *************************
  5. ENTRY test_export_A!
  6. *************************
  7. *************************
  8. ENTRY test_export_B!
  9. *************************
  10. param from other module is : 100
  11. result from test_export_A: 110
  12. [root@vbox module_B] rmmod export_B
  13. [root@vbox module_B] rmmod export_A

3. 内核对象

3.1 kobject 简介

统一设备模型的核心部分就是 kobject,通过下面对kobject结构体的介绍,可以大致了解它是如何使得各个物理设备能够以树结构的形式组织起来的。

3.1.1. kobject

kobject的定义在 <linux/kobject.h>

  1. struct kobject {
  2. const char *name; /* kobject 名称 */
  3. struct list_head entry; /* kobject 链表 */
  4. struct kobject *parent; /* kobject 的父对象,说明kobject是有层次结构的 */
  5. struct kset *kset; /* kobject 的集合,接下来有详细介绍 */
  6. struct kobj_type *ktype; /* kobject 的类型,接下来有详细介绍 */
  7. struct sysfs_dirent *sd; /* 在sysfs中,这个结构体表示kobject的一个inode结构体,sysfs之后也会介绍 */
  8. struct kref kref; /* 提供 kobject 的引用计数 */
  9. /* 一些标志位 */
  10. unsigned int state_initialized:1;
  11. unsigned int state_in_sysfs:1;
  12. unsigned int state_add_uevent_sent:1;
  13. unsigned int state_remove_uevent_sent:1;
  14. unsigned int uevent_suppress:1;
  15. };

kobject 本身不代表什么实际的内容,一般都是嵌在其他数据结构中来发挥作用。嵌入kobject后,数据结构之间就有了树结构关系和层次关系。

3.1.2. ktype

ktype是为了描述一族的kobject所具有的普遍属性,也就是将这一族的kobject的属性统一定义一下,避免每个kobject分别定义。ktype的定义很简单,参见

  1. struct kobj_type {
  2. void (*release)(struct kobject *kobj); /* kobject的引用计数降到0时触发的析构函数,负责释放和清理内存的工作 */
  3. struct sysfs_ops *sysfs_ops; /* sysfs操作相关的函数 */
  4. struct attribute **default_attrs; /* kobject 相关的默认属性 */
  5. };

3.1.3. kset

kset是kobject对象的集合体,可以所有相关的kobject置于一个kset之中,比如所有“块设备”可以放在一个表示块设备的kset中。kset的定义也不复杂,参见

  1. struct kset {
  2. struct list_head list; /* 表示kset中所有kobject的链表 */
  3. spinlock_t list_lock; /* 用于保护 list 的自旋锁*/
  4. struct kobject kobj; /* kset中嵌入的一个kobject,使得kset也可以表现的像一样kobject一样*/
  5. struct kset_uevent_ops *uevent_ops; /* 处理kset中kobject的热插拔事件 提供了与用户空间热插拔进行通信的机制 */
  6. };

1559832611395.png

3.1.4. kref

kref记录kobject被引用的次数,当引用计数降到0的时候,则执行release函数释放相关资源。kref的定义参见:

  1. struct kref {
  2. atomic_t refcount; /* 只有一个表示引用计数的属性,atomic_t 类型表示对它的访问是原子操作 */
  3. };
  4. void kref_set(struct kref *kref, int num); /* 设置引用计数的值 */
  5. void kref_init(struct kref *kref); /* 初始化引用计数 */
  6. void kref_get(struct kref *kref); /* 增加引用计数 +1 */
  7. int kref_put(struct kref *kref, void (*release) (struct kref *kref)); /* 减少引用计数 -1 当减少到0时,释放相应资源 */

上面这些函数的具体实现可以参考内核代码 lib/kref.c

3.2 kobject 操作

kobject的相关操作都在 中定义了,主要由以下一些:

  1. extern void kobject_init(struct kobject *kobj, struct kobj_type *ktype); /* 初始化一个kobject,设置它是哪种ktype */
  2. extern int __must_check kobject_add(struct kobject *kobj,
  3. struct kobject *parent,
  4. const char *fmt, ...); /* 设置此kobject的parent,将此kobject加入到现有对象层次结构中 */
  5. extern int __must_check kobject_init_and_add(struct kobject *kobj,
  6. struct kobj_type *ktype,
  7. struct kobject *parent,
  8. const char *fmt, ...); /* 初始化kobject,完成kobject_add 函数的功能*/
  9. extern void kobject_del(struct kobject *kobj); /* 将此kobject从现有对象层次结构中取消 */
  10. extern struct kobject * __must_check kobject_create(void); /* 创建一个kobject,比kobject_init更常用 */
  11. extern struct kobject * __must_check kobject_create_and_add(const char *name,
  12. struct kobject *parent); /* 创建一个kobject,并将其加入到现有对象层次结构中 */
  13. extern int __must_check kobject_rename(struct kobject *, const char *new_name); /* 改变kobject的名称 */
  14. extern int __must_check kobject_move(struct kobject *, struct kobject *); /* 给kobject设置新的parent */
  15. extern struct kobject *kobject_get(struct kobject *kobj); /* 增加kobject的引用计数 +1 */
  16. extern void kobject_put(struct kobject *kobj); /* 减少kobject的引用计数 -1 */
  17. extern char *kobject_get_path(struct kobject *kobj, gfp_t flag); /* 生成并返回与给定的一个kobj和kset相关联的路径 */

4. sysfs

sysfs是一个处于内存中的虚拟文件系统,它提供了kobject对象层次结构的视图。可以用下面这个命令来查看 /sys 的结构

  1. tree /sys 显示所有目录和文件
  2. 或者
  3. tree -L 1 /sys 只显示一层目录

4.1 sysfs中的kobject

4.1.1. sysfs中添加和删除kobject

非常简单,就是上面介绍的 kobject操作中提到。添加了kobject之后,只会增加文件夹,不会增加文件。因为kobject在sysfs中就是映射成一个文件夹。添加删除kobject的示例代码如下:

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. #include <linux/kobject.h>
  5. MODULE_LICENSE("Dual BSD/GPL");
  6. struct kobject* kobj = NULL;
  7. static int test_kobject_init(void)
  8. {
  9. /* 初始化kobject,并加入到sysfs中 */
  10. kobj = kobject_create_and_add("test_kobject", NULL);
  11. /* 进入内核模块 */
  12. printk(KERN_ALERT "*************************\n");
  13. printk(KERN_ALERT "test_kobject is inited!\n");
  14. printk(KERN_ALERT "*************************\n");
  15. return 0;
  16. }
  17. static void test_kobject_exit(void)
  18. {
  19. /* 如果 kobj 不为空,则将其从sysfs中删除 */
  20. if (kobj != NULL)
  21. kobject_del(kobj);
  22. /* 退出内核模块 */
  23. printk(KERN_ALERT "*************************\n");
  24. printk(KERN_ALERT "test_kobject is exited!\n");
  25. printk(KERN_ALERT "*************************\n");
  26. printk(KERN_ALERT "\n\n\n\n\n");
  27. }
  28. module_init(test_kobject_init);
  29. module_exit(test_kobject_exit);

测试方法:

  1. [root@localhost test_kobject] insmod mykobject.ko <-- 安装内核模块
  2. [root@localhost test_kobject] ll /sys/ <-- 安装后,sysfs中多了一个文件夹 test_kobject
  3. total 0
  4. drwxr-xr-x 2 root root 0 Dec 24 09:28 block
  5. drwxr-xr-x 17 root root 0 Dec 24 09:28 bus
  6. drwxr-xr-x 40 root root 0 Dec 24 09:28 class
  7. drwxr-xr-x 4 root root 0 Dec 24 09:28 dev
  8. drwxr-xr-x 12 root root 0 Dec 24 09:28 devices
  9. drwxr-xr-x 4 root root 0 Dec 24 09:28 firmware
  10. drwxr-xr-x 3 root root 0 Dec 24 09:28 fs
  11. drwxr-xr-x 2 root root 0 Dec 24 09:44 hypervisor
  12. drwxr-xr-x 5 root root 0 Dec 24 09:28 kernel
  13. drwxr-xr-x 85 root root 0 Dec 24 09:54 module
  14. drwxr-xr-x 2 root root 0 Dec 24 09:44 power
  15. drwxr-xr-x 2 root root 0 Dec 24 09:55 test_kobject
  16. [root@localhost test_kobject] ll /sys/test_kobject/ <-- 追加kobject只能增加文件夹,文件夹中是没有文件的
  17. total 0
  18. [root@localhost test_kobject] rmmod mykobject.ko <-- 卸载内核模块
  19. [root@localhost test_kobject] ll /sys/ <-- 卸载后,sysfs 中的文件夹 test_kobject 也消失了
  20. total 0
  21. drwxr-xr-x 2 root root 0 Dec 24 09:28 block
  22. drwxr-xr-x 17 root root 0 Dec 24 09:28 bus
  23. drwxr-xr-x 40 root root 0 Dec 24 09:28 class
  24. drwxr-xr-x 4 root root 0 Dec 24 09:28 dev
  25. drwxr-xr-x 12 root root 0 Dec 24 09:28 devices
  26. drwxr-xr-x 4 root root 0 Dec 24 09:28 firmware
  27. drwxr-xr-x 3 root root 0 Dec 24 09:28 fs
  28. drwxr-xr-x 2 root root 0 Dec 24 09:44 hypervisor
  29. drwxr-xr-x 5 root root 0 Dec 24 09:28 kernel
  30. drwxr-xr-x 84 root root 0 Dec 24 09:55 module
  31. drwxr-xr-x 2 root root 0 Dec 24 09:44 power

4.1.2. sysfs中添加文件

kobject是映射成sysfs中的目录,sysfs中的文件就是kobject的属性,属性的来源有2个:

  • 默认属性 :: kobject所关联的ktype中的 default_attrs 字段,类型是结构体 struct attribute, 定义在 <linux/sysfs.h>
  1. struct attribute {
  2. const char *name; /* sysfs文件树中的文件名 */
  3. struct module *owner; /* x86体系结构中已经不再继续使用了,可能在其他体系结构中还会使用 */
  4. mode_t mode; /* sysfs中该文件的权限 */
  5. };
  • sysfs_ops 则描述了如何使用默认属性。struct sysfs_ops 的定义也在
  1. struct sysfs_ops {
  2. /* 在读sysfs文件时该方法被调用 */
  3. ssize_t (*show)(struct kobject *kobj, struct attribute *attr,char *buffer);
  4. /* 在写sysfs文件时该方法被调用 */
  5. ssize_t (*store)(struct kobject *kobj,struct attribute *attr,const char *buffer, size_t size);
  6. };

show 方法在读取sysfs中文件时调用,它会拷贝attr提供的属性到buffer指定的缓冲区。store 方法在写sysfs中文件时调用,它会从buffer中读取size字节的数据到attr提供的属性中

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. #include <linux/kobject.h>
  5. #include <linux/sysfs.h>
  6. MODULE_LICENSE("Dual BSD/GPL");
  7. static void myobj_release(struct kobject*);
  8. static ssize_t my_show(struct kobject *, struct attribute *, char *);
  9. static ssize_t my_store(struct kobject *, struct attribute *, const char *, size_t);
  10. /* 自定义的结构体,2个属性,并且嵌入了kobject */
  11. struct my_kobj
  12. {
  13. int ival;
  14. char* cname;
  15. struct kobject kobj;
  16. };
  17. static struct my_kobj *myobj = NULL;
  18. /* my_kobj 的属性 ival 所对应的sysfs中的文件,文件名 val */
  19. static struct attribute val_attr = {
  20. .name = "val",
  21. .owner = NULL,
  22. .mode = 0666,
  23. };
  24. /* my_kobj 的属性 cname 所对应的sysfs中的文件,文件名 name */
  25. static struct attribute name_attr = {
  26. .name = "name",
  27. .owner = NULL,
  28. .mode = 0666,
  29. };
  30. static int test_kobject_default_attr_init(void)
  31. {
  32. struct attribute *myattrs[] = {NULL, NULL, NULL};
  33. struct sysfs_ops *myops = NULL;
  34. struct kobj_type *mytype = NULL;
  35. /* 初始化 myobj */
  36. myobj = kmalloc(sizeof(struct my_kobj), GFP_KERNEL);
  37. if (myobj == NULL)
  38. return -ENOMEM;
  39. /* 配置文件 val 的默认值 */
  40. myobj->ival = 100;
  41. myobj->cname = "test";
  42. /* 初始化 ktype */
  43. mytype = kmalloc(sizeof(struct kobj_type), GFP_KERNEL);
  44. if (mytype == NULL)
  45. return -ENOMEM;
  46. /* 增加2个默认属性文件 */
  47. myattrs[0] = &val_attr;
  48. myattrs[1] = &name_attr;
  49. /* 初始化ktype的默认属性和析构函数 */
  50. mytype->release = myobj_release;
  51. mytype->default_attrs = myattrs;
  52. /* 初始化ktype中的 sysfs */
  53. myops = kmalloc(sizeof(struct sysfs_ops), GFP_KERNEL);
  54. if (myops == NULL)
  55. return -ENOMEM;
  56. myops->show = my_show;
  57. myops->store = my_store;
  58. mytype->sysfs_ops = myops;
  59. /* 初始化kobject,并加入到sysfs中 */
  60. memset(&myobj->kobj, 0, sizeof(struct kobject)); /* 这一步非常重要,没有这一步init kobject会失败 */
  61. if (kobject_init_and_add(&myobj->kobj, mytype, NULL, "test_kobj_default_attr"))
  62. kobject_put(&myobj->kobj);
  63. printk(KERN_ALERT "*************************\n");
  64. printk(KERN_ALERT "test_kobject_default_attr is inited!\n");
  65. printk(KERN_ALERT "*************************\n");
  66. return 0;
  67. }
  68. static void test_kobject_default_attr_exit(void)
  69. {
  70. kobject_del(&myobj->kobj);
  71. kfree(myobj);
  72. /* 退出内核模块 */
  73. printk(KERN_ALERT "*************************\n");
  74. printk(KERN_ALERT "test_kobject_default_attr is exited!\n");
  75. printk(KERN_ALERT "*************************\n");
  76. printk(KERN_ALERT "\n\n\n\n\n");
  77. }
  78. static void myobj_release(struct kobject *kobj)
  79. {
  80. printk(KERN_ALERT, "release kobject");
  81. kobject_del(kobj);
  82. }
  83. /* 读取属性文件 val 或者name时会执行此函数 */
  84. static ssize_t my_show(struct kobject *kboj, struct attribute *attr, char *buf)
  85. {
  86. printk(KERN_ALERT "SHOW -- attr-name: [%s]\n", attr->name);
  87. if (strcmp(attr->name, "val") == 0)
  88. return sprintf(buf, "%d\n", myobj->ival);
  89. else
  90. return sprintf(buf, "%s\n", myobj->cname);
  91. }
  92. /* 写入属性文件 val 或者name时会执行此函数 */
  93. static ssize_t my_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len)
  94. {
  95. printk(KERN_ALERT "STORE -- attr-name: [%s]\n", attr->name);
  96. if (strcmp(attr->name, "val") == 0)
  97. sscanf(buf, "%d\n", &myobj->ival);
  98. else
  99. sscanf(buf, "%s\n", myobj->cname);
  100. return len;
  101. }
  102. module_init(test_kobject_default_attr_init);
  103. module_exit(test_kobject_default_attr_exit);

测试方法

  1. [root@localhost test_kobject_defalt_attr] insmod mykobject_with_default_attr.ko
  2. [root@localhost test_kobject_defalt_attr] ll /sys/ <-- kobject对应的文件夹
  3. total 0
  4. drwxr-xr-x 2 root root 0 Dec 24 15:50 block
  5. drwxr-xr-x 17 root root 0 Dec 24 15:50 bus
  6. drwxr-xr-x 40 root root 0 Dec 24 15:50 class
  7. drwxr-xr-x 4 root root 0 Dec 24 15:50 dev
  8. drwxr-xr-x 12 root root 0 Dec 24 15:50 devices
  9. drwxr-xr-x 4 root root 0 Dec 24 15:50 firmware
  10. drwxr-xr-x 3 root root 0 Dec 24 15:50 fs
  11. drwxr-xr-x 2 root root 0 Dec 24 16:06 hypervisor
  12. drwxr-xr-x 5 root root 0 Dec 24 15:50 kernel
  13. drwxr-xr-x 85 root root 0 Dec 24 16:59 module
  14. drwxr-xr-x 2 root root 0 Dec 24 16:06 power
  15. drwxr-xr-x 2 root root 0 Dec 24 16:59 test_kobj_default_attr
  16. [root@localhost test_kobject_defalt_attr] ll /sys/test_kobj_default_attr/ <-- kobject2个属性文件
  17. total 0
  18. -rw-rw-rw- 1 root root 4096 Dec 24 16:59 name
  19. -rw-rw-rw- 1 root root 4096 Dec 24 16:59 val
  20. [root@localhost test_kobject_defalt_attr] dmesg <-- dmesg 中只有初始化的信息
  21. *************************
  22. test_kobject_default_attr is inited!
  23. *************************
  24. ########################### 读取属性文件 ###############################################
  25. [root@localhost test_kobject_defalt_attr] cat /sys/test_kobj_default_attr/val <-- 属性值就是我们在测试代码中输入的值
  26. 100
  27. [root@localhost test_kobject_defalt_attr] cat /sys/test_kobj_default_attr/name <-- 属性值就是我们在测试代码中输入的值
  28. test
  29. [root@localhost test_kobject_defalt_attr] dmesg <-- dmesg 中多了2条读取属性文件的log
  30. SHOW -- attr-name: [val]
  31. SHOW -- attr-name: [name]
  32. ########################### 写入属性文件 ################################################
  33. [root@localhost test_kobject_defalt_attr] echo "200" > /sys/test_kobj_default_attr/val <-- val文件中写入 200
  34. [root@localhost test_kobject_defalt_attr] echo "abcdefg" > /sys/test_kobj_default_attr/name <-- name文件中写入 adcdefg
  35. [root@localhost test_kobject_defalt_attr] dmesg <-- dmesg 中又多了2条写入属性文件的log
  36. STORE -- attr-name: [val]
  37. STORE -- attr-name: [name]
  38. [root@localhost test_kobject_defalt_attr] cat /sys/test_kobj_default_attr/val <-- 再次查看 val文件中的值,已变为200
  39. 200
  40. [root@localhost test_kobject_defalt_attr] cat /sys/test_kobj_default_attr/name <-- 再次查看 name文件中的值,已变为abcdefg
  41. abcdefg
  42. ########################### 卸载 ########################################################
  43. [root@localhost test_kobject_defalt_attr] rmmod mykobject_with_default_attr.ko
  • 新属性 :: kobject 自己定义的属性。在一些特殊的情况下,kobject可能会需要自己特有的属性。内核也充分考虑到了这些情况,提供了创建或者删除新属性的方法。在sysfs中文件的操作方法参见: fs/sysfs/file.c
  1. /* 文件的相关操作非常多,这里只列出创建文件和删除文件的方法 */
  2. /**
  3. * 给 kobj 增加一个新的属性 attr
  4. * kobj 对应sysfs中的一个文件夹, attr 对应sysfs中的一个文件
  5. */
  6. int sysfs_create_file(struct kobject * kobj, const struct attribute * attr)
  7. {
  8. BUG_ON(!kobj || !kobj->sd || !attr);
  9. return sysfs_add_file(kobj->sd, attr, SYSFS_KOBJ_ATTR);
  10. }
  11. /**
  12. * 给 kobj 删除一个新的属性 attr
  13. * kobj 对应sysfs中的一个文件夹, attr 对应sysfs中的一个文件
  14. */
  15. void sysfs_remove_file(struct kobject * kobj, const struct attribute * attr)
  16. {
  17. sysfs_hash_and_remove(kobj->sd, attr->name);
  18. }

除了可以在sysfs中增加/删除的文件,还可以在sysfs中增加或者删除一个符号链接。具体实现参见:fs/sysfs/symlink.c

  1. /* 下面只列出了创建和删除符号链接的方法,其他方法请参考 symlink.c 文件 */
  2. /**
  3. * 在kobj对应的文件夹中创建一个符号链接指向 target
  4. * 符号链接的名称就是 name
  5. */
  6. int sysfs_create_link(struct kobject *kobj, struct kobject *target,
  7. const char *name)
  8. {
  9. return sysfs_do_create_link(kobj, target, name, 1);
  10. }
  11. void sysfs_remove_link(struct kobject * kobj, const char * name)
  12. {
  13. struct sysfs_dirent *parent_sd = NULL;
  14. if (!kobj)
  15. parent_sd = &sysfs_root;
  16. else
  17. parent_sd = kobj->sd;
  18. sysfs_hash_and_remove(parent_sd, name);
  19. }

增加新的属性的示例代码 (这里只演示了增加文件的方法,增加符号链接的方法与之类似)

  1. #include <linux/init.h>
  2. #include <linux/module.h>
  3. #include <linux/kernel.h>
  4. #include <linux/kobject.h>
  5. #include <linux/sysfs.h>
  6. MODULE_LICENSE("Dual BSD/GPL");
  7. static void myobj_release(struct kobject*);
  8. static ssize_t my_show(struct kobject *, struct attribute *, char *);
  9. static ssize_t my_store(struct kobject *, struct attribute *, const char *, size_t);
  10. /* 自定义的结构体,其中嵌入了kobject,通过属性 c_attr 来控制增加或者删除新属性 */
  11. struct my_kobj
  12. {
  13. int c_attr; /* 值为0:删除新属性, 值为1:增加新属性*/
  14. int new_attr;
  15. struct kobject kobj;
  16. };
  17. static struct my_kobj *myobj = NULL;
  18. /* my_kobj 的属性 c_attr 所对应的sysfs中的文件,文件名 c_attr */
  19. static struct attribute c_attr = {
  20. .name = "c_attr",
  21. .owner = NULL,
  22. .mode = 0666,
  23. };
  24. /* 用于动态增加或者删除的新属性 */
  25. static struct attribute new_attr = {
  26. .name = "new_attr",
  27. .owner = NULL,
  28. .mode = 0666,
  29. };
  30. static int test_kobject_new_attr_init(void)
  31. {
  32. struct attribute *myattrs[] = {NULL, NULL};
  33. struct sysfs_ops *myops = NULL;
  34. struct kobj_type *mytype = NULL;
  35. /* 初始化 myobj */
  36. myobj = kmalloc(sizeof(struct my_kobj), GFP_KERNEL);
  37. if (myobj == NULL)
  38. return -ENOMEM;
  39. /* 配置文件 val 的默认值 */
  40. myobj->c_attr = 0;
  41. /* 初始化 ktype */
  42. mytype = kmalloc(sizeof(struct kobj_type), GFP_KERNEL);
  43. if (mytype == NULL)
  44. return -ENOMEM;
  45. /* 增加1个默认属性文件 */
  46. myattrs[0] = &c_attr;
  47. /* 初始化ktype的默认属性和析构函数 */
  48. mytype->release = myobj_release;
  49. mytype->default_attrs = myattrs;
  50. /* 初始化ktype中的 sysfs */
  51. myops = kmalloc(sizeof(struct sysfs_ops), GFP_KERNEL);
  52. if (myops == NULL)
  53. return -ENOMEM;
  54. myops->show = my_show;
  55. myops->store = my_store;
  56. mytype->sysfs_ops = myops;
  57. /* 初始化kobject,并加入到sysfs中 */
  58. memset(&myobj->kobj, 0, sizeof(struct kobject)); /* 这一步非常重要,没有这一步init kobject会失败 */
  59. if (kobject_init_and_add(&myobj->kobj, mytype, NULL, "test_kobj_new_attr"))
  60. kobject_put(&myobj->kobj);
  61. printk(KERN_ALERT "*************************\n");
  62. printk(KERN_ALERT "test_kobject_new_attr is inited!\n");
  63. printk(KERN_ALERT "*************************\n");
  64. return 0;
  65. }
  66. static void test_kobject_new_attr_exit(void)
  67. {
  68. kobject_del(&myobj->kobj);
  69. kfree(myobj);
  70. /* 退出内核模块 */
  71. printk(KERN_ALERT "*************************\n");
  72. printk(KERN_ALERT "test_kobject_new_attr is exited!\n");
  73. printk(KERN_ALERT "*************************\n");
  74. printk(KERN_ALERT "\n\n\n\n\n");
  75. }
  76. static void myobj_release(struct kobject *kobj)
  77. {
  78. printk(KERN_ALERT "release kobject");
  79. kobject_del(kobj);
  80. }
  81. /* 读取属性文件 c_attr 或者 new_attr 时会执行此函数 */
  82. static ssize_t my_show(struct kobject *kboj, struct attribute *attr, char *buf)
  83. {
  84. printk(KERN_ALERT "SHOW -- attr-name: [%s]\n", attr->name);
  85. if (strcmp(attr->name, "c_attr") == 0)
  86. return sprintf(buf, "%d\n", myobj->c_attr);
  87. else if (strcmp(attr->name, "new_attr") == 0)
  88. return sprintf(buf, "%d\n", myobj->new_attr);
  89. return 0;
  90. }
  91. /* 写入属性文件c_attr 或者 new_attr 时会执行此函数 */
  92. static ssize_t my_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len)
  93. {
  94. printk(KERN_ALERT "STORE -- attr-name: [%s]\n", attr->name);
  95. if (strcmp(attr->name, "c_attr") == 0)
  96. sscanf(buf, "%d\n", &myobj->c_attr);
  97. else if (strcmp(attr->name, "new_attr") == 0)
  98. sscanf(buf, "%d\n", &myobj->new_attr);
  99. if (myobj->c_attr == 1) /* 创建新的属性文件 */
  100. {
  101. if (sysfs_create_file(kobj, &new_attr))
  102. return -1;
  103. else
  104. myobj->new_attr = 100; /* 新属性文件的值默认设置为 100 */
  105. }
  106. if (myobj->c_attr == 0) /* 删除新的属性文件 */
  107. sysfs_remove_file(kobj, &new_attr);
  108. return len;
  109. }
  110. module_init(test_kobject_new_attr_init);
  111. module_exit(test_kobject_new_attr_exit);

测试方法:

  1. ########################### 动态增加新属性文件 #########################################
  2. [root@localhost test_kobject_new_attr] ll /sys/test_kobj_new_attr/ <-- 默认没有新属性 new_attr
  3. total 0
  4. -rw-rw-rw- 1 root root 4096 Dec 24 18:47 c_attr
  5. [root@localhost test_kobject_new_attr] cat /sys/test_kobj_new_attr/c_attr <-- c_attr 的值为0
  6. 0
  7. [root@localhost test_kobject_new_attr] echo "1" > /sys/test_kobj_new_attr/c_attr <-- c_attr 的值设为1
  8. [root@localhost test_kobject_new_attr] ll /sys/test_kobj_new_attr/ <-- 增加了新属性 new_attr
  9. total 0
  10. -rw-rw-rw- 1 root root 4096 Dec 24 19:02 c_attr
  11. -rw-rw-rw- 1 root root 4096 Dec 24 19:02 new_attr
  12. ########################### 动态删除属性文件 ###########################################
  13. [root@localhost test_kobject_new_attr] echo "0" > /sys/test_kobj_new_attr/c_attr <-- c_attr 的值为0
  14. [root@localhost test_kobject_new_attr] ll /sys/test_kobj_new_attr/ <-- 删除了新属性 new_attr
  15. total 0
  16. -rw-rw-rw- 1 root root 4096 Dec 24 19:03 c_attr

4.1.3. sysfs相关约定

为了保持sysfs的干净和直观,在内核开发中涉及到sysfs相关内容时,需要注意以下几点:

  • sysfs属性保证每个文件只导出一个值,该值为文本形式并且可以映射为简单的C类型
  • sysfs中要以一个清晰的层次组织数据
  • sysfs提供内核到用户空间的服务

4.2 基于sysfs的内核事件

内核事件层也是利用kobject和sysfs来实现的,用户空间通过监控sysfs中kobject的属性的变化来异步的捕获内核中kobject发出的信号。用户空间可以通过一种netlink的机制来获取内核事件。内核空间向用户空间发送信号使用 kobject_uevent() 函数,具体参见:

  1. int kobject_uevent(struct kobject *kobj, enum kobject_action action);

内核模块安装或者删除时,会发送 KOBJ_ADD 或者 KOBJ_REMOVE 的消息。用户态程序通过netlink socket机制来接收 kobject 的事件通知

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/types.h>
  6. #include <asm/types.h>
  7. #include <sys/socket.h>
  8. #include <linux/netlink.h>
  9. void MonitorNetlinkUevent()
  10. {
  11. int sockfd;
  12. struct sockaddr_nl sa;
  13. int len;
  14. char buf[4096];
  15. struct iovec iov;
  16. struct msghdr msg;
  17. int i;
  18. memset(&sa,0,sizeof(sa));
  19. sa.nl_family = AF_NETLINK;
  20. sa.nl_groups = NETLINK_KOBJECT_UEVENT;
  21. sa.nl_pid = 0;//getpid(); both is ok
  22. memset(&msg,0,sizeof(msg));
  23. iov.iov_base = (void *)buf;
  24. iov.iov_len = sizeof(buf);
  25. msg.msg_name = (void *)&sa;
  26. msg.msg_namelen = sizeof(sa);
  27. msg.msg_iov = &iov;
  28. msg.msg_iovlen = 1;
  29. sockfd = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
  30. if(sockfd == -1)
  31. printf("socket creating failed:%s\n",strerror(errno));
  32. if(bind(sockfd,(struct sockaddr *)&sa,sizeof(sa)) == -1)
  33. printf("bind error:%s\n", strerror(errno));
  34. while(1) {
  35. memset(buf, 0, sizeof(buf));
  36. len=recvmsg(sockfd, &msg, 0);
  37. if(len < 0){}
  38. //printf("receive error\n");
  39. else if(len < 32||len > sizeof(buf))
  40. printf("invalid message");
  41. for(i=0; i<len; i++)
  42. if(*(buf+i) == '\0')
  43. buf[i] = '\n';
  44. printf("received %d bytes\n%s\n", len, buf);
  45. }
  46. }
  47. int main(int argc, char *argv[])
  48. {
  49. MonitorNetlinkUevent();
  50. return 0;
  51. }

测试方法:

  1. [root@localhost test_kobject_event] gcc -o test_netlink_client test_netlink_client.c <-- 编译用户态程序
  2. [root@localhost test_kobject_event] ./test_netlink_client <-- 启动后等待内核kobject的事件到来
  3. ########################### 安装内核模块并查看用户态程序输出 (窗口2)#######################
  4. [root@localhost test_kobject] insmod mykobject.ko <-- 在窗口2中安装内核模块,窗口1中会接收到 KOBJ_ADD 信号
  5. ########################### 卸载内核模块并查看用户态程序输出 (窗口2)#######################
  6. [root@localhost test_kobject] rmmod mykobject.ko <-- 在窗口2中安装内核模块,窗口1中会接收到 KOBJ_REMOVE 信号