</>EmbeddedInterview

What is a loadable kernel module?

EasyLinux Kernel & Device Drivers

Short answer: A loadable kernel module (.ko file) is kernel code that can be inserted into and removed from a running kernel without rebooting. It has an init function (run on load) and an exit function (run on unload), and it can use only symbols the kernel exports (EXPORT_SYMBOL, EXPORT_SYMBOL_GPL). Most drivers are built as modules so the kernel image stays small and hardware support loads on demand.

#include <linux/module.h>
#include <linux/init.h>

static int debug;
module_param(debug, int, 0644);                 /* /sys/module/hello/parameters/debug */
MODULE_PARM_DESC(debug, "enable debug output");

static int __init hello_init(void)
{
    pr_info("hello: loaded, debug=%d\n", debug);
    return 0;                                   /* non-zero = load fails */
}

static void __exit hello_exit(void)
{
    pr_info("hello: unloaded\n");
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("You");
MODULE_DESCRIPTION("Minimal example");

Key points

  • __init code is discarded after loading (for built-in code, after boot); __exit code is dropped if the module is built in.
  • Without a GPL-compatible MODULE_LICENSE, the kernel is tainted and GPL-only symbols are unavailable.
  • Parameters can be given at load time (insmod hello.ko debug=1) or on the kernel command line for built-in code (hello.debug=1).
  • Commands: insmod/modprobe to load, rmmod/modprobe -r to remove, lsmod, modinfo hello.ko.
  • The module must match the kernel's version and configuration (vermagic); with CONFIG_MODVERSIONS, symbol CRCs are checked too. Secure-boot systems may require signed modules.

Built-in vs module: obj-y (always in the image, needed for the root filesystem or early boot) vs obj-m (loadable). Kconfig choices y/m/n.