The Complete Guide to Rust for Linux Driver Development
Write Linux 6.18 drivers in Rust: toolchain, module anatomy, pinned initialization, device lifetimes, misc, platform, PCI and PHY drivers, testing and style.

A driver is the part of the kernel where bugs are most expensive. It runs with full privilege, it handles input from hardware and user space that nobody fully controls, it has to clean up correctly when a device disappears, and it is written by people who do not know every rule of the subsystem. That is the problem Rust for Linux set out to reduce, not by changing what a driver does, but by moving a set of its rules into types the compiler checks. This guide is the practical map to writing a driver that way in Linux 6.18: the toolchain, the shape of a module, the one unusual idea that everything else depends on (in-place pinned initialization), how kernel objects live and die, the four driver types that have abstractions today, how to talk to user space and hardware, how to test, and how to write code the maintainers will accept. It assumes you can read Rust and write C kernel code, and that you want to know what is different and why.
Everything stated here comes from the kernel's own documentation under Documentation/rust/ and the sources under rust/ and samples/rust/ at tag v6.18. The API is young and moves between releases, so read the version of the documentation that ships with the kernel you target, and treat code from older tutorials as suspect. Where output depends on your system, the examples show the format, and your values will differ.
A Rust driver is a set of types whose constructors cannot produce a broken device, whose destructors release everything on every path, and whose only unsafe code lives in a small abstraction layer a reviewer reads once. The compiler checks the rest.
The short version
Install the toolchain from one source, check it with make LLVM=1 rustavailable, enable CONFIG_RUST, and build with LLVM=1. A module is a module! block plus a type that implements kernel::Module, or a bus driver type that implements platform::Driver, pci::Driver or phy::Driver. Drivers are never moved after creation: they are initialized in place with #[pin_data], pin_init! and friends, which is how locks and C structures embedded in them stay valid. Every allocation takes GFP flags and returns a Result. Resources tied to a device, such as a mapped register region, live in Devres so they cannot be used after unbind. You write no unsafe in a driver; you use the abstractions in the kernel crate, and if one is missing, you write it first. That is the whole discipline, and the rest of this guide is how to apply it.
What you need and what you get
The tooling requirement is documented in the process notes: Rust 1.78.0 or newer and bindgen 0.65.1 or newer for 6.18, both optional dependencies of the kernel build, plus libclang for bindgen and the rust-src component so the build can compile core for the kernel target. The supported architectures, from the arch-support page, are arm (ARMv7 little endian), arm64 (little endian), loongarch, riscv (riscv64 with LLVM), um and x86 (x86_64 only). The recommended build is a full LLVM toolchain, make LLVM=1; GCC works for some configurations but is described as very experimental.
What you get is a growing library, the kernel crate, with abstractions for allocation, errors, locks and reference counts, devices and drivers, firmware properties, PCI and platform buses, file operations through misc devices, user-space memory access, ioctl helpers, network PHYs, KUnit, workqueues, debugfs and more. What you do not get is complete coverage. The documentation says plainly that abstractions are not available for all internal APIs and that coverage is expected to grow, and the status text calls the whole thing experimental, with no in-tree drivers suitable for production use. Plan accordingly: choose a subsystem that has abstractions, or budget time to write them.
The architecture in one picture
Everything is built from three layers, and a driver touches only the top one.
At the bottom, bindings: bindgen reads the C headers listed in rust/bindings/bindings_helper.h and writes Rust declarations of every function, type and constant. They are all unsafe to use. Where a C function is a macro or static inline, a small wrapper in rust/helpers/ makes it callable. How bindgen generates kernel bindings shows the build step.
In the middle, abstractions: modules in rust/kernel/ that wrap a C facility in a Rust type whose public interface cannot be misused in safe code. A Mutex that owns its data and unlocks on drop, a PCI Bar that checks offsets, a miscdevice that registers and unregisters itself. These contain the unsafe blocks, each with a // SAFETY: comment, and each is reviewed with the care that implies. How abstractions wrap C APIs safely follows the Mutex through every layer.
On top, drivers: your code. The documentation draws the rule as a diagram in which the path from a driver to the bindings is marked forbidden: leaf code uses abstractions, and if one is missing, you add it to the kernel crate rather than reach around it. A driver then contains no unsafe of its own, and the safety of the whole rests on the abstractions being sound.
Keep this layering in mind when you read code. If a driver has an unsafe block, either the abstraction is missing or the driver is doing something it should not.
Set up the build
The preconditions are covered in full in setting up a Rust for Linux environment. The short form, for a fresh tree:
make LLVM=1 rustavailable
make LLVM=1 defconfig
./scripts/config -e RUST -e SAMPLES_RUST
make LLVM=1 olddefconfig
make LLVM=1 -j"$(nproc)"Rust is available!The first command prints that line when the compiler, bindgen, libclang and the standard library source are all found, and otherwise explains what is missing. CONFIG_RUST is hidden until the toolchain check passes and its dependencies hold, among them that MODVERSIONS is off or GENDWARFKSYMS is on, and that structure randomization is off. Use the same LLVM=1 for every invocation.
Three other make targets belong in your workflow from day one. make LLVM=1 rust-analyzer writes rust-project.json, which gives your editor completion across the kernel crate. make LLVM=1 rustdoc generates the API reference for your exact configuration, and reading it is the way to find out whether an abstraction you need exists: generating and browsing the Rust kernel docs explains how. And make LLVM=1 rustfmt formats the code, rustfmtcheck checks it for CI, and adding CLIPPY=1 to a build runs the lints.
The anatomy of a module
The simplest Rust module declares its metadata with the module! macro and implements the kernel::Module trait:
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)?;
Ok(Hello { greetings })
}
}
impl Drop for Hello {
fn drop(&mut self) {
pr_info!("unloading\n");
}
}The type names the struct that holds the module's state. init returns Result<Self>: success keeps the value alive until unload, and failure is an errno that aborts the load. Cleanup is Drop, so a module has no separate exit function and an error path in init frees what it allocated by returning. The walk-through of building and loading this is in writing your first Rust kernel module.
Real drivers rarely use this form directly. A bus driver uses a macro that wraps the registration for you: module_platform_driver! for a platform driver, module_pci_driver! for PCI and module_phy_driver! for network PHYs. Each takes the driver type plus the module metadata, and generates the init and exit that register and unregister the driver with its bus.
The one idea you must get: in-place pinned initialization
C structures that embed a mutex, a list head, a work item or any self-referential object must not be moved after initialization, because they hold pointers to themselves. Rust values move freely by default: returning a struct from a function copies or moves it. The two collide, and the kernel's answer shapes every driver you write.
Types that must not move are marked !Unpin and pinned, and they are created by initializers, not by constructors that return values. An initializer is a recipe that writes a value directly into its final memory location. The pin-init crate, vendored in the tree, provides the macros. A struct that contains pinned fields is declared with #[pin_data], and each pinned field is marked #[pin]:
use kernel::prelude::*;
use kernel::sync::{new_mutex, new_spinlock, Mutex, SpinLock};
#[pin_data]
struct Device {
#[pin]
config: Mutex<Config>,
#[pin]
stats: SpinLock<Stats>,
name: &'static CStr,
}
impl Device {
fn new() -> impl PinInit<Self> {
pin_init!(Self {
config <- new_mutex!(Config { threshold: 10 }),
stats <- new_spinlock!(Stats { events: 0, errors: 0 }),
name: c_str!("demo"),
})
}
}Device::new() does not return a Device. It returns impl PinInit<Self>. The <- operator reads "initialize this field in place with this initializer", and plain name: value assigns an ordinary field. When the initializer can fail, try_pin_init! is used, and the error type flows through. To run an initializer you need a destination, and the usual ones are:
fn create() -> Result<Arc<Device>> {
Arc::pin_init(Device::new(), GFP_KERNEL)
}
fn create_boxed() -> Result<Pin<KBox<Device>>> {
KBox::pin_init(Device::new(), GFP_KERNEL)
}Both allocate, run the initializer in the allocation and return a Result, since allocation can fail. Nothing can produce a Device whose lock was not initialized, because the only way to get one is through this process. This is the structural fix for "I forgot mutex_init", and for the whole class of bugs where a C object is used before it is set up or after it moved.
Three details you will meet constantly. Opaque<T> wraps a C-owned structure so the compiler does not assume exclusive or immutable access to memory that C code mutates; every wrapper of a C struct stores it in an Opaque. #[pin_data(PinnedDrop)] plus an impl PinnedDrop is how you write cleanup for a pinned type, since a plain Drop would take &mut self and could move out of a pinned value. And a module whose state is pinned, such as one that holds a misc device registration, uses the InPlaceModule trait, whose init returns an initializer instead of a value.
Locking in Rust for Linux covers locks with this machinery in depth.
The rest of the language, as the kernel sees it
Several differences from user-space Rust follow from running inside the kernel, and the spoke on Rust in the kernel versus Rust in user space lists them with code. The ones that shape driver code every day:
**There is no std.** Only core and the kernel crate are available. Output goes through pr_info!, dev_info! and the related macros, which write to the kernel log with a trailing newline in the format string, and the device versions take a device so the message carries its name.
Allocation is explicit and fallible. KBox, KVec and their vmalloc and kvmalloc relatives take GFP flags and return Result. GFP_KERNEL may sleep and belongs in process context. GFP_ATOMIC does not sleep and is for interrupt context, and the better design in atomic code is to reserve capacity earlier and use push_within_capacity. Memory allocation in Rust kernel code explains the types and the flags.
Errors are errno values. kernel::error::Error wraps a negative errno and Result<T> is Result<T, Error>. The ? operator converts an allocation error into ENOMEM and a failed integer conversion into EINVAL. C status returns become Result with to_result, and ERR_PTR returns with from_err_ptr. Error handling with Result and kernel::error covers the conversions.
**A panic is a BUG().** The panic handler in the kernel crate ends in the C BUG() call. So unwrap() and expect() are discouraged, integer overflow panics by default through CONFIG_RUST_OVERFLOW_CHECKS, and slice indexing is bounds checked. Use checked_add and its relatives where overflow is real, and return errors rather than panicking.
Strings are C strings at the boundary. Names handed to C are &CStr, created with the c_str! macro at compile time, as in name: c_str!("rust-echo"). Format strings for logging are Rust format strings, checked at compile time.
A tour of the kernel crate
Before writing anything, spend ten minutes with the module list of the kernel crate in rust/kernel/lib.rs, because it is the inventory of what you can build on in 6.18. Grouped by what you will use them for:
| Group | Modules |
|---|---|
| Foundations | alloc, error, init, prelude, str, types, fmt, print, build_assert, static_assert, bug |
| Concurrency and time | sync (locks, Arc, CondVar, atomics, RCU), task, workqueue, time, irq, completion through sync |
| Devices and drivers | device, driver, devres, device_id, platform, pci, auxiliary, faux, of, acpi |
| Hardware access | io, dma, clk, regulator, cpu, cpufreq, cpumask, opp, page, mm, scatterlist |
| Talking to user space | miscdevice, fs, iov, uaccess, ioctl, seq_file, debugfs, configfs |
| Subsystems | net (with phy), block, drm, firmware, security, cred, pid_namespace |
| Data structures | list, rbtree, xarray, maple_tree, bitmap, id_pool |
| Observability and testing | tracepoint, kunit, jump_label |
| Re-exports | bindings, uapi, macros, ffi |
Read the table as a map of where to look first. A driver that talks to hardware needs a bus module (platform, pci, auxiliary or faux), device and devres for lifetimes, io or dma for access, irq for interrupts, and a user-space interface from miscdevice or debugfs. The data structure modules, list, rbtree and xarray, are the ones that let you hold collections of objects the way C code holds list_head and radix trees, and each has the same rule: the collection owns its elements, and an element cannot be in two collections by accident. The tracepoint module lets Rust code declare static tracepoints, so a driver can emit events that ftrace and perf see, as the tracing guide explains.
Two modules deserve a note. bindings and uapi are re-exported but not for driver use: bindings is the raw generated layer that abstractions are built on, and uapi carries the user-space API definitions, such as the ioctl-related constants. And the list changes every release. Modules that exist in 6.18 may be missing in the previous release, and new ones arrive constantly, so verify against rustdoc for the tree you are building rather than trusting any written list, this one included.
How kernel objects live and die
Most kernel objects are reference counted by C code, and a driver holds references to some of them. Rust needs a way to say "I own one reference to this C object, and I must release it". The abstraction is ARef<T>, the counted reference, for any type that implements AlwaysRefCounted, which tells the crate how to increment and decrement the count. A driver that stores the device it is bound to holds an ARef<Device>, as the samples do: pdev: ARef<platform::Device>. Cloning bumps the count and dropping releases it, so the object cannot disappear while the driver holds one. Arc<T> is the same idea for objects defined in Rust, built on the kernel's refcount type, and it is how a lock or a buffer is shared among the contexts that use it.
Some objects are handed to C and come back, such as the per-open state of a file. The ForeignOwnable trait describes how a Rust owner turns into a raw pointer that C stores, and how to borrow or take it back. You see it as the Ptr associated type in MiscDevice, with Pin<KBox<Self>>, and you rarely implement it yourself.
Device contexts: what you may do depends on where you are
A device is not always in the same state. During probe it is being bound, and during unbind it is going away, and what you may do differs. The 6.18 device abstraction encodes the state in the type. A Device<Core> is the device in the driver-core callbacks, probe and unbind, where the driver is bound and may use the full interface. A Device<Bound> is a device you can prove is bound to a driver, which is what resource mapping requires. Plain Device is the least capable view and can be held anywhere. You can see it in the signatures: probe(pdev: &pci::Device<Core>, ...), and iomap_region_sized is defined only on Device<Bound>. A function that needs a bound device asks for one in its parameter, and the compiler refuses a call with a weaker one, which keeps I/O out of contexts where the device may already be gone.
Devres: resources that cannot outlive their binding
The bug that most often hides in C drivers is using a resource after the device has been unbound: an ioremap mapping used by a late interrupt, a clock enabled after the driver left. Devres<T> ties a resource to the binding. It registers a callback with the driver core that runs on unbind and revokes the resource. After that, access fails with an error instead of touching freed memory:
let bar = drvdata.bar.access(pdev.as_ref())?;access takes the device as evidence that you are still bound and returns a reference valid for that borrow, or an error if the resource was revoked. The PCI driver in writing a PCI driver in Rust builds on this. The rule is: anything whose lifetime is "while the device is bound" belongs in a Devres.
Locks and concurrency
A driver is called from many contexts: system calls on every CPU, interrupt handlers, work items, other drivers. The kernel crate offers Mutex for sections that may sleep, SpinLock for short sections in atomic context, Arc to share, LockedBy for data protected by a lock it does not sit inside, CondVar for waiting, and atomic types. They share the property that the lock owns its data, so unlocked access does not compile, and the guard unlocks on every exit. They also share the limits: lock ordering, sleeping in atomic context and recursive locking are still yours to get right, and lockdep, with the lock class that new_mutex! and new_spinlock! generate at each call site, finds them at run time. Run your test kernel with lockdep and the sleep-in-atomic checks enabled.
The driver types you can write today
Four kinds of driver have working abstractions in the 6.18 tree, each with a sample or an in-tree user. They differ in how the kernel finds the device and what the driver registers.
Misc devices: a file in /dev
A misc device is a character device with a dynamic minor number. It is the simplest driver and the best place to learn the shape. You implement MiscDevice for a per-open type, whose open returns the object that represents one open file, with optional read_iter, write_iter, ioctl and release, and you hold a MiscDeviceRegistration in an InPlaceModule. Dropping the registration removes the node. The trait is #[vtable], so unimplemented operations are null in the C table. The complete example, with the buffer protected by a mutex and the per-open versus shared state decision, is writing a misc device driver in Rust.
Platform drivers: devices described by firmware
On an embedded board, most devices are listed in the device tree or ACPI. A platform driver matches by compatible string or ACPI ID with an ID table (of_device_table! and acpi_device_table!), whose entries carry per-variant data (IdInfo), and reads its configuration from firmware properties:
fn probe(pdev: &platform::Device<Core>, info: Option<&Self::IdInfo>)
-> Result<Pin<KBox<Self>>>
{
let dev = pdev.as_ref();
let fwnode = dev.fwnode().ok_or(ENOENT)?;
let freq: u32 = fwnode.property_read(c_str!("clock-frequency")).required_by(dev)?;
dev_info!(dev, "clock-frequency = {} Hz\n", freq);
let drvdata = KBox::new(Self { pdev: pdev.into() }, GFP_KERNEL)?;
Ok(drvdata.into())
}required_by(dev) makes a property mandatory and logs the missing one against the device; .or(default) makes it optional. There is no remove function: unbind runs first with the bound device for teardown that needs I/O, and then the driver data is dropped. Writing a platform driver in Rust has the device tree node and the log.
PCI drivers: discoverable hardware
A PCI driver matches vendor and device IDs from a pci_device_table!, enables the device in probe (enable_device_mem(), set_master()), maps a BAR into a Devres<Bar<SIZE>> and does register I/O through it. The BAR's size is a const generic, so accesses at constant offsets are bounds checked at build time, and the try_ accessors check offsets that come from the device at run time. It is the clearest demonstration of what the type system buys you, with a mapping that cannot be used out of range or after unbind. See writing a PCI driver in Rust.
Network PHY drivers
The PHY abstraction was the first network-facing one merged. A PHY driver implements phy::Driver with a name, a PHY ID and mask, and the callbacks the chip needs: probe, soft_reset, read_status, suspend, resume. It reads and writes MDIO registers with C22 or C45 addressing, and calls generic helpers (genphy_soft_reset, genphy_read_status) for the standard behavior. The in-tree Asix and QT2025 drivers are the references, and writing a PHY driver in Rust walks through one.
There are further samples in samples/rust/ for a DMA test driver, debugfs, configfs, USB, the faux bus and auxiliary bus drivers, which show the same patterns on other subsystems. The rule for choosing is simple: if the subsystem you need has no abstraction in your tree, you are writing one.
Talking to user space
A driver's interface to user space is its ABI, and mistakes there are hard to fix after release. The misc device abstraction gives the safe pieces. Reading and writing go through read_iter and write_iter, which receive an iterator over the user buffer, so the driver never touches a raw user pointer: simple_read_from_buffer copies from a kernel buffer to the user with position handling, and copy_from_iter_vec copies in, both returning a Result.
For ioctl, define command numbers with the helpers in kernel::ioctl, which are the Rust versions of the C macros, and access the argument through UserSlice:
const RUST_MISC_DEV_GET_VALUE: u32 = _IOR::<i32>('|' as u32, 0x81);
const RUST_MISC_DEV_SET_VALUE: u32 = _IOW::<i32>('|' as u32, 0x82);
fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> {
let arg = UserPtr::from_addr(arg);
let size = _IOC_SIZE(cmd);
match cmd {
RUST_MISC_DEV_GET_VALUE => me.get_value(UserSlice::new(arg, size).writer())?,
RUST_MISC_DEV_SET_VALUE => me.set_value(UserSlice::new(arg, size).reader())?,
_ => return Err(ENOTTY),
};
Ok(0)
}This is the shape of the in-tree sample, trimmed. UserSlice::new(arg, size) names a range of user memory, and .reader() and .writer() give typed access that returns an error on a bad address instead of faulting. An unknown command returns ENOTTY, the conventional answer. Design the command numbers, structure layouts and error codes as a stable interface from the first version: the documentation of the ioctl macros, Documentation/userspace-api/ioctl/, applies unchanged.
Reaching hardware
Registers are memory-mapped, and the abstractions turn the mapping into a value. PCI has Bar, platform devices have io_request_by_index for their memory resources, and both return a type with read8, read32, write8 and so on, with checked variants for run-time offsets. Interrupts have a Handler trait and registration types in kernel::irq, reached from the device through functions such as request_irq on a PCI device, and a registered handler is tied to the binding so it is released on unbind. DMA has its own abstraction, with a sample, and the same principle: a buffer that the device may access is a typed value with a defined lifetime, not a raw pointer and a length.
Two habits keep register code clear. Name the offsets as constants in one place, as in the PCI sample's Regs type, so the layout is documented once. And separate "read the hardware" from "decide what to do" so the decision logic can be tested without hardware.
Unsafe code: where it belongs and how to write it
A driver should contain none. If you find yourself writing unsafe in driver code, either an abstraction is missing or the design is fighting the model. When you are writing an abstraction, each unsafe block needs a // SAFETY: comment saying why this call satisfies the callee's preconditions, and each unsafe fn needs a # Safety section stating what callers must guarantee. The two are different things: the section is a promise by the author, the comment is the proof by each user. The kernel's build enforces the convention: -Dunsafe_op_in_unsafe_fn makes unsafe operations inside an unsafe function need their own block, and Clippy's undocumented_unsafe_blocks warns on a block with no safety comment. The details, with a worked register example, are in unsafe blocks and SAFETY comments.
A worked design: a sensor on the platform bus with a device node
The pieces fit together best in an example you design before you code. Suppose a board has a temperature sensor with a small register block, described in the device tree, and you want a character device that user space can read. The hardware is discovered by firmware, so the driver is a platform driver. The user interface is a file, so it also registers a misc device. Three questions decide the structure, and Rust makes you answer each in a type.
What lives as long as the device is bound? The mapped registers and the registered device node. Both go in the driver's data, and the registers go in a Devres so they cannot be used after unbind.
What is shared between open files and the interrupt or polling path? The last reading and the configuration. That is state with a lock around it, shared by reference count, so it goes in an Arc holding a Mutex.
What is per open file? Probably nothing but a reference to the shared state, since the sensor has one value. The per-open type is a thin struct holding an Arc clone.
The data layout follows from the answers:
const REGS_SIZE: usize = 0x20;
struct Shared {
regs: Devres<IoMem<REGS_SIZE>>,
last: Mutex<i32>,
}
#[pin_data]
struct SensorDriver {
// Declared first, so it is dropped first and the device node goes away before the rest.
#[pin]
node: MiscDeviceRegistration<SensorFile>,
shared: Arc<Shared>,
pdev: ARef<platform::Device>,
}
struct SensorFile {
shared: Arc<Shared>,
}Reading from the sensor locks last, reads a register through the Devres with access, stores the value and copies it out. If the device was unbound while a read was in progress, access returns an error and the read fails with it, which is the behavior you want and the one C drivers get wrong. The probe function assembles the pieces in order, and each step that can fail returns early with ?, which drops what was built:
Read the
compatible-selectedIdInfoand any required properties, withrequired_by(dev)for the mandatory ones.Request memory resource 0 and map it with
pdev.io_request_by_index(0).ok_or(ENODEV)?.iomap_sized::<REGS_SIZE>(), which yields an initializer for theDevres<IoMem<REGS_SIZE>>.Allocate the shared state with
Arc::pin_init, orArc::newif its fields do not need pinning.Register the misc device through
MiscDeviceRegistration::register, whoseopenclones theArcinto aSensorFile.Return the driver data as
Pin<KBox<Self>>.
The unbind order is the important property. When the device is removed, the driver core calls unbind, where you could stop the hardware, then drops the driver data. Fields of a struct are dropped in declaration order, and node is declared first, so its /dev entry is removed first and no new opens arrive, the Devres callback revokes the register mapping so in-flight reads fail cleanly, and the Arc count falls to zero when the last open file closes. There is no remove function that frees things in an order you must remember: the order is the declaration order of the fields, and an early return in probe runs the same drops. Every bug class that this removes, use of registers after unbind, a file operation racing with removal, a leaked mapping on an error path, is a comment in a typical C driver and a type here.
What the design does not decide for you is the hardware protocol, the units and the semantics of the file. Those need the same care as in C, and the ABI you give user space, the read format and any ioctls, is permanent once released.
Testing and debugging
Test a Rust driver as you would a C driver, plus the extra tools the language gives you.
Unit tests with KUnit. Pure logic, such as converting a raw register value to millidegrees, is a function you can test without hardware. A #[kunit_tests(name)] module of #[test] functions is turned into a KUnit suite, and the assert! macros map to KUnit. Run with ./tools/testing/kunit/kunit.py run --make_options LLVM=1 --arch x86_64 --kconfig_add CONFIG_RUST=y. The doctests of the kernel crate run the same way when CONFIG_RUST_KERNEL_DOCTESTS is on, and examples in your own module are documentation only. Testing Rust kernel code with KUnit and doctests covers it. Keep register-access code thin and the decision logic pure, and most of a driver becomes testable.
Selftests from user space. Behavior seen through the file, the ioctl or sysfs interface belongs in a kselftest, which is also where the Rust support keeps its own tests under tools/testing/selftests/rust.
Error paths with fault injection. Allocation failures and failed probe steps are rare on a healthy system, so the drop-on-error behavior is exercised only if you make it happen. The kernel's failslab and fail_function facilities force those failures. See testing error paths with fault injection.
Kernel debugging options. Build the test kernel with lockdep, the sleep-in-atomic checks, KASAN and CONFIG_RUST_DEBUG_ASSERTIONS as you would for any driver. Lock classes for Rust locks are generated automatically, so lockdep reports name them by file and line unless you pass a name to new_mutex!. KASAN is supported with Rust, with the exception noted in the CONFIG_RUST dependencies for the software-tags mode.
Tracing and debuggers. Rust functions appear in ftrace, kprobes and perf like any others. GDB needs version 10.2 or newer, or Binutils 2.36 or newer, to demangle Rust's v0 symbol mangling, the quick start says. The tracing guide covers the live-system tools, and kgdb over serial the debugger.
Writing code the maintainers will accept
The coding guidelines are short and mostly mechanical, which is deliberate: the less a reviewer spends on style, the more goes to the design.
**Format with
rustfmt**, with the default settings, viamake LLVM=1 rustfmt, and check withrustfmtcheck. Imports use a vertical layout, one item per line with braces as soon as there is more than one, and a trailing empty//comment on the last item to keep rustfmt from condensing it.Comments are written in Markdown, as full sentences starting with a capital letter and ending with a period, including
// SAFETY:and// TODO:lines. Comments explain implementation details, and documentation is///even on private items.Document every public item, with a one-sentence first paragraph,
# Safetyfor unsafe functions,# Panicswhere a panic is possible (which should be rare, since a fallible design is preferred) and# Examplesthat run as tests where the crate supports it.Name things after the C side where you wrap it, in Rust casing, without repeating the module in the item name:
gpio::LineDirection::In, notgpio::gpio_line_direction::GPIO_LINE_DIRECTION_IN.**Prefer
#[expect(...)]over#[allow(...)]**, so an unnecessary lint exception becomes a warning, with the documented exceptions for conditional compilation and macros.Use the kernel's C type aliases, such as
c_intfrom the prelude, not the ones incore::ffi, which may not map to the right types.Write the abstraction first if one is missing, and send it with its users. A driver that works around a missing abstraction with raw bindings will be asked to do this in review.
Build with CLIPPY=1 before you send a patch, and fix what it reports, since the Makefile enables lints such as undocumented_unsafe_blocks for the whole tree.
A checklist before you call a driver done
| Question | What good looks like |
|---|---|
Does the driver contain unsafe? | None. Missing abstractions were written in rust/kernel/ |
| Are all resources tied to the binding? | Register mappings and IRQs in Devres or abstraction types that revoke on unbind |
| Can every allocation fail safely? | Each has flags and ?, and fault injection exercised the paths |
| Is the lock design written down? | Which context takes which lock and in what order; lockdep clean |
| Is anything blocking in atomic context? | No Mutex under a spinlock, no GFP_KERNEL in atomic sections |
| Is the user ABI stable? | Command numbers, structures and error codes designed and documented |
| Are panics possible? | No unwrap, expect, unchecked arithmetic or indexing on device-supplied values |
| Is the logic testable? | Pure functions with KUnit tests; thin hardware layer |
| Do unload and unbind work? | Tried repeatedly, with I/O in flight |
| Does it build clean? | rustfmtcheck, Clippy and rustdoc without warnings |
When not to write the driver in Rust
The honest cases where C is still the better answer today:
A subsystem with no Rust abstraction. An engineer who needs an I2C client driver, a GPIO controller or a block driver for a subsystem whose abstraction is not in the tree faces a choice: write the abstraction, which is a reviewed contribution of its own, or write the driver in C. For a deadline, C.
A fix to an existing C driver. A bug in a C driver is fixed in C. The tree does not mix languages within one driver, and a fix is not the place to start a port.
An out-of-tree module for a distribution kernel. A vendor shipping a module against a kernel it does not build needs a Rust-enabled kernel with the matching toolchain, which most distribution kernels do not have. The CONFIG_RUST help text says external Rust modules are possible with a Rust-enabled kernel, but that is a narrower path than C.
A team without Rust experience on a short schedule. The learning curve, the in-place initialization model in particular, is real, and the API changes between releases. Rust pays off over the life of a driver, not in the first week.
Anything that must run on an unsupported architecture. The supported list is arm, arm64, loongarch, riscv64, um and x86_64, with the constraints in the arch-support page. A 32-bit x86 or big-endian target is outside it.
The map: where each topic goes deeper
Background: why the kernel accepted a second language and Rust in the kernel versus user space.
Getting started: the development environment, your first module and Rust versus C modules.
Quality: KUnit and doctests, SAFETY comments and rustdoc.
Internals: how abstractions wrap C APIs, error handling, memory allocation, locking and bindgen.
Drivers: misc device, platform, PCI and network PHY.


