16 KiB
Loadable modules
Modules are off in the default kernels. kernel/build.sh modules builds
a kernel with them (kw_modules.config over kw_defconfig:
CONFIG_MODULES, CONFIG_MODULE_UNLOAD, and iso9660, Bluetooth and kwbt
made =m) into vendor/build/kernel-mod (KW_SMP=1: also the SMP one,
kernel-mod-smp), its modules installed with depmod into
vendor/build/kmod/lib/modules/RELEASE and that tree packed as
vendor/build/kmod/modules.cpio (append it to an initramfs: cat base.cpio modules.cpio). A kernel with modules has a banner of its own
(#<id>-mod, kernel.md, Build stamps).
A module only loads into its own kernel (struct layouts follow
CONFIG_SMP, the SMP form uses shared memory and atomics, vermagic says
SMP), so the two kernels have two sets. The SMP kernel with modules has
the release 7.3.4-smp+ (kw_modules_smp.config: CONFIG_LOCALVERSION),
the UP one 7.3.4+ like the default kernels, so one root holds both sets
in /lib/modules/$(uname -r) and modprobe and request_module() use the
booted kernel's, with the bundle of the pair booted with one CPU or more
(its pair check allows the suffix, kernel.md). modules.cpio packs every
release installed in vendor/build/kmod: a modules run without
KW_SMP=1 leaves an SMP set installed earlier in it. The default kernels'
release stays 7.3.4+. The guest uses the usual tools (busybox or kmod insmod,
modprobe, rmmod, lsmod; finit_module and init_module); the base
shell has no /sbin, so request_module() needs echo /bin/modprobe > /proc/sys/kernel/modprobe there.
A module is a wasm side module that the host compiles and instantiates
against the kernel's own memory, function table and globals, carried in
an ELF .ko so that Kbuild, modpost, depmod and the generic loader
(kernel/module/main.c: modinfo, vermagic, licences, namespaces,
dependencies, reference counts, parameters, sysfs) work as for any arch.
Build (Kbuild, modpost, kwko)
- Exports (
include/linux/export.h, the__wasm__branch): wasm has no asm form ofEXPORT_SYMBOL, so the.export_symbolrecord modpost reads and the ksymtab entry are C. The entry's value is&symwith the symbol's own type: a function's table index, data's address. vmlinux's entries are___ksymtab+NAMEwith the flags byte just before the name in__ksymtab_strings; the link does not sort them (vmlinux.lds.S definesSORT()away, Toolchain below), sokw_ksymtab_sort()(arch/wasm/kernel/module.c, an early initcall) sorts them by name forfind_symbol()'s bisection and sets__kflagstabfrom those bytes. A module's entries (__kw_ksymtab) carry their flags; the loader sorts a copy intomod->syms. - modpost reads wasm objects through
scripts/mod/wasm.c(an ELF image of an object's data segments and function and data symbols; only the relocations into.export_symbol, so no section mismatch checks).mk_elfconfigpicks ELFCLASS64 for a memory64 object. For a wasm module NAME.mod.c has no__this_module(the side module imports it) but__kw_module(struct kw_module_info,asm/module.h): init, exit, parameters and exports, as pointers the side module's data relocations set. - Compile:
KBUILD_CFLAGS_MODULE += -fPIC -fvisibility=hidden(arch/wasm/Makefile), so a module imports only what it does not define. - Link (
arch/wasm/Makefile.modfinal, included byscripts/Makefile.modfinalin place of itsld -r):wasm-ld -shared --experimental-pic --no-entry --no-gc-sections --unresolved-symbols=import-dynamic --export=__kw_module --export-if-defined=__wasm_call_ctors(and--shared-memoryfor an SMP kernel) into NAME.ko.wasm64;wasm-opt -g --memory64-lowering --table64-lowering -O2(WASM_OPT) into NAME.ko.wasm32; thenarch/wasm/tools/kwko(a host program,archscripts) writes NAME.ko. The .ko files depend on kwko, so a new kwko writes them again. - The .ko (
asm/module.h): ELF, ET_REL, EM_NONE, ELFCLASS64 (the loader'smodule_elf_check_machine(); the arch's programs are arm64). Sections:.modinfoand__ksymtab_strings(from the objects, for the loader and depmod),.gnu.linkonce.this_module(a struct module with its name; size and layout from asm-offsets),.kw.mem(no bits: the side module's data and bss, at its dylink.0 alignment),.kw.wasm64and.kw.wasm32, and.symtab:__this_moduleand, undefined, every kernel or module symbol the side module imports (weak where dylink.0 says so). kwko refuses sections the loader does not set up on wasm (tracepoints, jump labels,__ex_table,__bug_table, static calls, dynamic debug,.ctors/.init_array, kunit, ...) and on SMP per-CPU data. - The kernel with modules has
--growable-tableand exports the wasm globals a module's code uses:__stack_pointer,current, and on SMPkw_irq_flagsandkw_irq_word. WithoutCONFIG_MODULESnone of this is built or exported (kmod.oandmodule.oareobj-$(CONFIG_MODULES), thekw_kmod_cpu_start()hooks are empty inlines).
Which kernel a module is for (vermagic)
A module loads only into the kernel build it was built against. Its
vermagic is RELEASE [SMP ]mod_unload wasm build:<id> config:<hash>
(asm/vermagic.h), for example 7.3.4+ mod_unload wasm build:7ac25b48e04d-mod config:bfb4bc10206d: <id> is the build id of
the banner (KBUILD_BUILD_VERSION, kernel.md, Build stamps: the kernel
tree with its uncommitted changes, kwemu's sources and the build options;
none without one) and <hash> 12 hex digits of the SHA-256 of
include/config/auto.conf (which also names the compiler and linker
versions). arch/wasm/Makefile writes both to generated/kw_build.h in
archprepare; an external module build (M=, test/kmod/build.sh) does
not run it and takes the kernel's, so its modules carry the same vermagic
as the kernel's own. The generic loader refuses any other vermagic
(NAME: version magic '<module's>' should be '<kernel's>', ENOEXEC);
modinfo -F vermagic shows it. The ids are not in the release, so
/lib/modules/RELEASE stays the same across builds. Kernels are
reproducible, so an identical rebuild accepts the modules of the first
build.
This refuses modules that would have worked (any change to the tree, a
different clang or wasm-ld, any config change) rather than load one whose
struct layouts, inline code or arch module ABI (asm/module.h,
asm/kmod.h, the wasm globals a module imports) differ: modules ship and
are rebuilt with their kernel. CONFIG_MODVERSIONS is off: genksyms
works on the wasm objects (the CRCs land in the .cmd files), but
modpost emits no SYMBOL_CRC on wasm, the kernel has no __kcrctab in
the order of its boot-sorted ksymtab, a module's exports have no CRCs in
__kw_module, and kwko does not carry __versions into the .ko; and
CRCs do not see the arch module ABI or code a module inlines from
headers.
Load (arch/wasm/kernel/module.c)
module_frob_arch_sections(): the side module of the running kernel's form (kw_kmod_form():.kw.wasm32on the lowered kernel,.kw.wasm64on vmlinux) becomesSHF_ALLOC, the other not. A .ko without it fails naming the section.- The generic loader lays out and allocates the module (execmem: plain
vmalloc,
execmem_arch_setup()): the struct module and.kw.meminMOD_DATA(zeroed), the image inMOD_RODATA. So/proc/modulescounts the struct module, the image and the data (sizes page-rounded; 2026-11-29, lowered: isofs 49152, libaes 20480, bluetooth 544768, kwbt 12288; wasm64 bluetooth 602112), and the image the backend keeps is the loader's copy. simplify_symbols()resolves the .ko's undefined symbols through the ksymtabs (a table index or an address each).module_finalize():kw_kmod_prepare()on the image,kw_kmod_link()with.kw.memas its memory and the resolved values (by name from the .ko's symbol table), then__kw_module(an export) givesmod->init,mod->exit,mod->kpandmod->syms.module_arch_cleanup()(unload, or a failure after finalize) frees the backend's part before the loader frees the module's memory.
Backend (asm/kmod.h, arch/wasm/kernel/kmod.c)
kw_kmod_form() asks the host which form it instantiates (cached).
kw_kmod_prepare(image, len, name) compiles the image in this CPU's host
(the image is not copied: it must stay until kw_kmod_free()) and gives
the memory size, alignment, table slots and the number of symbol imports.
kw_kmod_link(m, mem, resolve, ctx) resolves every import through the
caller (a table index for a function, an address for data; an unresolved
weak one is 0, and a call to it traps), allocates the table range,
instantiates on every CPU, and runs the constructors (__wasm_call_ctors,
in the kernel, not inside the host import: a call that sleeps there would
have to suspend through the host's frames). kw_kmod_symbol() is an
export of a linked module (a function without a slot gets one, owned by
the module), kw_kmod_free() unloads. Prepare and link of one module run
on one CPU in one system call (the compiled module waits in that CPU's
host); everything sleeps.
Table slots are the kernel's to hand out (kw_kmod_table_alloc(), first
fit past the kernel's own range): a range per module (its elem segment)
and single slots for a module's function that has none (its
__wasm_call_ctors), each freed with the module. The kernel's table never
shrinks.
The module form:
- Imports:
env.memory,env.__indirect_function_table,env.__memory_base/__table_base(and__memory_base32/__table_base32when lowered), the kernel's wasm globals by name, its symbols asenv.NAME(a call),GOT.func.NAME(a function's address),GOT.mem.NAME(data), and for a host-device driver (kwbt) that device'sunkernel.*functions, which CPU 0's host serves. Anything else is refused. The host refuses a module of another form (memory64 or not, shared or not, table64 or not) naming both forms; UP and SMP modules differ anyway (struct layouts followCONFIG_SMP; vermagic says SMP). - The plain form (unshared memory) writes its data segments and zeroes
its bss in its start function at every instantiation; the shared form
does so once, behind a flag in its own memory (zero in
.kw.mem).__wasm_apply_data_relocs(stores only) runs once, at the link, in the host.
Host imports (module unkernel, every CPU; js/core/kmod.ts)
Unlike the device imports they answer on every CPU: each CPU's host
instantiates into its own instance. None suspends. Errors come back as
-errno with the reason written to the kernel's buffer (and the host's
log); kmod.c prints it.
| Import | Does |
|---|---|
wasm_kmod_form() |
KW_KMOD_WASM64 (1) for a memory64 kernel, else KW_KMOD_WASM32 (0) |
wasm_kmod_parse(image, len, info, err, errlen) |
parse dylink.0 and the imports, check the form, compile; a handle, info = memory size, its log2 alignment, table size, its log2 alignment, symbol imports, this table's length |
wasm_kmod_import(handle, i, name, size, flags) |
symbol import i: its name, KW_KMOD_WEAK; returns its kind (1 call, 2 function address, 3 data) |
wasm_kmod_link(handle, rec, list, err, errlen) |
grow the table, instantiate (data written), __wasm_apply_data_relocs, set the record's slots |
wasm_kmod_export(rec, name, len, kind, value) |
a linked module's export: data address, or a function's slot (1: it has none) |
wasm_kmod_sync(list, err, errlen) |
make this host hold what the list says: drop modules no longer on it (their slots null), grow the table, instantiate what it lacks without writing its data, set new slots |
wasm_kmod_drop(handle) |
forget a handle never linked |
The records (kmod.c, all fields u64): kw_kmod_list {first record,
table_top, table_kernel}; kw_kmod_rec {next, id, name, image,
image_len, mem, mem_size, table_base, table_size, values, nr_values,
slots, nr_slots}; kw_kmod_slot {index, name}. Only linked modules are on
the list.
SMP
A link runs on the loading CPU's host first (data written and relocated
there), then the record goes on the list and every other online CPU
syncs in an IPI (smp_call_function(), waited for) before the link
returns, so init runs with the module on every CPU at the same slots. A
CPU that fails makes the link fail, and every CPU drops it again (a
driver's unknown host import is refused by CPU 0's host after the
loading CPU linked it). A free syncs the same way. Links and frees hold
cpus_read_lock(), and a CPU's bring-up syncs in kw_secondary_start()
before it runs anything. A module's code that calls a host device import
runs it on CPU 0 (kw_host_call(), exported for modules; kwbt's init).
Snapshots
The records, images and module memory are kernel memory, so a snapshot
has them. __kw_resume() (CPU 0, UP and SMP) and
kw_secondary_restart() call kw_kmod_cpu_start() before anything
else runs: a sync that instantiates every module at its old bases with
its old resolved values and slots. A shared-memory module's start
function skips its data (the flag in its memory is 2); for a plain one
the host copies its memory before instantiating and puts it back after.
No load can be in flight at the snapshot point: a load is inside a
system call, and a task parks only on its way to user mode. The backend
adds no kernel thread.
Cost in RAM (and in the snapshot) beyond what /proc/modules counts: a
record of 104 bytes and a few small allocations per module, 8 bytes per
symbol import, 16 bytes and a name per added slot.
Toolchain
Three things of the patched wasm-ld (toolchain.md) are worked around:
- A linker-script
SORT()that matches input sections uses an iterator into the output segment's list across appends that may reallocate it. vmlinux.lds.S definesSORT(files)asfiles; only the symbol tables ofCONFIG_MODULESmatch one, and module.c sorts them at boot. Without modules noSORT()matches anything: the default vmlinux is the same byte for byte with and without the define (2026-11-29). - A script label before a bounded section is the dot before the
section's first input is aligned. vmlinux.lds.S's
BOUNDED_SECTION_PRE_LABELaligns the dot to 8 first (with modules,__paramfollows the odd-sized__ksymtab_strings). The default vmlinux is the same byte for byte with and without it (2026-11-29). --no-merge-data-segmentswith-shared --experimental-picaddresses merged strings wrongly, so the fake-llvm wrapper adds none of its final-link flags to a-sharedlink (the kernel build has no other).
vmlinux.lds.S discards .modinfo: modpost now reads vmlinux.o and writes
the built-in modules' device aliases into .vmlinux.export.c, and wasm
has no non-loaded sections, so it would be data in the image (93 KB of
vmlinux, 2026-11-29). Nothing reads it at run time.
Sizes (2026-11-29, raw / gzip -n -9)
| Kernel | lowered | wasm64 |
|---|---|---|
| default UP (iso9660, Bluetooth built in) | 8,897,747 / 2,981,478 | 10,701,110 / 3,378,680 |
modules UP (both =m) |
9,449,331 / 3,132,381 | 10,531,664 / 3,316,009 |
UP with CONFIG_MODULES, nothing =m (6,859 exports) |
9,968,916 / 3,310,559 | |
| default SMP | 9,759,573 / 3,110,194 | |
| modules SMP | 10,334,320 / 3,268,265 |
Testing
pnpm test:kmod: test/kmod-host.test.ts (the parser on hand-built
side modules) and test/kmod.test.ts, which builds the test modules of
test/kmod/ (kmt_*.c, Kbuild) as external modules against
vendor/build/kernel-mod and kernel-mod-smp (test/kmod/build.sh KOUT OUT: make M=test/kmod MO=OUT modules, the same modpost, link, lowering
and kwko as the kernel's own) and loads them into the base shell with
modules.cpio appended: UP lowered and wasm64, inline and worker mode,
SMP with 2, 4 and 8 CPUs, the kernel's own iso9660 (on request) and
Bluetooth (kwbt, with the emulated controller) through a snapshot,
vermagic (the build id and configuration hash; a .ko whose vermagic names
another build or configuration refused, UP and SMP, lowered and wasm64;
with UNKERNEL_TEST_KOUT_OTHER, the test modules built against another
modules kernel refused), and
the bundle of the pair with that one cpio booted with 1 CPU and 2
(uname -r, iso9660 on request, modprobe kwbt with bluetooth and
libaes). The
header lists its variables; each kernel's tests skip when it is not
built.