Saturday, September 4, 2010

How to build kernel module + How to develop kernel module + How to create kernel module?

Guys,

I developed a small program called hello.c and called some kernel functions in it. Here are the steps those I followed :

========
1. yum install kernel-headers-$(uname -r)
2. vi hello.c and add the following codes :
-----
#include "linux/module.h"
#include "linux/kernel.h"
int init_module(void)
{
printk(KERN_INFO "init_module() called\n");
return 0;
}

void cleanup_module(void)
{
printk(KERN_INFO "cleanup_module() called\n");
}
-----

3. vi Makefile and add the following lines :

-----
obj-m += hello.o

all:
make -C /lib/modules/2.6.18-194.8.1.el5/build/ M=$(PWD) modules

clean:
make -C /lib/modules/2.6.18-194.8.1.el5/build/ M=$(PWD) clean
-----
Note : Replace the version here. -C option is used to use the Makefile which has inside the "build" directory.

4. make //To create object files like .o and .ko. PT: ./configure is not needed since basic function of ./configure is to check the existence of header files and to create the Makefile and setup rules in those files. Here we have manually created the file and put the rules.

5. List of created object files after executing "make" command :

-----
root@server [~/test]# ls
./ hello.c .hello.ko.cmd hello.mod.o hello.o Makefile Module.symvers
../ hello.ko hello.mod.c .hello.mod.o.cmd .hello.o.cmd Module.markers .tmp_versions/
root@server [~/test]#

Example(O/P) :-
root@server [~/test]#make
make -C /lib/modules/2.6.18-194.8.1.el5/build/ M=/root/test modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-194.8.1.el5-i686'
CC [M] /root/test/hello.o
Building modules, stage 2.
MODPOST
CC /root/test/hello.mod.o
LD [M] /root/test/hello.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-194.8.1.el5-i686'
-----

6. root@server [~/test]# modinfo hello.ko //To get the details of the module
filename: hello.ko
srcversion: 4F856ABA1F3290D5F81D961
depends:
vermagic: 2.6.18-194.8.1.el5 SMP mod_unload 686 REGPARM 4KSTACKS gcc-4.1
root@server [~/test]#

7. Load module : insmod hello.ko
example :
root@server [~/test]# insmod hello.ko

8. Check whether it has loaded or not : lsmod | grep hello
example :
root@server [~/test]# lsmod | grep hello
hello 5504 0
root@server [~/test]#

9. Remove the module : rmmod hello
Ex :
root@server [~/test]# rmmod hello

10. Check the log :

root@server [~/test]# tail -2 /var/log/messages
Sep 4 19:28:20 server kernel: init_module() called
Sep 4 19:28:28 server kernel: cleanup_module() called
root@server [~/test]#
========

That's it. Try :)

No comments:

Post a Comment