Loading and Unloading First Kernel Module in FreeBSD
A hands-on guide to writing, compiling, and loading your first FreeBSD kernel module. From source to kldload.
Your first kernel module. There's something deeply satisfying about writing code that runs in kernel space. No standard library, no safety nets, just you and the machine.
This guide walks through creating a simple FreeBSD kernel module from scratch. By the end, you'll have a working module that you can load and unload at will.
Setting Up
Before we write any code, make sure you have the FreeBSD source tree installed. You'll need the kernel headers for compilation.
sh# If you don't have sources installed pkg install git git clone https://git.freebsd.org/src.git /usr/src
The Module Source
Let's create the simplest possible kernel module. Create a file called hello_kmod.c:
c#include <sys/param.h> #include <sys/module.h> #include <sys/kernel.h> #include <sys/systm.h> static int hello_modevent(module_t mod, int event, void *arg) { switch (event) { case MOD_LOAD: uprintf("Hello, kernel!\n"); break; case MOD_UNLOAD: uprintf("Goodbye, kernel!\n"); break; default: return (EOPNOTSUPP); } return (0); } static moduledata_t hello_mod = { "hello", hello_modevent, NULL }; DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
Let's break this down:
- ·MOD_LOAD is called when the module is loaded via kldload
- ·MOD_UNLOAD is called when the module is unloaded via kldunload
- ·uprintf prints to the user's terminal, not the console
- ·DECLARE_MODULE registers our module with the kernel
The Makefile
FreeBSD's build system makes compiling kernel modules straightforward. Create a Makefile:
makeSRCS=hello_kmod.c KMOD=hello .include <bsd.kmod.mk>
That's it. The bsd.kmod.mk include handles all the complexity of kernel module compilation.
Building and Loading
Now for the moment of truth:
sh# Compile the module make # Load it (requires root) sudo kldload ./hello.ko # Check it's loaded kldstat | grep hello # Unload it sudo kldunload hello
When you load the module, you'll see "Hello, kernel!" printed to your terminal. When you unload it, "Goodbye, kernel!" appears.
What Just Happened
Your code is now running in ring 0. It has full access to the system: memory, devices, everything. This is both the power and the danger of kernel programming.
A few things to note:
- ·Bugs in kernel code can panic the system
- ·Memory leaks in the kernel persist until reboot
- ·There's no printf from libc. Use uprintf or the kernel's printf which goes to console/dmesg
Next Steps
This is just the beginning. From here, you can explore:
- ·Character devices (/dev/yourdevice)
- ·System calls
- ·File system modules
- ·Network protocol handlers
The FreeBSD kernel is remarkably well-documented. Start with the source, and don't be afraid to read it.
Welcome to kernel space.