Passing command line Arguments / Parameters to Linux kernel module

In Our previous post, “Writing first Linux kernel Module and understanding Kernel module compilation, loading and unloading” We learned how to write a simple Linux kernel module.

Lets see an example of how to pass the loading time parameters to the kernel module. The load time parameter passing is very helpful to enable / disable some code in runtime without recompiling the module. Lets say, we want to enable some debugging information to debug our driver, we can pass a flag like “enable_debug=1” during insmod / modprobe to enable that respective code, check the below code,

 vim hello.c 
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
static int enable_debug;
module_param(enable_debug, int , 0);
MODULE_PARM_DESC(enable_debug, “A 0/1 flag for enable debugging in loadtime”);
static int __init hello_init(void) { printk(KERN_INFO “Hello, world\n”); if(enable_debug) printk(KERN_INFO “Enabling debugging in driver…\n”); return 0;
static void __exit hello_exit(void) { printk(KERN_INFO “Goodbye, world\n”);
MODULE_DESCRIPTION(“Hello World Example”);

In this code, check the highlighted code, the code is very self explanatory, it sets/ unsets a flag to be used to make necessary decision in runtime to enable or disable debugging.

 $ make 
 $ insmod ./hello.ko enable_debug=1 

In dmesg, it will print the following message, indicating it has enbled debugging,

 $ dmesg
[ 2864.782079] hello: module verification failed: signature and/or required key missing - tainting kernel
[ 2864.782529] Hello, world
[ 2864.782536] Enabling debugging in driver...

We will see what is verification warning later.

READ  Understanding execution of very minimal C program in Linux / Ubuntu - Part 2

Now, check the modinfo of this module as,

 $ modinfo hello.ko
filename: /home/devbee/devlab/module/hello.kolicense: GPLdescription: Hello World Exampleauthor: DEVBEEsrcversion: 4EAF61EDA9E7BFB11A04EDF
vermagic: 3.19.0-30-generic SMP mod_unload modversions 686parm: enable_debug:A 0/1 flag for enable debugging in loadtime (int)

Above highlighted information can be corelated with the source.

More Read – Check TLDP

Leave a Reply

Your email address will not be published. Required fields are marked *