Skip to content

Linux Kernel Module (LKM)


Overview

A Linux Kernel Module (LKM) is a piece of code that can be dynamically loaded into the kernel.

It allows extending kernel functionality without rebuilding the kernel.


Why Kernel Modules?

  • Add device drivers
  • Extend kernel features
  • Debug kernel behavior

Kernel Space vs User Space

Type Description
User Space Applications
Kernel Space Core OS + drivers

Kernel modules run in kernel space.


Basic Structure

Minimal example:

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

static int __init hello_init(void)
{
    printk(KERN_INFO "Hello, Kernel Module Loaded!\n");
    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_INFO "Goodbye, Kernel Module Unloaded!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");

Build System

Makefile:

obj-m += hello.o

KDIR := /lib/modules/$(shell uname -r)/build
PWD  := $(shell pwd)

all:
$(MAKE) -C $(KDIR) M=$(PWD) modules

Build Output

After compilation:

  • .ko → kernel object (module)
  • .o, .mod.c, .symvers → build artifacts

Load / Unload Module

Load module:

sudo insmod hello.ko

Unload module:

sudo rmmod hello

Check Module Status

lsmod
modinfo hello.ko

Kernel Logging

Use printk instead of printf.

printk(KERN_INFO "info message\n");
printk(KERN_ERR  "error message\n");

View logs:

dmesg | tail

Important Notes

1. No standard C library

  • No printf
  • No malloc (use kmalloc)

2. Kernel crash risk

  • Bugs can crash the entire system
  • No memory protection like user space

3. Licensing

MODULE_LICENSE("GPL");

Required to avoid kernel warnings.


Summary

  • Kernel modules extend kernel dynamically
  • .ko files are loadable modules
  • printk is used for debugging
  • Runs with highest privilege

Next Step

  • Character device driver
  • file_operations
  • User ↔ Kernel communication