
Recall first from Device nodes and the open path
- class_create plus device_create makes devtmpfs create /dev/mychar automatically; udev or mdev then fixes permissions.
- Each registration step has a matching undo label, and the exit function runs the same sequence in reverse order.
- chrdev_open looks the number up in cdev_map and returns -ENXIO for a stale node; fops_get holds a module reference while a file is open, and cdev_del only unregisters, never freeing an embedded cdev.
Faults, compat and failure injection
6 min readThe driver registers, transfers data and has a node, so what remains is the faults and wrong-sized callers production hits. This lesson answers how you harden a driver against faults and wrong-sized callers.
The copy helpers can sleep. If the user page being touched is swapped out, the page-fault handler must wait for it to come back from disk, and that wait sleeps. The helpers are marked so that a debug kernel checks this: with CONFIG_DEBUG_ATOMIC_SLEEP enabled, calling them from an interrupt handler or while holding a spinlock produces a warning, because sleeping there would deadlock. The rule is simple: user copies belong in process context with page faults enabled, never in atomic context. If you must touch user memory from a path that cannot sleep, the kernel provides pagefault_disable and the copy then fails fast with -EFAULT instead of waiting.
For large transfers, copying through a kernel buffer costs a full extra copy. Zero-copy paths avoid it. mmap lets the process map the device memory directly, and get_user_pages pins the process's pages so the kernel can access them without copying. The current get_user_pages takes a start address, a page count, flags such as FOLL_WRITE, and an output array of struct page pointers; it may sleep and must run in process context. For pins that live a long time, the modern variant is pin_user_pages, which marks the pages so the memory-management code can track them correctly. These are the tools behind high-throughput drivers such as video capture; a small sensor driver rarely needs them.
The other production concern is word size. A 64-bit kernel often runs 32-bit applications: a 32-bit ARM userspace on an arm64 board is a common embedded configuration. When such a process calls ioctl, the kernel prefers the the file operation a 64-bit kernel calls for ioctl requests from a 32-bit process, so arguments can be translated method if you provide one; otherwise it falls back to unlocked_ioctl with the raw argument. The danger is that a struct passed by a 32-bit process has 4-byte pointers and longs where the 64-bit kernel expects 8, and different padding.
The clean solution is to design ioctl arguments with fixed-width types (__u32, __u64) and no implicit longs, so the layout is identical in both worlds. Then point both methods at the same function:
static const struct file_operations mychar_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = mychar_ioctl,
.compat_ioctl = mychar_ioctl,
/* ... */
};
If a command must pass a pointer, the kernel offers a helper, compat_ptr_ioctl, that converts the 32-bit pointer argument and forwards to your native handler. If the layouts genuinely differ, you write a real compat handler that translates field by field. The ioctl commands themselves are the subject of the next lesson; the point here is that the compat decision is part of designing the interface, not an afterthought.
Finally, the failure paths. Your -ENOMEM and -EFAULT branches are the ones least likely to run in normal testing, and most likely to be wrong. The kernel can force them to run. With CONFIG_FAULT_INJECTION and CONFIG_FAULT_INJECTION_DEBUG_FS enabled, plus the specific options CONFIG_FAILSLAB and CONFIG_FAULT_INJECTION_USERCOPY, the kernel exposes controllers through debugfs, a debugging filesystem mounted at /sys/kernel/debug/:
mount -t debugfs none /sys/kernel/debug
cd /sys/kernel/debug/fail_usercopy
echo 100 > probability # fail every eligible call
echo 1 > times # ...once, then stop
cat /dev/mychar # exercise the -EFAULT path
fail_usercopy makes copy_to_user and copy_from_user report failure; failslab makes kmalloc return NULL. The knobs include probability (0 to 100), times (how many failures, -1 for unlimited) and task-filter (restrict to a chosen process). Run your test harness with these armed and confirm the driver returns the right error and unwinds cleanly, rather than crashing or leaking.
Going deeperTesting the unwind, not just the happy path
A driver that loads fine but leaks the device number on a failed device_create is broken in a way normal testing never reveals. Arm failslab with a low probability and load and unload the module in a loop; each forced allocation failure exercises one more goto label. Check /proc/devices after each failed load to confirm the number was released, and watch for stale nodes. This is the same discipline as the previous lesson's forced init failure, now applied to every registration step of a real driver.
The common mistakes, with their symptoms:
- open returns -ENXIO. Cause: a stale node whose major no driver registers. Diagnose: compare
ls -l /dev/mycharwith/proc/devices. Fix: remove the stale node, or use automatic creation so it disappears with the driver. - read or write returns -EFAULT on a valid-looking buffer. Cause: the buffer is in kernel space, or the pointer was copied wrong, or a
__useraddress was dereferenced directly. Diagnose: check that you used the copy helpers and that the address came from the method argument, not a kernel allocation. Fix: route every user transfer throughcopy_to_user/copy_from_user. - cat prints nothing, or prints stale data. Cause: read returns 0 too early, or
sizeis never updated on write. Diagnose:stracethe read and check the returned counts against what you wrote. Fix: updatesizewhen a write extends the data, and return 0 only at or pastsize. - A partial write is reported as an error. Cause: returning
-EINVALwhencountexceeds the remaining space instead of clamping. Diagnose: write a buffer larger than the free space and read the return value. Fix: clamp to the space available and return the count accepted. - rmmod refuses with "module in use" after every client exited. Cause: a descriptor is still open somewhere, or a manual module reference was taken and never dropped. Diagnose: read the use count in
lsmod, look for a lingering open descriptor, and check for an unbalancedtry_module_get. Fix: close the descriptor or drop the reference in release; with.ownerset the VFS balances open and release for you. - The two-argument class_create will not compile. Cause: code copied from a pre-6.4 source. Diagnose: read the macro error. Fix: pass only the name.
Try it
1 min readDo the lab for this session: write the mychar driver with a kmalloc buffer and correct read, write and llseek return codes, then add class_create and device_create so /dev/mychar appears automatically. Test it with echo, cat and dd, and build a scripted harness that forces partial reads and end-of-file, verifying the exact byte counts with strace. Finish with the practice pack, which drills the return-value contract, the copy helpers and the registration sequence without repeating the lab steps.
Key takeaways
- User copies may sleep, so they belong in process context with page faults enabled, never in atomic context such as under a spinlock.
- Fixed-width ioctl argument types keep a 32-bit and 64-bit layout identical, so compat_ioctl can point at the same function as unlocked_ioctl.
- fail_usercopy and failslab force the -EFAULT and -ENOMEM paths so the error handling and goto unwinding can be tested instead of only read.
Reflect
- Explain to a colleague, in two sentences: diagnose common character-driver failures and evaluate the compat_ioctl and llseek choices for a product
- Which objective are you least sure about? Re-read that section.
References and further reading
Official documentation first. Links checked when the lesson was published.