Some things before you start:-
- check you kernel version => uname -r
- you will get an version name and local version. e.g.... (3.2.0-4-amd64)
- then search for your source tree ... it should be in /usr/src/ ... if not found there
- download you Linux source tree with exact version . in my case it will be Linux 3.2.0. Google it and you will get a zip file. Extract it under the folder /usr/src/
- now you need to run some commands
- first go into the kernel source directory then follow these steps
- make menuconfig (if you want to customise your kernel)
- make -j<number of cpus>
- make install
- make modules_install
- Now your kernel is ready
For more digging on above section go to "http://unix.stackexchange.com/questions/20864/what-happens-in-each-step-of-the-linux-kernel-building-process" . This will help you.
Here it starts:-
- You need two things first is your driver code(c file) and next is Makefile.
- This is a hello world program for kernel. Save it in hello.c
#include <linux/module.h>
#include <linux/kernel.h>
int init_module(void) //this function runs when your module is loaded
{
printk("Hello world");
return 0;
}
void cleanup_module(void) //this function runs when your module is unloaded
{
printk("Goodbye world \n");
}
MODULE_LICENSE("GPL"); //compulsory part in every driver code
- Now in Makefile .... be sure to name the file as Makefile (capital M don't forget):-
obj-m := hello.o //same as your module name with an .o extension
- Something you must not do:-
- compile the program to get (.o) . Makefile will take care of that.
- Now write this command on the terminal.
make -C /usr/src/"your Linux version" M=`pwd` modules
- If every thing goes write then you will see 6 files generated . You can inspect all of them and dig them vigorously . The file which is of your use is the one with .ko extension. it is a dynamic loadable module. go and read about it !!
- Since you have a dynamic module its time you load it !! Here is the command
- insmod <dynamic module>
- you might require root privileges so use sudo
- open dmesg and check whether all you wrote in the printk is there or not. you can use grep to find it . dmesg is the kernel ring buffer which gives us the details provided by the kernel messages.
- Since you have loaded it now its time to remove it.
- rmmod <dynamic module>
- This is it !! you have created a kernel module.
- Amount of efforts put in to write a hello world for kernel is high but if you love hardware then this is how it is going to be !!
No comments:
Post a Comment