Part 8 · 1 chapters · ~8 min
Modules and Drivers
Loadable kernel modules, a hello-world module, Kbuild, modprobe and dependencies, character devices and file operations, the device model and sysfs, interrupts and DMA in drivers, kernel coding rules (no floating point, small stacks, locking), signing, the lack of a stable internal API, and Rust in the kernel.
9
A minimal module and a character device
code
// hello.c
#include <linux/module.h>
#include <linux/init.h>
static int __init hello_init(void) { pr_info("hello: loaded\n"); return 0; }
static void __exit hello_exit(void) { pr_info("hello: unloaded\n"); }
module_init(hello_init); module_exit(hello_exit);
MODULE_LICENSE("GPL");
# Makefile
obj-m += hello.o
all: ; make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
sudo insmod hello.ko && dmesg | tail -1 && sudo rmmod hello # Linux only, in a VMKernel coding rules: no libc and no floating point; small fixed-size kernel stacks (16 KB on x86-64); never sleep while holding a spinlock or in interrupt context; handle every allocation failure. Rust for Linux has been merged since 6.1 for writing drivers with memory safety, with a growing set of Rust drivers upstream. Practise in a VM: a module bug can take down the machine.
A KERNEL MODULE'S LIFE
build, load, run, unload
swipe the figure sideways, or tap expand for full screen
1/4
a module
A loadable module is kernel code linked in at run time: it runs with full privilege, and a bug can crash the whole machine.
kernel code at run timefull privilege, no safety net