linux kernel的cmdline参数解析原理分析

来源:互联网 发布:萨克斯怎么挑选知乎 编辑:程序博客网 时间:2024/05/17 04:14

FROM:http://blog.csdn.net/skyflying2012/article/details/41142801

利用工作之便,今天研究了kernel下cmdline参数解析过程,记录在此,与大家共享,转载请注明出处,谢谢。


Kernel 版本号:3.4.55

Kernel启动时会解析cmdline,然后根据这些参数如console root来进行配置运行。


Cmdline是由bootloader传给kernel,如uboot,将需要传给kernel的参数做成一个tags链表放在ram中,将首地址传给kernel,kernel解析tags来获取cmdline等信息。

Uboot传参给kernel以及kernel如何解析tags可以看我的另一篇博文,链接如下:

http://blog.csdn.NET/skyflying2012/article/details/35787971


今天要分析的是kernel在获取到cmdline之后如何对cmdline进行解析。
依据我的思路(时间顺序,如何开始,如何结束),首先看kernel下2种参数的注册。
第一种是kernel通用参数,如console=ttyS0,115200  root=/rdinit/init等。这里以console为例。

第二种是kernel下各个driver中需要的参数,在写driver中,如果需要一些启动时可变参数。可以在driver最后加入module_param()来注册一个参数,kernel启动时由cmdline指定该参数的值。

这里以drivers/usb/gadget/serial.c中的use_acm参数为例(这个例子有点偏。。因为最近在调试usb虚拟串口)


一 kernel通用参数

对于这类通用参数,kernel留出单独一块data段,叫.ini.setup段。在arch/arm/kernel/vmlinux.lds中:

[cpp] view plain copy
  1. .init.data : {  
  2.   *(.init.data) *(.cpuinit.data) *(.meminit.data) *(.init.rodata) *(.cpuinit.rodata) *(.meminit.rodata) . = ALIGN(32); __dtb_star  
  3.  . = ALIGN(16); __setup_start = .; *(.init.setup) __setup_end = .;  
  4.   __initcall_start = .; *(.initcallearly.init) __initcall0_start = .; *(.initcall0.init) *(.initcall0s.init) __initcall1_start =  
  5.   __con_initcall_start = .; *(.con_initcall.init) __con_initcall_end = .;  
  6.   __security_initcall_start = .; *(.security_initcall.init) __security_initcall_end = .;  
  7.   . = ALIGN(4); __initramfs_start = .; *(.init.ramfs) . = ALIGN(8); *(.init.ramfs.info)  
  8.  }  

可以看到init.setup段起始__setup_start和结束__setup_end

.init.setup段中存放的就是kernel通用参数和对应处理函数的映射表。在include/Linux/init.h

[cpp] view plain copy
  1. struct obs_kernel_param {  
  2.     const char *str;  
  3.     int (*setup_func)(char *);  
  4.     int early;  
  5. };  
  6.   
  7. /* 
  8.  * Only for really core code.  See moduleparam.h for the normal way. 
  9.  * 
  10.  * Force the alignment so the compiler doesn't space elements of the 
  11.  * obs_kernel_param "array" too far apart in .init.setup. 
  12.  */  
  13. #define __setup_param(str, unique_id, fn, early)            \  
  14.     static const char __setup_str_##unique_id[] __initconst \  
  15.         __aligned(1) = str; \  
  16.     static struct obs_kernel_param __setup_##unique_id  \  
  17.         __used __section(.init.setup)           \  
  18.         __attribute__((aligned((sizeof(long)))))    \  
  19.         = { __setup_str_##unique_id, fn, early }  
  20.   
  21. #define __setup(str, fn)                    \  
  22.     __setup_param(str, fn, fn, 0)  
  23. /* NOTE: fn is as per module_param, not __setup!  Emits warning if fn 
  24.  * returns non-zero. */  
  25. #define early_param(str, fn)                    \  
  26.     __setup_param(str, fn, fn, 1)  

可以看出宏定义__setup以及early_param定义了obs_kernel_param结构体,该结构体存放参数和对应处理函数,存放在.init.setup段中。

可以想象,如果多个文件中调用该宏定义,在链接时就会根据链接顺序将定义的obs_kernel_param放到.init.setup段中。

console为例,在/kernel/printk.c中,如下:

[cpp] view plain copy
  1. static int __init console_setup(char *str)  
  2. {  
  3. .......  
  4. }  
  5. __setup("console=", console_setup);  

__setup宏定义展开,如下:

[cpp] view plain copy
  1. Static struct obs_kernel_param __setup_console_setup   
  2. __used_section(.init.setup) __attribute__((aligned((sizeof(long)))) = {  
  3. .name = “console=”,  
  4. .setup_func = console_setup,  
  5. .early = 0  
  6. }  

__setup_console_setup编译时就会链接到.init.setup段中,kernel运行时就会根据cmdline中的参数名与.init.setup段中obs_kernel_paramname对比。

匹配则调用console-setup来解析该参数,console_setup的参数就是cmdlineconsole的值,这是后面参数解析的大体过程了。

 

二 driver自定义参数

对于driver自定义参数,kernel留出rodata段一部分,叫__param,在arch/arm/kernel/vmlinux.lds中,如下:

[cpp] view plain copy
  1. __param : AT(ADDR(__param) - 0) { __start___param = .; *(__param) __stop___param = .; }  

该段放在.rodata段中。

那该段中存放的是什么样的数据呢?

Driver中使用module_param来注册参数,跟踪这个宏定义,最终就会找到对__param段的操作函数如下:

[cpp] view plain copy
  1. /* This is the fundamental function for registering boot/module 
  2.    parameters. */  
  3. #define __module_param_call(prefix, name, ops, arg, perm, level)    \  
  4.     /* Default value instead of permissions? */         \  
  5.     static int __param_perm_check_##name __attribute__((unused)) =  \  
  6.     BUILD_BUG_ON_ZERO((perm) < 0 || (perm) > 0777 || ((perm) & 2))  \  
  7.     + BUILD_BUG_ON_ZERO(sizeof(""prefix) > MAX_PARAM_PREFIX_LEN);   \  
  8.     static const char __param_str_##name[] = prefix #name;      \  
  9.     static struct kernel_param __moduleparam_const __param_##name   \  
  10.     __used                              \  
  11.     __attribute__ ((unused,__section__ ("__param"),aligned(sizeof(void *)))) \  
  12.     = { __param_str_##name, ops, perm, level, { arg } }  
  13. ........  
  14. #define module_param(name, type, perm)              \  
  15.     module_param_named(name, name, type, perm)  
  16.   
  17. #define module_param_named(name, value, type, perm)            \  
  18.     param_check_##type(name, &(value));                \  
  19.     module_param_cb(name, ¶m_ops_##type, &value, perm);        \  
  20.     __MODULE_PARM_TYPE(name, #type)  
  21.   
  22. #define module_param_cb(name, ops, arg, perm)                     \  
  23.     __module_param_call(MODULE_PARAM_PREFIX, name, ops, arg, perm, -1)  

driver/usb/gadget/serial.c中的use_acm为例,如下:

[cpp] view plain copy
  1. static bool use_acm = true;  
  2. module_param(use_acm, bool, 0);  

Module_param展开到__module_param_call,如下:

[cpp] view plain copy
  1. Static bool use_acm = true;  
  2. Param_check_bool(use_acm, &(use_acm));  
  3. __module_param_call(MODULE_PARAM_PREFIX, use_acm, ¶m_ops_bool, &(use_acm, 0, -1));  
  4. __MODULE_PARAM_TYPE(use_acm, bool);  

__module_param_call展开,可以看到是定义了结构体kernel_param,如下:

[cpp] view plain copy
  1. Static struct kernel_param __moduleparam_const __param_use_acm   
  2.  __used   __attribute__ ((unused,__section__ ("__param"),aligned(sizeof(void *)))) = {  
  3. .name = MODULE_PARAM_PREFIX#use_acm,  
  4. .ops = ¶m_ops_bool,  
  5. .Perm=0,  
  6. .level = -1.  
  7. .arg = &use_acm  
  8. }  

很清楚,跟.init.setup段一样,kernel链接时会根据链接顺序将定义的kernel_param放在__param段中。

Kernel_param3个成员变量需要注意:

(1)

ops=param_ops_bool,是kernel_param_ops结构体,定义如下:

[cpp] view plain copy
  1. struct kernel_param_ops param_ops_bool = {  
  2.     .set = param_set_bool,  
  3.     .get = param_get_bool,  
  4. };  

2个成员函数分别去设置和获取参数值

kernel/param.c中可以看到kernel默认支持的driver参数类型有bool byte short ushort int uint long ulong string(字符串) charp(字符串指针)array等。

对于默认支持的参数类型,param.c中提供了kernel_param_ops来处理相应类型的参数。

2

Arg = &use_acm,宏定义展开,可以看到arg中存放use_acm的地址。参数设置函数param_set_boolconst char *val, const struct kernel_param *kp

val值设置到kp->arg地址上,也就是改变了use_acm的值,从而到达传递参数的目的。

(3)

.name=MODULE_PARAM_PREFIX#use_acm,定义了该kernel_paramname

MODULE_PARAM_PREFIX非常重要,定义在include/linux/moduleparam.h中:

[cpp] view plain copy
  1. * You can override this manually, but generally this should match the  
  2.    module name. */  
  3. #ifdef MODULE  
  4. #define MODULE_PARAM_PREFIX /* empty */  
  5. #else  
  6. #define MODULE_PARAM_PREFIX KBUILD_MODNAME "."  
  7. #endif  

如果我们是模块编译(make modules),则MODULE_PARAM_PREFIXempty

在模块传参时,参数名为use_acm,如insmod g_serial.ko use_acm=0

正常编译kernelMODULE_PARAM_PREFIX为模块名+”.”

如果我们在传参时不知道自己的模块名是什么,可以在自己的驱动中加打印,将MODULE_PARAM_PREFIX打印出来,来确定自己驱动的模块名。

所以这里将serial.c编入kernel,根据driver/usb/gadget/Makefile,如下:

[cpp] view plain copy
  1. g_serial-y          := serial.o  
  2. ....  
  3. obj-$(CONFIG_USB_G_SERIAL)  += g_serial.o  

最终是生成g_serial.o,模块名为g_serial.ko.name = g_serial.use_acm

kernel传参时,该参数名为g_serial.use_acm

这样处理防止kernel下众多driver中出现重名的参数。

 

可以看出,对于module_param注册的参数,如果是kernel默认支持类型,kernel会提供参数处理函数。

如果不是kernel支持参数类型,则需要自己去实现param_ops##type了。

这个可以看drivers/video/uvesafb.c中的scroll参数的注册(又有点偏。。。无意间找到的)。

 

参数注册是在kernel编译链接时完成的(链接器将定义结构体放到.init.setup__param中)

接下来需要分析kernel启动时如何对传入的cmdline进行分析。


三 kernel对cmdline的解析

根据我之前写的博文可知,start_kernelsetup_arch中解析tags获取cmdline,拷贝到boot_command_line中。我们接着往下看start_kernel

调用setup_command_line,将cmdline拷贝2份,放在saved_command_line static_command_line

下面调用parse_early_param(),如下:

[cpp] view plain copy
  1. void __init parse_early_options(char *cmdline)  
  2. {  
  3.     parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param);  
  4. }  
  5.   
  6. /* Arch code calls this early on, or if not, just before other parsing. */  
  7. void __init parse_early_param(void)  
  8. {  
  9.     static __initdata int done = 0;  
  10.     static __initdata char tmp_cmdline[COMMAND_LINE_SIZE];  
  11.   
  12.     if (done)  
  13.         return;  
  14.   
  15.     /* All fall through to do_early_param. */  
  16.     strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);  
  17.     parse_early_options(tmp_cmdline);  
  18.     done = 1;  
  19. }  
  20. Parse_early_param拷贝cmdline到tmp_cmdline中一份,最终调用parse_args,如下:  
  21.   
  22. /* Args looks like "foo=bar,bar2 baz=fuz wiz". */  
  23. int parse_args(const char *name,  
  24.            char *args,  
  25.            const struct kernel_param *params,  
  26.            unsigned num,  
  27.            s16 min_level,  
  28.            s16 max_level,  
  29.            int (*unknown)(char *param, char *val))  
  30. {  
  31.     char *param, *val;  
  32.   
  33.     pr_debug("Parsing ARGS: %s\n", args);  
  34.   
  35.     /* Chew leading spaces */  
  36.     args = skip_spaces(args);  
  37.   
  38.     while (*args) {  
  39.         int ret;  
  40.         int irq_was_disabled;  
  41.   
  42.         args = next_arg(args, ¶m, &val);  
  43.         irq_was_disabled = irqs_disabled();  
  44.         ret = parse_one(param, val, params, num,  
  45.                 min_level, max_level, unknown);  
  46.         if (irq_was_disabled && !irqs_disabled()) {  
  47.             printk(KERN_WARNING "parse_args(): option '%s' enabled "  
  48.                     "irq's!\n", param);  
  49.         }  
  50.         switch (ret) {  
  51.         case -ENOENT:  
  52.             printk(KERN_ERR "%s: Unknown parameter `%s'\n",  
  53.                    name, param);  
  54.             return ret;  
  55.         case -ENOSPC:  
  56.             printk(KERN_ERR  
  57.                    "%s: `%s' too large for parameter `%s'\n",  
  58.                    name, val ?: "", param);  
  59.             return ret;  
  60.         case 0:  
  61.             break;  
  62.         default:  
  63.             printk(KERN_ERR  
  64.                    "%s: `%s' invalid for parameter `%s'\n",  
  65.                    name, val ?: "", param);  
  66.             return ret;  
  67.         }  
  68.     }  
  69.   
  70.     /* All parsed OK. */  
  71.     return 0;  
  72. }  
  73. .....  
  74. void __init parse_early_options(char *cmdline)  
  75. {  
  76.     parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param);  
  77. }  

Parse_args遍历cmdline,按照空格切割获取参数,对所有参数调用next_arg获取参数名param和参数值val。如console=ttyS0,115200,则param=consoleval=ttyS0,115200。调用parse_one。如下:

[cpp] view plain copy
  1. static int parse_one(char *param,  
  2.              char *val,  
  3.              const struct kernel_param *params,  
  4.              unsigned num_params,  
  5.              s16 min_level,  
  6.              s16 max_level,  
  7.              int (*handle_unknown)(char *param, char *val))  
  8. {  
  9.     unsigned int i;  
  10.     int err;  
  11.   
  12.     /* Find parameter */  
  13.     for (i = 0; i < num_params; i++) {  
  14.         if (parameq(param, params[i].name)) {  
  15.             if (params[i].level < min_level  
  16.                 || params[i].level > max_level)  
  17.                 return 0;  
  18.             /* No one handled NULL, so do it here. */  
  19.             if (!val && params[i].ops->set != param_set_bool  
  20.                 && params[i].ops->set != param_set_bint)  
  21.                 return -EINVAL;  
  22.             pr_debug("They are equal!  Calling %p\n",  
  23.                    params[i].ops->set);  
  24.             mutex_lock(¶m_lock);  
  25.             err = params[i].ops->set(val, ¶ms[i]);  
  26.             mutex_unlock(¶m_lock);  
  27.             return err;  
  28.         }  
  29.     }  
  30.   
  31.     if (handle_unknown) {  
  32.         pr_debug("Unknown argument: calling %p\n", handle_unknown);  
  33.         return handle_unknown(param, val);  
  34.     }  
  35.   
  36.     pr_debug("Unknown argument `%s'\n", param);  
  37.     return -ENOENT;  
  38. }  

由于从parse_early_options传入的num_params=0,所以parse_one是直接走的最后handle_unknown函数。该函数是由parse-early_options传入的do_early_param。如下:

[cpp] view plain copy
  1. static int __init do_early_param(char *param, char *val)  
  2. {  
  3.     const struct obs_kernel_param *p;  
  4.   
  5.     for (p = __setup_start; p < __setup_end; p++) {  
  6.         if ((p->early && parameq(param, p->str)) ||  
  7.             (strcmp(param, "console") == 0 &&  
  8.              strcmp(p->str, "earlycon") == 0)  
  9.         ) {  
  10.             if (p->setup_func(val) != 0)  
  11.                 printk(KERN_WARNING  
  12.                        "Malformed early option '%s'\n", param);  
  13.         }  
  14.     }  
  15.     /* We accept everything at this stage. */  
  16.     return 0;  
  17. }  

Do_early_param遍历.init.setup段,如果有obs_kernel_paramearly1,或cmdline中有console参数并且obs_kernel_paramearlycon参数,则会调用该obs_kernel_paramsetup函数来解析参数。

Do_early_param会对cmdline中优先级较高的参数进行解析。我翻了下kernel源码找到一个例子,就是arch/arm/kernel/early_printk.c,利用cmdline参数earlyprintk来注册最早的一个console,有兴趣大家可以参考下。

如果想kernel启动中尽早打印输出,方便调试,可以注册strearlyconobs_kernel_param

在其setup参数处理函数中register_console,注册一个早期的console,从而是printk信息正常打印,这个在后面我还会总结一篇kernel打印机制来说这个问题。

do_early_param是为kernel中需要尽早配置的功能(如earlyprintk  earlycon)做cmdline的解析。

Do_early_param就说道这里,该函数并没有处理我们经常使用的kernel通用参数和driver自定义参数。接着往下看。代码如下:

[cpp] view plain copy
  1. setup_arch(&command_line);  
  2. mm_init_owner(&init_mm, &init_task);  
  3. mm_init_cpumask(&init_mm);  
  4. setup_command_line(command_line);  
  5. setup_nr_cpu_ids();  
  6. setup_per_cpu_areas();  
  7. smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */  
  8.   
  9. build_all_zonelists(NULL);  
  10. page_alloc_init();  
  11.   
  12. printk(KERN_NOTICE "Kernel command line: %s\n", boot_command_line);  
  13. parse_early_param();  
  14. parse_args("Booting kernel", static_command_line, __start___param,  
  15.        __stop___param - __start___param,  
  16.        -1, -1, &unknown_bootoption);  

Parse_early_param结束后,start_kernel调用了parse_args。这次调用,不像parse_early_param中调用parse_args那样kernel_param指针都为NULL,而是指定了.__param段。

回到上面看parse_args函数,params参数为.__param段起始地址,numkernel_param个数。

Min_level,max_level都为-1.unknown=unknown_bootoption

Parse_args还是像之前那样,遍历cmdline,分割获取每个参数的paramval,对每个参数调用parse_one

回看Parse_one函数源码:

1parse_one首先会遍历.__param段中所有kernel_param,将其name与参数的param对比,同名则调用该kernel_param成员变量kernel_param_opsset方法来设置参数值。

联想前面讲driver自定义参数例子use_acm,cmdline中有参数g_serial.use_acm=0,则在parse_one中遍历匹配在serial.c中注册的__param_use_acm,调用param_ops_boolset函数,从而设置use_acm=0.

(2)如果parse_args传给parse_onekernel通用参数,如console=ttyS0,115200。则parse_one前面遍历.__param段不会找到匹配的kernel_param。就走到后面调用handle_unknown。就是parse_args传来的unknown_bootoption,代码如下: 

[cpp] view plain copy
  1. /* 
  2.  * Unknown boot options get handed to init, unless they look like 
  3.  * unused parameters (modprobe will find them in /proc/cmdline). 
  4.  */  
  5. static int __init unknown_bootoption(char *param, char *val)  
  6. {  
  7.     repair_env_string(param, val);  
  8.   
  9.     /* Handle obsolete-style parameters */  
  10.     if (obsolete_checksetup(param))  
  11.         return 0;  
  12.   
  13.     /* Unused module parameter. */  
  14.     if (strchr(param, '.') && (!val || strchr(param, '.') < val))  
  15.         return 0;  
  16.   
  17.     if (panic_later)  
  18.         return 0;  
  19.   
  20.     if (val) {  
  21.         /* Environment option */  
  22.         unsigned int i;  
  23.         for (i = 0; envp_init[i]; i++) {  
  24.             if (i == MAX_INIT_ENVS) {  
  25.                 panic_later = "Too many boot env vars at `%s'";  
  26.                 panic_param = param;  
  27.             }  
  28.             if (!strncmp(param, envp_init[i], val - param))  
  29.                 break;  
  30.         }  
  31.         envp_init[i] = param;  
  32.     } else {</span>  
[cpp] view plain copy
  1. <span style="font-size:14px;">        /* Command line option */  
  2.         unsigned int i;  
  3.         for (i = 0; argv_init[i]; i++) {  
  4.             if (i == MAX_INIT_ARGS) {  
  5.                 panic_later = "Too many boot init vars at `%s'";  
  6.                 panic_param = param;  
  7.             }  
  8.         }  
  9.         argv_init[i] = param;  
  10.     }  
  11.     return 0;  
  12. }  

首先repair_env_string会将param val重新组合为param=val形式。

Obsolete_checksetup则遍历-init_setup段所有obs_kernel_param,如有param->strparam匹配,则调用param_>setup进行参数值配置。

这里需要注意的一点是repair_env_stringparam重新拼成了param=val形式。后面遍历匹配都是匹配的”param=”而不是“param”

如之前分析kernel通用参数所举例子,__setup(“console=”, console_setup)

Console=ttyS0115200,obsolete_checksetup是匹配前面console=,如果匹配,则跳过console=,获取到其值ttyS0,115200,调用其具体的setup函数来解析设置参数值。

可以想象,parse_one对于parse_args传来的每一个cmdline参数都会将.__param以及-init.setup段遍历匹配,匹配到strname一致,则调用其相应的setsetup函数进行参数值解析或设置。

Start_kernelParse_args结束,kernelcmdline就解析完成!

 

总结下kernel的参数解析:

1kernel编译链接,利用.__param .init.setup段将kernel所需参数(driver及通用)和对应处理函数的映射表(obs_kernel_param  kernel_param结构体)存放起来。

2Kernel启动,do_early_param处理kernel早期使用的参数(如earlyprintk earlycon

(3)parse_argscmdline每个参数都遍历__param .init.setup进行匹配,匹配成功,则调用对应处理函数进行参数值的解析和设置。


还有一点很值得思考,kernel下对于这种映射处理函数表方式还有很多使用。比如之前博文中uboot传参给kernel,kernel对于不同tags的处理函数也是以该种方式来映射的。

kernel下driver私有结构体的回调处理函数也有这个思想哇!


原创粉丝点击