Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/deelerdev/linux/llms.txt

Use this file to discover all available pages before exploring further.

Rust is a second language supported in the Linux kernel alongside C. The motivation is safety: Rust’s type system and ownership model eliminate entire classes of bugs — use-after-free, data races, null pointer dereferences — that have historically plagued kernel code. Rust support was merged into the mainline kernel starting with Linux 6.1, and the set of abstractions covering kernel APIs continues to grow with each release.

Why Rust in the kernel?

Kernel code runs in a privileged environment where a single memory safety bug can compromise an entire system. C gives you the control you need to write a kernel but no static guardrails to prevent common errors. Rust provides the same low-level control as C while using its type system and borrow checker to make many of those errors impossible to compile. The goal is not to rewrite the kernel in Rust but to allow new components — especially drivers and file systems — to be written safely without giving up performance.
Rust kernel code can only link against core, not std. All crates intended for use in the kernel must include #![no_std] at the crate root.

Installing the required toolchain

You need three components beyond a standard Rust installation: the Rust compiler itself, the standard library source (so the build system can cross-compile core), and bindgen (which generates Rust bindings from C headers at build time).

Install via your Linux distribution

Several distributions ship packages that work out of the box.
pacman -S rust rust-src rust-bindgen

Install via rustup

If your distribution does not ship a suitable version, use rustup:
# Set the stable toolchain for your kernel build directory
rustup override set stable

# Add the standard library source
rustup component add rust-src

# Add optional development tools
rustup component add rustfmt
rustup component add clippy

# Install bindgen from crates.io
cargo install --locked bindgen-cli
bindgen requires libclang. Install LLVM from your distribution or build it following the instructions at llvm.org/docs/GettingStarted.html. You can also use the prebuilt LLVM+Rust toolchains hosted at kernel.org/pub/tools/llvm/rust/.

Verify the requirements

Once everything is installed, run the following to confirm the build system can find the toolchain:
make LLVM=1 rustavailable
This triggers the same check used by Kconfig and prints a diagnostic if any requirement is missing.

Enabling Rust support in the build

Open the kernel configuration menu and enable Rust support (CONFIG_RUST) under General setup. The option is only visible when make LLVM=1 rustavailable passes.
make LLVM=1 menuconfig
# General setup → Rust support
To try Rust with sample modules, navigate to:
Kernel hacking
    → Sample kernel code
        → Rust samples
Enable one or more samples as built-in (y) or as loadable modules (m).

Building with Rust enabled

Always build with a full LLVM toolchain when Rust is involved:
make LLVM=1
GCC works for some configurations but is experimental. LLVM is the best-supported setup. You can also run the linter and generate documentation locally:
# Run Clippy lints (do not use in production builds)
make LLVM=1 CLIPPY=1

# Generate rustdoc HTML documentation
make LLVM=1 rustdoc

# Open the generated docs
xdg-open Documentation/output/rust/rustdoc/kernel/index.html

The abstraction model

Rust kernel code is organized into two layers: bindings and abstractions.
                                            rust/bindings/
                                           (rust/helpers/)

                                               include/ -----+ <-+
                                                             |   |
  drivers/              rust/kernel/              +----------+ <-+   |
    fs/                                           | bindgen  |       |
   .../            +-------------------+          +----------+ --+   |
                   |    Abstractions   |                         |   |
+---------+        | +------+ +------+ |          +----------+   |   |
| my_foo  | -----> | | foo  | | bar  | | -------> | Bindings | <-+   |
| driver  |  Safe  | | sub- | | sub- | |  Unsafe  |          |       |
+---------+        | |system| |system| |          | bindings | <-----+
     |             | +------+ +------+ |          |  crate   |       |
     |             |   kernel crate    |          +----------+       |
     |             +-------------------+                             |
     |                                                               |
     +------------------# FORBIDDEN #--------------------------------+
Bindings are auto-generated by bindgen from C headers in include/. They live in rust/bindings/ and expose unsafe Rust declarations of C types and functions. For C inline functions or complex macros that bindgen cannot handle automatically, small wrapper functions can be added to rust/helpers/. Abstractions live in rust/kernel/ and wrap the unsafe bindings behind a safe, idiomatic Rust API. For example, the Mutex abstraction wraps struct mutex from the C side and exposes methods that use Rust’s ownership model to enforce correct locking discipline. Leaf code such as drivers must use abstractions rather than calling bindings directly.
Drivers and other leaf modules must not call C bindings directly. They must go through the safe abstractions provided by the kernel crate. Bypassing the abstraction layer is explicitly forbidden.

The kernel crate and the prelude

The kernel crate is the central library for Rust kernel code. It re-exports common types and brings frequently used items into scope via the prelude. C FFI types such as c_int and c_char are available from the kernel prelude — do not use core::ffi aliases, as they may not map to the correct types for the target architecture.
fn f(p: *const c_char) -> c_int {
    // ...
}
Rust kernel code uses the cfg attribute to conditionalize on kernel configuration symbols:
#[cfg(CONFIG_X)]       // Enabled (y or m)
#[cfg(CONFIG_X="y")]   // Enabled as a built-in
#[cfg(CONFIG_X="m")]   // Enabled as a module
#[cfg(not(CONFIG_X))]  // Disabled

Formatting and style

Rust code is formatted with rustfmt using the default settings (4-space indentation, idiomatic Rust style). Configure your editor to format on save. To reformat all Rust sources in the tree:
make LLVM=1 rustfmt
To check formatting without modifying files (useful in CI):
make LLVM=1 rustfmtcheck
Imports should be formatted in a vertical layout to minimize merge conflicts. Place a trailing empty comment (//) on the last item to prevent rustfmt from collapsing the list:
use crate::{
    example1,
    example2::{
        example3,
        example4,
        example5, //
    },
    example6,
    example7,
    example8::example9, //
};
Every unsafe block must be preceded by a // SAFETY: comment that explains why the code is correct:
// SAFETY: `p` is valid by the safety requirements.
unsafe { *p = 0; }

Documentation

Rust kernel code is documented with rustdoc using Markdown, not with the kernel-doc format used for C. The first line of a doc comment must be a single sentence summarizing the item. Unsafe functions must document their safety preconditions under a # Safety section.
/// Returns the contained [`Some`] value, consuming the `self` value,
/// without checking that the value is not [`None`].
///
/// # Safety
///
/// Calling this method on [`None`] is *[undefined behavior]*.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// let x = Some("air");
/// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
/// ```
pub unsafe fn unwrap_unchecked(self) -> T {
    match self {
        Some(val) => val,

        // SAFETY: The safety contract must be upheld by the caller.
        None => unsafe { hint::unreachable_unchecked() },
    }
}
The generated docs are published at rust.docs.kernel.org for the latest mainline, with per-release tags (e.g. rust.docs.kernel.org/6.10/).

Where Rust code lives in the tree

rust/

The core Rust support code: the kernel crate (rust/kernel/), auto-generated bindings (rust/bindings/), C helper wrappers (rust/helpers/), and build infrastructure.

samples/rust/

Sample kernel modules written in Rust. A good starting point for understanding how a minimal Rust module is structured.

drivers/

Production Rust drivers live alongside their C counterparts in the normal driver directories.

Kernel hacking → Rust hacking

Kconfig options under the Rust hacking menu provide debugging and instrumentation features specific to Rust kernel code.

Setting up rust-analyzer

The rust-analyzer language server provides IDE features (completion, go-to-definition, inline errors) for Rust kernel code. Generate its configuration file with:
make LLVM=1 rust-analyzer
This produces a rust-project.json file that you can point your editor at.

Build docs developers (and LLMs) love