Module 5 · Lesson 101 of 129

A first Rust kernel module

Configure Linux 6.8 for Rust, build a hello-world module with Kbuild, and verify its initialization and cleanup in the kernel log.

  • Beginner to advanced
  • 7 min read
  • 55 min lab
What you will need

Ubuntu 24.04 in an x86-64 VM with sudo, bootable Linux 6.8 source and configuration, and space for a kernel build

Your place in the module
By the end you can 4 objectives
  • Identify the Rust build tools required by a Linux 6.8 source tree
  • Enable and verify CONFIG_RUST in a bootable kernel configuration
  • Implement a module with module!, kernel::Module and Drop
  • Build, load, inspect and unload a Rust kernel module
Video coming soonA first Rust kernel module
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from USB and the driver class survey
  • USB interface drivers register a match table with USB core and probe individual interfaces.
  • An accepted URB completes asynchronously and reports its status and actual transfer length.
  • A driver's hardware bus and the subsystem it registers with determine different aspects of its behavior.
01

Enable Rust in the kernel build

3 min read

The last lesson ended the C driver survey. This lesson answers the Rust alternative, its toolchain and CONFIG_RUST, and the module! macro and Module trait behind a first module.

Rust support first entered mainline Linux in 6.1. The Linux 6.8 Rust Quick Start documents the tools needed to use that support. Linux 6.8 can build and load a Rust module, and its source tree includes Rust samples. The available Rust interfaces depend on the kernel release, so an example written for a newer tree can fail even when the compiler works. For this lesson, use an upstream Linux 6.8 tree and an Ubuntu 24.04 x86-64 VM where you can boot the kernel you build. Keep the VM's original kernel available at boot.

CONFIG_RUST=y enables the kernel's Rust build support. A loadable sample also needs CONFIG_MODULES=y. Enable CONFIG_MODULE_UNLOAD=y so you can run the cleanup path without rebooting. Installing Rust in Ubuntu supplies a compiler for the build host. The kernel configuration and the image you boot determine whether you can run the sample.

Preparing Rust supportKernelsource treeToolversion requirementsInstallbuild toolsrustc,rust-src,bindgen,LLVMCheck rustavailableEnableCONFIG_RUSTKernelsource treeToolversion requirementsInstallbuild toolsrustc,rust-src,bindgen,LLVMCheck rustavailableEnableCONFIG_RUST
The source tree specifies the Rust tools and Kbuild checks them before configuration

Kbuild invokes rustc to compile Rust code and needs the matching Rust standard-library source from the rust-src component to build the Rust core library for the kernel. It invokes bindgen to generate Rust declarations from C headers. bindgen needs libclang to parse those headers, so installing the executable alone is insufficient. Use LLVM=1 consistently to have Kbuild select Clang and the LLVM tools, including the linker. Keep the ordinary kernel build dependencies from the earlier build lesson.

Install the Ubuntu packages clang, llvm, lld and libclang-dev. With rustup available in your shell, run these commands from the Linux source root. The version lookups use the selected kernel tree so they also work when the exact requirement differs between source trees.

bash
rust_version=$(scripts/min-tool-version.sh rustc)
bindgen_version=$(scripts/min-tool-version.sh bindgen)
rustup toolchain install "$rust_version" --component rust-src
rustup override set "$rust_version"
cargo install --locked --version "$bindgen_version" bindgen-cli
make LLVM=1 rustavailable

cargo install installs the host-side bindgen tool. Kbuild compiles the kernel module itself. Make sure rustc and the installed bindgen are on your PATH when you run make. If rustavailable fails, read its diagnostic and repeat the check after correcting the tool version, missing Rust sources or libclang lookup it reports. A successful check establishes tool availability. Kconfig still decides whether the selected architecture and other options permit enabling Rust.

Start from the bootable VM configuration you used for the kernel build lesson. On Linux 6.8, CONFIG_MODVERSIONS conflicts with Rust. If Rust is missing in the configuration menu, search for RUST in menuconfig and inspect the dependencies shown for your configuration. Run make LLVM=1 menuconfig, enable Rust support and module unloading, then save and check the resulting settings.

bash
grep -E '^CONFIG_(RUST|MODULES|MODULE_UNLOAD)=y$' .config

Here you want all three settings. If one is absent, resolve the configuration dependency before compiling. This check is worth doing after Kconfig saves the file because it shows the effective selection that Kbuild will use.

02

Write the module and read its metadata

2 min read

Replace the contents of samples/rust/rust_minimal.rs in your lab tree with the source below. The tree already connects that file to the CONFIG_SAMPLE_RUST_MINIMAL sample option. Reusing the existing entry lets you build the example from the same configuration as the boot image.

rust
// SPDX-License-Identifier: GPL-2.0

use kernel::prelude::*;

module! {
    type: RustMinimal,
    name: "rust_minimal",
    author: "Embedded Linux course",
    description: "Rust hello-world module",
    license: "GPL",
}

struct RustMinimal;

impl kernel::Module for RustMinimal {
    fn init(_module: &'static ThisModule) -> Result<Self> {
        pr_info!("Rust hello-world initialized\n");
        Ok(Self)
    }
}

impl Drop for RustMinimal {
    fn drop(&mut self) {
        pr_info!("Rust hello-world unloaded\n");
    }
}

use kernel::prelude::*; brings commonly used kernel Rust items into scope, including module!, ThisModule, Result and pr_info!. module! names the Rust type that represents the loaded instance and supplies the module name, author, description and license. It also generates the integration code that connects the kernel's module entry and exit paths to the Rust instance. The SPDX comment identifies the source file's license, and license: "GPL" supplies the license metadata in the module artifact.

Lifetime of a Rust moduleInsertmoduleCall Module::initKeep RustinstanceRemovemoduleExit from step 2: init returns errorInsertion failsRunDrop::dropInsertmoduleCall Module::initExit from step 2: initreturns errorInsertion failsKeep RustinstanceRemovemoduleRunDrop::drop
Successful initialization creates the instance and unloading runs its Drop implementation

kernel::Module is the trait that defines the initialization method. The argument gives the method a reference to the current module. This example leaves it unused, as the leading underscore indicates. Returning Ok(Self) tells the loader that initialization succeeded and provides the instance to keep until unload. RustMinimal has no fields because the example has no state to keep. Returning an error from init would make insertion fail. After successful insertion, removing the module runs Drop::drop on the stored instance, where this example records the unload event. Both messages go to the kernel log.

A lets an operator configure a module without recompiling. For a module that declares a parameter, use modinfo -p on the module or its file to list the advertised parameters and pass values as name=value arguments after the file path to insmod. In Linux 6.8, the Rust module! macro accepts the metadata shown above and has no params: field. The hello-world module therefore advertises no parameters. You can confirm that with modinfo -p samples/rust/rust_minimal.ko after building it. When adapting an example that declares Rust parameters, first check the macro implementation or samples in that example's kernel release.

03

Build, load and verify the module

2 min read

Return to make LLVM=1 menuconfig. Under Kernel hacking, enable Sample kernel code, open its Rust samples menu (it appears only when CONFIG_RUST is enabled) and set Minimal to <M>. Verify that the effective configuration contains CONFIG_SAMPLE_RUST_MINIMAL=m. That setting produces a separate .ko file. A y selection would build the sample into the boot image, where its initialization would run during boot and you could not remove it with rmmod.

Build and verifyBuild imageand moduleBoot builtimageInsertmoduleRemovemoduleRead kernellogBuild imageand moduleBoot builtimageInsertmoduleRemovemoduleRead kernellog
Kbuild produces a boot image and a module that you test together

Build the kernel and its configured modules from the source root. Save the kernel release printed by the second command so you can compare it after reboot.

bash
make LLVM=1 -j"$(nproc)"
make -s LLVM=1 kernelrelease

For an in-tree build, the module is samples/rust/rust_minimal.ko. Use the installation and boot procedure from the earlier kernel-build lessons to install this build and boot its image. Build and boot from the same tree and configuration. A different image can have a different module version string or different available symbols, even if it also belongs to the 6.8 series.

After reboot, return to the source root. Compare the running release from uname -r with the saved release, and inspect vermagic on the .ko. The first field of vermagic should match the running release. The rest records build properties that also matter to module compatibility, so a matching release alone is an initial check.

bash
uname -r
modinfo -F vermagic samples/rust/rust_minimal.ko
modinfo -p samples/rust/rust_minimal.ko

Insert the module by file path. In the next command, lsmod reports the module by its registered name. Remove it by that same name and read the latest kernel messages. Run each command after the previous operation succeeds.

bash
sudo insmod ./samples/rust/rust_minimal.ko
lsmod | grep '^rust_minimal '
sudo rmmod rust_minimal
sudo dmesg | tail

Find the initialization message after insertion and the unload message after removal. On a busy VM, tail may miss an earlier message. In that case, filter the kernel log with sudo dmesg | grep 'Rust hello-world' and use the timestamps to identify the pair from your latest run. If insmod reports an invalid module format, check the kernel log for the reason and compare the running image with the build that produced the .ko. If loading fails on a signature check, follow the module signing policy of the VM's booted kernel. Changing the Rust source or rerunning rustavailable will leave those loader errors in place.

The practice below follows the same sequence and uses both log messages as evidence that the module completed its lifecycle. The next lesson, Rust abstractions and the safety model, explains the guarantees Rust interfaces can provide once a module starts working with kernel resources.

Key takeaways

  • CONFIG_RUST enables Rust support in a kernel build, and CONFIG_MODULES enables loadable modules.
  • Kbuild uses rustc, the selected LLVM tools and bindgen to build against the kernel tree.
  • The module! macro supplies module metadata and connects the loader to the type that implements kernel::Module.
  • The Linux 6.8 Rust module! macro has no module parameter declaration support.
Reflect
  1. Explain to a colleague, in two sentences: identify the Rust build tools required by a Linux 6.8 source tree
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close