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 4: How to Read and Write a Rust Misc Device From User Space

Add a Rust misc device to your out-of-tree module on Ubuntu 26.04: registration, read and write handlers, and why lseek returns ESPIPE.

Rust for Linux: A Beginner’s Guide — Part 4: How to Read and Write a Rust Misc Device From User Space

In this part you give the module from Part 3 a device node, so a buffer allocated inside the kernel can be written and read from a shell. Adding a Rust misc device forces two changes you cannot avoid: the module trait changes, and the allocation moves from load time to open time. You also find out why lseek on the device fails, and why that decides how the read handler must behave.

Part 1 set up the toolchain. Part 2 showed that the generated exit path only drops your module struct. Part 3 built rust_alloc_demo, which takes a buffer size as a parameter and allocates it with fallible allocation. Nothing outside the kernel could reach that buffer. This part turns it into a Rust misc device at /dev/rust_alloc_demo.

What you need before you start

The ~/rust_alloc_demo directory from Part 3, Kbuild and Makefile unchanged, on Ubuntu 26.04 LTS running its stock generic kernel. This run used 7.0.0-43-generic, so the minor numbers, timestamps and warning line numbers below will differ on your machine. The packages are the ones Part 3 installed:

raghu@techveda:~$ sudo apt install linux-headers-$(uname -r) linux-lib-rust-$(uname -r) rustc rust-src build-essential dwarves
raghu@techveda:~$ uname -r
7.0.0-43-generic
raghu@techveda:~$ rustc --version
rustc 1.93.1 (01f6ddf75 2026-02-11) (built from a source tarball)

One version gate first: the Rust misc device abstraction is still changing. The code below matches the trait at Linux 7.0, unchanged at 7.1, 7.2 and 7.3. At 7.4-rc4 the associated type is File rather than Ptr and register is unsafe and takes a second argument, so this file needs edits there.

Step 1: Change the module trait so the registration can be pinned

Part 3’s module wrote impl kernel::Module for AllocDemo, whose init returns Result<Self>: the kernel gets a value back and moves it into its final place. A registration cannot survive that. MiscDeviceRegistration<T> wraps a C struct miscdevice, and misc_register() puts the address of that struct on a kernel list, so it has to be built where it will stay. That is what pinning means here.

The kernel crate has a second trait for exactly this: InPlaceModule::init returns an initialiser instead of a value. You cannot implement both, because rust/kernel/lib.rs carries a blanket impl<T: Module> InPlaceModule for T. Start rust_alloc_demo.rs again; Part 3’s Stats and Setup types are not needed here:

// SPDX-License-Identifier: GPL-2.0

//! Misc device backed by the fallible allocation from Part 3.

use kernel::{
    fs::{File, Kiocb},
    iov::{IovIterDest, IovIterSource},
    miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration},
    new_mutex,
    prelude::*,
    sync::Mutex,
};

module! {
    type: AllocDemoModule,
    name: "rust_alloc_demo",
    authors: ["TECH VEDA"],
    description: "Misc device backed by a fallible allocation",
    license: "GPL",
    params: {
        buffer_kb: usize {
            default: 64,
            description: "Per-open buffer size in KiB (must be non-zero)",
        },
    },
}

#[pin_data(PinnedDrop)]
struct AllocDemoModule {
    #[pin]
    _miscdev: MiscDeviceRegistration<AllocDemoDev>,
}

impl kernel::InPlaceModule for AllocDemoModule {
    fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
        pr_info!("registering misc device rust_alloc_demo\n");

        let options = MiscDeviceOptions {
            name: c"rust_alloc_demo",
        };

        try_pin_init!(Self {
            _miscdev <- MiscDeviceRegistration::register(options),
        })
    }
}

#[pinned_drop]
impl PinnedDrop for AllocDemoModule {
    fn drop(self: Pin<&mut Self>) {
        pr_info!("unregistering misc device rust_alloc_demo\n");
    }
}

#[pin_data] marks the struct as pin-initialised, #[pin] marks the field that must not move, and the <- arrow inside try_pin_init! means that field is built by an initialiser rather than assigned. Drop becomes PinnedDrop. Deregistration is not your job: the registration’s destructor calls misc_deregister().

Step 2: Declare the state behind one open file

The module struct now holds only the registration. The buffer belongs to the device, so it needs a type of its own. Add these below the code in Step 1:

/// State behind one open file.
struct Inner {
    buffer: KVVec<u8>,
    used: usize,
}

#[pin_data]
struct AllocDemoDev {
    #[pin]
    inner: Mutex<Inner>,
}

used records how many bytes have been written, so the read handler knows where the data ends. The Mutex is not optional: two threads can share one open file and call read and write at once, so the buffer and the count must change together. It is a pinned type, hence #[pin_data] here too.

Step 3: Allocate the Rust misc device buffer on open

Here is where the Rust misc device changes the shape of Part 3’s module. Part 3 validated buffer_kb and allocated the buffer in init. The module no longer owns a buffer, so both the check and the allocation move into open:

#[vtable]
impl MiscDevice for AllocDemoDev {
    type Ptr = Pin<KBox<Self>>;

    fn open(_file: &File, _misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Self>>> {
        let kb = *module_parameters::buffer_kb.value();
        if kb == 0 {
            pr_err!("open: buffer_kb must be non-zero\n");
            return Err(EINVAL);
        }
        let bytes = kb.checked_mul(1024).ok_or(EINVAL)?;

        let buffer = KVVec::from_elem(0u8, bytes, GFP_KERNEL)?;
        pr_info!("open: allocated {} bytes\n", buffer.len());

        KBox::try_pin_init(
            try_pin_init! {
                AllocDemoDev {
                    inner <- new_mutex!(Inner { buffer, used: 0 }),
                }
            },
            GFP_KERNEL,
        )
    }

    fn release(device: Self::Ptr, _file: &File) {
        let used = device.inner.lock().used;
        pr_info!("release: {} bytes had been written\n", used);
        drop(device);
    }

type Ptr says what kind of pointer the per-open state is wrapped in. What open returns is stored in the file’s private data and handed back to every later call on that file. release receives it by value, so dropping it frees the buffer.

This moves Part 3’s error paths. insmod now succeeds whatever buffer_kb says, because loading allocates nothing; a bad size is reported to whoever opens the device.

Step 4: Write the read and write handlers

Finish the impl block with the two handlers and a closing brace:

    fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource<'_>) -> Result<usize> {
        let me = kiocb.file();
        let mut inner = me.inner.lock();

        let pos = usize::try_from(kiocb.ki_pos()).map_err(|_| EINVAL)?;
        if pos >= inner.buffer.len() {
            return Err(ENOSPC);
        }

        let written = iov.copy_from_iter(&mut inner.buffer[pos..]);
        inner.used = core::cmp::max(inner.used, pos + written);
        drop(inner);

        pr_info!("write: {} bytes at offset {}\n", written, pos);
        *kiocb.ki_pos_mut() = 0;
        Ok(written)
    }

    fn read_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterDest<'_>) -> Result<usize> {
        let me = kiocb.file();
        let inner = me.inner.lock();

        let used = inner.used;
        let read = iov.simple_read_from_buffer(kiocb.ki_pos_mut(), &inner.buffer[..used])?;

        pr_info!("read: {} bytes of {}\n", read, used);
        Ok(read)
    }
}

Both handlers receive a Kiocb, the kernel’s description of one I/O request: a file and a position. kiocb.file() is not the struct file but the per-open state open returned, which is why me.inner.lock() works. ki_pos() reads the position and ki_pos_mut() gives a writable reference.

Both copies go through an iov_iter, the kernel’s wrapper over a user-space buffer. copy_from_iter copies into a slice and returns how many bytes fitted. simple_read_from_buffer serves the slice from *ppos onwards, advances the position, and returns zero once it reaches the end of the data, which is the end of file a reader sees.

Step 5: Build the module and inspect the Rust misc device

raghu@techveda:~$ cd ~/rust_alloc_demo && make
make -C /lib/modules/7.0.0-43-generic/build M=/home/raghu/rust_alloc_demo modules
make[1]: Entering directory '/usr/src/linux-headers-7.0.0-43-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-43-generic'
raghu@techveda:~$ modinfo -p rust_alloc_demo.ko
buffer_kb:Per-open buffer size in KiB (must be non-zero) (usize)
raghu@techveda:~$ sudo dmesg -C
raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=4
raghu@techveda:~$ ls -l /dev/rust_alloc_demo
crw------- 1 root root 10, 263 Nov 29 13:31 /dev/rust_alloc_demo
raghu@techveda:~$ grep rust_alloc_demo /proc/misc
263 rust_alloc_demo
raghu@techveda:~$ ls -d /sys/class/misc/rust_alloc_demo
/sys/class/misc/rust_alloc_demo

You wrote no device number and ran no mknod. Major 10 is the misc major; the minor, 263 here, was allocated because MiscDeviceOptions::into_raw sets MISC_DYNAMIC_MINOR. misc_register() made the class entry and devtmpfs made the node, root-only, so every command below needs sudo.

Step 6: Read back what you wrote on one file descriptor

Open the device once for reading and writing, write to it, then read from the same descriptor:

raghu@techveda:~$ sudo sh -c 'exec 3<>/dev/rust_alloc_demo; printf "hello from userspace" >&3; head -c 64 <&3; echo; exec 3>&-'
hello from userspace
raghu@techveda:~$ sudo dmesg | grep rust_alloc_demo
[  203.250418] rust_alloc_demo: loading out-of-tree module taints kernel.
[  203.252546] rust_alloc_demo: module verification failed: signature and/or required key missing - tainting kernel
[  203.265152] rust_alloc_demo: registering misc device rust_alloc_demo
[  204.200011] rust_alloc_demo: open: allocated 4096 bytes
[  204.206523] rust_alloc_demo: write: 20 bytes at offset 0
[  204.304674] rust_alloc_demo: read: 20 bytes of 20
[  204.307622] rust_alloc_demo: read: 0 bytes of 20
[  204.316400] rust_alloc_demo: release: 20 bytes had been written

exec 3<> opened the device once, so open allocated once. head -c 64 asked for 64 bytes, got 20, asked again and got zero, which is how it knew to stop. Closing the descriptor ran release.

Step 7: Find out why a second open sees nothing

raghu@techveda:~$ sudo cat /dev/rust_alloc_demo | wc -c
0

The twenty bytes are gone, by design rather than by accident. open allocates a fresh AllocDemoDev every time, so each descriptor has its own buffer and byte count, freed at release. The device is scratch space per open, not storage.

Sharing one buffer between opens is not a small edit here: open receives only &MiscDeviceRegistration<Self>, with no handle on module state. Upstream answered that at 7.4-rc4 by giving register an initialiser for data the registration owns.

Step 8: Try to seek, and follow the error to the file operations table

Reading and writing usually implies seeking. On a Rust misc device it does not:

raghu@techveda:~$ sudo python3 -c "
import os
fd = os.open('/dev/rust_alloc_demo', os.O_RDWR)
try:
    print('lseek returned', os.lseek(fd, 0, os.SEEK_SET))
except OSError as e:
    print('lseek: errno', e.errno, '-', e.strerror)
os.close(fd)"
lseek: errno 29 - Illegal seek

Errno 29 is ESPIPE, the error a pipe gives for a seek. Three pieces of kernel source explain it, and the conclusion shapes the handlers.

First, the table. In rust/kernel/miscdevice.rs the constant MiscdeviceVTable::VTABLE fills in open, release, mmap, read_iter, write_iter, the two ioctl entries and show_fdinfo, then finishes with ..pin_init::zeroed(). There is no llseek entry, so that pointer is null, at 7.0 and still at 7.4-rc4.

Second, the open path. do_dentry_open() in fs/open.c sets three mode bits optimistically and then takes one back:

	/* normally all 3 are set; ->open() can clear them if needed */
	f->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
...
	if ((f->f_mode & FMODE_LSEEK) && !f->f_op->llseek)
		f->f_mode &= ~FMODE_LSEEK;

Third, the syscall. vfs_llseek() in fs/read_write.c checks that bit before it calls anything:

loff_t vfs_llseek(struct file *file, loff_t offset, int whence)
{
	if (!(file->f_mode & FMODE_LSEEK))
		return -ESPIPE;
	return file->f_op->llseek(file, offset, whence);
}

So a Rust misc device is a stream, not a file: the position moves only as a side effect of reads and writes, and user space cannot reset it. That is why write_iter sets the position back to zero. If it left the position where the write ended, nothing a process could do would bring it back, and reading back what you just wrote on the same descriptor would be impossible. The driver does the rewind because user space cannot ask for it, and the upstream sample does the same.

Step 9: Make the open fail, and find your handler in the warning

Both error paths from Step 3 now surface at open. A zero size:

raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg -C
raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=0
raghu@techveda:~$ sudo cat /dev/rust_alloc_demo
cat: /dev/rust_alloc_demo: Invalid argument
raghu@techveda:~$ sudo dmesg | grep rust_alloc_demo
[  210.773590] rust_alloc_demo: registering misc device rust_alloc_demo
[  211.302145] rust_alloc_demo: open: buffer_kb must be non-zero

And a size no allocator will satisfy: kvmalloc refuses anything over INT_MAX bytes before it looks at free memory, so 4 GiB fails on any machine:

raghu@techveda:~$ sudo rmmod rust_alloc_demo
raghu@techveda:~$ sudo dmesg -C
raghu@techveda:~$ sudo insmod rust_alloc_demo.ko buffer_kb=4194304
raghu@techveda:~$ sudo cat /dev/rust_alloc_demo
cat: /dev/rust_alloc_demo: Cannot allocate memory
raghu@techveda:~$ sudo dmesg | grep -E "rust_alloc_demo: |cut here|WARNING: mm"
[  212.952141] rust_alloc_demo: registering misc device rust_alloc_demo
[  213.448433] ------------[ cut here ]------------
[  213.448709] WARNING: mm/slub.c:6785 at __kvmalloc_node_noprof+0x586/0x810, CPU#1: cat/1925

Further down, the trace names your own code. The frame is a Rust v0 mangled symbol whose length-prefixed fragments spell out rust_alloc_demo, AllocDemoDev, MiscDevice and open, so the failure is attributed to your handler:

[  213.453754]  _RNvXs3_Csb5skpbK7zPz_15rust_alloc_demoNtB5_12AllocDemoDevNtNtCsj9bqJNU6tGA_6kernel10miscdevice10MiscDevice4open+0x70/0x1c0 [rust_alloc_demo]

Common wrong turns

Unloading the module while a process still has the device open. Do not try this on a machine you care about; it left the test machine needing a reboot. The misc core takes a reference to your module on open only if the file operations table names an owner, and at 7.0 it does not, so the reference count stays at zero:

raghu@techveda:~$ sudo sh -c 'exec 3<>/dev/rust_alloc_demo; lsmod | grep "^rust_alloc_demo"; exec 3>&-'
rust_alloc_demo        16384  0

With the count at zero, rmmod is allowed: the module’s code is freed while the open file still points into it, and closing the descriptor faults:

[ 1081.099624] BUG: unable to handle page fault for address: ffffffffc0aec090
[ 1081.103918] Oops: Oops: 0000 [#1] SMP NOPTI
[ 1081.105766] RIP: 0010:filp_flush+0x2b/0xb0
[ 1081.155033] Fixing recursive fault but reboot is needed!

This is a known gap in the Rust misc device abstraction, fixed upstream: the vtable gains owner: this_module::<T::OwnerModule>().as_ptr() at 7.3, and it is absent at 7.0, 7.1 and 7.2. That boundary comes from reading the source at each tag; no 7.3 kernel was tested here. The wrong turn is attractive because every other resource here is released by ownership, so it is natural to assume the module is protected too.

Expecting a write larger than the buffer to be refused. The ENOSPC arm in write_iter never fires, because the position is reset to zero after every write. Sending 5,000 bytes into a 4 KiB buffer looks like a success:

raghu@techveda:~$ sudo dmesg -C
raghu@techveda:~$ sudo sh -c 'head -c 5000 /dev/zero | tr "\0" "x" > /dev/rust_alloc_demo'
raghu@techveda:~$ sudo dmesg | grep rust_alloc_demo
[  207.250760] rust_alloc_demo: open: allocated 4096 bytes
[  207.423642] rust_alloc_demo: write: 4096 bytes at offset 0
[  207.423986] rust_alloc_demo: write: 904 bytes at offset 0
[  207.430119] rust_alloc_demo: release: 4096 bytes had been written

The shell wrote 4,096 bytes, saw a short write, and sent the remaining 904 bytes, which landed back at offset 0 and overwrote the start. The reasoning is sound: a short write is the right answer to a full buffer. What it misses is that the rewind in Step 8 makes every write a write to offset 0. A Rust misc device can have the rewind or an honest position, not both.

Verification checklist

  1. modinfo -p rust_alloc_demo.ko prints buffer_kb with type (usize).
  2. After insmod, ls -l /dev/rust_alloc_demo shows the Rust misc device as a character device with major 10.
  3. Writing then reading on one descriptor returns the bytes you wrote, and dmesg shows one open, one write, two read lines and one release.
  4. A separate cat returns zero bytes and logs its own open: allocated line.
  5. lseek on the device fails with ESPIPE.
  6. With buffer_kb=0, insmod succeeds and the cat fails with Invalid argument.
  7. With buffer_kb=4194304, the cat fails with Cannot allocate memory.

Key takeaways

  • A Rust misc device registration has to be pinned, so a module that holds one implements kernel::InPlaceModule rather than kernel::Module, with #[pin_data], try_pin_init! and PinnedDrop.
  • Whatever open returns is the per-open state, handed back through Kiocb::file() and freed at release. Each descriptor gets its own, so a Rust misc device shares nothing between opens unless you arrange it.
  • The abstraction fills in no llseek, so the device is a stream and lseek returns ESPIPE. A read handler that has to be re-readable must manage the position itself.
  • At 7.0 the file operations table names no owner, so the module can be unloaded while the device is open. The field arrives at 7.3; before that, treat unloading as unsafe.

The driver model this sits on, and what a character device owes user space, are covered in our Linux device drivers course.

Was this worth your time?

Frequently asked questions

What is a Rust misc device, and how does it differ from a character device?
It is a character device that shares the misc major, number 10, so the kernel allocates the minor and creates the /dev node for you. You implement a trait instead of filling in a struct file_operations by hand.

Why does lseek fail on a Rust misc device?
The abstraction’s file operations table has no llseek entry at any kernel from 7.0 to 7.4-rc4. The kernel clears FMODE_LSEEK on a file whose operations lack it, and vfs_llseek() then returns -ESPIPE, which user space sees as “Illegal seek”.

Is it safe to unload the module while the device is open?
Not on 7.0, 7.1 or 7.2. The file operations table names no owner there, so no module reference is taken, rmmod succeeds and the next operation on the open file touches freed code. The owner field is set from 7.3 onwards.

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.