
Recall first from Rust for Linux and the build
- CONFIG_RUST_IS_AVAILABLE reports toolchain availability, while CONFIG_RUST enables Rust support when the kernel configuration permits it.
- Kbuild uses the sample's tristate value to select a built-in object or a loadable module.
- The host-side macros crate and the target-side kernel crate have different roles in the same build.
Declare a module and its lifetime
4 min readYou built the kernel with Rust enabled. This lesson answers how to declare a module with module! and return kernel errors.
A .ko file can exist on disk and still fail to load because its initialization routine returned an error. Linux reports that failure to the program requesting insertion. This is a useful property for a driver with missing hardware or invalid settings. It is also easy to see with a hello module. You can make one insertion succeed and another fail using the same file, then use the kernel log to tell how far each request got. Kernel module loading
module! is a procedural macro from the kernel's macros crate, and use kernel::prelude::*; brings it into scope. It declares which Rust type implements the module and supplies metadata for the kernel build. Use it once for this module. The type field names the Rust type. The name field gives the module its name, which matches the Kbuild target in this example. author credits the author, and description gives the module a short human-readable description. license supplies the module license declaration the kernel uses for purposes such as access to GPL-only exports. The source file still carries its own SPDX identifier. The optional alias field takes an array of strings, such as alias: ["embeddex-hello"], and advertises alternate match names. For example, a device module can advertise a device alias so userspace can resolve that alias to the module. This hello module has no device to match, so it leaves the optional field out.
On Linux 6.8, the macro reads the metadata values from the Rust source as plain ASCII string literals. It rejects escape sequences, raw strings, and b"..." byte strings. Here is the complete Rust source for the parameter-free module. Save it as embeddex_hello.rs if you follow it in the lab.
// SPDX-License-Identifier: GPL-2.0
use kernel::prelude::*;
module! {
type: MyModule,
name: "embeddex_hello",
author: "Embeddex",
description: "Rust hello module",
license: "GPL",
}
struct MyModule;
impl kernel::Module for MyModule {
fn init(_module: &'static ThisModule) -> Result<Self> {
pr_info!("embeddex_hello: loaded\n");
Ok(Self)
}
}
impl Drop for MyModule {
fn drop(&mut self) {
pr_info!("embeddex_hello: unloaded\n");
}
}
kernel::Module is the trait that defines the initialization contract. The prelude brings Result, ThisModule, the error constants such as EINVAL, and the pr_* macros into scope. The kernel passes init a reference to ThisModule, the handle for this module. The example has no use for the handle, so the argument starts with an underscore. The successful return value is a MyModule instance. This version uses a unit struct because it has no settings or resources to keep. In the parameterized version, the instance will keep a value that the destructor can read.
For a loadable module, the macro supplies the entry points corresponding to C's module_init and module_exit. The generated initialization code calls your Module::init. On Ok(instance), it retains the instance and reports success to the kernel. On Err(error), it reports the negative errno. When the kernel proceeds with ordinary module removal, the generated exit code drops the retained instance. The drop method is where this example logs that removal. It has no return value and cannot ask the kernel to cancel removal. The kernel can reject a removal request before the exit code runs, for example if the module is in use. Kernel module unloading
You may also see #[vtable] in Rust kernel examples. That attribute belongs on traits and implementations that use the kernel's vtable support, such as operation traits that expose which optional callbacks an implementation supplies. kernel::Module on Linux 6.8 uses a plain impl Module for MyModule. Its lifecycle entry points come from module!, and its destructor is an ordinary impl Drop. When borrowing code from a driver sample, check which trait the attribute belongs to before copying it.
Return a kernel error from initialization
3 min readThe kernel uses negative errno values to report many failures at C interfaces. Rust code expresses the same failures with kernel::error::{Error, Result}. Result<T> is a result whose error type is the kernel's Error. For initialization, T is Self. A function that only needs to report success or failure can return Result<()>. If the reason is already known in Rust, use a named error constant. The module later in this lesson returns Err(EINVAL) when its input falls outside the accepted range.
In Linux 6.8, Error::from_errno is crate-private, so module code cannot call it. A module gets an Error from a named constant such as EINVAL, from ? on an API that already returns Result, or from kernel::error::to_result. Error::to_errno() is public and returns the signed kernel form, such as -EINVAL in C terms, which the generated entry point hands back to the kernel.
kernel::error::to_result() takes a C int status for APIs in which negative values report failures and any nonnegative value indicates success. It converts a negative status to Err(Error) and a nonnegative status to Ok(()). Use it directly when the successful number carries no information you need. If the successful number is a byte count or an index, call to_result for the check and keep the original number yourself, because a Result<()> alone cannot tell you how many bytes a call transferred. The C interface's documented return convention determines whether this conversion is appropriate.
use kernel::error::to_result;
use kernel::prelude::*;
fn check_status(status: core::ffi::c_int) -> Result {
to_result(status)
}
fn preserve_count(status: core::ffi::c_int) -> Result<core::ffi::c_int> {
to_result(status)?;
Ok(status)
}
The first function fits a C call whose useful outcome is simply success. The second fits a C call that returns a count on success and an errno on failure. Both assume the C function returns a valid negative errno on failure. For the first case, an initializer can call to_result(status)? and then continue constructing its state. If the value is negative, ? returns the error from init, and the entry point generated by the macro returns that errno to the kernel. The userspace insertion command then sees a failed syscall. Any diagnostic you printed before the failure can still be in the kernel log.
If init returns an error before creating a MyModule, there is no retained module instance to drop at unload. Already-created Rust locals follow their usual drop rules on the early return. For this example, validating the setting before constructing MyModule also makes the log easy to interpret. A rejection message means the initializer reached its validation branch. A successful load message means the setting passed validation and the initializer is about to return its instance. When comparing logs from several attempts, use the order of messages or watch them live so that a message from an earlier insertion does not get attributed to a later one.
Load a hello module with a parameter
4 min readA load-time parameter lets you change a setting between insertions of the same .ko. The Linux 6.8 Rust module! macro has no parameter declaration field. For this lab, link a short C source file and the Rust source into a single module. The C source declares the integer parameter using the kernel's module_param macro and exposes a getter. Rust calls the getter during init and records the value it accepts. The C source uses kernel headers and builds through Kbuild. Building external modules
Save this as hello_param.c. greet defaults to 1. The 0444 mode makes the sysfs parameter readable and gives it no write permission. A value supplied at insertion can still replace the default because the kernel parses the supplied argument before initialization. The C getter takes no arguments and returns a C int by value.
// SPDX-License-Identifier: GPL-2.0
#include <linux/moduleparam.h>
static int greet = 1;
module_param(greet, int, 0444);
MODULE_PARM_DESC(greet, "Greeting value from 1 through 3");
int embeddex_hello_get_greet(void);
int embeddex_hello_get_greet(void)
{
return greet;
}
Save the Rust source as hello_main.rs. It keeps the module! declaration from the first example, including name: "embeddex_hello", and replaces the struct and its two implementations. The foreign function declaration must match the C definition. The unsafe call is justified here by the matching signature and the getter's implementation, which reads the module's integer and returns it by value. It takes no pointers and has no caller-side memory requirements.
// SPDX-License-Identifier: GPL-2.0
use core::ffi::c_int;
use kernel::prelude::*;
module! {
type: MyModule,
name: "embeddex_hello",
author: "Embeddex",
description: "Rust hello module with a parameter",
license: "GPL",
}
extern "C" {
fn embeddex_hello_get_greet() -> c_int;
}
struct MyModule {
greet: c_int,
}
impl kernel::Module for MyModule {
fn init(_module: &'static ThisModule) -> Result<Self> {
// SAFETY: The linked C getter takes no arguments and returns an int.
let greet = unsafe { embeddex_hello_get_greet() };
if !(1..=3).contains(&greet) {
pr_err!("embeddex_hello: unsupported greet={}\n", greet);
return Err(EINVAL);
}
pr_info!("embeddex_hello: loaded with greet={}\n", greet);
Ok(Self { greet })
}
}
impl Drop for MyModule {
fn drop(&mut self) {
pr_info!("embeddex_hello: unloaded with greet={}\n", self.greet);
}
}
Put the following two lines in Kbuild beside those sources. For the parameter-free version, use just the obj-m line and the original embeddex_hello.rs instead. The composite build combines hello_main.o and hello_param.o into the one module named by obj-m. The Rust declaration still uses the final module name, even though its source file now has a different name.
obj-m := embeddex_hello.o
embeddex_hello-y := hello_main.o hello_param.o
From the source directory, with KDIR set to the prepared build tree for the running lab kernel, build and inspect the file with the commands below. modinfo reads the file's metadata without loading it. Its description, license, and parameter information let you verify which artifact you are about to insert. A module built against a different kernel can fail before its Rust initializer runs. Use the same build and boot environment for the positive and negative tests.
make -C "$KDIR" M="$PWD" modules
modinfo ./embeddex_hello.ko
The pr_info! and pr_err! macros send messages to the kernel log through the kernel's printk facilities. In a separate terminal, sudo dmesg --follow lets you watch the log while issuing commands in the first terminal. The messages belong to the kernel even though the load command runs in userspace. Inserting successfully can produce no text in the command's own terminal. The module's messages are available from the kernel log subject to access permissions. Message logging with printk
sudo insmod ./embeddex_hello.ko greet=2
cat /sys/module/embeddex_hello/parameters/greet
sudo rmmod embeddex_hello
Pass a path to insmod and the module name to rmmod. After a successful insertion, the sysfs read shows the live parameter while the module is present. The initialization and removal messages both show the value supplied for that insertion, with the removal message reading it from the retained Rust instance. If you omit greet=2, the next fresh insertion starts with the C default. For the parameter-free version, omit the argument and the sysfs read.
The choice of invalid input determines which code performs the rejection. greet=4 parses as an integer, so it reaches the Rust range check and returns EINVAL from init. A nonnumeric setting can fail during parameter parsing before init runs. If the preceding valid insertion is still active, remove it before testing either case. Otherwise an already-loaded module can prevent the test from reaching the code you meant to observe. After the range rejection, there is no successful new insertion to remove. Compare the rejection message with the load and unload messages from the valid case to identify which callbacks ran.
In Kernel allocation, locking, and pin-init, the module instance will hold state with stricter initialization and access requirements than a single integer. The same init success and error contract determines whether the kernel keeps that state.
Key takeaways
- module! connects kernel entry points to a Rust type and emits module metadata.
- Successful initialization gives the module an instance whose destructor runs on successful unload.
- Kernel Result uses Error, which represents a negative Linux errno.
- On Linux 6.8, a C source file linked into the same module can declare the load-time parameter.
Reflect
- Explain to a colleague, in two sentences: explain how module! declares metadata and supplies the kernel entry points.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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
- Man pageKernel module loading: finit_module and init_module
- Man pageKernel module unloading: delete_module
- Kernel documentationBuilding external modules
- Kernel documentationMessage logging with printk
Official documentation first. Links checked when the lesson was published.