Privileged Kernel Module Lifecycle
Trace an ARMv7-A Linux 6.12 kernel module from Kbuild's relocatable ET_REL .ko ELF sections through Ring-0 symbol relocation, publication commit points, failed-init rollback, and THIS_MODULE reference pinning.
What you'll learn
- Given a driver trace, trace module load, failed initialization and normal unload paths.
- Given a driver trace, inspect ELF metadata without confusing vermagic with a safety proof.
- Given a driver trace, diagnose an unload attempt while an open file retains its module owner.
What a Loadable Kernel Module Physically Is Inside Ring 0
Engineers moving from user-space C (GL-C01..C04) to kernel drivers often picture insmod ksa_core.ko as launching a privileged background process. A loadable kernel module is not a process at all. It has no main(), no PID, no private TTBR0 address space, no user stack, and no automatic resource sweeper when it exits. Instead, a .ko file is an unlinked, relocatable ARM32 ELF object (ET_REL, EM_ARM) that the running Linux kernel dynamically links straight into its own privileged Supervisor (SVC / Ring 0) virtual address space!
Trace the three columns of Figure 1.1a from source file to resident machine code. During an out-of-tree Kbuild run (make -C "$KDIR" M="$PWD" ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- modules), scripts/mod/modpost scans your compiled .o for unresolved kernel symbols (_printk, cdev_add), verifies them against Module.symvers, and generates ksa_core.mod.c containing .modinfo (vermagic, license), __versions (symbol CRC hashes), and .gnu.linkonce.this_module (struct module __this_module). When insmod or modprobe invokes the finit_module() syscall, kernel/module/main.c (load_module()) maps the .ko into MODULES_VADDR (0xBF00_0000 .. 0xBFFF_FFFF on ARMv7-A—a 16 MiB SVC-only virtual window placed immediately below PAGE_OFFSET = 0xC000_0000 so 24-bit ARM BL branch instructions reach vmlinux .text within +-32 MiB without veneers!), patches R_ARM_CALL relocations, marks .text Read-Only + Executable and .data Execute-Never (XN = 1), and calls your module_init() entry point. If module_init() returns 0, the loader immediately frees .init.text and .init.data pages back to RAM; your callbacks then sit dormant until invoked in whichever task or interrupt context reaches them!
Figure 1.1a. Out-of-tree Kbuild compilation, relocatable .ko ELF anatomy, and Ring-0 relocation into ARMv7-A MODULES_VADDR (0xBF000000..0xBFFFFFFF).
mental model: Commissioning a live substation bay means wiring and testing internal breakers (locks, buffers, MMIO) before closing the bus tie switch (callback publication); decommissioning means opening the bus tie and draining active loads before unbolting the breakers.
Where it stops working: Unlike physical switchgear, returning an error from module_init() never invokes module_exit(), and pinning executable code via THIS_MODULE does not stop bus-level device unbind or active timers.
definition (Loadable Kernel Module (.ko), Commit Boundary & THIS_MODULE Ownership): A Loadable Kernel Module (LKM, .ko) is an ET_REL ELF object carrying .modinfo metadata whose vermagic checks kernel release, SMP, preemption, and ARM patch ABI compatibility—necessary to load, yet never a proof of race-free logic. module_init() registers the __init startup transaction: if it fails partway through and returns a negative errno, the loader aborts without calling module_exit(), so module_init() must unwind every completed acquisition itself. module_exit() runs only on normal unload (rmmod) when the module reference count is 0. Setting file_operations.owner = THIS_MODULE lets VFS open() pin resident .ko code via try_module_get(), though dynamic hardware removal still requires an independent object-lifetime protocol.
Step through the four-stage module lifecycle transaction below before inspecting the failure timelines:
- Step 1. Step 1: Build an ARM32 ET_REL .ko against the exact Linux 6.12 .config and Module.symvers.
- Step 2. Step 2: Initialize private locks and resources BEFORE publishing callbacks; self-unwind on error.
- Step 3. Step 3: Pin resident .ko code across open file descriptions via .owner = THIS_MODULE.
- Step 4. Step 4: Block new opens, quiesce async producers, and release resources in reverse 3-2-1 order.
Figure 1.1b. Module initialization is an all-or-nothing publication transaction, while unload must withdraw entry, drain callers, and release in reverse order.
Publication Commit Points, Failed-Init Rollback & Kbuild ABI Gates
Why do driver bugs so often wedge /proc/iomem or major numbers on the second insmod after a failed first attempt? Compare Panel A and Panel B in Figure 1.1b. When module_init() acquires Stage 1 and Stage 2 and then fails at Stage 3 (-ENOMEM or -EBUSY), the kernel module loader aborts transition to MODULE_STATE_LIVE and discards the .ko without ever calling module_exit()! If module_init() simply returns -ENOMEM expecting module_exit() to clean up, Stages 1 and 2 leak into global kernel tables until reboot. Conversely, once Stage 3 publishes a callback table (cdev_add, request_irq), another CPU can enter your code before module_init() even returns—so every lock and buffer must be initialized prior to publication!
Panel C in Figure 1.1b clarifies what .owner = THIS_MODULE protects during normal operation. When user space opens your character node, VFS calls try_module_get(fops->owner), incrementing the module's refcount so rmmod fails with -EBUSY until the last struct file closes (__fput() -> module_put()). That refcount prevents unmapping .ko .text pages while a task executes inside read() or write(), but it does not stop sysfs driver unbind, cancel armed timers, or make kfree(dev) safe while open descriptors remain!
Figure 1.1b. Successful publication vs failed-init self-rollback (top), and resident-code reference pinning via .owner = THIS_MODULE vs device lifetime (bottom).
| Lifecycle / Build Mechanism | Kernel / Kbuild Artifact | What It Guarantees | What It Does NOT Guarantee |
|---|---|---|---|
Full tree + Module.symvers | make -C $KDIR M=$PWD modules | Exact .config struct layout + symbol CRCs | modules_prepare alone omits Module.symvers! |
.modinfo vermagic check | 6.12.x SMP mod_unload ARMv7 p2v8 | Rejects mismatched kernel ABI on insmod | Zero proof of lock ordering or rollback safety |
Failed module_init() (< 0) | Loader aborts before LIVE state | .ko pages freed by load_module() | module_exit() never runs; init owns rollback |
fops.owner = THIS_MODULE | try_module_get() on VFS open() | Blocks rmmod (-EBUSY) while fd stays open | Does not block driver unbind or drain timers |
When building for our Cortex-A7 target, inspect ksa_core.ko on the host before copying it to the board: readelf -h ksa_core.ko confirms ELF32 + ARM, readelf -p .modinfo ksa_core.ko dumps raw metadata strings, and modinfo ksa_core.ko verifies vermagic and depends (insmod ./ksa_core.ko loads one file directly, whereas depmod + modprobe ksa_core resolves dependencies under /lib/modules/$(uname -r)/). Never hex-edit vermagic or pass rmmod -f to paper over mismatches—both corrupt Ring-0 invariants!
learner@ksa:~/gl-e04/m01-l01$ bat -H 4 -H 10 -H 15 target.c File: target.c #include <linux/init.h> #include <linux/module.h> static int __init ksa_core_init(void) { pr_info("ksa_core: initialized\n"); return 0; } static void __exit ksa_core_exit(void) { pr_info("ksa_core: removed\n"); } module_init(ksa_core_init); module_exit(ksa_core_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Cortex-A7 lifecycle exercise");- __init places ksa_core_init in .init.text (freed once 0 is returned); any negative return here must unwind completed acquisitions itself.
- __exit ksa_core_exit runs ONLY during normal rmmod after module_refcount drops to zero — never after a failed ksa_core_init().
Proving Commit, Busy-Unload Rejection & Prefix Rollback in ISO C11
Before loading privileged Ring-0 code, verify.c models a three-stage acquisition lifecycle (m->live bits 0..2, m->refs active open handles, and a base-10 release ledger m->cleanup) in strict ISO C11:
- Full load + busy unload check:
module_start(&m, 0)setsm.live == 7U(0b111). Whilem.refs == 1,module_stop(&m)refuses removal (-1) without touchingm.live; oncem.refs == 0,module_stop(&m)unwinds in strict reverse dependency order (321U). - Exhaustive failed-init boundaries: Injecting failure at stages
1,2, and3provesmodule_start()leavesm.live == 0and records exact prefix rollbacks0,1, and21—never releasing an unacquired stage!
learner@ksa:~/gl-e04/m01-l01$ bat -H 19 -H 20 -H 21 -H 22 -H 23 -H 32 -H 47 -H 48 verify.c File: verify.c /* m01-l01 / failed initialization and busy unload: native model, not a loaded Linux driver. */ #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> #include <stdatomic.h> #include <threads.h> struct module_model { unsigned live, refs, cleanup; }; int module_start(struct module_model *m, unsigned fail_at); int module_stop(struct module_model *m); int module_start(struct module_model *m, unsigned fail_at) { *m = (struct module_model){0}; for (unsigned stage = 1; stage <= 3; ++stage) { if (stage == fail_at) { for (unsigned undo = stage - 1; undo > 0; --undo) m->cleanup = m->cleanup * 10U + undo; m->live = 0; return -1; } m->live |= 1U << (stage - 1U); } return 0; } int module_stop(struct module_model *m) { if (m->refs != 0U) return -1; for (unsigned undo = 3; undo > 0; --undo) { if ((m->live & (1U << (undo - 1U))) != 0U) m->cleanup = m->cleanup * 10U + undo; } m->live = 0; return 0; } #define CHECK(x) do { if (!(x)) { fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); return EXIT_FAILURE; } } while (0) int main(void) { { struct module_model m; CHECK(module_start(&m, 0) == 0 && m.live == 7U); m.refs = 1; CHECK(module_stop(&m) == -1 && m.live == 7U); m.refs = 0; CHECK(module_stop(&m) == 0 && m.cleanup == 321U); puts("lifecycle: publication=7 busy-unload=rejected reverse=321"); } { for (unsigned fail = 1; fail <= 3; ++fail) { struct module_model m; CHECK(module_start(&m, fail) == -1 && m.live == 0); unsigned expected[] = {0,0,1,21}; CHECK(m.cleanup == expected[fail]); } puts("faults: failed-init stages=1,2,3 all resources unwound"); } return EXIT_SUCCESS; }- When stage == fail_at fails, unwind ONLY stages (stage - 1) down to 1 inside module_start() because module_stop() will never be called.
- Refuse unload (-1) while m->refs != 0U (modeling an open file holding THIS_MODULE) without mutating m->live.
- Verify both busy-unload refusal and reverse 321 teardown before testing every failed-init boundary (expected rollbacks 0, 1, 21).
Running the Lifecycle Verifier & Auditing Host vs Target Evidence
Compile and run verify.c below. Notice the strict evidence boundary in strace (and when running readelf -h verify on the ELF64 X86-64 host binary): the host run proves our rollback and busy-refusal state algebra, whereas target ELF32 EM_ARM relocation, vermagic acceptance, and finit_module() / delete_module() syscalls must be verified separately on the ARMv7-A Linux kernel 6.12 image.
learner@ksa:~/gl-e04/m01-l01gcc -std=c11 -Wall -Wextra -Werror -O2 -pthread verify.c -o verifylearner@ksa:~/gl-e04/m01-l01./verifylifecycle: publication=7 busy-unload=rejected reverse=321faults: failed-init stages=1,2,3 all resources unwoundlearner@ksa:~/gl-e04/m01-l01echo $?0learner@ksa:~/gl-e04/m01-l01readelf -h verifyELF Header: Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: DYN (Position-Independent Executable file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x11d0 Start of program headers: 64 (bytes into file) Start of section headers: 14192 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 56 (bytes) Number of program headers: 13 Size of section headers: 64 (bytes) Number of section headers: 31 Section header string table index: 30learner@ksa:~/gl-e04/m01-l01learner@ksa:~/gl-e04/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "lifecycle: publication=7 busy-un"..., 113) = 113exit_group(0) = ?+++ exited with 0 +++Why Post-Publication Failures & Unbind Lifetimes Differ From Simple Goto Ladders
Suppose an engineer adds a fourth resource acquisition after Stage 3 has already published file_operations to user space. If Stage 4 fails, another CPU may already have opened the character device! Simple reverse goto unwinding is only race-free while all state remains private; once an entry point is published, failure recovery becomes a full concurrent teardown (withdraw entry -> synchronize/drain callers -> release backing state). Keep callback publication as the final commit step whenever possible! Later: Lesson m01-l02 moves inside those published .read/.write callbacks to secure the untrusted __user address-space boundary, and Module m02 separates cdev publication from per-device object lifetime.
Common Production Pitfalls
warning: Symptom: insmod ksa_core.ko fails with -ENOMEM at step 3, and every subsequent insmod fails permanently with -EBUSY until the board reboots. Root Cause: ksa_core_init() returned -ENOMEM without releasing steps 1 and 2, assuming ksa_core_exit() would clean up—when in fact the kernel never invokes module_exit() after a non-zero module_init() return. Fix: Unwind every completed acquisition in reverse dependency order inside module_init()'s goto ladder before returning the negative errno.
warning: Symptom: insmod rejects a compiled .ko with Invalid module format (no symbol version for ... or vermagic mismatch), so a developer edits VERMAGIC_STRING to force-load it and triggers a Kernel Oops. Root Cause: The .ko was compiled against modules_prepare alone (missing Module.symvers) or a mismatched .config (PREEMPT_RT / SMP struct layout differences), and spoofing vermagic bypassed the loader's ABI guard without fixing binary struct offsets. Fix: Always build out-of-tree modules (M="$PWD") against the exact configured, built target Linux kernel tree containing Module.symvers.
Practice & Retrieval
Guided Practice: Tracing a Four-Stage Rollback Ledger
Extend the mental trace of module_start() to four stages (1: alloc_chrdev_region, 2: kzalloc, 3: mutex_init + buffer setup, 4: cdev_add commit) when Stage 4 fails with -EBUSY. List which stages exist at the failure point (1..3), write the exact reverse release sequence (3 needs no destructor, release 2 kfree, release 1 unregister_chrdev_region), and confirm module_exit() is called 0 times.
Independent Practice: Auditing Premature Publication (pub_order_audit.c)
Copy verify.c to a scratch file pub_order_audit.c with four stages where Stage 2 wrongly sets a published = 1 flag before Stage 3 initializes buffer capacity, and simulate a reader thread checking published between Stages 2 and 3. Repair the order so published transitions to 1 only as Stage 4, and document which target commands (readelf -h, modinfo, dmesg, lsmod) complete hardware sign-off.
Key takeaways
- A
.kois anET_RELrelocatable ELF object linked byfinit_module()directly into privileged Ring-0 (SVC) memory (MODULES_VADDR = 0xBF00_0000onARM32), freeing.init.textoncemodule_init()returns0. - Initialize all locks and state before publishing callbacks; if
module_init()fails (< 0),module_exit()never runs, somodule_init()must unwind completed acquisitions in reverse order. - Build out-of-tree modules (
M="$PWD") against the configured targetLinux kerneltree withModule.symvers;vermagicguards ABI flags, not driver logic. - Setting
.owner = THIS_MODULEpins resident.kocode while character files stay open (rmmod->-EBUSY), while device unbind and async callbacks require explicit synchronization. Later: Lessonm01-l02secures untrusted__usercopies andsize_tbounds. module_init()identifies the initialization entry; a failed initialization must undo its own completed acquisitions.- A
.kois a relocatable ELF object carrying.modinfo; compatible vermagic is necessary but does not prove behavioral correctness. - An open character file with
file_operations.owner = THIS_MODULEholds a module reference, but hardware removal needs its own lifetime protocol.