Linux Device Drivers Part 2 | Writing your first kernel module!
17 November 2013 By Bhavyanshu Parasher
In this tutorial, i am gonna write a very basic code in C for a very basic kernel module. Then I will show you the compiling and running process for the module we will create.
Now is the time to learn about MAKE file. The kernel hackers have developed a make file default syntax so that they can compile the kernel from outside the kernel source tree. You should use the following lines of code.
Testing : insmod & rmmod utils
Now to test the module we can use insmod and rmmod utilities. For this you need to be a superuser.
insmod ./mymodule.ko & it will show the output as in the first printk statement. Next use
rmmod mymodule & it will output the statement in the second printk. In case you are running linux using virtual system, you may not see any output. The messages go to /var/log/messages.
#Compiling & Loading A Module
We must make sure we have the right versions for tools in order to compile a kernel module without any failures. For this we can use Documentation/Changes in the kernel docs directory.
Look at the default makefile. This is an extended syntax GNU make syntax. Basically the above make file checks whether the KERNELRELEASE variable has been set or not. But do note that the above makefile is not complete. The complete makefile usually includes other stuff like cleaning up unneeded files and installing modules info.
After the module is built using make command, the next thing to do is to load it into the kernel. Just like we used insmod and rmmod, we can enhance the loading process. Another utility similar to insmod, called modprobe loads a module into the kernel. It differs in that it will look at the module to be loaded to see whether it references any symbols that are not currently defined in the kernel. If found, it looks for such modules in the path. If we use insmod in such case, it gives an error stating unresolved symbols.
This is it for the second part. I will write up the third part soon. It will consist of theory and details about insmod, kernel symbol table & platform dependencies. Thanks for being patient. Happy kernel hacking!
blog comments powered by Disqus