Overview
- What is Linux loadable kernel module(LKM)?
A loadable kernel module (LKM) is a mechanism for adding/removing code from Linux kernel at run time. Many of device drivers are implemented through this way, otherwise the monolithic kernel would be too large.
LKM communicates with user-space applications through system calls, and it can access almost all the objects/services of the kernel. LKM can be inserted to the monolithic kernel at any time – usually at booting or running phase.
Writing LKM has many advantages against directly tweaking the whole kernel. For LKM can be dynamically inserted or removed at run time, we don’t need to recompile the whole kernel nor reboot, and it’s more shippable.
So, the easiest way to start kernel programming is to write a module - a piece of code that can be dynamically loaded into the kernel.
- How is the LKM different from an user-space application?
LKM is run in kernel space, which is quite different.
First off, the code is always asynchronous, which means it doesn’t execute sequentially and may be interrupted at any time. Thus programmers should always care about the concurrency as well as reentrant issues. Unlike user-space application, which has an entry-point like main()
and then execute and exit, the LKM is more like a complicated event-driven server that internally has the ability to interact with various kernel services, and externally provides system calls as its user-space api
.
Secondly, there’s only a fixed and small stack, resource cleanup as well as utilization should always be highly considered. While as for the user-space application, the resource quota is fairly sufficient.
Thirdly, note that there’s no floating-point math.
Prepare Headers
1 2 3 |
|
Simple Module Code
hello.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
pr_info is a more convenient way of debugging, comparing to the old-style printk.
1
|
|
Makefile
1 2 3 4 5 6 |
|
Build && Install
Now we can make
our hello module and then a hello.ko emerged successfully.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Display module info
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 |
|
we can watch the log by tail -f
the /var/log/kern.log or just dmesg
1 2 3 4 |
|
Done!
note: char parm can even be Chinese.
Conclusions
With this article, we managed to complete our first yet very simple Linux loadable kernel module(LKM).
We’ve got a broad view of how the LKMs work. And we should configure our own kernel modules, build and insert/remove them at runtime, and define/pass custom parameters to them.