The “Hello world” driver: loading and removing the driver in kernel space
When a module device driver is loaded into the kernel, some preliminary tasks are usually performed like resetting the device, reserving RAM, reserving interrupts, and reserving input/output ports, etc.These tasks are performed, in kernel space, by two functions which need to be present (and explicitly declared):
module_init
and module_exit
; they correspond to the user space commands insmod
and rmmod
, which are used when installing or removing a module. To sum up, the user commands insmod
and rmmod
use the kernel space functions module_init
and module_exit
.Let’s see a practical example with the classic program
Hello world
:=
#include // here linux/init.hThe actual functions
#include // here linux/module.h
#include // linux/kernel.h
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void) {
printk("<1> Hello world!\n");
return 0;
}
static void hello_exit(void) {
printk("<1> Bye, cruel world\n");
}
module_init(hello_init);
module_exit(hello_exit);
hello_init
and hello_exit
can be given any name desired. However, in order for them to be identified as the corresponding loading and removing functions, they have to be passed as parameters to the functions module_init
and module_exit
.The
printk
function has also been introduced. It is very similar to the well known printf
apart from the fact that it only works inside the kernel. The <1>
symbol shows the high priority of the message (low number). In this way, besides getting the message in the kernel system log files, you should also receive this message in the system console.This module can be compiled using the same command as before, after adding its name into the Makefile.
=
obj-m := nothing.o hello.oIn the rest of the article, I have left the Makefiles as an exercise for the reader. A complete Makefile that will compile all of the modules of this tutorial is shown in Appendix A.
When the module is loaded or removed, the messages that were written in the
printk
statement will be displayed in the system console. If these messages do not appear in the console, you can view them by issuing the dmesg
command or by looking at the system log file with cat /var/log/syslog
.Table 4 shows these two new functions.
Events | User functions | Kernel functions |
Load module | insmod | module_init() |
Open device | ||
Read device | ||
Write device | ||
Close device | ||
Remove module | rmmod | module_exit() |
The complete driver “memory”: initial part of the driver
I’ll now show how to build a complete device driver:memory.c
. This device will allow a character to be read from or written into it. This device, while normally not very useful, provides a very illustrative example since it is a complete driver; it’s also easy to implement, since it doesn’t interface to a real hardware device (besides the computer itself).
0 nhận xét:
Đăng nhận xét