
Recall first from Kernel allocation, locking, and pin-init
- GFP_KERNEL allows direct reclaim and requires a context that permits sleeping.
- A Rust lock guard bounds access to protected data and releases the lock when dropped.
- Reference counting keeps an object alive while a lock protects its mutable state.
From a device number to a Rust callback
4 min readYou allocated and locked kernel data. This lesson answers how to expose a character device and wrap the C API safely.
The Linux 6.8 Miscellaneous Devices documentation describes a rule that matters as soon as a driver is callable from user space. The struct miscdevice passed to misc_register stays linked into the kernel until the driver unregisters it. Imagine that structure belongs to an object created during module initialization. If the object moves or is freed after registration succeeds, the kernel still holds its original address. The Rust abstraction has to make that address stable and preserve the object's lifetime.
A character-device node records a major and minor number. When a process opens the node, the kernel uses that device number to find the character device and its operations. A driver's struct file_operations is a C table of callback pointers. Its entries determine what the kernel can call for operations such as open, read, write, and release. Once open succeeds, the process uses its file descriptor for subsequent requests. The kernel dispatches through the operations associated with the open file. The device number selects the device at open, while the open file can carry state for that particular opening.
Registering a general character device in C involves reserving a device number or range, initializing a struct cdev with the file operations, and adding it to the kernel's character-device lookup. For example, alloc_chrdev_region reserves a range and cdev_add publishes a device for that range or a portion of it. Publishing a cdev and making a named node appear under /dev are distinct operations. Initialize callback-visible state before publishing the device. An existing node with the matching device number can be used as soon as the device is live.
The earlier Rust-for-Linux development tree offered this general route through kernel::chrdev::Registration. Its registration logic managed the device-number range and added cdev entries. Rust drivers supplied operations through a Rust file-operations trait. The abstraction provided a C file_operations table whose callback functions called the corresponding Rust methods and translated their results to the C conventions. Keeping Registration alive kept its registrations in place. Dropping it removed the character-device entries and released the reserved numbers. Exact signatures and initialization syntax belong to the tree that supplied the abstraction.
Upstream Linux 6.8 has no kernel::chrdev::Registration or Rust misc-device registration abstraction. The historical Registration explains how a Rust wrapper can expose a character device. The C registration APIs are present in Linux 6.8.
The misc-device route in 6.8 starts with a struct miscdevice containing a name, file operations, and a minor-number choice. With MISC_DYNAMIC_MINOR, misc_register assigns an available minor under the shared misc major. The misc core publishes the device through the device model. On a system that populates /dev through devtmpfs or device management, this normally gives the driver a named device node. On open, the misc core switches to the driver's file operations and sets the kernel file object's private_data to the registered miscdevice before invoking the driver's open callback, if one exists. That callback can establish its own per-open state under a defined ownership contract. A Rust misc-device abstraction can express the same sequence by owning the pinned descriptor, making its callbacks available, and pairing successful registration with misc_deregister.
Deregistration stops new lookups through that registration. An already-open file can still exist and keep its operations. Removing the registration and reclaiming everything callbacks can access therefore have different conditions. A wrapper needs to account for operation-table lifetime, module ownership, and the references held by open files. This applies even to a device with one minor and very little state.
From generated C bindings to safe Rust methods
5 min readThe kernel build uses bindgen to generate Rust declarations from selected kernel headers for the target build. In Rust kernel code, bindings:: refers to the generated C interface. It can expose a C structure, a constant, or a declaration for a callable symbol. Generation depends on the selected headers, configuration, and architecture. Kernel builds also provide C helper functions for some operations that cannot be called directly as ordinary C symbols, such as operations defined only as macros or inline functions. Finding a declaration establishes that Rust can describe the interface. Calling it still requires the C operation's preconditions, and a loadable module also needs access to any symbols it calls.
Consider the boundary around misc_register. A raw pointer argument says little about which object owns the descriptor or how long the kernel may keep its address. The wrapper has to know that the descriptor was initialized with valid fields, that any name and callback table it points to stay alive while needed, and that the call runs in a context where sleeping is allowed. It must also interpret the result according to this function's contract. Zero means registration succeeded and a negative errno reports failure. A successful call creates a cleanup obligation. A failed call leaves no successful registration for the wrapper to deregister.
A safe registration method can encode several of these conditions by construction. It can initialize the descriptor itself, retain the storage that backs its fields, and tie cleanup to a guard that exists only after success. Pinning can preserve the descriptor's address after publication. Ownership keeps the allocation alive. The callback contract accounts for concurrent access, and the registration interface must account for any calling-context restriction before it is safe to expose. Keep the raw call in a small unsafe block and record where each guarantee comes from. If a condition still depends on an unchecked promise from the caller, expose that operation as unsafe with the promise documented, or redesign the interface to establish the condition internally.
Going deeperExplore the mechanism
C callbacks often receive a pointer to an embedded C structure. For example, a driver can store a bindings::miscdevice field in a Rust allocation that also holds device state. At the beginning of the misc open callback, private_data can identify that field. Linux 6.8 has no container_of! macro in its Rust crate, so a driver there computes the offset itself in unsafe code. Newer trees supply container_of!, and the macro takes the field pointer, the enclosing type, and the field name. It uses the field's byte offset in the enclosing type to recover a raw pointer to the enclosing object. A layout such as #[repr(C)] is appropriate when C code also relies on the Rust container's layout.
The pointer must really come from the named field of a live instance of that type. A stack-allocated descriptor with identical field values would give the wrong enclosing address. To create a shared Rust reference, the callback must also know that the enclosing object is initialized, that its lifetime covers the borrow, and that access respects Rust aliasing rules. Tie the borrow to a guard or to the callback interval in which the caller guarantees liveness. A callback pointer alone supplies no exclusive access, so mutable driver state may need its own synchronization.
A dev_get_drvdata-style interface uses a different kind of pointer. The driver stores an opaque value using dev_set_drvdata, and dev_get_drvdata retrieves it. In a tree that provides ForeignOwnable, Rust can convert an owning value to an opaque pointer with into_foreign. On a path that guarantees the value remains live, the wrapper uses borrow for temporary access. After preventing further lookups and synchronizing with existing borrowers, teardown uses from_foreign once to recover the transferred owner. The slot can be empty, and assigning to it has no Rust destructor semantics. The code that manages the slot is responsible for arranging publication, borrowing, and cleanup.
If a supported Rust Arc<T> is transferred this way, the slot owns one strong reference. A temporary borrow leaves that count alone. When a callback needs to retain the object independently, it must acquire its own strong reference while the original is still live. Kernel Arc uses kernel reference-counting primitives for the allocation it owns. For an existing C object with its own get and put rules, a wrapper can use ARef with an appropriate AlwaysRefCounted implementation to reuse that object's C refcount. The implementation must acquire and release references using the rules of the particular C object. Recovering an enclosing address by offset and retrieving a transferred owner from a slot thus require different evidence before either can yield a usable Rust reference.
Which abstractions can this kernel use?
2 min readThe Rust build for Linux 6.8 uses unstable compiler features. The kernel crate enables features such as allocator_api for allocator APIs and coerce_unsized for smart-pointer coercions. This is a property of the kernel build even if the driver you write contains ordinary stable Rust syntax. A normal stable Rust compilation rejects feature gates. Linux 6.8's kernel build uses the RUSTC_BOOTSTRAP environment variable to enable the features it needs with its supported Rust compiler release. A nightly compiler can enable unstable features, but compatibility also depends on the compiler version and the kernel tree's build requirements. Use the version expected by the target tree and check toolchain availability there with make LLVM=1 rustavailable. A successful check reports build prerequisites, while the kernel configuration determines whether Rust support is enabled.
Subsystem coverage varies by tree. In upstream Linux 6.8, kernel::net::phy exposes abstractions for Ethernet PHY drivers. A PHY driver handles the physical Ethernet link through that interface. Writing a network driver that needs other facilities still requires checking those facilities individually. The presence of a PHY wrapper tells you nothing about the availability of a safe wrapper for registering a network interface or operating its packet queues.
For block devices, Linux 6.8 has the C block layer, with no upstream Rust block driver abstraction in that release. For misc devices, the in-tree registration interface is the C misc_register and misc_deregister pair. UART drivers in 6.8 use the C serial core, which includes interfaces such as uart_add_one_port; the release has no upstream safe Rust UART registration abstraction. These are limits of the specified tree. Code from a development or vendor tree may supply extra abstractions and can have different type names, signatures, and initialization rules.
For a proposed driver, start with the operation it needs. Find the Rust module and check that it covers that operation under the target configuration. If only a raw C interface is available, identify the callable functions and the ownership, callback, and cleanup rules a wrapper would have to encode. Some operations rely on C macros or symbols unavailable to modules. They may require kernel-side C support before a Rust driver can call them. Existing C subsystems can remain implemented in C even where a Rust driver has a safe interface to them. For the next lesson, Porting the M5 driver to Rust, this check tells you which device-facing behavior can use the selected tree's Rust APIs and which behavior needs a C interface underneath.
Key takeaways
- 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.
- An embedded-field pointer and an opaque driver-data pointer require different recovery procedures.
Reflect
- Explain to a colleague, in two sentences: trace a character-device open from the device node to the driver's file operations.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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
- Kernel documentationMiscellaneous Devices: registration and open semantics
- Kernel documentationQuick Start: requirements for building Rust in the kernel
- Kernel documentationGeneral Information: Rust bindings and abstractions
- Man pageopen(2): open and possibly create a file
Official documentation first. Links checked when the lesson was published.