Module 5 · Lesson 104 of 129

Rust vs C and the roadmap

Compare the safety guarantees of equivalent C and Rust drivers, identify the Rust support in a target kernel, and port an ioctl without changing its ABI.

  • Beginner to advanced
  • 7 min read
  • 45 min lab
What you will need

Ubuntu 24.04 in a VM; the M5 C ioctl driver and user-space test program; the Rust character-device source and matching Rust-enabled kernel build from the preceding lesson

Your place in the module
By the end you can 3 objectives
  • Explain how Rust rejects a reference that outlives its owner
  • Distinguish Rust support in Linux 6.8 from the APIs available in a specific kernel build
  • Port one M5 ioctl and compare its user-visible behavior with the C implementation
Video coming soonRust vs C and the roadmap
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from A Rust character device
  • The historical FileOperations, IoctlHandler and character-device Registration interfaces are absent from upstream Linux 6.8.
  • The read and write callbacks report transferred bytes and follow the reference driver's offset and fault rules.
  • An ioctl with an unknown request returns ENOTTY.
01

What the compiler can prevent

4 min read

The last lesson built a Rust char device. This lesson answers the comparison: which C bugs the type system makes impossible, and the current state and limitations of Rust in the kernel.

The Linux ioctl documentation recommends fixed-width fields and careful attention to padding because a user program and its driver can disagree about the layout of the same request. This is a concrete problem for a port. The Rust compiler can prove that a reference to the driver's state is valid while the handler uses it. The command number and byte layout must still agree with the C implementation. Linux ioctl interface documentation

Take the M5 character device with one ioctl that reads a setting from driver state. In the C version, imagine that a helper takes a lock, obtains a pointer to a setting inside a replaceable object, releases the lock and returns the pointer. While an ioctl holds that pointer, another caller can replace and free the object. The pointer has the expected C type throughout, so that type alone does not prevent the ioctl from dereferencing freed storage. A correct C implementation can copy the setting under the lock and return the independent value. It can also retain a reference to the backing object if the design requires access after unlocking.

In Rust, put the same replaceable object behind a lock whose guard grants access to it. A reference obtained through that guard is borrowed from it. Returning that reference after the local guard is dropped is rejected at compile time. Copying a scalar while the guard is held gives the handler an independent value it can use after unlocking. The compiler can check the distinction between that owned snapshot and the borrowed reference because the lock API expresses it in types and lifetimes.

Reading a locked settingC implementationSafe RustUnder lockPointer tosettingBorrowthrough guardAfter unlockPointer maydangleBorrowrejectedIndependentsnapshotCopy underlockCopy underguard
The same setting read, with different compiler guarantees

The same distinction applies to per-open state. Assigning a raw pointer in C creates another pointer to the same object. The driver must track who may free that object and when. Moving a Rust value with a unique, non-copyable owner transfers ownership. Safe code cannot keep using the moved owner or drop it a second time. Safe references also prevent conflicting access to ordinary borrowed data. Shared mutation requires a suitable abstraction, such as a lock or an atomic type. That rules out data races through sound safe APIs, while a race over which correctly synchronized operation happens first can still change the result.

A safe slice carries its length. Checked access can report a missing element, and ordinary indexing checks bounds and can panic. For an index supplied through an ioctl, handle the invalid case explicitly and return the error specified by the device interface. The bounds check protects memory. Choosing a consistent error is the driver's job.

The guarantees depend on the implementations underneath the safe API. At a C callback boundary, code that turns a raw pointer into a Rust reference must establish that the pointer is valid, suitably aligned and live for the lifetime it claims. Incorrect unsafe code or a C callback that violates that assumption can invalidate the guarantee. Safe Rust also permits deadlocks through inconsistent lock order and cannot check whether a register write occurs at the right time.

02

What the target kernel supports

2 min read

Use upstream Linux 6.8 as the baseline for this Ubuntu 24.04 lesson. That tree includes Rust build support, sample modules, core abstractions for kernel objects and synchronization, and Rust abstractions for Ethernet PHY drivers. PHY support covers a specific area of networking. The C interfaces covered in M5, including GPIO, I2C, SPI, IIO and DRM, do not acquire equivalent Rust APIs simply because the kernel can build a Rust module. A subsystem can expose a small Rust interface for a particular driver while much of its C API remains outside that interface.

Verify Rust supportKernelreleaseBuild configurationToolchaincheckRequiredinterfaceKernelreleaseBuild configurationToolchaincheckRequiredinterface
Check the source and build you will actually use

A running Ubuntu kernel, the upstream 6.8 source and the course kernel are distinct things to check. uname -r gives the running kernel release. Check that kernel's build configuration for CONFIG_RUST=y, then inspect the matching source tree for the abstraction and callback your driver needs. In the source tree, make LLVM=1 rustavailable checks whether the toolchain meets that tree's Rust build requirements. A successful toolchain check does not tell you that the running kernel was built with Rust or that the desired subsystem abstraction exists. Use the character-device interface supplied by the course tree when it differs from the upstream baseline. Linux 6.8 Rust Quick Start

Three build and API constraints explain why a user-space Rust example seldom ports directly. First, procedural macros run on the build host during compilation. Kernel macros such as module! are built for that environment and generate code for the target kernel. A third-party procedural macro also runs on the host, but both its build dependencies and the code it emits must suit the kernel build. In particular, generated target code cannot assume the Rust standard library is available.

Second, the kernel supplies its own allocation support. Use allocation APIs available in your tree and account for allocation failure and the caller's execution context. An allocation that may sleep is unsuitable while holding a spinlock. A scalar ioctl snapshot gives a useful comparison because copying it needs no heap allocation in either implementation.

Third, the 6.8 Rust support uses unstable compiler features. Toolchain compatibility is therefore a property of the target source tree. Follow its documented version requirements and check its available APIs before copying an example from a newer kernel. The roadmap is incremental: add abstractions needed by real drivers, express ownership and callback requirements in those APIs, and reduce reliance on unstable compiler features as suitable support becomes available. Judge availability by the code in the target tree. A posted series or a working driver on a different tree establishes a different level of support. Linux 6.8 Rust General Information

03

Preserve the ioctl contract

2 min read

Treat the C command definition and the existing user-space test program as the specification for this port. Record the request number, whether the argument is a pointer or an immediate value, the data width and layout, and the success and error behavior. An _IOR getter transfers data to user space. The type in the command definition contributes to its encoded size, so substituting a wider field can change both the bytes transferred and the command number. For an existing fixed-width scalar getter, encode the same width and native byte order. For a structure, verify the layout and padding against the existing definition before transferring bytes. Linux ioctl interface documentation

Porting a getterExistingrequestnumberSnapshotunder lockReleaselockCheckeduser copyExistingbyte layoutExistingrequestnumberSnapshotunder lockReleaselockCheckeduser copyExistingbyte layout
The ioctl contract stays the same across the port

The Rust callback should dispatch the existing request number, obtain a snapshot of the setting under the appropriate lock, then drop the guard before the user copy. Use the user-access helper provided by the course tree. If the course device uses a C adapter for the callback, that adapter can perform the checked user copy while Rust supplies the value. A pointer passed by a user program can be invalid even when it has the right width. Keep it at the user-access boundary and report a failed copy as EFAULT for the pointer-based getter. Unknown commands should produce ENOTTY. These behaviors require explicit implementation and comparison.

Run the same user-space program against each driver in turn, changing the device path if needed. Compare the return status and returned value for the same initial state, then compare the unknown-command result and the bad-pointer result for a pointer-based getter. Record one lifetime or ownership rule the Rust compiler enforced and one ABI rule the program had to check at runtime. Those two observations show what changed in the implementation and what the device still owes its callers. ioctl(2)

The next lesson, How the kernel is developed, explains how changes such as a new driver or a Rust subsystem abstraction move from proposed code into a released kernel.

Key takeaways

  • Safe Rust rejects dangling references and conflicting borrows when the driver uses sound abstractions.
  • The compiler cannot prove that a driver implements the correct ABI, lock order or hardware protocol.
  • Linux 6.8 includes Rust infrastructure and Ethernet PHY abstractions, with coverage varying by subsystem and kernel tree.
  • A port can reuse its user-space test program when it preserves the ioctl ABI.
Reflect
  1. Explain to a colleague, in two sentences: explain how Rust rejects a reference that outlives its owner
  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