Skip to main content

TECH VEDA

Corporate on-site training - Submit proposal Pick your modulesSharpen your kernel skills: deep dives, drivers, Yocto, CVEs, careers — updated daily. Read the blog →
Tutorials

Rust for Linux: A Beginner’s Guide — Part 3: Handling Memory Allocation Failure in Rust Kernel Modules

Write a Rust kernel module from an empty file on Ubuntu 26.04 LTS: a size parameter, your own EINVAL, ENOMEM through ?, and a guard that cleans up when init fails.

Rust for Linux: A Beginner’s Guide — Part 3: Handling Memory Allocation Failure in Rust Kernel Modules

In this part you write a Rust kernel module from an empty file and load it into the kernel your Ubuntu 26.04 LTS machine is already running. It takes a buffer size as a module parameter, rejects a bad value with its own EINVAL, and uses fallible allocation so that running out of memory comes back as ENOMEM instead of a crash. You will load it three ways and read what each leaves in dmesg.

Part 1 set up the toolchain and loaded a first module. Part 2 showed that the generated exit path only drops your module struct. This part puts that to work in a module of your own, rust_alloc_demo.

What you need before you start

Ubuntu 26.04 LTS on x86_64, running its stock generic kernel. This run used 7.0.0-44-generic. Install the headers and Rust support for that exact kernel, plus the distribution’s Rust toolchain:

raghu@techveda:~$ sudo apt install linux-headers-$(uname -r) linux-lib-rust-$(uname -r) rustc rust-src build-essential dwarves

An out-of-tree Rust module must be compiled by the same rustc that built the kernel. Check that the two match before writing any code:

raghu@techveda:~$ uname -r
7.0.0-44-generic
raghu@techveda:~$ rustc --version
rustc 1.93.1 (01f6ddf75 2026-02-11) (built from a source tarball)
raghu@techveda:~$ grep RUSTC_VERSION_TEXT /lib/modules/$(uname -r)/build/.config
CONFIG_RUSTC_VERSION_TEXT="rustc 1.93.1 (01f6ddf75 2026-02-11) (built from a source tarball)"

Ubuntu builds its kernel with the distribution’s default rustc, so on a stock 26.04 install the two lines agree. If you have a rustup toolchain earlier in your PATH, rustc --version will show that one instead, and that compiler cannot use the kernel’s precompiled Rust crates.

Step 1: Declaring the module and its parameter

Create a directory for the module and a source file in it:

raghu@techveda:~$ mkdir ~/rust_alloc_demo && cd ~/rust_alloc_demo

Start rust_alloc_demo.rs with the macro every Rust module begins with:

// SPDX-License-Identifier: GPL-2.0

//! Fallible allocation demo: a buffer sized by a module parameter.

use kernel::prelude::*;

module! {
    type: AllocDemo,
    name: "rust_alloc_demo",
    authors: ["TECH VEDA"],
    description: "Fallible allocation demo",
    license: "GPL",
    params: {
        buffer_kb: usize {
            default: 64,
            description: "Buffer size in KiB (must be non-zero)",
        },
    },
}

type: names the struct you are about to write, name: becomes the .ko name and the dmesg prefix, and params: declares buffer_kb as a usize with a default of 64.

Step 2: Defining what the module owns

Add three types below the macro:

/// Bookkeeping kept in its own heap allocation.
struct Stats {
    requested_kb: usize,
}

/// Stands in for something init must undo if a later step fails.
struct Setup;

impl Drop for Setup {
    fn drop(&mut self) {
        pr_info!("setup guard dropped\n");
    }
}

struct AllocDemo {
    stats: KBox<Stats>,
    buffer: KVVec<u8>,
}

AllocDemo holds two heap allocations, deliberately different. KBox<Stats> is a box from kmalloc: small and physically contiguous. KVVec<u8> is a vector from kvmalloc, which tries kmalloc and falls back to vmalloc when the request is too big for contiguous pages. Your buffer size comes from a user, so that fallible allocation gets the allocator that can cope with a large value. Step 9 shows what happens with plain KVec instead.

Setup owns nothing. It stands in for the thing a real driver acquires early in init and must give back if a later step fails — a registration, a clock, an IRQ. Its Drop only prints, so you can see when it runs.

Step 3: Writing init, where fallible allocation happens

impl kernel::Module for AllocDemo {
    fn init(_module: &'static ThisModule) -> Result<Self> {
        let kb = *module_parameters::buffer_kb.value();
        pr_info!("init: buffer_kb={}\n", kb);

        if kb == 0 {
            pr_err!("buffer_kb must be non-zero\n");
            return Err(EINVAL);
        }
        let bytes = kb.checked_mul(1024).ok_or(EINVAL)?;

        let _setup = Setup;

        let stats = KBox::new(Stats { requested_kb: kb }, GFP_KERNEL)?;
        let buffer = KVVec::from_elem(0xa5u8, bytes, GFP_KERNEL)?;

        pr_info!("allocated {} bytes, first byte {:#x}\n", buffer.len(), buffer[0]);
        Ok(AllocDemo { stats, buffer })
    }
}

The first line reads the parameter. On this kernel value() returns a reference, hence the *. Then there are four ways out:

  • Zero: you return Err(EINVAL) yourself. EINVAL comes from the prelude as a kernel::error::Error, and the kernel hands its negative value back to insmod.
  • Overflow: checked_mul returns None if kb * 1024 does not fit in a usize. ok_or(EINVAL) turns that into an error, and ? returns it.
  • Out of memory: KBox::new and KVVec::from_elem both take a GFP flag and return a Result. That is fallible allocation: the failure is a value you must handle, and ? converts the AllocError into ENOMEM and returns it.
  • Success: both allocations move into the struct, and the kernel keeps it until unload.

Note where _setup is created: after the parameter checks, before the allocations. Every ? below it returns from a scope that owns _setup, and leaving a scope drops what it owns. On success it is dropped too, at the end of init, because it was never moved into the struct; that is why the success output in Step 6 also prints the guard line. A driver that has to keep the resource stores it in the struct instead.

Step 4: Writing Drop for unload

impl Drop for AllocDemo {
    fn drop(&mut self) {
        pr_info!(
            "exit: freeing {} bytes ({} KiB requested)\n",
            self.buffer.len(),
            self.stats.requested_kb
        );
    }
}

There is no exit function to write. The generated exit path drops your struct, and dropping it frees stats and buffer after this drop returns. Every fallible allocation here is released by ownership; you never call kfree or kvfree.

Step 5: Adding a Kbuild file and a Makefile, then building

Two small files tell the kernel build system what to compile. Kbuild is one line:

obj-m := rust_alloc_demo.o

and the Makefile hands the work to the build tree of the running kernel:

KDIR ?= /lib/modules/$(shell uname -r)/build

all:
	$(MAKE) -C $(KDIR) M=$(CURDIR) modules

clean:
	$(MAKE) -C $(KDIR) M=$(CURDIR) clean

The recipe lines start with a tab, not spaces. Build it:

raghu@techveda:~$ make
make -C /lib/modules/7.0.0-44-generic/build M=/home/raghu/rust_alloc_demo modules
make[1]: Entering directory '/usr/src/linux-headers-7.0.0-44-generic'
make[2]: Entering directory '/home/raghu/rust_alloc_demo'
warning: the compiler differs from the one used to build the kernel
  The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 15.2.0-16ubuntu1) 15.2.0
  You are using:           gcc (Ubuntu 15.2.0-16ubuntu1) 15.2.0
  RUSTC [M] rust_alloc_demo.o
  MODPOST Module.symvers
  CC [M]  rust_alloc_demo.mod.o
  CC [M]  .module-common.o
  LD [M]  rust_alloc_demo.ko
  BTF [M] rust_alloc_demo.ko
Skipping BTF generation for rust_alloc_demo.ko due to unavailability of vmlinux
make[2]: Leaving directory '/home/raghu/rust_alloc_demo'
make[1]: Leaving directory '/usr/src/linux-headers-7.0.0-44-generic'

The compiler warning is harmless: Ubuntu’s kernel was built by x86_64-linux-gnu-gcc and you are calling the same compiler as gcc, as the identical version strings show. The BTF line only means no debug type data is generated for the module. Check that the parameter made it into the module:

raghu@techveda:~$ modinfo -p rust_alloc_demo.ko
buffer_kb:Buffer size in KiB (must be non-zero) (usize)

Step 6: Loading the module with a valid size

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=64
raghu@techveda:~$ ls /sys/module/rust_alloc_demo/
coresize
holders
initsize
initstate
notes
refcnt
sections
srcversion
taint
uevent
raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg
[  113.205555] rust_alloc_demo: init: buffer_kb=64
[  113.210476] rust_alloc_demo: allocated 65536 bytes, first byte 0xa5
[  113.210999] rust_alloc_demo: setup guard dropped
[  113.749225] rust_alloc_demo: exit: freeing 65536 bytes (64 KiB requested)

65,536 bytes were allocated and filled, the guard dropped as init returned, and the last line came from your Drop when rmmod ran. If this is the first module you have built yourself since boot, sudo dmesg also shows two lines saying the module taints the kernel, because it is out-of-tree and unsigned. That is expected.

Step 7: Rejecting zero with your own EINVAL

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=0
insmod: ERROR: could not insert module rust_alloc_demo.ko: Invalid parameters
raghu@techveda:~$ sudo dmesg
[  114.937893] rust_alloc_demo: init: buffer_kb=0
[  114.937995] rust_alloc_demo: buffer_kb must be non-zero

insmod prints Invalid parameters because that is how kmod words EINVAL — your Err(EINVAL) reached userspace unchanged. There is no guard line: _setup did not exist yet when you returned. A value large enough to overflow checked_mul takes the same path:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=18014398509481984
insmod: ERROR: could not insert module rust_alloc_demo.ko: Invalid parameters
raghu@techveda:~$ sudo dmesg
[  118.358777] rust_alloc_demo: init: buffer_kb=18014398509481984

Step 8: Making a fallible allocation fail with ENOMEM

Ask for 4 GiB. kvmalloc refuses any request larger than INT_MAX bytes, just under 2 GiB, before it looks at free memory, so this fails on any machine:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=4194304
insmod: ERROR: could not insert module rust_alloc_demo.ko: Cannot allocate memory
raghu@techveda:~$ lsmod | grep rust_alloc_demo
raghu@techveda:~$ sudo dmesg | grep -E "rust_alloc_demo: |cut here|WARNING"
[  116.043738] rust_alloc_demo: init: buffer_kb=4194304
[  116.044641] ------------[ cut here ]------------
[  116.045033] WARNING: mm/slub.c:6785 at __kvmalloc_node_noprof+0x586/0x810, CPU#1: insmod/690
[  116.052865] rust_alloc_demo: setup guard dropped
[  116.077967] rust_alloc_demo: init: buffer_kb=4194304
[  116.078177] rust_alloc_demo: setup guard dropped

This is fallible allocation doing its job. The size check in __kvmalloc_node_noprof logged a one-time WARNING with a stack trace (hidden here by the grep) and returned no memory. The AllocError became ENOMEM through ?, insmod reported Cannot allocate memory, and lsmod shows nothing loaded. The kernel carried on.

Two things to read in it. First, setup guard dropped printed, but exit: freeing did not. The guard was a local, so ? dropped it on the way out. The module struct was never built, so its Drop had nothing to run on, and the loader does not call exit after a failed init. On a failed init, only the locals you already own are cleaned up for you, which is why anything acquired early in init needs an owning type with a Drop.

Second, init ran twice. That is not your module. strace shows Ubuntu’s insmod trying finit_module, getting ENOMEM, then retrying with init_module:

raghu@techveda:~$ sudo strace -e trace=finit_module,init_module insmod rust_alloc_demo.ko buffer_kb=4194304
finit_module(3, "buffer_kb=4194304", 0) = -1 ENOMEM (Cannot allocate memory)
init_module(0x7ca48f93d000, 796672, "buffer_kb=4194304") = -1 ENOMEM (Cannot allocate memory)
insmod: ERROR: could not insert module rust_alloc_demo.ko: Cannot allocate memory
+++ exited with 1 +++

The second attempt logs no warning because it is a WARN_ON_ONCE. The lesson is that init can be called again after it fails, so it must leave nothing behind — and this one does not.

What the same init looks like in C

To see what the Rust version saves you, here is the same init written in C, with setup() and undo_setup() standing in for the guard. It compiles against the same Ubuntu headers and behaves the same way on all three loads: 64 KiB loads, zero gives Invalid parameters, and 4 GiB gives Cannot allocate memory.

static int __init c_alloc_demo_init(void)
{
	int ret;

	if (!buffer_kb || check_mul_overflow(buffer_kb, 1024UL, &bytes))
		return -EINVAL;

	ret = setup();
	if (ret)
		return ret;

	stats = kmalloc(sizeof(*stats), GFP_KERNEL);
	if (!stats) {
		ret = -ENOMEM;
		goto err_undo_setup;
	}
	stats->requested_kb = buffer_kb;

	buffer = kvmalloc(bytes, GFP_KERNEL);
	if (!buffer) {
		ret = -ENOMEM;
		goto err_free_stats;
	}
	memset(buffer, 0xa5, bytes);

	undo_setup();
	return 0;

err_free_stats:
	kfree(stats);
err_undo_setup:
	undo_setup();
	return ret;
}

Three things here are your job in C and the compiler’s in Rust.

  • The check. kmalloc and kvmalloc return a pointer that may be NULL, and nothing stops you using it unchecked. KVVec::from_elem returns a Result, so there is no buffer to touch until you have dealt with the error.
  • The unwind. Each allocation adds a goto label, and the labels must stay in reverse order as init grows. Miss one and every failed load leaks. In Rust, ? returns and every value init owns is dropped on the way out, in reverse order of creation. In Step 8 that included stats: its KBox had already succeeded, and ? freed it along with the guard.
  • The error code. C sets ret = -ENOMEM by hand at each failure site. Rust converts AllocError to ENOMEM in one place, inside the kernel crate.

Unload differs the same way. The C exit function must call kvfree and kfree on what init kept; in Rust, dropping the module struct does it.

Step 9: Seeing why the buffer is a KVVec

Change KVVec to KVec in both places, rebuild, and load it with buffer_kb=8192. KVec uses kmalloc only, which needs 8 MiB of physically contiguous pages:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=8192
insmod: ERROR: could not insert module rust_alloc_demo.ko: Cannot allocate memory
raghu@techveda:~$ sudo dmesg | grep -E "rust_alloc_demo: |WARNING|cut here"
[  266.397606] rust_alloc_demo: init: buffer_kb=8192
[  266.400722] ------------[ cut here ]------------
[  266.400934] WARNING: mm/page_alloc.c:5290 at __alloc_frozen_pages_noprof+0x304/0x360, CPU#0: insmod/1602
[  266.409883] rust_alloc_demo: setup guard dropped
[  266.440060] rust_alloc_demo: init: buffer_kb=8192
[  266.440221] rust_alloc_demo: setup guard dropped

The warning comes from the page allocator’s check that the requested order is no larger than MAX_PAGE_ORDER. With 4 KiB pages that caps a single block at 4 MiB, so the 8 MiB request is refused however much memory is free. The same KVec build loads 2 MiB without complaint:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=2048
raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg
[  267.550082] rust_alloc_demo: init: buffer_kb=2048
[  267.560404] rust_alloc_demo: allocated 2097152 bytes, first byte 0xa5
[  267.560727] rust_alloc_demo: setup guard dropped
[  267.918090] rust_alloc_demo: exit: freeing 2097152 bytes (2048 KiB requested)

Change the two words back to KVVec, rebuild with make, and the 8 MiB load succeeds:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=8192
raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg
[  269.000426] rust_alloc_demo: init: buffer_kb=8192
[  269.047796] rust_alloc_demo: allocated 8388608 bytes, first byte 0xa5
[  269.047919] rust_alloc_demo: setup guard dropped
[  269.399540] rust_alloc_demo: exit: freeing 8388608 bytes (8192 KiB requested)

For a fallible allocation of small, bounded data pick KVec; anything sized by a user belongs in KVVec.

Common wrong turns

Dropping the * on value(). On this kernel the parameter is read by reference, and the compiler says so:

raghu@techveda:~$ make 2>&1 | grep -E "^error|-->"
error[E0277]: can't compare `&usize` with `{integer}`
  --> rust_alloc_demo.rs:45:15
error[E0308]: mismatched types
  --> rust_alloc_demo.rs:53:53
error: aborting due to 2 previous errors

Leaving out the GFP flag on a fallible allocation. Standard Rust collections take no flag, so the habit is strong. Here it is a compile error that names the missing piece:

raghu@techveda:~$ make 2>&1 | grep -E "^error|-->|missing"
error[E0061]: this function takes 3 arguments but 2 arguments were supplied
  --> rust_alloc_demo.rs:54:22
   |                      ^^^^^^^^^^^^^^^^--------------- argument #3 of type `kernel::alloc::Flags` is missing
  --> /build/linux-jtx3CT/linux-7.0.0/rust/kernel/alloc/kvec.rs:795:11
error: aborting due to 1 previous error

Writing let _ = Setup; instead of let _setup = Setup;. It compiles without complaint, but _ binds nothing, so the guard is dropped on the spot. On a load it prints before the allocation, and on a failure path it protects nothing:

raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=64
raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg
[  217.149063] rust_alloc_demo: init: buffer_kb=64
[  217.156558] rust_alloc_demo: setup guard dropped
[  217.160547] rust_alloc_demo: allocated 65536 bytes, first byte 0xa5
[  217.565518] rust_alloc_demo: exit: freeing 65536 bytes (64 KiB requested)

Reading the kernel log without sudo. Ubuntu restricts the kernel log to root, so a plain dmesg fails with dmesg: read kernel buffer failed: Operation not permitted. Use sudo dmesg.

Looking for the parameter under /sys/module/rust_alloc_demo/parameters/. Step 6 listed that directory, and there is no parameters entry. The module! macro registers Rust parameters with no sysfs permissions. Use modinfo -p to see the parameter, and dmesg to see the value the module received.

Verification checklist

Each check exercises one fallible allocation path in your module.

  1. rustc --version matches CONFIG_RUSTC_VERSION_TEXT in your kernel’s build tree.
  2. modinfo -p rust_alloc_demo.ko prints buffer_kb with its description and type (usize).
  3. buffer_kb=64 loads and unloads; sudo dmesg ends with exit: freeing 65536 bytes.
  4. buffer_kb=0 fails with Invalid parameters, and there is no setup guard dropped line.
  5. buffer_kb=4194304 fails with Cannot allocate memory; setup guard dropped appears and exit: freeing does not.
  6. lsmod | grep rust_alloc_demo prints nothing after either failure.
  7. With KVec in place of KVVec, buffer_kb=8192 fails and buffer_kb=2048 loads.

Limits, and what was not verified

Every command, compiler message, insmod result and dmesg line above came from Ubuntu 26.04 LTS on x86_64 with kernel 7.0.0-44-generic, 2 GiB of RAM and Secure Boot off. With Secure Boot on, Ubuntu will not load an unsigned module, and module signing is not covered here. Timestamps, addresses and the line numbers in the warnings will differ on other kernel updates. The 4 MiB kmalloc ceiling is specific to 4 KiB pages.

Key takeaways

  • On Ubuntu 26.04 an out-of-tree Rust module needs linux-headers and linux-lib-rust for the running kernel and the matching rustc; nothing has to be rebuilt.
  • Fallible allocation is the default in kernel Rust: KBox::new, KVVec::from_elem and their relatives take a GFP flag and return a Result, and ? turns an AllocError into ENOMEM.
  • Validate parameters before acquiring anything, and return your own Err(EINVAL); kmod reports it as Invalid parameters.
  • A failed init never runs the module struct’s Drop. Hold early resources in a named local with its own Drop, and expect init to be called again.
  • Use KVVec for anything sized by a user; KVec stops at the page allocator’s largest block.

The C conventions this wraps — kmalloc against vmalloc, GFP flags and the negative-errno return contract — are covered in our Linux kernel infrastructure course.

Was this worth your time?

Frequently asked questions

What does fallible allocation mean in kernel Rust?
Every allocating call takes a GFP flag and returns a Result, instead of panicking or handing back a null pointer you might forget to check. The failure is a value you handle, and ? is the shortest way to pass it up to the caller.

Do I need to build a kernel to write Rust modules on Ubuntu?
No. Ubuntu 26.04’s generic kernel is built with Rust support, and linux-lib-rust-$(uname -r) ships the precompiled kernel crates an out-of-tree module links against.

Will my Drop implementation run if init fails?
Not the module struct’s. It never runs after a failed init, because the struct was never built. Locals that init already owns are dropped as ? returns, which is why the Setup guard printed in Step 8 and exit: freeing did not.

Further reading

RB
Raghu Bharadwaj

Founder, TECH VEDA — 20+ years teaching the Linux kernel, device drivers and embedded systems.

Follow on LinkedIn

Get the best of TECH VEDA by email

The best of our kernel and embedded Linux writing, a few emails a month. No spam.

We email occasionally and never share your address.