world leader in high performance signal processing
Trace: » parameters

Kernel Module Parameters

A Kernel Module Parameter is an effective way of defining variables within a module that can be altered at load time without the need to recompile the module. The sysfs filesystem also gives us an easy means of adjusting these parameters while the system is running.

Kernel Code

A parameter used to be defined using the MODULE_PARM macro. Apart from missing an A in PARAM, this macro was restricted in what you could do when setting up a variable to be used.

Now a new way of setting up a module parameter is to use a new macro:

module_param(name, type, perm)

  • name is the variable name
  • type defines the variable type which can now be “user defined”.
  • perm controls the visibility and access of the param in sysfs

A code example helps:

#include <linux/module.h>
 
/* define the parameter */
static int debug;
 
/* use this to turn it into a param */
module_param(debug, int, S_IRUGO | S_IWUSR);

Controlling Value

Userspace

Look at the file system entry:

root> ls /sys/module/mymodule/parameters
debug

Set the value

root> echo 23 -n > /sys/module/mymodule/parameters/debug 

Inspect the value

root> cat /sys/module/mymodule/parameters/debug
23

This is a very useful way to add the ability to modify module behavior both at load and run time.

Kernel Command line

If this module is statically compiled into the kernel then the parameter is still available as a boot time option in the kernel command line.

mymodule.test=OFF
<module name>.<parametername>=<value>

User Defined Parameter Types

You can also create your own variable types. To do this you need to define functions to allow the module loader to understand how to parse and present the data in the parameter.

Lets call a type newtype

The three functions that need to be defined are:

  • param_set_newtype - parse the string to set the type
  • param_get_newtype - show the meaning of the param structure as a string
  • param_check_newtype - check the variable type

A small code example may help:

struct newtype {
    int test;
    int val;
};
 
#define param_check_newtype(name, p)__param_check(name, p, newtype)
 
int param_set_newtype(const char * val, struct kernel_param *par ) {
     struct newtype * nt = (struct newtype *) par;
     if (strncmp(val,"on",2)==0) {
        nt->test = 1;
     } else if (strncmp(val,"off",3) {
        nt->test = 2;
     } else {
         nt->test = 0;
     }
     return 0;
}
 
int param_get_newtype(char * buf, struct kernel_param *par ) {
     struct newtype * nt = (struct newtype *) par;
     int len = 0;
 
     switch ( nt->test ) {
        case 1:
           len += sprintf(buf,"ON");
           break;
        case 2:
           len += sprintf(buf,"Off");
           break;
        default:
           len += sprintf(buf,"DUNNO?");
           break;
      }
      return len;
}
 
struct newtype mypar;
 
module_param(mypar, newtype, 0664);