What a kernel module is and how it thinks
2 min readThe previous lesson showed a minimal module loading in QEMU. This one takes the same idea apart and builds it properly. A a relocatable .ko object file that the running kernel links into itself at run time and can later remove is the unit of a device driver on a modular kernel. Understanding its contract matters more than memorising its syntax.
Where an application starts at main, does a task, and exits, a module runs an the function registered with module_init, called once when the module loads, which must register the module's facilities and return 0 on success and then returns immediately. From that moment the module is passive: the kernel calls its functions only through whatever it registered, such as a set of file operations that a later lesson covers. When the module is removed, its exit function runs and must undo every registration.
That asymmetry is the whole discipline. The init function says "here is what I offer"; the exit function says "I am gone, forget me". An application that exits can be lazy and let the operating system reclaim its memory. A module cannot: if the exit function forgets a registration, the kernel keeps pointers to code that has been freed, and the next use of that pointer is an oops or worse. Every line of init has a matching line of exit, in reverse order.
Why bother with modules at all, when a driver can be compiled into the kernel image? The answer is partly development speed and partly product design. Rebuilding and rebooting for every driver change is slow; loading a fresh .ko takes milliseconds. On a production device the reasons are about resources.
An embedded board has a fixed flash budget. A base kernel with the drivers for a dozen possible peripherals built in wastes space for every board that uses only three of them. A modular kernel boots a small core image and loads only the drivers this product needs, and a board with a different sensor stack loads a different set of modules from the same kernel. Keep in mind the trade-off: modules need a root filesystem with the .ko files and the module tools present, which a tiny initramfs may not carry.
Entry points, section attributes and the metadata macros
3 min readThe complete skeleton for this lesson's working module is below. The functions can be named anything; the macros are what make them entry points.
#include <linux/init.h>
#include <linux/module.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");
MODULE_AUTHOR("learner");
MODULE_DESCRIPTION("First parameterised module");
MODULE_VERSION("1.0");
The init function returns int and takes no arguments. Returning 0 means success; anything else means failure and aborts the load. The exit function returns void. Both are static because nothing outside the file calls them directly. MODULE_AUTHOR, MODULE_DESCRIPTION and MODULE_VERSION are documentation written into the object file; modinfo prints them. Kernel checkpatch now expects a MODULE_DESCRIPTION on every new module.
The two markers before the functions deserve attention. __init and __exit are section attributes, macros that expand to a compiler placement such as __section(".init.text"). __initdata does the same for data. A function marked __init is placed in a dedicated ELF section, .init.text, separate from ordinary code.
The purpose is memory. Built-in initialisation code runs once at boot and is never needed again, so the kernel frees the entire .init.text and .init.data regions afterwards and hands the pages back to the allocator. For a loadable module, the section is dropped after insmod completes. The rule follows from this: never mark with __init any function or data you might touch after initialisation. __exit marks code needed only at unload; when the module is built into the kernel, or when CONFIG_MODULE_UNLOAD is off, that section is discarded entirely.
Copy: the loader reads the
.koand copies its code and data into kernel memory.Verify: the module's version magic and build options are checked against the running kernel.
Link: unresolved symbols in the module are bound to kernel and module exports.
Init: the function named by
module_initruns and registers the module's facilities.Free init: the
.init.textsection is dropped now that it has done its job.List: the module appears in
/proc/modulesand/sys/module.
Going deeperWhere .init.text goes at boot
The discarding happens in free_initmem() in init/main.c, which walks the init region recorded by the architecture's linker script (arch/x86/kernel/vmlinux.lds.S and its arm64 equivalent). The pages are returned to the buddy allocator, which is why after boot you can see "Freeing unused kernel memory" messages in dmesg. A driver that wrongly stores an __init function pointer and calls it later dereferences freed memory; the symptom is a crash whose address is inside the former init range.
Module parameters: making a module configurable
4 min readDrivers differ from board to board: an I/O base address, a poll interval, a debug flag. Recompiling for each value is wasteful, so the kernel provides a global variable declared with module_param, settable on the insmod or modprobe command line and optionally exposed as a sysfs file.
The macro lives in <linux/moduleparam.h> and takes three arguments: the variable name, its type, and a permission mask.
static char *who = "world";
static int count = 1;
static bool debug;
static unsigned long delay_ms = 100;
module_param(who, charp, 0644);
module_param(count, int, 0644);
module_param(debug, bool, 0600);
module_param(delay_ms, ulong, 0444);
MODULE_PARM_DESC(who, "who to greet");
MODULE_PARM_DESC(count, "how many times to greet");
MODULE_PARM_DESC(debug, "enable extra diagnostics");
MODULE_PARM_DESC(delay_ms, "delay between greetings, read-only");
The type must match the variable's C type. The supported names are byte, short, ushort, int, uint, long, ulong, charp, bool and invbool. charp is a char *; the kernel duplicates the string you pass and points the variable at the copy. bool maps to a bool variable and accepts values such as 1/0, y/n and on/off. invbool stores the inverted value. The delay_ms parameter shows ulong, an unsigned long.
MODULE_PARM_DESC writes a description into the module's info section, so modinfo documents each parameter with its type.
The permission mask controls the sysfs file. A parameter with a nonzero permission appears as /sys/module/<name>/parameters/<param> with those permissions; 0 means no sysfs entry at all. Passing a value on the command line works either way. The two are independent: you can load with who=labpc count=3 and still never create a sysfs file, or you can expose read-only values for inspection.
Toggle the bits below to see the masks used above as octal, ls -l text and a chmod command.
sudo insmod hello.ko who=labpc count=3 debug=1
cat /sys/module/hello/parameters/who # labpc
Arrays and renamed parameters round out the interface. module_param_array stores a comma-separated list into a static array and records how many values arrived; the count pointer may be NULL if you do not need it. module_param_named gives the external name separately from the internal variable, which is useful when the public name should not match the C identifier.
static int levels[4] = { 1, 2, 3, 4 };
static int levels_count;
static int io_base = 0x3f8;
module_param_array(levels, int, &levels_count, 0444);
module_param_named(base, io_base, int, 0444);
insmod hello.ko levels=1,2,3 base=0x2f8
The loader refuses more array values than fit, so an overrun is impossible as long as the array is statically sized.
If a parameter's sysfs file is writable, anyone with permission can change the value at run time, but your module is never notified. If the module reads the variable on every use, the change takes effect; if it caches the value at init, it does not. Prefer read-only permissions (0444) unless you specifically handle runtime changes.
Going deeperHow module_param really works
Each module_param expands to a struct kernel_param placed in a dedicated ELF section (.init.rodata is used for the description, and the parameter operations land in a __param section). The struct holds the variable's address and a pair of param_ops callbacks such as param_set_int and param_get_charp. The loader finds every entry in that section and runs the appropriate set callback against each name=value argument. This is the same machinery that later lessons use through module_param_cb to attach custom get/set handlers to a parameter.
Building out-of-tree with Kbuild: obj-m, M= and Module.symvers
3 min readA module can live inside the kernel tree or outside it. For a new driver you almost always work out of tree first, so your source directory has a small Makefile.
obj-m += hello.o
KDIR ?= /lib/modules/$(shell uname -r)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
obj-m += hello.o tells Kbuild to build hello.o as a module from hello.c. -C $(KDIR) changes into the kernel build directory and reads its top-level Makefile; M=$(PWD) tells that Makefile to come back and build your external directory. KDIR must point at a configured and built tree. On a desktop that is the build symlink of the linux-headers-$(uname -r) package; for the QEMU work from the previous lesson, point it at your own tree instead, and for cross-building add the same two variables the kernel build uses.
make # native, against the running kernel's headers
make KDIR=$HOME/linux # against your QEMU kernel tree
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- KDIR=$HOME/linux-arm64
Typical output (yours will differ):
CC [M] /home/learner/hello/hello.o
MODPOST /home/learner/hello/Module.symvers
CC [M] /home/learner/hello/hello.mod.o
LD [M] /home/learner/hello/hello.ko
The last step is the interesting one. modpost is the module postprocessor: after compilation it reads the object, checks that every referenced symbol is actually exported somewhere, and generates hello.mod.c, which holds the metadata that becomes the module's .modinfo and __versions sections. It also updates the local Module.symvers file.
the file Kbuild maintains that records each exported symbol and its CRC checksum, used to verify that a module was built against a compatible set of headers is the handshake that keeps a module and a kernel from silently disagreeing. When CONFIG_MODVERSIONS is enabled, every exported symbol gets a CRC derived from its prototype. Your module records the CRC it expects for each symbol it uses; if the running kernel's CRC differs, loading fails instead of linking to an incompatible function. This is separate from, and stronger than, the vermagic release string.
A module built from several files names its parts with a <name>-objs (or, for the library style, <name>-y) list.
obj-m += demo.o
demo-objs := core.o i2c.o
This compiles core.c and i2c.c and links them into a single demo.ko. The resulting module name is demo, not core.
The number one out-of-tree build failure is compiling against the desktop's linux-headers while loading into your QEMU kernel. The two must match release and configuration. Set KDIR to the exact tree you built and booted, and keep a separate object directory per architecture.
Loading and unloading in detail
2 min readinsmod takes a path and asks the kernel to load that one file. It resolves nothing: if the module uses a symbol exported by another module, insmod fails with an unresolved symbol and the reason appears in dmesg. modprobe takes a module name, reads the dependency map that depmod built, loads every prerequisite first, and then the requested module. Development uses insmod (your module is in the current directory, not installed); production uses modprobe.
modinfo reads the .modinfo section without loading anything. Typical output for the parameterised module (yours will differ):
filename: /home/learner/hello/hello.ko
license: GPL
author: learner
description: First parameterised module
version: 1.0
parm: who:who to greet (charp)
parm: count:how many times to greet (int)
parm: debug:enable extra diagnostics (bool)
parm: delay_ms:delay between greetings, read-only (ulong)
parm: levels:levels to use (array of int)
depends:
vermagic: 6.8.0 SMP mod_unload modversions
The depends: line lists other modules this one needs, and parm: documents each parameter. modinfo -F license hello.ko prints a single field, which scripts use.
lsmod is a formatter for /proc/modules. A loaded line looks like this (typical):
hello 16384 0 - Live 0x0000000000000000 (O)
The columns are name, size in bytes, reference count, the list of modules using it, state, and the load address. The (O) suffix marks the module as out of tree, which is a taint flag. The sysfs view under /sys/module/hello/ carries the same information structured as directories: parameters/ for the parameters you declared, and files such as refcnt, holders and sections for the loader's bookkeeping.
Removal is rmmod hello by name. It runs the exit function and fails if the module is in use. modprobe -r hello also removes now-unused dependencies.
1load and inspect
sudo insmod hello.ko who=board count=2
lsmod | grep hello
cat /proc/modules | grep hello
cat /sys/module/hello/parameters/count
2remove and confirm the exit function ran
sudo rmmod hello
sudo dmesg | tail -2
The two pr_info lines from init and exit bracket the load and unload. If the module prints nothing on load, you likely have a mismatch between pr_info level and the console level; the message is still in the ring buffer, so dmesg shows it.
Failing cleanly: error codes, unwinding and ERR_PTR
4 min readReal init functions do more than print. They allocate memory, register devices and request resources, and any of those steps can fail. The kernel's error convention is simple and universal: functions return a a negative error number such as -ENOMEM or -EINVAL, the kernel's way of reporting failure from a function that returns an integer, where 0 means success. The codes live in <linux/errno.h>; the common ones are ENOMEM (out of memory), EINVAL (bad argument), ENODEV (no such device), EBUSY (resource busy), EIO (hardware I/O error) and EPERM (not permitted).
When step three of five fails, steps one and two must be undone. The kernel idiom for this is the forward-only goto to error labels.
static int __init demo_init(void)
{
struct demo_dev *dev;
int err;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
err = -ENOMEM;
goto fail_alloc;
}
err = demo_register_a(dev);
if (err)
goto fail_a;
err = demo_register_b(dev);
if (err)
goto fail_b;
return 0;
fail_b:
demo_unregister_a(dev);
fail_a:
kfree(dev);
fail_alloc:
return err;
}
Read the labels from bottom to top: each one undoes one more step than the last. If demo_register_b fails, control jumps to fail_b, which unregisters A and frees the allocation, then returns the error. The goto always moves forward in the function, never backward, and the exit function mirrors the same sequence in reverse.
Pointer-returning helpers have their own convention. Rather than returning NULL for every failure (which tells the caller nothing), they return an an error code encoded as a pointer, so a function that returns a pointer can report a specific errno; tested with IS_ERR and decoded with PTR_ERR.
static struct demo_dev *demo_create(void)
{
struct demo_dev *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return ERR_PTR(-ENOMEM);
return dev;
}
static int demo_probe(void)
{
struct demo_dev *dev = demo_create();
if (IS_ERR(dev))
return PTR_ERR(dev);
/* ... */
return 0;
}
The value of ERR_PTR is an address in the top of the address range that can never be a real allocation, which is why IS_ERR is a cheap range check and why the two macros must always be paired.
Allocate:
kzallocreturns NULL, soerris set to-ENOMEMand control jumps tofail_alloc.Register a: the first registration fails; control jumps to
fail_a.Register b: the second registration fails; control jumps to
fail_b.Unwind in reverse:
fail_bunregisters A,fail_afrees the allocation, andfail_allocreturns the code.
For reporting the failure, use pr_err, or pr_warn when the module can limp on. The previous lesson covered the eight log levels and pr_debug; the practical addition here is rate limiting. A condition that can fire in a loop or interrupt path should use pr_err_ratelimited or printk_ratelimited, which drop further messages once a threshold is reached (about ten messages in five seconds by default, tunable through /proc/sys/kernel/printk_ratelimit and /proc/sys/kernel/printk_ratelimit_burst).
The classic mistakes in this area, with their symptoms:
- Load fails with "could not insert module: Operation not permitted" or a negative error. Cause: the init function returned a nonzero value. Diagnose: read dmesg for the error message the module printed just before. Fix: find the failing step and make the unwind match it exactly.
- Half-registered module after a failure. Cause: a step failed but an earlier registration was not undone. Diagnose: the device or symbol still exists after the load failed. Fix: complete the
gotochain so every succeeded step has a label that undoes it. - Unknown symbol on load. Cause: a symbol is not exported, or an out-of-tree build ran against a different tree. Diagnose:
dmesg | grep -i unknownand comparemodinfo -F vermagicwith the running kernel. Fix: export the symbol or rebuild against the correct tree. rmmod: ERROR: Module hello is in use. Cause: the reference count is above zero. Diagnose:lsmodshows the use count and holders. Fix: release the reference, or investigate who still holds it.
Exporting symbols, refcounting, licensing and taint
5 min readA module can call any non-static symbol in the kernel core, but between modules the rule is explicit. To make a function available to other modules, export it.
int demo_helper_add(int a, int b)
{
return a + b;
}
EXPORT_SYMBOL(demo_helper_add);
EXPORT_SYMBOL makes the symbol visible to every module. EXPORT_SYMBOL_GPL makes it visible only to modules whose declared licence is GPL-compatible. A third form, EXPORT_SYMBOL_NS, places the symbol in a a label attached to exported symbols that importing modules must opt into with MODULE_IMPORT_NS, used to keep subsystem-internal symbols from leaking to unrelated code.
EXPORT_SYMBOL_GPL(demo_secret);
EXPORT_SYMBOL_NS(demo_quirk, DEMO);
A consumer uses the plain symbol with a declaration, and must import a namespace before using its symbols.
MODULE_IMPORT_NS(DEMO);
extern int demo_helper_add(int a, int b);
This is how layered subsystems work: a generic layer exports symbols that specific hardware drivers stack on top of, the way the USB core exports for USB device drivers. When module B uses a symbol from module A, depmod records the dependency and modprobe loads A first.
The a per-module counter that records how many users currently depend on it; the kernel refuses to unload a module while the count is above zero is what makes removal safe. A driver that opens a device and needs the module to stay resident while the device is open takes a reference on open and drops it on release. The classic pattern sets the owner in the file operations and manages the count by hand:
static int demo_open(struct inode *inode, struct file *file)
{
if (!try_module_get(THIS_MODULE))
return -ENODEV;
/* use the device */
return 0;
}
static int demo_release(struct inode *inode, struct file *file)
{
module_put(THIS_MODULE);
return 0;
}
static const struct file_operations demo_fops = {
.owner = THIS_MODULE,
.open = demo_open,
.release = demo_release,
};
try_module_get returns false if the module is already going away, and the open fails cleanly rather than racing with removal. module_put drops the reference, and when the count reaches zero the module can be removed. In current kernels, setting .owner = THIS_MODULE lets the VFS core take and release this reference automatically around open and release, but the explicit pattern is still the model to understand, and it is still what you write when a module holds a reference to a different module's code.
Licensing ties the two halves together. MODULE_LICENSE declares the module's licence, and the kernel recognises a fixed set of GPL-compatible strings: "GPL", "GPL v2", "GPL and additional rights", "Dual BSD/GPL", "Dual MIT/GPL" and "Dual MPL/GPL". Anything else, or nothing at all, marks the module proprietary. Two consequences follow. First, a proprietary module cannot resolve EXPORT_SYMBOL_GPL symbols, so it fails to load if it needs them. Second, loading it sets the P taint flag, alongside the O (out of tree) and E (unsigned) flags the previous lesson explained.
Taint flags are a bitmask read from /proc/sys/kernel/tainted: toggle the three flags this lesson introduces and read the value.
sudo insmod proprietary.ko # loads only if it needs no GPL-only symbols
cat /proc/sys/kernel/tainted
A tainted kernel is a signal that the running combination is not one the maintainers can support. Developers routinely ignore bug reports that mention a tainted kernel, because a binary module they cannot read makes the trace impossible to follow. The practical rule for this program: declare a real GPL-compatible licence, and treat a tainted kernel in an oops as a prompt to reproduce the bug on a clean kernel.
Going deeperHow namespaces are enforced
EXPORT_SYMBOL_NS(sym, NS) records the namespace alongside the symbol in the kernel's export table, and MODULE_IMPORT_NS(NS) writes an import_ns=NS entry into the module's .modinfo. During the build, modpost warns if a module uses a namespaced symbol without importing its namespace, and the warning tells you the exact MODULE_IMPORT_NS line to add. At load time the loader checks each symbol's namespace against the module's import list, so a module that bypasses the build warning still fails to resolve the symbol. Namespaces first shipped in kernel 5.4 and were driven by subsystems that wanted internal helpers usable by a small set of related drivers without exporting them to everyone.
Initcalls and boot-time ordering
2 min readmodule_init means two different things. For a loadable module it is the function the loader calls after linking. For built-in code, module_init is an alias for device_initcall, a a function registered to run at a numbered stage of boot; built-in code runs its init function at its initcall level, in link order within a level.
The levels form an ordered ladder, from earliest to latest:
pure_initcall(early_fn); /* level 0, the very first */
core_initcall(core_fn); /* level 1 */
postcore_initcall(pc_fn); /* level 2 */
arch_initcall(arch_fn); /* level 3 */
subsys_initcall(subsys_fn); /* level 4 */
fs_initcall(fs_fn); /* level 5 */
device_initcall(dev_fn); /* level 6, where module_init lands */
late_initcall(late_fn); /* level 7, after device init */
rootfs_initcall sits between fs and device, and late_initcall_sync runs after late. Within a level, functions run in the order they were linked, which follows the order of the obj-y lines in the Makefiles.
The ordering exists so that infrastructure is ready before its users. A clock controller must initialise before the drivers that request clocks from it, so clock drivers use subsys_initcall and their consumers use device_initcall. A driver that reads a filesystem during init would use fs_initcall or later. When you write a normal device driver, module_init and thus device_initcall is the right level: the core subsystems, buses and filesystems are already up.
The difference shows in the logs. A built-in driver prints its init message during boot, among the other initcalls; the same driver loaded as a module prints it whenever insmod runs. This is also why a driver that another built-in driver depends on sometimes has to move earlier in a Makefile: link order within a level becomes the scheduling order, and getting it wrong produces a probe failure that a later lesson's deferred-probe machinery exists to repair.
The loader underneath: sections, modpost, vermagic and signing
2 min readA .ko file is an ELF relocatable object. objdump -h hello.ko lists its sections, and the kernel-specific ones tell the loader what to do with each piece. Typical sections (yours will differ in addresses):
.text executable code
.data initialised data
.rodata read-only data
.bss zero-initialised data
.init.text code marked __init, freed after load
.exit.text code marked __exit, freed on unload
.modinfo the MODULE_* strings and parameter descriptions
__versions per-symbol CRCs when CONFIG_MODVERSIONS is on
The a string baked into each module recording the kernel release and key build options, compared against the running kernel before loading is the first gate. modinfo -F vermagic hello.ko shows a string like 6.8.0 SMP mod_unload modversions; a mismatch produces "Invalid module format" and the comparison is logged in dmesg. The CRC check from Module.symvers is the second, finer gate.
an optional build feature that signs each module with a kernel key and, with forced loading, refuses to load unsigned or wrongly signed modules is the third gate, enabled with CONFIG_MODULE_SIG. Each module is signed with the key at certs/signing_key.pem, and modinfo exposes the result through fields such as sig_id, signer, sig_key and sig_hashalgo. Without CONFIG_MODULE_SIG_FORCE, an unsigned module still loads but taints the kernel with E. With forced signing, the loader refuses it outright, printing a verification failure. Distributions enable this, which is why a home-built module can fail on a Secure Boot desktop but load fine in the QEMU loop where you control the kernel.
rmmod -f and the CONFIG_MODULE_FORCE_UNLOAD option bypass the use count, and CONFIG_MODULE_SIG_FORCE bypasses nothing but tightens loading. Forcing unload while a device is in use is a one-way trip to a crash; in development a reboot is the safer fallback.
modprobe under the hood: config, aliases, blacklists and the kmod helper
3 min readEverything modprobe knows comes from files depmod generated under /lib/modules/$(uname -r)/. modules.dep lists dependencies, and modules.alias maps device identifiers to module names, which is how a hotplugged device finds its driver. Configuration lives in /etc/modprobe.d/*.conf and /etc/modules-load.d/*.conf, the latter simply naming modules to load at boot.
The most common entries are blacklist, options, alias, install and softdep.
# /etc/modprobe.d/demo.conf
blacklist pcspkr # never auto-load this module
options hello who=board count=2 # default parameters for hello
alias demo-device hello # the name demo-device loads hello
softdep hello pre: other # other must be loaded before hello
install hello /sbin/modprobe --ignore-install hello && echo loaded
Blacklisting stops automatic loading, not manual loading: modprobe pcspkr still works after a blacklist, which is why a broken driver is often blacklisted rather than removed. options sets defaults that an explicit command line overrides. alias adds names modprobe accepts. softdep declares an ordering without a hard symbol dependency. The install line replaces the load command entirely, which some packages use to run setup before or after loading.
The the usermode-helper path through which the kernel itself runs modprobe, configured by /proc/sys/kernel/modprobe, used for requests that originate inside the kernel is how the kernel loads a module when no user typed anything. When a driver needs a capability it does not have, it calls request_module("net-pf-%d-proto-%d", PF_INET6, IPPROTO_TCP), and the kernel runs the helper named in /proc/sys/kernel/modprobe (default /sbin/modprobe).
cat /proc/sys/kernel/modprobe # /sbin/modprobe
Device hotplug travels a parallel path: the kernel emits a uevent carrying the device's modalias, a user-space manager such as udev or systemd reads it, and it calls modprobe with the alias, which modules.alias resolves. Both paths end at the same two system calls.
The loader's entry points are init_module and finit_module. init_module takes a pointer to the module image in user memory plus its length; finit_module, added in kernel 3.8, takes a file descriptor instead, which lets the kernel read the file itself and avoids a time-of-check to time-of-use window. Modern module tools use finit_module. Both land in load_module() in kernel/module/main.c, which performs the checks and copies this section described: verify the magic and configuration, parse the ELF sections, resolve symbols against the kernel and module export tables, allocate memory, run the init function, and insert the module into the kernel's list.
Going deeperWhy finit_module replaced init_module
With init_module the kernel receives a buffer the tool already read, so between the tool's read and the kernel's copy the file on disk could be swapped for another. finit_module removes that race by passing an open file descriptor, and the kernel reads the module directly. It also lets the kernel verify the signature over the same bytes it will execute. The flags argument later grew options such as MODULE_INIT_IGNORE_MODVERSIONS and MODULE_INIT_IGNORE_VERMAGIC, the controlled escapes used by debugging and out-of-tree frameworks, which correspond to the (F) force-load taint flag.
Try it
1 min readDo the lab for this session: write, build, load and unload a hello module with a charp parameter, an int parameter and a debug flag, and read its modinfo and sysfs files. Then split it into two modules where one exports a symbol the other uses, set the licence, and observe the dependency and taint with modinfo and lsmod. Finally, force an init failure and verify the clean unwinding and the error message in dmesg. Finish with the practice pack, which drills each of these skills without repeating the lab steps.
Key takeaways
- A module registers facilities during init, returns immediately, and must undo everything in its exit function.
- __init and __exit place code in dedicated ELF sections so built-in init code can be freed after boot.
- module_param exposes a global variable as a load-time option and optionally as a sysfs file under /sys/module.
- Out-of-tree modules build with make -C $(KDIR) M=$(PWD) modules; Module.symvers carries the symbol CRCs that modpost checks.
- Kernel functions return negative errno values, and pointer-returning functions use ERR_PTR, checked with IS_ERR and read with PTR_ERR.
- EXPORT_SYMBOL_GPL and symbol namespaces restrict which modules may use a symbol; try_module_get keeps a module in use.
- A proprietary module loses access to GPL-only symbols and taints the kernel with the P flag.
- module_init becomes a device_initcall for built-in code, so initialisation follows the ordered initcall levels.
Reflect
- Explain to a colleague, in two sentences: explain the register-and-return contract of a module and the roles of its init and exit functions
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docsThe Linux kernel documentation
- Official docsBuilding External Modules (Kbuild)
- Official docsKernel module signing facility
- Official docsTainted kernels
- ArticleThe Linux Kernel Module Programming Guide
- ArticleBootlin Linux kernel and driver development training slides
Official documentation first. Links checked when the lesson was published.