Pass Parameters To Kernel Module

Leave a comment

In previous tutorial we learned how to write a basic kernel module for Linux. This tutorial will explain how we can pass parameters to kernel module using command line arguments. This writing is greatly inspired by The Linux Kernel Module Programming Guide, a great book for device driver developers.


Passing command line arguments are very common for user space program. But what is the use of doing so for kernel module? One use might be to activate or deactivate an end-point(we’ll learn about end-points later) of a hardware interface. For example consider some hardware interface with two end-points. We want to select only one end-point for sending/receiving data. During module installation we want to define which end-point to be used. We can pass that information as a command line argument.

 To pass parameters to kernel module, we’ve to use the module_param() macro. This macro takes two parameters with the format module_param(VAR_NAME, VAR_TYPE, PERMISSION)VAR_NAME is the name of the variable which will take the command line argument and VAR_TYPE is the type of the variable and PERMISSION is for permissions of the corresponding file in sysfs. Look at the typical usage scenario of this module_param().

int endPointAddress = 0;
module_param(endPointAddress, int, 0);

 It is a good practice to put the variable declaration and the module_param() macro at the beginning of the code. Let’s modify the test_module.c module written in our previous tutorial.

#include <linux/module.h>

int endPointAddress = 5;
module_param(endPointAddress, int, 0);


static int test_module_init(void)
{
    printk("Test Module Installedn")
	printk("endPointAddress = %dn", endPointAddress);

    return 0;
}

static void test_module_exit(void)
{
    printk("Test Module Removedn")
}

module_init(test_module_init);
module_exit(test_module_exit);

MODULE_AUTHOR("IsonProjects");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Kernel Module");

Now build the binary using make command. I’m assuming you know how to write Makefile and build the source using Makefile. If you don’t know, you should check the Writing Kernel Module guide.

Now install the generated .ko file using the command 

sudo insmod test_module.ko endPointAddress=100

Here we are passing a value of 100 to the endPointAddress during the module installation. So dmesg command will show following output in the terminal.

Test Module Installed
endPointAddress = 100

If we don’t pass any value during module installation, it’ll display default value which is 5 in our above code.

Same way we can pass character string to a kernel module as below

char* testString = "abcd";
module_param(testString, charp, 0);

 

Leave a Reply