Saturday 13 February 2016

How to Create, Compile and Load Linux Loadable Kernel Module



  • ·         What is kernel module?
Kernel module is a simple C program. Which can be loaded and unloaded into the kernel upon demand.
They extend the functionality of the kernel without the need to reboot the system.
  • ·         What is the difference between Normal C program and kernel module 

Normal C program
Kernel module
1. Written in .c file and after compiling become an .exe file (Executable).
1. Written in .c file and after compiling become a .ko file (Kernel Object).
2. Run in own address space and whole process is a separate process.
2. Run in kernel's address space and become a part of kernel.
3. There is lots of priorities
3. It is become a part of kernel so no priority
4. Address is not fixed for running in whole RAM
4. Address is fixed for running in whole RAM
5. After terminating a process address  will remove
5. After rmmod address will not remove
6. Many scheduling algorithms is available for this process.
6. After insmod execution is directly start so no need to scheduling algorithm.
7. There is many permission needed to access a normal resource.
7.There is no permission needed to access a any resource.
8. Insufficient memory error can be occur
8. Running address is fixed so no any error occur regarding memory
9. No need a licence for writing a normal c program.
9. Need a licence for writing a kernel module (any one can have it)
10. Demand paging and swapping is available
10. Whole module is loaded in RAM, so no need
11. Used CPU's bit for storing a result
11. Used kernel's flag for storing a result.
12. .exe is only OS depended
12. .ko is OS as well as Version of OS dependent
13. Two processes can share a one resource
13. Two module can’t share one resource.
14. Any exception is occur then process will crash
14. Any exception is occur then kernel will crash
 


  • ·         There are two thing needed to writing kernel module

1. Normal .c file:-
                        This file has a main code/logic of our kernel module
2. Makefile:-
                        This file is only used for compiling a kernel module

-------------------------------------------C file-------------------------------------------
 




01        #include<linux/module.h>
02        #include<linux/kernel.h>
03        #define DRIVER_AUTHOR "Ashutosh Jagtap"
04        #define DRIVER_DESC "This is a Demo Module"
05
06        int init_module(void)
07        {
08                    printk(KERN_INFO "TEST : WELCOME ASHUTOSH  \n",);
09                    return 0;
10        }
11
12        void cleanup_module(void)
13        {
14                    printk(KERN_INFO "TEST : GOOD BY ASHUTOSH \n");
15        }
16
17        MODULE_LICENSE("GPL");
18        MODULE_AUTHOR(DRIVER_AUTHOR);
19        MODULE_DESCRIPTION(DRIVER_DESC);


Description:-

Line 1:-
            Flag which are used in our module.
            Init and cleanup prototype in our module

Line 2:-
            This header file has predefine symbols which are needed on the fly.

Line 3:-define a macro for specifying our author

Line 4:-define a macro for specifying our description

Line 6:- This function is automatically invoked after firing insmod command
                        Ex. sudo insmod hello.ko
                        sudo means Super User Do
                        For inserting a module into kernel we have to have super user permission.
                                                                                                                              
After insmod command our .ko file loaded inside a kernel's address space at specific address.
After invoking this function name of our kernel module is written inside list of kernel’s module
Ex.
1. Inside /proc/modules file
2. Hit lsmod (List Modules) command
            At the beginning of the list you will see our module name.
Actually init_module() is used for initialization activity but we are not doing this because this is our demo module.
Line 8:- kernel module can’t interact with user for input / output but kernel module can maintain the log.
printk() is used to the data into kernel log file. Which is store at /var/log/syslog.
This file is automatically crated when boot our machine.
printk() is a variable no of argument function in which 1st argument should be a macro for printing our data at priority.
            2Nd is message which we want to print.

Line 9:- init_module function return a integer value if return 0 the indicate the success
                        If return any negative or -1 value then internal problem is occur.
            This return value is not use for our program but the corresponding error display in kernel log file.

Line 12:-
             cleanup_module is a function which gets implicitly called at the time of removing the module from memory.
            When we fire rmmod (remove module) command then internally this function will invoked.
              Ex. sudo rmmod hello
             Generally this function is used to de-allocate the resources which is allocated at  init_module()

 ------------------------------------Makefile-------------------------


obj-m += hello.o

all:
            make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
            make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

---------------------------------------------------------------------------------
                       
·         Steps to create Linux Loadable Kernel Module

Step 1:- install gcc

Step 2:- before writing any kernel module we have to check require headers for our linux.
 If not available then download it.
By using apt-get

sudo apt-get install build-essential linux-hearders-$(uname-r)

Step 3:- create folder and create two new files in that folder
            1] .C file. Source code of our kernel module
            2] Makefile which is used to build our kernel module
Note -I created this folder at desktop because desktop has all permission (Read, Write and Execute)
Step 4:-write a source code of kernel module (copy above code)

Step 5:-write a make file (copy above code)

Step 6:- go to the above folder which is created at Step 3 using command prompt and run make utility using Make command


Step 7:- if any error in our make file and c file then we have to solve this.

Step 8:- after making error free code then we get .ko and .o file in our current directory


Step 9:- we can check the information of our kernel object by using the command
            modinfo hello.ko
            If srcversion: is blank then something happened wrong with our module then fix it.



Step 10:- before inserting a module we are opening a syslog file using tail command.(on different terminal)
                        Ex. sudo tail –f /var/log/syslog
            This command will show last 10 lines of syslog file.
            Syslog file contain an our prink() functions output.
printk() function print into syslog file.


Step 11:-after getting .ko file we are ready to insert our module inside kernel using the command
                        sudo insmod hello.ko
                        Now our kernel module inside a kernel image.


Step 12:- if you want to know is your kernel module successfully insert or not then used lsmod                command.



Step 13:- After inserting the module init_module() function will call automatically if the function contain printk() for writing into a log file. To get the contain of kernel log file reside into (/var/log/syslog) use dmesg (device message) command. 
Note- we are not using dmesg because using this command very difficult to find our output.

Step 14:-Now we have to remove our kernel module form kernel's image using sudo rmmod hello command. No need to .ko extension

 





After removing the our kernel module cleanup_module() function will call automatically if the function
 contain printk() for writing into a log file. To get the contains of kernel log file reside into
 (/var/log/syslog) use dmesg command.




Step 15:  if you want to know is your kernel module successfully remove or not then used lsmod  command.


                                          Thanks for reading....



                                                                                      -Created By Ashutosh Jagtap
                                                                             For any grievance kindly mail me on
                                                                               ashujagtap333@gmail.com