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.
This commit is contained in:
Edson Brandi 2026-04-22 18:57:42 +00:00
parent 92ac73a6fb
commit f92af5b969
44 changed files with 138773 additions and 1499 deletions

File diff suppressed because it is too large Load diff

View file

@ -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 `<sys/queue.h>` 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 `<sys/tree.h>`
**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 `<net/radix.h>`
**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 `<sys/tree.h>` 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 `<sys/bitstring.h>`
**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 `<sys/queue.h>` 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 `<sys/hash.h>` 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 `<sys/fnv_hash.h>`.
**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.
<!-- remove after Chapter 11 revision is durable -->
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 `<sys/queue.h>` |
| A FIFO queue with no arbitrary removal | `STAILQ_` |
| A collection ordered by a key, grows large | `RB_` from `<sys/tree.h>` |
| A dense universe of boolean flags | `bit_*` from `<sys/bitstring.h>` |
| 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.

View file

@ -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.

View file

@ -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 `<sys/queue.h>`
**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.

View file

@ -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 (`<sys/queue.h>`, 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/<subsystem>/` 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.

View file

@ -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-<label>.txt
```
4. For the DTrace condition, launch the script in another terminal before running the suite:
```console
# dtrace -q -s dtrace_overhead.d
```
After all four runs, compare the `result-*.txt` files side by side. The ratios `INVARIANTS_ns / base_ns`, `WITNESS_ns / base_ns`, and `dtrace_ns / base_ns` are the overhead figures Chapter 34 refers to.
### Representative result
Harness only, no result captured. The workloads have been compiled on the reference system and their logic reviewed against the Chapter 34 claims, but the author has not built the three comparison kernels to capture end-to-end numbers while writing this appendix. Readers who run the four-kernel comparison on typical FreeBSD 14.3-amd64 hardware should expect `INVARIANTS` to land in the five-to-twenty-percent range on `workload_syscalls`, somewhat higher on `workload_locks` because lock paths are the hottest code under `INVARIANTS`. `WITNESS` should land lower than `INVARIANTS` on pure-syscall workloads (where few new lock orders are visited) and higher on `workload_locks`, approaching the twenty-percent figure the chapter names. The DTrace column should be small on `workload_locks` (no relevant probes fire in the hot path) and non-trivial on `workload_syscalls` (every iteration fires two probes).
### Hardware envelope
The ratios are more stable across hardware than the absolute numbers. Readers on different CPUs will see different wall times for the baseline workload, but the per-kernel percentage overhead should stay within a tight band because it is determined by how much extra work the debug kernel does per operation, not by how fast each operation is. The most common sources of surprise are virtualisation (where the syscall path has additional per-call hypervisor overhead that dilutes the percentage), aggressive power management (where CPU frequency varies across runs), and SMT (where per-core numbers differ from per-logical-CPU numbers). The harness does not try to control for any of these; a reader wanting production-quality numbers will need to pin the test to a single CPU, disable frequency scaling, and run the suite several times.
See also Chapter 34 for the surrounding treatment of debugging kernels and for the discussion of when each of `INVARIANTS`, `WITNESS`, and DTrace is worth enabling.
## Scheduler Wakeup Latency
Chapter 33 contains a DTrace snippet that measures scheduler wakeup latency using `sched:::wakeup` and `sched:::on-cpu`. That snippet is already the harness; this section would only duplicate it. Readers interested in the sub-microsecond idle-system figure and the low-tens-of-microseconds contended-system figure that Chapter 33 names should use the script exactly as printed there, on the reader's hardware. The DTrace provider sources are under `/usr/src/sys/cddl/dev/dtrace/`.
If the reader wants to compare wakeup latency with and without `WITNESS`, the same script applies; just boot the two kernels and run it on each.
## Wrapping Up: Using the Harness Without Being Misled
The harness in this appendix exists because every number in Chapters 15, 28, 33, and 34 is an order-of-magnitude claim, and order-of-magnitude claims deserve reproducibility. A few habits make the harness actually useful rather than a source of false confidence.
First, run each benchmark more than once. Single-run results are dominated by startup noise, warm-up effects, and interference from whatever else is running on the machine. The harness scripts report a single number; run them three to five times and take the median, or extend them to aggregate runs automatically before trusting the result.
Second, keep the conditions honest. If you want to compare `INVARIANTS` to a base kernel, build both kernels with the same compiler, the same `CFLAGS`, and the same `GENERIC` or `GENERIC-NODEBUG` baseline. If you want to compare two timecounter sources, run both comparisons on the same boot of the same kernel; a reboot between runs changes too many variables.
Third, resist the temptation to treat the numbers as universal. A measurement on one 4-core laptop in a quiet office is not a measurement on a 64-core production server in a noisy rack. The harness measures the machine in front of you; Chapter 15 through 34's qualified phrases ("on typical 14.3-amd64 hardware", "in our lab environment") are honest about the same limitation. The harness makes the qualified phrase testable without pretending it becomes universal.
Fourth, prefer ratios to absolutes. A claim that `WITNESS` costs twenty percent is much more stable than a claim that `WITNESS` costs four hundred nanoseconds per lock. The former survives CPU changes, compiler changes, and kernel-version changes that would wipe out the latter. When you run the harness on your hardware, the percentage overhead is what you should keep; the absolute number is just the arithmetic that produced it.
And finally, extend the harness rather than trusting it blindly. Every script here is small enough to read end to end; every kmod is under three hundred lines. If a chapter claim matters to you, open the harness, verify that it measures what you expect it to measure, modify it if your workload needs something different, and run the modified version. The harness is a starting point, not a finish line.
The qualified phrases in Chapters 15, 28, 33, and 34 and the runnable harness in this appendix are two halves of the same discipline. The chapters are honest about what is variable; the appendix shows you how to measure the variation yourself.

View file

@ -4,12 +4,11 @@ description: "Discover why FreeBSD matters, what device drivers do, and how this
partNumber: 1
partName: "Foundations: FreeBSD, C, and the Kernel"
chapter: 1
lastUpdated: "2025-08-24"
lastUpdated: "2026-04-20"
status: "complete"
author: "Edson Brandi"
reviewer: "TBD"
translator: "TBD"
date: "2025-08-24"
estimatedReadTime: 30
---
@ -23,13 +22,13 @@ Every book begins with a reason to exist. For this one, the reason is deeply per
**From Chemistry to Technology: A True Story About Curiosity and Change**
In 1995, I was a chemistry student at Unicamp (State University of Campinas), one of Brazil’s top universities. I had no plan to work with infrastructure, software, or systems. But I had questions. I wanted to know how computers really worked, not just how to use them, but how the pieces fit together under the hood.
In 1995, I was a chemistry student at Unicamp (State University of Campinas), one of Brazil's top universities. I had no plan to work with infrastructure, software, or systems. But I had questions. I wanted to know how computers really worked, not just how to use them, but how the pieces fit together under the hood.
That search for answers led me to FreeBSD. What fascinated me most was not only the way the system behaved but that I had access to its source code. This was not just an operating system to use; it was one I could study, line by line. That possibility became the fuel for my growing passion.
At first, I could only explore FreeBSD on the university’s machines. During the day, my time was consumed by chemistry studies, but I longed for more hours to dive deeper. I couldn’t let this curiosity interfere with my degree. Coming from a humble background, I was the first in my family to reach university, and I carried that responsibility with pride.
At first, I could only explore FreeBSD on the university's machines. During the day, my time was consumed by chemistry studies, but I longed for more hours to study it more closely. I couldn't let this curiosity interfere with my degree. Coming from a humble background, I was the first in my family to reach university, and I carried that responsibility with pride.
In those early years, I had no computer of my own. Living on a limited budget, I barely managed the basics of being away from home. For nearly two years, my studies of FreeBSD took place in the chemistry institute’s library, where I devoured every document I could find about Unix and system programming. But without my own machine, I couldn’t put theory into practice for many of the things I was learning.
In those early years, I had no computer of my own. Living on a limited budget, I barely managed the basics of being away from home. For nearly two years, my studies of FreeBSD took place in the chemistry institute's library, where I devoured every document I could find about Unix and system programming. But without my own machine, I couldn't put theory into practice for many of the things I was learning.
Finally, in 1997, I managed to assemble my first computer: a 386DX running at 40 MHz, with 8 MB of RAM and a 240 MB hard drive. The parts came from a generous friend I had met in the FreeBSD community, Adriano Martins Pereira. Over the years, he became such a close friend that he would later stand beside me as one of my groomsmen at my wedding.
@ -37,13 +36,13 @@ I will never forget the moment I brought home the more than 20 floppy disks to i
When I first touched FreeBSD, I understood very little of what I was seeing. The installation messages felt cryptic, the commands unfamiliar. Yet each small success, booting into a prompt, configuring a network card, compiling a kernel, felt like unlocking a new part of a hidden world. That thrill of discovery never fully goes away.
Over time, I wanted to share what I was learning. I created **FreeBSD Primeiros Passos** (FreeBSD First Steps), a small website in Portuguese that introduced newcomers to the system. It was simple, but it helped many people. That effort grew into the **Brazilian FreeBSD User Group (FUG-BR)**, which brought enthusiasts together to learn, exchange knowledge, and even meet in person at conferences. Speaking at early editions of **FISL**, Brazil’s International Free Software Forum, was one of my proudest moments. Standing in front of an audience to share something that had changed my life was unforgettable.
Over time, I wanted to share what I was learning. I created **FreeBSD Primeiros Passos** (FreeBSD First Steps), a small website in Portuguese that introduced newcomers to the system. It was simple, but it helped many people. That effort grew into the **Brazilian FreeBSD User Group (FUG-BR)**, which brought enthusiasts together to learn, exchange knowledge, and even meet in person at conferences. Speaking at early editions of **FISL**, Brazil's International Free Software Forum, was one of my proudest moments. Standing in front of an audience to share something that had changed my life was unforgettable.
Around that time, I also co-created the **FreeBSD LiveCD Tool Set**. Back in the late 1990s, installing an operating system like FreeBSD could feel daunting. Our tool allowed users to boot a complete FreeBSD environment directly from a CD without touching their hard drive. It was a simple idea, but it lowered the barrier for countless new users.
By 2002, I became one of the founders of **FreeBSD Brasil** ([https://www.freebsdbrasil.com.br](https://www.freebsdbrasil.com.br)), a company dedicated to training, consulting, and supporting businesses with FreeBSD. It was an opportunity to bridge the gap between open source ideals and professional, real-world applications. Although I’m no longer involved, FreeBSD Brasil continues to this day, helping companies across Brazil adopt FreeBSD in their operations.
By 2002, I became one of the founders of **FreeBSD Brasil** ([https://www.freebsdbrasil.com.br](https://www.freebsdbrasil.com.br)), a company dedicated to training, consulting, and supporting businesses with FreeBSD. It was an opportunity to bridge the gap between open source ideals and professional, real-world applications. Although I'm no longer involved, FreeBSD Brasil continues to this day, helping companies across Brazil adopt FreeBSD in their operations.
Eventually, my work led me deeper into the FreeBSD Project itself. I became a **committer**, focusing on documentation and translations. Today, I am part of the **FreeBSD Documentation Engineering Team (DocEng)**, helping maintain the systems that keep FreeBSD’s documentation alive, updated, and accessible worldwide.
Eventually, my work led me deeper into the FreeBSD Project itself. I became a **committer**, focusing on documentation and translations. Today, I am part of the **FreeBSD Documentation Engineering Team (DocEng)**, helping maintain the systems that keep FreeBSD's documentation alive, updated, and accessible worldwide.
All of this, every project, every friendship, every opportunity, grew from that first decision to explore FreeBSD out of sheer curiosity.
@ -51,17 +50,17 @@ Even though my formal studies were in chemistry, my career shifted toward techno
And it all began with one question: **How does this work?**
I share this story because I want you to see what is possible. You don’t need a degree in computer science to become a great developer, sysadmin, or technology leader. What you need is curiosity, persistence, and the patience to keep learning when things get hard.
I share this story because I want you to see what is possible. You don't need a degree in computer science to become a great developer, sysadmin, or technology leader. What you need is curiosity, persistence, and the patience to keep learning when things get hard.
FreeBSD helped me unlock my potential. This book is here to help you unlock yours.
## FreeBSD in Context
Before we dive into writing drivers, let’s take a moment to appreciate the stage on which all this happens.
Before we start on writing drivers, let's take a moment to appreciate the stage on which all this happens.
### A Brief History
FreeBSD traces its roots back to the **Berkeley Software Distribution (BSD)**, a derivative of the original UNIX developed at AT&T in the early 1970s. At the University of California, Berkeley, students and researchers added groundbreaking features that shaped modern operating systems, including the **TCP/IP networking stack** that still powers the internet today.
FreeBSD traces its roots back to the **Berkeley Software Distribution (BSD)**, a derivative of the original UNIX developed at AT&T in the early 1970s. At the University of California, Berkeley, students and researchers contributed foundational work that shaped later UNIX-like systems, including the first widely adopted open **TCP/IP networking stack**, the Fast File System, and sockets, all of which remain recognizable in FreeBSD and many other systems today.
While many commercial UNIX variants rose and fell over the decades, FreeBSD endured. The project was officially founded in 1993, built on the work of the Berkeley CSRG (Computer Systems Research Group), and guided by a commitment to openness, technical excellence, and long-term stability. Over thirty years later, it is still actively developed and maintained, a rare achievement in the fast-moving world of technology.
@ -71,7 +70,7 @@ More than a piece of software, FreeBSD represents a **continuum of knowledge**.
### Why FreeBSD Is Special
FreeBSD is far more than just another operating system. It combines the depth of a mature UNIX tradition with the focus and care of a modern engineering project. Over the years, it has earned a reputation for qualities that set it apart:
FreeBSD is developed as a complete UNIX-like operating system, with the kernel and the base userland built, versioned, and released together. Several characteristics follow directly from that approach:
- **Stability**: FreeBSD systems are famous for their ability to run for months or even years without rebooting. Internet service providers, data centers, and research institutions rely on this predictability for mission-critical workloads.
- **Performance**: The operating system consistently demonstrates excellent performance under demanding conditions. From high-throughput networking to complex storage systems, FreeBSD has been chosen in environments where efficiency is not optional but essential.
@ -80,15 +79,15 @@ FreeBSD is far more than just another operating system. It combines the depth of
Beyond these qualities, FreeBSD also stands out for its **license and philosophy**. The BSD license is permissive, giving both individuals and companies the freedom to use, adapt, and even commercialize their work without the obligation to open-source every change. This balance has encouraged widespread adoption in industry while keeping the project open and community-driven.
FreeBSD also has a **strong sense of stewardship**. Developers in the project are not just writing code for today’s needs; they are maintaining a system that has been evolving for decades, with careful attention to long-term stability and clean design. This mindset makes it an excellent environment for learning, because decisions are not made hastily but with a view of how they will shape the system years into the future.
FreeBSD also has a **strong sense of stewardship**. Developers in the project are not just writing code for today's needs; they are maintaining a system that has been evolving for decades, with careful attention to long-term stability and clean design. This mindset makes it an excellent environment for learning, because decisions are not made hastily but with a view of how they will shape the system years into the future.
For beginners, this means FreeBSD is not only a robust system to use but also a *teacher*. Exploring its tools, its source code, and its documentation provides lessons in how operating systems are built and how good software communities sustain themselves.
For beginners, this means FreeBSD is a system you can both use and study. Exploring its tools, its source code, and its documentation provides concrete lessons in how operating systems are built and how a long-running open source community sustains itself.
### Kernel Insight
Did you know? Apple’s macOS and iOS draw heavily from BSD code, including parts of FreeBSD. When you browse the web on an iPhone or MacBook, you’re relying on decades of BSD engineering that has been tested and trusted in countless environments.
Did you know? Apple's macOS and iOS draw heavily from BSD code, including parts of FreeBSD. When you browse the web on an iPhone or MacBook, you're relying on decades of BSD engineering that has been tested and trusted in countless environments.
This lineage highlights an important truth: BSD is not a relic of the past. It is living technology, still shaping the systems people use every day. FreeBSD, in particular, has remained fully open and community-driven, offering the same foundation of reliability that large companies use, but without hiding it behind closed doors. When you study FreeBSD, you are looking at the same DNA that runs through some of the world’s most advanced operating systems.
This lineage highlights an important truth: BSD is not a relic of the past. It is living technology, still shaping the systems people use every day. FreeBSD, in particular, has remained fully open and community-driven, offering the same foundation of reliability that large companies use, but without hiding it behind closed doors. When you study FreeBSD, you are looking at the same DNA that runs through some of the world's most advanced operating systems.
### Clearing Misconceptions
@ -104,49 +103,49 @@ FreeBSD is everywhere, though often invisibly. When you stream a show from Netfl
Even closer to home, FreeBSD powers firewalls, NAS devices, and appliances you might have in your office or living room. Projects like pfSense and FreeNAS (now TrueNAS) are based on FreeBSD, bringing enterprise-grade networking and storage into homes and small businesses worldwide.
And of course, FreeBSD has a long tradition in **research and education**. Universities use it in computer science curricula and labs, where having open access to the complete source code of a production-grade operating system is invaluable. Whether you realize it or not, you’ve probably already depended on FreeBSD in your daily life.
And of course, FreeBSD has a long tradition in **research and education**. Universities use it in computer science curricula and labs, where having open access to the complete source code of a production-grade operating system is invaluable. Whether you realize it or not, you've probably already depended on FreeBSD in your daily life.
### Why FreeBSD for Driver Development?
For someone learning about device drivers, FreeBSD offers a rare balance. Its codebase is modern and production-ready, but it is also clean and approachable compared to many alternatives. Developers often describe FreeBSD’s kernel as "readable," a trait that matters greatly when you are just starting out.
For someone learning about device drivers, FreeBSD offers a rare balance. Its codebase is modern and production-ready, but it is also clean and approachable compared to many alternatives. Developers often describe FreeBSD's kernel as "readable," a trait that matters greatly when you are just starting out.
The project also has a strong tradition of documentation. The FreeBSD Handbook, man pages, and developer guides provide a level of guidance that is hard to find in other open source kernels. This means you won’t be left guessing how things fit together.
The project also has a strong tradition of documentation. The FreeBSD Handbook, man pages, and developer guides provide a level of guidance that is hard to find in other open source kernels. This means you won't be left guessing how things fit together.
For professionals, FreeBSD is more than a teaching tool. It is widely respected in areas where performance, networking, and storage are critical. Learning how to write drivers here prepares you for work that extends far beyond FreeBSD itself; it builds skills in systems programming, debugging, and hardware interaction that are transferable to many platforms.
Perhaps most importantly, FreeBSD encourages learning by participation. Its open, collaborative culture welcomes contributions from beginners and experts alike. Starting here, you’re not just learning in isolation; you are stepping into a community that values clarity, quality, and curiosity.
Perhaps most importantly, FreeBSD encourages learning by participation. Its open, collaborative culture welcomes contributions from beginners and experts alike. Starting here, you're not just learning in isolation; you are stepping into a community that values clarity, quality, and curiosity.
## Drivers and the Kernel - A First Glimpse
Now that you know why FreeBSD matters, let’s peek at the world you are about to explore.
Now that you know why FreeBSD matters, let's peek at the world you are about to explore.
At the heart of every operating system lies the **kernel**, the core that never sleeps. It orchestrates memory, manages processes, and directs communication with hardware. Most users never notice it, yet every keystroke, network packet, and disk read depends on its decisions.
### Why Drivers Matter
A kernel without drivers would be like a conductor without musicians. Drivers are the interpreters that let hardware and software communicate with each other. Your keyboard, network card, and graphics adapter are just silent pieces of silicon until a driver tells the kernel how to use them. Without drivers, even the most powerful hardware is nothing more than inert circuitry.
A kernel without drivers would be like a conductor without musicians. Drivers are the interpreters that let hardware and software communicate with each other. Your keyboard, network card, and graphics adapter are just pieces of silicon until a driver tells the kernel how to address their registers, handle their interrupts, and move data to and from them. Without drivers, even sophisticated hardware is inert circuitry as far as the operating system is concerned.
### Everyday Technology, Powered by Drivers
Drivers are everywhere, working quietly in the background. When you plug in a USB stick and see it appear on your desktop, that’s a driver at work. When you connect to Wi-Fi, adjust your screen brightness, or listen to sound through your headphones, all of these actions depend on drivers. They are invisible to most users, but they are what make computers feel alive and responsive.
Drivers are everywhere, working quietly in the background. When you plug in a USB stick and see it appear on your desktop, that's a driver at work. When you connect to Wi-Fi, adjust your screen brightness, or listen to sound through your headphones, all of these actions depend on drivers. They are invisible to most users, but they are what make computers feel alive and responsive.
Think about it: every modern convenience of computing, from cloud servers processing millions of requests per second to the phone in your pocket, depends on the unseen labour of device drivers.
### Beginner’s Tip
### Beginner's Tip
If terms like *kernel*, *driver*, or *module* feel abstract right now, don’t worry. This chapter is just the trailer, a preview of the whole story. In the coming chapters, we’ll break these ideas down step by step until the pieces start to click together.
If terms like *kernel*, *driver*, or *module* feel abstract right now, don't worry. This chapter is just the trailer, a preview of the whole story. In the coming chapters, we'll break these ideas down step by step until the pieces start to click together.
### A Teaser of FreeBSD’s Kernel World
### A Teaser of FreeBSD's Kernel World
One of FreeBSD’s strengths is its **modular design**. Drivers can be loaded and unloaded dynamically as kernel modules, giving you the freedom to experiment without rebuilding the entire system. This flexibility is a gift for learners: you can try out code, test it, and remove it when you are done.
One of FreeBSD's strengths is its **modular design**. Drivers can be loaded and unloaded dynamically as kernel modules, giving you the freedom to experiment without rebuilding the entire system. This flexibility is a gift for learners: you can try out code, test it, and remove it when you are done.
In this book, you will begin with the simplest form of drivers, character drivers, and progressively move toward more complex subsystems like PCI devices, USB peripherals, and even high-performance features such as DMA.
For now, hold on to this simple truth: **drivers are the bridge between possibility and reality in computing.** They turn abstract code into working hardware, and by learning how to write them, you are learning how to connect ideas with the physical world.
## Your Journey Through This Book
## Your Path Through This Book
This book is not just a reference; it is a guided journey, designed to take you step by step from the very basics to advanced concepts in FreeBSD driver development. You won’t just read, you’ll practice, experiment, and build real code along the way.
This book is not just a reference; it is a guided course, designed to take you step by step from the very basics to advanced concepts in FreeBSD driver development. You won't just read, you'll practice, experiment, and build real code along the way.
### Who This Book Is For
@ -158,15 +157,15 @@ This book was written with inclusivity in mind, especially for readers who may f
If you bring curiosity and persistence, you will find a path here that starts where you are and builds your confidence chapter by chapter.
### Who This Book Isn’t For
### Who This Book Isn't For
Not every book fits every reader, and that is intentional. This book may not be the right fit if:
- You are looking for a **quick copy-and-paste manual**. This journey emphasizes understanding and practice, not shortcuts.
- You are looking for a **quick copy-and-paste manual**. This book emphasizes understanding and practice, not shortcuts.
- You are already a **seasoned kernel developer**. The pace starts from the ground up, introducing fundamentals carefully before moving on to complex topics.
- You expect a **comprehensive hardware reference manual**. This is not an encyclopedic listing of every device or bus specification. Instead, it focuses on practical, real-world driver development in FreeBSD.
### What You’ll Learn and Gain
### What You'll Learn and Gain
This book gives you a structured, hands-on path into FreeBSD driver development. Along the way, you will:
@ -179,7 +178,7 @@ By the end, you will not only know how FreeBSD drivers are written, but also hav
### The Learning Path Ahead
This book is organized as a journey, with each part building on the one before it. You will start with the essentials, learning the FreeBSD environment, basic UNIX tools, and C programming fundamentals before gradually stepping into kernel space and driver development. From there, the path expands into more advanced areas of practice:
This book is organized as a sequence of parts that build on each other. You will start with the essentials, learning the FreeBSD environment, basic UNIX tools, and C programming fundamentals before gradually stepping into kernel space and driver development. From there, the path expands into more advanced areas of practice:
- **Part 1:** Foundations: FreeBSD, C, and the Kernel
- **Part 2:** Building Your First Driver
@ -194,13 +193,53 @@ Along this path, you will reach important milestones. You will write and load yo
When I first started writing drivers, I felt intimidated. *"Kernel programming"* sounded like something reserved for experts in dark rooms full of servers. The truth is more straightforward. It is still programming, only with more explicit rules, greater responsibility, and a bit more power. Once you understand that, the fear gives way to excitement. That is the spirit in which this learning path was designed: approachable, progressive, and rewarding.
## How to Read This Book
Before the learning begins in earnest, a short word on pace, expectations, and what to do when something does not land on the first pass.
### Time and Commitment
The book is long because the material is cumulative. A careful reader who works through the exercises should expect to spend around **two hundred hours** with it from start to finish: roughly **one hundred hours of reading** and an additional **one hundred hours on the labs and challenge exercises**. A reader who only reads can finish in about one hundred hours but will leave with correct mental models and little muscle memory.
**Part 1 alone accounts for about forty-five hours** of reader time. That is not an accident. Part 1 lays the foundations on which the rest of the book rests, and the later Parts move faster because they lean on that foundation. Later Parts are typically shorter, depending on whether the subsystem they cover is new to you.
### Labs Are Strongly Recommended
Every chapter includes hands-on labs, and most chapters include challenge exercises that push beyond the labs. **The labs are strongly recommended.** They are where prose turns into reflex. Kernel programming rewards muscle memory in a way few disciplines do: the same attach pattern, the same cleanup chain, the same locking shape appears in chapter after chapter and in driver after driver. Typing those patterns, compiling them, loading them into a running kernel, and watching them fail on purpose is the single most effective way to internalise them.
Learning is self-paced and ultimately under your control. If a chapter is informational and the material is already familiar, skimming is a fair choice. But when a chapter asks you to load a module and observe its behaviour, resist the urge to read around the exercise. The difference between a reader who ran the labs and one who did not tends to show up several chapters later, as either smooth progress or quiet confusion.
### A Suggested Cadence
For a reader with about **five hours per week** available for study, **one chapter per week** is a sustainable pace. That cadence puts the whole book within reach across a typical academic or professional year. More hours per week allow a brisker pace; fewer hours call for patience rather than skipping. What matters most is continuity: short, regular sessions beat occasional marathons.
Some chapters are naturally longer than others. Chapter 4 on C is the longest in Part 1 and may span two or three weeks at five hours a week. Chapters in Parts 3, 4, and 5 are substantial because the technical material is layered. Allow extra time for Part 6 and Part 7 if the subsystems they cover are new to you.
### Fast-Path Hints for Experienced Readers
If you already know C, UNIX, and the general shape of an operating-system kernel, not every section will be new territory. **Chapter 4 includes an "If You Already Know C" sidebar near its opening** that names the sections still worth a careful read and the ones you can skim. A similar principle applies to Chapters 2 and 3: if FreeBSD is familiar and the UNIX toolchain is second nature, read the opening pages to absorb this book's vocabulary, then move on. Parts 3 through 7 introduce disciplines that reward careful reading regardless of prior experience.
### What to Do When You Are Stuck
You will get stuck. Every reader does, and the places where you get stuck are often where the real learning happens. Three tactics work well.
First, **re-read the section slowly**. Kernel writing is dense, and a second pass often reveals a sentence you skimmed the first time. A slow re-read is almost always more productive than rushing onward.
Second, **run the labs that led up to the confusion**. A concept that is blurry in prose often becomes clear when you type the code, compile it, load it, and watch the kernel's response in `dmesg`. If a lab is already behind you, repeat it and vary one piece at a time. Observation on a running module teaches things no paragraph can.
Third, **file an issue**. The book's repository welcomes questions and corrections. If a passage seems wrong or a lab fails in an unexpected way, an issue helps more than you might expect; every such report is a chance to make the next reader's path smoother.
Above all, be patient with yourself. The material compounds. A concept that feels opaque in Chapter 5 may feel obvious by Chapter 11, not because you re-read Chapter 5 but because the vocabulary has had time to settle. Trust that, and keep going.
One final note on commitment. Taken together with the labs, the book is on the order of two hundred hours of work: call it a six-month evening project at roughly five hours a week, or a focused two-month sprint at twice that pace. A reader who skips the labs can finish in about half that time, with correct ideas but less muscle memory to show for it. You do not need to decide any of that today. Pick a pace that feels honest, begin with the next chapter, and let the rhythm settle as you go.
## How to Get the Most from This Book
Learning kernel programming is not just about reading; it’s about patience, practice, and persistence. The following principles will help you make the most of this journey.
Learning kernel programming is not just about reading; it's about patience, practice, and persistence. The following principles will help you make the most of this book.
### Build the Right Mindset
At first, kernels and drivers may feel overwhelming. That’s normal. The secret is to take things one step at a time. Don’t rush through chapters. Let each concept settle, and give yourself room to experiment and make mistakes.
At first, kernels and drivers may feel overwhelming. That's normal. The secret is to take things one step at a time. Don't rush through chapters. Let each concept settle, and give yourself room to experiment and make mistakes.
### Approach Exercises Seriously
@ -210,13 +249,13 @@ This is a hands-on book. Every chapter includes labs and tutorials designed to t
You will face errors, failed compilations, and perhaps even a kernel panic or two. That is not failure; it is part of the process. Some mistakes will be small, others frustrating, but each one is an opportunity to refine your understanding and grow stronger. The most successful developers are not those who avoid mistakes, but those who persist, turning setbacks into stepping stones.
### Beginner’s Tip
### Beginner's Tip
Don’t be afraid of mistakes; treat them as milestones. Every failed driver load or kernel panic is proof that you’re experimenting and learning. With practice, these mistakes will become your best teachers.
Don't be afraid of mistakes; treat them as milestones. Every failed driver load or kernel panic is proof that you're experimenting and learning. With practice, these mistakes will become your best teachers.
### Engage with the Community
FreeBSD is built by a community of volunteers and professionals who share their time and expertise. Don’t try to learn in isolation. Use the mailing lists, forums, and chat channels. Ask questions, share your progress, and contribute when you can. Becoming part of the community is one of the most rewarding ways to learn.
FreeBSD is built by a community of volunteers and professionals who share their time and expertise. Don't try to learn in isolation. Use the mailing lists, forums, and chat channels. Ask questions, share your progress, and contribute when you can. Becoming part of the community is one of the most rewarding ways to learn.
### Kernel Insight
@ -226,12 +265,12 @@ One reason FreeBSD is an excellent learning platform is its modular driver syste
Remember: you are not just learning to write code, you are learning to shape how an entire operating system interacts with hardware. That is a rare and empowering skill. When progress feels slow, remind yourself that every small step is moving you closer to understanding and influencing the core of a modern operating system.
## Closing Words
## Wrapping Up
This first chapter has been about setting the stage. You’ve walked through my journey, seen why FreeBSD is worth your attention, and caught a first glimpse of the role device drivers play in modern systems. The road ahead will bring challenges, but also the satisfaction of overcoming them step by step.
This first chapter has been about setting the stage. You've walked through my story, seen why FreeBSD is worth your attention, and caught a first glimpse of the role device drivers play in modern systems. The road ahead will bring challenges, but also the satisfaction of overcoming them step by step.
This book is, in many ways, the guide I wish I had when I was starting out. If it saves you even a fraction of the confusion I faced and gives you the same spark of excitement that kept me going, then it has already achieved its purpose.
So take a deep breath. You’re about to move from inspiration to action. In the next chapter, we’ll roll up our sleeves and set up your FreeBSD lab, the environment where all your learning will take place.
So take a deep breath. You're about to move from inspiration to action. In the next chapter, we'll roll up our sleeves and set up your FreeBSD lab, the environment where all your learning will take place.
In chemistry, I learned, the lab was where theory met practice. In this journey, your computer is the lab, and it’s time to prepare it.
In chemistry, I learned, the lab was where theory met practice. In this journey, your computer is the lab, and it's time to prepare it.

View file

@ -1,11 +1,12 @@
---
title: "Setting Up Your Lab"
description: "This chapter guides you through setting up a safe and ready FreeBSD lab for driver development."
author: "Edson Brandi"
date: "2025-08-24"
status: "complete"
part: 1
partNumber: 1
partName: "Foundations: FreeBSD, C, and the Kernel"
chapter: 2
lastUpdated: "2026-04-20"
status: "complete"
author: "Edson Brandi"
reviewer: "TBD"
translator: "TBD"
estimatedReadTime: 60
@ -15,9 +16,9 @@ estimatedReadTime: 60
Before we can begin writing code or exploring FreeBSD's internals, we need a place where it's safe to experiment, make mistakes, and learn. That place is your **lab environment**. In this chapter, we'll create the foundation you'll use throughout the rest of the book: a FreeBSD system configured for driver development.
Think of this chapter as preparing your **workshop**. Just as a carpenter needs the right bench, tools, and safety gear before building furniture, you need a reliable FreeBSD installation, the right development utilities, and a way to recover quickly when things go wrong. Kernel programming is powerful but unforgiving; a tiny mistake in your driver can crash the whole system. Having a dedicated lab means those crashes become part of the learning process, not disasters.
Think of this chapter as preparing your **workshop**. Just as a carpenter needs the right bench, tools, and safety gear before building furniture, you need a reliable FreeBSD installation, the right development utilities, and a way to recover quickly when things go wrong. Kernel programming is unforgiving; a tiny mistake in your driver can crash the whole system. Having a dedicated lab means those crashes become part of the learning process, not disasters.
By the end of this chapter, you will:
After finishing this chapter you will be able to:
- Understand the importance of isolating your experiments from your main computer.
- Choose between using a virtual machine or bare-metal installation.
@ -29,7 +30,7 @@ Along the way, we'll pause for **hands-on labs** so you don't just read about se
### Reader Guidance: How to Use This Chapter
This chapter is more practical than theoretical. Think of it as a step-by-step manual to prepare your workshop before you begin the real experiments. You'll be asked to make choices (virtual machine or bare metal), follow installation steps, and configure your FreeBSD system.
This chapter is more practical than theoretical. Think of it as a step-by-step manual to set up your FreeBSD lab before you begin the real experiments. You'll be asked to make choices (virtual machine or bare metal), follow installation steps, and configure your FreeBSD system.
The best way to use this chapter is to **do the steps as you read them**. Don't just skim through, actually install FreeBSD, take the snapshots, write down your choices in your lab logbook, and try the exercises. Each section builds on the last, so by the end you'll have a complete environment that matches the examples in the rest of this book.
@ -45,7 +46,7 @@ Before we start typing commands and writing our first pieces of code, we need to
This doesn't mean driver development is dangerous, it means we need to take precautions and set up a **safe environment** where mistakes are expected, recoverable, and even encouraged as part of the learning process. That environment is what we'll call your **lab**.
Think of your lab as your **personal workshop**. Just like a chemist wouldn't run an experiment on the family dining table without protective equipment, you shouldn't run unfinished kernel code on the same machine where you keep your personal photos, work documents, or important school projects. You need a space designed for exploration and failure, because failure is how you'll learn.
Your lab should be a **dedicated, isolated environment**. Just like a chemist wouldn't run an experiment on the family dining table without protective equipment, you shouldn't run unfinished kernel code on the same machine where you keep your personal photos, work documents, or important school projects. You need a space designed for exploration and failure, because failure is how you'll learn.
### Why Not Use Your Main Computer?
@ -57,7 +58,7 @@ Your lab setup gives you freedom: you can break things, restart, and recover in
Most beginners (and even many experienced developers) start with **virtual machines (VMs)**. A VM is like a sandboxed computer running inside your real computer. It acts just like a physical machine, but if something goes wrong, you can reset it, take a snapshot, or reinstall FreeBSD in minutes. You don't need a spare laptop or server to start developing drivers; your current computer can host your lab.
We'll dive deeper into virtualization in the next section, but here are the highlights:
We'll cover virtualization in more detail in the next section, but here are the highlights:
- **Safe experiments**: If your driver crashes the kernel, only the VM goes down, not your host computer.
- **Easy recovery**: Snapshots let you save the VM's state and roll back instantly if you break something.
@ -91,7 +92,7 @@ This may feel unnecessary, but keeping a **lab log** will help you track your pr
We've introduced the idea of your **lab environment** and why it's so important for safe driver development. Whether you choose a virtual machine or a spare physical computer, the key is having a dedicated place where it's okay to make mistakes.
In the next section, we'll dive deeper into the **pros and cons of virtual machines versus bare metal setups**. By the end of that section, you'll know exactly which setup makes sense for you to begin your FreeBSD journey.
In the next section, we'll look more closely at the **pros and cons of virtual machines versus bare metal setups**. By the end of that section, you'll know exactly which setup makes sense for you to begin your FreeBSD work.
## Choosing Your Setup: Virtual Machine or Bare Metal
@ -406,7 +407,7 @@ On Windows, the easiest tool is **Rufus**:
If you already have a UNIX-like system, you can create the USB from the terminal using the `dd` command:
```
```console
% sudo dd if=FreeBSD-14.3-RELEASE-amd64-memstick.img of=/dev/da0 bs=1M
```
@ -446,7 +447,7 @@ In the next section, we'll walk through the **initial configuration** you should
When your FreeBSD system finishes its first reboot after installation, you're greeted with something that feels very different from Windows or macOS. There's no flashy desktop, no icons, no "getting started" wizard. Instead, you're dropped at a **login prompt**.
Don't worry, this is normal and intentional. FreeBSD is a UNIX-like system designed to be powerful, stable, and flexible, not flashy. The default environment is simple so that you, the administrator, are in full control. Think of this as the moment you've just unlocked the door to your workshop: the benches are empty, the tools aren't yet arranged, but the space is ready to be built into exactly what you need.
Don't worry, this is normal and intentional. FreeBSD is a UNIX-like system designed for stability and flexibility, not flashy first impressions. The default environment is deliberately minimal so that you, the administrator, stay in full control. Think of this as the first time you sit down at a freshly provisioned lab machine: the shell is empty, the tools are not yet installed, but the system is ready to be shaped into exactly what your work requires.
In this section, we'll perform the **essential first steps** to make your FreeBSD lab comfortable, secure, and ready for driver development.
@ -465,7 +466,7 @@ You're now inside FreeBSD as a regular user.
Some tasks, like installing software or editing system files, require **root privileges**. You should avoid staying logged in as root all the time (it's too risky if you mistype a command), but it's good practice to temporarily switch to root when needed:
```
```console
% su -
Password:
```
@ -514,13 +515,13 @@ Your system needs a name and correct time settings.
Most installations with DHCP "just work." To verify:
```
```console
% ifconfig
```
You should see an interface (like `em0`, `re0`, or `vtnet0` in VMs) with an IP address. If you don't, you may need to enable DHCP in `/etc/rc.conf`:
```
```ini
ifconfig_em0="DHCP"
```
@ -575,7 +576,7 @@ Now your user can safely perform admin tasks without staying logged in as root.
Before installing development tools, bring your system up to date:
```
```console
# freebsd-update fetch install
# pkg update
# pkg upgrade
@ -662,7 +663,7 @@ You have two simple approaches. Pick the one you prefer; both are fine for a lab
Run these regularly to stay current:
```
```console
% sudo freebsd-update fetch install
% sudo pkg update && pkg upgrade
```
@ -677,7 +678,7 @@ In the next section, we'll install the **development tools** needed for driver p
## Preparing the System for Development
Now that your FreeBSD lab is installed, updated, and lightly hardened, it's time to turn it into a proper **driver development environment**. Think of this step as stocking your workshop with the right tools; compiler, debugger, version control, and the FreeBSD source tree. Without these, you won't be able to build or test the code we'll write in later chapters.
Now that your FreeBSD lab is installed, updated, and lightly hardened, it's time to turn it into a proper **driver development environment**. This step adds the pieces needed to build, debug, and version-control kernel code: the compiler, the debugger, a version control system, and the FreeBSD source tree. Without these, you won't be able to build or test the code we'll write in later chapters.
The good news is that FreeBSD already includes most of what we need. In this section, we'll install the missing pieces, verify everything works, and run a tiny "hello module" test to prove that your lab is ready for driver development.
@ -685,7 +686,7 @@ The good news is that FreeBSD already includes most of what we need. In this sec
FreeBSD comes with **Clang/LLVM** in the base system. To confirm:
```
```console
% cc --version
FreeBSD clang version 19.1.7 (...)
```
@ -694,7 +695,7 @@ If you see a version string like the above, you're ready to compile C code.
Still, you'll need some additional tools:
```
```console
# pkg install git gmake gdb
```
@ -704,9 +705,9 @@ Still, you'll need some additional tools:
### Choosing an Editor
Every developer has their favourite editor. FreeBSD includes `vi` by default, powerful, but with a steep learning curve. If you're brand new, you can safely start with **`ee` (Easy Editor)**, which guides you with on-screen help, or install **`nano`**, which has simpler shortcuts like Ctrl+O to save and Ctrl+X to quit:
Every developer has their favourite editor. FreeBSD includes `vi` by default, capable but with a steep learning curve. If you're brand new, you can safely start with **`ee` (Easy Editor)**, which guides you with on-screen help, or install **`nano`**, which has simpler shortcuts like Ctrl+O to save and Ctrl+X to quit:
```
```console
% sudo pkg install nano
```
@ -755,7 +756,7 @@ But sooner or later, you'll want to learn **`vim`**, the improved version of `vi
If you prefer `nano`, it also supports syntax highlighting. The configuration is stored in `/usr/local/share/nano/`. To enable it for C:
```
```console
% cp /usr/local/share/nano/c.nanorc ~/.nanorc
```
@ -769,7 +770,7 @@ Now open a `.c` file with `nano` and you'll see basic highlighting.
The **man pages** are your built-in reference library. Try this:
```
```console
% man 9 malloc
```
@ -785,9 +786,11 @@ Other useful commands:
Most driver development requires access to the FreeBSD kernel source code. You'll store it in `/usr/src`.
From this point on, whenever this book cites a file such as `/usr/src/sys/kern/kern_module.c`, it refers to a real file inside the source tree you are about to clone. `/usr/src` is the conventional location for the FreeBSD source tree on a FreeBSD system, and every path of the form `/usr/src/...` in later chapters maps directly to a file under the `src` checkout below. Later chapters will not re-explain this convention; they will simply quote the path and expect you to find it at that location.
Clone it with Git:
```
```console
% sudo git clone --branch releng/14.3 --depth 1 https://git.FreeBSD.org/src.git src /usr/src
```
@ -795,7 +798,7 @@ This will take a few minutes and download several gigabytes. When finished, you'
Verify with:
```
```console
% ls /usr/src/sys
```
@ -807,7 +810,7 @@ FreeBSD is very strict about building loadable kernel modules against the exact
**Tip**: if `/usr/src` already exists and points elsewhere, you can retarget it:
```
```console
% sudo git -C /usr/src fetch --all --tags
% sudo git -C /usr/src checkout releng/14.3
% sudo git -C /usr/src pull --ff-only
@ -874,7 +877,7 @@ MODULE_VERSION(hello_world, 1);
1. Create a `Makefile`:
```
```console
# Makefile for hello_world kernel module
KMOD= hello_world
@ -885,7 +888,7 @@ SRCS= hello_world.c
1. Build the module:
```
```console
# make
```
@ -893,13 +896,13 @@ This should create a file `hello.ko`.
1. Load the module:
```
```console
# kldload ./hello_world.ko
```
Check the message in the system log:
```
```console
% dmesg | tail -n 5
```
@ -909,13 +912,13 @@ You should see:
1. Unload the module:
```
```console
# kldunload hello_world.ko
```
Check again:
```
```console
% dmesg | tail -n 5
```
@ -993,11 +996,11 @@ If your VM disk is stored on a ZFS dataset, for example `/zroot/vm/freebsd.img`:
### Snapshots on Bare Metal
If you're running FreeBSD directly on hardware, you don't have the luxury of GUI snapshots. But if you installed FreeBSD with **ZFS**, you still have access to the same powerful snapshot tools.
If you're running FreeBSD directly on hardware, you don't have the luxury of GUI snapshots. But if you installed FreeBSD with **ZFS**, you still have access to the same snapshot tools.
With ZFS:
```
```console
# zfs snapshot -r zroot@clean-install
```
@ -1061,7 +1064,7 @@ Record in your **lab logbook**: which method you used, how long it took, and how
### Wrapping Up
By learning to use **snapshots and backups**, you've added one of the most important safety nets to your lab. Now you can crash, break, or misconfigure FreeBSD and recover in minutes. This freedom is what makes a lab so powerful, it lets you focus on learning, not on being afraid of mistakes.
By learning to use **snapshots and backups**, you've added one of the most important safety nets to your lab. Now you can crash, break, or misconfigure FreeBSD and recover in minutes. This freedom is what makes a lab so valuable, it lets you focus on learning, not on being afraid of mistakes.
In the next section, we'll set up **version control with Git** so you can track your progress, manage your experiments, and share your drivers.
@ -1087,13 +1090,13 @@ Think of Git as the **lab notebook for your code**, only smarter: it not only re
If you haven't already installed Git in section 2.5, do it now:
```
```console
# pkg install git
```
Check the version:
```
```console
% git --version
git version 2.45.2
```
@ -1102,7 +1105,7 @@ git version 2.45.2
Before using Git, configure your identity so your commits are labeled correctly:
```
```console
% git config --global user.name "Your Name"
% git config --global user.email "you@example.com"
```
@ -1111,7 +1114,7 @@ This doesn't need to be your real name or email if you're just experimenting loc
You can check your settings with:
```
```console
% git config --list
```
@ -1172,7 +1175,7 @@ For now, you can keep everything local. But if you want to sync your code betwee
Basic workflow:
```
```console
% git remote add origin git@github.com:yourname/mydriver.git
% git push -u origin main
```
@ -1269,7 +1272,7 @@ Git commit messages are a form of documentation. Together, they tell the story o
Example:
```
```text
Fix panic when unloading hello module
The handler did not check for NULL before freeing resources,
@ -1280,7 +1283,7 @@ causing a panic when unloading. Added a guard condition.
In Section 2.1, we suggested starting a lab logbook. Now is a good time to make it a habit. Keep a text file (for example, `LABLOG.md`) in the root of your Git repository. Each time you try something new, add a short entry:
```
```text
2025-08-23
- Built hello module successfully.
- Confirmed "Hello, kernel world!" appears in dmesg.
@ -1321,9 +1324,9 @@ This log doesn't need to be polished, it's just for you. Later, when debugging,
You've now learned how to document your FreeBSD driver experiments so that you never lose track of what you did or why. With a `README`, meaningful commit messages, and a lab logbook, you're building habits that will make you a more professional and efficient developer.
In the next section, we'll wrap up this chapter, reviewing everything you've built: a safe FreeBSD lab with the right tools, backups, version control, and documentation, all ready for the deeper journey into FreeBSD itself in Chapter 3.
In the next section, we'll wrap up this chapter, reviewing everything you've built: a safe FreeBSD lab with the right tools, backups, version control, and documentation, all ready for the deeper exploration of FreeBSD itself in Chapter 3.
### Bringing It All Together
## Wrapping Up
Congratulations! You've built your FreeBSD lab!

View file

@ -1,11 +1,12 @@
---
title: "A Gentle Introduction to UNIX"
description: "This chapter provides a hands-on introduction to UNIX and FreeBSD basics."
author: "Edson Brandi"
date: "2025-08-23"
status: "complete"
part: 1
partNumber: 1
partName: "Foundations: FreeBSD, C, and the Kernel"
chapter: 3
lastUpdated: "2026-04-20"
status: "complete"
author: "Edson Brandi"
reviewer: "TBD"
translator: "TBD"
estimatedReadTime: 120
@ -35,9 +36,9 @@ Recommendation: Don't try to do everything in one sitting. Break the chapter int
Before we start writing device drivers for FreeBSD, we need to pause and talk about the foundation they stand on: **UNIX**.
Every driver you'll ever write for FreeBSD, every system call you'll explore, every kernel message you'll read, they all make sense only when you understand the operating system they live in. For a beginner, the world of UNIX can feel mysterious, filled with odd commands and a very different philosophy compared to Windows or macOS. But once you learn its logic, you'll see it's not only approachable but also elegant and incredibly powerful.
Every driver you'll ever write for FreeBSD, every system call you'll explore, every kernel message you'll read, they all make sense only when you understand the operating system they live in. For a beginner, the world of UNIX can feel mysterious, filled with odd commands and a very different philosophy compared to Windows or macOS. But once you learn its logic, you'll see it's not only approachable but also elegant.
This chapter is about giving you a **gentle introduction** to UNIX as it appears in FreeBSD. By the end, you'll feel comfortable navigating the system, working with files, running commands, managing processes, installing applications, and even writing small scripts to automate your tasks. These are everyday skills for any FreeBSD developer and absolutely essential before we dive into kernel development.
This chapter is about giving you a **gentle introduction** to UNIX as it appears in FreeBSD. By the end, you'll feel comfortable navigating the system, working with files, running commands, managing processes, installing applications, and even writing small scripts to automate your tasks. These are everyday skills for any FreeBSD developer and absolutely essential before we start on kernel development.
### Why Should You Learn UNIX Before Writing Drivers?
@ -162,7 +163,7 @@ If you've mostly used Windows, the UNIX approach will feel different at first. H
- **Registry vs. text files**
Windows centralizes settings in the Registry. UNIX uses plain-text configuration files under `/etc` and `/usr/local/etc`. You can open them with any text editor.
- **GUI focus vs. CLI focus**
While Windows assumes a graphical interface, UNIX treats the command line as the primary tool. Graphical environments exist, but the shell is always available and powerful.
While Windows assumes a graphical interface, UNIX treats the command line as the primary tool. Graphical environments exist, but the shell is always available.
- **Permissions model**
UNIX was multi-user from day one. Every file has permissions (read, write, execute) for the owner, group, and others. This makes security and sharing simpler and more consistent.
@ -190,7 +191,7 @@ Let's make this concrete. Open a terminal in the FreeBSD you installed in the pr
This prints system details: the OS, the system name, release version, kernel build, and machine type. On FreeBSD 14.x, you might see:
```
```text
FreeBSD freebsd.edsonbrandi.com 14.3-RELEASE FreeBSD 14.3-RELEASE releng/14.3-n271432-8c9ce319fef7 GENERIC amd64
```
@ -217,7 +218,7 @@ You just created a file, wrote to it, and read it back. This is the same model y
### Wrapping Up
In this section, you learned that UNIX is not just an operating system but a family of ideas and design principles that shaped modern computing. You saw how FreeBSD fits into this history as a direct descendant of BSD UNIX, why its philosophy of small tools and plain text makes it powerful, and how many of the concepts you'll rely on as a driver developer, like processes, daemons, and file descriptors, have been part of UNIX since the beginning.
In this section, you learned that UNIX is not just an operating system but a family of ideas and design principles that shaped modern computing. You saw how FreeBSD fits into this history as a direct descendant of BSD UNIX, why its philosophy of small tools and plain text makes it effective, and how many of the concepts you'll rely on as a driver developer, like processes, daemons, and file descriptors, have been part of UNIX since the beginning.
But knowing what UNIX is only gets us halfway. To really use FreeBSD, you need a way to **interact with it**. That's where the shell comes in, the command interpreter that lets you speak the system's language. In the next section, we'll start using the shell to run commands, explore the filesystem, and get hands-on experience with the tools that every FreeBSD developer depends on daily.
@ -301,7 +302,7 @@ This consistency is one of UNIX's strengths: once you learn the pattern, every c
### Essential Commands for Beginners
Let's explore the core commands you'll use constantly.
We will walk through the core commands you'll use constantly.
#### Navigating Directories
@ -418,7 +419,7 @@ Sooner or later, you'll need to edit a configuration file or a source file. Free
- **vi / vim**
- The traditional UNIX editor, always available.
- Extremely powerful, but it has a steep learning curve.
- Extremely capable, but it has a steep learning curve.
- Beginners often get stuck because `vi` starts in *command mode* instead of insert mode.
- To start typing text: press **i**, write your text, then press **Esc** followed by `:wq` to save and quit.
- You don't need to master it now, but every sysadmin and developer eventually learns at least the basics of `vi`.
@ -620,7 +621,7 @@ This is called a **hierarchical filesystem**. At the very top is `/`, and everyt
Here's a simplified map:
```
```text
/
├── bin → Essential user commands (ls, cp, mv)
├── sbin → System administration commands (ifconfig, shutdown)
@ -660,7 +661,7 @@ Understanding this layout is critical for a driver developer because some direct
### Devices as Files: `/dev`
One of UNIX's most powerful ideas is that **devices appear as files** under `/dev`.
One of UNIX's core ideas is that **devices appear as files** under `/dev`.
Examples:
@ -700,7 +701,7 @@ Example:
Suppose your home directory contains this structure:
```
```text
/home/dev/unix_lab/
├── docs/
│ └── notes.txt
@ -772,7 +773,7 @@ This lab gives you a "mental map" of the FreeBSD filesystem and shows how config
### Wrapping Up
In this section, you've learned that FreeBSD uses a **single, hierarchical filesystem** starting at `/`, with key directories dedicated to system binaries, configuration, logs, user data, and devices. You also saw how `/dev` treats devices as files, a powerful concept that you'll rely on when you write drivers.
In this section, you've learned that FreeBSD uses a **single, hierarchical filesystem** starting at `/`, with key directories dedicated to system binaries, configuration, logs, user data, and devices. You also saw how `/dev` treats devices as files, a core concept that you'll rely on when you write drivers.
But files and directories aren't just about structure; they're also about **who can access them**. UNIX is a multi-user system, and every file has an owner, a group, and permission bits that control what can be done with it. In the next section, we'll explore **users, groups, and permissions**, and you'll learn how FreeBSD keeps the system both secure and flexible.
@ -800,7 +801,7 @@ You can see your current identity with:
Example output:
```
```text
dev
uid=1001(dev) gid=1001(dev) groups=1001(dev), 0(wheel)
```
@ -824,7 +825,7 @@ Let's check with `ls -l`:
Output:
```
```text
-rw-r--r-- 1 dev dev 12 Aug 23 10:15 hello.txt
```
@ -856,7 +857,7 @@ And three kinds of permission bits:
Example:
```
```text
-rw-r--r--
```
@ -1047,13 +1048,13 @@ And bring one back to the foreground:
To see which processes are running, use `ps`:
```
```console
ps aux
```
Sample output:
```
```text
USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
root 1 0.0 0.0 1328 640 - Is 10:00AM 0:00.01 /sbin/init
dev 1024 0.0 0.1 4220 2012 - S 10:05AM 0:00.02 -tcsh
@ -1118,13 +1119,13 @@ Here we can see:
If you don't need the full detail of `top`, you can use:
```
```console
% uptime
```
Which shows something like:
```
```text
3:45PM up 2 days, 4:11, 2 users, load averages: 0.32, 0.28, 0.25
```
@ -1304,7 +1305,7 @@ In this section, you learned that processes are the living, running programs ins
Processes are essential because they make the system alive, and as a driver developer, the programs that use your driver will always run as processes.
But monitoring processes is only part of the story. To do real work, you'll need more tools than those included in the base system. FreeBSD provides a clean and powerful way to install and manage extra software, from simple utilities like `nano` to large applications like web servers. In the next section, we'll dive into the **FreeBSD package system and the Ports Collection**, so you can extend your system with the software you need.
But monitoring processes is only part of the story. To do real work, you'll need more tools than those included in the base system. FreeBSD provides a clean and flexible way to install and manage extra software, from simple utilities like `nano` to large applications like web servers. In the next section, we'll look at the **FreeBSD package system and the Ports Collection**, so you can extend your system with the software you need.
## Installing and Managing Software
@ -1313,7 +1314,7 @@ FreeBSD is designed as a lean and reliable operating system. Out of the box, you
1. **pkg** - The binary package manager: fast, simple, and convenient.
2. **The Ports Collection** - A massive source-based build system that allows fine-tuned customization.
Together, they give FreeBSD one of the most flexible and powerful software ecosystems in the UNIX world.
Together, they give FreeBSD one of the most flexible software ecosystems in the UNIX world.
### Binary Packages with pkg
@ -1427,7 +1428,7 @@ Once Ports is installed, explore it:
You'll see files and categories such as:
```
```text
CHANGES UIDs comms ftp mail portuguese x11
CONTRIBUTING.md UPDATING converters games math print x11-clocks
COPYRIGHT accessibility databases german misc russian x11-drivers
@ -1493,7 +1494,7 @@ Try:
Output:
```
```text
/usr/local/bin/nano
```
@ -1680,7 +1681,7 @@ After reboot, your system is fully patched.
### Kernel Updates with `freebsd-update`
One of the powerful things about `freebsd-update` is that it can update the kernel itself. You don't have to rebuild it manually unless you want to run a custom kernel (we'll cover that later in the book).
One of the useful things about `freebsd-update` is that it can update the kernel itself. You don't have to rebuild it manually unless you want to run a custom kernel (we'll cover that later in the book).
This means that for most users, staying secure and current is just a matter of running `fetch` + `install` regularly.
@ -1809,11 +1810,11 @@ The crontab format has **five fields** that describe *when* to run a job, follow
minute hour day month weekday command
```
- **minute**: 0–59
- **hour**: 0–23 (24-hour clock)
- **day**: 1–31
- **month**: 1–12
- **weekday**: 0–6 (0 = Sunday, 6 = Saturday)
- **minute**: 0-59
- **hour**: 0-23 (24-hour clock)
- **day**: 1-31
- **month**: 1-12
- **weekday**: 0-6 (0 = Sunday, 6 = Saturday)
A mnemonic to help you remember: *"My Hungry Dog Must Wait."* (Minute, Hour, Day, Month, Weekday)
@ -1855,13 +1856,13 @@ This opens your crontab in the default editor (`vi` or `ee`).
To list your jobs:
```
```console
crontab -l
```
To remove your crontab:
```
```console
crontab -r
```
@ -1871,7 +1872,7 @@ When cron runs a job, its output (stdout and stderr) is sent by **email** to the
You can also redirect output to a log file to make things easier:
```
```text
0 0 * * * /home/dev/backup.sh >> /home/dev/backup.log 2>&1
```
@ -1918,7 +1919,7 @@ These tasks run automatically at **daily, weekly, and monthly intervals**, thank
The scripts are organized in directories under `/etc/periodic`:
```
```text
/etc/periodic/daily
/etc/periodic/weekly
/etc/periodic/monthly
@ -1947,7 +1948,7 @@ Many new FreeBSD users run their system for a few days, knowing periodic is supp
To read them, log in as root and run:
```
```console
# mail
```
@ -2055,7 +2056,7 @@ For everyday users, periodic keeps the system tidy and secure without extra effo
- Rotate or clean up custom log files created by your driver.
- Run automated integrity checks (e.g., verify your driver's device node exists and responds).
By hooking into periodic, you leverage the same framework FreeBSD itself uses for its own housekeeping.
By hooking into periodic, you build on the same framework FreeBSD itself uses for its own housekeeping.
**Hands-On Lab: Exploring and Customizing periodic**
@ -2150,7 +2151,7 @@ In this section, you learned how FreeBSD automates tasks using three main tools:
You practiced creating jobs, checked their output, and learned how FreeBSD itself relies on automation to stay healthy.
Automation is powerful, but sometimes you need to go beyond fixed schedules. You might want to chain commands together, use loops, or add logic to decide what happens. That's where **shell scripting** comes in. In the next section, we'll write your first scripts and see how to create custom automation tailored to your needs.
Automation is useful, but sometimes you need to go beyond fixed schedules. You might want to chain commands together, use loops, or add logic to decide what happens. That's where **shell scripting** comes in. In the next section, we'll write your first scripts and see how to create custom automation tailored to your needs.
## Introduction to Shell Scripting
@ -2181,7 +2182,7 @@ echo "User: $(whoami)"
The first line of this script is:
```
```sh
#!/bin/sh
```
@ -2204,7 +2205,7 @@ Now let's make the script executable and run it:
If you get "Permission denied", you forgot `chmod +x`.
If you get "Command not found", you probably typed `hello.sh` without `./` and the current directory is not included in system `PATH`.
**Tip**: Don't feel pressured to master all scripting features at once. Start small, write a 2–3 line script that prints your username and the date. Once you're comfortable, add conditions (`if`), then loops, then functions. Shell scripting is like LEGO: build one block at a time.
**Tip**: Don't feel pressured to master all scripting features at once. Start small, write a 2-3 line script that prints your username and the date. Once you're comfortable, add conditions (`if`), then loops, then functions. Shell scripting is like LEGO: build one block at a time.
### 2) Variables and quoting
@ -2593,7 +2594,7 @@ All scripts should start with `#!/bin/sh`, contain comments explaining each step
### Wrapping up
In this section, you learned the **native FreeBSD way** to automate work with portable scripts that run on any clean FreeBSD install. You can now write small programs with `/bin/sh`, handle arguments, test conditions, loop through files, define functions, use temporary files safely, and debug issues with simple tools. In your driver journey, scripts will help you repeat tests, gather logs, and package builds reliably.
In this section, you learned the **native FreeBSD way** to automate work with portable scripts that run on any clean FreeBSD install. You can now write small programs with `/bin/sh`, handle arguments, test conditions, loop through files, define functions, use temporary files safely, and debug issues with simple tools. While writing drivers, scripts will help you repeat tests, gather logs, and package builds reliably.
Before we move on, a reminder: you do not need to memorise every construct or command option. Part of being productive in UNIX is knowing where to **find the right information at the right time**.
@ -2620,7 +2621,7 @@ file_with?newline.txt
The `?` appears because `ls` substitutes unprintable characters when displaying filenames. The actual filename contains:
```
```text
file_with
newline.txt
```
@ -2828,7 +2829,7 @@ The **manual pages**, or **man pages**, are the built-in reference system for UN
You read them with the `man` command, for example:
```
```console
% man ls
```
@ -2890,7 +2891,7 @@ Later in this book, we'll constantly refer to section 9 as we introduce new kern
If you don't know the exact command name, use the `-k` flag (equivalent to `apropos`):
```
```console
man -k network
```
@ -2898,7 +2899,7 @@ This shows every man page related to networking.
Another example:
```
```console
man -k disk | less
```
@ -3024,7 +3025,7 @@ This is short but complete; version, command, error, and troubleshooting steps a
### Wrapping Up
FreeBSD gives you powerful tools to teach yourself. The **man pages** are your first stop; they're always on your system, always up to date, and cover everything from basic commands to kernel APIs. The **Handbook** is your big-picture guide, and the **community** mailing lists, forums, user groups, and online chat are there to help when you need human answers.
FreeBSD gives you solid tools to teach yourself. The **man pages** are your first stop; they're always on your system, always up to date, and cover everything from basic commands to kernel APIs. The **Handbook** is your big-picture guide, and the **community** mailing lists, forums, user groups, and online chat are there to help when you need human answers.
Later, as you write drivers, you'll rely heavily on man pages (especially section 9) and on discussions in FreeBSD mailing lists and forums. Knowing how to find information is just as important as memorizing commands.
@ -3045,7 +3046,7 @@ FreeBSD gives you **three magical windows into the kernel's state**:
2. **`sysctl`** - the control panel full of switches and meters.
3. **`/dev`** - the doorway where devices show up as files.
These three tools will become your **companions**. Every time you add or debug a driver, you'll use them. Let's explore them now, step by step.
These three tools will become your **companions**. Every time you add or debug a driver, you'll use them. Let's look at them now, step by step.
### dmesg: Reading the Kernel's Diary
@ -3104,7 +3105,7 @@ If `dmesg` is the diary, `sysctl` is the **dashboard full of knobs and meters**.
Try this commands:
```
```console
% sysctl kern.ostype
% sysctl kern.osrelease
% sysctl hw.model
@ -3113,7 +3114,7 @@ Try this commands:
Output might look like:
```
```text
kern.ostype: FreeBSD
kern.osrelease: 14.3-RELEASE
hw.model: AMD Ryzen 7 5800U with Radeon Graphics
@ -3231,9 +3232,9 @@ With this short lab, you've already read kernel messages, queried kernel variabl
### From Shell to Hardware: The Big Picture
To understand why tools like `dmesg`, `sysctl`, and `/dev` are so powerful, it helps to picture how FreeBSD is layered:
To understand why tools like `dmesg`, `sysctl`, and `/dev` are so useful, it helps to picture how FreeBSD is layered:
```
```text
+----------------+
| User Space | ← Commands you run: ls, ps, pkg, scripts
+----------------+
@ -3313,11 +3314,17 @@ The **big picture** to remember is this: whenever you type a command, it travels
These aren't just abstract tools; they're exactly how you'll see your **own driver** appear in the system. When you load your module, you'll watch `dmesg` light up, you may expose a knob with `sysctl`, and you'll interact with your device node under `/dev`.
Before we move on to the next chapter and start learning about C programming, let's pause to consolidate everything you've learned in this chapter. In the next section, we'll review the key ideas and give you a set of challenges to practice, exercises that will help lock in these new skills and prepare you for the journey ahead.
It is worth pausing for a moment on what this tells you about the road ahead. Every line of `dmesg` that describes hardware attaching, every `sysctl` name that starts with `kern.` or `vm.`, and every file under `/dev` is the visible face of kernel code written in C. When you ran `dmesg`, you were reading strings that a driver passed to `device_printf` or `printf` during attach. When you walked `sysctl -a`, you were traversing a tree that drivers and subsystems populate with `SYSCTL_INT`, `SYSCTL_ULONG`, and related macros. When you opened `/dev/null`, the kernel dispatched your `read` or `write` into a driver whose structure you will meet in Chapter 6. You have been looking at the outputs of driver code all along; the next two chapters teach you to write the inputs.
## Putting It All Together: Your FreeBSD Journey So Far
Chapter 5 takes you into the **C language as the kernel actually uses it**: fixed-width integer types, explicit memory management with `malloc(9)` and `free(9)`, pointer discipline under interrupt context, and the subset of C that FreeBSD's Kernel Normal Form (KNF) considers idiomatic. It is not "just C again." The kernel cannot call `printf` from libc, cannot allocate with plain `malloc`, and cannot assume the usual userland safety nets. Chapter 5 shows you what changes and why, so that the code you write later compiles, loads, and behaves predictably.
Congratulations! You've just taken your **first deep dive into UNIX and FreeBSD**. What started as abstract ideas is now becoming practical skills. You can move around the system, manage files, edit and install software, control processes, automate tasks, and even peek into the kernel's inner workings.
Chapter 6 then takes the C you have just relearned and assembles it into a first driver, stepping through the **anatomy of a FreeBSD driver** piece by piece: the softc structure, the Newbus method table, the `DRIVER_MODULE` macro, and the path a `read` or `write` takes from your `/dev/foo` device node to the driver routine that services it. By the end of Chapter 6 you will have loaded your own module, seen it announce itself in `dmesg`, and used the same commands you practised in this chapter to confirm that it works.
Before we move on and start learning about C programming, let's pause to consolidate everything you've learned in this chapter. In the next section, we'll review the key ideas and give you a set of challenges to practice, exercises that will help lock in these new skills and prepare you for the work ahead.
## Wrapping Up
Congratulations! You've just taken your **first guided tour through UNIX and FreeBSD**. What started as abstract ideas is now becoming practical skills. You can move around the system, manage files, edit and install software, control processes, automate tasks, and even peek into the kernel's inner workings.
Let's take a moment to review what you've accomplished in this chapter:
@ -3335,9 +3342,9 @@ That's a lot, but don't worry if you don't feel like an expert yet. The goal of
### Practice Ground
To make sure these skills stick, here are **46 exercises**.
If you would like a hands-on way to reinforce what you just read, the next pages collect **46 optional exercises**. None of them are required to continue with the book, so treat them as extras: pick the ones that cover ground where you still feel unsure, skip the ones that feel redundant, and come back to the rest later if they become useful.
They're grouped by topic, so you can practice section by section or mix them up as you like.
They are grouped by topic, so you can practice section by section or mix them up as you like.
### Filesystem and Navigation (8 exercises)
@ -3420,7 +3427,7 @@ With these **46 exercises**, you've covered every major topic in this chapter:
By completing them, you'll move from being a *passive reader* to an **active UNIX practitioner**. You'll not only know how FreeBSD works, you'll have *lived inside it*.
These exercises are the **muscle memory** you'll need when we start programming. When we dive into C and later kernel development, you'll already be fluent in the daily tools of a UNIX developer.
These exercises are the **muscle memory** you'll need when we start programming. When we reach C and later kernel development, you'll already be fluent in the daily tools of a UNIX developer.
### Looking Ahead

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff