Skip to content
systemcoding.dev
Kernels

Write Your First Rust Kernel Module

Write, build and load a first Rust kernel module in a Linux 6.18 tree: the module! macro, init and Drop, KVec, Kconfig and Makefile entries and dmesg output.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Rust, Linux and GNU logos.

A first module should prove the whole path works: source file, build system entry, compiler, loader, log. This post writes a small Rust module for a Linux 6.18 tree, adds it to the sample directory so the kernel build picks it up, builds it, loads it and reads its messages. It is the entry-level walk-through: it assumes the toolchain from setting up a Rust for Linux environment is working and says nothing about drivers, which come later in the series. If you have written a C module before, the shape will be familiar; what changes is how the entry point, cleanup and errors are expressed.

The pieces used here, module!, kernel::Module, KVec and pr_info!, are the ones in samples/rust/rust_minimal.rs of the 6.18 tree, and the module documentation is generated from rust/kernel/.

The module

Create samples/rust/rust_hello.rs:

samples/rust/rust_hello.rsrust
// SPDX-License-Identifier: GPL-2.0

//! A first Rust kernel module.

use kernel::prelude::*;

module! {
    type: Hello,
    name: "rust_hello",
    authors: ["Example Author"],
    description: "First Rust kernel module",
    license: "GPL",
}

struct Hello {
    greetings: KVec<&'static str>,
}

impl kernel::Module for Hello {
    fn init(_module: &'static ThisModule) -> Result<Self> {
        pr_info!("loading\n");

        let mut greetings = KVec::new();
        greetings.push("hello", GFP_KERNEL)?;
        greetings.push("kernel", GFP_KERNEL)?;

        for greeting in greetings.iter() {
            pr_info!("greeting: {}\n", greeting);
        }

        Ok(Hello { greetings })
    }
}

impl Drop for Hello {
    fn drop(&mut self) {
        pr_info!("unloading, {} greetings dropped\n", self.greetings.len());
    }
}

Go through it from the top. The first line is the license identifier the kernel requires in every source file. use kernel::prelude::* brings in the names almost every kernel Rust file needs: Result, KVec, GFP_KERNEL, the pr_info! family, ThisModule and the error codes.

The module! macro declares the module's metadata and generates the glue that the C module loader expects. type names the struct that holds the module's state, name is the module name and so the file name rust_hello.ko, and authors, description and license fill the usual MODULE_AUTHOR, MODULE_DESCRIPTION and MODULE_LICENSE fields. The license string matters: a module that does not declare a GPL-compatible license cannot use GPL-only kernel symbols, and the kernel crate is built on them.

The state is a struct, Hello, which here owns a vector of string slices. The entry point is the init function of the kernel::Module trait. It returns Result<Self>: on success, the value is the module's state, kept alive until unload; on failure, the error is an errno and the module does not load. KVec::new() creates an empty vector without allocating. Each push may allocate, takes the allocation flags GFP_KERNEL because initialization may sleep, and returns a Result that the ? operator turns into an early return of the error. If the second push failed, the function would return Err(ENOMEM), greetings would be dropped on the way out and its memory freed, and insmod would report that the module could not be inserted.

Cleanup is not a separate function. When the module is unloaded, the kernel drops the Hello value, and its Drop implementation runs. self.greetings.len() works because KVec dereferences to a slice. After drop returns, the fields are dropped in order, which frees the vector. In C you would write module_exit and free by hand, and an error path in init would need its own unwinding code. Here ownership does both.

Tell the build about it

Samples have two registration points. First the Kconfig entry. Add this inside the if SAMPLES_RUST block of samples/rust/Kconfig, next to the other samples:

samples/rust/Kconfigkconfig
config SAMPLE_RUST_HELLO
	tristate "Hello"
	help
	  This option builds the first Rust kernel module.

	  To compile this as a module, choose M here:
	  the module will be called rust_hello.

	  If unsure, say N.

Second, the Makefile line in samples/rust/Makefile, which maps the Kconfig symbol to the object file. The object name is the source file name with .o:

samples/rust/Makefilemakefile
obj-$(CONFIG_SAMPLE_RUST_HELLO)			+= rust_hello.o

Kbuild finds rust_hello.rs automatically for rust_hello.o when the file is in a directory built with Rust support. This is the same pattern the existing entries use, as in obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o.

Configure and build

Enable the new symbol as a module and build:

Shell
./scripts/config -e RUST -e SAMPLES_RUST -m SAMPLE_RUST_HELLO
make LLVM=1 olddefconfig
make LLVM=1 -j"$(nproc)"
ls samples/rust/rust_hello.ko
Text
samples/rust/rust_hello.ko

If the build fails, the compiler's messages are in the usual Rust format, with the file, the line and a suggested fix. The two most common first errors are a missing use for a name the prelude does not export, and a type mismatch from forgetting that push takes the flags argument. A third is forgetting the Result return type on init, which the trait requires.

Load it and read the log

On a machine or VM running this exact kernel build, load and unload the module and read the kernel log. The rust_hello: prefix is added by the pr_info! macros from the module name, so the messages do not repeat it:

Shell
insmod samples/rust/rust_hello.ko
rmmod rust_hello
dmesg | tail -n 4
Text
rust_hello: loading
rust_hello: greeting: hello
rust_hello: greeting: kernel
rust_hello: unloading, 2 greetings dropped

Your dmesg output has a timestamp in front of each line. modinfo samples/rust/rust_hello.ko prints the metadata from the module! block: the author, description and license, plus the kernel version it was built for. A module built for another kernel will not load; the loader rejects it with a version mismatch.

See the error path work

Change one line of init to fail after the pushes, for example by returning an error when a condition holds:

rust
        if greetings.len() > 1 {
            return Err(ENODEV);
        }

Rebuild, and loading now fails with the error you chose:

Text
insmod: ERROR: could not insert module samples/rust/rust_hello.ko: No such device

Nothing is left behind: the vector was dropped as init returned, so there is no leak to hunt, and no Drop runs for Hello because the value was never constructed. Compare that with the C equivalent, where every early return after an allocation needs a goto to the right cleanup label. This is the practical gain of ownership in the kernel, and you can feel it in a thirty-line module.

What the macro hides

module! expands to a good deal of code, including the module's init and cleanup functions, a static holding the module's type, and the .modinfo strings. You can read the expansion with make LLVM=1 samples/rust/rust_hello.rsi, which writes the preprocessed Rust source. It shows that the init function the kernel calls is an extern "C" function that creates your Hello through kernel::Module::init, and that the cleanup function drops it. Read it once to confirm that nothing magic is going on; the rest of Rust for Linux builds on the same few ideas.

Where this does not fit

A module with no driver and no hardware is a teaching tool. Real code needs a kernel subsystem to attach to, which means an abstraction: a misc device, a platform driver, a PCI driver. Those also need a module state that can be shared between contexts, which brings in the Mutex and Arc types and in-place initialization with pin_init. And building an in-tree sample is not the same as shipping a module for a distribution kernel: out-of-tree Rust modules need the kernel's CONFIG_RUST build, with the same compiler, and are less well supported than in-tree ones.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.