Linux Kernel Module (LKM)¶
Overview¶
A Linux Kernel Module (LKM) is a piece of code that can be dynamically loaded into the kernel.
It allows extending kernel functionality without rebuilding the kernel.
Why Kernel Modules?¶
- Add device drivers
- Extend kernel features
- Debug kernel behavior
Kernel Space vs User Space¶
| Type | Description |
|---|---|
| User Space | Applications |
| Kernel Space | Core OS + drivers |
Kernel modules run in kernel space.
Basic Structure¶
Minimal example:
#include <linux/module.h>
#include <linux/kernel.h>
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, Kernel Module Loaded!\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, Kernel Module Unloaded!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
Build System¶
Makefile:
obj-m += hello.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
Build Output¶
After compilation:
.ko→ kernel object (module).o,.mod.c,.symvers→ build artifacts
Load / Unload Module¶
Load module:
Unload module:
Check Module Status¶
Kernel Logging¶
Use printk instead of printf.
View logs:
Important Notes¶
1. No standard C library¶
- No
printf - No
malloc(usekmalloc)
2. Kernel crash risk¶
- Bugs can crash the entire system
- No memory protection like user space
3. Licensing¶
Required to avoid kernel warnings.
Summary¶
- Kernel modules extend kernel dynamically
.kofiles are loadable modulesprintkis used for debugging- Runs with highest privilege
Next Step¶
- Character device driver
- file_operations
- User ↔ Kernel communication