Module 9 · Lesson 92 of 112

Porting the M5 driver to Rust

Map the M5 character driver's callbacks and user copies to Rust abstractions while preserving the Linux device interface.

  • Beginner to advanced
  • 10 min read
  • 20 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, the M5 C driver source, and familiarity with the Rust kernel module build. The exercises use source inspection and require no board.

Your place in the module
By the end you can 4 objectives
  • Identify the M5 device number, registration method, and user-visible contract.
  • Map the C callbacks to Rust registration, per-open state, and operation methods.
  • Calculate bounded transfer lengths and specify byte counts, offsets, and errors.
  • Distinguish the Ubuntu 24.04 kernel baseline from Rust APIs supplied by other kernel trees.
Video coming soonPorting the M5 driver to Rust
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Character devices and C abstractions
  • Character-device registration connects device numbers to file operations.
  • Linux 6.8 provides the C misc-device API and lacks an upstream Rust character-device registration wrapper.
  • Generated bindings describe the C interface, while safe Rust wrappers enforce its usage rules.
01

Preserve the M5 device interface

4 min read

The Rust-for-Linux lessons ended with char devices and C abstractions. This lesson answers how to port the M5 character driver to Rust.

A program can open the expected device node and still break after a driver port. For example, read(2) can return fewer bytes than requested. A program that reads a finite value in successive calls depends on the driver making progress and eventually returning zero at end of file. A port that serves the beginning on every call can keep that program reading indefinitely. Before translating the callbacks, write down what the M5 driver returns and how each call affects the next one. read(2)

Start at the C driver's initialization function. A character device node carries a device number made of a major and a minor. A registration associates a device number or range with a character device and its operations. A range can give one driver several instances, distinguished by minor. The pathname is how the program finds the node. The device number is how the kernel finds the corresponding registration. Record whether M5 requests a fixed number or accepts an assigned one, and whether anything outside the module depends on that choice. A system that creates a node from fixed numbers needs a different compatibility check from one that discovers the node by name.

The direct character device route reserves a device number range and registers a cdev with its file_operations. The Rust-for-Linux chrdev::Registration abstraction in trees that provide it manages the character device registrations through an owned value. Keep the registration alive in the module or device state for as long as new opens should be possible. Dropping it removes its registrations. If M5 uses multiple minors to choose an instance, preserve the mapping from minor to instance. Check node creation separately, since registering a cdev and making a pathname available to a program are distinct operations.

A miscdevice is another route for a simple character device. Misc devices share a major, and MISC_DYNAMIC_MINOR asks the misc subsystem to assign a minor. Use the misc registration approach when it fits the M5 contract, for example when the program discovers a single device by name and can accept the assigned number. A switch from a dedicated character device range to misc changes the device number scheme. Check any static node, startup script, or minor-based instance logic before making that switch. The C misc subsystem also supplies a default file->private_data value pointing to the miscdevice before any driver open callback runs. Keep that distinction in mind when deciding which context supplies the device and which value belongs to the open file. Miscellaneous devices

Character device lookupDevice nodePath openedby programMajor andminorDevicenumberstored innodeDevice registrationFileoperationsDriver opencallback ifsuppliedDevice nodePath openedby programMajor andminorDevicenumberstored innodeDevice registrationFileoperationsDriver opencallback ifsupplied
Opening a character device resolves its device number to the registered operations
Match the Rust API to the kernel source

The upstream Linux 6.8 baseline used by Ubuntu 24.04 does not supply the historical Rust-for-Linux chrdev::Registration, file::Operations, and kernel::io_buffer driver interfaces described here. UserSlice is an API from newer Rust kernel trees. These names describe concrete approaches from different trees, with no assumption that they coexist. Inspect the source for the kernel you will build before choosing imports, method signatures, and registration macros. On the 6.8 baseline, a port needs a C integration layer for the missing interfaces or a kernel tree that provides the required abstractions.

Keep a short contract beside the C source. Record the node name, any device number requirements, what an open initializes, and what happens when a second caller opens the device. Record the return values for a zero-length request, a short transfer, and a read after the data is exhausted. Include the seek policy and the ioctl commands the C table actually provides. Where M5 leaves an operation absent, look at the user-visible result before deciding whether the Rust driver needs to register a callback at all.

02

Translate the file operations

4 min read

In a tree with file::Operations, implement the trait for the driver type and use that tree's operation-table mechanism to register the methods with the VFS. Read the trait together with its adapter. The trait defines the arguments the Rust driver sees, while the adapter defines which C table entries are present and how a Rust result becomes a return value at the kernel boundary. A method name in a Rust trait can differ from the corresponding field name in the C table.

open and release. Start with every assignment to file->private_data in M5. If open creates state for the open file, construct the corresponding Rust value and return it as the trait's associated Data. The adapter owns that value on behalf of the open file and gives later operations access to it. If M5 opens a shared device, use the registration context to find it and keep the appropriate owned reference in the open data when the implementation needs one. When an open fails, return its error and let any values already created for that attempt drop.

release receives the per-open value back in the historical trait design. Drop that value to reclaim the resources it owns and perform any final driver action M5 requires. The lifetime here is the life of the open file description. Two independent opens can have separate state. A duplicated descriptor refers to the same open file description and shares its file position. Closing just one descriptor can leave the description alive if another reference remains. For example, clearing per-open state on every close would be too early for a caller that continues through a duplicate. open(2)

read and write. In the historical Operations interface, read receives an IoBufferWriter, and write receives an IoBufferReader. Read fills the caller's destination. Write consumes the caller's source. Both methods also need the file position when M5 defines position-based I/O. Use the offset supplied by the interface and inspect how the adapter updates the underlying position. If it advances the position by the successful byte count, leave that update to the adapter. For an operation defined as a stream, preserve the stream's rules for positions. An Ok(n) from either transfer reports n bytes, and an error reports the corresponding kernel errno through the adapter.

llseek. Use the Rust seek hook, named seek in the historical trait, to implement the C .llseek behavior when the device supports positioning. The seek input describes the origin and an offset. For a seekable device, resolve the origin against the correct base, such as the current file position for SEEK_CUR or the logical end for SEEK_END. Check arithmetic and reject positions outside the range allowed by M5. A seek beyond the current end is a policy decision to preserve from the C driver. For a device defined as nonseekable, configure and check that behavior through the target interface. A user call to lseek on an open file marked nonseekable fails with ESPIPE.

unlocked_ioctl. The C .unlocked_ioctl slot receives a command and an argument. In the historical Rust trait, the ioctl hook receives the request through an IoctlCommand abstraction. Match the same command values as M5 and interpret the argument according to each command's definition. If the argument is a userspace address, handle it through the user-access interface. Preserve each command's successful result and return ENOTTY for unsupported commands. When M5 exposes no commands, the port needs no new command handler. A writable device can still reject every ioctl request. ioctl based interfaces

Character driver callback mappingC slotRust hookCreate openstate.openopenDrop open state.releasereleaseSend bytes.readreadReceive bytes.writewriteSet position.llseekseekHandle controlrequest.unlocked_ioctlioctl
The operation table connects C callback slots to Rust method responsibilities

For each callback, review the operation from a caller's point of view. If a read succeeds after a short transfer, the next read should start from the position implied by that byte count. If an open fails, there is no new usable descriptor. If a seek succeeds, the next position-based operation should use the returned position. These observable results give you a way to compare the port against M5 even when the driver state and callback signatures look different in Rust.

03

Copy bytes across the user boundary

4 min read

A C read callback receives a userspace destination buf and a requested count. It uses copy_to_user to send bytes from a kernel buffer. A C write callback receives a userspace source and uses copy_from_user to bring bytes into kernel memory. Those C helpers return the number of bytes left uncopied. Zero means the full requested copy succeeded. The driver interprets that return before reporting progress. For example, directly returning that value from .read would report zero for a complete copy, which a reader could interpret as end of file.

In the historical Rust interface, kernel::io_buffer::{IoBufferReader, IoBufferWriter} gives the driver safe slice-based operations. IoBufferReader::read_slice copies bytes into a mutable kernel slice. IoBufferWriter::write_slice copies bytes from a kernel slice into the supplied destination. Use the buffer's remaining len() when calculating the transfer. On a user-backed implementation, these methods wrap the kernel's user-copy machinery and report a Result. In a newer tree with kernel::uaccess::UserSlice, use the reader or writer obtained from the user slice. The address and length describe untrusted userspace memory, and the reader or writer supplies the access operations.

User copy directionsDevice readDevice writeSourceKernel bufferUser bufferDestinationUser bufferKernel bufferC helpercopy_to_usercopy_from_userRust buffer viewIoBufferWriterIoBufferReader
A write reads from the user buffer, and a read writes to the user buffer

Walk through one call to the M5 read handler. For a finite, position-based read, check the position before slicing the kernel data. If it is at or beyond the logical end, return zero. Otherwise calculate how many bytes remain, then take the smaller of that number and the user writer's remaining length. Select exactly that many initialized kernel bytes and pass the slice to write_slice. After a successful copy, report the slice length. If the request was shorter than the available data, the caller can issue another read to get the rest. Determine zero-length behavior before touching the user buffer. read(2)

For write, determine how much data M5 will accept for the current request. Bound the amount by the reader's remaining length and by what the driver can accept at this position. Pass a mutable kernel slice of that size to read_slice. If the M5 contract commits data only after a successful copy, stage the bytes separately and commit after success. On a copy error, the staging slice may already contain some copied bytes. Returning an error keeps those bytes out of committed device state in this design. If M5 deliberately reports a copied prefix as a short write, verify that the chosen Rust interface exposes enough information to account for that prefix. An interface that returns just Result<()> for a requested copy can tell you it failed without giving you the number of bytes copied. write(2)

Going deeperExplore the mechanism

UserSlice describes a user address and length without constructing a Rust reference into userspace. Its reader and writer compare the requested kernel slice length with the remaining user length before copying. The kernel slice provides its own valid extent. With a user-backed IoBufferReader or IoBufferWriter, the implementation likewise provides a bounded, safe operation to the calling driver. Safe here means the driver calls these methods without an unsafe block. The implementation underneath is responsible for calling the low-level user-access code correctly.

A length check answers whether the transfer fits within the declared count. The kernel's user-access routines handle the address checks and the actual memory access. Creating a UserSlice does not verify that every page in buf is mapped or accessible. A request can fit the length and still return EFAULT when the copy touches an inaccessible page. Userspace can change its memory while a system call is running. If the driver needs to validate a value before acting on it, copy it into kernel memory once and validate and use that copy.

The raw C helpers also perform user access checks. A C caller can still give the helper a length that exceeds the intended kernel buffer or mistake the uncopied-byte result for success. A safe Rust wrapper derives the copy size from the kernel slice and checks it against the user extent. The driver remains responsible for choosing the correct bytes, handling the returned error, and deciding when state changes take effect. A failed copy to userspace can already have modified some destination bytes, so an error result supplies no guarantee that the original user buffer is intact.

When reviewing the port, trace one successful transfer and one failed transfer through the callback. For each, account for the syscall result, the file position, and any committed device state. This gives you the information you need to tell whether the Rust code preserves the behavior M5 callers rely on.

The next lesson, Device buffers, logging, and ioctl, answers how the driver organizes its device buffer, reports events, and implements control commands once its file operations and user copies are in place.

Key takeaways

  • A character device node identifies a kernel registration by major and minor number.
  • Registration state lives for the device, while private file state lives for an open file description.
  • A device read writes to userspace, and a device write reads from userspace.
  • A bounded user buffer can still fault when the kernel accesses it.
Reflect
  1. Explain to a colleague, in two sentences: identify the M5 device number, registration method, and user-visible contract.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close