You cannot currently use Rust to write loadable Linux kernel modules (.ko files) in the same way you do with C, because the kernel does not yet support dynamically loading Rust code. However, you can write Rust code that is compiled directly into the kernel image (built-in modules) on Linux 6.1 and newer, which is the standard approach for production use today.
The Rust-for-Linux project provides the necessary tooling, but it requires a specific build environment and kernel configuration. You must enable CONFIG_RUST in your kernel config and use the rustc compiler that matches the kernel's internal toolchain. The build process is handled entirely by the kernel's Kbuild system, not by cargo directly.
Here is a minimal example of a built-in Rust kernel module. First, ensure your kernel config has CONFIG_RUST=y and CONFIG_RUST_IS_ENABLED=y.
1. Create the Rust source file (drivers/example/rust_module.rs):
// drivers/example/rust_module.rs
use kernel::prelude::*;
mod init {
use super::*;
pub fn init() -> Result<(), Error> {
info!("Rust module initialized successfully!");
Ok(())
}
pub fn exit() {
info!("Rust module exiting.");
}
}
module!(
name: "rust_example",
init: init::init,
exit: init::exit,
);
2. Create the build configuration (drivers/example/Kconfig):
config RUST_EXAMPLE
tristate "Rust Example Module"
depends on RUST
default n
help
A simple example of a Rust kernel module.
3. Create the Makefile (drivers/example/Makefile):
obj-$(CONFIG_RUST_EXAMPLE) += rust_example.o
rust_example-objs := rust_module.o
4. Build the kernel:
Run the standard kernel build command from the kernel root directory:
make -j$(nproc)
If successful, the Rust code is compiled and linked directly into the vmlinux image. You can verify it is loaded by checking dmesg for the "Rust module initialized successfully!" message upon boot.
Key Constraints:
- No Dynamic Loading: You cannot compile this as a separate
.kofile to load withinsmodormodprobeyet. The code must be compiled into the kernel image at build time. - Toolchain: You must use the Rust compiler version pinned by the kernel source (usually found in
rust/within the kernel tree). Using your system'srustcwill fail due to ABI mismatches. - Async Support: The kernel's Rust implementation uses a custom async runtime; standard
tokioorasync-stdare not compatible. Use thekernelcrate's async primitives.
This approach is stable for kernel 6.1+ and is the only supported method for using Rust in the Linux kernel today.