良许Linux教程网 干货合集 Linux干货 | 内核模块参数传递与sysfs

Linux干货 | 内核模块参数传递与sysfs

一、开篇

在Linux应用开发中,为了让应用程序能够更加灵活地满足用户的需求,我们经常会通过命令行传递参数给main函数,以便根据参数执行不同的任务。类似地,Linux内核也提供了一种类似于main函数传参的机制,即内核传参机制。通过实现传参接口,内核程序可以在加载内核模块时接收用户指定的参数,从而使得内核模块具有更大的灵活性。

二、内核模块传参

1、内核模块传参的意义

内核模块传参的意义在于增强程序的灵活性,使其能够适配各种复杂的应用场景并兼容不同的硬件设备。通过参数选择,可以避免重新编译内核模块,从而节省时间和精力。此外,通过内核模块传递参数还能够更好地实现产品的兼容性和迭代更新。

2、内核传参实现

内核支持传递的参数类型包含了C语言中常用的数据类型。

 

  • 基本类型,字符型(char)、布尔型(bool)、整型(int)、长整型(long)、短整型(short),以及相关的无符号整型(unsigned)、字符指针(charp,内存为用户提供的字符串分配,即char *)、颠倒了值的bool类型(invbool)
  • 数组(array)
  • 字符串(string)

实现内核模块传参,只需在内核模块程序中调用module_param系列宏即可,module_param系列宏位于“/include/linux/moduleparam.h”中定义,包括module_param_arraymodule_param_stringmodule_param_cb

#define module_param(name, type, perm)                \
    module_param_named(name, name, type, perm)

#define module_param_array(name, type, nump, perm)        \
    module_param_array_named(name, name, type, nump, perm)

#define module_param_string(name, string, len, perm)            \
    static const struct kparam_string __param_string_##name        \
        = { len, string };                    \
    __module_param_call(MODULE_PARAM_PREFIX, name,            \
                ¶m_ops_string,                \
                .str = &__param_string_##name, perm, -1, 0);\
    __MODULE_PARM_TYPE(name, "string")

#define module_param_cb(name, ops, arg, perm)          \
 __module_param_call(MODULE_PARAM_PREFIX, name, ops, arg, perm, -1, 0)

module_param用于处理基本类型参数,module_param_array用于处理数组类型参数,module_param_string用于处理字符串类型参数。

1)基本类型

module_param(name, type, perm)
  • name,内核模块程序中的变量名称,同时又是用户传入参数时的名称
  • type,参数类型,见上面
  • perm,该参数指定sysfs中相应文件的访问权限,访问权限与linux文件访问权限相同的方式管理,位于"/include/linux/stat.h"定义,一般使用S_IRUGO;也可以直接用数字表示,如0444表示S_IRUGO
/* include/linux/stat.h */
#define S_IRWXUGO    (S_IRWXU|S_IRWXG|S_IRWXO)    /* 所有用户可读、写、执行 */
#define S_IALLUGO   
 (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO)/* 所有用户可读、写、执行*/
#define S_IRUGO     
   (S_IRUSR|S_IRGRP|S_IROTH)    /* 所有用户可读 */
#define S_IWUGO    
    (S_IWUSR|S_IWGRP|S_IWOTH)    /* 所有用户可写 */
#define S_IXUGO      
  (S_IXUSR|S_IXGRP|S_IXOTH)    /* 所有用户可执行 */

/* include/uapi/linux/stat.h */
/* 三者分别表示用于者权限、用户组权限、其他访问者权限 
* bit[0]、bit[1]、bit[2]分别表示可执行、可写、可读属性
*/
#define S_IRWXU 00700
#define S_IRUSR 00400
#define S_IWUSR 00200
#define S_IXUSR 00100

#define 
S_IRWXG 00070
#define S_IRGRP 00040
#define S_IWGRP 00020
#define S_IXGRP 00010

#define S_IRWXO 
00007
#define S_IROTH 00004
#define S_IWOTH 00002
#define S_IXOTH 00001

 

  • S_I:只是一个前缀
  • R:读。W:写。X:执行
  • USR:用户。GRP:组。UGO:用户、组和其他

示例:

static int mode = 1;
static char *p = NULL;

module_param(mode, int , S_IRUGO);    /* int型 */   
module_param(p, charp, S_IRUGO);    /* 指针 */

 

注:必须写在模块源文件的开头部分(mode和*p是全局的);该宏不会声明变量,因此在使用宏之前,必须声明变量

2)数组类型

module_param_array(name, type, nump, perm)
  • name,内核模块程序中数组名称,同时又是用户传入参数时的名称
  • type,数组类型,int、char等
  • nump,指针,指向一个整数,其值表示有多少个参数存放在数组name中,用来接收用户实际传递的数组成员的个数,内核接收到实际用户传递的个数赋值到nump对应地址空间
  • perm,该参数指定sysfs访问权限,位于"/include/linux/stat.h"定义,一般使用S_IRUGO;也可以直接用数字表示,如0444表示S_IRUGO

示例:

static int array[3] = {0};
static int array_size;

module_param_array(array, int, &array_size, S_IRUGO);

3)字符串类型

module_param_string(name, string, len, perm)
  • name,外部的参数名,可以与内核模块程序中变量名称string相同
  • string,内部的变量名
  • len,以string命名的buffer大小(可以小于buffer的大小,但是没有意义)
  • perm,该参数指定sysfs访问权限(perm为零表示完全关闭相对应的sysfs项),位于"/include/linux/stat.h"定义,一般使用S_IRUGO;也可以直接用数字表示,如0444表示S_IRUGO

示例:

static char string[6] = {0};

module_param_string(usestr, string, sizeof(string), S_IRUGO);

4)参数回调类型

module_param_cb(name, ops, arg, perm)          
  • name,内核模块程序中的变量名称,同时又是用户传入参数时的名称
  • ops, 指针变量,指向被自定义的回调函数初始化的kernel_param_ops变量
  • arg, 指针变量,指向内核模块程序中的变量名称,保存用户传入的参数值
  • perm, 该参数指定sysfs访问权限,位于"/include/linux/stat.h"定义,一般使用S_IRUGO;也可以直接用数字表示,如0444表示S_IRUGO

这个宏用于在参数(参数)发生变化时注册回调。例如,我使用 module_param 创建了一个参数debug,一旦我加载带有 debug=0 的simple模块,它将创建一个 sysfs 条目。并且我们想在不重新加载模块的情况下打开调试消息,我们可以使用该文件:

[root@localhost tmp23]# ls -l /sys/module/simple/parameters/debug
-rw-r--r-- 1 root root 4096 May 23 14:46 /sys/module/simple/parameters/debug

当 sysfs 的值改变时(你可以使用 echo 1 > /sys/module//parameters/debug 改变),我们可以通过回调得到通知。如果您想在值发生变化时收到通知,我们需要将我们的处理函数注册到它的文件操作结构中,即下面数据结构:

struct kernel_param_ops {
  int (*set)(const char *val, const struct kernel_param *kp);
  int (*get)(char *buffer, const struct kernel_param *kp);
  void (*free)(void *arg);
}

 

注: module_param_array和module_param调用的是默认的回调函数, module_param_cb支持自定义回调函数

示例:

/*----------------------Module_param_cb()--------------------------------*/
static int debug= 0;
int custom_callback_function(const char *val, const struct kernel_param *kp)
{
        int res = param_set_int(val, kp); // Use for write variable
        if(res==0) {
                printk(KERN_INFO "Call back function called...\n");
                printk(KERN_INFO "New value of debug = %d\n", debug);
                return 0;
        }
        return -1;
}
 
const struct kernel_param_ops my_param_ops = 
{
        .set = &custom_callback_function, // Use our setter ...
        .get = ¶m_get_int,            // .. and standard getter
};
 
module_param_cb(debug, &my_param_ops, &debug, S_IRUGO|S_IWUSR );

执行echo 1 > /sys/module/simple/parameters/debug后,您可以看到调试变量发生了变化:

[root@localhost ~]# dmesg
[891496.255781] hello... debug=0
[891555.726272] Call back function called...
[891555.726277] New value of debug = 1

5)参数描述

用户向内核模块传递参数时,参数较多的情况下,开发工程师不易全部记住;因此,一般都会增加准确、清晰的参数描述信息,描述不同参数代表的含义,用户调用时首先查询驱动模块的参数描叙信息,进而有目的地传入具体参数。参数描述信息通过MODULE_PARM_DESC宏实现,该宏位于“/include/linux/moduleparam.h”中定义

#define MODULE_PARM_DESC(_parm, desc) \
    __MODULE_INFO(parm, _parm, #_parm ":" desc)
  • _parm,参数名称
  • desc,描述信息,字符串类型

示例:

static int mode = 0;

module_param(mode, int , S_IRUGO);
MODULE_PARM_DESC(mode, "0:mode0; 1:mode1; 2:mode2");

 

  • module_param()module_param_array()的作用就是让那些全局变量对 insmod 可见,使模块装载时可重新赋值
  • module_param_array()宏的第三个参数用来记录用户 insmod 时提供的给这个数组的元素个数,NULL 表示不关心用户提供的个数
  • module_param()module_param_array()最后一个参数权限值不能包含让普通用户也有写权限,否则编译报错。这点可参考linux/moduleparam.h__module_param_call()宏的定义
  • 字符串数组中的字符串似乎不能包含逗号或者空格,否则一个字符串会被解析成两个或多个

3、内核模块传参实例

编写一个基本的Linux内核模块程序,实现命令行往内核模块传递参数的功能,加载内核模块时传入指定参数。

内核模块源码如下:

#include 
#include 
#include 
#include 

/*传递整型类型数据*/
static int irq=10;
module_param(irq,int,0660);
MODULE_PARM_DESC(irq,"Interrupt range:1-32");

static int debug=0;
module_param(debug,int,0660);
MODULE_PARM_DESC(debug,"0:non debug mode; 1:debug mode");

/*传递指针类型数据*/
static char *devname = "simpdev";
module_param(devname,charp,0660);
MODULE_PARM_DESC(devname,"device name");

/*
传递数组类型数据
module_param_array(数组名, 元素类型, 元素个数(取地址), 权限);
*/
static int array[3];
static int count;
module_param_array(array, int, &count,  0660);
MODULE_PARM_DESC(array,"set array value"); 

/*
传递字符串: module_param_string
(传递参数时的字符串名称, 字符串名称, 字符串大小, 权限);
*/
static char string[20] = {0};
module_param_string(mystr, string, sizeof(string), 0660);
MODULE_PARM_DESC(mystr, "string variable of demonstration");


static int simple_init(void)
{
        int i=0;
        printk(KERN_WARNING "hello... irq=%d name=%s debug=%d\n",irq,devname,debug);
        for(i=0;i"array[%d]:%d\n", i, array[i]);
        }
        printk("count=%d\n",count);
        printk("string=%s\n", string);
        return 0;
}

static void simple_cleanup(void)
{
        printk(KERN_WARNING "bye... irq=%d name=%s debug=%d,count=%d, string=%s\n",irq,devname,debug,count,string);
}

module_init(simple_init);
module_exit(simple_cleanup); 
MODULE_LICENSE("GPL");

Makefile文件:

ifneq ($(KERNELRELEASE),)
$(info "2nd")
obj-m:=simple.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
PWD  :=$(shell pwd)
all:
        $(info "1st")
        make -C $(KDIR) M=$(PWD) modules
clean:
        rm -f *.ko *.o *.mod.o *.symvers *.cmd *.mod.c *.order *.mod
endif

命令行执行make编译程序,如下:

[root@localhost tmp22]# make
"1st"
make -C /lib/modules/4.18.0-394.el8.x86_64/build M=/tmp/tmp22 modules
make[1]: Entering directory '/usr/src/kernels/4.18.0-394.el8.x86_64'
"2nd"
  CC [M]  /tmp/tmp22/simple.o
  Building modules, stage 2.
"2nd"
  MODPOST 1 modules
  CC      /tmp/tmp22/simple.mod.o
  LD [M]  /tmp/tmp22/simple.ko
make[1]: Leaving directory '/usr/src/kernels/4.18.0-394.el8.x86_64'

查看驱动模块信息,执行"modinfo simple.ko"查看驱动模块信息,可看到我们在驱动程序中添加的参数,以及参数描述信息。

[root@localhost tmp22]# modinfo simple.ko
filename:       /tmp/tmp22/simple.ko
license:        GPL
rhelversion:    8.7
srcversion:     41AA4F4D38C05858A72127D
depends:
name:           simple
vermagic:       4.18.0-394.el8.x86_64 SMP mod_unload modversions
parm:           irq:Interrupt range:1-32 (int)
parm:           debug:0:non debug mode; 1:debug mode (int)
parm:           devname:device name (charp)
parm:           array:set array value (array of int)
parm:           mystr:string variable of demonstration (string)

加载内核模块,同时指定传递的参数;使用dmesg查看程序打印结果如下:

[root@localhost tmp22]# insmod ./simple.ko irq=22 devname=mydev debug=1 array=0x1000,0x2000,0x3000 mystr="kernel-module"
[root@localhost tmp22]#
[root@localhost tmp22]# lsmod | grep simple
simple                 16384  0

[root@localhost ~]# dmesg
[792494.652624] hello... irq=22 name=mydev debug=1
[792494.652631] array[0]:4096
[792494.652632] array[1]:8192
[792494.652633] array[2]:12288
[792494.652634] count=3
[792494.652635] string=kernel-module

#卸载simple内核模块
[root@localhost tmp22]# rmmod simple

#查看卸载simple内核模块后,dmesg打印信息
[root@localhost ~]# dmesg
[792494.652624] hello... irq=22 name=mydev debug=1
[792494.652631] array[0]:4096
[792494.652632] array[1]:8192
[792494.652633] array[2]:12288
[792494.652634] count=3
[792494.652635] string=kernel-module
[792615.350968] bye... irq=22 name=mydev debug=1,count=3, string=kernel-module

 

加载内核模块时,不同的参数之间使用空格分隔;对于数组参数,则使用逗号分隔不同的数组元素提供值:

三、内核模块参数与sysfs文件系统

1、查看sysfs文件系统下内核参数

在带有参数的内核模块安装成功后,/sys/目录下会生成加载内核模块以后的parameters文件夹,内含以变量名字命名的文件,文件内容则为通过命令行传递的参数的值。

[root@localhost tmp22]# ls -l /sys/module/simple/parameters/
total 0
-rw-rw---- 1 root root 4096 May 22 13:22 array
-rw-rw---- 1 root root 4096 May 22 13:22 debug
-rw-rw---- 1 root root 4096 May 22 13:22 devname
-rw-rw---- 1 root root 4096 May 22 13:22 irq
-rw-rw---- 1 root root 4096 May 22 13:22 mystr
[root@localhost tmp22]#
[root@localhost tmp22]# cat /sys/module/simple/parameters/array
4096,8192,12288
[root@localhost tmp22]#
[root@localhost tmp22]# cat /sys/module/simple/parameters/debug
1
[root@localhost tmp22]# cat /sys/module/simple/parameters/devname
mydev
[root@localhost tmp22]# cat /sys/module/simple/parameters/irq
22
[root@localhost tmp22]# cat /sys/module/simple/parameters/mystr
kernel-module

当内核模块卸载以后,则在/sys目录下的以模块名命名的文件夹则会被清除掉。

[root@localhost tmp22]# ls -l /sys/module/ | grep simple
[root@localhost tmp22]#

2、手动修改sysfs文件,回调通知内核

编写一个基本的Linux内核模块程序,实现修改sysfs文件后,通知内核模块的功能。

内核模块源码如下:

#include 
#include 
#include 
#include 

static int debug=0;
MODULE_PARM_DESC(debug,"0:non debug mode; 1:debug mode");

/*----------------------Module_param_cb()--------------------------------*/
int custom_callback_function(const char *val, const struct kernel_param *kp)
{
        int res = param_set_int(val, kp); // Use for write variable
        if(res==0) {
                printk(KERN_INFO "Call back function called...\n");
                printk(KERN_INFO "New value of debug = %d\n", debug);
                return 0;
        }
        return -1;
}

const struct kernel_param_ops my_param_ops =
{
        .set = &custom_callback_function, // Use our setter ...
        .get = ¶m_get_int,            // .. and standard getter
};

module_param_cb(debug, &my_param_ops, &debug, S_IRUGO|S_IWUSR );


static int simple_init(void)
{
        printk(KERN_WARNING "hello... debug=%d\n", debug);
        return 0;
}

static void simple_cleanup(void)
{
        printk(KERN_WARNING "bye... debug=%d\n", debug);
}

module_init(simple_init);
module_exit(simple_cleanup);
MODULE_LICENSE("GPL");

实际的参数值保存在debug中,set函数将用户输入作为字符串并将其转换为int,并使用内核提供的param_set_int函数进行设置。要返回参数值,我们使用内核提供的param_get_int函数。

Makefile文件:

ifneq ($(KERNELRELEASE),)
$(info "2nd")
obj-m:=simple.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
PWD  :=$(shell pwd)
all:
        $(info "1st")
        make -C $(KDIR) M=$(PWD) modules
clean:
        rm -f *.ko *.o *.mod.o *.symvers *.cmd *.mod.c *.order *.mod
endif

编译源文件,并加载相应模块,结果如下:

[root@localhost tmp23]# make
"1st"
make -C /lib/modules/4.18.0-394.el8.x86_64/build M=/tmp/tmp23 modules
make[1]: Entering directory '/usr/src/kernels/4.18.0-394.el8.x86_64'
"2nd"
  CC [M]  /tmp/tmp23/simple.o
  Building modules, stage 2.
"2nd"
  MODPOST 1 modules
  CC      /tmp/tmp23/simple.mod.o
  LD [M]  /tmp/tmp23/simple.ko
make[1]: Leaving directory '/usr/src/kernels/4.18.0-394.el8.x86_64'
[root@localhost tmp23]# ls
Makefile  modules.order  Module.symvers  simple.c  simple.ko  simple.mod.c  simple.mod.o  simple.o
[root@localhost tmp23]#
[root@localhost tmp23]#
[root@localhost tmp23]# lsmod | grep simple
simple                 16384  0
[root@localhost tmp23]# rmmod simple
[root@localhost tmp23]#
[root@localhost tmp23]# ls
Makefile  modules.order  Module.symvers  simple.c  simple.ko  simple.mod.c  simple.mod.o  simple.o
[root@localhost tmp23]#
[root@localhost tmp23]# insmod ./simple.ko
[root@localhost tmp23]# lsmod | grep simple
simple                 16384  0
[root@localhost tmp23]#
[root@localhost tmp23]# ls -l /sys/module/simple/parameters/debug
-rw-r--r-- 1 root root 4096 May 23 14:46 /sys/module/simple/parameters/debug
[root@localhost tmp23]# cat /sys/module/simple/parameters/debug
0  

#此时,查看demsg信息,如下:
[root@localhost ~]# dmesg
[891496.255781] hello... debug=0

#修改sysfs条目内容
[root@localhost tmp23]# echo 1 > /sys/module/simple/parameters/debug
[root@localhost tmp23]#
[root@localhost tmp23]# cat /sys/module/simple/parameters/debug#此时,查看dmesg信息,可以看到debug变量的值已被修改成1
[root@localhost ~]# dmesg
[891496.255781] hello... debug=0
[891555.726272] Call back function called...
[891555.726277] New value of debug = 1 

以上就是良许教程网为各位朋友分享的Linu系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !

137e00002230ad9f26e78-265x300
本文由 良许Linux教程网 发布,可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。
良许

作者: 良许

良许,世界500强企业Linux开发工程师,公众号【良许Linux】的作者,全网拥有超30W粉丝。个人标签:创业者,CSDN学院讲师,副业达人,流量玩家,摄影爱好者。
上一篇
下一篇

发表评论

联系我们

联系我们

公众号:良许Linux

在线咨询: QQ交谈

邮箱: yychuyu@163.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部