Device drivers: writing a kernel module
Code that handles hardware inside the kernel. From the simplest module to the structure of a platform driver and an I2C driver.
The simplest kernel module
#include <linux/module.h>
static int __init hello_init(void) { pr_info("hello\n"); return 0; }
static void __exit hello_exit(void) { pr_info("bye\n"); }
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
Load it with insmod hello.ko, check with dmesg, and unload it with rmmod hello.
The driver model
| Concept | Meaning |
|---|---|
| Bus | platform, i2c, spi, usb |
| Device | A device listed in the device tree |
| Driver | probe() is called when compatible matches |
For an I2C sensor driver, probe() initialises the registers and creates the interface that shows values to user space (sysfs attributes, IIO, hwmon, a character device).
Differences from MCU code
- A crash in the kernel takes down the whole board (kernel panic).
- Floating point is restricted, and the stack is small (a few KB)
- Register access is through
ioremapandreadl/writel; I2C through subsystem APIs such asi2c_smbus_read_byte_data - Interrupt handling is split into a top half (fast handling) and a bottom half (threads, work queues)
Look first
Most common chips already have a driver in the mainline kernel. Often all you need is the right device tree.