From f92af5b9699455c03028c663f0a07e44e8eeb94e Mon Sep 17 00:00:00 2001 From: Edson Brandi Date: Wed, 22 Apr 2026 18:57:42 +0000 Subject: [PATCH] docs: complete initial draft of all content for my FreeBSD Device Drivers: From First Steps to Kernel Mastery book. After 10 months of daily work, the first full draft of the book is now complete. --- content/appendices/appendix-a.md | 1137 +++++- content/appendices/appendix-b.md | 628 ++- content/appendices/appendix-c.md | 470 ++- content/appendices/appendix-d.md | 479 ++- content/appendices/appendix-e.md | 580 ++- content/appendices/appendix-f.md | 315 ++ content/chapters/part1/chapter-01.md | 123 +- content/chapters/part1/chapter-02.md | 93 +- content/chapters/part1/chapter-03.md | 123 +- content/chapters/part1/chapter-04.md | 554 +-- content/chapters/part1/chapter-05.md | 1169 ++---- content/chapters/part1/chapter-06.md | 424 +- content/chapters/part2/chapter-07.md | 5034 ++++++++++++++++++++++- content/chapters/part2/chapter-08.md | 3900 +++++++++++++++++- content/chapters/part2/chapter-09.md | 4013 ++++++++++++++++++- content/chapters/part2/chapter-10.md | 4169 ++++++++++++++++++- content/chapters/part3/chapter-11.md | 4016 ++++++++++++++++++- content/chapters/part3/chapter-12.md | 4009 ++++++++++++++++++- content/chapters/part3/chapter-13.md | 4081 ++++++++++++++++++- content/chapters/part3/chapter-14.md | 3998 ++++++++++++++++++- content/chapters/part3/chapter-15.md | 4130 ++++++++++++++++++- content/chapters/part4/chapter-16.md | 4074 ++++++++++++++++++- content/chapters/part4/chapter-17.md | 4022 ++++++++++++++++++- content/chapters/part4/chapter-18.md | 4118 ++++++++++++++++++- content/chapters/part4/chapter-19.md | 4005 ++++++++++++++++++- content/chapters/part4/chapter-20.md | 4134 ++++++++++++++++++- content/chapters/part4/chapter-21.md | 4029 ++++++++++++++++++- content/chapters/part4/chapter-22.md | 4040 ++++++++++++++++++- content/chapters/part5/chapter-23.md | 4017 ++++++++++++++++++- content/chapters/part5/chapter-24.md | 4003 ++++++++++++++++++- content/chapters/part5/chapter-25.md | 4068 ++++++++++++++++++- content/chapters/part6/chapter-26.md | 4023 ++++++++++++++++++- content/chapters/part6/chapter-27.md | 4066 ++++++++++++++++++- content/chapters/part6/chapter-28.md | 4024 ++++++++++++++++++- content/chapters/part7/chapter-29.md | 4055 ++++++++++++++++++- content/chapters/part7/chapter-30.md | 4049 ++++++++++++++++++- content/chapters/part7/chapter-31.md | 3998 ++++++++++++++++++- content/chapters/part7/chapter-32.md | 4003 ++++++++++++++++++- content/chapters/part7/chapter-33.md | 3996 ++++++++++++++++++- content/chapters/part7/chapter-34.md | 4692 +++++++++++++++++++++- content/chapters/part7/chapter-35.md | 5519 ++++++++++++++++++++++++- content/chapters/part7/chapter-36.md | 5530 +++++++++++++++++++++++++- content/chapters/part7/chapter-37.md | 4303 +++++++++++++++++++- content/chapters/part7/chapter-38.md | 4059 ++++++++++++++++++- 44 files changed, 138773 insertions(+), 1499 deletions(-) create mode 100644 content/appendices/appendix-f.md diff --git a/content/appendices/appendix-a.md b/content/appendices/appendix-a.md index 1b34671..991e216 100644 --- a/content/appendices/appendix-a.md +++ b/content/appendices/appendix-a.md @@ -1,12 +1,1137 @@ --- title: "FreeBSD Kernel API Reference" -description: "Comprehensive reference for FreeBSD kernel APIs, system calls, and data structures used in device driver development." -status: "planned" -estimatedReadTime: 25 -date: "2024-01-15" +description: "A practical, lookup-oriented reference for the FreeBSD kernel APIs, macros, data structures, and manpage families used throughout the book's driver-development chapters." +appendix: "A" +lastUpdated: "2026-04-20" +status: "complete" author: "Edson Brandi" -reviewer: "FreeBSD Community" +reviewer: "TBD" +translator: "TBD" +estimatedReadTime: 45 --- -planned +# Appendix A: FreeBSD Kernel API Reference +## How to Use This Appendix + +This appendix is the companion lookup table for everything the book has taught you to use inside a FreeBSD driver. The main chapters build each API carefully, show it in a working driver, and explain the mental model behind it. This appendix is the short, scannable counterpart you keep open while coding, debugging, or reading someone else's driver. + +It is deliberately written to be a reference and not a tutorial. It does not try to teach any subsystem from scratch. Each entry assumes you have already met the API somewhere in the book, or that you are willing to read the manual page before you use it. What the entry gives you is the vocabulary to navigate: what the API is for, the small set of names that actually matter, the mistakes you are likely to make, where it typically fits in the driver lifecycle, and which chapter teaches it in full. If the entry is doing its job, you can answer four questions in under a minute: + +1. Which API family do I need for the problem in front of me? +2. What is the exact name of the function, macro, or type I want? +3. What caveat should I check before I trust it? +4. Which manual page or chapter should I open next? + +Nothing more is promised. Every detail below was verified against the FreeBSD 14.3 source tree and the corresponding manual pages in `man 9`. Where a distinction is important but deferred to another part of the book, the entry points forward rather than pretending to resolve it here. + +### How the Entries Are Organised + +The appendix groups APIs by the problem they solve, not alphabetically. A driver rarely reaches for a name in isolation. It reaches for a whole family: memory with its flags, a lock with its sleep rules, a callout with its cancellation story. Keeping those families together makes the appendix more useful for real lookup tasks. + +Within each family, every entry follows the same short pattern: + +- **Purpose.** What the API is for, in one or two sentences. +- **Typical use in drivers.** When a driver reaches for it. +- **Key names.** The functions, macros, flags, or types you actually call or declare. +- **Header(s).** Where the declarations live. +- **Caveats.** The handful of mistakes that cause real bugs. +- **Lifecycle phase.** Where in probe, attach, normal operation, or detach the API usually appears. +- **Manual pages.** The `man 9` entries to read next. +- **Where the book teaches this.** Chapter references for full context. + +Keep this pattern in mind when you scan. If you only need the name of a flag, look at **Key names**. If you only need the manual page, look at **Manual pages**. If you have forgotten why the API exists at all, read **Purpose** and stop there. + +### What This Appendix Is Not + +This appendix is not a replacement for `man 9`, not a replacement for the book's teaching chapters, and not a replacement for reading real drivers under `/usr/src/sys/dev/`. It is short on purpose. The canonical reference remains the manual page; the canonical mental model remains the chapter that introduced the API; the canonical truth remains the source tree. This appendix helps you find all three quickly. + +It also does not cover every kernel interface. The kernel is large, and a full reference would repeat material that belongs in Appendix E (FreeBSD Internals and Kernel Reference) or in focused chapters such as Chapter 16 (Accessing Hardware), Chapter 19 (Handling Interrupts), and Chapter 20 (Advanced Interrupt Handling). The goal here is coverage of the APIs that a driver author actually uses in day-to-day work, at the level of detail a driver author actually needs. + +## Reader Guidance + +You can use this appendix in three different ways, and they each call for a different reading strategy. + +If you are **writing new code**, treat it as a checklist. Pick the family that matches your problem, skim the entries, note the key names, and jump to the manual page or the chapter for the details. Time investment: one or two minutes per lookup. + +If you are **debugging**, treat it as a map of assumptions. When a driver misbehaves, the bug is almost always in a caveat that the author overlooked: a mutex held across a sleepable copy, a callout stopped but not drained, a resource freed before the interrupt was torn down. The **Caveats** line of each entry is where those assumptions live. Read them in order and ask whether your driver honours each one. + +If you are **reading an unfamiliar driver**, treat it as a translator. When you see a function or macro you do not recognise, find its family in this appendix, read the **Purpose**, and move on. The full understanding can come later from the chapter or the manual page. The goal during exploration is to keep moving and to form an initial mental model of what the driver is doing. + +A few conventions used throughout: + +- All source paths are shown in book-facing form, `/usr/src/sys/...`, matching the layout on a standard FreeBSD system. +- Manual pages are cited in the usual FreeBSD style: `mtx(9)` means section 9 of the manual. You can read any of them with, for example, `man 9 mtx`. +- When a family has no dedicated manual page, the entry says so and points to the closest available documentation. +- When the book defers a topic to a later chapter or to Appendix E, the entry points forward rather than fabricating detail here. + +With that in mind, we can open the appendix proper. The first family is memory: where drivers get the bytes they need, how they give them back, and which flags control the behaviour along the way. + +## Memory Allocation + +Every driver allocates memory, and every allocation carries rules about when you may block, where the memory is physically located, and how it is returned. The kernel provides three main allocators: `malloc(9)` for general-purpose allocation, `uma(9)` for high-frequency fixed-size objects, and `contigmalloc(9)` for physically contiguous ranges that hardware can address. Below you will find each one at a glance, plus the small vocabulary of flags they share. + +### `malloc(9)` / `free(9)` / `realloc(9)` + +**Purpose.** General-purpose kernel memory allocator. Gives you a byte buffer of any size, tagged by a `malloc_type` so you can account for it later with `vmstat -m`. + +**Typical use in drivers.** Softc allocation, small variable-size buffers, temporary scratch space, anything where a fixed-size zone would be overkill. + +**Key names.** + +- `void *malloc(size_t size, struct malloc_type *type, int flags);` +- `void free(void *addr, struct malloc_type *type);` +- `void *realloc(void *addr, size_t size, struct malloc_type *type, int flags);` +- `MALLOC_DEFINE(M_FOO, "foo", "description for vmstat -m");` +- `MALLOC_DECLARE(M_FOO);` for use in headers. + +**Header.** `/usr/src/sys/sys/malloc.h`. + +**Flags that matter.** + +- `M_WAITOK`: the caller may block until memory is available. The allocation will succeed or the kernel will panic. +- `M_NOWAIT`: the caller must not block. The allocation may return `NULL`. Always check for `NULL` with `M_NOWAIT`. +- `M_ZERO`: zero the returned memory before handing it back. Combine with either wait flag. +- `M_NODUMP`: exclude the allocation from crash dumps. + +**Caveats.** + +- `M_WAITOK` must not be used while holding a spin mutex, in an interrupt filter, or in any context that cannot sleep. +- `M_NOWAIT` callers must check the return value. Failing to handle `NULL` is one of the most common driver crashes in review. +- Never mix allocator families. Memory returned by `malloc(9)` must be freed by `free(9)`; `uma_zfree(9)` and `contigfree(9)` are not interchangeable. +- The `struct malloc_type` pointer must match between `malloc` and the corresponding `free`. + +**Lifecycle phase.** Most commonly in `attach` (softc, buffers) and `detach` (release). Smaller allocations can appear in normal I/O paths as long as the context permits the chosen flag. + +**Manual page.** `malloc(9)`. + +**Where the book teaches this.** Introduced in Chapter 5 alongside kernel-specific C idioms; used in Chapter 7 when your first driver allocates its softc; revisited in Chapter 10 when I/O buffers become real, and again in Chapter 11 when allocation flags must obey locking rules. + +### `uma(9)` Zones + +**Purpose.** Fixed-size object cache, highly optimised for allocations that are frequent, uniform, and performance-sensitive. Reuses objects instead of repeatedly hitting the general allocator. + +**Typical use in drivers.** Network mbuf-like structures, per-packet state, per-request descriptors, anything where you allocate and free millions of identical small objects per second. + +**Key names.** + +- `uma_zone_t uma_zcreate(const char *name, size_t size, uma_ctor, uma_dtor, uma_init, uma_fini, int align, uint32_t flags);` +- `void uma_zdestroy(uma_zone_t zone);` +- `void *uma_zalloc(uma_zone_t zone, int flags);` +- `void uma_zfree(uma_zone_t zone, void *item);` + +**Header.** `/usr/src/sys/vm/uma.h`. + +**Flags.** + +- `M_WAITOK`, `M_NOWAIT`, `M_ZERO` on allocation, identical in meaning to `malloc(9)`. +- Creation-time flags such as `UMA_ZONE_ZINIT`, `UMA_ZONE_NOFREE`, `UMA_ZONE_CONTIG`, and alignment hints (`UMA_ALIGN_CACHE`, `UMA_ALIGN_PTR`, and so on) tune behaviour for specific workloads. + +**Caveats.** + +- Zones must be created before they can be used and must be destroyed before the module unloads. Forgetting `uma_zdestroy` in `detach` leaks the entire zone. +- Constructors and destructors run on allocation and free respectively, not on zone creation and destruction; use the `init` and `fini` callbacks for once-per-slab work. +- A zone is expensive to create. Create one per object type per module, not per instance. +- There is no dedicated `uma(9)` manual page. The authoritative reference is the header and the existing users under `/usr/src/sys/`. + +**Lifecycle phase.** `uma_zcreate` in module load or early attach; `uma_zalloc` and `uma_zfree` in I/O paths; `uma_zdestroy` in module unload. + +**Manual page.** None dedicated. Read `/usr/src/sys/vm/uma.h` and look at `/usr/src/sys/kern/kern_mbuf.c` and `/usr/src/sys/net/netisr.c` for realistic use. + +**Where the book teaches this.** Mentioned briefly in Chapter 7 as an alternative to `malloc(9)`; revisited when high-rate drivers need it in Chapter 28 (networking) and Chapter 33 (performance tuning). + +### `contigmalloc(9)` / `contigfree(9)` + +**Purpose.** Allocate a physically contiguous range of memory within a specified address window. Required when hardware must DMA into memory without an IOMMU and therefore needs contiguous physical pages. + +**Typical use in drivers.** DMA buffers for devices that cannot scatter-gather, and only after confirming that `bus_dma(9)` is not a better fit. + +**Key names.** + +- `void *contigmalloc(unsigned long size, struct malloc_type *type, int flags, vm_paddr_t low, vm_paddr_t high, unsigned long alignment, vm_paddr_t boundary);` +- `void contigfree(void *addr, unsigned long size, struct malloc_type *type);` + +**Header.** `/usr/src/sys/sys/malloc.h`. + +**Caveats.** + +- Fragmentation after boot makes large contiguous allocations fail. Do not assume success. +- For almost all modern hardware, prefer the `bus_dma(9)` framework. It handles tags, maps, bouncing, and alignment in a portable way. +- `contigmalloc` allocations are a scarce system resource; free them as soon as possible. + +**Lifecycle phase.** Typically in `attach`; freed in `detach`. + +**Manual page.** `contigmalloc(9)`. + +**Where the book teaches this.** Mentioned alongside `bus_dma(9)` in Chapter 21 when DMA first becomes a real concern. + +### Allocation Flag Cheat Sheet + +| Flag | Meaning | +| :----------- | :----------------------------------------------------- | +| `M_WAITOK` | Caller may block until memory is available. | +| `M_NOWAIT` | Caller must not block; returns `NULL` on failure. | +| `M_ZERO` | Zero the allocation before returning. | +| `M_NODUMP` | Exclude the allocation from crash dumps. | + +Use `M_WAITOK` only where sleeping is permitted. When in doubt, the safe answer is `M_NOWAIT` plus a `NULL` check. + +## Synchronisation Primitives + +If memory is the raw material of a driver, synchronisation is the discipline that prevents two execution contexts from corrupting it at the same time. FreeBSD gives you a small, well-designed toolkit. The names below are the ones you will meet most often. Full teaching lives in Chapters 11, 12, and 15, with interrupt-context nuances in Chapters 19 and 20; this appendix collects the vocabulary. + +### `mtx(9)`: Mutexes + +**Purpose.** The default kernel mutual-exclusion primitive. A thread acquires the lock, enters the critical section, and releases the lock. + +**Typical use in drivers.** Protecting softc fields, circular buffers, reference counts, and any shared state whose critical section is short and does not sleep. + +**Key names.** + +- `void mtx_init(struct mtx *m, const char *name, const char *type, int opts);` +- `void mtx_destroy(struct mtx *m);` +- `mtx_lock(m)`, `mtx_unlock(m)`, `mtx_trylock(m)`. +- `mtx_assert(m, MA_OWNED | MA_NOTOWNED | MA_RECURSED | MA_NOTRECURSED);` for invariants. +- Sleep-on-mutex helpers: `msleep(9)` and `mtx_sleep(9)`. + +**Header.** `/usr/src/sys/sys/mutex.h`. + +**Options.** + +- `MTX_DEF`: the default sleepable-on-contention mutex. Use this for almost everything. +- `MTX_SPIN`: pure spinlock. Required for interrupt-filter context and other places where blocking is impossible. Rules are stricter. +- `MTX_RECURSE`: allow the same thread to acquire the lock multiple times. Use with caution; it often hides design mistakes. +- `MTX_NEW`: force `mtx_init` to treat the lock as newly created. Useful with `WITNESS`. + +**Caveats.** + +- Never sleep while holding an `MTX_DEF` or `MTX_SPIN` mutex. `uiomove(9)`, `copyin(9)`, `copyout(9)`, `malloc(9, M_WAITOK)`, and most bus primitives can sleep. Audit carefully. +- Always pair `mtx_init` with `mtx_destroy`. Forgetting the destroy leaks internal state and annoys `WITNESS`. +- Lock order matters. Once the kernel has seen you acquire lock A before lock B, it will warn if you ever reverse the pair. Plan your lock hierarchy in advance. +- `MTX_SPIN` disables preemption; hold it for as short a time as possible. + +**Lifecycle phase.** `mtx_init` in `attach`; `mtx_destroy` in `detach`. Lock and unlock operations everywhere in between. + +**Manual pages.** `mutex(9)`, `mtx_pool(9)`, `msleep(9)`. + +**Where the book teaches this.** First treatment in Chapter 11, deepened in Chapter 12 with lock-order and `WITNESS` discipline, and revisited in Chapter 19 for interrupt-safe variants (`MTX_SPIN`). + +### `sx(9)`: Sleepable Shared-Exclusive Locks + +**Purpose.** A reader-writer lock where either the reader or the writer may block. Use when multiple readers are common, writers are rare, and the critical section may sleep. + +**Typical use in drivers.** Configuration state read by many paths and modified infrequently. Not for fast-path data. + +**Key names.** + +- `void sx_init(struct sx *sx, const char *desc);` +- `void sx_destroy(struct sx *sx);` +- `sx_slock(sx)`, `sx_sunlock(sx)` for shared access. +- `sx_xlock(sx)`, `sx_xunlock(sx)` for exclusive access. +- `sx_try_slock`, `sx_try_xlock`, `sx_upgrade`, `sx_downgrade`. +- `sx_assert(sx, SA_SLOCKED | SA_XLOCKED | SA_LOCKED | SA_UNLOCKED);` + +**Header.** `/usr/src/sys/sys/sx.h`. + +**Caveats.** + +- `sx` allows sleeping inside the critical section, unlike `mtx`. That flexibility is the whole point; make sure you actually need it. +- `sx` locks are more expensive than mutexes. Do not use them as a default. +- Avoid mixing `sx` and `mtx` in the same lock order without thinking through the implications. + +**Lifecycle phase.** `sx_init` in `attach`; `sx_destroy` in `detach`. + +**Manual page.** `sx(9)`. + +**Where the book teaches this.** Chapter 12. + +### `rmlock(9)`: Read-Mostly Locks + +**Purpose.** Extremely fast reader path, slower writer path. Readers do not contend with each other. Designed for data that is read on every operation but written only rarely. + +**Typical use in drivers.** Routing-like tables, configuration state used in fast paths, structures where writer overhead is acceptable because writes are rare. + +**Key names.** + +- `void rm_init(struct rmlock *rm, const char *name);` +- `void rm_destroy(struct rmlock *rm);` +- `rm_rlock(rm, tracker)`, `rm_runlock(rm, tracker)`. +- `rm_wlock(rm)`, `rm_wunlock(rm)`. + +**Header.** `/usr/src/sys/sys/rmlock.h`. + +**Caveats.** + +- Each reader needs its own `struct rm_priotracker`, typically on the stack. Do not share one. +- Readers may not sleep unless the lock was initialised with `RM_SLEEPABLE`. +- The writer path is heavy; if writes are frequent, `sx` or `mtx` is a better choice. + +**Lifecycle phase.** `rm_init` in `attach`; `rm_destroy` in `detach`. + +**Manual page.** `rmlock(9)`. + +**Where the book teaches this.** Introduced briefly in Chapter 12 and used in later chapters where read-mostly patterns arise. + +### `cv(9)` / `condvar(9)`: Condition Variables + +**Purpose.** A named wait channel. One or more threads sleep until another thread signals that the condition they are waiting for has become true. + +**Typical use in drivers.** Waiting for a buffer to drain, for hardware to finish a command, or for a specific state transition. Use instead of bare `wakeup(9)` channels when you want the wait reason to be explicit. + +**Key names.** + +- `void cv_init(struct cv *cv, const char *desc);` +- `void cv_destroy(struct cv *cv);` +- `cv_wait(cv, mtx)`, `cv_wait_sig(cv, mtx)`, `cv_wait_unlock(cv, mtx)`. +- `cv_timedwait(cv, mtx, timo)`, `cv_timedwait_sig(cv, mtx, timo)`. +- `cv_signal(cv)`, `cv_broadcast(cv)`, `cv_broadcastpri(cv, pri)`. + +**Header.** `/usr/src/sys/sys/condvar.h`. + +**Caveats.** + +- The mutex passed to `cv_wait` must be held by the caller; `cv_wait` drops it while sleeping and reacquires it on return. +- Always recheck the predicate after `cv_wait` returns. Spurious wakeups and signals are possible. +- `cv_signal` wakes one waiter; `cv_broadcast` wakes all. Pick based on the design, not on instinct. + +**Lifecycle phase.** `cv_init` in `attach`; `cv_destroy` in `detach`. + +**Manual page.** `condvar(9)`. + +**Where the book teaches this.** Chapter 12, with interruptible and timed waits revisited in Chapter 15. + +### `sema(9)`: Counting Semaphores + +**Purpose.** A counting semaphore with `wait` and `post` operations. Less common than mutexes or condition variables. + +**Typical use in drivers.** Producer-consumer patterns where a counted resource must be tracked, such as a fixed pool of command slots. + +**Key names.** + +- `void sema_init(struct sema *sema, int value, const char *desc);` +- `void sema_destroy(struct sema *sema);` +- `sema_wait(sema)`, `sema_trywait(sema)`, `sema_timedwait(sema, timo)`. +- `sema_post(sema)`. + +**Header.** `/usr/src/sys/sys/sema.h`. + +**Caveats.** + +- Semaphores are appropriate for counting. For one-thread-in-critical-section patterns, use `mtx` instead. +- `sema_wait` may return early on signal; check return values. + +**Manual page.** `sema(9)`. + +**Where the book teaches this.** Chapter 15, as part of the advanced synchronisation toolkit. + +### `atomic(9)`: Atomic Operations + +**Purpose.** Single-word, interruption-free read-modify-write operations. Faster than any lock, and strictly limited in expressiveness. + +**Typical use in drivers.** Counters, flags, and compare-and-swap patterns where the critical section fits in one integer. + +**Key names.** + +- `atomic_add_int`, `atomic_subtract_int`, `atomic_set_int`, `atomic_clear_int`. +- `atomic_load_int`, `atomic_store_int`, with acquire and release variants. +- `atomic_cmpset_int`, `atomic_fcmpset_int` for compare-and-swap. +- Width variants: `_8`, `_16`, `_32`, `_64`, and pointer-sized `_ptr`. +- Barrier helpers: `atomic_thread_fence_acq()`, `atomic_thread_fence_rel()`, `atomic_thread_fence_acq_rel()`. + +**Header.** `/usr/src/sys/sys/atomic_common.h` plus `machine/atomic.h` for architecture-specific pieces. + +**Caveats.** + +- Atomic operations give you one word of mutual exclusion. Any invariant that spans two fields still needs a lock. +- Memory ordering matters. The plain operations are relaxed; use the `_acq`, `_rel`, and `_acq_rel` variants when one access must become visible before or after another. +- For per-CPU counters that are read rarely, `counter(9)` scales better. + +**Lifecycle phase.** Any. Cheap enough to use in interrupt filters. + +**Manual page.** `atomic(9)`. + +**Where the book teaches this.** Chapter 11, with `counter(9)` introduced alongside for per-CPU patterns. + +### `epoch(9)`: Read-Mostly Lock-Free Sections + +**Purpose.** Lightweight reader protection for data structures where readers vastly outnumber writers and latency must be minimal. Writers wait for all current readers to leave before freeing memory. + +**Typical use in drivers.** Network stack fast paths, read-mostly lookup tables in high-performance drivers. Not a general-purpose primitive. + +**Key names.** + +- `epoch_t epoch_alloc(const char *name, int flags);` +- `void epoch_free(epoch_t epoch);` +- `epoch_enter(epoch)`, `epoch_exit(epoch)`. +- `epoch_wait(epoch)` for writers to block until readers drain. +- `NET_EPOCH_ENTER(et)` and `NET_EPOCH_EXIT(et)` wrappers for the network stack. + +**Header.** `/usr/src/sys/sys/epoch.h`. + +**Caveats.** + +- Readers must not block, sleep, or call any function that does, while inside an epoch section. +- Freeing protected memory must be deferred until `epoch_wait` returns. +- Epoch sections are a tool of last resort, not a default primitive. Choose locks first. + +**Manual page.** `epoch(9)`. + +**Where the book teaches this.** Introduced briefly in Chapter 12; used in depth only where real drivers in later chapters require it. + +### Lock Decision Cheat Sheet + +| You want to... | Reach for | +| :---------------------------------------------------- | :------------------------- | +| Protect a short, non-sleeping critical section | `mtx(9)` with `MTX_DEF` | +| Protect state in an interrupt filter | `mtx(9)` with `MTX_SPIN` | +| Allow many readers, rare writers, may sleep | `sx(9)` | +| Allow many readers, rare writers, no sleep in readers | `rmlock(9)` | +| Sleep until a named condition holds | `cv(9)` with a mutex | +| Increment or compare-and-swap a single word | `atomic(9)` | +| Lock-free reader path for read-mostly data | `epoch(9)` | + +When a row does not obviously match the problem, the full discussion in Chapters 11, 12, and 15 is the place to resolve it. + +## Deferred Execution and Timers + +Drivers often need to run work later, periodically, or from a context that can sleep. The kernel gives you three tools for that: `callout(9)` for one-shot and periodic timers, `taskqueue(9)` for deferred work that may sleep, and `kthread(9)` or `kproc(9)` for long-running background threads. They overlap in some situations; the rule of thumb is that callouts run from the timer interrupt context (fast, no sleeping), taskqueues run in a worker thread (can sleep, can grab sleepable locks), and kthreads are whole threads you own. + +### `callout(9)`: Kernel Timers + +**Purpose.** Schedule a function to run after a time delay. The callback runs in soft-interrupt context by default and must not sleep. + +**Typical use in drivers.** Watchdog timers, polling intervals, retry delays, idle timeouts. + +**Key names.** + +- `void callout_init(struct callout *c, int mpsafe);` plus `callout_init_mtx` and `callout_init_rm`. +- `int callout_reset(struct callout *c, int ticks, void (*func)(void *), void *arg);` +- `int callout_stop(struct callout *c);` +- `int callout_drain(struct callout *c);` +- `int callout_pending(struct callout *c);`, `callout_active(struct callout *c);` + +**Header.** `/usr/src/sys/sys/callout.h`. + +**Caveats.** + +- `callout_stop` does not wait for a running callback. Use `callout_drain` before freeing the softc in `detach`. +- A callout can fire even after you think you cancelled it if the timer was already dispatched. Guard the callback with a flag or use the `_mtx` and `_rm` variants to integrate cancellation with your lock. +- Running tickless kernels means ticks are abstract. Convert real time with `hz` or use `callout_reset_sbt` for subsecond precision. + +**Lifecycle phase.** `callout_init` in `attach`; `callout_drain` in `detach`; `callout_reset` whenever the next firing time needs to be set. + +**Manual page.** `callout(9)`. + +**Where the book teaches this.** Chapter 13. + +### `taskqueue(9)`: Deferred Work in a Worker Thread + +**Purpose.** Hand off work from a context that cannot sleep, or that should not hold a lock for long, to a worker thread. Tasks queued on the same taskqueue run in order. + +**Typical use in drivers.** Interrupt post-processing, hardware command completion handlers, reset and recovery paths that may need to allocate memory or grab sleepable locks. + +**Key names.** + +- `struct taskqueue *taskqueue_create(const char *name, int mflags, taskqueue_enqueue_fn, void *context);` +- `void taskqueue_free(struct taskqueue *queue);` +- `TASK_INIT(struct task *t, int priority, task_fn_t *func, void *context);` +- `int taskqueue_enqueue(struct taskqueue *queue, struct task *task);` +- `void taskqueue_drain(struct taskqueue *queue, struct task *task);` +- `void taskqueue_drain_all(struct taskqueue *queue);` +- Global queues such as `taskqueue_thread`, `taskqueue_swi`, `taskqueue_fast`. + +**Header.** `/usr/src/sys/sys/taskqueue.h`. + +**Caveats.** + +- Enqueuing the same task twice before it runs is a no-op by design. If you need a new request every time, that is fine; if you expect two runs, use distinct tasks. +- `taskqueue_drain` waits for the task to finish; call it before freeing anything the task uses. +- Private taskqueues are cheap but not free. Reuse global taskqueues (`taskqueue_thread`, `taskqueue_fast`) unless you have a reason to own one. + +**Lifecycle phase.** `taskqueue_create` (if private) and `TASK_INIT` in `attach`; `taskqueue_drain` and `taskqueue_free` in `detach`. + +**Manual page.** `taskqueue(9)`. + +**Where the book teaches this.** Chapter 14. + +### `kthread(9)` and `kproc(9)`: Kernel Threads and Processes + +**Purpose.** Create a dedicated kernel thread or process that runs your function. Useful when the workload is long-lived, needs its own scheduling policy, or needs to be explicitly addressable. + +**Typical use in drivers.** Rare. Most driver work is served better by a taskqueue or a callout. Kernel threads appear in subsystems with genuine long-running loops, such as housekeeping daemons. + +**Key names.** + +- `int kthread_add(void (*func)(void *), void *arg, struct proc *p, struct thread **td, int flags, int pages, const char *fmt, ...);` +- `int kproc_create(void (*func)(void *), void *arg, struct proc **procp, int flags, int pages, const char *fmt, ...);` +- `void kthread_exit(void);` +- `kproc_exit`, `kproc_suspend_check`. + +**Header.** `/usr/src/sys/sys/kthread.h`. + +**Caveats.** + +- Creating a thread is heavier than queuing a task. Prefer `taskqueue(9)` unless the workload is genuinely long-running. +- Cleanly shutting down a kthread requires cooperation: set a stop flag, wake the thread, and wait for it to exit. Forgetting any step leaks the thread across module unloads. +- A kthread must exit by calling `kthread_exit`, not by returning. + +**Manual pages.** `kthread(9)`, `kproc(9)`. + +**Where the book teaches this.** Mentioned in Chapter 14 as the heavier alternative to taskqueues. + +### Deferred Work Decision Cheat Sheet + +| You need to... | Reach for | +| :--------------------------------------------------------------- | :---------------- | +| Fire a function after a delay, briefly, no sleeping | `callout(9)` | +| Defer work that may sleep or grab sleepable locks | `taskqueue(9)` | +| Run a persistent background loop | `kthread(9)` | +| Convert short periodic polling into real interrupts | See Chapter 19 | + +## Bus and Resource Management + +The bus layer is where a driver meets hardware. Newbus introduces the driver to the kernel; `rman(9)` hands out the resources that represent MMIO regions, I/O ports, and interrupts; `bus_space(9)` accesses them portably; `bus_dma(9)` lets devices DMA safely. + +### Newbus: `DRIVER_MODULE`, `DEVMETHOD`, and Related Macros + +**Purpose.** Register a driver with the kernel, bind it to a device class, declare the entry points the kernel should call, and publish version and dependency information. + +**Typical use in drivers.** Every kernel module that owns a device. This is the scaffolding that turns a pile of C code into something `kldload` can attach to hardware. + +**Key names.** + +- `DRIVER_MODULE(name, bus, driver, devclass, evh, evharg);` +- `MODULE_VERSION(name, version);` +- `MODULE_DEPEND(name, busname, vmin, vpref, vmax);` +- `DEVMETHOD(method, function)` and `DEVMETHOD_END` for the method table. +- `device_method_t` entries such as `device_probe`, `device_attach`, `device_detach`, `device_shutdown`, `device_suspend`, `device_resume`. +- Types: `device_t`, `devclass_t`, `driver_t`. + +**Header.** `/usr/src/sys/sys/module.h` and `/usr/src/sys/sys/bus.h`. + +**Caveats.** + +- `DRIVER_MODULE` expands into a module event handler; do not declare your own `module_event_t` table by hand unless you know exactly why. +- `MODULE_DEPEND` is how you make the loader bring in your prerequisites. Forgetting it produces ugly symbol-resolution failures at load time. +- `DEVMETHOD_END` terminates the method table. Without it the kernel will walk past the end. +- `device_t` is opaque; use accessors such as `device_get_softc`, `device_get_parent`, `device_get_name`, and `device_printf`. + +**Lifecycle phase.** Declaration only. The macros expand into module-init and module-fini glue that is run on `kldload` and `kldunload`. + +**Manual pages.** `DRIVER_MODULE(9)`, `MODULE_VERSION(9)`, `MODULE_DEPEND(9)`, `module(9)`, `DEVICE_PROBE(9)`, `DEVICE_ATTACH(9)`, `DEVICE_DETACH(9)`. + +**Where the book teaches this.** Full treatment in Chapter 7, with the anatomy first sketched in Chapter 6. + +### `devclass(9)` and Device Accessors + +**Purpose.** A `devclass_t` groups instances of the same driver so the kernel can find them, number them, and iterate over them. In drivers, you mostly use the accessors, not the devclass directly. + +**Key names.** + +- `device_t device_get_parent(device_t dev);` +- `void *device_get_softc(device_t dev);` +- `int device_get_unit(device_t dev);` +- `const char *device_get_nameunit(device_t dev);` +- `int device_printf(device_t dev, const char *fmt, ...);` +- `devclass_find`, `devclass_get_device`, `devclass_get_devices`, `devclass_get_count` when you truly need to walk a class. + +**Header.** `/usr/src/sys/sys/bus.h`. + +**Caveats.** + +- `device_get_softc` assumes the softc was registered through the driver structure. Rolling your own `device_t`-to-state mapping is almost always wrong. +- Direct devclass manipulation is rare in drivers. If you find yourself reaching for it, check whether the question belongs in a bus-level interface instead. + +**Manual pages.** `devclass(9)`, `device(9)`, `device_get_softc(9)`, `device_printf(9)`. + +**Where the book teaches this.** Chapter 6 and Chapter 7. + +### `rman(9)`: Resource Manager + +**Purpose.** A uniform view over MMIO regions, I/O ports, interrupt numbers, and DMA channels. Your driver asks for resources by type and RID and gets back a `struct resource *` with useful accessors. + +**Key names.** + +- `struct resource *bus_alloc_resource(device_t dev, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags);` +- `struct resource *bus_alloc_resource_any(device_t dev, int type, int *rid, u_int flags);` +- `int bus_release_resource(device_t dev, int type, int rid, struct resource *r);` +- `int bus_activate_resource(device_t dev, int type, int rid, struct resource *r);` +- `int bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r);` +- `rman_res_t rman_get_start(struct resource *r);`, `rman_get_end`, `rman_get_size`. +- `bus_space_tag_t rman_get_bustag(struct resource *r);`, `rman_get_bushandle`. +- Resource types: `SYS_RES_MEMORY`, `SYS_RES_IOPORT`, `SYS_RES_IRQ`, `SYS_RES_DRQ`. +- Flags: `RF_ACTIVE`, `RF_SHAREABLE`. + +**Header.** `/usr/src/sys/sys/rman.h`. + +**Caveats.** + +- The `rid` parameter is a pointer and may be rewritten by the allocator. Pass the address of a real variable. +- Release every allocated resource in `detach` in reverse order of allocation. Leaking a resource almost always corrupts the next attach. +- `RF_ACTIVE` is the common case. Do not forget it, or you will get a handle that cannot be used with `bus_space(9)`. +- Always check the return value. A failed allocation is common on hardware with quirks. + +**Lifecycle phase.** Allocation in `attach`; release in `detach`. If the driver has exotic needs, `bus_activate_resource` and `bus_deactivate_resource` can manage activation separately. + +**Manual pages.** `rman(9)`, `bus_alloc_resource(9)`, `bus_release_resource(9)`, `bus_activate_resource(9)`. + +**Where the book teaches this.** Chapter 16. + +### `bus_space(9)`: Portable Register Access + +**Purpose.** Read and write device registers through a `(tag, handle, offset)` triple that hides whether the underlying access is memory-mapped, port-based, big-endian, little-endian, or indexed. + +**Typical use in drivers.** Every MMIO or I/O port access. Do not dereference `rman_get_virtual` yourself; use `bus_space`. + +**Key names.** + +- Types: `bus_space_tag_t`, `bus_space_handle_t`. +- Reads: `bus_space_read_1(tag, handle, offset)`, `_2`, `_4`, `_8`. +- Writes: `bus_space_write_1(tag, handle, offset, value)`, `_2`, `_4`, `_8`. +- Multi-register helpers: `bus_space_read_multi_N`, `bus_space_write_multi_N`, `bus_space_read_region_N`, `bus_space_write_region_N`. +- Barriers: `bus_space_barrier(tag, handle, offset, length, flags)` with `BUS_SPACE_BARRIER_READ` and `BUS_SPACE_BARRIER_WRITE`. + +**Header.** `/usr/src/sys/sys/bus.h`, with machine-specific details in `machine/bus.h`. + +**Caveats.** + +- Never touch device registers through a raw pointer. Portability and debugging both depend on `bus_space`. +- Barriers are not automatic. When two writes must occur in order, insert `bus_space_barrier` between them. +- The width used in `bus_space_read_N` or `bus_space_write_N` must match the register's natural size. Mismatches cause silent corruption on some architectures. + +**Lifecycle phase.** Any time the driver talks to the device. + +**Manual page.** `bus_space(9)`. + +**Where the book teaches this.** Chapter 16. + +### `bus_dma(9)`: Portable DMA + +**Purpose.** Describe DMA constraints with a tag, load a buffer through a map, and let the framework handle alignment, bouncing, and coherency. Required for any serious device that moves data. + +**Key names.** + +- `int bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment, bus_addr_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr, bus_dma_filter_t *filtfunc, void *filtfuncarg, bus_size_t maxsize, int nsegments, bus_size_t maxsegsz, int flags, bus_dma_lock_t *lockfunc, void *lockfuncarg, bus_dma_tag_t *dmat);` +- `int bus_dma_tag_destroy(bus_dma_tag_t dmat);` +- `int bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp);` +- `int bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map);` +- `int bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf, bus_size_t buflen, bus_dmamap_callback_t *callback, void *arg, int flags);` +- `void bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map);` +- `void bus_dmamap_sync(bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op);` +- `int bus_dmamem_alloc(bus_dma_tag_t dmat, void **vaddr, int flags, bus_dmamap_t *mapp);` +- `void bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map);` +- Flags: `BUS_DMA_WAITOK`, `BUS_DMA_NOWAIT`, `BUS_DMA_ALLOCNOW`, `BUS_DMA_COHERENT`, `BUS_DMA_ZERO`. +- Sync operations: `BUS_DMASYNC_PREREAD`, `BUS_DMASYNC_POSTREAD`, `BUS_DMASYNC_PREWRITE`, `BUS_DMASYNC_POSTWRITE`. + +**Header.** `/usr/src/sys/sys/bus_dma.h`. + +**Caveats.** + +- Tags form a tree. Child tags inherit parent constraints; create them in the right order. +- `bus_dmamap_load` may complete asynchronously. Always use the callback, even for synchronous buffers. +- `bus_dmamap_sync` is not decoration. Without the right sync direction, caches and device memory will disagree. +- On platforms with IOMMUs the framework does the right thing. Do not skip it just because your development hardware is coherent. + +**Lifecycle phase.** Tag creation and mapping setup in `attach`; load and sync in I/O paths; unload and destroy in `detach`. + +**Manual page.** `bus_dma(9)`. + +**Where the book teaches this.** Chapter 21. + +### Interrupt Setup + +**Purpose.** Attach a filter or handler to an IRQ resource so the kernel can deliver interrupts to the driver. + +**Key names.** + +- `int bus_setup_intr(device_t dev, struct resource *r, int flags, driver_filter_t *filter, driver_intr_t *handler, void *arg, void **cookiep);` +- `int bus_teardown_intr(device_t dev, struct resource *r, void *cookie);` +- Flags: `INTR_TYPE_NET`, `INTR_TYPE_BIO`, `INTR_TYPE_TTY`, `INTR_TYPE_MISC`, `INTR_MPSAFE`, `INTR_EXCL`. + +**Caveats.** + +- Provide a filter when the fast-path decision is cheap and the driver can honour filter-context restrictions (no sleeping, no sleepable locks). Provide a handler when the work needs a thread. +- `INTR_MPSAFE` is mandatory for new drivers. Without it, the kernel serialises the handler on the Giant lock, which is almost always wrong. +- Tear down before freeing the resource. The order is: `bus_teardown_intr`, then `bus_release_resource`. + +**Lifecycle phase.** `bus_setup_intr` at the end of `attach`, after the rest of the softc is ready; `bus_teardown_intr` at the start of `detach`, before any resource is released. + +**Manual page.** `BUS_SETUP_INTR(9)`, `bus_alloc_resource(9)` for the resource side. + +**Where the book teaches this.** Chapter 19, with advanced patterns in Chapter 20. + +## Device Nodes and Character-Device I/O + +Once hardware is bound, drivers most often expose themselves to userland through a device node in `/dev/`. The APIs below build and tear down those nodes, and the associated switch table declares how the kernel should dispatch `read`, `write`, `ioctl`, and `poll`. + +### `make_dev_s(9)` and `destroy_dev(9)` + +**Purpose.** Create a new device node under `/dev/`, connected to a `cdevsw` that holds the function pointers the kernel will call. + +**Key names.** + +- `int make_dev_s(struct make_dev_args *args, struct cdev **cdev, const char *fmt, ...);` +- `void destroy_dev(struct cdev *cdev);` +- Fields in `struct make_dev_args`: `mda_si_drv1`, `mda_devsw`, `mda_uid`, `mda_gid`, `mda_mode`, `mda_flags`, `mda_unit`. +- Legacy helper `make_dev(struct cdevsw *, int unit, uid_t, gid_t, int mode, const char *fmt, ...)` still exists but `make_dev_s` is preferred in new code. + +**Header.** `/usr/src/sys/sys/conf.h`. + +**Caveats.** + +- Always use `make_dev_s`. The older `make_dev` swallows errors and does not let you set all the arguments. +- Set `mda_si_drv1` to the softc so the cdev carries a pointer back to driver state without a separate lookup. +- `destroy_dev` waits for all active threads to leave the cdev before returning, making it safe to free the softc afterwards. + +**Lifecycle phase.** `make_dev_s` at the end of `attach`; `destroy_dev` at the start of `detach`, before any backing state is torn down. + +**Manual page.** `make_dev(9)`. + +**Where the book teaches this.** Chapter 8. + +### `cdevsw`: Character-Device Switch Table + +**Purpose.** Declare the entry points the kernel should call when a process opens, reads, writes, or otherwise interacts with the device node. + +**Key names.** + +- `struct cdevsw` fields: `d_version`, `d_flags`, `d_name`, `d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl`, `d_poll`, `d_kqfilter`, `d_mmap`, `d_mmap_single`. +- `d_version` must be `D_VERSION`. +- Common flags: `D_NEEDGIANT` (legacy), `D_TRACKCLOSE`, `D_MEM`. + +**Header.** `/usr/src/sys/sys/conf.h`. + +**Caveats.** + +- Always set `d_version = D_VERSION`. The kernel refuses to attach a switch table with a missing or stale version. +- `d_flags` default of zero is fine for modern MPSAFE drivers. Do not add `D_NEEDGIANT` unless you genuinely need it. +- Unused entries can be left as `NULL`; the kernel substitutes defaults. Do not point them at stubs that do nothing. + +**Lifecycle phase.** Declared statically at module scope. Referenced by `struct make_dev_args`. + +**Manual page.** `make_dev(9)` covers the structure in the context of `make_dev_s`. + +**Where the book teaches this.** Chapter 8. + +### `ioctl(9)` Dispatch + +**Purpose.** Provide out-of-band commands to a device, addressed by a numeric command and an argument buffer. + +**Key names.** + +- Entry point: `d_ioctl_t` with signature `int (*)(struct cdev *, u_long cmd, caddr_t data, int fflag, struct thread *td);` +- Command encoding macros: `_IO`, `_IOR`, `_IOW`, `_IOWR`. +- Copy helpers: `copyin(9)` and `copyout(9)` for pointer-carrying ioctls. + +**Caveats.** + +- Use `_IOR`, `_IOW`, or `_IOWR` to declare commands. They encode size and direction, which matters for cross-architecture compatibility. +- Validate command arguments before acting on them. An ioctl is a trust boundary. +- Never dereference a user pointer directly. Use `copyin(9)` and `copyout(9)`. + +**Lifecycle phase.** Normal operation. + +**Manual page.** `ioctl(9)` (conceptual); the entry point is documented alongside `cdevsw` in `make_dev(9)`. + +**Where the book teaches this.** Chapter 24 (Section 3), with further patterns in Chapter 25. + +### `devfs_set_cdevpriv(9)`: Per-Open State + +**Purpose.** Attach a driver-private pointer to an open file descriptor. The pointer is freed by a callback when the last close occurs. + +**Key names.** + +- `int devfs_set_cdevpriv(void *priv, d_priv_dtor_t *dtor);` +- `int devfs_get_cdevpriv(void **datap);` +- `void devfs_clear_cdevpriv(void);` + +**Header.** `/usr/src/sys/sys/conf.h`. + +**Caveats.** + +- Per-open state is the right tool for per-descriptor settings, cursors, or pending transactions. Do not store per-open state in the softc. +- The destructor runs in the context of the last close. Keep it short and non-blocking. + +**Manual page.** `devfs_set_cdevpriv(9)`. + +**Where the book teaches this.** Chapter 8. + +## Process and User-Space Interaction + +Userland cannot be trusted with kernel addresses, and the kernel cannot be trusted to follow userland pointers without care. The APIs below cross the trust boundary safely. + +### `copyin(9)`, `copyout(9)`, `copyinstr(9)` + +**Purpose.** Move bytes between kernel and user address spaces with address validation. These are the only safe way to touch a user pointer from kernel code. + +**Key names.** + +- `int copyin(const void *uaddr, void *kaddr, size_t len);` +- `int copyout(const void *kaddr, void *uaddr, size_t len);` +- `int copyinstr(const void *uaddr, void *kaddr, size_t len, size_t *done);` +- Related: `fueword`, `fuword`, `subyte`, `suword`, documented under `fetch(9)` and `store(9)`. + +**Header.** `/usr/src/sys/sys/systm.h`. + +**Caveats.** + +- All three may sleep. Do not call them while holding a non-sleepable mutex. +- They return `EFAULT` on a bad address, not zero. Always check the return value. +- `copyinstr` distinguishes truncation from success via its `done` argument; do not ignore it. + +**Lifecycle phase.** `d_ioctl`, `d_read`, `d_write`, and anywhere else userland is the source or destination. + +**Manual pages.** `copy(9)`, `fetch(9)`, `store(9)`. + +**Where the book teaches this.** Chapter 9. + +### `uio(9)`: I/O Descriptor for Read and Write + +**Purpose.** The kernel's own description of an I/O request. Hides the difference between user and kernel buffers, between scatter-gather and contiguous transfers, and between read and write directions. + +**Key names.** + +- `int uiomove(void *cp, int n, struct uio *uio);` +- `int uiomove_nofault(void *cp, int n, struct uio *uio);` +- Fields in `struct uio`: `uio_iov`, `uio_iovcnt`, `uio_offset`, `uio_resid`, `uio_segflg`, `uio_rw`, `uio_td`. +- Segment flags: `UIO_USERSPACE`, `UIO_SYSSPACE`, `UIO_NOCOPY`. +- Direction: `UIO_READ`, `UIO_WRITE`. + +**Header.** `/usr/src/sys/sys/uio.h`. + +**Caveats.** + +- Use `uiomove` in `d_read` and `d_write` entry points. It is the right tool even when the userland buffer is a simple contiguous region. +- `uiomove` may sleep. Drop non-sleepable mutexes before calling it. +- After `uiomove` returns, `uio_resid` has been updated. Do not maintain your own byte count in parallel; read it from `uio_resid`. + +**Lifecycle phase.** Normal I/O. + +**Manual page.** `uio(9)`. + +**Where the book teaches this.** Chapter 9. + +### `proc(9)` and Thread Context for Drivers + +**Purpose.** Access to the calling thread and its process, primarily for credential checks, signal state, and diagnostic printing. + +**Key names.** + +- `curthread`, `curproc`, `curthread->td_proc`. +- `struct ucred *cred = curthread->td_ucred;` +- `int priv_check(struct thread *td, int priv);` +- `pid_t pid = curproc->p_pid;` + +**Header.** `/usr/src/sys/sys/proc.h`. + +**Caveats.** + +- Direct use of process internals is rare. When you need it, it is usually for a credential check, which should go through `priv_check(9)`. +- Do not store `curthread` across sleeps. The thread that re-enters the driver may be a different one. + +**Manual page.** No single page; see `priv(9)` and `proc(9)`. + +**Where the book teaches this.** Referenced in Chapter 9 and Chapter 24 when ioctl handlers need credentials. + +## Observability and Notification + +A driver that cannot be observed is a driver that cannot be trusted. The kernel provides several ways for userland to peek at driver state, subscribe to events, and wait for readiness. The APIs below are the most common. + +### `sysctl(9)`: Read-and-Write Configuration Nodes + +**Purpose.** Publish driver state and tunables under a hierarchical name so tools like `sysctl(8)` and monitoring scripts can read or modify them. + +**Key names.** + +- Static declarations: `SYSCTL_NODE`, `SYSCTL_INT`, `SYSCTL_LONG`, `SYSCTL_STRING`, `SYSCTL_PROC`, `SYSCTL_OPAQUE`. +- Dynamic context API: `sysctl_ctx_init`, `sysctl_ctx_free`, `SYSCTL_ADD_NODE`, `SYSCTL_ADD_INT`, `SYSCTL_ADD_PROC`. +- Handler helpers: `sysctl_handle_int`, `sysctl_handle_long`, `sysctl_handle_string`. +- Access flags: `CTLFLAG_RD`, `CTLFLAG_RW`, `CTLFLAG_TUN`, `CTLFLAG_STATS`, `CTLTYPE_INT`, `CTLTYPE_STRING`. + +**Header.** `/usr/src/sys/sys/sysctl.h`. + +**Caveats.** + +- For anything tied to a specific device instance, use the dynamic API. `device_get_sysctl_ctx` and `device_get_sysctl_tree` give you the right context. +- Handlers run in user context. They may sleep and may fail. +- Publish tunables sparingly. Every knob is a contract with future users. + +**Lifecycle phase.** Static declarations are module-wide. Dynamic declarations are created in `attach` and destroyed automatically in `detach` through the context. + +**Manual pages.** `sysctl(9)`, `sysctl_add_oid(9)`, `sysctl_ctx_init(9)`. + +**Where the book teaches this.** Introduced in Chapter 7, with deeper treatment in Chapter 24 (Section 4) when the driver starts exposing metrics to userland. + +### `eventhandler(9)`: In-Kernel Publish-Subscribe + +**Purpose.** Register for kernel-wide events such as mount, unmount, low memory, and shutdown. The kernel invokes registered callbacks in response. + +**Key names.** + +- `EVENTHANDLER_DECLARE(name, type_t);` +- `eventhandler_tag EVENTHANDLER_REGISTER(name, func, arg, priority);` +- `void EVENTHANDLER_DEREGISTER(name, tag);` +- `void EVENTHANDLER_INVOKE(name, ...);` +- Priority constants: `EVENTHANDLER_PRI_FIRST`, `EVENTHANDLER_PRI_ANY`, `EVENTHANDLER_PRI_LAST`. + +**Header.** `/usr/src/sys/sys/eventhandler.h`. + +**Caveats.** + +- Handlers run synchronously. Keep them short. +- Always deregister before module unload. A dangling handler will panic when the event fires. + +**Manual page.** `EVENTHANDLER(9)`. + +**Where the book teaches this.** Referenced in Chapter 24 when drivers integrate with kernel-wide notifications such as shutdown and low-memory events. + +### `poll(2)` and `kqueue(2)`: Readiness Notification + +**Purpose.** Let userland wait for driver-owned readiness events. `poll(2)` is the older interface; `kqueue(2)` is the modern one with richer filters. + +**Key names.** + +- Entry point for `poll`: `int (*d_poll)(struct cdev *, int events, struct thread *);` +- Entry point for `kqueue`: `int (*d_kqfilter)(struct cdev *, struct knote *);` +- Wait-list management: `struct selinfo`, `selrecord(struct thread *td, struct selinfo *sip)`, `selwakeup(struct selinfo *sip)`. +- kqueue support: `struct knote`, `knote_enqueue`, `knlist_init_mtx`, `knlist_add`, `knlist_remove`. +- Event bits: `POLLIN`, `POLLOUT`, `POLLERR`, `POLLHUP` for `poll`; `EVFILT_READ`, `EVFILT_WRITE` for `kqueue`. + +**Headers.** `/usr/src/sys/sys/selinfo.h`, `/usr/src/sys/sys/event.h`, `/usr/src/sys/sys/poll.h`. + +**Caveats.** + +- `d_poll` must call `selrecord` when no events are ready and report current readiness when they are. +- `selwakeup` must be called with no mutex held that might invert against the scheduler. This is a common lock-order bug. +- `kqueue` support is richer but also more code. When the driver already has a clean `poll` path, extending it to `kqueue` is often the right next step rather than a rewrite. + +**Lifecycle phase.** Setup in `attach`; tear down in `detach`; actual dispatch in `d_poll` or `d_kqfilter`. + +**Manual pages.** `selrecord(9)`, `kqueue(9)`, and the userland pages `poll(2)` and `kqueue(2)`. + +**Where the book teaches this.** Chapter 10 introduces `poll(2)` integration in full; `kqueue(2)` is referenced there and explored in depth in Chapter 35. + +## Diagnostics, Logging, and Tracing + +Driver correctness does not just live in the code. It lives in the ability to observe, assert, and trace. The APIs below are how you make a driver tell the truth about itself. + +### `log(9)` and `printf(9)` + +**Purpose.** Emit messages to the kernel log so they appear in `dmesg` and in `/var/log/messages`. + +**Key names.** + +- `void log(int level, const char *fmt, ...);` +- Standard kernel `printf` family: `printf`, `vprintf`, `uprintf`, `tprintf`. +- Per-device helper: `device_printf(device_t dev, const char *fmt, ...);` +- Priority constants from `syslog.h`: `LOG_EMERG`, `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`, `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`. + +**Headers.** `/usr/src/sys/sys/systm.h`, `/usr/src/sys/sys/syslog.h`. + +**Caveats.** + +- Do not log at `LOG_INFO` on the I/O fast path. It floods the console and masks real issues. +- `device_printf` automatically prepends the device name, which makes logs easy to filter. Prefer it over bare `printf`. +- Log once for each distinct event class, not once per packet. + +**Lifecycle phase.** Any. + +**Manual pages.** `printf(9)`. + +**Where the book teaches this.** Chapter 23. + +### `KASSERT(9)`: Kernel Assertions + +**Purpose.** Declare invariants that must be true. When the kernel is built with `INVARIANTS`, a violated assertion panics with a descriptive message. Without `INVARIANTS`, the assertion compiles away. + +**Key names.** + +- `KASSERT(expression, (format, args...));` +- `MPASS(expression);` for simpler message-free assertions. +- `CTASSERT(expression);` for compile-time assertions on constants. + +**Header.** `/usr/src/sys/sys/kassert.h`, included transitively by `/usr/src/sys/sys/systm.h`. + +**Caveats.** + +- The expression must be cheap and free of side effects. The compiler does not optimise it into place; you write the invariant. +- The message is a parenthesised `printf` argument list. Include enough context to diagnose a failure from the panic alone. +- Use `KASSERT` for conditions that indicate a programmer error, not for normal runtime conditions. + +**Lifecycle phase.** Wherever an invariant must be documented and enforced. + +**Manual page.** `KASSERT(9)`. + +**Where the book teaches this.** Chapter 23 introduces `INVARIANTS` and assertion use; Chapter 34 Section 2 treats `KASSERT` and diagnostic macros in depth. + +### `WITNESS`: Lock-Order Verifier + +**Purpose.** A kernel option that tracks the order in which each thread acquires locks and warns when a later thread reverses a previously observed order. + +**Key names.** + +- Built into `mtx(9)`, `sx(9)`, `rm(9)`, and the locking macros. No separate API call is needed. +- Kernel options: `WITNESS`, `WITNESS_SKIPSPIN`, `WITNESS_COUNT`. +- Assertions that cooperate with `WITNESS`: `mtx_assert`, `sx_assert`, `rm_assert`. + +**Caveats.** + +- `WITNESS` is a debugging option. Build a debug kernel to enable it; it is too expensive for production. +- Warnings are not noise. If `WITNESS` complains, there is a bug. +- Lock-order warnings reference the lock names passed to `mtx_init`, `sx_init`, and so on. Give each lock a meaningful name. + +**Manual page.** No single page. See `lock(9)` and `locking(9)`. + +**Where the book teaches this.** Chapter 12 (Section 6), with reinforcement in Chapter 23. + +### `ktr(9)`: Kernel Trace Facility + +**Purpose.** A low-overhead ring buffer for event tracing inside the kernel. `ktr` records are emitted by macros and can be dumped with `ktrdump(8)`. + +**Key names.** + +- `CTR0(class, fmt)`, `CTR1(class, fmt, a1)`, up to `CTR6` with increasing argument counts. +- Trace classes: `KTR_GEN`, `KTR_NET`, `KTR_DEV`, and many others in `sys/ktr_class.h`. +- Kernel option: `KTR` with per-class masks. + +**Header.** `/usr/src/sys/sys/ktr.h`. + +**Caveats.** + +- `ktr` must be enabled at kernel build time; check for `KTR` in the configuration. +- Each record is small. Do not try to log entire structures. +- For user-facing diagnostics, `dtrace(1)` is often a better answer. + +**Manual page.** `ktr(9)`. + +**Where the book teaches this.** Chapter 23. + +### DTrace Static Probes and Major Providers + +**Purpose.** Static and dynamic tracing infrastructure that lets userland attach to probe points in the running kernel without a recompile. + +**Key names.** + +- Statically defined tracing: `SDT_PROVIDER_DECLARE`, `SDT_PROVIDER_DEFINE`, `SDT_PROBE_DECLARE`, `SDT_PROBE_DEFINE`, `SDT_PROBE`. +- Common providers on FreeBSD: `sched`, `proc`, `io`, `vfs`, `fbt` (function boundary tracing), `sdt`. +- Headers: `/usr/src/sys/sys/sdt.h`, `/usr/src/sys/cddl/dev/dtrace/...`. + +**Caveats.** + +- `fbt` requires no change to the driver, but `sdt` probes give you named, stable points that survive future refactoring. +- A disabled probe has negligible cost. Do not worry about adding several of them. +- DTrace scripts themselves are userland code; the driver only defines the probe points that the scripts can attach to. + +**Manual pages.** `SDT(9)`, `dtrace(1)`, `dtrace(8)`. + +**Where the book teaches this.** Chapter 23. + +## Cross-Reference by Driver Lifecycle Phase + +The same APIs show up in different phases of a driver's life. The table below is a quick reverse index: when you are writing a particular phase, here are the families that usually belong there. + +### Module Load + +- `MODULE_VERSION`, `MODULE_DEPEND`, `DEV_MODULE` (if the module is a pure cdev). +- Static `MALLOC_DEFINE`, `SYSCTL_NODE`, `SDT_PROVIDER_DEFINE` declarations. +- Event-handler registration that must survive before any device attaches. + +### Probe + +- `device_get_parent`, `device_get_nameunit`, `device_printf`. +- Return values: `BUS_PROBE_DEFAULT`, `BUS_PROBE_GENERIC`, `BUS_PROBE_SPECIFIC`, `BUS_PROBE_LOW_PRIORITY`, `ENXIO` on no match. + +### Attach + +- `device_get_softc`, `malloc(9)` for softc fields, `MALLOC_DEFINE` tags. +- Locking initialisation: `mtx_init`, `sx_init`, `rm_init`, `cv_init`, `sema_init`. +- Resource allocation: `bus_alloc_resource` or `bus_alloc_resource_any`. +- `bus_space` setup through `rman_get_bustag` and `rman_get_bushandle`. +- DMA scaffolding: `bus_dma_tag_create`, `bus_dmamap_create`. +- `callout_init`, `TASK_INIT`, taskqueue creation when needed. +- Interrupt setup: `bus_setup_intr`. +- Device node creation: `make_dev_s`. +- sysctl tree: `device_get_sysctl_ctx`, `SYSCTL_ADD_*`. +- `uma_zcreate` for high-frequency objects. +- Eventhandler registration tied to this driver. + +### Normal Operation + +- `d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl`, `d_poll`, `d_kqfilter`. +- `uiomove`, `copyin`, `copyout`, `copyinstr`. +- `bus_space_read_*`, `bus_space_write_*`, `bus_space_barrier`. +- `bus_dmamap_load`, `bus_dmamap_sync`, `bus_dmamap_unload`. +- Locking: `mtx_lock`, `mtx_unlock`, `sx_slock`, `sx_xlock`, `cv_wait`, `cv_signal`, `atomic_*`. +- Deferred work: `callout_reset`, `taskqueue_enqueue`. +- Diagnostics: `device_printf`, `log`, `KASSERT`, `SDT_PROBE`. + +### Detach + +- Tear-down in reverse attach order. +- `bus_teardown_intr` before any resource is released. +- `destroy_dev` before the softc fields it references are torn down. +- `callout_drain` before freeing the callout structure. +- `taskqueue_drain_all` and `taskqueue_free` for private taskqueues. +- `bus_dmamap_unload`, `bus_dmamap_destroy`, `bus_dma_tag_destroy`. +- `bus_release_resource` for every resource allocated in attach. +- `cv_destroy`, `sx_destroy`, `mtx_destroy`, `rm_destroy`, `sema_destroy`. +- `uma_zdestroy` for every zone the driver owns. +- Eventhandler deregistration. +- Final `free` or `contigfree` of anything allocated. + +### Module Unload + +- Verify that no device instance is still attached. Newbus usually handles this, but defensive `DRIVER_MODULE` event handlers should refuse unload if state remains. + +## Quick-Reference Checklists + +These checklists are meant to be read in five minutes or less. They do not replace the teaching in the chapters; they remind you of the things that experienced driver authors no longer forget. + +### Locking Discipline Checklist + +- Every shared field in the softc has exactly one lock that protects it, documented in a comment near the field. +- No mutex is held across `uiomove`, `copyin`, `copyout`, `malloc(9, M_WAITOK)`, or `bus_alloc_resource`. +- Lock order is declared in a comment at the top of the file and respected everywhere. +- `mtx_assert` or `sx_assert` appears on functions that require a particular lock to be held on entry. +- `WITNESS` is enabled in the development kernel and its warnings are treated as bugs. +- Every `mtx_init` has a matching `mtx_destroy`, and so on for every lock type. + +### Resource Lifetime Checklist + +- `bus_setup_intr` is the last thing in `attach`; `bus_teardown_intr` is the first thing in `detach`. +- Every allocated resource has a matching release, in reverse order, in `detach`. +- `callout_drain` is called before the structure it points at is freed. +- `taskqueue_drain_all` or `taskqueue_drain` is called before the task structures or their arguments are freed. +- `destroy_dev` is called before the softc fields referenced by `mda_si_drv1` are torn down. + +### User-Space Safety Checklist + +- No user pointer is dereferenced directly. Every cross-boundary access goes through `copyin`, `copyout`, `copyinstr`, or `uiomove`. +- All return values from the copy helpers are checked. `EFAULT` is propagated rather than ignored. +- `_IOR`, `_IOW`, and `_IOWR` are used for ioctl command numbers. +- Ioctl handlers validate arguments before acting on them. +- Credentials are checked with `priv_check(9)` when the operation is privileged. + +### Diagnostic Coverage Checklist + +- Every major branch that should never be taken carries a `KASSERT`. +- Logs use `device_printf` for instance context. +- At least one DTrace SDT probe marks entry to the main I/O paths. +- `sysctl` exposes the driver's counters in a stable, documented tree. +- The driver has been built and exercised under `INVARIANTS` and `WITNESS` before it is considered done. + +## Wrapping Up + +This appendix is a reference, not a chapter. It becomes more useful the more you use it. Keep it within reach while you are writing, debugging, or reading driver code, and turn to it whenever you want a fast reminder about a flag, a manual page, or a caveat you almost remember. + +Three suggestions for getting the most out of it over time. + +First, treat the **Manual pages** line as the canonical next step for any API you only half remember. The manual pages in section 9 are maintained with the tree; they age well. Opening one of them costs nothing and pays back every time. + +Second, treat the **Caveats** line as a debugging companion. Most driver bugs are not unknown unknowns. They are documented caveats that the author skipped under time pressure. When you are stuck, read the caveats for every API the problem area touches. It is unglamorous but effective. + +Third, when you find a missing entry or a correction to make, write it down. This appendix improves as drivers improve. The FreeBSD kernel is alive and so is the reference. If a new primitive appears, or an old one is retired, the appendix that matches reality is the one you will actually trust. + +From here you can jump in several directions. Appendix E covers FreeBSD internals and subsystem behaviour at a depth this reference deliberately avoids. Appendix B collects the algorithms and systems-programming patterns that recur throughout the kernel. Appendix C grounds the hardware concepts that the bus and DMA families depend on. And every chapter in the main book still has source code you can read, labs you can run, and questions you can answer by opening `/usr/src/` and looking at the real thing. + +Good reference material is quiet. It stays out of the way while you work, and it is there when you need it. That is the role this appendix is meant to play for the rest of your driver-writing life with FreeBSD. diff --git a/content/appendices/appendix-b.md b/content/appendices/appendix-b.md index 929b668..11745da 100644 --- a/content/appendices/appendix-b.md +++ b/content/appendices/appendix-b.md @@ -1,13 +1,631 @@ --- title: "Algorithms and Logic for Systems Programming" -description: "Common algorithms and logical patterns used in systems programming and device drivers" +description: "A pattern guide to the data structures, control flow, and reasoning idioms that recur throughout FreeBSD kernel and driver code." appendix: "B" -date: "2025-08-01" -status: "planned" +lastUpdated: "2026-04-20" +status: "complete" author: "Edson Brandi" reviewer: "TBD" translator: "TBD" -estimatedReadTime: 25 +estimatedReadTime: 30 --- -planned +# Appendix B: Algorithms and Logic for Systems Programming + +## How to Use This Appendix + +The main chapters teach the primitives a driver author uses day to day. Alongside those primitives there is a second layer of knowledge that the book assumes without always naming it: the small catalogue of data structures, control-flow shapes, and reasoning patterns that show up in nearly every driver you will read. A red-black tree in a virtual-memory subsystem, a `STAILQ` of pending requests on the side of a softc, a `goto out` ladder that unwinds an `attach` routine, a switch on a state enum that drives a protocol handshake. None of these ideas is hard in isolation. What makes them feel hard is meeting them for the first time embedded in real kernel code, where the pattern is implicit and the name is nowhere on the page. + +This appendix is that missing name. It is a short, practical field guide to the algorithmic patterns that recur across FreeBSD kernel and driver code, organised so that you can recognise a pattern when you see it and decide which pattern fits when you have to write one. It is not a computer-science textbook, and it is not a replacement for the chapters that already teach the specific pieces you will use most. What it provides is a middle layer: enough pattern recognition to let you read driver code confidently, enough mental modelling to pick the right structure when the blank page stares back at you, and enough caveat awareness to avoid the mistakes that every driver author eventually makes once. + +### What You Will Find Here + +The appendix is organised by problem family, not by abstract taxonomy. Each family collects a few related patterns with a consistent short structure: + +- **What it is.** One or two sentences. +- **Why drivers use it.** The concrete role in kernel or driver code. +- **Use this when.** A compact decision hint. +- **Avoid this when.** The other side of the same decision. +- **Core operations.** The handful of names you need in muscle memory. +- **Common traps.** The mistakes that actually cost people time. +- **Where the book teaches it.** A pointer back to the main chapters. +- **What to read next.** A manual page or a realistic source-tree example. + +When a pattern has a real FreeBSD implementation with a stable interface, the entry uses those names directly. When the pattern is generic, the entry still grounds itself in how FreeBSD drivers actually apply it. + +### What This Appendix Is Not + +It is not a first course in algorithms. If you have never met a linked list or a state machine before, this appendix will feel too compressed; read Chapters 4 and 5 first, then come back. It is not a deep theoretical reference either. You will find almost no asymptotic analysis here, because driver authors rarely choose between O(log n) and O(n) on paper. They choose between patterns whose trade-offs are mostly about locking, cache behaviour, and invariants. Finally, it is not a replacement for Appendix A (which covers the APIs), Appendix C (which covers hardware concepts), or Appendix E (which covers kernel subsystems). If the pattern you want points you there, go there and come back. + +## Reader Guidance + +Three ways to read this appendix, each calling for a different strategy. + +If you are **writing new code**, skim the problem family that matches your situation, read the one or two entries that apply, glance at the **Common traps** line, and close the appendix. Thirty seconds is enough. Start from the pattern, not from the code. + +If you are **reading someone else's driver**, treat the appendix as a translator. When you see an unfamiliar idiom, find the family that names it, read **What it is** and **Core operations**, and keep moving. Full understanding can come later; right now the goal is to form a mental model of what the driver is doing. + +If you are **debugging**, read the **Common traps** lines in the pattern family around the bug. Most driver bugs that look mysterious are ordinary caveats the author did not honour. A ring buffer with a stale `full` check, an unwind ladder that frees in the wrong order, a state machine that forgot a transient state. The traps in this appendix are not exhaustive, but they cover the ones that recur. + +A few conventions apply throughout: + +- Source paths are shown in the book-facing form, `/usr/src/sys/...`, matching a standard FreeBSD system. +- Manual pages are cited in the usual FreeBSD style. For the data-structure macros, the authoritative pages live in section 3: `queue(3)`, `tree(3)`, `bitstring(3)`. For kernel services such as `hashinit(9)`, `buf_ring(9)`, `refcount(9)`, the pages live in section 9. The distinction matters only when you type `man` at the prompt. +- When an entry points to real source as a reading example, it points to a file that a beginner can open and navigate. Larger subsystems exist that also use the pattern; those are mentioned only when they are the canonical place to see a pattern in practice. + +With that in mind, we start with the structures a driver uses to hold state. + +## Data Structures in the Kernel + +A driver without state is rare. Almost every non-trivial driver keeps a collection of something: pending requests, open handles, per-CPU statistics, per-channel configuration, per-client contexts. The question is which collection shape matches the access pattern. The kernel ships a small toolkit of header-file data structures that you should reach for by default instead of rolling your own. Each of them solves a different problem; confusing them is one of the most common category errors in driver design. + +### The `` Family + +**What it is.** A family of intrusive linked-list macros. You define a head and an entry, embed the entry inside your element structure, and the macros give you insertion, removal, and traversal without heap allocation for list nodes. + +The header defines four flavours: + +- `SLIST` is a singly linked list. Cheapest, forward only, O(n) removal of arbitrary elements. +- `LIST` is a doubly linked list. Forward and backward traversal, O(1) removal of an arbitrary element. +- `STAILQ` is a singly linked tail queue. Forward only, but with fast insertion at the tail. Classic FIFO. +- `TAILQ` is a doubly linked tail queue. Every operation you can reasonably want, at the cost of two pointers per element. + +**Why drivers use them.** Almost every per-driver collection in the tree is one of these. Pending commands, open file handles, registered callbacks, child devices. They are predictable, allocation-free at the list level, and the macros make the code read almost like pseudocode. + +**Use this when** you have a collection of objects you already allocate yourself, and you want standard list operations without inventing them. The intrusive design means an object can live in several lists at once; that is a feature, not a bug. + +**Avoid this when** you need ordered lookup by key. A list is O(n) to search. Reach for a tree or a hash table instead. + +**Choosing among the four.** + +- Start with `TAILQ` unless you have a reason not to. It is the most common and the most flexible. +- Drop to `STAILQ` when you know you only ever push and pop like a queue. You save one pointer per element. +- Use `LIST` when you want doubly linked behaviour but do not need a tail pointer. Unordered sets of independent elements, for example. +- Use `SLIST` when every byte counts and the list is short or traversal is linear anyway. Fast paths in hot structures sometimes justify it. + +**Core operations.** The macros are uniform across flavours. Insertion: `TAILQ_INSERT_HEAD`, `TAILQ_INSERT_TAIL`, `TAILQ_INSERT_BEFORE`, `TAILQ_INSERT_AFTER`. Removal: `TAILQ_REMOVE`. Traversal: `TAILQ_FOREACH`, plus the `_SAFE` variant when you may remove the current element. The same operations exist with `LIST_`, `STAILQ_`, and `SLIST_` prefixes. Field storage is an embedded `TAILQ_ENTRY(type)` in your struct. + +**Common traps.** + +- Using the non-`_SAFE` foreach while removing elements. Plain `TAILQ_FOREACH(var, head, field)` expands to a `for` loop that reads `TAILQ_NEXT(var, field)` at the end of each iteration. If the body freed `var`, the next step dereferences freed memory. `TAILQ_FOREACH_SAFE(var, head, field, tmp)` caches the next pointer into `tmp` before the body runs, and is always the right answer when the loop body may remove `var`. +- Forgetting that the list is intrusive. The same element cannot be in two `TAILQ`s through the same entry field at once. If you need that, define two `TAILQ_ENTRY` fields with different names. +- Mixing flavours on the same head. `SLIST_INSERT_HEAD` on a `TAILQ_HEAD` compiles but produces silent corruption. Keep the macros consistent with the head type. + +**Where the book teaches this.** Introduced briefly in Chapter 5 as part of the kernel dialect of C and revisited whenever a driver in later parts of the book needs an internal collection. + +**What to read next.** `queue(3)` for the full macro catalogue, and any real driver that keeps pending work. `/usr/src/sys/net/if_tuntap.c` uses these idioms extensively. + +### Red-Black Trees via `` + +**What it is.** A set of macros that generate a self-balancing binary search tree inlined into your types. FreeBSD's implementation is rank-balanced, but it exposes the historical `RB_` prefix and behaves like a red-black tree for all practical purposes. + +**Why drivers use them.** When you need O(log n) ordered lookup by a key and the key is not a small integer, a red-black tree is the default. Virtual-memory maps, scheduler run-queues in some subsystems, and per-subsystem registries of named objects all use this header. + +**Use this when** you have a collection of objects indexed by a key, the set grows to hundreds or thousands of entries, and you care about ordered traversal as well as lookup. + +**Avoid this when** the set is small (a dozen elements) or the key space is small and dense. A linear scan on a cache-hot array usually beats a tree in both cases, because the constant factor of a pointer chase is much higher than a sequential read. + +**Core operations.** `RB_HEAD(name, type)` defines the head type, `RB_ENTRY(type)` defines the embedded node field, `RB_PROTOTYPE` and `RB_GENERATE` instantiate the function family (insert, remove, find, min, max, next, prev, foreach). You also write a comparison function that returns negative, zero, or positive the way `strcmp(3)` does. A variant `SPLAY_` family in the same header gives splay trees when locality of reference is important. + +**Common traps.** + +- Calling `RB_GENERATE` in a header. That produces multiple definitions at link time. Keep `RB_GENERATE` in exactly one `.c` file and `RB_PROTOTYPE` in the header that declares the type. +- Forgetting that the tree is intrusive. An element cannot live in two trees through the same entry, and removing from the wrong tree silently corrupts both. +- Holding a pointer across an insert. Balance rotations do not move nodes, but the comparator must be consistent; if your key changes while the node is in the tree, you have invalidated the search structure and every subsequent lookup is undefined. + +**Where the book teaches this.** Not taught as a dedicated pattern in the book. The reader meets it through example when Appendix E walks the virtual-memory subsystem and when advanced drivers in Part 7 reach for ordered lookup. + +**What to read next.** `tree(3)` for the macro catalogue, and any subsystem that keeps an ordered set of named things. + +### Radix Trees via `` + +**What it is.** A kernel-specific radix (or Patricia) tree, primarily used by the routing table to match addresses against prefixes. A radix tree differs from a red-black tree in that it keys on prefix length rather than total order, which is precisely what longest-prefix-match needs. The header lives at `/usr/src/sys/net/radix.h`, alongside the rest of the networking code, rather than under `/usr/src/sys/sys/`. + +**Why drivers use them.** Rarely, directly. The radix tree exists because the networking stack needs it, and the machinery is specialised to that use. A driver almost never creates its own radix tree. You may meet one as a caller in network-adjacent code, or you may see the related LinuxKPI radix-tree shim in compatibility layers. + +**Use this when** you genuinely need prefix matching over keys of varying length. Routing, ACL tables, prefix-based policy. + +**Avoid this when** what you actually need is ordered lookup by exact key. Use `` instead. + +**Core operations.** `rn_inithead`, `rn_addroute`, `rn_delete`, `rn_lookup`, `rn_match`, `rn_walktree`. These are specialised enough that the routing subsystem is the canonical reference. + +**Common traps.** The header and the routines are tightly coupled to the routing-table abstraction. Attempting to reuse the radix tree for non-routing data structures is almost always a mistake; the abstraction will leak in uncomfortable ways. The LinuxKPI radix tree in `/usr/src/sys/compat/linuxkpi/common/include/linux/radix-tree.h` is a different structure and should not be confused with the native one. + +**Where the book teaches this.** Only mentioned in Appendix E alongside the routing table. This appendix names it so you can recognise it in passing. + +**What to read next.** The routing-table code under `/usr/src/sys/net/`. + +### Bitmaps and Bit-Strings via `` + +**What it is.** A compact set-of-bits abstraction backed by an array of machine words. You allocate a bit-string of N bits, then set, clear, test, and scan individual bits. + +**Why drivers use them.** Any time you have a dense finite universe and want to track boolean state for each element. Free-slot bitmaps for a fixed pool of hardware descriptors, interrupt allocations, minor numbers, per-channel enable flags. A bitmap uses one bit per element and supports efficient first-free searches. + +**Use this when** the universe is dense, known in advance, and you track boolean state per element. Bitmaps are particularly effective when you need "find the first free slot" or "how many are set". + +**Avoid this when** the universe is sparse. A set of a few thousand used slot numbers in a 32-bit key space does not belong in a bitmap; use a hash table or a tree. + +**Core operations.** `bit_alloc` (kernel allocator variant) and `bit_decl` (stack), `bit_set`, `bit_clear`, `bit_test`, `bit_nset`, `bit_nclear` for ranges, `bit_ffs` for first-set, `bit_ffc` for first-clear, `bit_foreach` for iteration. Sizes are computed with `bitstr_size(nbits)`. + +**Common traps.** + +- Forgetting that bit indices are zero-based and that the `bit_ffs` / `bit_ffc` macros do not return a value; they write the found index into `*_resultp` and set it to `-1` when nothing matched. Always check `if (result < 0)` before using the index. +- Race conditions under concurrent modification. `bitstring(3)` is not atomic; if two contexts can set or clear bits concurrently, they need a lock or a coordinated handoff. +- Allocating the wrong size. Use `bitstr_size(nbits)` rather than doing the division by hand. + +**Where the book teaches this.** Not taught directly. A driver that needs a free-slot bitmap will reach for this header, and this entry is the pointer. + +**What to read next.** `bitstring(3)`. + +### Hash Tables with `hashinit(9)` + +**What it is.** A small helper pattern for building hash tables out of `` lists. `hashinit(9)` allocates a power-of-two array of `LIST_HEAD` buckets and gives you back the array and a mask. Your code hashes the key to a 32-bit value, ANDs it with the mask, and walks the resulting bucket. + +**Why drivers use them.** When you need unordered lookup by key and the set is large enough that a linear scan is too slow. File-system name caches, open-file tables per-process, and any driver that maintains a registry keyed by hashable identifier all use this shape. + +**Use this when** the set is large, lookups are frequent, and ordering does not matter. A hash table beats a tree on average-case lookup and is easier to lock coarsely (one lock per bucket, or one lock for the whole table if writes are rare). + +**Avoid this when** the set is small (a tree or a list is simpler) or you need ordered traversal (`RB_FOREACH` is the answer, not hashing). + +**Core operations.** `void *hashinit(int elements, struct malloc_type *type, u_long *hashmask);` returns the bucket array and writes the mask to `*hashmask`. Each bucket is a `LIST_HEAD`, so you insert and iterate with the usual `LIST_` macros. `hashdestroy` tears it down. `hashinit_flags` takes an extra flags word (`HASH_WAITOK` or `HASH_NOWAIT`) when you need the non-sleeping variant; `hashinit` itself is equivalent to `HASH_WAITOK`. `phashinit` and `phashinit_flags` give you a prime-sized table when you prefer modulo arithmetic to masking, and write the chosen size (not a mask) through the out-pointer. A small `` header provides basic hash functions such as `hash32_buf` and `hash32_str`, along with `jenkins_hash` and `murmur3_32_hash`; the Fowler-Noll-Vo family lives in ``. + +**Common traps.** + +- Hashing a pointer directly. Pointer low bits are usually aligned and produce poor bucket distribution. Use a proper hash function on the contents or on the shifted pointer. +- Assuming `hashinit` uses your requested size. It rounds down to the nearest power of two and returns the mask for that size. A request for 100 elements produces a 64-bucket table, not 100. +- Forgetting the lock story. A bare hash table is not thread-safe. Decide up front whether you want a single lock, per-bucket locks, or something fancier, and document it in the softc. + +**Where the book teaches this.** Briefly referenced in Part 7 drivers that maintain a per-client registry. This entry gives the scaffolding for when you need to build one yourself. + +**What to read next.** `hashinit(9)`, and the implementation in `/usr/src/sys/kern/subr_hash.c`. + +## Circular and Ring Buffers + +Rings appear everywhere in a driver that mediates between hardware and software. A NIC hands out a ring of descriptors for packet transmission. A UART buffers characters between the interrupt that receives them and the process that consumes them. A command driver batches requests into a ring for the hardware engine to pick up. The shape is always the same: a fixed-size array plus a producer index and a consumer index that wrap around. What varies is who is concurrent with whom, which primitives you use, and whether the ring needs to be lock-free. + +### Single-Producer Single-Consumer Ring Buffers + +**What it is.** A fixed-size circular buffer where exactly one context produces and exactly one context consumes. The producer advances a `head` (or `tail`) index after writing; the consumer advances a `tail` (or `head`) index after reading; neither ever writes the other's index. + +**Why drivers use them.** The interrupt handler produces data (a received character, a completion event), and a thread consumes it. That is the prototypical SPSC shape. It is lock-free by construction, because no two contexts modify the same variable. + +**Use this when** you have exactly one producer and exactly one consumer, and you want to avoid a lock. Character device ring buffers are the classic case. + +**Avoid this when** more than one thread can produce, or more than one thread can consume. Adding a second producer breaks the invariant; you need a lock, or you need `buf_ring(9)`. + +**Core operations and invariants.** The usual invariants are: + +- `head` advances only by the producer; `tail` advances only by the consumer. +- `(head - tail) mod capacity` is the number of occupied slots. +- `capacity - (head - tail) mod capacity` is the number of free slots (minus one, depending on the encoding). +- The buffer is empty when `head == tail`. +- The buffer is full when `(head + 1) mod capacity == tail`. The one sacrificed slot is how you distinguish full from empty. + +The alternative encoding uses a separate `count` variable or uses free-running indices modulo the capacity with a mask (`head & mask`, `tail & mask`). Free-running indices make full-versus-empty a signed comparison and avoid the sacrificed slot. + +**Common traps.** + +- Mixing up full and empty without the one-slot convention. Every ring design must have a clear answer; pick one and write it at the top of the file. +- Not ordering memory properly. On modern CPUs, writes can become visible out of order. The producer must make sure the buffer contents are visible to the consumer before the updated `head` is. In the kernel that means an explicit memory barrier (`atomic_thread_fence_rel` on the producer, `atomic_thread_fence_acq` on the consumer), or using the atomic store-release and load-acquire variants. +- Assuming `capacity` is a power of two when the code does not enforce it. Masking requires a power of two; modulo does not. The code and the invariant must agree. + +**Where the book teaches this.** Chapter 10 builds a circular buffer for the `myfirst` driver's character device and teaches the head/tail/full/empty discipline from first principles. Revisited in Chapters 11 and 12 when the ring meets synchronisation. + +**What to read next.** The circular-buffer example from Chapter 10 in the companion `examples/` tree, and any small character-device driver that uses a ring to bridge interrupt and process context. + +### `buf_ring(9)` for MPMC Rings + +**What it is.** FreeBSD's kernel ring-buffer library. `buf_ring` provides a multi-producer multi-consumer ring with lock-free enqueue and both single-consumer and multi-consumer dequeue paths. It is used heavily by iflib, networking drivers, and elsewhere in the tree. + + +See Chapter 11 for the introduction and the `buf_ring(9)` man page for the authoritative concurrency contract. + +**Why drivers use them.** When more than one context can enqueue (several CPUs pushing packets onto the same transmit queue) or more than one context can dequeue (several worker threads draining the same work queue), you cannot get away with the SPSC invariants. `buf_ring` does the atomic compare-and-swap work for you and hides the memory-ordering details behind a stable interface. + +**Use this when** you have multiple producers or multiple consumers and you want a lock-free path. Network-adjacent drivers are the canonical case. + +**Avoid this when** you truly have one producer and one consumer. The SPSC ring is simpler, cheaper, and easier to reason about. + +**Core operations.** `buf_ring_alloc(count, type, flags, lock)` and `buf_ring_free` at setup and teardown. `buf_ring_enqueue(br, buf)` enqueues, returning `0` on success or `ENOBUFS` when full. `buf_ring_dequeue_mc(br)` dequeues safely under multiple consumers; `buf_ring_dequeue_sc(br)` is faster when the caller guarantees single-consumer semantics. `buf_ring_peek`, `buf_ring_count`, `buf_ring_empty`, `buf_ring_full` give you inspection without removing. + +**Common traps.** + +- Calling `buf_ring_dequeue_sc` from multiple consumers at once. The SC path assumes only one consumer is running; violating that corrupts the tail index silently. +- Treating `ENOBUFS` as a hard error. `buf_ring_enqueue` returning `ENOBUFS` is an ordinary back-pressure signal; the caller must either retry, drop, or queue on a slower path. +- Forgetting that `buf_ring_count` and `buf_ring_empty` are advisory. Another CPU may enqueue or dequeue the moment after you check. Design the caller around eventual consistency, not instantaneous truth. + +**Where the book teaches this.** Named in Chapter 10 as the production-grade counterpart to the pedagogical SPSC ring. Used in Part 5 networking chapters when driver examples need real ring semantics. + +**What to read next.** `buf_ring(9)`, and the header itself at `/usr/src/sys/sys/buf_ring.h`. For a real user, browse iflib or any high-performance NIC driver under `/usr/src/sys/dev/`. + +### Wrap-Around Arithmetic and the Full-vs-Empty Problem + +Every ring has to distinguish full from empty. The two states satisfy `head == tail` or are one slot apart, and the encoding you pick decides which comparison to use. The two common conventions are worth naming so you can spot them in code. + +- **Sacrificed slot.** The ring holds `capacity - 1` usable slots. Empty is `head == tail`. Full is `(head + 1) mod capacity == tail`. Simple, cheap, works with any capacity. +- **Free-running indices.** `head` and `tail` count every operation since the ring was created and never wrap. The modular index for array access is `head & mask` (which requires `capacity` to be a power of two). Occupied count is `head - tail` as unsigned arithmetic; full is `occupied == capacity`; empty is `occupied == 0`. The advantage is that you never sacrifice a slot; the cost is that you must write `(uint32_t)(head - tail)` carefully. + +Both conventions are correct. Pick one and make it a one-sentence comment at the top of the file. Readers who know ring buffers will know what to look for; readers who do not will have the comment. + +## Sorting and Searching + +Drivers sort and search less often than they list, ring, or tree things. But when they do, a small toolkit covers almost every case, and knowing which tool is appropriate saves time. + +### In-Kernel `qsort` and `bsearch` + +**What it is.** The kernel provides the familiar `qsort` and `bsearch` from the standard library, declared in `/usr/src/sys/sys/libkern.h`. A thread-safe variant `qsort_r` passes a user context pointer through to the comparator. + +**Use this when** you need to sort an array in place once or occasionally, or when you need binary search over a sorted array. Device ID tables, compatibility matching, and sorted snapshots all fit here. + +**Avoid this when** the collection is long-lived and changes frequently. In that case you want a tree, not a sort-and-search pair. Also avoid `qsort` on hot paths: the function-call overhead of the comparator dominates for small arrays. + +**Core operations.** `qsort(base, nmemb, size, cmp)` and `qsort_r(base, nmemb, size, cmp, thunk)` for sorting; `bsearch(key, base, nmemb, size, cmp)` for searching. The comparator returns negative, zero, or positive in the `strcmp(3)` style. All three are declared in `libkern.h` and have section-3 manual pages (`qsort(3)`, `bsearch(3)`). + +**Common traps.** + +- Non-stable comparisons. `qsort` is not guaranteed stable. If ordering among equal keys matters, add a tiebreaker to the comparator. +- Passing a comparator that tests with subtraction (`a->x - b->x`) when the fields are wide. Integer overflow can make a negative look positive. Use explicit comparisons (`a->x < b->x ? -1 : a->x > b->x ? 1 : 0`). + +**Where the book teaches this.** Referenced in Chapter 4 (the C tour) and in Part 7 where specific drivers sort a table once at attach. + +**What to read next.** `qsort(3)`, `bsearch(3)`. + +### Binary Search Over Device ID Tables + +**What it is.** A specialised application of `bsearch`. A driver maintains a sorted table of `(vendor, device)` or compatible-string keys, and the probe path does a binary search to decide whether the hardware is one it supports. + +**Why drivers use it.** A PCI driver may match dozens of device IDs. A scan through the table is fine at attach time; doing it linearly works. Doing it with `bsearch` is a small, readable, fast improvement when the table grows. + +**Use this when** the ID table is longer than a handful of entries and ordering by key is easy. You can sort at compile time by declaring the table statically sorted, or once at module load with `qsort`. + +**Avoid this when** the match is not a simple key comparison. PCI matching sometimes involves subclass and programming interface fields; express the matching logic directly rather than contorting it into a comparator. + +**Common traps.** Sorting at runtime and then relying on the sort for ABI compatibility. If another piece of code reads the table by index, changing the order breaks it. Declare the table `const` and sort at build time when you can. + +**Where the book teaches this.** Referenced in Chapter 18 (PCI) and in the device-matching discussion in Chapter 6. + +**What to read next.** Any PCI driver's ID table and probe path. `/usr/src/sys/dev/uart/uart_bus_pci.c` is a readable example. + +### When Linear Search Wins + +**What it is.** A reminder that for small collections, linear search on a cache-hot array is the fastest lookup you can write. CPU caches reward sequential reads and punish pointer chasing. + +**Use this when** the collection has fewer than a few dozen entries. In practice, a linear scan on twenty items is faster than any tree lookup, because the tree walk takes several cache misses while the linear scan takes one. + +**Avoid this when** the collection grows without bound, or when the hot-path latency requirement is tight and the worst case matters more than the average. + +**Common traps.** Optimising the wrong side. Do not introduce a tree to cure "linear search is slow" before measuring. The real cost is usually elsewhere. + +## State Machines and Protocol Handling + +Many drivers are state machines in disguise. A USB device probes, attaches, goes idle, resumes, suspends, detaches. A network driver goes through link-down, link-up, negotiation, steady-state, error recovery. When the state transitions are complicated, making the state explicit pays off immediately. When they are simple, an enum and a switch often do the job. + +### Explicit State Enum vs Implicit Flag Bits + +**What it is.** Two ways to represent state. An enum says "this device is in exactly one of N states". A flag word says "this device has any combination of N independent booleans". + +**Use the enum when** the conditions are mutually exclusive and naming the transitions matters. A link is one of `LINK_DOWN`, `LINK_NEGOTIATING`, or `LINK_UP`. A command is one of `CMD_IDLE`, `CMD_PENDING`, `CMD_RUNNING`, or `CMD_DONE`. An enum forces every transition to be explicit; you cannot accidentally be in two states at once. + +**Use flag bits when** the conditions are independent and can be combined. "Interrupt enabled", "autonegotiation allowed", "in promiscuous mode". Mixing mutually exclusive and independent conditions in the same flag word is the usual mistake; separate them into an enum for the first and a flag word for the second. + +**Common traps.** + +- Encoding a state machine as bit flags and then having to decide what "both `CMD_PENDING` and `CMD_DONE` set" means. That never means anything useful. Switch to an enum. +- Encoding independent booleans as a single packed state. You will reinvent bitwise OR, badly. + +### Switch-Based FSMs + +**What it is.** The simplest explicit state machine: an enum for the state, a switch in a function that takes an event, and a body per case that updates the state and performs the action. + +**Use this when** the state space is small (perhaps ten states) and the transitions are shallow. A switch is easy to read, easy to extend, and the compiler catches missing cases if you enable the right warning flag. + +**Avoid this when** the switch grows to hundreds of lines or the same transition logic is duplicated across several states. That is the signal to move to a table-driven FSM. + +**Common traps.** + +- Forgetting a state. Compile with `-Wswitch-enum` so the compiler tells you. +- Doing non-trivial work inside the switch. Keep the switch as a dispatcher; delegate the real work to named helper functions. + +**Where the book teaches this.** The pattern appears naturally in many driver examples. Chapter 5 introduces it in its simplest form. + +### Table-Driven FSMs + +**What it is.** The state machine expressed as a two-dimensional table indexed by `(state, event)`. Each cell holds the next state and, typically, a function pointer for the action to run on that transition. + +**Use this when** the FSM has many states and many events and you want the transition logic to be data, not code. Visualising the matrix is often easier than chasing a giant switch. Protocol stacks, bus enumeration logic, and suspend-resume state machines are classic uses. + +**Avoid this when** the FSM is small. A five-state switch is easier to read than a five-by-five matrix. + +**Core operations.** Define the state enum, the event enum, and a transition struct containing `next_state` and `action_fn`. Declare the table as a static constant two-dimensional array. The driver steps the machine with `table[current_state][event]`. + +**Common traps.** + +- Null action pointers without a check. Either the table must be dense (every cell is a valid transition) or the dispatcher must treat a null action as "ignore", and the convention must be consistent. +- Embedding locks inside the action functions without a clear discipline. The state transition is a critical section; decide whether the caller holds the lock or the dispatcher takes it, and stick to that. + +### Function-Pointer Dispatch + +**What it is.** A lighter alternative to a full state table. The current "mode" of the driver is a pointer to a set of handler functions; switching state is as simple as reassigning the pointer. + +**Use this when** the "state" is really a set of methods the driver performs differently depending on mode. A link that comes up has a different receive path than a link that is still negotiating. A device that is booting its firmware dispatches commands differently from one that is already running. + +**Avoid this when** the state transitions are ad-hoc or numerous. A function-pointer swap is a coarse operation; reserving it for a few well-named modes keeps the code honest. + +**Common traps.** + +- Racing with the swap. If one CPU calls through the pointer while another is replacing it, the call may dispatch to stale code. The swap needs ordering. In the kernel, that usually means a lock or an RCU-style deferred free via `epoch(9)` for any state structure the old pointer referenced. +- Orphaned resources. When you swap the function-pointer table, make sure the resources the old mode owned are handed off or released cleanly. The switch itself does not free anything. + +### Reentrancy and Partial Completion + +**What it is.** A state-machine design concern rather than a data structure. Real drivers receive events in interleaved order: an interrupt fires while the driver is halfway through processing an ioctl; a completion arrives while the command that triggered it is still being posted; a detach races with an open. The state machine has to tolerate this. + +**Design principles.** + +- Make every transition a single, atomic update. Read current state, compute next state, commit with a lock or an atomic. Do not perform the action before committing the state; if you crash or return early, the state must match reality. +- Separate "what to do" from "who runs it". The state transition decides what needs to happen; a taskqueue or a worker thread actually does the work. That way the transition can finish before the expensive work starts, and a second caller sees consistent state. +- Have a "transient" state for every transition that takes time. A command that is in the act of being sent is neither `IDLE` nor `RUNNING`; it is `SENDING`. A link that is bringing itself down is neither `UP` nor `DOWN`; it is `GOING_DOWN`. Transient states give concurrent callers something to wait for or retry on. + +**Common traps.** Assuming events are serialised. They are not. An interrupt can arrive at any time, a detach can race with an open, a userspace close can race with a device's internal teardown. Build the state machine so that every event is handled from every state, even if the handling is just "reject" or "defer". + +**Where the book teaches this.** Revisited in Chapter 11 (synchronisation), Chapter 14 (interrupts in depth), and Part 5 when real networking drivers hit these cases hard. + +## Error-Handling Patterns + +A driver that gets the happy path right but gets the error path wrong will corrupt memory, leak resources, or panic the kernel. Good error handling in driver code is almost always about structure, not cleverness. The kernel has a strong, uniform idiom for it, and this section names that idiom. + +### The `goto out` Idiom + +**What it is.** The canonical kernel cleanup pattern. At the top of the function, declare every resource to `NULL`. At each acquisition, check the result; on failure, `goto fail_N` where `fail_N` is a label that releases exactly the resources acquired so far. At the end of the function, the success path returns; the cleanup ladder runs in reverse order of acquisition and falls through every label down to the final return. + +**Why drivers use it.** Because it works. The ladder makes it impossible to forget a release, and the order-of-release is visually identical to the reverse of the order of acquisition. The pattern is pervasive in the FreeBSD tree. + +**Use this when** a function acquires more than one resource. Three is usually the threshold where a ladder is cleaner than nested `if`. + +**Avoid this when** the function is simple. A single acquisition, a single release, and a single error path do not need a ladder; a straight-line function with two returns is clearer. + +**The shape.** + +```c +int +my_attach(device_t dev) +{ + struct my_softc *sc; + struct resource *mem = NULL; + void *ih = NULL; + int error, rid; + + sc = device_get_softc(dev); + sc->dev = dev; + + rid = 0; + mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); + if (mem == NULL) { + device_printf(dev, "cannot allocate memory window\n"); + error = ENXIO; + goto fail_mem; + } + + error = bus_setup_intr(dev, sc->irq, INTR_TYPE_MISC | INTR_MPSAFE, + NULL, my_intr, sc, &ih); + if (error != 0) { + device_printf(dev, "cannot setup interrupt: %d\n", error); + goto fail_intr; + } + + sc->mem = mem; + sc->ih = ih; + return (0); + +fail_intr: + bus_release_resource(dev, SYS_RES_MEMORY, rid, mem); +fail_mem: + return (error); +} +``` + +The shape is what matters. Each label releases exactly the resources acquired between it and the start of the function. Falling through is intentional; the labels are stacked in the order a human would read them from the top of the function. + +**Variants.** + +- A single `out:` label with conditional checks (`if (mem != NULL) bus_release_resource(...)`) works for short functions. For long ones, the numbered-label variant is easier to audit because it encodes the order directly. +- Some code names the labels `err_mem`, `err_intr` instead of `fail_mem`, `fail_intr`. The prefix does not matter; consistency within a file does. + +**Common traps.** + +- Freeing in the wrong order. Always free in reverse order of allocation. The ladder's visual order is a reminder, not a proof; review the labels when you add a new resource. +- Initialising pointers to something other than `NULL`. If a ladder conditionally frees, the condition has to be reliable. Uninitialised pointers are undefined; free of uninitialised memory is a panic. +- Returning on the success path with a partial state. The success path at the end should either hand full ownership to the caller or return an error and unwind. There is no third option. + +**Where the book teaches this.** Chapter 5 introduces the pattern explicitly and the book uses it consistently from Chapter 7 onward. + +**What to read next.** Real attach functions under `/usr/src/sys/dev/`. Almost any driver shows the pattern in action. + +### Return-Code Conventions + +**What it is.** The kernel convention: integer return codes where `0` means success and a positive errno value means failure. `1` is not an error; it is a truthy return that would be confusing next to `EPERM` (which is also `1`). Always return `0` on success. + +**Core conventions.** + +- `0` on success, a positive errno (`EINVAL`, `ENOMEM`, `ENXIO`, `EIO`, `EBUSY`, `EAGAIN`) on failure. +- Never return a negative error code. That is a Linux convention and does not match the rest of FreeBSD. +- Propagate error codes upwards unchanged unless you can make them more specific. +- When a function returns a pointer, convention is to return `NULL` on failure and set a separate `int` if the caller needs to distinguish why. +- Probe routines follow a different rule: they return `BUS_PROBE_DEFAULT` and friends on success and `ENXIO` on no-match. See Appendix A for the full list. + +**Common traps.** + +- Returning `-1` from a kernel function. That is a userspace idiom; do not do it in kernel code. +- Overloading a single return value to mean both "an error" and "a resource count". Use a separate output pointer parameter if you need both. +- Swallowing errors. An error code from a lower-level call is a contract; either handle it or propagate it. Returning `0` after a failed `copyin` is how kernel panics are born. + +**Where the book teaches this.** Chapter 5 again, alongside the cleanup ladder. + +### Resource Acquisition and Release Ordering + +**What it is.** The discipline that says: every resource you acquire in attach must be released in detach, in reverse order. Every lock you take must be released along every exit path. Every reference you add must be released before you drop the last one. The cleanup ladder above is a local expression of this principle; the whole driver is a global one. + +**Core principles.** + +- Attach acquires in order A, B, C. Detach releases in order C, B, A. The two are mirror images. +- Every error path inside attach unwinds what has been acquired so far, in reverse. That is the ladder. +- Locks are held for as short a time as possible and released along every exit, including the error paths. A `goto` ladder that unwinds memory but forgets the mutex is still wrong. +- Ownership should be local. One function acquires; the same function releases, or it hands ownership explicitly to the caller. A function that "leaks" ownership to a parameter side-effect is almost always a bug waiting to happen. + +**Where the book teaches this.** Chapter 7 introduces the mirror-image discipline for a first driver, and every driver chapter afterwards repeats it. + +## Concurrency Patterns + +Two threads touching the same state is where kernel bugs are born. The synchronisation primitives in Appendix A are the tools; this section collects the patterns that use those tools well. The goal here is pattern recognition, not a full concurrency course. + +### Producer-Consumer with Condition Variables + +**What it is.** One context produces data (fills a buffer, posts a command, receives a character), and another consumes it. A shared state protected by a mutex, and a condition variable that the consumer waits on when the state is empty. + +**Mental model.** + +- The mutex protects the shared state. That is non-negotiable. +- The consumer checks the state under the mutex. If there is nothing to do, it sleeps on the condition variable via `cv_wait`. `cv_wait` atomically drops the mutex while sleeping and reacquires it on return. +- The producer also holds the mutex while it modifies the state, then signals the condition variable. +- The consumer re-checks the state after waking, because spurious wakeups and shared signals are possible. The check is always a loop, not an `if`. + +**The shape.** + +```c +/* Producer. */ +mtx_lock(&sc->lock); +put_into_buffer(sc, item); +cv_signal(&sc->cv); +mtx_unlock(&sc->lock); + +/* Consumer. */ +mtx_lock(&sc->lock); +while (buffer_is_empty(sc)) + cv_wait(&sc->cv, &sc->lock); +item = take_from_buffer(sc); +mtx_unlock(&sc->lock); +``` + +**Common traps.** + +- Using `if` instead of `while` around `cv_wait`. Spurious wakeups are real; always re-check. +- Signalling without holding the lock. FreeBSD permits it, but it is almost always easier to reason about if you signal while holding the lock. +- `cv_signal` when you meant `cv_broadcast`. `cv_signal` wakes exactly one waiter; if several waiters are waiting on different preconditions, only one of them will be unblocked, possibly the wrong one. +- Sleeping under a spinlock. `cv_wait` is sleepable; you need a normal mutex (`MTX_DEF`), not a spin mutex (`MTX_SPIN`). + +**Where the book teaches this.** Chapter 10 builds the pattern implicitly around the circular buffer; Chapters 11 and 12 formalise it. + +### Reader-Writer: `rmlock(9)` vs `sx(9)` + +**What it is.** Two different read-write locks, with different cost profiles. + +- `sx(9)` is a sleepable shared-exclusive lock. Readers block writers; writers block readers. Both sides may sleep inside the critical section. +- `rmlock(9)` is a read-mostly lock with an extremely cheap reader path (essentially a per-CPU indicator) and a much more expensive writer path (the writer must wait for every reader to drain). + +**Choosing between them.** + +- If reads are frequent, writes are rare, and the reader path must not sleep, choose `rmlock`. +- If reads are frequent, writes are occasional, and the reader path needs to sleep (for example, it calls `copyout`), choose `sx`. +- If reads and writes are roughly balanced or if the critical section is short, neither is right. Use a plain mutex. + +**Core operations.** + +- `sx`: `sx_slock`, `sx_sunlock` for shared; `sx_xlock`, `sx_xunlock` for exclusive; `sx_try_slock`, `sx_try_xlock`. +- `rmlock`: `rm_rlock(rm, tracker)`, `rm_runlock(rm, tracker)` for readers (each reader needs its own `struct rm_priotracker`, typically on the stack); `rm_wlock(rm)`, `rm_wunlock(rm)` for writers. + +**Common traps.** + +- Using `rmlock` for a balanced workload. The writer path is genuinely slow; use it only when reads dwarf writes. +- Letting an `rmlock` reader sleep without initialising with `RM_SLEEPABLE`. The default `rmlock` forbids sleeping in the read path. +- Upgrading a shared lock to an exclusive one. Neither `sx` nor `rmlock` supports a lock-free upgrade. Drop the shared lock, acquire the exclusive one, and re-check state. + +**Where the book teaches this.** Chapter 12. + +### Reference Counting with `refcount(9)` + +**What it is.** A kernel-blessed pattern for counting how many contexts still use an object. An atomic counter, `refcount_acquire` to bump it, `refcount_release` to drop it and return `true` when the count reaches zero (so the caller can free). + +**Why drivers use it.** Whenever an object can outlive the operation that produced it. A `cdev` that is being closed while a read is in flight; a softc whose detach races an ioctl; a buffer passed to hardware that must not be freed until the hardware is done. + +**Use this when** you have shared ownership and no single place that can reliably free the object. If one piece of code unambiguously owns the object, skip the reference count and free it there. + +**Core operations.** `refcount_init(count, initial)`, `refcount_acquire(count)` returning the previous value, `refcount_release(count)` returning `true` if the count reached zero (caller must free). There are `_if_gt` and `_if_not_last` variants for conditional acquisition, and `refcount_load` for read-only inspection. + +**Common traps.** + +- Using `refcount` for resources with a real ownership hierarchy. Refcounts are for genuinely shared ownership, not for laziness about who frees what. +- Freeing before the release. `refcount_release` returning `true` is your permission to free; do it inside that branch, not before. +- Mixing refcounts with locks. Refcount operations are lock-free, but "increment the refcount then dereference" is a race if another thread may drop the last reference between the two steps. The usual fix is to hold a lock while you decide to acquire. + +**Where the book teaches this.** Mentioned in Appendix A, with the concurrency context built up through Chapters 11 and 12. + +**What to read next.** `refcount(9)`, and any subsystem that manages shared lifetime. + +## Decision Aids + +The compact tables below are meant to be glanceable. They are not decision oracles; they are reminders of which family to look inside. The real decision is always local to the problem. + +### Collection Shape + +| You have... | Reach for | +| :-- | :-- | +| A small collection, no ordered lookup | `TAILQ_` or `LIST_` from `` | +| A FIFO queue with no arbitrary removal | `STAILQ_` | +| A collection ordered by a key, grows large | `RB_` from `` | +| A dense universe of boolean flags | `bit_*` from `` | +| Unordered lookup on a large set | `hashinit(9)` plus `LIST_` | +| Prefix-matching networking keys | `radix.h` (you usually do not write this yourself) | + +### Ring Buffer Shape + +| You have... | Reach for | +| :-- | :-- | +| One producer, one consumer, lock-free | SPSC ring with head/tail indices | +| Many producers, many consumers | `buf_ring(9)` | +| Producer is an interrupt, consumer is a thread | SPSC ring plus condition variable or `selrecord` | +| Soft queue with back-pressure to userspace | SPSC ring plus `poll(2)` or `kqueue(2)` integration | + +### State Representation + +| Your state is... | Reach for | +| :-- | :-- | +| A handful of mutually exclusive modes | `enum` plus `switch` | +| Many states, many events, complex transitions | Table-driven FSM | +| Coarse modes that change the driver's methods | Function-pointer dispatch | +| Independent boolean facts | Flag bits in an integer | + +### Cleanup Strategy + +| Your function... | Reach for | +| :-- | :-- | +| Acquires one resource | Single early return, single release | +| Acquires two or three | `goto out:` with conditional `if (ptr != NULL)` | +| Acquires many, order-sensitive | Numbered `goto fail_N:` ladder | +| Has to roll back a mid-way success | Same ladder with explicit "rollback" label | + +### Concurrency Pattern + +| You have... | Reach for | +| :-- | :-- | +| Short critical section, no sleeping | `mtx(9)` with `MTX_DEF` | +| Short critical section in an interrupt filter | `mtx(9)` with `MTX_SPIN` | +| Many readers, occasional writer, may sleep | `sx(9)` | +| Many readers, rare writer, no sleep in readers | `rmlock(9)` | +| One producer, one consumer, waiting on an event | mutex plus `cv(9)` | +| Shared ownership of an object with no single freer | `refcount(9)` | +| A counted resource (pool of slots) | `sema(9)` | +| One-word counter or flag | `atomic(9)` | + +## Wrapping Up: How to Recognise These Patterns in Real Code + +Recognising a pattern in someone else's driver is a different skill from writing the pattern yourself. The easy part is spotting the API: `TAILQ_FOREACH`, `buf_ring_enqueue`, `goto fail_mem`. The harder part is spotting the pattern when the author has not used an API at all, because the pattern is pure control flow. + +Three habits help. + +The first is asking what invariant the author is trying to preserve. A ring buffer preserves "the interrupt and the thread never write the same index". A state machine preserves "we are always in exactly one state". A cleanup ladder preserves "every resource is released exactly once, in reverse order". When you read new code, naming the invariant first gives the rest of the code somewhere to attach to. + +The second is reading the comment at the top of the file. Most FreeBSD drivers include a short block comment explaining the locking discipline, the state machine, or the ring conventions they use. That comment exists precisely because a reader cannot recover it from the code alone. Read it before you read the code, and read it again when the code surprises you. + +The third is letting the patterns in this appendix colonise your vocabulary. When you find yourself writing "the ring buffer", be able to say whether it is SPSC or MPMC, whether the indices are sacrificed-slot or free-running, where the barrier belongs. When you find yourself writing "the state machine", be able to name the states, the events, and the transient states. When you find yourself writing "the cleanup path", be able to list the resources in reverse order of acquisition. The appendix becomes useful once these words come to mind automatically. + +From here you can move in several directions. Appendix A has the detailed API entries for every primitive named above. Appendix C grounds the hardware-side patterns (DMA rings, descriptor arrays, and the discipline of coherency) that sit just below these software ones. Appendix E covers the kernel subsystems that many of these patterns were born inside. And every chapter of the book has labs where these patterns appear in a working driver, so that the next time you meet one in the wild you recognise it without slowing down. That is all pattern recognition really is: the confidence to keep reading. diff --git a/content/appendices/appendix-c.md b/content/appendices/appendix-c.md index b4d273c..d9e9d38 100644 --- a/content/appendices/appendix-c.md +++ b/content/appendices/appendix-c.md @@ -1,13 +1,475 @@ --- title: "Hardware Concepts for Driver Developers" -description: "Essential hardware concepts and terminology for device driver development" +description: "A concept-level field guide to the memory, buses, interrupts, and DMA ideas that recur throughout FreeBSD device-driver development." appendix: "C" -lastUpdated: "2025-08-01" -status: "planned" +lastUpdated: "2026-04-20" +status: "complete" author: "Edson Brandi" reviewer: "TBD" translator: "TBD" estimatedReadTime: 30 --- -planned +# Appendix C: Hardware Concepts for Driver Developers + +## How to Use This Appendix + +The main chapters teach the driver-facing side of FreeBSD: how to write a softc, how to declare a `cdev`, how to set up an interrupt, how to walk a PCI BAR into a `bus_space` handle, how to tame a DMA engine with `bus_dma(9)`. Underneath every one of those topics there is a quiet layer of hardware knowledge that the book keeps using without always naming. What a physical address really is. Why the CPU cannot simply read a device register through an ordinary pointer. Why PCI and I2C feel like completely different worlds even though both carry bytes between a CPU and a peripheral. Why an interrupt is not a function call. Why DMA changes how you write a driver from top to bottom. + +This appendix is that quiet layer, written down. It is a concept guide, not an electronics textbook. It is shaped by what a driver author actually needs to believe about the machine in order to write correct code, and deliberately stops short of full computer-architecture teaching. If you have ever written a `bus_space_read_4` call and wondered what the tag and the handle really represent, or set up an MSI-X vector and wondered what is being signalled across which wires, or debugged a DMA transfer that worked on your desk and broke on a different board, you are in the right place. + +### What You Will Find Here + +The appendix is organised by driver relevance, not by abstract hardware taxonomy. Each topic follows the same compact rhythm: + +- **What it is.** One or two sentences of plain definition. +- **Why this matters to driver writers.** The concrete place where the concept shows up in your code. +- **How this shows up in FreeBSD.** The API, header, or convention that names the idea. +- **Common trap.** The misunderstanding that actually costs people time. +- **Where the book teaches this.** A pointer back to the chapter that uses it in context. +- **What to read next.** A manual page, a header, or a real driver you can open. + +Not every topic uses every label; the shape is a guide, not a template. + +### What This Appendix Is Not + +It is not a first course in electronics. It assumes you can accept "a wire carries a signal" and move on. It is not a computer-architecture textbook either; there is no discussion of pipelines, caches beyond what a driver author must know, or branch prediction. It is not a replacement for the focused chapters: Chapter 16 teaches `bus_space(9)`, Chapter 18 teaches PCI, Chapter 19 teaches interrupts, Chapter 20 teaches MSI and MSI-X, and Chapter 21 teaches DMA in depth. This appendix is what you keep open beside those chapters when you want a mental-model anchor instead of a full walkthrough. + +It also does not overlap with the other appendices. Appendix A is the API reference; Appendix B is the algorithmic-pattern field guide; Appendix D is the operating-systems-concepts companion; Appendix E is the kernel-subsystem reference. If the question you want answered is "what does this macro call do" or "what algorithm fits this problem" or "how does the scheduler schedule", you want a different appendix. + +## Reader Guidance + +Three ways to use this appendix, each calling for a different strategy. + +If you are **learning the main chapters**, open the appendix alongside them. When Chapter 16 mentions memory barriers, flip to the memory section here. When Chapter 18 talks about BARs, flip to the PCI section. When Chapter 19 introduces edge versus level triggering, flip to the interrupt section. The appendix is designed to be a mental-model companion, not a linear read. Thirty minutes from start to finish is realistic for a first pass; a few minutes at a time is more common in daily use. + +If you are **reading real driver code**, use the appendix as a translator for unfamiliar terminology. When the header comment says "coherent DMA memory" or "message-signalled interrupt" or "BAR at offset 0x10", find the concept here and keep going. Full understanding can come later; the first job is to form a mental picture of what the driver is doing against what kind of hardware. + +If you are **designing a new driver**, read the sections that match your hardware. A PCI NIC will touch the memory model, PCI, interrupts (probably MSI-X), and DMA, so those four sections are your warm-up. An I2C sensor will touch the I2C section and the interrupt section and almost nothing else. An embedded driver on a system-on-chip will touch everything except PCI. Match the hardware to the sections, then skim only those. + +A few conventions apply throughout: + +- Source paths are shown in the book-facing form, `/usr/src/sys/...`, matching a standard FreeBSD system. You can open any of them on your lab machine. +- Manual pages are cited in the usual FreeBSD style. The kernel-facing pages live in section 9: `bus_space(9)`, `bus_dma(9)`, `pci(9)`, `malloc(9)`, `intr_event(9)`. Device overviews usually live in section 4: `pci(4)`, `usb(4)`, `iicbus(4)`. +- When an entry points to real source as reading material, the file is one a beginner can navigate in one sitting. Larger subsystems exist that also use the pattern; those are mentioned only when they are the canonical example. + +With that in mind, we start with memory: the single concept that separates a working driver from a puzzling one. + +## Memory in the Kernel + +A driver that misunderstands memory will write perfect-looking code that crashes on real hardware. Memory in the kernel is not the same as memory in a C tutorial. There are at least two address spaces in play (physical and virtual), there are constraints the hardware enforces (DMA addressing limits, page boundaries), and there are regions where even an ordinary read has side effects (device registers). This section builds the mental model that every later topic in the appendix depends on. + +### Physical vs Virtual Memory + +**What it is.** A physical address is the number the memory controller uses to select a real location in RAM, or the number the I/O fabric uses to select a register on a peripheral. A virtual address is the number a running thread sees when it dereferences a pointer; the memory-management unit (MMU) translates it to a physical address on the fly, using the page tables that the kernel maintains. + +**Why this matters to driver writers.** Every pointer in your driver is virtual. The CPU never sees a physical address when it executes your C code. The kernel and the `pmap(9)` layer keep the page tables so that kernel virtual addresses map to wherever in physical memory the kernel has decided to put the corresponding pages. A driver that "knows" a physical address cannot simply cast it to `(void *)` and dereference; the translation might not exist, the permissions might forbid it, or the attributes might be wrong for the kind of access you need. + +Hardware is on the opposite side of the mirror. A peripheral device lives somewhere in a physical address space (its registers are physical addresses, and when it does DMA it emits physical addresses on the bus). A device never dereferences a virtual pointer. If your driver hands the device a kernel virtual address and expects it to read the data there, the device will read some unrelated physical location and you will spend a long afternoon figuring out why. + +**How this shows up in FreeBSD.** Two places. First, `bus_space(9)` encodes the translation for register access: a tag describes the kind of physical address space, a handle describes the virtual mapping the kernel has set up, and the `bus_space_read_*` and `bus_space_write_*` accessors use the handle to reach the device through that mapping. Second, `bus_dma(9)` mediates DMA: the `bus_dmamap_load` call walks a buffer and produces the list of bus addresses the device should use, which are not necessarily the same as either the virtual addresses or the physical addresses, because an IOMMU may sit in between. + +**Common trap.** Casting a physical address returned by firmware or a BAR register to a pointer and reading from it directly. On some architectures and some builds this compiles and may even return something, but it is never correct. Always map through `bus_space`, `pmap_mapdev`, or an established FreeBSD API. + +**Where the book teaches this.** Chapter 16 establishes the distinction and shows why raw pointer arithmetic is not enough for device memory. Chapter 21 returns to it when DMA makes the physical side visible. + +**What to read next.** `bus_space(9)`, `pmap(9)`, and the early parts of `/usr/src/sys/kern/subr_bus_dma.c`. + +### The MMU, Page Tables, and Device Mappings + +**What it is.** The MMU is the hardware unit that translates virtual addresses into physical addresses using a tree of page tables. Each page-table entry holds a physical page number and a small set of attribute bits: readable, writable, executable, cacheable, user-accessible. The same physical page can be mapped at several virtual addresses with different attributes; the same virtual address can point at different physical pages at different times. + +**Why this matters to driver writers.** Device memory is not ordinary RAM, and the CPU must know that. A register may change on its own (a status bit that sets when the device finishes a transfer), it may have side effects on read (a read-to-clear flag), and it may require that writes become visible in a specific order. If the CPU caches a device register the way it caches an integer in RAM, the code reads a stale value forever. The MMU solves this by letting the kernel map device regions with different attributes: typically uncached, strongly ordered, and sometimes write-combining. A driver does not usually choose those attributes by hand. `bus_space` and `bus_alloc_resource` do it on your behalf. + +**How this shows up in FreeBSD.** When `bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE)` returns, the kernel has already mapped the device region with the right attributes for MMIO. The `struct resource *` you get back carries a `bus_space_tag_t` and `bus_space_handle_t` pair that the accessors use. You should never manipulate the underlying page table yourself. In practice the access is two lines: + +```c +uint32_t val = bus_space_read_4(rman_get_bustag(res), + rman_get_bushandle(res), STATUS_REG_OFFSET); +``` + +Each `bus_space_read_4` / `bus_space_write_4` call goes through the MMIO mapping the kernel set up for you; no pointer dereference, no cached load. + +**Common trap.** Mixing cacheable and uncacheable views of the same physical region. A DMA buffer allocated with `bus_dmamem_alloc` and then cast to a different virtual mapping will give you two incoherent views of the same bytes. Use the mapping the allocator returned, not a mapping you build on the side. + +**Where the book teaches this.** Chapter 16 touches the MMU indirectly when it explains why the `bus_space` abstraction exists. Chapter 21 makes it explicit when DMA coherence becomes the topic. + +**What to read next.** `pmap(9)`, `bus_space(9)`, and `/usr/src/sys/vm/vm_page.h` for the kernel's representation of a physical page (`vm_page_t`). + +### Why Hardware Cannot Simply See Kernel Pointers + +**What it is.** A short way of stating the most important consequence of the previous two subsections. The kernel lives in virtual memory. Peripherals live in physical (and sometimes I/O-virtual) memory. A kernel pointer has no meaning to a device. + +**Why this matters to driver writers.** Every time you give a device a memory address, you must give it a bus address, not a virtual pointer. The bus address is what the device sees; it may be the physical address, or it may be an I/O-virtual address remapped by an IOMMU. You do not compute it yourself. The DMA infrastructure computes it for you when you load a map. + +**How this shows up in FreeBSD.** `bus_dmamap_load` takes a virtual buffer and produces `bus_dma_segment_t` entries whose `ds_addr` is the address the device must use. You copy that value into the descriptor you are about to hand the hardware. The moment you find yourself wanting to pass the output of `vtophys` or a raw BAR value to the device, stop and reach for `bus_dma` instead. + +**Common trap.** Writing `(uint64_t)buffer` into a device descriptor because it works in a toy test on one machine. It will fail on any machine where the kernel address is not the same as the bus address, which is most real machines. + +**Where the book teaches this.** Chapter 21. The whole chapter is about honouring this separation. + +**What to read next.** `bus_dma(9)`, and the DMA section below. + +### Kernel Memory Allocation in One Page + +The kernel provides three main ways to get memory, each with a different purpose. Drivers reach for them constantly, and picking the wrong one is a classic beginner mistake. The point here is the conceptual difference; the full API reference is in Appendix A. + +- **`malloc(9)`** is the general-purpose allocator. It returns kernel-virtual memory that is perfectly fine for softc structures, lists, command buffers for your own bookkeeping, and anything else that stays inside the driver's data. It is not automatically physically contiguous, and it is not automatically suitable for DMA. Use it for control data. + +- **`uma(9)`** is the zone allocator. It is a fast cache for fixed-size objects that the driver allocates and frees often, such as per-request structures or per-packet state. It is a specialisation of general-purpose allocation; it does not change the physical-vs-virtual story. + +- **`contigmalloc(9)`** returns a physically contiguous range, with options for alignment and an upper address limit. A driver calls it directly only when it truly needs a single contiguous physical block and the `bus_dma` layer is not a better fit. In modern drivers, `bus_dma` almost always is the better fit. The call shape is telling on its own: + + ```c + void *buf = contigmalloc(size, M_DEVBUF, M_WAITOK | M_ZERO, + 0, BUS_SPACE_MAXADDR, PAGE_SIZE, 0); + ``` + + The `low`, `high`, `alignment`, and `boundary` arguments are exactly the DMA constraints a `bus_dma_tag_create` call would express, which is why `bus_dma(9)` is almost always the better place to encode them. + +- **`bus_dmamem_alloc(9)`** is the DMA-aware allocator. It returns a buffer that is usable for DMA under a given tag, properly aligned, optionally coherent, and paired with a `bus_dmamap_t` you can load. This is the call you want in almost every DMA scenario. + +**Why this matters to driver writers.** The question to ask yourself is always "who is going to read or write this memory?". If only the CPU ever touches it, `malloc(9)` is fine. If the device needs to read or write it, you want `bus_dmamem_alloc(9)` under a `bus_dma(9)` tag that expresses the device's addressing constraints. Mixing the two is the source of an entire genus of driver bugs. + +**Common trap.** Allocating a buffer with `malloc(9)`, handing its virtual address to the device, and wondering why the device reads garbage. The fix is rarely to patch around the symptoms; it is to rewrite the allocation through `bus_dma(9)`. + +**Where the book teaches this.** Chapter 5 introduces `malloc(9)` in a kernel-C context, and the driver chapters from Chapter 7 onward use it repeatedly for softc and bookkeeping memory. Chapter 21 introduces `bus_dmamem_alloc`. Appendix A lists the full API and flags. + +**What to read next.** `malloc(9)`, `contigmalloc(9)`, `uma(9)`, `bus_dma(9)`. + +### IOMMUs and Bus Addresses + +**What it is.** An IOMMU is a hardware unit (sometimes the `amdvi` or `intel-iommu` unit; on ARM, the SMMU) that sits between devices and main memory and translates the addresses devices emit into physical addresses. It is the device-side analogue of the MMU. + +**Why this matters to driver writers.** When an IOMMU is present, the address the device uses on the bus (a bus address or I/O-virtual address) is not the same as the physical address of the underlying memory. The IOMMU lets the kernel give each device a restricted view of memory, which is good for safety and isolation, and it lets the kernel use scatter-gather where the device would otherwise demand contiguous physical pages. + +**How this shows up in FreeBSD.** Transparently, for most drivers. When the kernel is built with the `IOMMU` option and one of the architecture backends (the Intel and AMD drivers under `/usr/src/sys/x86/iommu/` on amd64, the SMMU backend under `/usr/src/sys/arm64/iommu/` on arm64), the `busdma_iommu` layer in `/usr/src/sys/dev/iommu/` bridges `bus_dma(9)` and the IOMMU automatically, without changing the driver's code. You still allocate a tag, create a map, load the map, and read the `ds_addr` of each segment; the number you get is the address the device should use, IOMMU or not. You do not need to know whether an IOMMU is present. + +**Common trap.** Assuming `ds_addr` is a physical address and logging it that way. On IOMMU systems the number is an I/O-virtual address and will not match anything you see in `/dev/mem`. The right mental model is "the address the device uses", not "the physical address". + +**Where the book teaches this.** Chapter 21 mentions IOMMU integration briefly and sticks to the common case where `bus_dma` hides it. + +**What to read next.** `bus_dma(9)`, `/usr/src/sys/dev/iommu/busdma_iommu.c` for the bridge code, and `/usr/src/sys/x86/iommu/` or `/usr/src/sys/arm64/iommu/` for the per-architecture backends. + +### Memory Barriers in One Paragraph + +On modern CPUs, memory operations may become visible to other agents (other CPUs, other devices) in an order different from the one in which the code issued them. For ordinary RAM the kernel's locking primitives hide this from you. For device registers, though, ordering matters: writing to a "start" register before writing to the "data" register produces a different outcome from the reverse. The kernel provides explicit barriers for both sides. For register access, `bus_space_barrier(tag, handle, offset, length, flags)` is the right tool; for DMA buffers, `bus_dmamap_sync(tag, map, op)` is the right tool. You will meet both again later in this appendix. For now, internalise the rule: when the order of two accesses matters to the hardware, say so with a barrier. Do not rely on the code order alone. + +## Buses and Interfaces + +A bus is a physical and logical pathway that carries commands, addresses, and data between a CPU and peripherals. FreeBSD treats every bus as a specialised tree in the Newbus framework: the bus has a driver that enumerates its children, each child is a `device_t`, and each child can in turn be a bus for further children. The concept of "a bus" is uniform at the Newbus level. The concepts of "the electrical, protocol, and enumeration rules of a particular bus" are not uniform at all, and a driver author must understand which one they are writing for. + +This section gives the mental models for the four buses the book cares about: PCI (and PCIe), USB, I2C, and SPI. Their chapters are later; this is the shared vocabulary you need first. + +### PCI and PCIe at a Driver-Relevant Level + +**What it is.** PCI is the canonical bus for attaching peripherals to a CPU complex. Classical PCI was parallel and shared; modern PCI Express is a set of point-to-point serial lanes that a switch fabric organises into a tree. From a driver's perspective, the electrical difference is mostly invisible: you still see a configuration space, you still see Base Address Registers, you still see interrupts, and you still write probe-and-attach code. Unless stated otherwise, "PCI" in this book means "PCI and PCIe together". + +A PCI device is identified by a Bus:Device:Function (B:D:F) tuple and by a configuration space that the firmware and the kernel populate. The configuration space holds the vendor and device identifiers, the class code that describes what kind of peripheral this is, the Base Address Registers (BARs) that describe the device's memory and I/O windows, and a linked list of capability structures that advertise optional features like MSI, MSI-X, and power management. + +**Why this matters to driver writers.** Every PCI driver does roughly the same dance. Read `pci_get_vendor(dev)` and `pci_get_device(dev)` during `probe`, compare them to a table of devices the driver supports, return a `BUS_PROBE_*` value on a match. In `attach`, allocate each BAR with `bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE)`, pull the `bus_space_tag_t` and `bus_space_handle_t` out with `rman_get_bustag` and `rman_get_bushandle`, allocate the interrupt with `bus_alloc_resource_any(dev, SYS_RES_IRQ, ...)` (or `pci_alloc_msix`/`pci_alloc_msi` for message-signalled interrupts), wire the handler with `bus_setup_intr`, and you are in business. + +Capabilities are where the PCI driver meets the features of the specific device family. `pci_find_cap(dev, PCIY_MSIX, &offset)` finds the MSI-X capability; `pci_find_extcap(dev, PCIZ_AER, &offset)` finds the extended capability for Advanced Error Reporting. A driver usually only walks the capabilities it cares about. + +**How this shows up in FreeBSD.** The PCI bus driver lives under `/usr/src/sys/dev/pci/`. The key header is `/usr/src/sys/dev/pci/pcireg.h` for register constants and `/usr/src/sys/dev/pci/pcivar.h` for functions a client driver calls. Every PCI driver you will write starts with a `device_probe_t` and a `device_attach_t`, with `DRIVER_MODULE(name, pci, driver, 0, 0)` at the bottom of the file. The last two arguments are the per-module event handler and its argument, which are normally left as `0, 0` (or `NULL, NULL`); the separate `devclass_t` slot that older books mention was removed from the macro some releases ago. + +**Common trap.** Forgetting to call `pci_enable_busmaster(dev)` before expecting the device to DMA. The chip can live in a quiet state where MMIO works and DMA silently does nothing. Enabling bus-mastering in `attach` is part of the usual sequence. + +**Where the book teaches this.** Chapter 18 is the full chapter on PCI driver writing. Chapter 20 extends it with MSI-X. + +**What to read next.** `pci(4)`, `pci(9)`, and a compact real example such as `/usr/src/sys/dev/uart/uart_bus_pci.c`. The PCI bus itself is implemented in `/usr/src/sys/dev/pci/pci.c`. + +### USB at a Driver-Relevant Level + +**What it is.** USB is a host-controlled tiered bus, in which a host controller talks to devices through a tree of hubs. Unlike PCI, the bus is strictly hierarchical and polling-like: the host schedules every transaction. A device does not "speak" on the bus without being asked. USB speed classes (low, full, high, super) share the same conceptual model; the protocol details change. + +A USB device exposes a set of endpoints. Each endpoint is a one-way data channel with a specific transfer type: control, bulk, interrupt, or isochronous. Control is the setup channel every device has. Bulk is high-throughput with no timing guarantees. Interrupt is small, periodic, low-latency (mice, keyboards, sensors). Isochronous is real-time streaming (audio, video) that trades reliability for timing. + +**Why this matters to driver writers.** A FreeBSD USB driver attaches to a `device_t` whose parent is a USB bus, not a PCI bus. The identification model is different: instead of vendor/device IDs and class codes in configuration space, a USB driver matches on a USB Vendor ID (VID), Product ID (PID), device class, subclass, and protocol. The FreeBSD USB stack gives you a structured probe against those fields. At run time, a USB driver opens specific endpoints through the USB framework and issues transfers whose lifetime is managed by the host controller; you do not write to registers the way a PCI driver does. + +**How this shows up in FreeBSD.** The USB stack lives under `/usr/src/sys/dev/usb/`. A class driver uses `usbd_transfer_setup` to describe the endpoints it wants, `usbd_transfer_start` to initiate transfers, and callback functions to handle completion. Transfer-type constants live in `/usr/src/sys/dev/usb/usb.h` (`UE_CONTROL`, `UE_ISOCHRONOUS`, `UE_BULK`, `UE_INTERRUPT`). + +**Common trap.** Thinking in terms of registers and interrupts. A USB device driver is event-driven around transfer completion callbacks, not around device-register reads. A register-oriented mindset leads to fighting the framework instead of using it. + +**Where the book teaches this.** Chapter 26 is the full chapter on USB and serial drivers. This appendix is the concept-level primer; the chapter is where your first USB driver lives. + +**What to read next.** `usb(4)`, `usbdi(9)`, and the headers under `/usr/src/sys/dev/usb/`. + +### I2C at a Driver-Relevant Level + +**What it is.** I2C (Inter-Integrated Circuit) is a slow, two-wire, master-slave bus designed to connect low-bandwidth peripherals on a board: temperature sensors, power management controllers, EEPROMs, small displays. Each slave has a seven-bit or ten-bit address. A master initiates every transaction by asserting a start condition, sending the address, sending or receiving bytes, and asserting a stop condition. + +Speeds are typically 100 kHz (standard), 400 kHz (fast), 1 MHz (fast-plus), and higher variants on newer devices. The bus supports multiple masters, but most embedded systems use a single master; in that case the driver only has to worry about the master-to-slave interaction. + +**Why this matters to driver writers.** An I2C driver in FreeBSD comes in two flavours. An I2C *controller* driver implements the master side of a specific controller chip and hangs under the Newbus tree as an I2C bus. An I2C *device* driver is a client that uses the `iicbus` layer to talk to a slave device without knowing the controller details. The second form is what most driver authors write. You ask `iicbus_transfer` to perform a short sequence of `struct iic_msg` operations, and the `iicbus` layer takes care of arbitration and timing. + +There are no interrupts or BARs to allocate in the client driver. There is no DMA. Each transfer is short and blocking, typically a few bytes; long reads are broken into a series of transfers. + +**How this shows up in FreeBSD.** The framework lives under `/usr/src/sys/dev/iicbus/`. The client interface centres on `iicbus_transfer(dev, msgs, nmsgs)` and the `struct iic_msg` type. FreeBSD discovers I2C buses through FDT on embedded platforms and ACPI on x86 laptops that expose an I2C controller. + +**Common trap.** Writing an I2C driver that busy-waits. Even at 1 MHz, a transfer is several tens of microseconds; a driver that pins a CPU through a polling loop wastes resources. The `iicbus` layer handles the waiting for you. + +**Where the book teaches this.** The book does not dedicate a full chapter to I2C; this appendix is the primary concept treatment, and the embedded chapter (Chapter 32) revisits it in the context of device-tree bindings. For a concrete client you can read front-to-back, open `/usr/src/sys/dev/iicbus/icee.c`. + +**What to read next.** `iicbus(4)`, `/usr/src/sys/dev/iicbus/iicbus.h`, and an example client such as `/usr/src/sys/dev/iicbus/icee.c` (an EEPROM driver). + +### SPI at a Driver-Relevant Level + +**What it is.** SPI (Serial Peripheral Interface) is a simple, fast, full-duplex, master-slave bus. It has no addressing in the bus itself; each slave has a dedicated chip-select line, and the master asserts that line to begin a transaction. Four wires are typical: SCLK (clock), MOSI (master-out slave-in), MISO (master-in slave-out), and SS/CS (slave-select). Speeds commonly range from a few MHz to tens of MHz. + +Unlike I2C, SPI has no protocol beyond the electrical one: the master shifts bits out on MOSI while simultaneously shifting bits in on MISO. What those bits mean is entirely up to the device. + +**Why this matters to driver writers.** As with I2C, FreeBSD separates the controller from the client. A controller driver knows how the SPI master in a particular chip is programmed; a client driver uses the `spibus` interface to send and receive bytes without knowing the controller. The client calls `spibus_transfer` or `spibus_transfer_ext` with a `struct spi_command` that describes a single transaction, including the chip-select to assert and the buffers to shift. + +**How this shows up in FreeBSD.** The framework lives under `/usr/src/sys/dev/spibus/`. The typical client driver hangs under an `spibus` parent in Newbus and uses the same probe/attach shape as any other device. `/usr/src/sys/dev/spibus/spigen.c` is a generic character-device client that exposes raw SPI to userland; reading it is a good way to see the client side of the framework. + +**Common trap.** Expecting SPI to carry data with any built-in framing. It does not. The device datasheet tells you what bytes mean; the bus tells you nothing. + +**Where the book teaches this.** The book does not dedicate a full chapter to SPI; this appendix is the primary concept treatment, and the embedded chapter (Chapter 32) revisits it in the context of device-tree bindings. For a concrete example you can read front-to-back, open `/usr/src/sys/dev/spibus/spigen.c`. + +**What to read next.** `/usr/src/sys/dev/spibus/spibus.c`, `/usr/src/sys/dev/spibus/spigen.c`, and the device datasheet for whatever SPI peripheral you are driving. + +### A Compact Comparison of the Four Buses + +A small reference is often easier than a long description. This table compares the buses along the axes that actually affect driver design. It is not a full electrical comparison. + +| Aspect | PCI / PCIe | USB | I2C | SPI | +| :-- | :-- | :-- | :-- | :-- | +| Topology | Tree (PCIe switches) | Strict host/hub tree | Multi-drop, addressed | Multi-drop, chip-select | +| Typical speed | Gigabytes/s per lane | Kilobytes/s to gigabytes/s | 100 kHz - 1 MHz | 1 MHz - tens of MHz | +| Identification | Vendor/Device + class | VID/PID + class | 7- or 10-bit slave address | None (chip-select) | +| Protocol framing | PCI TLPs, invisible | Packets + transfer types | Start/address/data/stop | Raw bits | +| Interrupts | INTx or MSI / MSI-X | Transfer callbacks | Rare; bus is polled | Rare; bus is polled | +| DMA | Yes, device-driven | Host controller does it | No | No | +| Driver role | Register-level | Framework client | `iicbus` client | `spibus` client | +| Enumeration | Firmware + `pci(4)` | Hub/device descriptors | FDT / ACPI / hand-wired | FDT / ACPI / hand-wired | + +The pattern you should take away is that PCI and USB are complex enough to need their own enumeration stacks and transaction machinery, while I2C and SPI are simple enough that a short transaction struct is the whole API. A driver author's workload looks different on each side of that split. + +## Interrupts + +An interrupt is how a device tells the CPU that something has happened. Without interrupts, drivers would have to poll, burning CPU cycles to discover events the hardware already knows about. With interrupts, the CPU does other work until the hardware signals; then the kernel dispatches a handler in a narrow, well-defined context. This section explains what that signal actually is, what distinguishes the common forms, and why interrupt discipline is one of the most demanding skills in driver work. + +### What an Interrupt Actually Is + +**What it is.** At the hardware level, an interrupt is a signal the device raises to request CPU attention. On classical parallel buses, the signal is a line that the device pulls high or low. On modern PCIe, the signal is a memory-write transaction carrying a small payload that the interrupt controller recognises. In both cases, the interrupt controller maps the signal to a CPU vector, the CPU saves just enough state to switch context, and the kernel's low-level entry code decides which driver to call. + +What the driver sees is a function call: the interrupt handler runs with a small stack, in a special scheduling context, usually with preemption disabled or highly constrained. The hardware model is "a device raised a line"; the software model is "the kernel ran your callback". + +**Why this matters to driver writers.** Interrupts are not ordinary function calls. They happen asynchronously, possibly on a different CPU from the one your driver is running on, and they can arrive in the middle of almost any code path. That is why interrupt handlers must be short, must avoid sleeping, and must not touch shared state without a lock that is safe in that context. Most of the discipline a driver learns about locking, ordering, and deferred work exists because of this one fact. + +**How this shows up in FreeBSD.** Interrupts reach drivers through `intr_event(9)`. A driver calls `bus_setup_intr(dev, irq_resource, flags, filter, ithread, arg, &cookie)` to register up to two callbacks: a *filter* that runs first, in interrupt context, with only spin locks available, and optionally an *ithread* (interrupt thread) that runs as a kernel thread and may use sleep locks. The filter's return value decides what happens next: `FILTER_HANDLED` (fully handled, acknowledge at the controller), `FILTER_STRAY` (not mine, do nothing), or `FILTER_SCHEDULE_THREAD` (the ithread should run now). Those constants live in `/usr/src/sys/sys/bus.h`. + +**Common trap.** Doing real work in the filter. The filter is there to decide ownership, acknowledge the device quickly if possible, and either handle a trivially small amount of work or schedule the thread. Long processing belongs in the ithread or on a taskqueue, not in the filter. + +**Where the book teaches this.** Chapter 19 is the dedicated chapter on interrupts. Chapter 20 adds MSI and MSI-X. Chapter 14 (taskqueues) explains how to defer heavy work out of the interrupt path. + +**What to read next.** `intr_event(9)`, `bus_setup_intr(9)`, and the filter/ithread documentation in `/usr/src/sys/sys/bus.h` around the `FILTER_` and `INTR_` constants. + +### Edge-Triggered vs Level-Triggered + +**What it is.** Two ways the hardware signal can mean "there is something new". + +- **Edge-triggered.** The device asserts a transition (a rising or falling edge) to signal an event. If the driver does not record that an interrupt happened, the event is lost. The edge is a moment, not a state. +- **Level-triggered.** The device holds the line (or the signal) active as long as the condition persists. The interrupt controller keeps firing until the driver acknowledges the device and the line deasserts. The level is a state, not a moment. + +**Why this matters to driver writers.** Edge-triggered interrupts are unforgiving: if the driver has a race and a second edge arrives while the first is being processed without being recorded, the second event is forgotten. Level-triggered interrupts are self-healing: if the line is still asserted when you return, the controller will fire again. Legacy PCI INTx lines are level-triggered and shared, which is why driver handlers must read the device's status register and check whether "this interrupt" is really theirs before claiming it. MSI and MSI-X are effectively edge-like: each message is a discrete event. + +**How this shows up in FreeBSD.** The distinction is mostly handled below your driver. Legacy INTx registration with `SYS_RES_IRQ` and rid `0` gets you level-triggered, shared interrupts; `pci_alloc_msi` and `pci_alloc_msix` give you message-signalled interrupts that are per-vector and not shared with unrelated drivers. Your filter still has to behave well; but the sharing concern goes away. + +**Common trap.** Writing a filter that returns `FILTER_HANDLED` without actually checking the device. On level-triggered INTx, this hangs the system because the line stays asserted and the controller fires forever. + +**Where the book teaches this.** Chapter 19 teaches the classical case; Chapter 20 teaches the message-signalled case. + +**What to read next.** The legacy interrupt discussion in `/usr/src/sys/dev/pci/pci.c` around `pci_alloc_msi`, and the filter examples in Chapter 19. + +### MSI and MSI-X Without the Acronyms + +**What it is.** Message-Signalled Interrupts. Instead of asserting a shared interrupt line, a PCI Express device sends a small memory-write transaction to a special address that the interrupt controller watches. The payload of the write identifies which interrupt has fired. MSI supports a handful of vectors per device (typically up to 32); MSI-X supports thousands, each with its own address and data, and per-vector CPU affinity. + +**Why this matters to driver writers.** Two things change when a driver uses MSI or MSI-X instead of legacy INTx. First, the interrupts are no longer shared, so the filter does not need to coexist with unrelated drivers (it still has to confirm the event came from its own hardware). Second, you can have more than one interrupt per device. A NIC can have one interrupt per receive queue, another per transmit queue, another for the management path, and you can bind each one to a different CPU. That changes how you structure the driver: each queue has its own softc substructure, its own lock, and its own handler. + +**How this shows up in FreeBSD.** `pci_msi_count(dev)` and `pci_msix_count(dev)` tell you how many vectors are available. `pci_alloc_msi(dev, &count)` and `pci_alloc_msix(dev, &count)` reserve them; the call updates `count` with the number actually allocated. You then allocate each vector with `bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE)` using `rid = 1, 2, ..., count`. CPU affinity is set with `bus_bind_intr(dev, res, cpu_id)`. Teardown mirrors the sequence: per-vector `bus_teardown_intr` and `bus_release_resource`, then a single `pci_release_msi(dev)`. + +**Common trap.** Requesting too many vectors and assuming the system will give them all. `pci_alloc_msix` may return fewer than requested, even on hardware that advertises plenty; the driver must adapt its queue structure to the number actually allocated. A fallback ladder (MSI-X, then MSI, then INTx) is the standard shape. + +**Where the book teaches this.** Chapter 20. + +**What to read next.** `pci(9)` for the function list, and `/usr/src/sys/dev/pci/pci.c` for the implementation. + +### Why Interrupt Discipline Matters + +**What it is.** The set of rules that keep a driver correct under interrupts. Most of it follows from three facts: the filter runs with very few primitives available, the filter can race with every other path in the driver, and late acknowledgement produces wedged systems. + +**Core rules.** + +- Keep the filter short and allocation-free. No `malloc`, no sleeping, no calls that might sleep, no complex logic. +- Acknowledge at the device before returning `FILTER_HANDLED`, or make sure the device continues to assert until your ithread runs. +- Use spin locks (`MTX_SPIN`) to protect state the filter and a CPU path share. Sleep locks cannot be taken in the filter. +- Defer real work to an ithread, a taskqueue, or a callout. The filter's job is to move data off the critical path. +- Count your interrupts. A `sysctl` counter per vector is cheap and often the first clue when the driver misbehaves. + +**Common trap.** Holding a sleep lock across a path that could be re-entered from the filter. A thread that owns a sleep mutex cannot be preempted by an interrupt on the same CPU; the kernel's `witness(9)` diagnostic will catch many of these before production, but only if the scenario is actually exercised. + +**Where the book teaches this.** Chapter 11 introduces the discipline in general; Chapter 19 makes it concrete for real hardware. + +**What to read next.** The locking summary in Appendix A and the filter/ithread split in `/usr/src/sys/sys/bus.h`. + +## DMA + +DMA (Direct Memory Access) is how a peripheral reads or writes memory without the CPU copying every byte. It exists because the alternative (the CPU reading a register, placing the byte in RAM, and looping) is too slow for any modern device. DMA is also the most hardware-aware part of a driver, because it is where the driver must speak the bus's address language instead of the kernel's virtual-pointer language. A driver that is not disciplined about DMA will produce data corruption that is almost impossible to diagnose from user space. + +### What DMA Is and Why It Exists + +**What it is.** A transfer in which the device reads from or writes to system memory under its own control, using bus addresses the driver has handed it in advance. The CPU sets up the transfer and goes on with other work; the device signals completion, usually by raising an interrupt. There is no per-byte CPU involvement during the data movement itself. + +**Why this matters to driver writers.** Everything about how you allocate, load, synchronise, and release memory changes the moment DMA enters the picture. You no longer own the buffer exclusively; the device owns it during the transfer. You must tell the kernel which parts of the buffer are being read or written and when, so that cache coherence, alignment, and address remapping can be handled correctly. + +**How this shows up in FreeBSD.** `bus_dma(9)` is the whole machinery. The driver author's workflow is consistent across every DMA-capable device: + +1. Create a `bus_dma_tag_t` in `attach`, describing the device's addressing constraints (alignment, boundary, `lowaddr`, `highaddr`, maximum segment size, number of segments, and so on). The tag captures the device's truth. +2. Allocate a DMA-capable buffer with `bus_dmamem_alloc(tag, &vaddr, flags, &map)`, or allocate an ordinary buffer and load it later. +3. Load the buffer with `bus_dmamap_load(tag, map, vaddr, length, callback, arg, flags)`. The callback receives one or more `bus_dma_segment_t` entries whose `ds_addr` fields are the bus addresses to hand the device. +4. Before the device reads, `bus_dmamap_sync(tag, map, BUS_DMASYNC_PREWRITE)`. Before the CPU reads what the device wrote, `bus_dmamap_sync(tag, map, BUS_DMASYNC_POSTREAD)`. The flags are defined in `/usr/src/sys/sys/bus_dma.h`. +5. When the transfer is complete, `bus_dmamap_unload(tag, map)` releases the mapping; `bus_dmamem_free(tag, vaddr, map)` releases the buffer; `bus_dma_tag_destroy(tag)` releases the tag (usually in `detach`). + +**Common trap.** Forgetting the `PREWRITE` or `POSTREAD` sync. On coherent architectures (amd64 with IOMMU, for example), the driver often works without it; on non-coherent architectures (some ARM systems), it silently corrupts data. Write the sync calls every time, even when you are developing on a forgiving platform. + +**Where the book teaches this.** Chapter 21 is the full-length dedicated treatment. + +**What to read next.** `bus_dma(9)` and `/usr/src/sys/kern/subr_bus_dma.c`. + +### The Mental Model: Tags, Maps, Segments, Sync + +A short refresher in the shape of a diagram. The pieces fit together like this: + +```text ++----------------------------------------------------------+ +| Device constraints -> bus_dma_tag_t (made once) | ++----------------------------------------------------------+ + | + v ++----------------------------------------------------------+ +| Buffer in kernel memory -> virtual address | ++----------------------------------------------------------+ + | + v bus_dmamap_load() ++----------------------------------------------------------+ +| bus_dmamap_t -> one or more bus_dma_segment_t entries | +| (ds_addr, ds_len) | ++----------------------------------------------------------+ + | + v bus_dmamap_sync(PREWRITE) / PREREAD ++----------------------------------------------------------+ +| Device reads or writes memory at ds_addr | ++----------------------------------------------------------+ + | + v bus_dmamap_sync(POSTWRITE) / POSTREAD ++----------------------------------------------------------+ +| CPU reads the buffer; kernel knows ordering is valid | ++----------------------------------------------------------+ +``` + +Each arrow is a responsibility. The tag expresses what the device can tolerate. The map expresses one particular set of segments the device will actually touch. The sync calls bracket the device's use of the buffer. Miss any one of them and the transfer is undefined. + +### Why Synchronisation and Mapping Matter + +**What it is.** Two concerns that together explain why `bus_dma` is not just an address translator. + +- **Mapping.** The device needs a bus address, not a virtual one. On IOMMU systems, the mapping is a real I/O-virtual range; on non-IOMMU systems, it is the physical address, possibly through a bounce buffer if the device cannot reach where the memory actually lives. The driver does not choose which; `bus_dma` chooses based on the tag. +- **Synchronisation.** The CPU has caches. The device may have its own. The kernel has ordering rules. The sync calls translate the driver's intent ("I am about to hand this buffer to the device for reading") into whatever cache flushes, invalidations, or memory barriers the architecture requires. + +**Why this matters to driver writers.** Skipping synchronisation is the single most common source of subtle data corruption in a DMA driver. The code appears to work because the CPU caches happen to be flushed by other activity; then a kernel update changes cache behaviour slightly and the driver begins to fail. Writing every sync call every time is the only reliable habit. + +**How this shows up in FreeBSD.** The four sync flags are `BUS_DMASYNC_PREREAD`, `BUS_DMASYNC_PREWRITE`, `BUS_DMASYNC_POSTREAD`, and `BUS_DMASYNC_POSTWRITE` (values 1, 4, 2, 8 in `/usr/src/sys/sys/bus_dma.h`). "PRE" runs before the device touches the buffer; "POST" runs after. The "READ" and "WRITE" halves follow the wording in `bus_dma(9)`: `PREREAD` is "the device is about to update host memory, and the CPU will later read what was written"; `PREWRITE` is "the CPU has updated host memory, and the device is about to access it". In the pair of directions a driver usually thinks about, `PREWRITE` covers the CPU-writes-buffer-then-device-reads case, and `PREREAD` covers the device-writes-buffer-then-CPU-reads case. + +**Common trap.** Reading the flag names as if they described the device's own action. If the device is about to write to memory, and the CPU will later read what the device wrote, you call `BUS_DMASYNC_PREREAD` first (because the CPU will later read this memory), not `BUS_DMASYNC_PREWRITE`. The flag pairs track the memory operation the CPU is part of, not the direction the device happens to move data on the wire. + +**Where the book teaches this.** Chapter 21 spends substantial space on the sync semantics because they are easy to get wrong. + +**What to read next.** `bus_dma(9)` and the header comments in `/usr/src/sys/sys/bus_dma.h`. + +### DMA Buffers vs Control Buffers + +**What it is.** A final distinction that keeps the memory section and the DMA section in step. Not every buffer in a DMA-capable driver is a DMA buffer. + +- **DMA buffers** are the ones the device reads from or writes to. They go through `bus_dma(9)`: allocated with `bus_dmamem_alloc` or `malloc` plus `bus_dmamap_load`, loaded, synchronised, unloaded. +- **Control buffers** are the ones only the CPU touches: ring indices, per-request bookkeeping, command structures the driver inspects but the hardware does not. They live in ordinary `malloc(9)` memory. + +**Why this matters to driver writers.** Both kinds of buffer usually exist in the same driver, often side by side inside the same softc. Keeping them straight makes the code much easier to review. A pointer that the device reads should be labelled and allocated unambiguously; a pointer the device never sees should be labelled and allocated just as unambiguously. Confusing the two usually produces hard-to-reproduce bugs. + +**Where the book teaches this.** Chapter 21 revisits the split when it walks a complete descriptor-ring driver. + +## Quick-Reference Tables + +The compact tables below are meant for scanning. They do not replace the sections above; they help you point at the right section fast. + +### Address Spaces at a Glance + +| You have... | It lives in... | How you get it | Who can dereference it | +| :-- | :-- | :-- | :-- | +| A C pointer in kernel code | Kernel virtual memory | `malloc`, `uma_zalloc`, stack, softc | CPU | +| A device register | Physical I/O space | `bus_alloc_resource(SYS_RES_MEMORY,...)` + `bus_space_handle_t` | CPU via `bus_space_*` | +| A DMA buffer | Kernel virtual, plus a bus view | `bus_dmamem_alloc` | CPU via virtual, device via `ds_addr` | +| A device-side bus address | Bus address space (maybe IOMMU-mapped) | `bus_dmamap_load` callback | Device only | + +### When to Use Which Allocator + +| Purpose | Call | +| :-- | :-- | +| Softc, lists, control structures | `malloc(9)` with `M_DRIVER_NAME` | +| Frequent fixed-size objects | `uma(9)` zone | +| DMA buffer with tag constraints | `bus_dmamem_alloc(9)` under a `bus_dma` tag | +| Physically contiguous block, no DMA tag | `contigmalloc(9)` (rarely) | +| Stack temporary, small and bounded | Plain C stack | + +### Interrupt vs Polling + +| You should use... | When... | +| :-- | :-- | +| A hardware interrupt | The event rate is moderate and latency matters | +| Polling inside an ithread | The event rate is very high and interrupts would dominate | +| A taskqueue triggered by interrupts | The work is heavy and cannot run in the filter | +| A timer (callout) plus occasional interrupts | The device is slow and state is simple | + +### Bus at a Glance (Driver-Writer View) + +| Bus | Driver form | Identification | Main API call | +| :-- | :-- | :-- | :-- | +| PCI / PCIe | Full Newbus driver with registers | Vendor/Device ID + class | `bus_alloc_resource_any`, `bus_setup_intr` | +| USB | Framework class driver | VID/PID + class/subclass/protocol | `usbd_transfer_setup`, `usbd_transfer_start` | +| I2C | `iicbus` client | Slave address | `iicbus_transfer` | +| SPI | `spibus` client | Chip-select line | `spibus_transfer` | + +### DMA Sync Quick Check + +| You are about to... | Call this | +| :-- | :-- | +| Hand a buffer to the device for the device to *read* | `bus_dmamap_sync(..., BUS_DMASYNC_PREWRITE)` | +| Hand a buffer to the device for the device to *write* | `bus_dmamap_sync(..., BUS_DMASYNC_PREREAD)` | +| Read from a buffer the device just wrote | `bus_dmamap_sync(..., BUS_DMASYNC_POSTREAD)` | +| Reuse a buffer after the device read it | `bus_dmamap_sync(..., BUS_DMASYNC_POSTWRITE)` | + +The "PRE" calls fence the CPU writes or cache lines before the device looks at the buffer. The "POST" calls fence the device's completion before the CPU looks at what changed. + +## Wrapping Up: How to Keep Relating Hardware Concepts to Driver Code + +The hardware concepts in this appendix are not a separate subject from driver writing. Every one of them shows up in code. The sequence the reader will use, over and over, is always the same: + +1. The device exists in physical address space. Its registers are at physical addresses. +2. The kernel gives the driver a `bus_space` handle that maps those registers with the right attributes. +3. The device raises interrupts on events, and the driver handles them through a filter (fast, small, spin-lock safe) and optionally an ithread (slower, sleep-lock safe). +4. When the device needs to move data, the driver uses `bus_dma(9)` to produce bus addresses that the device can use, and it brackets every transfer with sync calls. +5. The driver never hands a kernel virtual pointer to the device, and never treats a `ds_addr` as if it were a physical address the CPU can read directly. + +If you keep that sequence in mind, the hardware concepts here stop being a separate subject and become a running commentary on the code you are writing. When you are about to cast a pointer and hand it to hardware, stop and translate the action into the sequence: in which address space is this, who is going to read it, what attributes does that view need. The sequence never changes. The details change with every device family. + +Three habits that reinforce the model. + +The first is reading the header comment of a real driver before reading its code. Most FreeBSD drivers open with a block that explains the locking discipline, the MSI-X structure, or the ring layout. That comment is there because the code alone cannot communicate it. When the comment says "the receive ring uses the per-queue lock; the filter acknowledges the device and schedules a taskqueue", read it carefully. It is a condensed map of the hardware-to-software bridge for that driver. + +The second is naming the bus every time. When you read an unfamiliar driver, find the `DRIVER_MODULE` line. The bus name in that line (`pci`, `usb`, `iicbus`, `spibus`, `acpi`, `simplebus`) tells you which hardware model applies before you read a single function. A driver attached to `pci` is register-oriented and interrupt-driven; a driver attached to `iicbus` is transaction-oriented and polled at the bus level. The same C code reads differently when you know which bus is behind it. + +The third is keeping a short companion sheet with your driver notes. The files under `examples/appendices/appendix-c-hardware-concepts-for-driver-developers/` are meant for exactly this. A bus-comparison cheatsheet you can glance at when you open a new datasheet. A DMA mental-model checklist you can walk when you suspect a sync is missing. A physical-vs-virtual diagram you can annotate with the particular tag and handle pair you are working with today. The teaching is in this appendix; the application is in those sheets. + +With that, the hardware side of the book has a consolidated home. The chapters keep teaching; the appendix keeps naming; the examples keep reminding. When a reader closes this appendix and opens a real driver, the vocabulary is ready. diff --git a/content/appendices/appendix-d.md b/content/appendices/appendix-d.md index 1c383ec..441b355 100644 --- a/content/appendices/appendix-d.md +++ b/content/appendices/appendix-d.md @@ -1,14 +1,485 @@ --- title: "Operating System Concepts" -description: "Core operating system concepts relevant to device driver development" +description: "A concept-level companion to the kernel/user boundary, driver types, recurring kernel data structures, and the boot-to-init path that drivers must fit into." appendix: "D" -lastUpdated: "2025-08-01" -status: "planned" +lastUpdated: "2026-04-20" +status: "complete" author: "Edson Brandi" reviewer: "TBD" translator: "TBD" estimatedReadTime: 25 --- -planned +# Appendix D: Operating System Concepts +## How to Use This Appendix + +The main chapters teach the reader how to write a FreeBSD device driver: how to declare a softc, how to probe and attach to a bus, how to register a character device, how to set up an interrupt, how to do DMA. Beneath all of that there is a running assumption that the reader has a working mental model of what an operating system kernel actually is, how it differs from userland, what a driver is *inside* that kernel, and how the machine gets from power-on to a kernel that is ready to load and run that driver. The book introduces each piece of this model in the chapter where it first becomes relevant, but the pieces never appear in one place together. + +This appendix is that one place. It is a concept companion for the operating-system ideas the rest of the book keeps reusing: the kernel/user boundary, the definition of a driver, the handful of data structures you will see again and again in FreeBSD source, and the boot-to-init sequence that sets the stage for everything a driver can do. It is deliberately short. The goal is to consolidate the mental model, not to teach operating-systems theory, and not to repeat what the chapters already teach at length. + +### What You Will Find Here + +The appendix is organised by driver relevance, not by textbook taxonomy. Four sections, each with a small set of entries. Each entry follows the same compact rhythm: + +- **What it is.** One or two sentences of plain definition. +- **Why this matters to driver writers.** The concrete place where the concept shows up in your code. +- **How this shows up in FreeBSD.** The API, header, subsystem, or convention that names the idea. +- **Common trap.** The misunderstanding that actually costs people time. +- **Where the book teaches this.** A pointer back to the chapter that uses it in context. +- **What to read next.** A manual page, a header, or a real source file you can open. + +Not every entry uses every label; the shape is a guide, not a template. + +### What This Appendix Is Not + +It is not an introduction to operating-systems theory. If you have never met the idea of a process or an address space before, pick up a general operating-systems textbook first and come back. It is not a systems-programming tutorial either; the early chapters of the book already handle that. And it does not overlap with the other appendices. Appendix A is the API lookup. Appendix B is the algorithmic-pattern field guide. Appendix C is the hardware-concepts companion. Appendix E is the kernel-subsystem reference. If the question you want answered is "what does this macro call do", "what data structure should I use", "what is a BAR", or "how does the scheduler work", you want a different appendix. This one keeps its focus on the operating-system mental model that makes driver work make sense. + +## Reader Guidance + +Three ways to use this appendix, each with a different reading strategy. + +If you are **learning the main chapters**, keep this appendix open as a companion. When Chapter 3 discusses the UNIX division between the kernel and userland, glance at Section 1 here for the driver-relevant summary. When Chapter 6 introduces Newbus and the driver lifecycle, Section 2 compresses the same story into a one-page mental model. When Chapter 11 walks you through your first mutex, Section 3 names the family. A first pass through the whole appendix should take about twenty-five minutes; daily use looks more like two or three minutes at a time. + +If you are **reading unfamiliar kernel code**, treat the appendix as a translator. Kernel source assumes the reader already knows why `copyin(9)` exists, what a softc is, when a `TAILQ` is better than a `LIST`, and where `SYSINIT` chains come from. If any of those words feel fuzzy when you meet them in code, the entry here names the concept in one page and points to the chapter that teaches it in full. + +If you are **coming back to the book after time away**, read the appendix as a consolidation. The concepts here are the recurring spine of driver work. Re-reading them is a low-cost way to reload the mental model before you open an unfamiliar driver. + +A few conventions apply throughout: + +- Source paths are shown in the book-facing form, `/usr/src/sys/...`, matching a standard FreeBSD system. You can open any of them on your lab machine. +- Manual pages are cited in the usual FreeBSD style. Kernel-facing pages live in section 9 (`intr_event(9)`, `mtx(9)`, `kld(9)`). Userland system calls live in section 2 (`open(2)`, `ioctl(2)`). Device overviews live in section 4 (`devfs(4)`, `pci(4)`). +- When an entry points to real source as reading material, the file is one a beginner can navigate in a single sitting. + +With that framing in place, we start where every driver must start: by understanding which side of the kernel/user line it lives on. + +## Section 1: What Is a Kernel, and What Does It Do? + +A kernel is the program that owns the machine. It is the only program that runs in the CPU's most privileged mode, the only program that may touch physical memory directly, the only program that may talk to hardware, and the only program that may decide which other programs run and when. Everything else (shells, compilers, web browsers, daemons, your own programs) runs in a less privileged mode and asks the kernel for the things it cannot do itself. A driver is kernel code. That single fact changes the rules the code must follow, and the rest of this section explains why. + +### Kernel Responsibilities in One Page + +**What it is.** The FreeBSD kernel is responsible for a small, well-defined set of jobs: managing the CPU (processes, threads, scheduling, interrupts), managing memory (virtual address spaces, page tables, allocation), managing I/O (talking to devices through drivers), managing files and filesystems (through VFS and GEOM), and managing the network stack. It also mediates security boundaries, handles signals, and serves as the only entry point for every system call. + +**Why this matters to driver writers.** A driver is not a free-standing program. It is a participant in each of those jobs. A network driver participates in the networking subsystem. A storage driver participates in the I/O and filesystem subsystems. A sensor driver participates in the I/O subsystem and sometimes in the event-handler subsystem. When you write a driver, you are extending the kernel, not sitting beside it. The kernel's invariants become your invariants, and every convention the kernel relies on (locking discipline, memory discipline, error-return conventions, cleanup ordering) becomes a convention you must honour. + +**How this shows up in FreeBSD.** The kernel source tree under `/usr/src/sys/` is organised by responsibility: `/usr/src/sys/kern/` holds the machine-independent core (process management, scheduling, locking, VFS), `/usr/src/sys/vm/` holds the virtual-memory system, `/usr/src/sys/dev/` holds the device drivers, `/usr/src/sys/net/` and `/usr/src/sys/netinet/` hold the network stack, and `/usr/src/sys/amd64/` (or `arm64/`, `i386/`, `riscv/`) holds the machine-dependent code. When you read a driver, you are reading code that ties together pieces from several of these directories. + +**Common trap.** Treating the kernel as a passive library that drivers "call into". The kernel is the running program; your driver lives inside it. A crash, a memory leak, or a held lock in your driver is a crash, a memory leak, or a held lock for the whole system. + +**Where the book teaches this.** Chapter 3 introduces the UNIX and FreeBSD picture. Chapter 5 sharpens the distinction at the level of kernel-space C. Chapter 6 grounds it in driver anatomy. + +**What to read next.** `intro(9)` for the top-level kernel overview, and the directory listing of `/usr/src/sys/` itself. Spend five minutes reading folder names and you will already have a rough map. + +### Kernel Space vs User Space + +**What it is.** Two distinct execution environments inside the same machine. Kernel space runs with full CPU privileges, shares one address space among all kernel threads, and has direct access to hardware. User space runs with reduced privileges, lives in per-process virtual address spaces that the kernel sets up and protects, and has no direct access to hardware. A single machine is always running code from both environments; the CPU switches between them many times per second. + +**Why this matters to driver writers.** Almost every rule that makes kernel programming feel different from user programming comes from this separation. A kernel pointer is not addressable from user space, and a user pointer is not safely addressable from kernel space. User memory may be swapped, paged, or unmapped at any moment; kernel memory is stable within its allocation lifetime. The kernel must never blindly dereference a pointer that came from userland; it must always use the dedicated copy primitives. And because one kernel address space is shared by every thread in the kernel, any kernel bug that stomps memory can corrupt every subsystem at once. + +**How this shows up in FreeBSD.** Three places in driver code are visible every time the boundary is crossed: + +- `copyin(9)` and `copyout(9)` move fixed-size data between a user buffer and a kernel buffer, returning an error on a bad user address instead of panicking. +- `copyinstr(9)` does the same for NUL-terminated strings with a caller-supplied length cap. +- `uiomove(9)` walks a `struct uio` (user I/O descriptor) through either direction of a `read` or `write` system call, handling the buffer list and the direction flag for you. + +Under the hood, each of these routines uses machine-dependent helpers that know how to catch a fault from a bad user address and convert it into an `EFAULT` return rather than a kernel panic. + +**Common trap.** Dereferencing a user pointer directly inside a syscall handler or an `ioctl` implementation. The code may appear to work when the user passes a valid pointer and the page happens to be resident. It will panic or silently misbehave the moment the user passes something bad (either by mistake or deliberately), and that is one of the easier bugs to turn into a security problem. + +**Where the book teaches this.** Chapter 3 sets up the distinction. Chapter 5 covers it in kernel C. Chapter 9 walks the boundary in character-driver code. + +**What to read next.** `copyin(9)`, `copyout(9)`, `uiomove(9)`, and the header `/usr/src/sys/sys/uio.h` for `struct uio`. + +### System Calls: The Door Between the Two Sides + +**What it is.** A system call is the disciplined mechanism a user-space program uses to ask the kernel to do something on its behalf. The user program invokes a special instruction (`syscall` on amd64, `svc` on arm64, with equivalent traps on every other architecture FreeBSD supports), which causes the CPU to trap into kernel mode, switch to the kernel stack of the current thread, and dispatch to the implementation the kernel has registered for that system-call number. + +**Why this matters to driver writers.** Most driver interaction with userland happens because a userland program issued a system call. When the user runs `cat /dev/mydevice`, `cat(1)` invokes `open(2)`, `read(2)`, and `close(2)` against that device node. Each of those system calls eventually reaches your driver through the `cdev` switch table you registered with `make_dev_s(9)`: `open(2)` becomes `d_open`, `read(2)` becomes `d_read`, `ioctl(2)` becomes `d_ioctl`. Your driver's entry points are therefore system-call entry points in disguise, which is exactly why the copy primitives above matter so much. + +**How this shows up in FreeBSD.** Two pieces. First, the system-call table itself and the trap-handling path, which live in the machine-independent core and in the architecture-specific backends. Second, the driver-visible structures that a system call hands you: a `struct thread *` for the calling thread, a `struct uio *` for the buffer list on `read`/`write`, an argument pointer for `ioctl`, and a set of flags that describe the mode of the call. The driver does not see the trap; it sees a function call that arrives already in kernel context. + +**Common trap.** Assuming the calling thread can be treated as an ordinary kernel thread. A thread that entered the kernel through a system call is temporarily running kernel code on behalf of a user process. It may be killed if the process is killed, its priority may be different from an internal kernel thread, and it is usually the wrong thread to own long-lived work. Long work belongs on a taskqueue or a kernel thread the driver owns. + +**Where the book teaches this.** Chapter 3 names the mechanism. Chapter 9 exercises it in a working read/write path. + +**What to read next.** `syscall(2)` for the userland view, `uiomove(9)` for the kernel entry shape, and `/usr/src/sys/kern/syscalls.master` if you are curious about the actual system-call numbering table. + +### Why Kernel Mistakes Have System-Wide Consequences + +**What it is.** A short way of stating what the previous entries imply. A kernel thread can read and write any kernel memory; there is no per-module address space inside the kernel. A kernel bug is therefore free to damage any data structure, including data structures that belong to other subsystems. A kernel crash takes the whole machine down. A kernel deadlock can wedge threads across every driver at once. + +**Why this matters to driver writers.** The blast radius of a kernel bug is the whole system. That is why the book repeats the same disciplines in every chapter: balanced allocate/free pairs, balanced lock acquire/release pairs, consistent cleanup ladders on error, defensive validation of any pointer that comes from userland, and careful ordering at boundaries (interrupts, DMA, device registers). None of these disciplines are about heroics; they are about acknowledging that the cost of a kernel mistake is paid by every process on the machine, not only by the driver that made it. + +**How this shows up in FreeBSD.** Directly, in the tools the kernel offers you to catch mistakes before they escape. `witness(9)` verifies lock ordering. `KASSERT(9)` lets you encode invariants that compile away in production but fire loudly in a development build. `INVARIANTS` and `INVARIANT_SUPPORT` in the kernel config turn on extra self-checks. DTrace lets you watch driver behaviour under real load. Your development lab should always be running a kernel with these diagnostics enabled; your production target should not. + +**Common trap.** Testing only on a release-build kernel and discovering the bugs in production. The development kernel is the one that finds the problem cheaply. Use it. + +**Where the book teaches this.** Chapter 2 walks you through building a diagnostics-enabled lab kernel. Chapter 5 makes the discipline concrete at the C level. Every chapter from Chapter 11 onward depends on these habits. + +**What to read next.** `witness(9)`, `kassert(9)`, `ddb(4)`, and the kernel-debugging options in `/usr/src/sys/conf/NOTES`. + +### How Drivers Participate in Kernel Responsibilities + +The previous entries describe the kernel as an abstract entity. The role a driver plays inside that kernel is concrete and limited. A driver is the component that makes a specific piece of hardware, or a specific pseudo-device, usable through the kernel's existing subsystems. A storage driver exposes a disk through GEOM and the buffer cache so that filesystems can use it. A network driver exposes a NIC through `ifnet` so that the network stack can use it. A character driver exposes a device node in `/dev` so that userland programs can use it through ordinary file system calls. Drivers do not invent interfaces; they implement the ones the kernel already publishes. + +That framing is worth keeping close while you read a new driver. Finding the two ends, the hardware end (registers, interrupts, DMA) and the subsystem end (the `ifnet`, the `cdev`, the GEOM provider), is the single best way to orient yourself in an unfamiliar driver. Section 2 puts more shape on the subsystem end. + +## Section 2: What Is a Device Driver? + +A device driver is the piece of kernel code that makes a particular device, real or virtual, usable through the operating system's regular interfaces. It lives on two fronts at once. On one side it speaks the hardware's language: register accesses, interrupts, DMA descriptors, protocol sequences. On the other side it speaks one of FreeBSD's standard subsystem interfaces: `cdevsw` for character devices, `ifnet` for network interfaces, GEOM for storage. A driver's job is to translate between those two sides, correctly and safely, for the lifetime of the device. + +This section names the driver types the book cares about, the role the driver plays in the hardware-to-userland path, and the mechanics by which FreeBSD loads a driver and binds it to a device. + +### Driver Types: Character, Block, Network, Pseudo + +**What it is.** A classification by the subsystem interface the driver publishes. The vocabulary is older than FreeBSD and the historical category names still appear, but on modern FreeBSD the exact boundaries differ from the textbook picture. + +- A **character device driver** exposes the hardware as a stream through a `cdev` node in `/dev`. It registers a `struct cdevsw` with entry points such as `d_open`, `d_close`, `d_read`, `d_write`, and `d_ioctl`, and the kernel routes corresponding system calls to those entry points. Pseudo-devices (drivers with no real hardware behind them, like `/dev/null` or `/dev/random`) are character devices too. +- A **block device driver** in the historical UNIX sense exposed a fixed-size disk through a block-oriented cache. In modern FreeBSD, disk-like devices are presented through GEOM, not through a separate block-`cdevsw`; the entries in `/dev` for a disk (`/dev/ada0`, `/dev/da0`) are still `cdev` nodes, but their substance is a GEOM provider, and filesystems talk to them through the BIO layer rather than through raw read/write. +- A **network driver** exposes a network interface through `ifnet`. It does not use `cdevsw` at all; it registers with the network stack, receives packets as `struct mbuf` chains, sends packets through the stack's transmit queues, and participates in link-state events. +- A **pseudo-device driver** is any driver with no real hardware behind it. It may be a character device (`/dev/null`, `/dev/random`), a network device (`tun`, `tap`, `lo`), or a storage provider (`md`, `gmirror`). The word "pseudo" refers only to the absence of hardware; the subsystem integration is the same as for a real device. + +**Why this matters to driver writers.** The type of driver you are writing determines the interface you must implement. A character-device driver spends its time in `d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl`. A network driver spends its time in `if_transmit`, `if_input`, and interrupt-driven receive paths. A storage driver spends its time in GEOM start routines and BIO completion. Picking the right type early saves a rewrite; picking the wrong one is an expensive mistake. + +**How this shows up in FreeBSD.** Three separate sets of headers and chapters of the tree handle the three main types: + +- Character drivers register through `/usr/src/sys/sys/conf.h` (`struct cdevsw`, `make_dev_s`) and are implemented all across `/usr/src/sys/dev/`. +- Network drivers register through `/usr/src/sys/net/if.h` (`struct ifnet`) and have their stack integration in `/usr/src/sys/net/` and `/usr/src/sys/netinet/`. +- Storage drivers register through the GEOM framework under `/usr/src/sys/geom/` and use `struct bio` for I/O requests. + +**Common trap.** Reaching for `cdevsw` to expose a disk. The "everything is a file" intuition is half right, but a modern FreeBSD disk is a GEOM provider; a raw `cdevsw` interface skips the cache, the partitioning layer, and the transforms the rest of the system expects. + +**Where the book teaches this.** Chapter 6 names the categories and positions them inside Newbus. Chapter 7 writes the first character driver from scratch. Chapter 27 covers storage and GEOM. Chapter 28 covers network drivers. + +**What to read next.** `cdevsw(9)`, `ifnet(9)`, and a compact pseudo-device such as `/usr/src/sys/dev/null/null.c`. Read the `null` driver in one sitting; it is the cleanest example of a complete character driver in the tree. + +### The Role of a Driver in Hardware Communication + +**What it is.** The driver is the only kernel code that talks to its hardware. Nothing else in the kernel accesses the device's registers, arms its interrupts, or queues its DMA transfers. All other subsystems reach the device through the driver. + +**Why this matters to driver writers.** This exclusivity is why the driver must be trustworthy. The network stack cannot double-check whether a packet was really transmitted; it trusts the network driver. The filesystem cannot double-check whether a block really reached the disk; it trusts the storage driver. When the driver lies (by completing a transfer before the hardware is finished, for example), the rest of the system believes the lie and carries on. Most catastrophic failures in real systems come from this class of subtle driver dishonesty, not from outright crashes. + +**How this shows up in FreeBSD.** In the shape of the driver's public functions. A character driver's `d_read` returns only after the data is really in the user buffer or an error has occurred. A network driver's `if_transmit` tells the stack whether the packet is owned by the driver now or still by the stack. A storage driver's `g_start` takes responsibility for completing the `bio` through `biodone(9)` eventually. Every one of those contracts is a promise the driver is making on behalf of the hardware. + +**Common trap.** Returning early from a completion path because "the hardware usually works". On a good day, nothing fails. On a bad day, the stack thinks a packet was sent that was not, a filesystem thinks a block was written that was not, and the resulting corruption is impossible to track back to its source. + +**Where the book teaches this.** Chapter 6 sets up the contract. Chapter 19 makes it rigorous for interrupt-driven completion. Chapter 21 does the same for DMA. + +**What to read next.** `biodone(9)`, and the transmit/receive path of a small NIC driver. + +### How Drivers Are Loaded and Bound to Devices + +**What it is.** FreeBSD drivers reach a running kernel in one of two ways. Either they are compiled into the kernel binary (built-in drivers, activated during boot) or they are built as kernel-loadable modules (`.ko` files) that the administrator loads at run time with `kldload(8)`. Once a driver is present in the kernel, Newbus offers it the devices it claims. + +The binding dance is the *probe/attach* cycle. Every bus enumerates its children at boot or on hot-plug and asks each registered driver whether it can handle each child. The driver's `probe` function examines the child (vendor/device ID for PCI, VID/PID for USB, FDT compatibility string for embedded systems, a class register for generic buses) and returns a priority value saying how confident it is. The bus picks the highest-priority match and calls that driver's `attach` function. From that point on, the device belongs to the driver, and the driver's softc holds the device's state. + +**Why this matters to driver writers.** Every FreeBSD driver ends with a short block of boilerplate that registers it for this dance. The boilerplate is the contract between the driver and the rest of the kernel. Get it wrong and the driver never attaches; get it right and the kernel will attach, detach, suspend, resume, and unload your driver at the moments it chooses. + +**How this shows up in FreeBSD.** Five pieces, all compact: + +- A `device_method_t` array that lists the driver's implementations of the standard device methods, ending with `DEVMETHOD_END`. +- A `driver_t` structure that binds a driver name, the method table, and a softc size. +- A `DRIVER_MODULE(name, busname, driver, evh, arg)` invocation at the bottom of the file, which registers the driver with the named bus. The `evh` and `arg` fields pass an optional event handler; most drivers leave them as `0, 0`. +- A `MODULE_VERSION(name, version)` invocation to advertise the module's ABI version. +- Optional `MODULE_DEPEND(name, other, min, pref, max)` lines if the driver depends on another module. + +These live in `/usr/src/sys/sys/module.h` and `/usr/src/sys/sys/bus.h`. The `DEVMETHOD` macro hooks the driver's `probe`, `attach`, `detach`, and optional `suspend`/`resume`/`shutdown` functions into the kobj method dispatcher that Newbus uses internally. + +**Common trap.** Forgetting `MODULE_VERSION`. The module may load and work on your machine, and then fail to load on someone else's because the kernel has no way to check ABI compatibility. The version declaration is not ceremonial; it is how the module loader keeps pieces compatible. + +**Where the book teaches this.** Chapter 6 introduces the Newbus tree. Chapter 7 writes the full boilerplate end to end and uses `kldload(8)` to exercise it. + +**What to read next.** `DRIVER_MODULE(9)`, `MODULE_VERSION(9)`, `kld(9)`, `kldload(8)`, and the compact `/usr/src/sys/dev/null/null.c` as a complete example. + +### Connecting Hardware, Kernel Subsystems, and Userland + +**What it is.** A short way of stating what a driver does viewed from the top. Hardware is on one side. Userland is on the other. In between are the kernel subsystems (VFS, GEOM, `ifnet`, `cdev`). The driver is the component that lets bytes flow through that sandwich. + +A rough picture, in one direction: + +```text +userland kernel subsystems driver hardware +-------- ------------------ ------ -------- +cat(1) -> open(2) / read(2) + -> cdev switch ADC, NIC, + (d_read) -> driver entry disk, etc. + point + -> register read, + MMIO, DMA + -> bytes + + <- sync, interrupt, + completion + <- mbuf chain / bio / + uiomove back + <- read(2) returns +``` + +The picture is not literal code. It is the shape of responsibility. Every driver fits some variant of it. + +**Why this matters to driver writers.** When you are unsure where a piece of code belongs, ask which layer of the sandwich is responsible for the current concern. A user-pointer validation belongs at the subsystem boundary. A register access belongs in the driver. A per-device state update belongs in the softc. Once the layer is clear, the names and primitives follow. + +**Where the book teaches this.** Chapter 6 draws the picture for character drivers. Chapter 27 redraws it for GEOM. Chapter 28 redraws it for `ifnet`. The shape is always recognisable. + +**What to read next.** The top of `/usr/src/sys/dev/null/null.c` for a minimal character variant, and the top of `/usr/src/sys/net/if_tuntap.c` for a minimal network variant. + +## Section 3: Kernel Data Structures You Will See Often + +Certain shapes appear in nearly every FreeBSD driver. A linked list of pending requests. A buffer that crosses the kernel/user boundary. A lock around the softc. A condition variable waited on from one thread and signalled from another. None of these is complicated in isolation, but meeting them for the first time inside real code is where the mental model often breaks down. This section names the families, explains what role they play, and points you back to the chapter that teaches them in full. Appendix A has the detailed APIs; Appendix B has the algorithmic patterns. This section is the one-page orientation. + +### Lists and Queues from `` + +**What it is.** A header-only family of intrusive-list macros. You embed a `TAILQ_ENTRY`, `LIST_ENTRY`, or `STAILQ_ENTRY` inside your element structure, define a head, and the macros give you insertion, removal, and traversal without any heap allocation for list nodes. Four flavours exist: `SLIST` (singly linked), `LIST` (doubly linked, insertion at head), `STAILQ` (singly linked with fast tail insertion), and `TAILQ` (doubly linked with tail insertion and O(1) arbitrary removal). + +**Why this matters to driver writers.** Almost every per-driver collection in the tree is one of these. Pending commands, open file handles, registered callbacks, queued `bio` requests. Picking the right flavour for the access pattern produces code that is short, predictable, and lockable with a single mutex. Picking the wrong one produces needless pointer bookkeeping or surprise O(n) removal. + +**How this shows up in FreeBSD.** The macros live in `/usr/src/sys/sys/queue.h`. A softc often holds its queue heads as ordinary fields. Every traversal is wrapped by the driver's lock. The safe-against-removal variants (`TAILQ_FOREACH_SAFE`, `LIST_FOREACH_SAFE`) are the ones you want any time the body of the loop might unlink the current element. + +**Common trap.** Using a plain `LIST_FOREACH` while freeing elements inside the loop body. The iterator dereferences the element's link pointer after you have already freed it. Switch to the `_SAFE` variant or rearrange the loop. + +**Where the book teaches this.** Chapter 5 introduces the macros in kernel C. Chapter 11 uses them with locking. Appendix B has the full pattern-oriented treatment. + +**What to read next.** `queue(3)`, `/usr/src/sys/sys/queue.h`, and any driver softc that holds an in-flight request list. + +### Kernel Buffers: `mbuf`, `buf`, and `bio` + +**What it is.** Three buffer representations that appear in specific subsystems. `struct mbuf` is the networking packet-representation type, a linked list of small fixed-size units that together hold a packet and its metadata. `struct buf` is the storage buffer-cache unit, used by the VFS and the legacy block layer. `struct bio` is the GEOM I/O-request structure, the modern unit of storage I/O that a storage driver completes with `biodone(9)`. + +**Why this matters to driver writers.** You will not meet all three at once. A network driver thinks in `mbuf` chains. A storage driver thinks in `bio` requests and, at the VFS layer, in `buf` entries. A character driver rarely sees any of them; it uses `struct uio` instead. Knowing which buffer type your subsystem uses tells you which completion convention applies and which headers to include. Mixing them up is a signal that the driver type is wrong or that a layer boundary is being violated. + +**How this shows up in FreeBSD.** `struct mbuf` is defined in `/usr/src/sys/sys/mbuf.h`. `struct buf` is defined in `/usr/src/sys/sys/buf.h`. `struct bio` is defined in `/usr/src/sys/sys/bio.h`. Each has its own allocation, reference-counting, and completion rituals; the driver never invents a substitute. + +**Common trap.** Allocating a plain byte buffer for network transmit because it looks easier. The network stack hands you an `mbuf`; the network stack expects an `mbuf` back. Converting in and out of the right type is almost always a mistake, and it breaks zero-copy fast paths that the stack relies on. + +**Where the book teaches this.** Chapter 27 introduces `bio` in the storage context. Chapter 28 introduces `mbuf` in the network context. Appendix E will have deeper entries for each. + +**What to read next.** `mbuf(9)`, `bio(9)`, `buf(9)`. + +### Locking: Mutex, Spin Mutex, Sleep Lock, Condition Variable + +**What it is.** A family of kernel primitives for ordering access to shared data. Four kinds matter at the appendix level: + +- A **default mutex** (`mtx(9)` with `MTX_DEF`) is the everyday sleep-capable mutex. A thread that cannot immediately acquire it goes to sleep until the owner releases. It is the right default for almost every softc field. +- A **spin mutex** (`mtx(9)` with `MTX_SPIN`) is an interrupt-safe busy-wait lock. A thread that cannot immediately acquire it spins. Spin mutexes are used in the tiny set of contexts where sleeping is forbidden (interrupt filters and a few scheduler paths). They are not a performance optimisation; they are a correctness tool for a narrow case. +- A **sleepable shared/exclusive lock** (`sx(9)`) is the right choice for long read-mostly critical sections that may sleep while holding the lock. It is used by code that performs operations the kernel might block on (for example, allocating memory with `M_WAITOK` while holding the lock). +- A **condition variable** (`cv(9)`) is a synchronisation primitive for waiting on a predicate. A thread holds a mutex, checks a condition, and if the condition is false, calls `cv_wait` which atomically drops the mutex, sleeps, and reacquires the mutex on wakeup. Another thread changes the predicate under the same mutex and calls `cv_signal` or `cv_broadcast`. A condition variable never exists without an accompanying mutex. + +**Why this matters to driver writers.** Every non-trivial driver keeps shared state: the softc itself, an in-flight request list, a pending I/O counter, a reference count. Protecting that state correctly is the difference between a driver that works under load and a driver that fails intermittently in ways nobody can reproduce. The FreeBSD locking primitives are the tools you reach for every time. + +**How this shows up in FreeBSD.** The headers are `/usr/src/sys/sys/mutex.h` for the regular and spin mutexes, `/usr/src/sys/sys/sx.h` for the shared/exclusive lock, and `/usr/src/sys/sys/condvar.h` for condition variables. The convention is to store the lock inside the softc and name it after the softc field: a driver that protects its work queue usually has something like `mtx_init(&sc->sc_lock, device_get_nameunit(dev), NULL, MTX_DEF)` in `attach` and a matching `mtx_destroy` in `detach`. + +**Common trap.** Two, both common. The first is taking a sleep mutex from an interrupt filter. A filter runs in a context that cannot sleep; a sleep mutex may block; the kernel detects this with `witness(9)` in a development build. The second is reading the state the condition variable guards *outside* the mutex. The mutex-predicate-wait pattern relies on the predicate and the wait being atomic with respect to the signaller; breaking that atomicity reintroduces the race the condition variable was supposed to eliminate. + +**Where the book teaches this.** Chapter 11 introduces mutexes and spin mutexes. Chapter 12 adds condition variables and shared/exclusive locks. Appendix B collects the reasoning patterns. + +**What to read next.** `mtx(9)`, `sx(9)`, `cv(9)`, `witness(9)`, and the top of a real driver's softc structure to see the lock and its users in one place. + +### `softc`: The Per-Device Driver Structure + +**What it is.** The per-device state structure that the driver defines and the kernel allocates on its behalf. "Softc" is short for "software context". It holds everything the driver needs to know about one specific instance of the device it drives: the `device_t` back-pointer, the lock, the `bus_space` tag and handle for MMIO, the allocated resources, any in-flight state, counters, and sysctl nodes. When FreeBSD attaches a driver to a device, it allocates a softc of the size the driver declared in its `driver_t` and gives the driver a pointer to it through `device_get_softc(9)`. + +**Why this matters to driver writers.** Every function in the driver reaches the softc the same way: `struct mydev_softc *sc = device_get_softc(dev)`. Everything specific to this particular device lives behind that pointer. A driver that attaches to three devices gets three independent softcs, each with its own lock, its own state, its own hardware view. Keeping the softc the single owner of per-device state is what makes the code reentrant across multiple devices. + +**How this shows up in FreeBSD.** The pattern is uniform across the tree. In the driver: + +- A `struct mydev_softc` definition at the top of the file. +- `.size = sizeof(struct mydev_softc)` in the `driver_t` initialiser. +- `struct mydev_softc *sc = device_get_softc(dev)` at the top of every function that receives a `device_t`. +- A `sc->sc_lock` field initialised in `attach` and destroyed in `detach`. + +The kernel zeroes the softc before handing it to the driver, so a fresh attach always starts in a known state. + +**Common trap.** Stashing state in file-scope globals because "there is only one device". Then someone attaches two, or builds a VM with two, and the second device silently corrupts the first. Every driver, no matter how simple it looks, keeps state in the softc. + +**Where the book teaches this.** Chapter 6 introduces the concept. Chapter 7 writes a full softc and uses it end to end. Every chapter from Chapter 8 onward assumes the pattern. + +**What to read next.** `device_get_softc(9)`, the `softc` block at the top of `/usr/src/sys/dev/null/null.c`, and the softc of any small PCI driver. + +### Why These Structures Keep Reappearing + +The families above (queues, buffers, locks, and the softc) recur because they correspond to the four questions every driver eventually has to answer. What pending work do I hold? What bytes am I moving? How do I serialise access to my own state? Where do I keep the state of one instance of my device? Once you recognise that framing, driver code starts to read very differently. The unfamiliar parts are the details of a specific device or bus; the familiar parts are the four answers, in four standard shapes, used by every driver in the tree. + +## Section 4: Kernel Compilation and Booting + +A driver runs inside a kernel. That kernel did not appear from nothing; something had to compile it, something had to load it into memory, something had to call its entry point, and something had to set up the environment in which your driver's `attach` function eventually runs. This section traces that chain at concept level, so that when a bug happens early in the boot, you have a mental picture of what the system was trying to do. + +### The Boot Process Overview + +**What it is.** The sequence of events from power-on to a running FreeBSD kernel with userland processes. On a typical x86 machine it is roughly: firmware (BIOS or UEFI), first-stage boot (`boot0` on BIOS, the UEFI boot manager on UEFI), the FreeBSD loader (`loader(8)`), the architecture-specific kernel entry (`hammer_time` on amd64, called from assembly), the machine-independent startup (`mi_startup`), the `SYSINIT` chain, and finally the first userland process (`/sbin/init`). On ARM64 and other architectures, the firmware and machine-dependent parts differ; the machine-independent kernel startup is the same. + +**Why this matters to driver writers.** Two reasons. First, many driver failures happen during `SYSINIT` processing, before there is a console to print to, and you need to know where you are when that happens. Second, the order in which subsystems initialise determines when your driver's bus has enumerators, when memory allocators are available, when the root filesystem is mounted, and when it is safe to talk to userland. A driver that tries to allocate memory too early will fail; a driver that tries to open a file before the root filesystem is mounted will also fail. The `SYSINIT` mechanism names the stages explicitly so that ordering is visible in the code. + +**How this shows up in FreeBSD.** Each stage has a file you can open. The boot loader lives under `/usr/src/stand/`; the amd64 early C entry is `hammer_time` in `/usr/src/sys/amd64/amd64/machdep.c` (called from `/usr/src/sys/amd64/amd64/locore.S`); the machine-independent startup is `mi_startup` in `/usr/src/sys/kern/init_main.c`; and `start_init` in the same file is what the init process runs when it is finally scheduled, execing `/sbin/init` as PID 1. + +**Common trap.** Treating boot as opaque. The `SYSINIT` mechanism makes the stages explicit and inspectable, and a driver that understands its place in them is much easier to debug. + +**Where the book teaches this.** Chapter 2 walks through boot in lab context. Chapter 6 connects the driver-loading sequence to the kernel's startup picture. + +**What to read next.** `boot(8)`, `loader(8)`, `/usr/src/sys/kern/init_main.c`, and the `SYSINIT` section of `/usr/src/sys/sys/kernel.h`. + +### From Power-On to `init`: A Compact Timeline + +A thumbnail picture of the whole sequence. The names on the right are the functions or manual pages you would open to look closer. + +```text ++-----------------------------------------------+-----------------------------+ +| Stage | Where to look | ++-----------------------------------------------+-----------------------------+ +| Firmware: BIOS / UEFI starts executing | (hardware / firmware) | ++-----------------------------------------------+-----------------------------+ +| First-stage boot: boot0 / UEFI boot manager | /usr/src/stand/ | ++-----------------------------------------------+-----------------------------+ +| FreeBSD loader: selects kernel and modules | loader(8), loader.conf(5) | ++-----------------------------------------------+-----------------------------+ +| Kernel entry (amd64): hammer_time() + locore | sys/amd64/amd64/machdep.c, | +| | sys/amd64/amd64/locore.S | ++-----------------------------------------------+-----------------------------+ +| MI startup: mi_startup() drives SYSINITs | sys/kern/init_main.c | ++-----------------------------------------------+-----------------------------+ +| SYSINIT chain: subsystems init in order | sys/sys/kernel.h | +| SI_SUB_VM, SI_SUB_LOCK, SI_SUB_KLD, ... | | +| SI_SUB_DRIVERS, SI_SUB_CONFIGURE, ... | | ++-----------------------------------------------+-----------------------------+ +| Bus probe and attach: drivers bind to devices | sys/kern/subr_bus.c | ++-----------------------------------------------+-----------------------------+ +| SI_SUB_CREATE_INIT / SI_SUB_KTHREAD_INIT: | sys/kern/init_main.c | +| init proc forked, then made runnable | | ++-----------------------------------------------+-----------------------------+ +| start_init() mounts root, execs /sbin/init | sys/kern/init_main.c, | +| (PID 1) | sys/kern/vfs_mountroot.c | ++-----------------------------------------------+-----------------------------+ +| Userland startup: rc(8), daemons, logins | rc(8), init(8) | ++-----------------------------------------------+-----------------------------+ +``` + +The table is a map, not a contract. Many details differ per architecture, and the boundaries between stages shift as the kernel evolves. What does not change is the direction: small, simple environment at the top, increasingly functional environment at the bottom, userland at the end. + +### Boot Loaders and Kernel Modules at Boot Time + +**What it is.** The FreeBSD loader (`/boot/loader`) is a small program that the first-stage boot code hands control to. Its job is to read `/boot/loader.conf`, load the kernel (`/boot/kernel/kernel`), load any modules requested by configuration, hand tunables and hints to the kernel, and transfer control to the kernel's entry point. It also provides the boot menu, the ability to boot a different kernel for recovery, and the facility to load a module before the kernel starts. + +**Why this matters to driver writers.** Some drivers must be present before the root filesystem is mounted (storage controllers, for example). Those drivers are either compiled into the kernel or loaded by the loader from `/boot/loader.conf`. A driver that is loaded after root mount (through `kldload(8)`) cannot drive the disk that holds `/`. Knowing the difference is part of planning when a driver should attach. + +**How this shows up in FreeBSD.** `/boot/loader.conf` is the text file that lists modules to load at boot. `loader(8)` and `loader.conf(5)` describe the mechanism. The loader also provides facilities such as `kenv(2)` tunables that the kernel can read in early `SYSINIT` stages. + +**Common trap.** Relying on boot-time loader variables from kernel code that runs after root mount. Those variables are available; they are just not the right place for runtime configuration. Use `sysctl(9)` tunables for runtime, `kenv` only for early init decisions. + +**Where the book teaches this.** Chapter 2 uses the loader while setting up the lab. Chapter 6 introduces `kldload(8)` for run-time driver loading. + +**What to read next.** `loader(8)`, `loader.conf(5)`, `kenv(2)`. + +### Kernel Modules and Driver Attachment + +**What it is.** A kernel module is a compiled `.ko` file that the kernel can load at runtime (or that the loader can load before kernel entry). Modules are how most drivers reach the kernel during normal operation. The module framework handles symbol resolution, versioning (`MODULE_VERSION`), dependencies (`MODULE_DEPEND`), and the registration of any `DRIVER_MODULE` declarations the file contains. + +**Why this matters to driver writers.** Most of your development cycle will look like this: edit source, run `make`, `kldload ./mydriver.ko`, test, `kldunload mydriver`, repeat. The module framework makes that cycle fast and safe, and it also makes the production deployment story clean (the same `.ko` that you test is what ships). The loader and the run-time `kldload(8)` use the same module format. + +**How this shows up in FreeBSD.** Every driver file ends with `DRIVER_MODULE`, `MODULE_VERSION`, and optionally `MODULE_DEPEND`. The declarations register the driver's bus-attachment metadata and module-level metadata with the kernel. When the module is loaded, the kernel runs the module's event handler for `MOD_LOAD`, which (among other things) registers the driver with Newbus. Newbus then offers the driver each device of the right bus, calling `probe` on each. + +**Common trap.** Forgetting to call `bus_generic_detach`, `bus_release_resource`, or `mtx_destroy` from `detach`. The module unload succeeds, the driver is gone, but the resources leak. Subsequent reloads accumulate leaks until something obvious breaks. + +**Where the book teaches this.** Chapter 6 introduces the module/driver relationship. Chapter 7 exercises the full edit-build-load-test-unload cycle. + +**What to read next.** `kld(9)`, `kldload(8)`, `kldstat(8)`, `DRIVER_MODULE(9)`, `MODULE_VERSION(9)`. + +### `init_main` and the `SYSINIT` Chain + +**What it is.** `mi_startup` is the machine-independent entry point that the architecture-specific boot code calls after early assembly (on amd64, `hammer_time` returns to `locore.S`, which calls `mi_startup`). Its body is almost entirely a loop that walks a sorted list of `SYSINIT` records and calls each one. Each record is registered at compile time by a `SYSINIT(...)` macro and carries a subsystem identifier (`SI_SUB_*`) and an order within the subsystem (`SI_ORDER_*`). The linker collects them all into a single section; `mi_startup` sorts and runs them. The init process itself is created in a stopped state at `SI_SUB_CREATE_INIT`, made runnable at `SI_SUB_KTHREAD_INIT`, and once it is scheduled it runs `start_init`, which mounts the root filesystem and execs `/sbin/init` as PID 1. + +**Why this matters to driver writers.** Most drivers never touch `SYSINIT` directly; `DRIVER_MODULE` wraps the right registration for them. But a few pieces of infrastructure (kernel threads that must exist before drivers attach, subsystem-wide initialisers, early event handlers) use `SYSINIT` directly, and when you read such code it helps to know what the declaration is registering. The `SI_SUB_*` names make the ordering auditable, and the numeric spacing between them leaves room for future stages. + +**How this shows up in FreeBSD.** The `SYSINIT` macro and the `SI_SUB_*` constants are in `/usr/src/sys/sys/kernel.h`. The driver-relevant stages include `SI_SUB_VM` (virtual memory up), `SI_SUB_LOCK` (lock initialisation), `SI_SUB_KLD` (module system), `SI_SUB_DRIVERS` (early driver-subsystem init), `SI_SUB_CONFIGURE` (Newbus probe and attach), `SI_SUB_ROOT_CONF` (candidate root devices identified), `SI_SUB_CREATE_INIT` (init process forked), and `SI_SUB_KTHREAD_INIT` (init made runnable). `mi_startup` is in `/usr/src/sys/kern/init_main.c`, and `start_init` is in the same file. + +**Common trap.** Assuming your driver's `attach` runs very early. It runs at `SI_SUB_CONFIGURE`, which is after locks, memory, and most subsystems are up. If you need to coordinate with something earlier, either use the event-handler system (`eventhandler(9)`) to hook a well-defined event, or place the work at the right `SYSINIT` stage. + +**Where the book teaches this.** Chapter 2 introduces the picture at boot-time. Chapter 6 connects `DRIVER_MODULE` to the `SYSINIT` chain conceptually. Appendix E goes into the subsystem-stage detail for readers who need it. + +**What to read next.** The `SYSINIT` definitions in `/usr/src/sys/sys/kernel.h`, the loop in `/usr/src/sys/kern/init_main.c`, and `/usr/src/sys/kern/subr_bus.c` for the Newbus side. + +### Kernel Compilation in One Paragraph + +A FreeBSD kernel is built from source by the ordinary `make` system invoked from `/usr/src`. The build takes a kernel configuration file (typically under `/usr/src/sys/amd64/conf/GENERIC` or a customised file you keep alongside it), compiles the selected options and device entries, and links the result into `kernel` plus a set of `.ko` files for devices not statically included. The standard commands are `make buildkernel KERNCONF=MYCONF` and `make installkernel KERNCONF=MYCONF`, run from `/usr/src`. For out-of-tree modules, the build uses `bsd.kmod.mk`, a short Makefile fragment that knows how to compile one or more `.c` files into a `.ko` file with the right kernel flags. Chapter 2 walks through both paths in lab context; the details are not repeated here. + +## Quick-Reference Tables + +The compact tables below are meant for scanning. They do not replace the sections above; they help you point at the right section fast. + +### Kernel Space vs User Space at a Glance + +| Property | Kernel space | User space | +| :-------------------------- | :------------------------------------- | :-------------------------------------- | +| Privilege | Full CPU privilege | Reduced, CPU-enforced | +| Address space | One, shared by all kernel threads | One per process, isolated | +| Memory stability | Stable while allocated | May be paged, unmapped, moved | +| Direct hardware access | Yes | No | +| Failure blast radius | Whole machine | One process | +| How to cross over | System call trap | `syscall` instruction (architecture) | +| Data copy primitive (into) | `copyin(9)`, `uiomove(9)` | (no equivalent; kernel does the copy) | +| Data copy primitive (out) | `copyout(9)`, `uiomove(9)` | (no equivalent; kernel does the copy) | + +### Driver Type Comparison + +| Driver type | Registers with | Main entry points | Main buffer type | Typical devices | +| :----------------- | :------------------- | :------------------------------ | :--------------- | :------------------------- | +| Character | `cdevsw` in devfs | `d_open`, `d_read`, `d_ioctl` | `struct uio` | Serial, sensors, `/dev/*` | +| Network | `ifnet` | `if_transmit`, receive path | `struct mbuf` | NICs, `tun`, `tap` | +| Storage (GEOM) | GEOM class/provider | `g_start`, `biodone(9)` | `struct bio` | Disks, `md`, `geli` | +| Pseudo (character) | `cdevsw` in devfs | Same as character | `struct uio` | `/dev/null`, `/dev/random` | +| Pseudo (network) | `ifnet` | Same as network | `struct mbuf` | `tun`, `tap`, `lo` | + +### Locking Primitive Selection + +| You need... | Use | +| :------------------------------------------ | :------------------------------------- | +| A default lock around softc fields | `mtx(9)` with `MTX_DEF` | +| A lock safe to hold in an interrupt filter | `mtx(9)` with `MTX_SPIN` | +| Many readers, occasional writer, may sleep | `sx(9)` | +| Wait for a predicate under a mutex | `cv(9)` together with the mutex | +| Atomic single-word read-modify-write | `atomic(9)` | + +### `softc` Lifecycle Checkpoint + +| Phase | Typical softc actions | +| :-------- | :------------------------------------------------------------- | +| `probe` | Read IDs, return `BUS_PROBE_*`. No softc allocation yet. | +| `attach` | `device_get_softc`, init lock, allocate resources, setup state. | +| Runtime | All operations dereference `sc`, all state updates under lock. | +| `suspend` | Save volatile hardware state, stop pending work. | +| `resume` | Restore state, restart work. | +| `detach` | Stop work, free resources in reverse order, destroy lock. | + +### Boot-to-Init Quick Map + +| Phase | Driver-relevant fact | +| :------------------------------------------ | :--------------------------------------------------------------- | +| Firmware + loader | Kernel and preloaded modules reach memory. | +| Kernel entry (`hammer_time` on amd64) | Machine-dependent early setup; no drivers yet. | +| `mi_startup` / `SYSINIT` chain | Subsystems initialise in `SI_SUB_*` order. | +| `SI_SUB_DRIVERS` / `SI_SUB_CONFIGURE` | Buses enumerate; compiled-in and preloaded drivers `probe` / `attach`. | +| `SI_SUB_ROOT_CONF` | Candidate root devices identified. | +| `SI_SUB_CREATE_INIT` / `SI_SUB_KTHREAD_INIT`| Init process forked, then made runnable. | +| `start_init` runs | Root filesystem mounted; `/sbin/init` execed as PID 1. | +| Runtime `kldload(8)` | Additional drivers attach after this point. | + +## Wrapping Up: How These OS Concepts Support Driver Development + +Each of the concepts in this appendix is already in use somewhere in the book. The appendix only assembles the pieces so that the reader can glance at the whole picture when one part feels out of focus. + +The kernel/user boundary is the reason driver code looks different from ordinary C. Every unusual rule, from `copyin(9)` to the short spin-safe interrupt filter, exists because the kernel runs in a privileged world that cannot afford to trust the less privileged one. Keep that framing and the rest follows. + +The driver types name the contracts with the rest of the kernel. Character, network, and GEOM are not ornaments; they are the standard interfaces that let userland and other subsystems reach your device without learning anything about its hardware. When you begin a new driver, naming the type is the first architectural decision you make. + +The recurring data structures name the shapes inside the driver. A queue for pending work. A buffer for bytes moving through the subsystem. A mutex around shared state. A softc that owns everything about one device. The shapes are small; the discipline they encode is what keeps the driver correct. + +The boot sequence names the stage on which your driver performs. The kernel did not spring into existence; it was assembled by a chain of well-defined steps, and your driver enters during one specific step at `SI_SUB_CONFIGURE`. Understanding the order of the steps turns early-boot bugs from mysteries into ordinary kernel diagnostics. + +Three habits keep these concepts active instead of dormant. + +The first is asking which side of the boundary you are on. Before you touch a pointer, ask whether it is a user pointer, a kernel pointer, or a bus address; the correct primitive follows immediately. + +The second is asking which subsystem you are speaking to. Before you reach for a buffer type, ask whether the code is in the character, network, or GEOM path; the right buffer follows immediately. + +The third is keeping a short companion sheet for the concepts you use most. The files under `examples/appendices/appendix-d-operating-system-concepts/` are meant for exactly that. A kernel-vs-user-space cheatsheet, a driver-type comparison, a softc lifecycle checklist, a boot-to-init timeline, and a "where drivers fit in the OS" diagram. The teaching is in this appendix; the application is in those sheets. + +With that, the operating-system side of the book has a consolidated home. The chapters keep teaching; this appendix keeps naming; the examples keep reminding. When a reader closes this appendix and opens an unfamiliar driver, the mental model is ready, and every line of kernel code has a place to attach to. diff --git a/content/appendices/appendix-e.md b/content/appendices/appendix-e.md index e64fd72..b73ef36 100644 --- a/content/appendices/appendix-e.md +++ b/content/appendices/appendix-e.md @@ -1,13 +1,581 @@ --- -title: "FreeBSD Internals and Kernel Reference" -description: "Comprehensive reference for FreeBSD kernel internals and APIs" +title: "Navigating FreeBSD Kernel Internals" +description: "A navigation-oriented map of the FreeBSD kernel subsystems that surround driver work, with the structures, source-tree locations, and driver touchpoints that help a reader orient themselves quickly." appendix: "E" -lastUpdated: "2025-08-01" -status: "planned" +lastUpdated: "2026-04-20" +status: "complete" author: "Edson Brandi" reviewer: "TBD" translator: "TBD" -estimatedReadTime: 35 +estimatedReadTime: 40 --- -planned +# Appendix E: Navigating FreeBSD Kernel Internals + +## How to Use This Appendix + +The main chapters teach you to build a FreeBSD device driver from the first `printf("hello")` module to a working PCI driver with DMA and interrupts. Underneath that progression is a large kernel with many moving parts, and the book cannot teach each of those parts from scratch without losing the thread of what you are actually trying to do. Most of the time you do not need to know every corner of the kernel. You just need to know where you are, which subsystem your current line of code is touching, which structure gives you the answer when you stop to look, and where in `/usr/src` the evidence lives. + +This appendix is that map. It does not try to teach each subsystem from first principles. It takes the seven subsystems a driver author meets most often and, for each one, gives you the short version: what it is for, which structures matter, which APIs your driver is likely to cross, where to open a file and look, and what to read next. You can think of it as the field guide you keep next to the chapters, not a replacement for them. + +### What You Will Find Here + +Each subsystem is covered with the same small pattern, so that you can skim one and know where to look in the next. + +- **What the subsystem is for.** A one-paragraph statement of the subsystem's responsibility. +- **Why a driver author should care.** The concrete reason your code meets this subsystem. +- **Key structures, interfaces, or concepts.** The short list of names that actually matter. +- **Typical driver touchpoints.** The specific places where a driver calls in, registers with, or receives a callback from the subsystem. +- **Where to look in `/usr/src`.** The two or three files that are worth opening first. +- **Manual pages and files to read next.** The next step when you want more depth. +- **Common beginner confusion.** The misunderstanding that costs people time. +- **Where the book teaches this.** Back-references into the chapters that use the subsystem in context. + +Not every entry needs every label, and no entry tries to be exhaustive. The aim is pattern recognition, not a full subsystem manual. + +### What This Appendix Is Not + +It is not an API reference. Appendix A is the API reference and goes deeper into flags, lifecycle phases, and caveats for each call. When the question is *what does this function do* or *which flag is right*, Appendix A is the place to look. + +It is not a concept tutorial either. Appendix D covers the operating-system mental model (kernel vs userland, driver types, the boot-to-init path), Appendix C covers the hardware model (physical memory, MMIO, interrupts, DMA), and Appendix B covers the algorithmic patterns (``, ring buffers, state machines, unwind ladders). If the question you want answered is "what is a process", "what is a BAR", or "which list macro should I use", one of those appendices is the right destination. + +It is also not a complete subsystem reference. A full tour of the VFS, the VM, or the network stack would be its own book. What you get here is the ten per cent of each subsystem a driver author actually meets, in the order in which a driver author meets it. + +## Reader Guidance + +Three ways to use this appendix, each calling for a different reading strategy. + +If you are **reading the main chapters**, keep the appendix open in a second window. When Chapter 5 introduces the kernel's memory allocators, glance at the Memory Subsystem section here to see where those allocators sit relative to UMA and the VM system. When Chapter 6 walks through `device_t`, softc, and the probe/attach lifecycle, the Driver Infrastructure section shows where those types fit into the Newbus layer. When Chapter 24 discusses `SYSINIT`, `eventhandler(9)`, and taskqueues, the Boot and Module System and Kernel Services sections give you the surrounding context in one page each. + +If you are **reading unfamiliar kernel code**, treat the appendix as a translator. When you see `struct mbuf` in a function signature, jump to the Network Subsystem section. When you see `struct bio`, jump to File and VFS. When you see `kobj_class_t` or `device_method_t`, jump to Driver Infrastructure. The goal during exploration is not to master the subsystem, just to name it. + +If you are **designing a new driver**, scan the subsystems your driver will touch before you start. A character driver for a small peripheral will lean on Driver Infrastructure and File and VFS. A network driver will add the Network Subsystem. A storage driver will add the GEOM and buffer cache layers. An early-boot driver on an embedded board will add the Boot and Module System section. Knowing which subsystems you will touch helps you guess the right headers and the right chapters before you write a line of code. + +A few conventions apply throughout: + +- Source paths are shown in the book-facing form, `/usr/src/sys/...`, matching the layout on a standard FreeBSD system. You can open any of them on your lab machine. +- Manual pages are cited in the usual FreeBSD style. Kernel-facing pages live in section 9: `kthread(9)`, `malloc(9)`, `uma(9)`, `bus_space(9)`, `eventhandler(9)`. Userland interfaces live in section 2 or 3 and are mentioned where they matter. +- When an entry points at a reading example, the file is one a beginner can read in one sitting. Larger files exist that also use each pattern; those are mentioned only when they are the canonical reference. + +With that in mind, we start with a one-page orientation to the whole kernel before drilling into subsystems one at a time. + +## How This Appendix Differs From Appendix A + +A driver author ends up consulting two very different kinds of reference while working. One kind answers the question *what is the exact name of the function or flag I need*. That is Appendix A. The other kind answers the question *which subsystem am I in, and where does this piece fit*. That is this appendix. + +Concretely, the difference shows up like this. When you want to know the signature of `malloc(9)`, the meaning of `M_WAITOK` versus `M_NOWAIT`, and which manual page to open, that is Appendix A. When you want to know that `malloc(9)` is a thin convenience on top of UMA, which in turn builds on the `vm_page_t` layer, which in turn depends on the per-architecture `pmap(9)`, that is this appendix. + +Both appendices cite real source paths and real manual pages. The split is deliberate. Keeping the API lookup separate from the subsystem map makes each one short enough to actually use. If an entry here starts to look like Appendix A, it has drifted from its role, and the right move is to read Appendix A instead. + +## A Map of the Major Subsystems + +Before you walk into any one subsystem, the shape of the whole kernel is worth naming. The FreeBSD kernel is large, but the pieces a driver author meets fit into a small set of families. The diagram below is the simplest honest picture. + +```text ++-----------------------------------------------------------------+ +| USER SPACE | +| applications, daemons, shells, tools, the libraries | ++-----------------------------------------------------------------+ + | + system-call trap (the boundary) + | ++-----------------------------------------------------------------+ +| KERNEL SPACE | +| | +| +-----------------------+ +-----------------------------+ | +| | VFS / devfs / GEOM | | Network stack | | +| | struct vnode, buf, | | struct mbuf, socket, | | +| | bio, vop_vector | | ifnet, route, VNET | | +| +-----------------------+ +-----------------------------+ | +| \ / | +| \ / | +| Driver infrastructure (Newbus) | +| device_t, driver_t, devclass_t, softc, kobj | +| bus_alloc_resource, bus_space, bus_dma | +| | | +| Process/thread subsystem | Memory / VM subsystem | +| struct proc, thread | vm_map, vm_object, vm_page | +| ULE scheduler, kthreads | pmap, UMA, pagers | +| | | +| Boot and module system (SYSINIT, KLD, modules) | +| Kernel services (eventhandler, taskqueue, callout) | ++-----------------------------------------------------------------+ + | + hardware I/O boundary + | ++-----------------------------------------------------------------+ +| HARDWARE | +| MMIO registers, interrupt controllers, DMA-capable memory | ++-----------------------------------------------------------------+ +``` + +Each of the labelled boxes above has a section below. The driver-infrastructure box in the middle is where every driver starts. The two boxes at the top are the subsystem entry points that a driver publishes to the rest of the kernel (character or storage on the left, network on the right). The two boxes in the middle rows are the horizontal services every driver relies on. The bottom boxes are the plumbing that gets the kernel running in the first place. + +Most drivers touch only three or four of these boxes in detail. The appendix is organised so that you can read only the ones your driver actually uses. + +## Process and Thread Subsystem + +### What the subsystem is for + +The process and thread subsystem manages every unit of execution inside FreeBSD. It owns the data structures that describe a running program, the scheduler that decides which thread runs next on which CPU, the machinery that creates and destroys kernel threads, and the rules that govern how a thread may block, sleep, or be preempted. Every line of kernel code, including your driver, is being executed by some thread, and the discipline the subsystem enforces is a direct constraint on what your driver is allowed to do. + +### Why a driver author should care + +Three practical reasons. First, the context your code runs in (interrupt filter, ithread, taskqueue worker, syscall thread from userland, dedicated kernel thread you spawned) decides whether you may sleep, may allocate memory with `M_WAITOK`, or may hold a sleep lock. Second, any driver that needs background work (a polling loop, a recovery watchdog, a deferred command handler) will create a kernel thread or a kproc to host it. Third, any driver that looks at the caller's process credentials (for security checks in `d_ioctl`, for example) reaches into the process structure. + +### Key structures, interfaces, or concepts + +- **`struct proc`** is the per-process descriptor. It records the process id, credentials, file-descriptor table, signal state, address space, and the list of threads that belong to the process. +- **`struct thread`** is the per-thread descriptor. It records the thread id, priority, run state, saved register context, the pointer to its owning `struct proc`, and the locks it currently holds. A FreeBSD kernel thread is also described by a `struct thread`; it simply has no userland side. +- **The ULE scheduler** is FreeBSD's default multi-processor scheduler. It assigns threads to CPUs, implements priority classes (real-time, time-sharing, idle), and honours interactivity and affinity hints. From a driver author's perspective, the most important fact about ULE is that it runs whichever thread is next, whenever a lock is released, a sleep ends, or an interrupt finishes; you cannot assume control of the CPU across such events. +- **`kthread_add(9)`** creates a new kernel thread inside an existing kernel process. Use it when you want a lightweight worker that shares state with an existing kproc (for example, extra worker threads inside a driver-specific kproc). +- **`kproc_create(9)`** creates a new kernel process, which comes with its own `struct proc` and one initial thread. Use it when you want an independent, top-level worker that `ps -axH` will show as a distinct name (for example, `g_event`, `usb`, `bufdaemon`). + +### Typical driver touchpoints + +- Interrupt handlers and `bus_setup_intr(9)` callbacks run in kernel-thread context created by the interrupt framework. +- A driver that needs long-running background work calls `kproc_create(9)` or `kthread_add(9)` from its `attach` path and joins the thread from `detach`. +- A driver that takes action on behalf of a user process reads `curthread` or `td->td_proc` to look at credentials, process id, or root-directory for validation. +- A driver that sleeps on a condition uses the sleep primitives, which record the sleeping thread and yield to the scheduler until woken. + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/proc.h` defines `struct proc` and `struct thread` and the macros that navigate between them. +- `/usr/src/sys/sys/kthread.h` declares the kernel-thread creation API. +- `/usr/src/sys/kern/kern_kthread.c` contains the implementation. +- `/usr/src/sys/kern/sched_ule.c` is the ULE scheduler source. + +### Manual pages and files to read next + +`kthread(9)`, `kproc(9)`, `curthread(9)`, `proc(9)`, and the header `/usr/src/sys/sys/proc.h`. If you want to see a driver that owns a kernel thread, `/usr/src/sys/dev/random/random_harvestq.c` is a readable example. + +### Common beginner confusion + +The most frequent trap is assuming that the thread running your driver code is a driver-owned thread. It is not. Most of the time it is a user thread that entered the kernel through a syscall, or an ithread that the interrupt framework created for you. Your driver only owns the threads it explicitly creates. Another recurring trap is reaching into `curthread->td_proc` from a context where `curthread` has nothing to do with the device (an interrupt ithread, for example); the process you find is not the process that asked for the operation. + +### Where the book teaches this + +Chapter 5 introduces kernel execution context and the sleep-versus-atomic distinction. Chapter 11 returns to it when concurrency becomes real. Chapter 14 uses taskqueues as a way to offload work into a safely sleepable context. Chapter 24 shows a full kproc lifecycle inside a driver. + +### Further reading + +- **In this book**: Chapter 11 (Concurrency in Drivers), Chapter 14 (Taskqueues and Deferred Work), Chapter 24 (Integrating with the Kernel). +- **Man pages**: `kthread(9)`, `kproc(9)`, `scheduler(9)`. +- **External**: McKusick, Neville-Neil, and Watson, *The Design and Implementation of the FreeBSD Operating System* (2nd ed.), chapters on process and thread management. + +## Memory Subsystem + +### What the subsystem is for + +The virtual-memory (VM) subsystem manages every byte of memory the kernel can address. It owns the mapping from virtual addresses to physical pages, the allocation of pages to processes and to the kernel, the paging policy that reclaims pages under pressure, and the page-backing stores that hand pages in from disk, from devices, or from zero. A driver that allocates memory, exposes memory to userland through `mmap`, or does DMA is interacting with the VM subsystem whether it names it or not. + +### Why a driver author should care + +Four practical reasons. First, every kernel allocation goes through this subsystem, directly or indirectly. Second, any driver that exports a memory-mapped view of a device (or of a software buffer) does so through a VM pager. Third, DMA involves physical addresses, and only the VM subsystem knows how virtual kernel addresses translate to them. Fourth, the subsystem defines the sleep rules for allocation: `M_WAITOK` may walk the VM's page-reclamation path, which is something you cannot do from an interrupt filter. + +### Key structures, interfaces, or concepts + +- **`vm_map_t`** represents a contiguous collection of virtual address mappings belonging to one address space. The kernel has its own `vm_map_t`, and each user process has one. Drivers almost never walk a `vm_map_t` directly; higher-level APIs do the walking for them. +- **`vm_object_t`** represents a backing store: a set of pages that can be mapped into a `vm_map_t`. Objects are typed by the pager that produces their pages (anonymous, vnode-backed, swap-backed, device-backed). +- **`vm_page_t`** represents one physical page of RAM, together with its current state (wired, active, inactive, free) and the object it currently belongs to. All physical memory in the system is tracked by an array of `vm_page_t` records. +- **The pager layer** is the set of pluggable strategies that fill pages with data. The three most important ones for driver authors are the swap pager (anonymous memory), the vnode pager (file-backed memory), and the device pager (memory whose content is produced by a driver). When a driver implements `d_mmap` or `d_mmap_single`, it is publishing a slice of the device pager. +- **`pmap(9)`** is the machine-dependent page-table manager. It knows how to translate virtual addresses into physical ones for the current CPU architecture. Drivers rarely call `pmap` directly. The portable way to see a physical view is through `bus_dma(9)` (for DMA) or `bus_space(9)` (for MMIO registers). +- **UMA** is FreeBSD's slab allocator for fixed-size objects, with per-CPU caches to avoid locking in the fast path. `malloc(9)` itself is implemented on top of UMA for common sizes. Drivers that allocate and free millions of identical small objects per second (network descriptors, per-request contexts) create their own UMA zone with `uma_zcreate` and reuse objects instead of walking the general allocator. + +### Typical driver touchpoints + +- `malloc(9)`, `free(9)`, `contigmalloc(9)` for general control-plane memory. +- `uma_zcreate(9)`, `uma_zalloc(9)`, `uma_zfree(9)` for high-rate fixed-size objects. +- `bus_dmamem_alloc(9)` and the rest of the `bus_dma(9)` interface for DMA-capable memory; this is the driver-facing wrapper around the physical side of the VM. +- `d_mmap(9)` or `d_mmap_single(9)` in a `cdevsw` method table to publish a device pager view of hardware memory to userland. +- `vm_page_wire(9)` and `vm_page_unwire(9)` only in the rare cases where the driver needs to pin pages of a user buffer across a long-running I/O. + +### Where to look in `/usr/src` + +- `/usr/src/sys/vm/vm.h` declares the `vm_map_t`, `vm_object_t`, and `vm_page_t` typedefs. +- `/usr/src/sys/vm/vm_map.h`, `/usr/src/sys/vm/vm_object.h`, and `/usr/src/sys/vm/vm_page.h` hold the full type definitions. +- `/usr/src/sys/vm/swap_pager.c`, `/usr/src/sys/vm/vnode_pager.c`, and `/usr/src/sys/vm/device_pager.c` are the three pagers most relevant to drivers. +- `/usr/src/sys/vm/uma.h` is the UMA public interface; `/usr/src/sys/vm/uma_core.c` is the implementation. +- `/usr/src/sys/vm/pmap.h` is the machine-independent pmap interface; the machine-specific side lives under `/usr/src/sys/amd64/amd64/pmap.c`, `/usr/src/sys/arm64/arm64/pmap.c`, and similar files for each architecture. + +### Manual pages and files to read next + +`malloc(9)`, `uma(9)`, `contigmalloc(9)`, `bus_dma(9)`, `pmap(9)`, and the header `/usr/src/sys/vm/uma.h`. For a readable driver that publishes a device pager, inspect `/usr/src/sys/dev/drm2/` or the framebuffer code under `/usr/src/sys/dev/fb/`. + +### Common beginner confusion + +Two traps. First, conflating the three pointer flavours a DMA-capable driver sees: the kernel virtual address (what your pointer dereferences), the physical address (what the memory controller sees), and the bus address (what the device sees, which may go through an IOMMU). `bus_dma(9)` exists precisely to keep these separate. Second, assuming that a `bus_dmamem_alloc(9)` allocation is a generic memory allocation; it is a specialised allocation with stricter alignment, boundary, and segment rules dictated by the tag you passed in. + +### Where the book teaches this + +Chapter 5 introduces kernel memory and the allocator flags. Chapter 10 revisits buffers in read/write paths. Chapter 17 introduces `bus_space` for MMIO access. Chapter 21 is the full DMA chapter and where the bus-versus-physical distinction becomes concrete. + +### Further reading + +- **In this book**: Chapter 5 (Understanding C for FreeBSD Kernel Programming), Chapter 21 (DMA and High-Speed Data Transfer). +- **Man pages**: `malloc(9)`, `uma(9)`, `contigmalloc(9)`, `bus_dma(9)`, `pmap(9)`. +- **External**: McKusick, Neville-Neil, and Watson, *The Design and Implementation of the FreeBSD Operating System* (2nd ed.), chapter on memory management. + +## File and VFS Subsystem + +### What the subsystem is for + +The file and VFS (Virtual File System) subsystem owns everything that userland sees through `open(2)`, `read(2)`, `write(2)`, `ioctl(2)`, `mmap(2)`, and the filesystem hierarchy in general. It dispatches operations to the correct filesystem through the vnode-operation vector, manages the buffer cache that sits between filesystems and storage drivers, and hosts the GEOM framework that lets storage drivers compose into stacks. For a driver author, this subsystem is either the main entry point (if you write a character or storage driver) or a quiet middle layer you are glad to let someone else worry about (if you write a network or embedded driver). + +### Why a driver author should care + +Three practical reasons. First, every character driver publishes itself to VFS through a `cdevsw` and a `/dev` node created by devfs. Second, every storage driver plugs into the bottom of a stack that the VFS and GEOM layers assemble on top, and the unit of work you receive is a `struct bio`, not a user pointer. Third, even a non-storage driver may need to understand vnodes and `mmap` if it publishes its memory to userland. + +### Key structures, interfaces, or concepts + +- **`struct vnode`** is the kernel's abstract file or device. It carries a type (regular file, directory, character device, block device, named pipe, socket, symbolic link), a pointer to its filesystem's `vop_vector`, the mount it belongs to, a reference count, and a lock. Every file descriptor in userland ultimately resolves to a vnode. +- **`struct vop_vector`** is the vnode-operation dispatch table: a pointer per operation (`VOP_LOOKUP`, `VOP_READ`, `VOP_WRITE`, `VOP_IOCTL`, and dozens more) that the filesystem or devfs implements. The vector is declared conceptually in `/usr/src/sys/sys/vnode.h` and generated from the operation list in `/usr/src/sys/kern/vnode_if.src`. +- **The GEOM framework** is FreeBSD's stackable storage layer. A GEOM *provider* is a storage surface; a *consumer* is something attaching to a provider. Drivers for storage hardware register as providers; classes such as `g_part`, `g_mirror`, or filesystems attach as consumers. The topology graph is dynamic and visible at runtime through `gpart show`, `geom disk list`, and `sysctl kern.geom`. +- **devfs** is the pseudo-filesystem that populates `/dev`. When your character driver calls `make_dev_s(9)`, devfs allocates a vnode-backed entry that forwards VFS operations into your `cdevsw` callbacks. devfs is the single layer between `open(2)` on a `/dev` path and `d_open` in your driver. +- **`struct buf`** is the traditional buffer-cache descriptor used by the old block-device path and by filesystems that layer on top of the buffer cache. It is still important because many filesystems drive I/O through `buf` objects before `buf_strategy()` funnels them into GEOM. +- **`struct bio`** is the modern per-operation descriptor that flows through GEOM. Every block read or write in GEOM is a `bio` with a command (`BIO_READ`, `BIO_WRITE`, `BIO_FLUSH`, `BIO_DELETE`), a range, a buffer pointer, and a completion callback. Your storage driver receives `bio`s on its start routine and calls `biodone()` (or the GEOM equivalent) when it finishes them. + +### Typical driver touchpoints + +- A character driver fills a `struct cdevsw` with callbacks (`d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl`, optionally `d_poll`, `d_mmap`) and calls `make_dev_s(9)` to attach it to `/dev`. +- A storage driver registers a GEOM class, implements a start routine that accepts `bio`s, and calls `g_io_deliver()` when it finishes them. +- A driver that wants to be visible as a file (for reading telemetry, for example) may expose a character device whose `d_read` copies driver data out. +- A driver that publishes device memory to userland implements `d_mmap` or `d_mmap_single` to hand back a device pager object. + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/vnode.h` declares `struct vnode` and the vnode-operation plumbing. +- `/usr/src/sys/kern/vnode_if.src` is the source of truth for every VOP in the kernel; read it to see the operation list and the locking protocol. +- `/usr/src/sys/fs/devfs/` holds the devfs implementation; `devfs_devs.c` and `devfs_vnops.c` are the readable entry points. +- `/usr/src/sys/geom/geom.h` declares providers, consumers, and the GEOM class interface. +- `/usr/src/sys/sys/buf.h` and `/usr/src/sys/sys/bio.h` declare the block-I/O structures. +- `/usr/src/sys/dev/null/null.c` is the simplest character driver in the tree and the right first read. + +### Manual pages and files to read next + +`vnode(9)`, `VOP_LOOKUP(9)` and the rest of the VOP family, `devfs(4)`, `devfs(5)`, `cdev(9)`, `make_dev(9)`, `g_attach(9)`, `geom(4)`, and the header `/usr/src/sys/sys/bio.h`. + +### Common beginner confusion + +Three traps. First, expecting a character driver to deal with `struct buf` or `struct bio`. It does not; those live in the storage path. A character driver sees `struct uio` on its `d_read` and `d_write` callbacks and nothing more. Second, expecting a storage driver to create a `/dev` node itself. In modern FreeBSD the GEOM layer creates the `/dev` entries for block devices; your storage driver registers with GEOM, and devfs does the rest on the other side of GEOM. Third, assuming the vnode and the cdev are the same object. They are not. The vnode is the VFS-side handle to the open file; the cdev is the driver-side identity. `open(2)` on `/dev/foo` produces a vnode whose operations forward into your `cdevsw`. + +### Where the book teaches this + +Chapter 7 writes the first character driver and the first `cdevsw`. Chapter 8 walks through `make_dev_s(9)` and devfs node creation. Chapter 9 connects `d_read` and `d_write` to `uio`. Chapter 27 is the storage chapter and introduces `struct bio`, GEOM providers and consumers, and the buffer cache. + +### Further reading + +- **In this book**: Chapter 7 (Writing Your First Driver), Chapter 8 (Working with Device Files), Chapter 27 (Working with Storage Devices and the VFS Layer). +- **Man pages**: `vnode(9)`, `make_dev(9)`, `devfs(5)`, `geom(4)`, `g_bio(9)`. +- **External**: McKusick, Neville-Neil, and Watson, *The Design and Implementation of the FreeBSD Operating System* (2nd ed.), chapters on the I/O system and local filesystems. + +## Network Subsystem + +### What the subsystem is for + +The network subsystem moves packets. It owns the data structures that represent a packet in flight (`mbuf` and friends), the per-interface state that represents a network device to the rest of the stack (`ifnet`), the routing tables that decide where a packet should go, the socket layer that userland sees, and the VNET infrastructure that lets multiple independent network stacks coexist in a single kernel. A network driver is the bottom layer of this stack: it hands packets up into the stack on receive, and the stack hands packets down into the driver on transmit. + +### Why a driver author should care + +Two reasons. If you write a network driver, nearly every byte you touch is a field of one of the structures named below, and the shape of your code is set by the protocols they enforce. If you write any other kind of driver, you still benefit from recognising `struct mbuf` and `struct ifnet` when you see them in code, because they turn up in many adjacent subsystems (packet filters, load-balancing helpers, virtual interfaces). + +### Key structures, interfaces, or concepts + +- **`struct mbuf`** is the packet fragment. Packets are represented as chains of mbufs, linked by `m_next` for a single packet and by `m_nextpkt` for consecutive packets in a queue. An mbuf carries a small header and either a small inline data area or a pointer into an external storage cluster. The design is optimised for cheap prepending of headers. +- **`struct m_tag`** is an extensible metadata tag attached to an mbuf. It lets the stack and drivers attach typed information to a packet (for example, hardware transmit-checksum offload, receive-side-scaling hash, filter decision) without enlarging the mbuf itself. +- **`ifnet`** (spelled `if_t` in modern APIs) is the per-interface descriptor. It carries the interface name and index, the flags, the MTU, a transmit function (`if_transmit`), the counters the stack increments, and the hooks that let higher layers deliver packets to the driver. +- **VNET** is the per-virtual-network-stack container. When `VIMAGE` is compiled in, every jail that enables VNET has its own routing table, its own set of interfaces, and its own protocol control blocks. Network drivers must be VNET-aware: they use `VNET_DEFINE` and `VNET_FOREACH` so that per-VNET state lives in the right place. +- **Routing** is the subsystem that selects a next-hop for an outbound packet. It owns the forwarding information base (FIB), a per-VNET radix tree of routes. Drivers rarely interact with routing directly; the stack has already chosen the interface before it reaches the driver. +- **The socket layer** is the kernel side of the `socket(2)` family of syscalls. For driver authors, the relevant fact is that a socket ultimately produces calls into `ifnet`, which produce calls into your driver. You do not implement sockets yourself. + +### Typical driver touchpoints + +- The driver allocates and populates an `ifnet` in `attach`, registers a transmit function, and calls `ether_ifattach(9)` or `if_attach(9)` to announce itself to the stack. +- The driver's transmit function receives an mbuf chain, writes descriptors, kicks the hardware, and returns. +- The receive path handles an interrupt or a poll, wraps received bytes in mbufs, and calls `if_input(9)` on the interface to push them up into the stack. +- On detach, the driver calls `ether_ifdetach(9)` or `if_detach(9)` before freeing its resources. +- The driver registers for `ifnet_arrival_event` or `ifnet_departure_event` if it needs to react when peers appear or disappear (see `/usr/src/sys/net/if_var.h` for the declarations). + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/mbuf.h` declares `struct mbuf` and `struct m_tag`. +- `/usr/src/sys/net/if.h` declares `if_t` and the public interface API. +- `/usr/src/sys/net/if_var.h` declares the interface-event eventhandlers and internal state. +- `/usr/src/sys/net/if_private.h` contains the full `struct ifnet` definition used inside the stack. +- `/usr/src/sys/net/vnet.h` declares the VNET infrastructure. +- `/usr/src/sys/net/route.h` and `/usr/src/sys/net/route/` hold the routing tables. +- `/usr/src/sys/sys/socketvar.h` declares `struct socket`. + +### Manual pages and files to read next + +`mbuf(9)`, `ifnet(9)`, `ether_ifattach(9)`, `vnet(9)`, `route(4)`, and `socket(9)`. For a small, readable real network driver, `/usr/src/sys/net/if_tuntap.c` is the canonical reading example. + +### Common beginner confusion + +Two traps. First, expecting a network driver to publish itself through `/dev`. It does not; it publishes itself through `ifnet` and becomes visible as `bge0`, `em0`, `igb0`, and so on, not through devfs. Second, holding onto an mbuf after handing it to the stack. Once you call `if_input` or return from `if_transmit`, the mbuf is no longer yours; using it afterwards corrupts the stack silently. + +### Where the book teaches this + +Chapter 28 is the full network-driver chapter and the right place for the details. Chapters 11 and 14 provide the locking and deferred-work discipline the receive path needs. Chapter 24 covers `ifnet_arrival_event` and related event hooks at a driver-integration level. + +### Further reading + +- **In this book**: Chapter 28 (Writing a Network Driver), Chapter 11 (Concurrency in Drivers), Chapter 14 (Taskqueues and Deferred Work). +- **Man pages**: `mbuf(9)`, `ifnet(9)`, `vnet(9)`, `socket(9)`. +- **External**: McKusick, Neville-Neil, and Watson, *The Design and Implementation of the FreeBSD Operating System* (2nd ed.), chapters on the network subsystem. + +## Driver Infrastructure (Newbus) + +### What the subsystem is for + +Newbus is FreeBSD's driver framework. It owns the tree of devices in the system, matches drivers to devices through probe, manages the lifecycle of each attachment, routes resource allocations to the right bus, and provides the object-oriented dispatch that lets buses override and extend each other's behaviour. Every character driver, storage driver, network driver, and embedded driver in the tree is a Newbus participant. If the other subsystems in this appendix are the rooms, Newbus is the hallway that connects them. + +### Why a driver author should care + +There is essentially no FreeBSD driver without Newbus. The types you meet first (`device_t`, softc, `driver_t`, `devclass_t`), the APIs you reach for in `attach` (`bus_alloc_resource_any`, `bus_setup_intr`), the macros you wrap the whole driver in (`DRIVER_MODULE`, `DEVMETHOD`, `DEVMETHOD_END`) all belong here. Learning to navigate Newbus is the same thing as learning to navigate FreeBSD driver source. + +### Key structures, interfaces, or concepts + +- **`device_t`** is an opaque handle to a node in the Newbus device tree. You receive one in `probe` and `attach`, pass it into almost every bus API, and use it to fetch the softc with `device_get_softc(9)`. +- **`driver_t`** is the descriptor for a driver: its name, its method table, and the size of its softc. You construct one for your driver and hand it to `DRIVER_MODULE(9)`, which registers it under a parent bus name. +- **`devclass_t`** is the per-driver-class registry: the collection of `device_t` instances a driver has attached. It is how the kernel gives each instance a unit number. +- **`kobj(9)`** is the object-oriented machinery underneath Newbus. Method tables, method dispatch, and the ability for a bus to inherit another bus's methods are all kobj features. As a driver author you use the `DEVMETHOD` macros, which expand into kobj metadata; you rarely call kobj primitives directly. +- **softc** is the per-instance state of your driver, allocated by the kernel when it allocates the `device_t`. The kernel knows how large your softc is because you told it in the `driver_t`. `device_get_softc(9)` gives you back a pointer to it. +- **`bus_alloc_resource(9)`** and friends allocate memory windows, I/O ports, and interrupt lines from the parent bus on behalf of your driver. They are the portable way to get at a device's resources without caring which bus it sits on. + +### Typical driver touchpoints + +- Declare a `device_method_t` array with `DEVMETHOD(device_probe, ...)`, `DEVMETHOD(device_attach, ...)`, `DEVMETHOD(device_detach, ...)`, terminated with `DEVMETHOD_END`. +- Declare a `driver_t` with your driver name, the methods, and `sizeof(struct mydev_softc)`. +- Use `DRIVER_MODULE(mydev, pci, mydev_driver, ...)` (or `usbus`, `iicbus`, `spibus`, `simplebus`, `acpi`, `nexus`) to register the driver under its parent bus. +- In `probe`, decide whether this device is yours and, if so, return `BUS_PROBE_DEFAULT` (or a weaker/stronger value) and a description. +- In `attach`, allocate resources with `bus_alloc_resource_any(9)`, map registers with `bus_space(9)`, set up interrupts with `bus_setup_intr(9)`, and only then expose yourself to the rest of the kernel. +- In `detach`, undo everything in reverse order. + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/bus.h` declares `device_t`, `driver_t`, `devclass_t`, `DEVMETHOD`, `DEVMETHOD_END`, `DRIVER_MODULE`, `bus_alloc_resource_any`, `bus_setup_intr`, and most of the rest. +- `/usr/src/sys/sys/kobj.h` declares the method-dispatch machinery. +- `/usr/src/sys/kern/subr_bus.c` holds the Newbus implementation. +- `/usr/src/sys/kern/subr_kobj.c` holds the kobj implementation. +- `/usr/src/sys/dev/null/null.c` and `/usr/src/sys/dev/led/led.c` are very small real drivers you can read in a sitting. + +### Manual pages and files to read next + +`device(9)`, `driver(9)`, `DEVMETHOD(9)`, `DRIVER_MODULE(9)`, `bus_alloc_resource(9)`, `bus_setup_intr(9)`, `kobj(9)`, and `devinfo(8)` to see the running Newbus tree. + +### Common beginner confusion + +Two traps. First, thinking that `device_t` and softc are the same object. `device_t` is the Newbus handle; softc is your driver's private state. You fetch softc from `device_t` with `device_get_softc(9)`. Second, forgetting that `DRIVER_MODULE`'s second argument is the parent bus name. A driver declared with `DRIVER_MODULE(..., pci, ...)` can only attach under a PCI bus, no matter how many PCI-like boards exist elsewhere. If a driver must attach under multiple buses (for example, a chip that appears both as PCI and as ACPI), you register it twice. + +### Where the book teaches this + +Chapter 6 is the full anatomy of a driver chapter and the canonical teaching location for everything above. Chapter 7 writes the first working driver against these APIs. Chapter 18 extends the picture for PCI. Chapter 24 returns to `DRIVER_MODULE`, `MODULE_VERSION`, and `MODULE_DEPEND` when kernel integration becomes the subject. + +### Further reading + +- **In this book**: Chapter 6 (The Anatomy of a FreeBSD Driver), Chapter 7 (Writing Your First Driver), Chapter 18 (Writing a PCI Driver). +- **Man pages**: `device(9)`, `driver(9)`, `DRIVER_MODULE(9)`, `bus_alloc_resource(9)`, `bus_setup_intr(9)`, `kobj(9)`, `rman(9)`. + +## Boot and Module System + +### What the subsystem is for + +The boot and module system is how the kernel gets into memory, how it initialises the hundreds of subsystems it depends on before anything can run, and how code that is not compiled into the kernel (loadable modules) is brought in, wired up, and eventually removed. From a driver author's perspective, the subsystem defines when your initialisation code runs relative to the rest of the kernel, and how your module-level `MOD_LOAD` and `MOD_UNLOAD` events interact with the kernel's internal initialisation order. + +### Why a driver author should care + +Three reasons. First, if your driver can be loaded as a module, it may run on a kernel whose subsystems have been ordered differently than you expect, and you need to declare what you depend on. Second, if your driver must run early (for example, a console driver or a boot-time storage driver), you must understand `SYSINIT(9)` subsystem IDs so that your code runs in the right slot. Third, even a plain driver relies on the module system to register itself, to declare ABI compatibility, and to fail cleanly if a dependency is missing. + +### Key structures, interfaces, or concepts + +- **The boot sequence** follows a fixed arc: the loader reads the kernel from disk, hands control to the kernel entry point, which sets up the early CPU state and then calls `mi_startup()`. `mi_startup()` walks a sorted list of `SYSINIT` entries, invoking each one in order. When the list is exhausted, the kernel has enough services up to start `init(8)` as user process 1. +- **`SYSINIT(9)`** is the macro that registers a function to be called at a specific phase of kernel initialisation. Each entry has a subsystem ID (`SI_SUB_*`, coarse ordering) and an order-within-subsystem (`SI_ORDER_*`, fine ordering). The full list of legal subsystem IDs is in `/usr/src/sys/sys/kernel.h` and is worth skimming once. `SYSUNINIT(9)` is the matching teardown. +- **Module loading** is driven by the KLD framework. `kldload(8)` invokes the linker, which relocates the module, resolves its symbols against the running kernel, and invokes the module's event handler with `MOD_LOAD`. A matching `MOD_UNLOAD` runs when the module is removed. Drivers rarely write module event handlers by hand; `DRIVER_MODULE(9)` produces one for you. +- **`MODULE_DEPEND(9)`** declares that your module requires another module (`usb`, `miibus`, `pci`, `iflib`) to be present, and at which version range. The kernel refuses to load your module if the dependency is missing. +- **`MODULE_VERSION(9)`** declares the ABI version your module exports, so that other modules can depend on it with `MODULE_DEPEND`. + +### Typical driver touchpoints + +- `DRIVER_MODULE(mydev, pci, mydev_driver, ...)` emits a module event handler that registers the driver on `MOD_LOAD` and deregisters it on `MOD_UNLOAD`. +- `MODULE_VERSION(mydev, 1);` announces your module's ABI version. +- `MODULE_DEPEND(mydev, pci, 1, 1, 1);` declares a pci dependency. +- A driver that must run before Newbus is available uses `SYSINIT(9)` to register a one-off setup hook at an early subsystem ID. +- A driver that wires a teardown hook at the last possible moment uses `SYSUNINIT(9)` with the matching ordering. + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/kernel.h` defines `SYSINIT`, `SYSUNINIT`, `SI_SUB_*`, and `SI_ORDER_*`. +- `/usr/src/sys/kern/init_main.c` contains `mi_startup()` and the walk through the SYSINIT list. +- `/usr/src/sys/sys/module.h` declares `MODULE_VERSION` and `MODULE_DEPEND`. +- `/usr/src/sys/sys/linker.h` and `/usr/src/sys/kern/kern_linker.c` implement the KLD linker. +- `/usr/src/stand/` holds the loader and the boot-time code. (On older FreeBSD releases this lived under `/usr/src/sys/boot/`; FreeBSD 14 hosts it entirely under `/usr/src/stand/`.) + +### Manual pages and files to read next + +`SYSINIT(9)`, `kld(9)`, `kldload(9)`, `kldload(8)`, `kldstat(8)`, `module(9)`, `MODULE_VERSION(9)`, and `MODULE_DEPEND(9)`. For a short real `SYSINIT` example, look near the top of `/usr/src/sys/dev/random/random_harvestq.c`. + +### Common beginner confusion + +Two traps. First, assuming that `MOD_LOAD` is the moment your `attach` function runs. It is not. `MOD_LOAD` is the moment your *driver* is registered with Newbus; `attach` runs later, per device, whenever a bus offers a matching child. Second, using `SYSINIT` levels as if they were arbitrary. Each `SI_SUB_*` corresponds to a well-defined phase of kernel startup, and registering your hook at the wrong phase either makes it run too early (with half the kernel missing) or too late (after the event you cared about has passed). + +### Where the book teaches this + +Chapter 6 introduces `DRIVER_MODULE`, `MODULE_VERSION`, and `MODULE_DEPEND` as part of driver anatomy. Chapter 24 covers kernel-integration topics including `SYSINIT`, subsystem IDs, and module teardown ordering. Chapter 32 returns to boot-time concerns on embedded platforms. + +### Further reading + +- **In this book**: Chapter 24 (Integrating with the Kernel), Chapter 32 (Device Tree and Embedded Development). +- **Man pages**: `SYSINIT(9)`, `module(9)`, `MODULE_VERSION(9)`, `MODULE_DEPEND(9)`, `kldload(8)`, `kldstat(8)`. + +## Kernel Services + +### What the subsystem is for + +The kernel ships a small set of general-purpose services that are not tied to any one subsystem but show up repeatedly in drivers: event notifications, deferred-work queues, timed callbacks, and subscription hooks. None of them teaches you how to write a driver, but all of them turn up in real driver code, and recognising them speeds up every code-reading session. This section collects the handful you are likely to meet. + +### Why a driver author should care + +Drivers often need to react to system-wide events (shutdown, low memory, interface arrival, root filesystem mount), or to do work outside the context that delivered the event (away from an interrupt filter, away from a spin-locked critical section). The kernel services below are the standard FreeBSD answers to both needs. Using them means your driver integrates cleanly with the rest of the system; reimplementing them means you will eventually collide with a subsystem that expects your hooks to exist. + +### Key structures, interfaces, or concepts + +- **`eventhandler(9)`** is the publish/subscribe system for kernel events. A publisher declares an event with `EVENTHANDLER_DECLARE`, a subscriber registers with `EVENTHANDLER_REGISTER`, and invocation with `EVENTHANDLER_INVOKE` fans out to every subscriber. Standard event tags defined in `/usr/src/sys/sys/eventhandler.h` include `shutdown_pre_sync`, `shutdown_post_sync`, `shutdown_final`, `vm_lowmem`, and `mountroot`; interface events (`ifnet_arrival_event`, `ifnet_departure_event`) are declared in `/usr/src/sys/net/if_var.h`. Drivers use these to clean up, to release memory, to react when a sibling interface appears, or to delay early work until the root filesystem is available. +- **`taskqueue(9)`** is a queue of deferred work items. A driver enqueues a task from a context that cannot sleep (for example, an interrupt filter) and the task later runs on a dedicated worker thread where sleeping and blocking are allowed. The kernel ships a small set of system-wide taskqueues (`taskqueue_swi`, `taskqueue_thread`, `taskqueue_fast`) and lets you create your own. +- **Grouped taskqueues (`gtaskqueue`)** extend `taskqueue` with CPU affinity and rebalancing; they are heavily used in `iflib` and in the high-rate network stack. The declarations live in `/usr/src/sys/sys/gtaskqueue.h`. +- **`callout(9)`** is the kernel's one-shot and periodic timer. A driver arms a callout with a future deadline and receives a callback when the deadline arrives. `callout(9)` replaces almost every ad-hoc "sleep for N ticks" loop a driver might otherwise write. +- **`hooks(9)`-style subsystem extension points.** A number of FreeBSD subsystems publish registration APIs that behave like eventhandlers but are specific to the subsystem (for example, packet filters register with `pfil(9)`; disk drivers can register with `disk(9)` events). These are not one unified interface, but the pattern is the same: a list of callbacks that a subsystem invokes at a well-defined moment. + +### Typical driver touchpoints + +- `EVENTHANDLER_REGISTER(shutdown_pre_sync, mydev_shutdown, softc, SHUTDOWN_PRI_DEFAULT);` in `attach` so the driver flushes hardware before a reboot; `EVENTHANDLER_DEREGISTER` in `detach`. (The three standard priority constants for shutdown hooks are `SHUTDOWN_PRI_FIRST`, `SHUTDOWN_PRI_DEFAULT`, and `SHUTDOWN_PRI_LAST`, declared in `/usr/src/sys/sys/eventhandler.h`.) +- `taskqueue_create("mydev", M_WAITOK, ...); taskqueue_start_threads(...);` in `attach` to create a per-device worker; `taskqueue_drain_all` and `taskqueue_free` in `detach`. +- `callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0)` in `attach` to arm a watchdog; `callout_drain` in `detach`. +- Grouped taskqueues are most visible inside `iflib`-based network drivers; a typical standalone driver rarely reaches for them directly. + +### Where to look in `/usr/src` + +- `/usr/src/sys/sys/eventhandler.h` and `/usr/src/sys/kern/subr_eventhandler.c` for event handlers. +- `/usr/src/sys/sys/taskqueue.h` and `/usr/src/sys/kern/subr_taskqueue.c` for taskqueues. +- `/usr/src/sys/sys/gtaskqueue.h` and `/usr/src/sys/kern/subr_gtaskqueue.c` for grouped taskqueues. +- `/usr/src/sys/sys/callout.h` and `/usr/src/sys/kern/kern_timeout.c` for callouts. + +### Manual pages and files to read next + +`eventhandler(9)`, `taskqueue(9)`, `callout(9)`, and the header `/usr/src/sys/sys/eventhandler.h`. Look at `/usr/src/sys/dev/random/random_harvestq.c` for a driver that uses `SYSINIT` and a dedicated kproc cleanly; it is a good companion when reading about kernel services even though it does not itself exercise `taskqueue(9)` or `callout(9)`. + +### Common beginner confusion + +One important trap: forgetting that registration is half of the contract. Every `EVENTHANDLER_REGISTER` needs an `EVENTHANDLER_DEREGISTER` at the matching lifecycle moment, every `taskqueue_create` needs a `taskqueue_free`, and every armed `callout` needs a `callout_drain` before its memory is freed. A leaked registration keeps a dangling pointer into freed memory; the next invocation of the event will then crash the kernel in a subsystem that has nothing to do with your driver. + +### Where the book teaches this + +Chapter 13 introduces `callout(9)`. Chapter 14 is the taskqueue chapter. Chapter 24 is the kernel-integration chapter and covers `eventhandler(9)` and the SYSINIT/module cooperation in context. + +### Further reading + +- **In this book**: Chapter 13 (Timers and Delayed Work), Chapter 14 (Taskqueues and Deferred Work), Chapter 24 (Integrating with the Kernel). +- **Man pages**: `eventhandler(9)`, `taskqueue(9)`, `callout(9)`. + +## Cross-References: Structures and Their Subsystems + +The table below is the fastest way to turn an unfamiliar type into a known subsystem. Use it when you are reading driver source, hit a struct name you do not recognise, and want to know which section of this appendix to open. + +| Structure or type | Subsystem | Where declared | +| :------------------------ | :---------------------------- | :------------------------------------------------- | +| `struct proc`, `thread` | Process and Thread | `/usr/src/sys/sys/proc.h` | +| `vm_map_t` | Memory (VM) | `/usr/src/sys/vm/vm.h` and `/usr/src/sys/vm/vm_map.h` | +| `vm_object_t` | Memory (VM) | `/usr/src/sys/vm/vm.h` and `/usr/src/sys/vm/vm_object.h` | +| `vm_page_t` | Memory (VM) | `/usr/src/sys/vm/vm.h` and `/usr/src/sys/vm/vm_page.h` | +| `uma_zone_t` | Memory (VM) | `/usr/src/sys/vm/uma.h` | +| `struct vnode` | File and VFS | `/usr/src/sys/sys/vnode.h` | +| `struct vop_vector` | File and VFS | generated from `/usr/src/sys/kern/vnode_if.src` | +| `struct buf` | File and VFS | `/usr/src/sys/sys/buf.h` | +| `struct bio` | File and VFS (GEOM) | `/usr/src/sys/sys/bio.h` | +| `struct g_provider` | File and VFS (GEOM) | `/usr/src/sys/geom/geom.h` | +| `struct cdev` | File and VFS (devfs) | `/usr/src/sys/sys/conf.h` | +| `struct cdevsw` | File and VFS (devfs) | `/usr/src/sys/sys/conf.h` | +| `struct mbuf`, `m_tag` | Network | `/usr/src/sys/sys/mbuf.h` | +| `if_t`, `struct ifnet` | Network | `/usr/src/sys/net/if.h`, `/usr/src/sys/net/if_private.h` | +| `struct socket` | Network | `/usr/src/sys/sys/socketvar.h` | +| `device_t` | Driver Infrastructure | `/usr/src/sys/sys/bus.h` | +| `driver_t`, `devclass_t` | Driver Infrastructure | `/usr/src/sys/sys/bus.h` | +| `device_method_t` | Driver Infrastructure (kobj) | `/usr/src/sys/sys/bus.h` (kobj in `sys/kobj.h`) | +| `struct resource` | Driver Infrastructure | `/usr/src/sys/sys/rman.h` | +| `SYSINIT`, `SI_SUB_*` | Boot and Module | `/usr/src/sys/sys/kernel.h` | +| `MODULE_VERSION`, `MODULE_DEPEND` | Boot and Module | `/usr/src/sys/sys/module.h` | +| `eventhandler_tag` | Kernel Services | `/usr/src/sys/sys/eventhandler.h` | +| `struct taskqueue` | Kernel Services | `/usr/src/sys/sys/taskqueue.h` | +| `struct callout` | Kernel Services | `/usr/src/sys/sys/callout.h` | + +When a type is not in the table, search `/usr/src/sys/sys/` or `/usr/src/sys//` for its declaration; the comment near the definition usually names the subsystem outright. + +## Source-Tree Navigation Checklists + +The FreeBSD source tree is organised by responsibility, and once you know the pattern you can guess where almost anything lives. The lists below are the five quick questions that turn "where in the tree" into "open this file". + +### When you have a structure name + +1. Is it a low-level primitive (`proc`, `thread`, `vnode`, `buf`, `bio`, `mbuf`, `callout`, `taskqueue`, `eventhandler`)? Look in `/usr/src/sys/sys/` first. +2. Is it a VM type (`vm_*`, `uma_*`)? Look in `/usr/src/sys/vm/`. +3. Is it a network type (`ifnet`, `if_*`, `m_tag`, `route`, `socket`, `vnet`)? Look in `/usr/src/sys/net/`, `/usr/src/sys/netinet/`, or `/usr/src/sys/netinet6/`. +4. Is it a device or bus type (`device_t`, `driver_t`, `resource`, `rman`, `pci_*`, `usbus_*`)? Look in `/usr/src/sys/sys/bus.h`, `/usr/src/sys/sys/rman.h`, or the matching bus directory under `/usr/src/sys/dev/`. +5. Is it something else entirely? `grep -r 'struct NAME {' /usr/src/sys/sys/ /usr/src/sys/kern/ /usr/src/sys/vm/ /usr/src/sys/net/` usually finds it in one pass. + +### When you have a function name + +1. If the name starts with `vm_`, it lives under `/usr/src/sys/vm/`. +2. If it starts with `bus_`, `device_`, `driver_`, `devclass_`, `resource_`, it lives in `/usr/src/sys/kern/subr_bus.c`, `/usr/src/sys/kern/subr_rman.c`, or one of the bus-specific directories. +3. If it starts with `vfs_`, `vn_`, or a `VOP_` prefix, it lives under `/usr/src/sys/kern/vfs_*.c` or one of the filesystems under `/usr/src/sys/fs/`. +4. If it starts with `g_`, it is GEOM; look in `/usr/src/sys/geom/`. +5. If it starts with `if_`, `ether_`, or `in_`, it is networking; look in `/usr/src/sys/net/` or `/usr/src/sys/netinet/`. +6. If it starts with `kthread_`, `kproc_`, `sched_`, or `proc_`, it is the process/thread subsystem under `/usr/src/sys/kern/`. +7. If it starts with `uma_` or `malloc`, it is memory; look in `/usr/src/sys/vm/uma_core.c` or `/usr/src/sys/kern/kern_malloc.c`. +8. When nothing matches, `grep -rl '\bFUNC_NAME\s*(' /usr/src/sys/` is slower but exhaustive. + +### When you have a macro name + +1. `SYSINIT`, `SYSUNINIT`, `SI_SUB_*`, `SI_ORDER_*`: `/usr/src/sys/sys/kernel.h`. +2. `DRIVER_MODULE`, `DEVMETHOD`, `DEVMETHOD_END`, `MODULE_VERSION`, `MODULE_DEPEND`: `/usr/src/sys/sys/bus.h` and `/usr/src/sys/sys/module.h`. +3. `EVENTHANDLER_*`: `/usr/src/sys/sys/eventhandler.h`. +4. `VNET_*`, `CURVNET_*`: `/usr/src/sys/net/vnet.h`. +5. `TAILQ_*`, `LIST_*`, `STAILQ_*`, `SLIST_*`: `/usr/src/sys/sys/queue.h`. +6. `VOP_*`: generated from `/usr/src/sys/kern/vnode_if.src`, visible in `sys/vnode_if.h` once the kernel is built. + +### When you have a subsystem question + +1. What initialises the kernel and in which order? `/usr/src/sys/kern/init_main.c`. +2. What drivers does the tree contain? `ls /usr/src/sys/dev/` and its subdirectories. +3. Where are network-stack entry points? `/usr/src/sys/net/if.c`, `/usr/src/sys/netinet/`, and their siblings. +4. How does a specific syscall reach a driver? start in `/usr/src/sys/kern/syscalls.master`, follow the dispatcher into the relevant VFS or socket code, and keep reading until the dispatch lands in a `cdevsw`, a `vop_vector`, or an `ifnet`. + +## Manual Pages and Source Reading Itinerary + +Pattern recognition across the kernel comes from reading it, not only from reading about it. A self-study plan that covers the subsystems in this appendix might look like this: + +1. `intro(9)` plus a walk of `/usr/src/sys/sys/` file names, fifteen minutes total. +2. `kthread(9)`, `kproc(9)`, and `/usr/src/sys/sys/proc.h`. +3. `malloc(9)`, `uma(9)`, `bus_dma(9)`, and `/usr/src/sys/vm/uma.h`. +4. `vnode(9)`, `cdev(9)`, `make_dev(9)`, `devfs(4)`, and `/usr/src/sys/dev/null/null.c`. +5. `mbuf(9)`, `ifnet(9)`, `ether_ifattach(9)`, and `/usr/src/sys/net/if_tuntap.c`. +6. `device(9)`, `DRIVER_MODULE(9)`, `bus_alloc_resource(9)`, and `/usr/src/sys/dev/led/led.c`. +7. `SYSINIT(9)`, `kld(9)`, `module(9)`, and the top of `/usr/src/sys/kern/init_main.c`. +8. `eventhandler(9)`, `taskqueue(9)`, `callout(9)`, and `/usr/src/sys/dev/random/random_harvestq.c`. + +The companion files in `examples/appendices/appendix-e-navigating-freebsd-kernel-internals/` collect the same itinerary in a form you can print, annotate, and keep next to the machine. + +## Wrapping Up: How to Keep Exploring the Kernel Safely + +Exploring a kernel source tree can feel endless, and it is easy to lose a weekend chasing one interesting thread through ten subsystems. A small set of habits keeps the exploration productive. + +Read in short sessions with a specific question. "What does `bus_setup_intr` actually do under the hood" is a good session. "Read the VM" is not. + +Keep the map in view. When you jump from a driver into the VFS, remind yourself that you are now in the VFS and that the rules of the VFS apply. When you return to the driver, remind yourself that the VFS stopped at the function boundary. Each subsystem has its own invariants and its own locking discipline, and they rarely carry over. + +Write down what you find. A short note like "`bus_alloc_resource_any` in subr_bus.c calls into `BUS_ALLOC_RESOURCE` via kobj dispatch, which the PCI bus method implements in `pci.c`" is worth more than an afternoon of passive reading. The appendix and its companion files are there to give you anchor points for exactly this kind of note-taking. + +Use the safety rails. `/usr/src/sys/dev/null/null.c` and `/usr/src/sys/dev/led/led.c` are tiny. `/usr/src/sys/net/if_tuntap.c` is small enough to read in a sitting. `/usr/src/sys/dev/random/random_harvestq.c` uses real kernel services without hiding behind layers of abstraction. Start from these whenever a subsystem feels too large to approach directly. + +And remember that the goal is not to memorise the kernel. It is to build enough pattern recognition that, the next time you open an unfamiliar driver or a new subsystem, the structures, the functions, and the source paths feel like neighbourhoods you have already walked through. This appendix, together with Appendices A through D and the chapters that teach the pieces in context, is designed to make that feeling arrive sooner. + +When the map here is not enough, the book is. When the book is not enough, the source is. And the source is already sitting on your FreeBSD machine, waiting to be read. diff --git a/content/appendices/appendix-f.md b/content/appendices/appendix-f.md new file mode 100644 index 0000000..1b78047 --- /dev/null +++ b/content/appendices/appendix-f.md @@ -0,0 +1,315 @@ +--- +title: "Benchmark Harness and Results" +description: "A reproducible benchmark harness, with working source code and representative measurements, for the performance claims made in Chapters 15, 28, 33, and 34." +appendix: "F" +lastUpdated: "2026-04-21" +status: "complete" +author: "Edson Brandi" +reviewer: "TBD" +translator: "TBD" +estimatedReadTime: 35 +--- + +# Appendix F: Benchmark Harness and Results + +## How to Use This Appendix + +Several chapters in this book make performance claims. Chapter 15 gives order-of-magnitude timings for `mtx_lock`, `sx_slock`, condition variables, and semaphores. Chapter 28 notes that driver code typically shrinks by thirty to fifty percent when a network driver is converted to `iflib(9)`. Chapter 33 discusses the cost hierarchy of timecounter sources, with TSC at one end, HPET at the other, and ACPI-fast in the middle. Chapter 34 describes the run-time cost of debug kernels with `INVARIANTS` or `WITNESS` enabled, and of kernels with active DTrace scripts attached. Every one of those claims is qualified in the text with a phrase such as "on typical FreeBSD 14.3-amd64 hardware", "in our lab environment", or "order-of-magnitude". The qualifiers exist because the absolute numbers depend on the specific machine, the specific workload, and the specific compiler that built the kernel. + +This appendix exists so that those qualifiers stand on reproducible ground. For each class of claim, the companion tree under `examples/appendices/appendix-f-benchmarks/` contains a working harness that the reader can build, run, and extend. Where a harness is portable and does not require hardware access, this appendix also reports the measurement it produces on a known machine, so that readers have a concrete number to compare against. Where a harness requires a specific kernel configuration that cannot be assumed to exist on any given reader's machine, only the harness itself is provided, together with clear instructions for reproducing it. + +The aim is not to replace the Chapter 15 or Chapter 34 claims with authoritative figures. It is to let readers see how the claims were arrived at, to let them verify the claims on their own hardware, and to make the results honest about what varies with environment and what does not. + +### How this appendix is organised + +The appendix has five benchmark sections, each with the same internal structure. + +- **What is being measured.** One paragraph describing the claim from the chapter and the quantity the harness measures. +- **The harness.** The filesystem location of the companion files, the programming language used, and a short description of the approach. +- **How to reproduce.** The exact command or command sequence the reader runs. +- **Representative result.** A measured value, or "harness only, no result captured" when the harness has not been run by the author. +- **Hardware envelope.** The range of machines over which the result is expected to generalise, and the range over which it is known not to. + +The five sections in order are timecounter read cost, synchronization primitive latency, iflib driver code-size reduction, and DTrace-with-INVARIANTS-and-WITNESS overhead. A final section on scheduler wakeup latency points at the existing Chapter 33 script rather than introducing a new one, since the script there is already the harness. + +## Hardware and Software Setup + +Before presenting the benchmarks, a word on the envelope. The numbers in this appendix and the representative results quoted inside it come from two kinds of measurement. + +The first kind is **portable measurement**: anything that counts lines of source code, reads the output of a deterministic tool, or otherwise depends only on the FreeBSD source tree and a working compiler. Those measurements produce the same result on any host that has the same source checkout. The iflib code-size comparison in Section 4 is the only portable measurement in the appendix, and its result can be reproduced exactly on any machine with `/usr/src` synchronised to a FreeBSD 14.3-RELEASE source tag. + +The second kind is **hardware-dependent measurement**: anything that times a kernel path, a syscall, or a hardware register read. Those measurements depend on the CPU, the memory hierarchy, and the kernel configuration. For every hardware-dependent benchmark in this appendix, the harness is provided, the reproduction steps are precise, and a representative result is quoted only when the author has actually run the harness on a known machine. Where the author has not, the appendix says so explicitly and leaves the results table blank for the reader to fill in. + +The fairer phrasing is that this appendix is a **runnable field guide**. The chapters quote qualified figures; the appendix shows you how to measure the same quantities on the hardware in front of you, and what to expect if your hardware belongs to the same broad family as the hardware the chapters had in mind ("modern amd64", "Intel and AMD generations currently in service"). + +### Caveats that apply to every section + +A few caveats apply throughout, and it is simpler to name them once than to repeat them in each section. + +All the hardware-dependent harnesses measure averages over large loops. Averages hide tail behaviour. A P99 latency can be an order of magnitude higher than the mean on the same path, especially for anything that involves a scheduler wakeup. Any serious performance claim in production will need a distributional measurement, not a single number; this appendix is about the mean because that is what the chapter claims refer to. + +Readers running these harnesses under virtualisation should expect significantly noisier results than on bare metal. A virtualised TSC, for example, may be synthesised by the hypervisor in a way that adds hundreds of nanoseconds to every read. The Chapter 33 cost hierarchy still holds qualitatively under virtualisation, but the absolute numbers will move. + +Finally, none of these harnesses are intended for use in production kernels. The sync-primitive kmod in particular spawns kernel threads that do tight no-op loops; it is safe to load for a few seconds on a development machine and unload, but it should not be loaded on a busy server. + +## Timecounter Read Cost + +### What is being measured + +Chapter 33 describes a three-way cost hierarchy for timecounter sources in FreeBSD: TSC is cheap to read, ACPI-fast is moderately expensive, and HPET is expensive. The claim is qualified with "on the Intel and AMD generations currently in service", and separately with "on typical FreeBSD 14.3-amd64 hardware". The harness in this section measures the average cost of one `clock_gettime(CLOCK_MONOTONIC)` call, which the kernel resolves through whichever source `kern.timecounter.hardware` currently selects, and separately the cost of a bare `rdtsc` instruction as a floor. + +The quantity measured is nanoseconds per call, averaged over ten million iterations. The underlying kernel path is `sbinuptime()` in `/usr/src/sys/kern/kern_tc.c`, which reads the current timecounter's `tc_get_timecount` method, scales it, and returns the result as an `sbintime_t`. + +### The harness + +The harness lives under `examples/appendices/appendix-f-benchmarks/timecounter/` and is composed of three pieces. + +`tc_bench.c` is a small userland program that calls `clock_gettime(CLOCK_MONOTONIC)` in a tight loop and reports the average nanoseconds per call. It reads `kern.timecounter.hardware` at startup and prints the current source name, so that each run is self-documenting. + +`rdtsc_bench.c` is a companion userland program that reads the `rdtsc` instruction directly, using the inline assembly pattern that the kernel uses in its own `rdtsc()` wrapper in `/usr/src/sys/amd64/include/cpufunc.h`. Its output is the cost of the instruction itself, without any kernel overhead. + +`run_tc_bench.sh` is a root-only shell wrapper that reads `kern.timecounter.choice` (the list of available sources for the current kernel), iterates over each entry, sets `kern.timecounter.hardware` to that source, runs `tc_bench`, and restores the original setting on exit. The result is a table with one row per timecounter source, ready to compare. + +### How to reproduce + +Build the two userland programs: + +```console +$ cd examples/appendices/appendix-f-benchmarks/timecounter +$ make +``` + +Run the rotation (requires root to flip the sysctl): + +```console +# sh run_tc_bench.sh +``` + +Or just the direct TSC floor: + +```console +$ ./rdtsc_bench +``` + +### Representative result + +Harness only, no result captured. The harness has been compiled and its logic reviewed, but the author has not run it on the reference machine while writing this appendix. A reader running the harness on typical FreeBSD 14.3-amd64 hardware should expect the TSC column to report values in the low tens of nanoseconds, the ACPI-fast column to report values several times higher, and the HPET column (if available and not disabled in firmware) to report values an order of magnitude higher still. The absolute numbers will vary with CPU generation, power state, and whether `clock_gettime` is served by the fast-gettime path or falls through to the full syscall. + +### Hardware envelope + +The ordering of the three timecounter sources by cost has been stable across amd64 generations since invariant TSC became standard in the mid-2000s. Readers on different CPU vendors or different microarchitectural generations will see different absolute numbers but the same ordering. On ARM64, there is no HPET or ACPI-fast in the usual sense, and the relevant comparison is between the Generic Timer counter register and the software paths that wrap it; the harness will still run, but only one entry will appear in the table. If `kern.timecounter.choice` on the reader's machine shows a single source, that is itself a useful data point: the system's firmware has restricted the choice, and no rotation is possible. + +See also Chapter 33 for the surrounding context, particularly the section on `sbinuptime()` and the discussion of why driver code should avoid reading `rdtsc()` directly. + +## Synchronization Primitive Latencies + +### What is being measured + +Chapter 15 presents a table of approximate per-operation costs for FreeBSD's synchronization primitives: atomics at a nanosecond or two, uncontended `mtx_lock` at tens of nanoseconds, uncontended `sx_slock` and `sx_xlock` slightly higher, and `cv_wait`/`sema_wait` at microseconds because they always involve a full scheduler wakeup. The numbers in the table are described as "order-of-magnitude estimates on typical FreeBSD 14.3 amd64 hardware", with the caveat that they "can move by a factor of two or more across CPU generations". The harness in this section measures each row of that table directly. + +The quantities measured are: + +- Nanoseconds per `mtx_lock` / `mtx_unlock` pair on an uncontended mutex. +- Nanoseconds per `sx_slock` / `sx_sunlock` pair on an uncontended sx. +- Nanoseconds per `sx_xlock` / `sx_xunlock` pair on an uncontended sx. +- Nanoseconds per one-shot `cv_signal` / `cv_wait` round-trip between two kernel threads. +- Nanoseconds per one-shot `sema_post` / `sema_wait` round-trip between two kernel threads. + +### The harness + +The harness lives under `examples/appendices/appendix-f-benchmarks/sync/` and is a single loadable kernel module, `sync_bench.ko`. The module exposes five write-only sysctls under `debug.sync_bench.` (one per benchmark) and five read-only sysctls that report the most recent result for each benchmark. + +Each benchmark times a fixed number of iterations using `sbinuptime()` in `/usr/src/sys/kern/kern_tc.c` for the timestamps. The mutex, sx_slock, and sx_xlock benchmarks run entirely in the calling thread and exercise only the uncontended fast path. The cv and sema benchmarks spawn a worker kproc that signs a ping/pong protocol with the main thread; every iteration therefore includes one wakeup and one context switch in each direction, which is precisely what Chapter 15's "wakeup latency" column measures. + +The module follows the kmod pattern used in other chapters of this book, declared with `DECLARE_MODULE` and initialised through `SI_SUB_KLD / SI_ORDER_ANY`. Sources are `/usr/src/sys/kern/kern_mutex.c` for `mtx_lock`, `/usr/src/sys/kern/kern_sx.c` for `sx_slock` / `sx_xlock`, `/usr/src/sys/kern/kern_condvar.c` for condition variables, and `/usr/src/sys/kern/kern_sema.c` for counting semaphores. + +### How to reproduce + +Build the module: + +```console +$ cd examples/appendices/appendix-f-benchmarks/sync +$ make +``` + +Load and drive it: + +```console +# kldload ./sync_bench.ko +# sh run_sync_bench.sh +# kldunload sync_bench +``` + +`run_sync_bench.sh` runs each benchmark in sequence and prints a small table; individual benchmarks can also be triggered directly by writing a `1` to the corresponding `debug.sync_bench.run_*` sysctl and then reading `debug.sync_bench.last_ns_*`. + +### Representative result + +Harness only, no result captured. The kmod has been written against FreeBSD 14.3 headers and its logic reviewed against the Chapter 15 table, but the author has not loaded and run it on the reference machine while writing this appendix. A reader running the harness on typical FreeBSD 14.3-amd64 hardware should expect the uncontended mutex and sx numbers to land in the low tens of nanoseconds, and the cv and sema round-trip numbers to land in the low microseconds because those paths cross the scheduler twice. Any reader whose numbers are more than a factor of two higher should look at scheduler affinity, CPU frequency scaling, and whether the host is under additional load. + +### Hardware envelope + +The Chapter 15 table's "order-of-magnitude" qualifier is deliberate. Uncontended lock costs track the cost of one or two atomic compare-and-swap operations on the current cache line, which varies with CPU generation and cache topology. Round-trip wakeup costs track scheduler latency, which varies more: a dedicated-CPU server with `kern.sched.preempt_thresh` tuned for low latency can show sub-microsecond round-trips, while a busy multi-tenant machine can see tens of microseconds. The harness reports a single mean per benchmark; readers who need a distribution should extend the module to capture quantiles, or use DTrace `lockstat` probes on the running kernel instead. + +See also Chapter 15 for the conceptual framework and the guidance on when each primitive is appropriate. + +## iflib Driver Code-Size Reduction + +### What is being measured + +Chapter 28 claims that on the drivers that have been converted to `iflib(9)` to date, driver code typically shrinks by thirty to fifty percent compared with the equivalent plain-ifnet implementation. Unlike the other benchmarks in this appendix, this one is not a hardware measurement. It is a source-code measurement: how many lines of C source a modern NIC driver needs under `iflib(9)` versus how many it needed without it. + +The quantity measured is the line count of a driver's main source file, split into three figures: the raw `wc -l` total, the number of non-blank lines, and the number of non-blank non-comment lines (an approximation of "code lines" that is close enough to the truth for order-of-magnitude comparison). + +### The harness + +The harness lives under `examples/appendices/appendix-f-benchmarks/iflib/` and is a set of portable shell scripts. + +`count_driver_lines.sh` takes one driver source file and reports all three figures. The comment stripping is a simple `awk` pass that understands `/* ... */` (including multi-line) and `// ... EOL` forms; it is not a full C parser but is accurate enough to be useful. + +`compare_iflib_corpus.sh` is the main driver. It walks two curated corpora and produces a comparison table: + +- iflib corpus: `/usr/src/sys/dev/e1000/if_em.c`, `/usr/src/sys/dev/ixgbe/if_ix.c`, `/usr/src/sys/dev/igc/if_igc.c`, `/usr/src/sys/dev/vmware/vmxnet3/if_vmx.c`. +- Plain-ifnet corpus: `/usr/src/sys/dev/re/if_re.c`, `/usr/src/sys/dev/bge/if_bge.c`, `/usr/src/sys/dev/fxp/if_fxp.c`. + +The iflib drivers were selected by grepping for `IFDI_` method callbacks, which are the characteristic iflib interface points; the plain-ifnet drivers were selected to span a comparable range of hardware classes. Both lists are variables at the top of the script that the reader can edit. + +`git_conversion_delta.sh` is a third script for readers who have a full FreeBSD Git clone with history. It finds the commit that converted a named driver to iflib (by searching commits that touch the file and mention "iflib" in the log) and reports the line-count delta at that commit. A before/after conversion diff is the only way to measure Chapter 28's claim directly; the cross-driver comparison is a proxy that depends on driver complexity being roughly comparable, which is a strong assumption. + +### How to reproduce + +On any FreeBSD 14.3 source checkout: + +```console +$ cd examples/appendices/appendix-f-benchmarks/iflib +$ sh compare_iflib_corpus.sh /usr/src +``` + +For the before/after measurement, on a full FreeBSD Git clone: + +```console +$ sh git_conversion_delta.sh /path/to/freebsd-src.git if_em.c +``` + +### Representative result + +Captured against the FreeBSD 14.3-RELEASE source tree, `compare_iflib_corpus.sh` produces the following summary: + +```text +=== iflib === + if_em.c raw=5694 nonblank=5044 code=4232 + if_ix.c raw=5168 nonblank=4519 code=3573 + if_igc.c raw=3305 nonblank=2835 code=2305 + if_vmx.c raw=2544 nonblank=2145 code=1832 + corpus=iflib drivers=4 avg_code=2985 + +=== plain-ifnet === + if_re.c raw=4151 nonblank=3693 code=3037 + if_bge.c raw=6839 nonblank=6055 code=4990 + if_fxp.c raw=3245 nonblank=2943 code=2228 + corpus=plain-ifnet drivers=3 avg_code=3418 + +=== summary === + iflib avg code lines: 2985 + plain-ifnet avg code lines: 3418 + delta: 433 + reduction: 12% +``` + +A cross-corpus reduction of roughly twelve percent is smaller than Chapter 28's thirty-to-fifty-percent claim, which is exactly what the caveat at the bottom of the script warns about. The chapter claim is a per-driver before-and-after figure: the same hardware, converted to iflib, goes from N lines to (0.5-0.7) times N lines. A cross-driver comparison is a different thing: it compares different hardware with different feature sets and different quirk counts. The cross-driver reduction sets a floor (there is *some* reduction in average size across the corpus), and the per-driver reduction quoted in Chapter 28 sets the ceiling (the individual conversion commits show the larger number). Readers with a Git clone can use `git_conversion_delta.sh` to verify the per-driver number directly. + +### Pinned per-driver measurement + +To anchor Chapter 28's range to a concrete figure, we ran the per-commit comparison on 2026-04-21 against the ixgbe conversion commit `4fd3548cada3` ("ixgbe(4): Convert driver to use iflib", authored 2017-12-20 by erj@FreeBSD.org). That commit is the cleanest per-driver conversion in the tree: it neither consolidated drivers nor changed features on the same revision. The four driver-specific files that existed on both sides of the commit (`if_ix.c`, `if_ixv.c`, `ix_txrx.c`, and `ixgbe.h`) went from 10,606 raw lines (7,093 non-blank non-comment) down to 7,600 raw lines (5,074 non-blank non-comment) on the conversion commit itself, a twenty-eight percent reduction in code lines. Restricting the comparison to the core PF files (`if_ix.c` and `ix_txrx.c`) tightens the result to thirty-two percent, inside Chapter 28's thirty-to-fifty-percent range. The twenty-eight-percent figure is the headline one to carry away, with the narrower thirty-two-percent figure showing how much of the residual is shared-header and VF-sibling code rather than framework-saved driver logic. + +A larger but less representative data point is the earlier em/e1000 conversion commit `efab05d61248` ("Migrate e1000 to the IFLIB framework", 2017-01-10), which achieves roughly a seventy percent reduction on the e1000-class driver code: the combined driver sources drop from 13,188 down to 3,920 non-blank non-comment lines. That commit folded `if_em.c`, `if_igb.c`, and `if_lem.c` into a single iflib-based `if_em.c` plus a new `em_txrx.c`, so the measured reduction mixes framework savings with the consolidation of three related drivers into one and should not be read as a typical per-driver figure. Taken together, the ixgbe and e1000 data points bracket Chapter 28's thirty-to-fifty-percent range from below and above: a clean single-driver conversion lands at or just below the lower edge, and a driver-consolidating conversion overshoots the upper edge. + +### Hardware envelope + +This benchmark does not depend on hardware. The result is a function of the FreeBSD source tree at a specific revision, and should be identical on any machine with the same checkout. Readers using a different FreeBSD branch (15-CURRENT, an older release) will see different absolute numbers because the tree evolves. + +See also Chapter 28 for the surrounding discussion of `ifnet(9)` and how `iflib(9)` sits inside it. + +## DTrace, INVARIANTS, and WITNESS Overhead + +### What is being measured + +Chapter 34 makes two performance claims about debug kernels: + +- A busy `INVARIANTS` kernel runs roughly five to twenty percent slower than a release kernel, sometimes more on allocation-heavy workloads, as a rough order-of-magnitude figure on typical FreeBSD 14.3-amd64 hardware. +- `WITNESS` adds bookkeeping to every lock acquisition and release; in our lab environment, on a busy kernel running a lock-heavy workload, the overhead can approach twenty percent. + +It also mentions, in the context of DTrace, that active DTrace scripts add overhead proportional to how many probes they fire and how much work each probe does. + +The quantity measured by the harness in this section is wall-clock time to complete a fixed workload. The harness does not attempt to compute percentages directly; it provides two well-defined workloads and a consistent output format, and it expects the reader to run the suite once per kernel condition and compute ratios between them. + +### The harness + +The harness lives under `examples/appendices/appendix-f-benchmarks/dtrace/` and has four parts. + +`workload_syscalls.c` is a userland program that performs one million iterations of a tight loop containing four cheap system calls (`getpid`, `getuid`, `gettimeofday`, `clock_gettime`). This workload exaggerates the cost of the syscall entry and exit path, where `INVARIANTS` assertions and `WITNESS` lock-tracking fire most often. + +`workload_locks.c` is a userland program that spawns four threads and performs ten million `pthread_mutex_lock` / `pthread_mutex_unlock` pairs per thread, on a small rotating set of mutexes. Userland mutexes fall through to the kernel's `umtx(2)` path when they contend, so this workload exercises the lock-heavy contention path that `WITNESS` instruments. + +`dtrace_overhead.d` is a minimal DTrace script that fires on every syscall entry and return without printing anything per probe. Attaching it during a `workload_syscalls` run measures the cost of having the DTrace probe framework actively instrumenting the syscall path. + +`run_overhead_suite.sh` runs both workloads once, captures `uname` and `sysctl kern.conftxt`, and writes a tagged report. The reader is expected to run the suite four times: on a base `GENERIC` kernel, on an `INVARIANTS` kernel, on a `WITNESS` kernel, and on any of those with `dtrace_overhead.d` attached in another terminal. Comparing the four reports gives the percentages Chapter 34 claims. + +The surrounding kernel sources are `/usr/src/sys/kern/subr_witness.c` for WITNESS, `/usr/src/sys/sys/proc.h` and its siblings for the assertion macros enabled by `INVARIANTS`, and the DTrace provider sources under `/usr/src/sys/cddl/dev/` for the probe framework. + +### How to reproduce + +On each kernel condition: + +1. Boot into the kernel under test. +2. Build the workloads: + + ```console + $ cd examples/appendices/appendix-f-benchmarks/dtrace + $ make + ``` + +3. Run the suite: + + ```console + # sh run_overhead_suite.sh > result-