diff --git a/examples/README.md b/examples/README.md index da03470..325021b 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,167 +1,233 @@ # Examples Directory -This directory contains the complete source code for all examples provided throughout the **FreeBSD Device Drivers Book**. These examples are designed to help readers understand and practice the concepts discussed in each chapter. +This directory contains the downloadable companion files for **FreeBSD Device Drivers: From First Steps to Kernel Mastery**. Each folder mirrors the place in the book where the file is introduced, so you can move from a chapter or appendix straight to the source code, Makefiles, scripts, configurations, and supporting artifacts the text asks you to type, edit, compile, run, test, or load. + +The companion tree is meant to make the labs and walkthroughs easier to follow. It is not a replacement for the prose. Read the chapter as you work through the matching folder. ## Directory Structure -The examples are organized to mirror the book's structure: +The tree is organized by part, then by chapter, then by example: ``` examples/ -├── README.md # This file -├── chapters/ # Examples from main chapters -│ ├── part1/ # Part 1: Fundamentals -│ ├── part2/ # Part 2: Basic Drivers -│ ├── part3/ # Part 3: Advanced Topics -│ ├── part4/ # Part 4: Specialized Drivers -│ ├── part5/ # Part 5: Performance & Optimization -│ ├── part6/ # Part 6: Debugging & Testing -│ └── part7/ # Part 7: Real-world Applications -└── appendices/ # Examples from appendices - ├── appendix-a/ # Appendix A examples - ├── appendix-b/ # Appendix B examples - ├── appendix-c/ # Appendix C examples - ├── appendix-d/ # Appendix D examples - └── appendix-e/ # Appendix E examples +├── README.md # This file +├── part-01/ # Part 1: Foundations: FreeBSD, C, and the Kernel +│ ├── ch02-setting-up-your-lab/ +│ ├── ch03-a-gentle-introduction-to-unix/ +│ ├── ch04-a-first-look-at-the-c-programming-language/ +│ ├── ch05-understanding-c-for-freebsd-kernel-programming/ +│ └── ch06-the-anatomy-of-a-freebsd-driver/ +├── part-02/ # Part 2: Building Your First Driver +│ ├── ch07-writing-your-first-driver/ +│ ├── ch08-working-with-device-files/ +│ ├── ch09-reading-and-writing/ +│ └── ch10-handling-io-efficiently/ +├── part-03/ # Part 3: Concurrency and Synchronization +│ ├── ch11-concurrency/ +│ ├── ch12-synchronization-mechanisms/ +│ ├── ch13-timers-and-delayed-work/ +│ ├── ch14-taskqueues-and-deferred-work/ +│ └── ch15-more-synchronization/ +├── part-04/ # Part 4: Hardware and Platform-Level Integration +│ ├── ch16-accessing-hardware/ +│ ├── ch17-simulating-hardware/ +│ ├── ch18-writing-pci-driver/ +│ ├── ch19-handling-interrupts/ +│ ├── ch20-advanced-interrupts/ +│ ├── ch21-dma/ +│ └── ch22-power/ +├── part-05/ # Part 5: Debugging, Tools, and Real-World Practices +│ ├── ch23-debug/ +│ ├── ch24-integration/ +│ └── ch25-advanced/ +├── part-06/ # Part 6: Writing Transport-Specific Drivers +│ ├── ch26-usb-serial/ +│ ├── ch27-storage-vfs/ +│ └── ch28-network-driver/ +├── part-07/ # Part 7: Mastery Topics: Special Scenarios and Edge Cases +│ ├── ch29-portability/ +│ ├── ch30-virtualisation/ +│ ├── ch31-security/ +│ ├── ch32-fdt-embedded/ +│ ├── ch33-performance/ +│ ├── ch34-advanced-debugging/ +│ ├── ch35-async-io/ +│ ├── ch36-reverse-engineering/ +│ ├── ch37-upstream/ +│ └── ch38-final-thoughts/ +└── appendices/ + ├── appendix-a-freebsd-kernel-api-reference/ + ├── appendix-b-algorithms-and-logic-for-systems-programming/ + ├── appendix-c-hardware-concepts-for-driver-developers/ + ├── appendix-d-operating-system-concepts/ + ├── appendix-e-navigating-freebsd-kernel-internals/ + └── appendix-f-benchmarks/ ``` -## Example Organization +Chapter 1 has no companion files, which is why no `ch01-...` folder appears under `part-01/`. -Each example includes: +## How Each Chapter Folder Is Organized -- **Source code files** (`.c`, `.h`, `.mk`, etc.) -- **Makefile** for building the example -- **README** with specific instructions for that example -- **Documentation** explaining the example's purpose and usage +Inside a chapter folder, the material is grouped by how the book uses it. The exact mix depends on the chapter, but the recurring patterns are: -## Building Examples +* `stageN-name/` for chapters that build a driver in successive stages. Each stage is a self-contained, buildable snapshot, so you can compile and load any stage on its own and compare it to the next one. +* `labNN-name/` for hands-on labs the chapter walks through. +* `challengeNN-name/` for the optional challenge exercises that follow the labs. +* `shared/` for files used by more than one lab in the same chapter, such as common headers or helper scripts. +* `scripts/` for chapter-level helper scripts that automate setup, testing, or measurement. +* `userland/` for user-space test programs that pair with a kernel module from the same chapter. +* `final/` or `stageN-final/` for the final converged version of a chapter-long driver. +* Topical folders, such as `configs/`, `demos/`, `patterns/`, `cheatsheets/`, `cbuf-userland/`, `hwsim-standalone/`, `templates/`, and similar, when a chapter introduces material that does not fit the lab or stage pattern. -### Prerequisites +## What You Will Find Inside an Example -Before building any examples, ensure you have: +A typical example folder contains some combination of: -1. **FreeBSD development environment** set up -2. **Kernel source code** available -3. **Required tools** installed: - - `gcc` or `clang` - - `make` - - `kldload`/`kldunload` (for kernel modules) +* **Source files** (`.c`, `.h`) for the driver, helper code, or user-space program. +* **A Makefile** that includes `bsd.kmod.mk` for kernel modules, or `bsd.prog.mk` for user-space programs. +* **Scripts** (`.sh`, DTrace `.d`, `awk`, and similar) used during the lab or its measurement steps. +* **Configuration fragments** (loader.conf snippets, sysctl files, FDT overlays) when the lab needs them. +* **Test artifacts** such as fixed input data, expected output, or trace files used for comparison. -### Building a Specific Example +## Building and Loading an Example -```bash -# Navigate to the example directory -cd examples/chapters/part1/example-01 +Each example is intended to be built from its own folder. There is no top-level aggregator Makefile. To build and load a kernel module example, change into the folder shown in the chapter and run `make`: -# Build the example +```sh +# From the repository root +cd examples/part-02/ch07-writing-your-first-driver/stage1-newbus + +# Build the module against the running kernel make -# Load the kernel module (if applicable) -sudo kldload ./example_module.ko +# Load it +sudo kldload ./myfirst.ko -# Unload the kernel module (if applicable) -sudo kldunload example_module +# Inspect it +kldstat | grep myfirst +dmesg | tail + +# Unload it when you are done +sudo kldunload myfirst ``` -### Building All Examples +User-space helper programs follow the same pattern, but produce an executable instead of a `.ko`. -```bash -# From the examples directory -make all -``` +## Prerequisites -## Example Types +Before you build any example, make sure your lab system has: -The examples cover various aspects of FreeBSD device driver development: +1. A working FreeBSD installation, ideally **FreeBSD 14.3** or later, set up using the procedure in Chapter 2. +2. The matching kernel source tree under `/usr/src/` (the system source, not a separate copy). +3. The base development tools, which are part of the FreeBSD base system: `cc` (Clang), `make`, `kldload(8)`, `kldunload(8)`, `kldstat(8)`, and the standard build infrastructure under `/usr/share/mk/`. +4. Root privileges for `kldload` and `kldunload`. The examples assume you can use `sudo` or are running as `root` in a dedicated lab environment. + +Some later chapters add specific prerequisites, such as DTrace, `pmcstat`, a USB device, a virtual machine for PCI passthrough, or an FDT-capable board. Those are listed in the chapter that introduces them. + +## Mapping Folders to the Book + +The folders below match the canonical chapter sequence. ### Part 1: Foundations: FreeBSD, C, and the Kernel -- **Introduction** - Getting started with FreeBSD device driver development -- **Setting Up Your Lab** - Development environment setup and configuration -- **A Gentle Introduction to UNIX** - UNIX fundamentals for driver development -- **A First Look at the C Programming Language** - C programming basics -- **Understanding C for Kernel Programming** - Advanced C concepts for kernel development -- **The Anatomy of a FreeBSD Driver** - Basic driver structure and components -### Part 2: Basic Driver Development -- **Writing Your First Driver** - Creating a simple kernel module -- **Working with Device Files** - Device file creation and management -- **Reading and Writing to Devices** - Implementing read/write operations -- **Handling Input and Output Efficiently** - Optimizing I/O operations +* Chapter 1, *Introduction: From Curiosity to Contribution*, has no companion files. +* `part-01/ch02-setting-up-your-lab/` — preparing the FreeBSD lab system, with starter configuration files and the first hello-world module. +* `part-01/ch03-a-gentle-introduction-to-unix/` — UNIX fundamentals, shell scripting, automation, and portability examples used throughout the book. +* `part-01/ch04-a-first-look-at-the-c-programming-language/` — early C exercises, multi-file programs, a driver-skeleton lab, and crash and memory labs. +* `part-01/ch05-understanding-c-for-freebsd-kernel-programming/` — kernel-oriented C demos and a series of safety-focused labs (memory, echo, logging, error handling). +* `part-01/ch06-the-anatomy-of-a-freebsd-driver/` — the first end-to-end module skeletons, common driver patterns, and supporting scripts. + +### Part 2: Building Your First Driver + +* `part-02/ch07-writing-your-first-driver/` — staged construction of the first Newbus pseudo-device (`stage0-scaffold`, `stage1-newbus`, `stage2-final`) plus labs and helper scripts. +* `part-02/ch08-working-with-device-files/` — staged refinements of `/dev` node creation (structured names, aliases, per-handle state, multiple nodes, safe destroy with drain), with `devfs` and `jail` materials and a userland tester. +* `part-02/ch09-reading-and-writing/` — staged read and write implementations (static message, generic `read`/`write`, echo) and a matching userland program. +* `part-02/ch10-handling-io-efficiently/` — circular buffers, blocking I/O, a `poll(2)` refactor, and an `mmap(2)` stage, with userland helpers including a circular-buffer tester. ### Part 3: Concurrency and Synchronization -- **Concurrency in Drivers** - Managing concurrent operations -- **Synchronization Mechanisms** - Implementing proper synchronization -- **Timers and Delayed Work** - Time-based operations and delayed execution -- **Taskqueues and Deferred Work** - Using taskqueues for deferred processing -- **More Synchronization — Conditions, Semaphores, and Coordination** - Advanced synchronization techniques + +* `part-03/ch11-concurrency/` — race demonstrations, concurrent-safe versions, and `KASSERT`-instrumented variants, with a userland exerciser. +* `part-03/ch12-synchronization-mechanisms/` — condition variables, bounded reads, `sx` lock based configuration, and a final converged module. +* `part-03/ch13-timers-and-delayed-work/` — heartbeat, watchdog, tick-source, and final variants of a timer-driven driver. +* `part-03/ch14-taskqueues-and-deferred-work/` — first task, private taskqueue, coalescing, and final stages, with a `labs/` folder. +* `part-03/ch15-more-synchronization/` — semaphores for writers, a stats cache, interruptible waits, and a final consolidated example. ### Part 4: Hardware and Platform-Level Integration -- **Accessing Hardware** - Direct hardware access techniques -- **Simulating Hardware** - Creating virtual hardware for testing -- **Writing a PCI Driver** - Developing drivers for PCI and PCIe devices -- **Handling Interrupts** - Basic interrupt handling implementation -- **Advanced Interrupt Handling** - Sophisticated interrupt techniques -- **DMA and High-Speed Data Transfer** - Direct Memory Access implementation -- **Power Management** - Power management features in drivers + +* `part-04/ch16-accessing-hardware/` — register-map, `bus_space(9)`, synchronized, and final stages, plus a standalone hardware simulator (`hwsim-standalone/`) and labs. +* `part-04/ch17-simulating-hardware/` — backend, integration, timing, faults, and final stages of a richer simulator (`hwsim2-standalone/`) and labs. +* `part-04/ch18-writing-pci-driver/` — probe, BAR mapping, integrated, and final stages for a PCI driver, with labs. +* `part-04/ch19-handling-interrupts/` — registration, handler, simulation, and final stages of an interrupt-driven driver. +* `part-04/ch20-advanced-interrupts/` — single MSI, multi-vector MSI, MSI-X, and final stages. +* `part-04/ch21-dma/` — allocation, polling, interrupt-driven, and final stages of a DMA-capable driver. +* `part-04/ch22-power/` — skeleton, quiesce, restore, and final stages of a power-management aware driver. ### Part 5: Debugging, Tools, and Real-World Practices -- **Debugging and Tracing** - Tools and techniques for debugging drivers -- **Integrating with the Kernel** - Best practices for kernel integration -- **Advanced Topics and Practical Tips** - Advanced techniques and practical advice + +* `part-05/ch23-debug/` — logging, SDT probes, and refactor stages, plus debugging labs. +* `part-05/ch24-integration/` — `devfs` integration, `ioctl(2)`, and `sysctl(9)` stages, plus integration labs. +* `part-05/ch25-advanced/` — ten focused labs covering log floods, errno audits, tunable reboots, failure injection, shutdown handlers, multi-cycle stress runs, capability negotiation, sysctl validation, log audits, and a compatibility matrix. ### Part 6: Writing Transport-Specific Drivers -- **USB and Serial Drivers** - Developing drivers for USB and serial devices -- **Working with Storage Devices and the VFS Layer** - Storage device drivers and VFS integration -- **Writing a Network Driver** - Network interface driver development + +* `part-06/ch26-usb-serial/` — nine USB and serial labs, from exploring the USB stack to a `ucom` skeleton and TTY troubleshooting, with a `shared/` folder for environment checks. +* `part-06/ch27-storage-vfs/` — twelve labs covering `geom(4)` exploration, a storage skeleton, BIO handling, UFS mount, persistence, safe unmount, DTrace, and stress testing, plus ten challenge exercises building toward an `mdconfig`-like tool. +* `part-06/ch28-network-driver/` — seven labs from skeleton to BPF and detach handling, plus six challenges including iperf3, sysctls, and netgraph. ### Part 7: Mastery Topics: Special Scenarios and Edge Cases -- **Portability and Driver Abstraction** - Creating portable drivers across architectures -- **Virtualisation and Containerization** - Driver development for virtualized environments -- **Security Best Practices** - Implementing security measures in drivers -- **Device Tree and Embedded Development** - Driver development for embedded systems -- **Performance Tuning and Profiling** - Optimizing driver performance -- **Advanced Debugging Techniques** - Sophisticated debugging methods -- **Asynchronous I/O and Event Handling** - Asynchronous operations and event-driven architectures -- **Creating Drivers Without Documentation (Reverse Engineering)** - Developing drivers without documentation -- **Submitting Your Driver to the FreeBSD Project** - Contributing drivers to FreeBSD -- **Final Thoughts and Next Steps** - Concluding guidance and continued learning -## Contributing +* `part-07/ch29-portability/` — twelve labs evolving a driver from a monolithic implementation through accessor abstractions, backend split, simulation, conditional compilation, endianness handling, a portability matrix, userland testing, sysctls, runtime detection, and CI, ending in a final consolidated build. +* `part-07/ch30-virtualisation/` — labs for hypervisor detection, jail device handling, VNET, PCI passthrough, plus a `vtedu/` virtio-style educational driver and a `shared/` folder. +* `part-07/ch31-security/` — paired unsafe and fixed labs covering bounds checking, information leaks, privilege handling, rate limiting, detach safety, and secure design. +* `part-07/ch32-fdt-embedded/` — FDT hello-world, overlays, debugging a broken tree, and two `edled` driver variants, with a shared support folder. +* `part-07/ch33-performance/` — performance counters, DTrace scripts, `pmcstat`, cache-aligned data, interrupt taskqueue handoff, and a final v2.3 consolidated build. +* `part-07/ch34-advanced-debugging/` — `KASSERT`, `kgdb`, debug kernel, tracing, `memguard`, remote `gdb`, and a `lab-challenges/` folder. +* `part-07/ch35-async-io/` — synchronous baseline, `poll(2)`, `kqueue(2)`, `SIGIO`, an event queue, a v2.5 async build, and a stress test. +* `part-07/ch36-reverse-engineering/` — identification, capture, register-map building, mock device construction, safe wrapper, pseudo-datasheet authoring, plus open-ended challenges and a `exercise-your-own/` folder. +* `part-07/ch37-upstream/` — a sample driver and sample man page suitable as templates when preparing a contribution, plus helper scripts. +* `part-07/ch38-final-thoughts/` — a template driver, project templates, and closing scripts to seed your own work after the book. -If you find issues with any examples or want to contribute improvements: +### Appendices -1. **Test the example** on your FreeBSD system -2. **Document any issues** you encounter -3. **Submit improvements** via pull request -4. **Follow the coding standards** used in the book +* `appendices/appendix-a-freebsd-kernel-api-reference/` — kernel API reference material with `cheatsheets/` and `scripts/`. +* `appendices/appendix-b-algorithms-and-logic-for-systems-programming/` — algorithm and data-structure cheatsheets relevant to driver work. +* `appendices/appendix-c-hardware-concepts-for-driver-developers/` — hardware-side cheatsheets used when reading datasheets and reasoning about buses, registers, and timing. +* `appendices/appendix-d-operating-system-concepts/` — operating-system concept cheatsheets that complement the kernel material in the main chapters. +* `appendices/appendix-e-navigating-freebsd-kernel-internals/` — cheatsheets for moving around the FreeBSD source tree, finding subsystems, and reading kernel code effectively. +* `appendices/appendix-f-benchmarks/` — benchmark harness and results, organized by area: `dtrace/`, `iflib/`, `sync/`, and `timecounter/`. ## Version Compatibility -These examples are designed for: -- **FreeBSD 14.x** and later -- **x86_64** and **ARM64** architectures -- **GCC** and **Clang** compilers +The companion files target: + +* **FreeBSD 14.3** as the primary reference release. Most examples build and load unchanged on FreeBSD 14.x, and many work on later releases without modification. +* **amd64** as the primary architecture, with several chapters in Part 7 also exercised on **arm64** for portability and FDT material. +* The base toolchain shipped with FreeBSD (Clang and `bmake`). ## Troubleshooting -### Common Issues +The most common issues, and where to look first: -1. **Build errors**: Ensure you have the correct kernel headers installed -2. **Module loading failures**: Check kernel messages with `dmesg` -3. **Permission errors**: Use `sudo` for kernel module operations -4. **Architecture mismatches**: Verify you're building for the correct architecture +1. **Build errors** usually mean the kernel source is not present at `/usr/src/` or does not match the running kernel. Reinstall the matching `src.txz` for your release. +2. **Module load failures** are best diagnosed with `dmesg | tail` immediately after the failed `kldload`. The driver almost always logs why it refused to attach. +3. **Permission errors** mean you are not running `kldload`, `kldunload`, or `sysctl` writes as root. Use `sudo` or work in a dedicated lab VM. +4. **Architecture mismatches** appear when a module was built on a different host. Rebuild from the same source tree as the running kernel. -### Getting Help +For deeper guidance, read the troubleshooting sections in Chapter 23 (*Debugging and Tracing*) and Chapter 34 (*Advanced Debugging Techniques*). -- Check the specific example's README for detailed instructions -- Review the book chapter for theoretical background -- Consult FreeBSD documentation and man pages -- Check kernel messages: `dmesg | tail` +## Contributing + +If you spot a problem with an example, or you would like to suggest an improvement: + +1. Reproduce the issue on a clean FreeBSD lab system using the same release the book targets. +2. Capture the relevant output, such as `dmesg`, `kldstat`, build logs, or DTrace traces. +3. Open an issue or pull request describing what you observed, what you expected, and the exact steps to reproduce it. +4. Keep changes consistent with the chapter's didactic intent. The companion files exist to support the prose, not to evolve independently of it. ## License -These examples are provided under the same license as the FreeBSD Device Driver Book. See the main project LICENSE file for details. +The companion files are distributed under the same license as the main project. See the top-level `LICENSE` file for the full terms. --- -**Note**: These examples are for educational purposes. Always test thoroughly before using in production environments. +These files are intended for learning and lab work on a dedicated FreeBSD system. Always test in a virtual machine or other isolated environment before running unfamiliar driver code on hardware you care about. diff --git a/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/kernel-api-cheatsheet.md b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/kernel-api-cheatsheet.md new file mode 100644 index 0000000..4780c62 --- /dev/null +++ b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/kernel-api-cheatsheet.md @@ -0,0 +1,117 @@ +# FreeBSD Kernel API Cheatsheet + +A one-page companion to Appendix A. Groups the APIs that a driver +reaches for most often, with just enough detail to scan quickly. + +## Memory Allocation + +| API | When to use | Header | +| :---------------- | :---------------------------------------- | :-------------------- | +| `malloc(9)` | General-purpose byte buffers | `sys/malloc.h` | +| `uma(9)` | High-frequency fixed-size objects | `vm/uma.h` | +| `contigmalloc(9)` | Physically contiguous DMA buffer | `sys/malloc.h` | + +Allocation flags: `M_WAITOK` (may sleep), `M_NOWAIT` (must check NULL), +`M_ZERO` (zero on allocation), `M_NODUMP` (exclude from crash dump). + +## Synchronisation + +| API | Problem it solves | +| :--------------- | :-------------------------------------------------- | +| `mtx(9)` default | Short, non-sleeping critical section | +| `mtx(9)` spin | Interrupt filter context, no sleeping allowed | +| `sx(9)` | Reader-writer lock, critical section may sleep | +| `rmlock(9)` | Many readers, rare writers, readers do not sleep | +| `cv(9)` | Named wait channel; use with a mutex | +| `sema(9)` | Counting semaphore for producer-consumer pools | +| `atomic(9)` | Single-word read-modify-write | +| `epoch(9)` | Lock-free reader path for read-mostly data | + +Discipline reminders: +- Never sleep while holding a non-sleepable mutex. +- Pair every `*_init` with a `*_destroy`. +- Document lock order at the top of the file. +- `WITNESS` warnings are bugs. + +## Deferred Execution and Timers + +| API | Purpose | +| :------------- | :--------------------------------------------------- | +| `callout(9)` | Schedule a function to fire after a delay | +| `taskqueue(9)` | Defer sleepable work to a worker thread | +| `kthread(9)` | Dedicated kernel thread (heavyweight, rarely used) | + +Rule of thumb: callout for timers, taskqueue for deferred work that may +sleep, kthread only for genuinely long-running loops. + +## Bus and Resource Management + +| API | Purpose | +| :-------------- | :------------------------------------------------------ | +| Newbus macros | Register the driver, methods, and module metadata | +| `rman(9)` | Allocate and release resources (MMIO, ports, IRQ) | +| `bus_space(9)` | Portable MMIO and port register access | +| `bus_dma(9)` | Portable DMA with tags, maps, and sync operations | +| `bus_setup_intr`| Attach an interrupt filter or handler | + +Resource rule: free in reverse order of allocation. Tear down interrupts +before releasing the IRQ resource. + +## Device Nodes and I/O + +| API | Purpose | +| :---------------------- | :---------------------------------------------- | +| `make_dev_s(9)` | Create a `/dev/` node | +| `destroy_dev(9)` | Destroy a `/dev/` node | +| `struct cdevsw` | Declare character-device entry points | +| `d_ioctl` | Out-of-band commands from userland | +| `devfs_set_cdevpriv(9)` | Attach per-open state to a descriptor | + +Entry-point signatures live in `sys/conf.h`. Always set `d_version = +D_VERSION`. + +## User-Space Interaction + +| API | Purpose | +| :------------------ | :------------------------------------------------- | +| `copyin(9)` | Copy a user buffer into kernel memory | +| `copyout(9)` | Copy a kernel buffer out to user memory | +| `copyinstr(9)` | Copy a null-terminated user string | +| `uiomove(9)` | Move bytes through a `struct uio` | +| `priv_check(9)` | Check a privilege credential | + +All of these may sleep. Do not call them under a non-sleepable lock. + +## Observability and Notification + +| API | Purpose | +| :--------------- | :---------------------------------------------------- | +| `sysctl(9)` | Publish configurable or observable state | +| `eventhandler(9)`| Subscribe to kernel-wide events | +| `d_poll` | Support `poll(2)` waiting | +| `d_kqfilter` | Support `kqueue(2)` waiting | +| `selrecord(9)` | Register a waiter in a `struct selinfo` | + +`poll(2)` and `kqueue(2)` both depend on correct `selwakeup` and `knote` +invocations. Keep them outside mutex-held regions that could cause +lock-order inversions. + +## Diagnostics + +| API | Purpose | +| :----------------- | :------------------------------------------------- | +| `device_printf(9)` | Log a message with device name prefix | +| `log(9)` | Write a prioritised message to the kernel log | +| `KASSERT(9)` | Enforce an invariant when `INVARIANTS` is set | +| `WITNESS` | Lock-order verifier (kernel option) | +| `ktr(9)` | Ring-buffer trace events (`CTR0`..`CTR6`) | +| `SDT(9)` | Static DTrace probe points | + +## Quick Reminders + +- Always tag memory allocations with a `malloc_type`. +- Prefer `make_dev_s` to `make_dev`. +- Prefer `taskqueue(9)` to `kthread(9)` unless you need a persistent thread. +- The manual pages in section 9 are the authoritative reference. +- `dmesg`, `vmstat -m`, `sysctl -a`, and `dtrace(1)` are your friends during + debugging. diff --git a/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/lifecycle-index.md b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/lifecycle-index.md new file mode 100644 index 0000000..b038af4 --- /dev/null +++ b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/lifecycle-index.md @@ -0,0 +1,70 @@ +# APIs by Driver Lifecycle Phase + +A reverse index to Appendix A. When you are writing or auditing a +particular phase of a driver, these are the APIs that usually belong +there. + +## Module load + +- `MODULE_VERSION`, `MODULE_DEPEND` +- Static `MALLOC_DEFINE` +- Static `SYSCTL_NODE` +- `SDT_PROVIDER_DEFINE` +- One-time event-handler registration + +## Probe + +- `device_get_parent`, `device_get_nameunit` +- Match-scoring return values: `BUS_PROBE_DEFAULT`, `BUS_PROBE_GENERIC`, + `BUS_PROBE_SPECIFIC`, `BUS_PROBE_LOW_PRIORITY`, `ENXIO` + +## Attach + +- `device_get_softc` +- `malloc` and `MALLOC_DEFINE` tags +- `mtx_init`, `sx_init`, `rm_init`, `cv_init`, `sema_init` +- `bus_alloc_resource` or `bus_alloc_resource_any` +- `bus_space` setup through `rman_get_bustag` and `rman_get_bushandle` +- `bus_dma_tag_create`, `bus_dmamap_create` +- `callout_init`, `TASK_INIT`, `taskqueue_create` when needed +- `bus_setup_intr` (as the last attach step) +- `make_dev_s` +- `device_get_sysctl_ctx`, `SYSCTL_ADD_*` +- `uma_zcreate` +- Driver-specific event-handler registration + +## Normal operation + +- `d_open`, `d_close`, `d_read`, `d_write`, `d_ioctl`, `d_poll`, `d_kqfilter` +- `uiomove`, `copyin`, `copyout`, `copyinstr` +- `bus_space_read_N`, `bus_space_write_N`, `bus_space_barrier` +- `bus_dmamap_load`, `bus_dmamap_sync`, `bus_dmamap_unload` +- `mtx_lock`, `mtx_unlock`, `sx_slock`, `sx_xlock` +- `cv_wait`, `cv_signal`, `cv_broadcast` +- `atomic_*` +- `callout_reset`, `taskqueue_enqueue` +- `device_printf`, `log`, `KASSERT`, `SDT_PROBE` + +## Detach (reverse of attach) + +- `bus_teardown_intr` (first) +- `destroy_dev` +- `callout_drain` +- `taskqueue_drain_all` and `taskqueue_free` for private queues +- `bus_dmamap_unload`, `bus_dmamap_destroy`, `bus_dma_tag_destroy` +- `bus_release_resource` for every resource from attach +- `cv_destroy`, `sx_destroy`, `mtx_destroy`, `rm_destroy`, `sema_destroy` +- `uma_zdestroy` +- Driver-specific event-handler deregistration +- Final `free` and `contigfree` + +## Module unload + +- Refuse unload if state remains (Newbus usually handles this for you) +- Static resources declared at module load clean themselves up + +## Print this page + +This index is intentionally short. Keep it next to your monitor, or +export it to a single-page PDF. It should fit on one printed page in +almost any font. diff --git a/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/manpage-checklist.md b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/manpage-checklist.md new file mode 100644 index 0000000..230df17 --- /dev/null +++ b/examples/appendices/appendix-a-freebsd-kernel-api-reference/cheatsheets/manpage-checklist.md @@ -0,0 +1,99 @@ +# Manual-Page Checklist for Driver Writers + +A list of the section 9 manual pages that every FreeBSD driver author +should be comfortable opening. Each line is a page, not a command; run +`man 9 ` to read it. + +You do not need to memorise these. You need to know that they exist, so +that you can open the right one the moment you need it. + +## Memory + +- `malloc` +- `contigmalloc` + +## Synchronisation + +- `mutex` +- `mtx_pool` +- `sx` +- `rmlock` +- `condvar` +- `sema` +- `atomic` +- `epoch` +- `lock` +- `locking` + +## Deferred execution + +- `callout` +- `taskqueue` +- `kthread` +- `kproc` + +## Bus and resources + +- `bus_space` +- `bus_dma` +- `rman` +- `bus_alloc_resource` +- `bus_release_resource` +- `bus_activate_resource` +- `BUS_SETUP_INTR` +- `device` +- `device_get_softc` +- `device_printf` +- `devclass` +- `DEVICE_PROBE` +- `DEVICE_ATTACH` +- `DEVICE_DETACH` + +## Module declaration + +- `module` +- `DRIVER_MODULE` +- `MODULE_VERSION` +- `MODULE_DEPEND` +- `DEV_MODULE` + +## Device nodes + +- `make_dev` +- `dev_clone` +- `devfs_set_cdevpriv` +- `dev_refthread` + +## User-space interaction + +- `copy` +- `fetch` +- `store` +- `uio` +- `priv` + +## Observability + +- `sysctl` +- `sysctl_add_oid` +- `sysctl_ctx_init` +- `EVENTHANDLER` +- `selrecord` +- `kqueue` + +## Diagnostics + +- `printf` +- `KASSERT` +- `ktr` +- `SDT` + +## How to learn one manual page a day + +Reading one manual page per working day is a realistic pace. Over +roughly two months, you will have made the full pass above. Start with +the families you already use, then broaden outward. + +The manual pages on FreeBSD are intentionally short and focused. +Reading them is often faster than searching the web, and the results +are always up to date with your installed kernel. diff --git a/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-api-grep b/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-api-grep new file mode 100755 index 0000000..0e40086 --- /dev/null +++ b/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-api-grep @@ -0,0 +1,76 @@ +#!/bin/sh +# +# fdd-api-grep: search the FreeBSD source tree for uses of a kernel API, +# restricted to places where drivers are most likely to show realistic +# patterns. +# +# Companion to Appendix A of "FreeBSD Device Drivers: From First Steps +# to Kernel Mastery". +# +# Usage: +# fdd-api-grep +# +# The script greps for the name under the directories listed in +# SEARCH_PATHS, relative to $FDD_SRC or /usr/src if unset. It limits +# output to C source and header files to keep results readable. +# +# Examples: +# fdd-api-grep bus_space_write_4 +# fdd-api-grep make_dev_s +# fdd-api-grep EVENTHANDLER_INVOKE +# +# Environment: +# FDD_SRC root of the FreeBSD source tree (default: /usr/src) + +set -eu + +if [ $# -ne 1 ]; then + printf 'usage: %s \n' "$(basename "$0")" >&2 + exit 64 +fi + +pattern=$1 +root=${FDD_SRC:-/usr/src} + +if [ ! -d "$root/sys" ]; then + printf '%s: cannot find sys/ under %s\n' \ + "$(basename "$0")" "$root" >&2 + printf 'Set FDD_SRC to the root of your FreeBSD source tree.\n' >&2 + exit 66 +fi + +# Directories most likely to show realistic driver-side usage. +SEARCH_PATHS=" + $root/sys/dev + $root/sys/net + $root/sys/cam + $root/sys/kern + $root/sys/vm + $root/sys/sys +" + +found=0 +for dir in $SEARCH_PATHS; do + if [ -d "$dir" ]; then + found=1 + break + fi +done + +if [ $found -eq 0 ]; then + printf '%s: none of the expected subdirectories exist under %s\n' \ + "$(basename "$0")" "$root" >&2 + exit 66 +fi + +# Use grep with --include to restrict output. Fall back gracefully if +# the system grep lacks those flags (rare on modern FreeBSD). +if grep --version 2>/dev/null | grep -q 'GNU'; then + grep -rn --include='*.[ch]' "$pattern" $SEARCH_PATHS 2>/dev/null +else + for dir in $SEARCH_PATHS; do + [ -d "$dir" ] || continue + find "$dir" \( -name '*.c' -o -name '*.h' \) \ + -exec grep -Hn "$pattern" {} + + done +fi diff --git a/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-manpage b/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-manpage new file mode 100755 index 0000000..15f0d1e --- /dev/null +++ b/examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-manpage @@ -0,0 +1,106 @@ +#!/bin/sh +# +# fdd-manpage: open the right section 9 manual page for a FreeBSD kernel API, +# with a small mapping from common shorthand names to their canonical pages. +# +# Companion to Appendix A of "FreeBSD Device Drivers: From First Steps +# to Kernel Mastery". +# +# Usage: +# fdd-manpage +# +# Examples: +# fdd-manpage mtx -> man 9 mutex +# fdd-manpage bus_space -> man 9 bus_space +# fdd-manpage uiomove -> man 9 uio +# fdd-manpage make_dev_s -> man 9 make_dev + +set -eu + +if [ $# -ne 1 ]; then + printf 'usage: %s \n' "$(basename "$0")" >&2 + exit 64 +fi + +name=$1 + +# Short names or alternate spellings that do not match a manual page +# one-to-one. Add new mappings here as the appendix grows. +case "$name" in + mtx|mtx_init|mtx_lock|mtx_unlock|mtx_destroy|mtx_assert) + page="mutex" ;; + cv|cv_init|cv_wait|cv_signal|cv_broadcast|cv_destroy) + page="condvar" ;; + uiomove|uio_read|uio_write) + page="uio" ;; + copyin|copyout|copyinstr) + page="copy" ;; + fueword|fuword|subyte|suword) + page="fetch" ;; + make_dev|make_dev_s|destroy_dev) + page="make_dev" ;; + sysctl_handle_int|sysctl_handle_long|sysctl_handle_string) + page="sysctl" ;; + SYSCTL_ADD_NODE|SYSCTL_ADD_INT|SYSCTL_ADD_PROC) + page="sysctl_add_oid" ;; + SYSCTL_NODE|SYSCTL_INT|SYSCTL_LONG|SYSCTL_STRING|SYSCTL_PROC) + page="sysctl" ;; + TASK_INIT|taskqueue_create|taskqueue_enqueue|taskqueue_drain) + page="taskqueue" ;; + callout_init|callout_reset|callout_stop|callout_drain) + page="callout" ;; + rm_init|rm_rlock|rm_wlock|rm_destroy) + page="rmlock" ;; + sx_init|sx_slock|sx_xlock|sx_destroy) + page="sx" ;; + atomic_*|atomic) + page="atomic" ;; + epoch_alloc|epoch_enter|epoch_exit|epoch_wait) + page="epoch" ;; + bus_space_read_1|bus_space_read_2|bus_space_read_4|bus_space_read_8) + page="bus_space" ;; + bus_space_write_1|bus_space_write_2|bus_space_write_4|bus_space_write_8) + page="bus_space" ;; + bus_space_barrier) + page="bus_space" ;; + bus_dma_tag_create|bus_dmamap_create|bus_dmamap_load|bus_dmamap_sync|bus_dmamap_unload) + page="bus_dma" ;; + bus_dmamem_alloc|bus_dmamem_free|bus_dma_tag_destroy|bus_dmamap_destroy) + page="bus_dma" ;; + bus_setup_intr|bus_teardown_intr) + page="BUS_SETUP_INTR" ;; + bus_alloc_resource|bus_alloc_resource_any) + page="bus_alloc_resource" ;; + bus_release_resource) + page="bus_release_resource" ;; + rman_get_start|rman_get_end|rman_get_size|rman_get_bustag|rman_get_bushandle) + page="rman" ;; + MALLOC_DEFINE|MALLOC_DECLARE|free|realloc) + page="malloc" ;; + contigfree) + page="contigmalloc" ;; + DEVMETHOD|DEVMETHOD_END|device_method_t) + page="DRIVER_MODULE" ;; + device_get_softc|device_get_parent|device_get_unit|device_get_nameunit) + page="device" ;; + device_printf) + page="device_printf" ;; + selrecord|selwakeup|selinfo) + page="selrecord" ;; + knote|knlist_init|knlist_add|knlist_remove) + page="kqueue" ;; + EVENTHANDLER_DECLARE|EVENTHANDLER_REGISTER|EVENTHANDLER_DEREGISTER|EVENTHANDLER_INVOKE) + page="EVENTHANDLER" ;; + CTR0|CTR1|CTR2|CTR3|CTR4|CTR5|CTR6) + page="ktr" ;; + SDT_PROVIDER_DEFINE|SDT_PROVIDER_DECLARE|SDT_PROBE|SDT_PROBE_DEFINE) + page="SDT" ;; + MPASS|CTASSERT) + page="KASSERT" ;; + priv_check|priv_check_cred) + page="priv" ;; + *) + page="$name" ;; +esac + +exec man 9 "$page" diff --git a/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/concurrency-decision-aid.md b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/concurrency-decision-aid.md new file mode 100644 index 0000000..35cbac4 --- /dev/null +++ b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/concurrency-decision-aid.md @@ -0,0 +1,138 @@ +# Concurrency-Pattern Decision Aid + +A decision aid for picking the right concurrency pattern. It does not +replace the chapters on locking and synchronisation; it helps you frame +the problem before you open them. + +## Step 1: Identify the shape of the problem + +Answer these questions in order. The first "yes" usually picks your +pattern. + +- **Is this a short critical section, no sleeping?** + -> `mtx(9)` with `MTX_DEF`. + +- **Is this inside a filter interrupt handler (`INTR_FILTER`)?** + -> `mtx(9)` with `MTX_SPIN`. + +- **Is there one thread that produces, one that consumes, with + blocking on empty or full?** + -> mutex plus condition variable (`cv(9)`), or a ring plus a + wakeup primitive. + +- **Does the workload have many readers and an occasional writer, and + readers may sleep (call `malloc`, copyin, etc.) while holding the + lock?** + -> `sx(9)`. + +- **Does the workload have many readers and a rare writer, and readers + must not sleep?** + -> `rmlock(9)`. + +- **Is the object owned by several parties and you do not know which + one will release it last?** + -> `refcount(9)`. + +- **Is the resource a pool of N identical slots?** + -> `sema(9)`. + +- **Is the state a single word (flag, counter) and every access is + trivial?** + -> `atomic(9)`. + +If two answers both apply, the higher-level pattern usually wins. A +reference-counted object still uses a mutex to serialise field +updates; a `cv` is built on top of a mutex. + +## Step 2: Check the constraints + +Some patterns exclude others. Use this table to catch conflicts early. + +| If you are in... | You cannot... | +| :-------------------------- | :------------------------------------- | +| A filter interrupt | Sleep, acquire a sleepable lock | +| Holding a spin mutex | Sleep, acquire `sx`, `rmlock`, sema | +| Holding a sleepable mutex | Acquire a spin mutex out of order | +| Holding any lock | Call an unrelated user-supplied cb | +| A callout or taskqueue item | Assume caller's lock is still held | + +## Step 3: Producer-consumer variants + +If you answered "producer/consumer" in Step 1, pick the variant. + +| Variant | Primitive | +| :--------------------------------------- | :---------------------------- | +| One producer, one consumer, fixed-size | SPSC ring, no lock | +| One producer, many consumers | `buf_ring(9)` in MPSC mode | +| Many producers, one consumer | `buf_ring(9)` in MPMC mode | +| Blocking consumer, non-interrupt producer| mutex + `cv(9)` | +| Interrupt producer, thread consumer | SPSC ring + wakeup | +| Select/poll/kqueue exposure | Ring + `selrecord`/`KNOTE` | + +## Step 4: Shared ownership variants + +If you answered "reference count" in Step 1, confirm the model. + +- [ ] The object is allocated once and may be destroyed multiple + places. +- [ ] Every acquire has a paired release. +- [ ] The release function frees the object when the count drops to + zero. +- [ ] The initial count is 1 on allocation; the creator holds the + first reference. +- [ ] No code loads, inspects, then acquires. Code uses + `refcount_acquire_if_gt()` when the acquire is conditional. +- [ ] Reads of the count for logging or statistics use + `refcount_load()`, not a raw load. + +## Step 5: Read-mostly variants + +If readers dominate, decide between `sx` and `rmlock`. + +- `sx(9)` if readers may sleep, writers are not extremely rare, or + the lock is not in the hottest path. +- `rmlock(9)` if readers must not sleep, writers are rare, and the + hot path is on the read side. + +Do not use `rmlock(9)` as a default read-mostly lock. Its writer +cost is higher than `sx(9)`'s, and the contract forbids sleeping in +readers. Use it when the profile actually shows it is warranted. + +## Step 6: Validate the choice + +Once you have picked a pattern, sanity-check it against these +questions. + +- [ ] Every code path that reaches the shared state acquires the + lock I picked. +- [ ] The lock discipline is documented at the top of the file (which + lock protects which fields). +- [ ] The locking order with other locks in the driver is documented + and consistent. +- [ ] Holding the lock does not cause a call into code that expects + not to be called under a lock of that type. +- [ ] Tests or runtime checks exist (WITNESS, INVARIANTS) to catch + violations during development. + +## Common mistakes + +- Using `mtx(9)` when a sleepable lock is needed because a path under + the lock calls `malloc(M_WAITOK)` or `copyin`. +- Using `sx(9)` when a spin mutex would suffice, adding needless + context switches. +- Using `rmlock(9)` by default because "reads dominate"; overpaying + on the write side without measurement. +- Holding a lock across a wakeup, or releasing it and then expecting + a wakeup to reach the waiter (race window). +- Mixing `refcount_acquire` and raw pointer copies; only one lineage + of references is tracked. +- Using `atomic(9)` ops on several fields that together are a + logical invariant; you need a lock, not atomics. + +## Cross-references + +- Appendix B, section **Concurrency Patterns**. +- Chapter 11, for `atomic(9)`, `mtx(9)`, `MTX_SPIN` vs `MTX_DEF`. +- Chapter 12, for `sx(9)`, `cv(9)`, and blocking primitives. +- `locking(9)` for the kernel locking overview. +- `refcount(9)`, `rmlock(9)`, `sx(9)`, `sema(9)` for the specifics. diff --git a/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/data-structure-cheatsheet.md b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/data-structure-cheatsheet.md new file mode 100644 index 0000000..92c5e64 --- /dev/null +++ b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/data-structure-cheatsheet.md @@ -0,0 +1,88 @@ +# Data-Structure Comparison Cheatsheet + +Quick reference for choosing a collection in kernel or driver code. +Full teaching lives in Appendix B. This sheet only helps you pick. + +## The question to ask first + +What is the *dominant access pattern* for this collection? Not the +average one, not the most common bug report, the one you will do in the +hot path. Most of the wrong choices below come from designing for the +easy access and forgetting the hot one. + +- Will I iterate the whole thing, or look up one element? +- Do I need order (sorted by key), or only presence? +- Do I add and remove from the middle, or only at the ends? +- Is the element set dense (all values from 0..N taken) or sparse? +- Do I need arbitrary removal from a cursor that is already in hand? + +## Families at a glance + +| Family | Header | Grows | Ordered? | Lookup | Arbitrary remove | Pointer overhead | +| :-- | :-- | :-- | :-- | :-- | :-- | :-- | +| `SLIST_` | `` | Yes | No | O(n) | Only with prev ptr | 1 next | +| `LIST_` | `` | Yes | No | O(n) | O(1) | 1 next, 1 prev ptr | +| `STAILQ_` | `` | Yes | No (FIFO) | O(n) | Hard in middle | 1 next + tail | +| `TAILQ_` | `` | Yes | No | O(n) | O(1) from node | 2 ptrs + tail | +| `RB_` tree | `` | Yes | By key | O(log n) | O(log n) | Left, right, parent, colour | +| Bit string | `` | Fixed | Dense indices | O(1) test | O(1) clear | 1 bit per slot | +| Hash table | `hashinit(9)` + `LIST_` | Yes | No | ~O(1) avg | O(1) from node | 1 bucket ptr per entry | +| Radix trie | `` | Yes | Prefix | O(key bits) | O(key bits) | Specialised; rarely driver code | + +## Decision hints + +Reach for **`TAILQ_`** by default. It covers most driver needs: +pending requests, per-channel contexts, a list of sub-devices. The +extra pointer compared with `LIST_` is almost never the problem that +sinks a driver. + +Reach for **`STAILQ_`** when the discipline really is first-in, +first-out and you will almost never remove from the middle. The +single-linkage keeps each element one word lighter and encourages the +FIFO invariant. + +Reach for **`LIST_`** when you want cheap O(1) removal from the middle +but do not need a tail pointer. + +Reach for **`SLIST_`** only when you are certain removal from the +middle will not happen (or when memory pressure is extreme). + +Reach for an **RB tree** when the collection will grow past a few +hundred entries and lookups happen on the hot path. If you have a +numeric key you plan to range-scan in order, the RB tree is the +straightforward answer. + +Reach for a **bit string** when the universe of slots is dense and +bounded: tag numbers, interrupt indices, I/O vector positions. + +Reach for a **hash table** when the identifier is large and opaque (a +name, a fd number, a pid), the set is large, and you do not need +ordered iteration. + +Do not reach for **radix tries** unless you are writing networking +code. They exist for IP prefix matching; outside the network stack the +RB tree is almost always the right answer instead. + +## Anti-patterns to avoid + +Do not promote a `TAILQ_` to an RB tree just because the list got +longer than expected. Measure first. A list of 200 entries that is +walked rarely costs less than a tree. + +Do not reinvent ``. Rolling your own list macros makes +the driver harder to review and almost always misses a removal case. + +Do not assume a hash table is faster than a tree. For a few thousand +entries, RB trees with no hashing overhead often win. Hashes shine +when the key domain is huge and lookups are the dominant cost. + +Do not choose by theoretical complexity alone. Locking, cache +behaviour, and how the data flows through the driver matter more than +O-notation. The decision is usually local to the problem. + +## Cross-references + +- Appendix A: kernel API reference for the macro families. +- `queue(3)`, `tree(3)`, `bitstring(3)`, `hashinit(9)`. +- Appendix B, section **Data Structures in the Kernel**, for the full + pattern discussion. diff --git a/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/error-unwinding-checklist.md b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/error-unwinding-checklist.md new file mode 100644 index 0000000..392606d --- /dev/null +++ b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/error-unwinding-checklist.md @@ -0,0 +1,164 @@ +# Error-Unwinding Checklist + +A line-by-line audit list for kernel functions that acquire multiple +resources. Use it when writing a new `attach` routine, reviewing +someone else's probe or ioctl handler, or debugging a leak report. + +## When this checklist applies + +The checklist applies to any function that: + +- acquires two or more resources (locks, memory, bus resources, device + handles, taskqueues, callouts, interrupts), +- can fail partway through, +- must leave the system in its original state on failure. + +The canonical example is `attach`, but the same pattern applies to +`ioctl` handlers, probe-time setup, and any helper that sets up a +non-trivial subsystem. + +## The pattern at a glance + +``` +int +foo_attach(device_t dev) +{ + struct foo_softc *sc = device_get_softc(dev); + int err; + + err = bus_alloc_resource_any(...); + if (err != 0) + goto fail; + + err = bus_setup_intr(...); + if (err != 0) + goto fail_res; + + err = make_dev_s(...); + if (err != 0) + goto fail_intr; + + return (0); + +fail_intr: + bus_teardown_intr(...); +fail_res: + bus_release_resource(...); +fail: + return (err); +} +``` + +The invariant: labels appear in **reverse order** of acquisition. Each +label releases one resource and falls through to the next. + +## The checklist + +### A. Acquisition order + +- [ ] Every resource acquisition is documented by a comment or a + `KASSERT` that names the resource. +- [ ] No two resources are acquired in a single statement that can + fail halfway. +- [ ] Each acquisition either succeeds completely or leaves no state + behind. + +### B. Label naming + +- [ ] Labels are named for the resource they undo (`fail_intr`, + `fail_res`, `fail_mem`), not for line numbers (`fail1`, + `fail2`). +- [ ] Labels are unique within the function. +- [ ] Labels appear in reverse order of acquisition. +- [ ] The last label before the shared return (`fail`, `out`) is used + for "release nothing, just return". + +### C. Ordering of release + +- [ ] Each label releases exactly the resource its name implies. +- [ ] Fall-through from one label to the next is intentional and + required. +- [ ] No label jumps over another label's release. +- [ ] The final return is on the success path, before the label + block. + +### D. Nullability and state + +- [ ] A resource acquired into a pointer is either `NULL`-initialised + or acquired unconditionally before the first `goto` that could + reach its release. +- [ ] A release that can tolerate `NULL` (e.g., `free()`, + `bus_release_resource()` on a saved pointer) is used safely. +- [ ] A release that cannot tolerate `NULL` is protected by an + `if (p != NULL)` check, or by careful ordering. + +### E. Error code + +- [ ] `err` (or the equivalent variable) holds a meaningful error + code at every `goto` site. +- [ ] The return value matches a `/usr/src/sys/sys/errno.h` constant + (not a negative number or a bespoke code). +- [ ] No path reaches the return statement with `err == 0` on the + failure side. + +### F. Locking during unwind + +- [ ] If a lock is held at the time of `goto`, each label that could + be reached while the lock is held releases it correctly. +- [ ] Locks are not double-released. +- [ ] Locks are not required to be held during a specific release; if + they are, the ordering reflects that. + +### G. Roll-back of partial success + +- [ ] Any mid-function state change that becomes visible to other + threads (publishing a pointer, inserting into a list, starting + an interrupt) has an explicit reversal on the unwind path. +- [ ] The reversal is in the correct label, not scattered. +- [ ] If the reversal itself can fail, the function's contract on + that case is documented. + +### H. Diagnostics + +- [ ] Each failure path logs via `device_printf(9)`, `log(9)`, or a + dedicated `counter_u64_t`, enough to diagnose the failure + without reproducing. +- [ ] The log message names the resource and the error code. +- [ ] Logs on the unwind path do not hide the original error. + +### I. Detach matches attach + +- [ ] The corresponding `detach` releases the same resources in the + same reverse order as the last `fail_*` label in `attach`. +- [ ] A successful `attach` followed by a `detach` leaves no leaked + resource. +- [ ] Detach is idempotent with respect to interrupted attach: if + `attach` failed partway, `detach` is not called by the bus. + +### J. Style + +- [ ] The function fits on one screen, or has been broken up because + it does not. +- [ ] The labels are separated from the success path by a visible + blank line. +- [ ] The function follows `style(9)`: four-space indent, labels at + column one, no tabs-after-code. + +## Common mistakes this catches + +- Forgetting to release a resource because it was acquired in a + conditional branch that falls through to the label. +- Releasing in alphabetical order instead of acquisition order, + triggering a use-after-free when one teardown depends on another. +- Returning `0` on a failure path because `err` was overwritten by a + successful intermediate call. +- Holding a mutex across a release that itself can sleep. +- Detaching resources that were never attached when probe failed very + early. + +## Cross-references + +- Appendix B, section **Error-Handling Patterns**. +- Chapter 5, for the teaching introduction to `goto` in kernel C. +- `style(9)` for formatting conventions. +- `errno(2)` for the standard error constants. diff --git a/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/ring-buffer-invariants.md b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/ring-buffer-invariants.md new file mode 100644 index 0000000..3f31e96 --- /dev/null +++ b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/ring-buffer-invariants.md @@ -0,0 +1,117 @@ +# Ring-Buffer Invariants Checklist + +An audit checklist for any circular (ring) buffer you write, review, or +debug. Most ring-buffer bugs are violations of an invariant the author +could have named on paper. Walk the code against this list. + +## 1. Size and indexing + +- [ ] The buffer capacity is a power of two, or the code documents why + it is not. +- [ ] Indices either (a) wrap at capacity by modulo, or (b) run free and + are reduced to a slot with `idx & (cap - 1)`. The choice is + explicit, not mixed. +- [ ] The mask constant matches the capacity (`mask == cap - 1` when + cap is a power of two). +- [ ] No code path compares a raw index with a masked index. + +## 2. Empty and full + +- [ ] The empty condition and the full condition are documented at the + top of the file. +- [ ] If using the **sacrificed-slot** scheme (never use all slots), + `full == ((head + 1) & mask) == tail`. +- [ ] If using **free-running** indices, `empty == (head == tail)` and + `full == (head - tail == cap)`. +- [ ] The two are mutually exclusive (never both true at once). + +## 3. Memory ordering + +- [ ] The producer issues a release-style fence or + `atomic_store_rel_*` before publishing the new head. +- [ ] The consumer issues an acquire-style fence or + `atomic_load_acq_*` when reading the published head. +- [ ] The payload write happens *before* the index publication in + program order, and the barrier enforces that order in machine + order. +- [ ] For architectures without TSO assumptions, the barriers are + explicit; there is no hidden dependency on x86 semantics. + +## 4. Single vs multiple producers / consumers + +- [ ] The ring's producer/consumer cardinality is documented in the + file's block comment. +- [ ] SPSC (single producer, single consumer) implementations assume + exactly one thread on each side and do **not** use atomics on the + index other than for fencing. +- [ ] MPMC or MPSC use `buf_ring(9)` or equivalent, not a hand-rolled + SPSC pattern. +- [ ] No third thread touches the indices without a lock. + +## 5. Enqueue and dequeue + +- [ ] Enqueue checks **full** before writing. If full, it returns an + explicit error (`ENOBUFS`, `EAGAIN`), not a silent drop. +- [ ] Enqueue writes the payload first, then the index. +- [ ] Dequeue checks **empty** before reading. If empty, it returns an + explicit error or blocks as the contract specifies. +- [ ] Dequeue reads the payload before advancing the tail that frees + the slot for reuse. +- [ ] No slot is returned to the free pool while another thread could + still be reading it. + +## 6. Notification and wakeup + +- [ ] Waking a consumer happens **after** the enqueue is visible, not + before. +- [ ] The wakeup uses the discipline the consumer expects: `cv_signal` + in the mutex-and-condvar model, `wakeup_one()` for `msleep`, + `selwakeup()` for `select`/`poll`, `KNOTE` for `kqueue`. +- [ ] Missed wakeups are handled: the consumer re-checks the queue + inside the sleep loop (`while`, not `if`). +- [ ] No wakeup happens while holding a spin lock that the sleeper + needs to reacquire. + +## 7. Shutdown and teardown + +- [ ] Detach drains the ring before freeing the buffer. +- [ ] Detach quiesces producers before consumers, or vice versa, + consistently with how the interrupt is stopped. +- [ ] Detach does not free the buffer while a softirq, taskqueue, or + callout could still touch it. +- [ ] The shutdown sequence is documented in the detach function's + comment block. + +## 8. Back-pressure and policy + +- [ ] The driver has a documented policy for the full condition: drop + newest, drop oldest, block, return error. +- [ ] The policy matches the subsystem's expectations (network drivers + drop, block-layer drivers usually queue upstream). +- [ ] Statistics for drops or blockages are exposed via `sysctl(9)` or + a similar interface. +- [ ] The policy is not silently different between the fast path and + the slow path. + +## 9. Visibility and debugging + +- [ ] Current head and tail are inspectable (via a sysctl, a debug + ioctl, or a DB command) without recompiling. +- [ ] The code logs a warning, not a panic, when a drop happens. +- [ ] The invariant checks exist as `KASSERT` statements in DEBUG + builds, but not as runtime costs in production. + +## 10. Documentation + +- [ ] The file comment names the ring's producer and consumer. +- [ ] The file comment names the empty and full conditions. +- [ ] The file comment names the memory-ordering discipline. +- [ ] The file comment cites the chapter or appendix it was derived + from. + +## Cross-references + +- Appendix B, section **Circular and Ring Buffers**. +- Chapter 10, for producer/consumer and interrupt context. +- Chapter 11, for `atomic(9)` and fences. +- `buf_ring(9)` for the generic kernel ring. diff --git a/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/state-machine-worksheet.md b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/state-machine-worksheet.md new file mode 100644 index 0000000..16ac05f --- /dev/null +++ b/examples/appendices/appendix-b-algorithms-and-logic-for-systems-programming/cheatsheets/state-machine-worksheet.md @@ -0,0 +1,149 @@ +# State-Machine Design Worksheet + +Fill this worksheet in **before** you write the state machine. If you +cannot complete it on paper, the code will not be simpler than the +paper. + +## 0. One-line purpose + +Write one sentence describing what this machine controls. + + Purpose: _______________________________________________________ + +A state machine that is hard to describe in one sentence is usually two +state machines wearing the same name. + +## 1. State inventory + +List every state. Each state should be a condition the driver can be +*in*, not an event it has just seen. Use noun-like names +(`CONNECTING`, `IDLE`, `ERROR`), not verb-like ones (`CONNECT`, +`RESET`). + + State 1: _______________________________________________________ + State 2: _______________________________________________________ + State 3: _______________________________________________________ + State 4: _______________________________________________________ + State 5: _______________________________________________________ + +If your list exceeds about eight, consider whether some of them are +actually orthogonal and belong in flag bits instead. + +## 2. Event inventory + +List every event that can drive a transition. Events come from three +common sources: the user (ioctl, open/close), the hardware (interrupt, +completion, timeout), and internal timers or callouts. + + Event 1: _______________________________________________________ + Event 2: _______________________________________________________ + Event 3: _______________________________________________________ + Event 4: _______________________________________________________ + Event 5: _______________________________________________________ + +## 3. Transition table + +For each (state, event) pair, write the next state and the action to +perform. An empty cell means the event is either impossible in that +state or is to be ignored; mark which. + +| State \\ Event | | | | | | +| :------------- | :----: | :----: | :----: | :----: | :----: | +| | | | | | | +| | | | | | | +| | | | | | | +| | | | | | | +| | | | | | | + +Conventions: + +- A cell entry like `CONNECTED / send_ack()` means "transition to + `CONNECTED` and call `send_ack()`". +- A cell entry like `-` means "no change, event ignored". +- A cell entry like `X` means "impossible; log and panic in DEBUG". + +## 4. Initial state + +What state does the machine start in after `attach`? What state does +it end in after successful `detach`? + + Initial state: ________________________________________________ + Terminal state (if any): ______________________________________ + +## 5. Transient states + +A transient state is one the machine enters, performs an action in, +and leaves almost immediately. Transients are a common source of +surprise because the driver spends so little time in them that tests +miss them. + +List your transients and the guarantees they provide. + + Transient 1: __________________________________________________ + Guarantees: _________________________________________________ + Transient 2: __________________________________________________ + Guarantees: _________________________________________________ + +## 6. Locking + +What lock protects the state variable? What actions may be taken while +the lock is held? Which may not? + + State lock: ___________________________________________________ + Held during transition: _______________________________________ + Released before: ______________________________________________ + +Actions performed inside the transition should be fast. Long-running +work belongs in a taskqueue or callout, with the machine advancing +into a "waiting" state until the work completes and posts its event. + +## 7. Error paths + +For each error condition, which state do you enter? Is it a terminal +error (requires a reset) or a recoverable one (returns to `IDLE`)? + + Error 1: ______________________________________________________ + -> state: ___________________________________________________ + -> recoverable? Y / N + Error 2: ______________________________________________________ + -> state: ___________________________________________________ + -> recoverable? Y / N + +## 8. Observability + +How does an operator inspect the current state? (A sysctl is the usual +answer.) How does an operator see recent transitions? (A small ring +buffer of recent (state, event, timestamp) tuples is a common pattern.) + + State visible via: ____________________________________________ + Transition log: _______________________________________________ + +## 9. Representation choice + +Based on the filled-in worksheet, choose how to implement the machine. + +- [ ] `enum` plus `switch`: up to ~6 states, ~6 events, transitions + are obvious. +- [ ] Table-driven with a 2D array: more states, more events, or you + want tests to operate on the table. +- [ ] Function-pointer per state: the action set changes radically + between states, not just which action fires. +- [ ] Flag bits in an integer: what you actually have is not a state + machine but a set of independent booleans. Go back to step 1. + +## 10. Self-check + +- [ ] Every (state, event) cell is filled or explicitly marked + impossible. +- [ ] Every state has at least one incoming and one outgoing + transition (terminal states excepted). +- [ ] Every transient state is reachable and exits. +- [ ] The machine reaches the terminal state from any initial state + via some sequence of events. +- [ ] Locking is consistent across every transition. + +## Cross-references + +- Appendix B, section **State Machines**. +- Chapter 5, for `switch` idioms in kernel C. +- Chapter 10, for event-driven programming in drivers. diff --git a/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/bus-comparison.md b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/bus-comparison.md new file mode 100644 index 0000000..e25be58 --- /dev/null +++ b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/bus-comparison.md @@ -0,0 +1,120 @@ +# Bus Comparison Cheatsheet + +Quick reference for the four buses a driver author is most likely to +meet in FreeBSD: PCI/PCIe, USB, I2C, and SPI. Full teaching lives in +Appendix C and in the dedicated chapters. This sheet only helps you +point at the right mental model fast. + +## The question to ask first + +What role is your driver in this bus? + +- **Register-level driver.** You allocate resources and touch device + registers directly. PCI/PCIe fits here. +- **Framework client.** You describe what you need and let the bus + framework run transactions for you. USB, I2C, and SPI fit here. + +Everything else follows from this distinction. + +## Buses at a glance + +| Aspect | PCI / PCIe | USB | I2C | SPI | +| :-- | :-- | :-- | :-- | :-- | +| Topology | Tree (PCIe switches) | Strict host/hub tree | Multi-drop, addressed | Multi-drop, chip-select | +| Typical speed | GB/s per lane | KB/s to GB/s | 100 kHz - 1 MHz | 1 MHz - tens of MHz | +| Identification | Vendor/Device + class | VID/PID + class/subclass/protocol | 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 | +| FreeBSD parent bus name | `pci` | `uhub` or similar | `iicbus` | `spibus` | +| Main API call | `bus_alloc_resource_any`, `bus_setup_intr` | `usbd_transfer_setup`, `usbd_transfer_start` | `iicbus_transfer` | `spibus_transfer` | +| Manual pages | `pci(4)`, `pci(9)` | `usb(4)`, `usbdi(9)` | `iicbus(4)` | - (see source) | + +## Decision hints + +Reach for **PCI/PCIe** when the device is on a motherboard slot, a +PCIe switch, or an x86 desktop machine's internal fabric. Expect +configuration space, BARs, MSI or MSI-X, and full DMA. + +Reach for **USB** when the device is external, hot-pluggable, or uses +transfer endpoints (control, bulk, interrupt, isochronous). Expect +a framework that runs transactions for you on callback. + +Reach for **I2C** when the peripheral is small, low-bandwidth, and +sits on a two-wire bus with a slave address. Sensors, EEPROMs, PMICs, +small displays. Transfers are short and blocking. + +Reach for **SPI** when the peripheral is slightly faster, has a +chip-select line, and you need full-duplex bit shifting. Expect raw +bytes with meaning defined entirely by the device datasheet. + +## What the driver's top-level shape looks like + +### PCI driver skeleton + +``` +probe: pci_get_vendor() / pci_get_device() match -> BUS_PROBE_DEFAULT +attach: bus_alloc_resource_any(SYS_RES_MEMORY, ...) // BAR + rman_get_bustag() / rman_get_bushandle() // tag/handle + pci_enable_busmaster() if DMA capable + bus_alloc_resource_any(SYS_RES_IRQ, ...) // IRQ + bus_setup_intr(filter, ithread, ...) // handler + bus_dma_tag_create(...) // DMA tag + bus_dmamem_alloc(...) / bus_dmamap_load(...) // DMA buffer +detach: reverse of attach, in exact reverse order +``` + +### USB client skeleton + +``` +match: VID/PID + class/subclass/protocol +attach: usbd_transfer_setup(xfer_config[], ...) // endpoints + usbd_transfer_start(xfer) // begin +callback: process completed transfer, restart if needed +detach: usbd_transfer_drain(), usbd_transfer_unsetup() +``` + +### I2C client skeleton + +``` +probe: FDT / ACPI match on compatible string or hardware ID +attach: record parent iicbus, slave address, callout for periodic work +use: iicbus_transfer(dev, msgs, nmsgs) for each transaction +detach: stop callouts, release softc resources +``` + +### SPI client skeleton + +``` +probe: FDT / ACPI match +attach: record parent spibus, chip-select index +use: spibus_transfer(dev, &cmd) per transaction +detach: release resources +``` + +## Anti-patterns to avoid + +Do not write a USB driver as if it were a PCI driver. Endpoints are +not registers, and transfers are not interrupts. Fight the framework +and you will lose. + +Do not write an I2C or SPI client that busy-waits inside the +transaction. The bus framework already knows how to wait properly. + +Do not skip `pci_enable_busmaster` in a PCI driver that does DMA. The +chip will look alive and move no data. + +Do not copy PCI resource allocation into an I2C or SPI client. There +are no resources to allocate there; the bus already owns the +controller. + +## Cross-references + +- Appendix C, section **Buses and Interfaces**, for the full mental model. +- Chapter 18 for PCI, a later chapter for USB, a later chapter for + I2C, and a later chapter for SPI. +- Real drivers worth reading: + - PCI: `/usr/src/sys/dev/uart/uart_bus_pci.c` + - USB stack: `/usr/src/sys/dev/usb/` + - I2C client: `/usr/src/sys/dev/iicbus/icee.c` + - SPI client: `/usr/src/sys/dev/spibus/spigen.c` diff --git a/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/dma-mental-model-checklist.md b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/dma-mental-model-checklist.md new file mode 100644 index 0000000..67e8cf0 --- /dev/null +++ b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/dma-mental-model-checklist.md @@ -0,0 +1,177 @@ +# DMA Mental-Model Checklist + +Audit a DMA path end to end. Walk this checklist when you are +designing a new DMA-capable driver, reviewing one, or debugging a +transfer that works on one machine and fails on another. Full teaching +lives in Appendix C and in Chapter 21. This sheet only helps you +verify. + +## The question to ask first + +Who touches the buffer, in what direction, and in what order? + +- The CPU writes -> the device reads -> the CPU frees or reuses. +- The device writes -> the CPU reads -> the CPU frees or reuses. +- Round-trip: CPU writes, device reads, device writes, CPU reads. + +Once you can say this out loud for your buffer, the sync calls follow +mechanically. If you cannot say it, stop and draw it on paper first. + +## The five-stage sequence + +Every DMA path in FreeBSD has the same five stages. Every bug lives +somewhere in this diagram. Audit each arrow. + +``` +(1) bus_dma_tag_create(parent, align, boundary, + lowaddr, highaddr, filter, + filterarg, maxsize, nsegments, + maxsegsz, flags, lockfunc, + lockarg, &tag) + | + v +(2) bus_dmamem_alloc(tag, &vaddr, flags, &map) + or + bus_dmamap_create(tag, flags, &map) + load later + | + v +(3) bus_dmamap_load(tag, map, vaddr, length, + callback, arg, flags) + -> callback receives bus_dma_segment_t entries + -> each segment has ds_addr (bus address) and ds_len + | + v +(4) Hand ds_addr values to the device descriptor. + Before the transfer: + bus_dmamap_sync(tag, map, BUS_DMASYNC_PRE...) + After the transfer: + bus_dmamap_sync(tag, map, BUS_DMASYNC_POST...) + | + v +(5) bus_dmamap_unload(tag, map) + bus_dmamem_free(tag, vaddr, map) + bus_dma_tag_destroy(tag) (usually in detach) +``` + +## Stage-by-stage audit + +### Stage 1: Tag + +- [ ] Parent tag is `bus_get_dma_tag(dev)` (inherits platform limits) + unless the device needs a custom parent. +- [ ] Alignment matches the device's actual alignment requirement. +- [ ] Boundary is zero unless the device cannot cross a page-size or + other hardware boundary. +- [ ] `lowaddr` is the highest bus address the device can reach. + `BUS_SPACE_MAXADDR_32BIT` for a 32-bit device. +- [ ] `highaddr` is `BUS_SPACE_MAXADDR` unless you are restricting on + purpose. +- [ ] `maxsize`, `nsegments`, and `maxsegsz` match what the device + actually accepts in a single transfer. + +### Stage 2: Allocation + +- [ ] For DMA buffers the device touches: `bus_dmamem_alloc`, not + plain `malloc`. +- [ ] For control structures the device never touches: `malloc(9)`. +- [ ] If you pre-create a map for user-supplied buffers: `bus_dmamap_create`, + remember to destroy with `bus_dmamap_destroy`. +- [ ] Flags: `BUS_DMA_WAITOK` in process context, `BUS_DMA_NOWAIT` in + atomic contexts; check the return value in the nowait case. +- [ ] Consider `BUS_DMA_COHERENT` and `BUS_DMA_ZERO` if appropriate. + +### Stage 3: Load + +- [ ] Callback handles the error case (`error != 0`) and does not + assume the callback always runs synchronously. +- [ ] Callback inspects `nseg` and walks every segment; do not assume + one segment unless the tag guarantees it. +- [ ] `ds_addr` is treated as a bus address, not a physical or + virtual address. Never printed or compared as if it were a + physical address. + +### Stage 4: Use + +- [ ] Before the device reads: `BUS_DMASYNC_PREWRITE`. +- [ ] Before the device writes: `BUS_DMASYNC_PREREAD`. +- [ ] After the device wrote (CPU about to read): `BUS_DMASYNC_POSTREAD`. +- [ ] After the device read (buffer reusable): `BUS_DMASYNC_POSTWRITE`. +- [ ] The sync calls are present on *every* architecture build, + even when they happen to be no-ops on coherent platforms. + +### Stage 5: Teardown + +- [ ] `bus_dmamap_unload` runs before `bus_dmamem_free`. +- [ ] `bus_dmamem_free` runs before `bus_dma_tag_destroy`. +- [ ] Teardown order mirrors setup order, in reverse. +- [ ] Detach path waits for all in-flight transfers before unloading + any map. A map cannot be safely unloaded while the device is + still reading or writing the buffer. + +## Sync direction reminder + +The `READ` and `WRITE` halves in the flag names follow the wording +used in `bus_dma(9)`: + +- `PREREAD` = "the device is about to update host memory, and the + CPU will later read what was written". +- `PREWRITE` = "the CPU has updated host memory, and the device is + about to access it". +- `POSTREAD` is the companion to `PREREAD`, issued after the device + has written and before the CPU reads. +- `POSTWRITE` is the companion to `PREWRITE`, issued after the device + has finished reading the buffer. + +Mapped to the two directions a driver actually thinks about: + +| CPU intent | Device operation | Sync calls | +| :-- | :-- | :-- | +| "Device, please read this" | Device reads the buffer | PREWRITE before, POSTWRITE after | +| "Device, please write here" | Device writes the buffer | PREREAD before, POSTREAD after | +| "Round trip" (CPU fills, device rewrites) | Device reads and writes | PREWRITE + PREREAD before, POSTREAD + POSTWRITE after | + +If the names feel backwards, remember that they describe what the +*CPU* will need to do with the buffer next: `PREREAD` prepares for a +later CPU read (so the device must be writing first), and `PREWRITE` +prepares for a device access to bytes the CPU just wrote. + +## Anti-patterns to avoid + +Do not cast a kernel virtual pointer to a `uint64_t` and hand it to +the device. Use `ds_addr`. + +Do not call `vtophys()` in a driver that has a `bus_dma` tag. The +layer already does the right thing; calling around it silently breaks +IOMMU setups. + +Do not skip the sync calls on amd64 because "it works". It will not +work on non-coherent platforms, and it will not work forever on amd64. + +Do not free a DMA buffer while the device may still be reading or +writing it. A descriptor ring that the hardware owns must be +quiesced before the buffer is released. + +Do not allocate the DMA tag with `lowaddr = BUS_SPACE_MAXADDR` on a +32-bit-only device. The driver will appear to work under an IOMMU and +fail on systems without one. + +## Debugging checklist + +- [ ] Confirm `pci_enable_busmaster(dev)` was called in attach for a + PCI device. +- [ ] Confirm `ds_addr` values look plausible for the device (not + 0xffffffff, not near the kernel's virtual range). +- [ ] Confirm sync calls bracket every device use. +- [ ] Confirm `bus_dmamap_unload` runs before any buffer reuse. +- [ ] Add a `sysctl` counter for successful and failed loads; a burst + of failures is often the first symptom. +- [ ] Rerun with `WITNESS` and `INVARIANTS` enabled; the kernel will + catch many misuses at the point of the mistake. + +## Cross-references + +- Appendix C, section **DMA**, for the full mental model. +- Chapter 21 for the line-by-line teaching. +- `bus_dma(9)`, `/usr/src/sys/sys/bus_dma.h`, and `/usr/src/sys/kern/subr_bus_dma.c`. +- Real drivers that use `bus_dma` extensively: most NIC drivers under + `/usr/src/sys/dev/` (for example, drivers under `/usr/src/sys/dev/e1000/`). diff --git a/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/hardware-to-driver-quick-reference.md b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/hardware-to-driver-quick-reference.md new file mode 100644 index 0000000..0fbd7cf --- /dev/null +++ b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/hardware-to-driver-quick-reference.md @@ -0,0 +1,179 @@ +# Hardware to Driver Quick Reference + +A short map of how a physical signal becomes a FreeBSD driver +callback, how a DMA transfer becomes bytes in a softc, and how a +PCI capability becomes an API call. Use this sheet to sanity-check +your understanding of a new device family before you write code. + +Full teaching lives in Appendix C and in Chapters 16 through 21. +This sheet only helps you see the whole pipeline at once. + +## From a device register to your C code + +``` +Device asserts a status bit + | + v +Bus fabric (PCI/PCIe/APB/etc.) routes the access + | + v +CPU MMU + cache attributes: "this region is uncached MMIO" + | + v +bus_space_handle_t resolves to virtual address in MMIO window + | + v +bus_space_read_4(tag, handle, offset) + | + v +Driver C code sees a uint32_t value +``` + +Reverse for writes. The `bus_space_barrier(9)` call lets you order +reads and writes when their order matters to the device. + +## From a device interrupt to your driver's filter + +``` +Device raises an interrupt signal + | + v +Interrupt controller (IOAPIC / local APIC / GIC / etc.) maps to a +CPU vector + | + v +Kernel low-level entry saves minimal state, dispatches through +intr_event(9) + | + v +Your filter function runs + | (spin locks only, no sleeping, no malloc, very short) + | + +-- returns FILTER_HANDLED -> controller EOIs, done + | + +-- returns FILTER_STRAY -> not mine, controller + | checks other handlers + | + +-- returns FILTER_SCHEDULE_THREAD -> ithread wakes to run + the heavy work +``` + +Per-vector counters (usually a `sysctl` under `dev..`) +are the cheapest and most useful diagnostic. + +## From DMA transfer setup to data in memory + +``` +attach: + bus_dma_tag_create(...) -> tag T + bus_dmamem_alloc(T, ...) -> vaddr V, map M + +runtime: + fill V with command data at the CPU virtual address + bus_dmamap_sync(T, M, BUS_DMASYNC_PREWRITE) + write ds_addr(M) into the device's descriptor register(s) + write the "start" register + | + v + device reads memory at ds_addr(M) via the bus (possibly IOMMU) + | + v + device writes result (if applicable) at another ds_addr + | + v + device raises an interrupt on completion + +completion: + filter recognises the event, optionally schedules the ithread + bus_dmamap_sync(T, M, BUS_DMASYNC_POSTREAD) + driver reads the result at V (the CPU virtual address) + optionally bus_dmamap_unload(T, M) +``` + +The two sync calls are the only thing that guarantees cache +coherence between the CPU view (V) and the device view (ds_addr). +Write them every time. + +## From PCI capabilities to API calls + +``` +PCI configuration space + +--- Base header (vendor, device, class, BARs, INTx, ...) + +--- Capability list (linked list starting at PCIR_CAP_PTR) + | + +--- PCIY_MSI -> pci_alloc_msi(dev, &count) + +--- PCIY_MSIX -> pci_alloc_msix(dev, &count) + +--- PCIY_PMG -> power management via ACPI/PCI + +--- PCIY_VENDOR -> vendor-specific, read through + pci_read_config at the capability + offset + +--- Extended capabilities (PCIe only, 4 KiB config window) + | + +--- PCIZ_AER -> advanced error reporting + +--- PCIZ_VC -> virtual channels + +--- ... +``` + +Lookup calls: +- `pci_find_cap(dev, PCIY_MSIX, &offset)` returns the offset of a + standard capability. +- `pci_find_extcap(dev, PCIZ_AER, &offset)` returns the offset of an + extended capability. +- Both are declared in `/usr/src/sys/dev/pci/pcivar.h` and defined in + `/usr/src/sys/dev/pci/pci.c`. + +## From probe to attached driver + +``` +Bus driver (pci, usb, iicbus, spibus) enumerates children at boot + | + v +For each child, kernel walks the list of registered drivers + | + v +Each driver's probe function runs: + PCI probe: match vendor/device IDs -> BUS_PROBE_DEFAULT + USB match: match VID/PID + class -> probe result + I2C/SPI: match FDT compatible or ACPI HID + | + v +Best-scoring driver wins + | + v +Driver's attach function runs: + allocate resources, set up interrupts, build softc, + make /dev nodes, expose sysctl, register with + subsystems if any + | + v +Driver is live +``` + +## Checklist: do I understand this device family? + +Answer yes to every line before writing code. + +- [ ] I know which bus the device sits on (`pci`, `usb`, `iicbus`, + `spibus`, `simplebus`, `acpi`, etc.). +- [ ] I know how the bus identifies devices (vendor/device ID, + VID/PID, slave address, chip-select, FDT compatible). +- [ ] I know whether the device uses registers I need to access + directly, or whether a framework handles transactions. +- [ ] I know whether the device uses interrupts and, if so, whether + they are legacy INTx, MSI, or MSI-X. +- [ ] I know whether the device uses DMA, and if so, what its + alignment and addressing limits are. +- [ ] I know which cache coherence mode applies on my target + architecture, and whether my code depends on it. +- [ ] I know which /dev node the device will expose, if any. +- [ ] I know which `sysctl` tree will expose counters and tunables. + +If any box is unchecked, the datasheet is where to look next. + +## Cross-references + +- Appendix C for every concept above. +- Chapter 16 (`bus_space`), Chapter 18 (PCI), Chapter 19 (interrupts), + Chapter 20 (MSI and MSI-X), Chapter 21 (DMA). +- Appendix A for the API reference, Appendix E for the subsystem + architecture. diff --git a/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/interrupt-vs-polling.md b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/interrupt-vs-polling.md new file mode 100644 index 0000000..4ce1f23 --- /dev/null +++ b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/interrupt-vs-polling.md @@ -0,0 +1,115 @@ +# Interrupt vs Polling Cheatsheet + +Quick reference for deciding how a driver should learn about events +from its device. Full teaching lives in Appendix C and in Chapters 19 +and 20. This sheet only helps you pick. + +## The question to ask first + +What is the *event rate* for this device, and how sensitive is the +driver to latency? + +- If events are rare and latency matters, use an interrupt. +- If events are frequent and dominate the CPU, consider polling + inside an ithread or a taskqueue instead. +- Do not decide by reflex. Measure the event rate before designing + the data path. + +## Comparison at a glance + +| You should use... | When... | Cost | +| :-- | :-- | :-- | +| A hardware interrupt | Event rate is moderate, latency matters | Interrupt setup, filter discipline, context switches | +| Polling in an ithread | Event rate is very high and interrupts dominate | Pinned CPU time, no latency from interrupt dispatch | +| A taskqueue triggered by interrupts | Work is heavy and cannot run in the filter | A thread wakeup per batch, not per event | +| A callout (timer) plus occasional interrupts | Device is slow, state is simple | Periodic wake-up, possibly imprecise timing | +| Pure polling in a kernel thread | The device has no interrupt, or the spec forbids interrupts | CPU time scales with polling rate | + +## Decision ladder + +``` +Does the device raise an interrupt on the event? +|-- No -> Polling loop in a kernel thread or callout; make sure the +| rate is tolerable. +|-- Yes -> Is the per-event work small enough for a filter? + |-- Yes -> Filter-only handler (FILTER_HANDLED). + |-- No -> Filter that acknowledges the device and returns + FILTER_SCHEDULE_THREAD; ithread or taskqueue + does the real work. + +Is the event rate so high that interrupts dominate the CPU? +|-- No -> Stay with the interrupt model. +|-- Yes -> Consider disabling interrupts while an ithread polls for a + batch, re-enabling when the queue is empty. This is the + iflib pattern for fast NICs. +``` + +## Interrupt discipline checklist + +If you chose the interrupt path, walk this checklist before you ship. + +- [ ] The filter is short and allocation-free. +- [ ] The filter takes spin locks only, never sleep mutexes. +- [ ] The filter acknowledges the device before returning + `FILTER_HANDLED`, or the device keeps asserting until the + ithread runs. +- [ ] The filter returns `FILTER_STRAY` when the interrupt did not + come from this driver's hardware (legacy INTx path). +- [ ] A per-vector counter is exported through `sysctl` so you can + see the interrupt rate in a live system. +- [ ] The ithread (or taskqueue) is the only place that does heavy + work, allocations, or sleeping. +- [ ] Teardown is the reverse of setup: `bus_teardown_intr` before + `bus_release_resource`. + +## Edge vs level reminder + +``` +Edge-triggered + __ __ + | | | | +___| |______________| |____ + ^ ^ + one event one event + (lose it once and it is gone) + +Level-triggered + ____________ + | | +_______________| |_______ + ^ ^ + interrupt driver acks + fires and the device, + keeps firing line deasserts + until ack +``` + +Legacy PCI INTx lines are level-triggered and shared. MSI and MSI-X +messages are effectively edge-like events (one message per signal). +A filter for legacy INTx must check the device's status before +returning `FILTER_HANDLED`, because the line is shared. + +## Anti-patterns to avoid + +Do not do real work in the filter. The filter is a dispatcher, not a +worker. If you find yourself writing a long sequence of reads and +writes, you belong in an ithread or a taskqueue. + +Do not return `FILTER_HANDLED` on a shared legacy line without first +checking that the interrupt came from your device. That wedges the +system. + +Do not poll when an interrupt would work. A polling loop that wakes +thousands of times per second on an idle system is a bug, not a +design. + +Do not start an ithread and never join it at detach. `bus_teardown_intr` +is non-optional. + +## Cross-references + +- Appendix C, section **Interrupts**, for the full mental model. +- Chapter 19 for the interrupt discipline in detail. +- Chapter 20 for MSI and MSI-X. +- `intr_event(9)`, `bus_setup_intr(9)`, and the `FILTER_` constants + in `/usr/src/sys/sys/bus.h`. diff --git a/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/physical-vs-virtual-memory.md b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/physical-vs-virtual-memory.md new file mode 100644 index 0000000..a3b34be --- /dev/null +++ b/examples/appendices/appendix-c-hardware-concepts-for-driver-developers/cheatsheets/physical-vs-virtual-memory.md @@ -0,0 +1,134 @@ +# Physical vs Virtual Memory Diagram Sheet + +A mental-model reference for the address spaces a FreeBSD driver +operates in. Full teaching lives in Appendix C, section **Memory in +the Kernel**, and in Chapters 16 and 21. Use this sheet when you want +to ground your current driver in the underlying layout. + +## The three address spaces a driver touches + +Every driver operates across at least three address spaces. +Understanding which one you are in at each line of code is the single +most important habit in driver work. + +``` ++-------------------------------------------------------------+ +| Kernel virtual memory | +| | +| C pointers live here. malloc(9), uma_zalloc, stack, | +| softc. The MMU translates these to physical pages on the | +| fly via the kernel's page tables. | +| | +| The CPU dereferences these. The device never sees them. | ++-------------------------------------------------------------+ + | + | MMU translation + v ++-------------------------------------------------------------+ +| Physical memory | +| | +| Real RAM pages, real MMIO register regions, real I/O | +| ports. A peripheral with no IOMMU sees memory this way | +| (subject to its own address bits). | ++-------------------------------------------------------------+ + ^ + | IOMMU translation (when present) + | ++-------------------------------------------------------------+ +| Bus address space | +| | +| The addresses a peripheral emits on the bus. Without an | +| IOMMU, these equal physical addresses (possibly through | +| a bounce buffer). With an IOMMU, these are I/O-virtual | +| addresses that the IOMMU translates to physical. | +| | +| The device dereferences these. The CPU cannot. | ++-------------------------------------------------------------+ +``` + +## How the driver API lines up + +Fill in the blanks for your current driver to pin down the layout. + +| Concept | Address space | How your driver obtains it | Example (your driver) | +| :-- | :-- | :-- | :-- | +| Softc pointer | Kernel virtual | `device_get_softc(dev)` | | +| DMA buffer (CPU view) | Kernel virtual | `bus_dmamem_alloc(...)` returns vaddr | | +| DMA buffer (device view) | Bus address | `ds_addr` from load callback | | +| Device register window | Physical (mapped) | `bus_alloc_resource(SYS_RES_MEMORY, ...)` | | +| Register access | Virtual, uncached | `bus_space_read_4(tag, handle, offset)` | | +| PCI BAR raw value | Physical | `pci_read_config(dev, PCIR_BAR(n), 4)` | | + +## What each layer owns + +- **CPU path (left side).** The kernel dereferences virtual pointers. + The MMU translates them. Your C code, including every pointer + dereference in the driver, lives here. +- **Device path (right side).** The device emits bus addresses. The + IOMMU (if present) translates them. Your DMA setup, including every + `ds_addr` you copy into a descriptor, lives here. + +The `bus_space` and `bus_dma` families are the bridges between the +two sides. Anything that crosses from one side to the other must go +through one of them. + +## MMIO access path (CPU to device register) + +``` +CPU code: bus_space_read_4(tag, handle, offset) + | + v + Tag decides address space (memory vs I/O port) and attributes + | + v + Handle resolves to a virtual address in the region + mapped by the kernel with uncached / strongly-ordered + attributes. + | + v + MMU translates to physical MMIO address, delivers the + read, returns the value. + | + v +CPU code: uses the value +``` + +## DMA access path (device to RAM) + +``` +Driver setup: + bus_dma_tag_create(...) -> tag encodes device constraints + bus_dmamem_alloc(...) -> CPU-virtual + map + bus_dmamap_load(...) -> callback receives ds_addr + hand ds_addr to device -> device stores it in a descriptor + +Runtime: + bus_dmamap_sync(..., PREWRITE or PREREAD) + device reads or writes memory at ds_addr + (IOMMU translates ds_addr -> physical if present) + device signals completion (interrupt) + bus_dmamap_sync(..., POSTREAD or POSTWRITE) + CPU reads the result through the virtual view +``` + +## Things to verify in your own driver + +- [ ] Every virtual pointer stays on the CPU path. +- [ ] Every bus address reaches the device only through `ds_addr` + or a raw PCI BAR on the device side. +- [ ] No line of code casts a `void *` to something the device will + dereference. +- [ ] Register reads and writes go through `bus_space_read_*` / + `bus_space_write_*`, not raw dereferences. +- [ ] DMA buffers and control buffers are clearly separated in the + softc. + +## Cross-references + +- Appendix C, section **Memory in the Kernel**, for the full + treatment. +- Chapter 16 for `bus_space(9)` and MMIO mapping. +- Chapter 21 for DMA and `bus_dma(9)`. +- `bus_space(9)`, `bus_dma(9)`, `pmap(9)`. +- `/usr/src/sys/sys/bus.h`, `/usr/src/sys/sys/bus_dma.h`, and + `/usr/src/sys/vm/vm_page.h` for the underlying types. diff --git a/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/boot-to-init-timeline.md b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/boot-to-init-timeline.md new file mode 100644 index 0000000..a85d41f --- /dev/null +++ b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/boot-to-init-timeline.md @@ -0,0 +1,106 @@ +# Boot-to-Init Timeline + +A compact timeline of how a FreeBSD machine gets from power-on to a +userland ready to run your driver. Use it to orient yourself when a +bug happens early in boot, or when you need to decide at which stage +a piece of initialisation should happen. + +## Timeline + +``` +Power on + | + v +Firmware (BIOS or UEFI) [hardware + vendor code] + | + v +First-stage boot (boot0 / UEFI boot manager) [/usr/src/stand/] + | + v +FreeBSD loader loader(8) + | reads /boot/loader.conf, loads kernel + | and any preload modules, passes tunables + v +Kernel entry (arch-specific) hammer_time() (amd64) + | early assembly -> C init386() (i386) + | set up basic CPU state, console (arch-specific) (arm64...) + v +mi_startup() sys/kern/init_main.c + | walks the sorted SYSINIT chain, in increasing SI_SUB_* value + | + |-- SI_SUB_VM (virtual memory up; malloc(9) safe) + |-- SI_SUB_LOCK (locking primitives ready) + |-- SI_SUB_EVENTHANDLER (event handlers registrable) + |-- SI_SUB_KLD (module and KLD system up) + |-- SI_SUB_INTRINSIC (proc 0 initialised) + |-- SI_SUB_DRIVERS (early driver-subsystem init) + |-- SI_SUB_CONFIGURE (bus probe/attach runs) <-- your driver here + |-- SI_SUB_KICK_SCHEDULER (callout machinery starts) + |-- SI_SUB_ROOT_CONF (root FS configuration stage) + |-- SI_SUB_CREATE_INIT (init proc created in stopped state) + |-- SI_SUB_KTHREAD_INIT (init proc made runnable by kick_init) + |-- SI_SUB_LAST (terminal SYSINIT bucket) + v +start_init() sys/kern/init_main.c + | runs on PID 1 once scheduled, mounts root FS + | via vfs_mountroot(), then execs /sbin/init + v +init(8) init(8), rc(8) + | runs /etc/rc, brings up services, opens consoles + v +login(1), daemons, getty, and the system is up +``` + +Stage names match `SI_SUB_*` constants in `/usr/src/sys/sys/kernel.h`, +sorted by their numeric value. Only the driver-relevant landmarks are +shown; many more stages exist between them. Order numbers +(`SI_ORDER_FIRST`, `SI_ORDER_MIDDLE`, `SI_ORDER_ANY`) decide ordering +within one subsystem. + +## Driver-Relevant Facts + +- A **compiled-in** driver runs its probe/attach at + `SI_SUB_CONFIGURE`, once buses have enumerators. +- A **preloaded module** (listed in `/boot/loader.conf`) is available + to the kernel by `SI_SUB_KLD` and registers with Newbus in the + usual way. Its `probe`/`attach` also happens at `SI_SUB_CONFIGURE`. +- A **runtime `kldload(8)`** happens after boot. Probe/attach happens + immediately, against whatever devices the module claims. +- A driver that must drive the root disk must reach the kernel before + `SI_SUB_VFS`. That usually means built-in or preloaded. + +## What Becomes Usable When + +| You want to... | Wait until (at least)... | +| :------------------------------------------- | :------------------------ | +| Call `malloc(9)` with `M_WAITOK` | `SI_SUB_VM` | +| Take and release a mutex | `SI_SUB_LOCK` | +| Register an event handler | `SI_SUB_EVENTHANDLER` | +| Load a kernel module | `SI_SUB_KLD` | +| `probe` / `attach` your device | `SI_SUB_CONFIGURE` | +| Arm a `callout(9)` and expect it to fire | `SI_SUB_KICK_SCHEDULER` | +| Read from the root filesystem | After `SI_SUB_ROOT_CONF` | +| Expect any userland process to exist | After `start_init` runs | + +## Common Traps + +- **Assuming the console is available very early.** The kernel has a + console message buffer from the start, but not every stage can + flush it to the actual screen. Early panics may leave limited + output; `boot -v` and `hw.serial` tunables help. +- **Depending on file-system presence at attach.** Root may not be + mounted yet. If you need to read a file at boot, use + `eventhandler(9)` to subscribe to `mountroot` or similar events. +- **Writing `SYSINIT` functions that can sleep before `SI_SUB_VM`.** + Early subsystems run before the VM is fully up; check the stage + before you call allocation or locking primitives. + +## Where to Read More + +- `/usr/src/sys/kern/init_main.c` for `mi_startup` and `start_init`. +- `/usr/src/sys/sys/kernel.h` for `SYSINIT` macros and `SI_SUB_*`. +- `/usr/src/sys/kern/subr_bus.c` for the Newbus side of + `SI_SUB_CONFIGURE`. +- `loader(8)`, `loader.conf(5)`, `kld(9)`, `kldload(8)`, `kldstat(8)`. +- Chapter 2 for boot in a lab context. Chapter 6 for the driver side + of module loading. Appendix E for deeper subsystem detail. diff --git a/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/driver-type-comparison.md b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/driver-type-comparison.md new file mode 100644 index 0000000..66a29b0 --- /dev/null +++ b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/driver-type-comparison.md @@ -0,0 +1,112 @@ +# Driver Type Comparison + +A compact map of the driver categories FreeBSD publishes. Use it when +you are starting a new driver and deciding which subsystem interface +to implement, or when you open an unfamiliar driver and want to know +which set of rules applies. + +## Side-by-side + +| Aspect | Character | Network | Storage (GEOM) | Pseudo | +| :------------------ | :--------------------------------- | :------------------------------ | :----------------------------- | :------------------------------ | +| Registers with | `cdevsw` via `make_dev_s` | `ifnet` | GEOM class / provider | Same as the category it mimics | +| Userland view | `/dev/` node | `if_` (e.g., `em0`) | `/dev/` node (GEOM) | `/dev/` or `if_` | +| Main entry points | `d_open`, `d_close`, `d_read`, | `if_transmit`, receive | `g_start`, `biodone(9)` | Same as above | +| | `d_write`, `d_ioctl` | callbacks, link-state | | | +| Main buffer | `struct uio` (user I/O) | `struct mbuf` chain | `struct bio` request | Same as above | +| Completion style | Return from entry point | `m_freem(m)` or post to stack | `biodone(9)` on the `bio` | Same as above | +| Typical device | Serial port, sensor, `/dev/null` | Ethernet, WiFi, `tun`, `tap` | Disk, SSD, `md(4)` | Any driver with no hardware | +| Example source | `/usr/src/sys/dev/null/null.c` | `/usr/src/sys/net/if_tuntap.c` | `/usr/src/sys/dev/md/md.c` | `/usr/src/sys/dev/null/null.c` | +| Taught in | Chapter 7, 8, 9 | Chapter 28 | Chapter 27 | Chapter 7 (as first driver) | + +## Decision prompts + +Answer these in order. Usually one answer ends the question. + +1. **Is the device a network interface?** If yes, you want an + `ifnet`-based network driver. Everything network-shaped flows + through the stack, not through `cdevsw`. + +2. **Is the device storage with a GEOM-compatible abstraction?** If + yes, write a GEOM class or provider. The data unit is `struct bio`, + completion is `biodone(9)`, and filesystems reach you through the + GEOM tree. + +3. **Is the device a stream or control surface exposed as a device + node?** A character driver with a `cdevsw` is the right shape. + +4. **Is there no hardware at all?** You are writing a pseudo-device. + Pick the category of its userland interface (character, network, + storage) and follow that category's rules. + +## What not to mix + +- Do **not** reach for `cdevsw` when writing a network driver. The + stack expects an `ifnet`, not a `/dev` node. +- Do **not** expose a disk as a raw `cdevsw` character device. Modern + FreeBSD routes disks through GEOM; bypassing it skips partitioning, + caching, and transforms the rest of the system expects. +- Do **not** register with both `cdevsw` and `ifnet` for the same + logical device. If you need a userland control surface for a + network driver, add a `sysctl(9)` tree or a small `ioctl(2)` on + a separate character node; do not duplicate identities. + +## Minimum registration sketches + +Character driver (end of file): + +```c +static struct cdevsw mydev_cdevsw = { + .d_version = D_VERSION, + .d_name = "mydev", + .d_open = mydev_open, + .d_close = mydev_close, + .d_read = mydev_read, + .d_write = mydev_write, + .d_ioctl = mydev_ioctl, +}; + +DRIVER_MODULE(mydev, , mydev_driver, 0, 0); +MODULE_VERSION(mydev, 1); +``` + +Network driver (key step at attach): + +```c +if_t ifp = if_alloc(IFT_ETHER); +if_setsoftc(ifp, sc); +if_initname(ifp, device_get_name(dev), device_get_unit(dev)); +if_settransmitfn(ifp, mydev_transmit); +/* ... further if_set*() calls to wire up flags, MTU, mediastatus ... */ +if_attach(ifp); +``` + +GEOM provider (skeleton): + +```c +static struct g_class g_mydev_class = { + .name = "mydev", + .version = G_VERSION, + .start = mydev_start, + /* ... */ +}; +DECLARE_GEOM_CLASS(g_mydev_class, mydev); +``` + +## Common traps + +- Writing a character driver and then realising partway through that + the device is really network-shaped. Stop and switch early; the + buffer type and the locking shape are both different. +- Copying the `cdevsw` of a real device when writing a pseudo-device + without trimming the entry points to the ones you actually support. + Unused entry points should not be registered; they should simply be + absent from the `cdevsw` initialiser. + +## Where to read more + +- `cdevsw(9)`, `ifnet(9)`, `bio(9)`, `geom(4)`, `geom(9)`. +- Appendix A for the full API entries. +- Chapter 6 for driver anatomy, Chapter 7 for the first character + driver, Chapter 27 for GEOM and storage, Chapter 28 for `ifnet` and + networking. diff --git a/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/kernel-vs-user-space.md b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/kernel-vs-user-space.md new file mode 100644 index 0000000..42791c1 --- /dev/null +++ b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/kernel-vs-user-space.md @@ -0,0 +1,78 @@ +# Kernel vs User Space Cheatsheet + +A one-page reminder of the boundary that shapes every rule in driver +code. Read it before touching any pointer that came from userland. + +## The Two Sides + +``` ++---------------------------------------------+---------------------------+ +| Kernel Space | User Space | ++---------------------------------------------+---------------------------+ +| Full CPU privilege | Reduced privilege | +| One shared address space | One per process, isolated | +| Memory stable while allocated | May page, swap, unmap | +| Direct hardware access | None | +| Bug blast radius: whole machine | Bug blast radius: one proc| +| Entered from userland via a syscall trap | Entered from kernel on | +| | return from syscall | ++---------------------------------------------+---------------------------+ +``` + +## The Rule of the Door + +A user pointer is never dereferenced directly from the kernel. +Always use a copy primitive that catches a bad user address and +returns `EFAULT` instead of panicking. + +``` +user side kernel side +--------- ----------- +char buf[N] -- write(2) --> struct uio -- uiomove() --> kernel buffer + <- read(2) -- struct uio <- uiomove() <-- kernel buffer + +void *ptr -- ioctl(2) --> arg cookie -- copyin() --> kernel struct + <- ioctl(2) -- arg cookie <- copyout() <- kernel struct +``` + +## Copy Primitive Cheat Lines + +| You have... | Use | +| :---------------------------------------- | :-------------------------- | +| A fixed-size struct coming in from user | `copyin(9)` | +| A fixed-size struct going out to user | `copyout(9)` | +| A NUL-terminated string from user | `copyinstr(9)` | +| A buffer list described by `struct uio` | `uiomove(9)` | +| A single word from user | `fueword(9)` / `suword(9)` | + +## Red-Flag Checklist + +Before you press commit on a driver function that received a user +pointer or structure, tick all of these. + +- [ ] The user pointer is never dereferenced directly in this function. +- [ ] Every copy primitive has its return value checked and propagated. +- [ ] `EFAULT` is returned, not ignored, on a bad user address. +- [ ] Any structure received from user is validated before use + (sizes bounded, offsets inside the buffer, flags in the known set). +- [ ] String lengths are capped with the `maxlen` argument to + `copyinstr(9)`; no unbounded lengths pulled from user fields. +- [ ] No kernel pointer is written out verbatim to user space (no info + leak, no bypass of address-space-layout protections). + +## Common Traps + +- Assuming a write of known size is safe because the user "always + passes the right value". Size fields must be bounded on input. +- Copying user data once and trusting it thereafter, when an + attacker can change the buffer between two accesses. Copy once, + work from the kernel copy only. +- Holding a sleep mutex across a copy primitive. Copy primitives may + sleep; design the critical section to release before copying. + +## Where to Read More + +- `copyin(9)`, `copyout(9)`, `copyinstr(9)`, `uiomove(9)` manual pages. +- `/usr/src/sys/sys/uio.h` for `struct uio`. +- Chapter 5 for kernel-C context. Chapter 9 for a working character + driver `d_read`/`d_write` path that uses `uiomove(9)` end to end. diff --git a/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/softc-lifecycle-checklist.md b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/softc-lifecycle-checklist.md new file mode 100644 index 0000000..5339736 --- /dev/null +++ b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/softc-lifecycle-checklist.md @@ -0,0 +1,115 @@ +# Softc Lifecycle Checklist + +A one-page audit sheet for the per-device state structure. Use it when +you review a driver's `probe`, `attach`, `detach`, `suspend`, and +`resume` paths. Most lifecycle bugs are checklist violations you can +name on paper. + +## The Big Picture + +``` ++---------+ +---------+ +-------------+ +---------+ +| probe | ---> | attach | ---> | runtime | --> | detach | ++---------+ +---------+ +-------------+ +---------+ + | | | + v v v + [softc allocated] [softc in use] [softc freed by + and initialised for every the kernel, after + in this order: operation; this driver's + all state under detach cleanup] + 1. device_get_softc the softc lock] + 2. init sc->sc_lock + 3. alloc resources + 4. setup_intr + 5. publish (/dev, + ifnet, GEOM) +``` + +The kernel zeroes the softc before handing it to `attach`. Nothing is +"left over" from a previous attach. + +## Probe Checklist + +- [ ] Read only what is needed to identify the device (vendor/device + IDs, class codes, FDT compatibility strings). +- [ ] Return `BUS_PROBE_DEFAULT`, `BUS_PROBE_GENERIC`, or a more + specific value depending on confidence. +- [ ] Do **not** allocate resources in `probe`. +- [ ] Do **not** store long-lived state anywhere (the softc is not + yours yet). +- [ ] Set `device_set_desc` so that `devinfo(8)` has a human label. + +## Attach Checklist + +- [ ] Get the softc: `sc = device_get_softc(dev)`. +- [ ] Stash back-pointer: `sc->dev = dev`. +- [ ] Initialise the softc lock: `mtx_init(&sc->sc_lock, ...)`. +- [ ] Allocate memory (`malloc(9)`), queues, and internal state. +- [ ] Allocate bus resources (`bus_alloc_resource_any`) in the order + that matches the `detach` release order (you will release in + reverse). +- [ ] Map MMIO through `bus_space`, not raw pointers. +- [ ] Install the interrupt last (`bus_setup_intr`), so the handler + cannot fire before the softc is ready. +- [ ] Publish the device to its subsystem (`make_dev_s`, `if_attach`, + `g_new_providerf`, etc.) only after the softc is fully ready. +- [ ] On any failure, unwind in reverse through a `goto fail_N:` ladder. + +## Runtime Checklist + +- [ ] Every entry point starts by fetching `sc = device_get_softc(dev)`. +- [ ] Every field access that can race is protected by the softc lock. +- [ ] Long operations (allocation with `M_WAITOK`, copyin/copyout) + happen with the lock dropped, or under an `sx(9)` lock designed + for the purpose. +- [ ] Interrupt filters take only spin locks; sleep locks are forbidden. +- [ ] Sysctl handlers walk the softc under the right lock too. + +## Suspend Checklist + +- [ ] Stop hardware DMA and pending work before the system suspends. +- [ ] Snapshot volatile register state that the hardware will lose. +- [ ] Cancel any callouts with `callout_drain` (not just `callout_stop`). +- [ ] Return `0` only after the device is quiescent. + +## Resume Checklist + +- [ ] Restore the snapshot taken in `suspend`. +- [ ] Re-arm interrupts, DMA engines, timers, callouts. +- [ ] Replay any state the hardware requires (NIC MAC filter, + transceiver mode, clock dividers). + +## Detach Checklist + +Walk the attach steps in reverse. + +- [ ] Unpublish from the subsystem (`destroy_dev`, `if_detach`, + `g_wither_geom`, etc.). +- [ ] Tear down the interrupt (`bus_teardown_intr`). +- [ ] Drain any callout, taskqueue, or kernel thread the driver owns. +- [ ] Release bus resources in reverse order. +- [ ] Free allocated memory and queue contents. +- [ ] Destroy the softc lock (`mtx_destroy(&sc->sc_lock)`). +- [ ] Return `0` only after nothing can dereference the softc anymore. + +## Common Traps + +- **Globals masquerading as "single device" convenience.** If a second + instance of the device appears, the two will share the globals. Keep + everything in the softc. +- **Interrupt set up before the softc is ready.** The handler can fire + between `bus_setup_intr` and the rest of `attach`. Install interrupts + last. +- **Detach that frees memory the interrupt still uses.** Tear down the + interrupt before freeing the state it references. +- **`callout_stop` instead of `callout_drain` in `detach`.** `stop` + cancels a pending callout but does not wait for a running one; a + driver can be freed while a callout is mid-execution. +- **Forgetting `mtx_destroy` in `detach`.** The mutex leaks; repeated + load/unload cycles accumulate leaked locks. + +## Where to Read More + +- `device_get_softc(9)`, `mtx(9)`, `callout(9)`. +- Chapter 6 for the lifecycle overview, Chapter 7 for a full + implementation, Chapter 11 for locking discipline. diff --git a/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/where-drivers-fit.md b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/where-drivers-fit.md new file mode 100644 index 0000000..066bb9e --- /dev/null +++ b/examples/appendices/appendix-d-operating-system-concepts/cheatsheets/where-drivers-fit.md @@ -0,0 +1,128 @@ +# Where Drivers Fit in the Operating System + +A short map of how a user program reaches your driver, and how your +driver reaches the hardware. Use it to sanity-check where a piece of +new code belongs before you write it. + +## The Sandwich + +``` ++--------------------------------------------------------------------+ +| USER SPACE | +| | +| Applications, daemons, shells, tools | +| open(2), read(2), write(2), ioctl(2), socket(2), ... | ++--------------------------------------------------------------------+ + | + system-call trap (boundary) + | ++--------------------------------------------------------------------+ +| KERNEL SPACE | +| | +| System-call dispatcher | +| | | +| +-- VFS / devfs --> cdevsw entry points (char / pseudo) | +| | | | +| | +-- your driver (d_open, d_read, d_write, d_ioctl) | +| | | +| +-- Network stack (socket, IP, L2) --> ifnet | +| | | | +| | +-- your driver (if_transmit, receive callback) | +| | | +| +-- VFS / GEOM --> GEOM class / provider | +| | | +| +-- your driver (g_start, biodone) | +| | +| Core kernel services (proc, vm, locks, callout, taskqueue, | +| bus, interrupts, sysctl, eventhandler, kld) | +| | +| Newbus tree | +| root -> pci -> your-device -> your-softc | +| root -> usbus -> your-device -> your-softc | +| root -> iicbus -> your-device -> your-softc | ++--------------------------------------------------------------------+ + | + hardware I/O boundary + | ++--------------------------------------------------------------------+ +| HARDWARE | +| | +| MMIO registers, interrupt lines, DMA-capable memory | ++--------------------------------------------------------------------+ +``` + +Your driver is the single component with feet on both sides of the +lower boundary: it speaks the hardware's language down, and the +kernel subsystem's language up. + +## What Lives Where + +| Concern | Lives in | +| :----------------------------- | :------------------------------------- | +| User pointer validation | Subsystem boundary (syscall handler or | +| | `d_ioctl` prologue) | +| Kernel-to-user copy | Same boundary | +| Subsystem-format buffer | Subsystem layer (`uio`, `mbuf`, `bio`) | +| Pending-work queue | Your driver's softc | +| Softc lock | Your driver | +| Register access | Your driver | +| Interrupt filter | Your driver (registered via | +| | `bus_setup_intr`) | +| Interrupt ithread / taskqueue | Your driver | +| DMA descriptor setup | Your driver | +| Cache coherence / bus sync | `bus_dma(9)`, invoked from your driver | + +## Decision Heuristics + +1. **Is this code validating something from userland?** It belongs at + the subsystem boundary (the first lines of `d_ioctl`, the first + lines of the syscall handler, the receive path of the stack). + +2. **Is this code manipulating per-device state?** It belongs in the + softc, under the softc lock. + +3. **Is this code touching a register?** It belongs in the driver, + through `bus_space_read_*` / `bus_space_write_*`. + +4. **Is this code deciding when work runs?** It belongs in an interrupt + filter, an ithread, a taskqueue, or a callout, depending on + urgency and sleepability. + +5. **Is this code allocating memory?** Use `malloc(9)` for control + data, `uma(9)` for frequent fixed-size allocations, + `bus_dmamem_alloc(9)` for DMA buffers. + +## Newbus in One Paragraph + +Every FreeBSD device is a `device_t` node in the Newbus tree. The +root of the tree (`root0`) has a child for each top-level bus +(`nexus0`), and each bus has a child for each peripheral it +enumerates. Your driver registers with a parent bus name +(`pci`, `usbus`, `iicbus`, `spibus`, `acpi`, `simplebus`) in its +`DRIVER_MODULE` line, and the kernel offers each child of that bus +to your `probe` function. The `device_t` you receive is a handle +into the tree; the softc behind it is your per-instance state. Read +`devinfo -v` on a running system to see the tree in action. + +## Common Traps + +- **Putting user-pointer validation deep inside the driver.** If the + entry point already took a copied, validated structure, the + internal paths should not re-validate the raw user pointer; they + should not have access to it at all. +- **Mixing subsystem buffers.** An `mbuf` does not belong in the + storage path; a `bio` does not belong in the network path. If a + pipeline seems to need conversion, a layer boundary is in the + wrong place. +- **Reaching past the subsystem to call into another driver + directly.** Let the subsystem be the contact surface. Cross-driver + coupling through private APIs is the fastest way to make both + drivers unmaintainable. + +## Where to Read More + +- `intro(9)` for the kernel overview, `devinfo(8)` for the running + Newbus tree, `sysctl(8)` for runtime visibility. +- Chapter 3 for UNIX foundations, Chapter 6 for driver anatomy, + Chapter 7 for a first complete driver. +- Appendix A for the full API vocabulary. diff --git a/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/driver-touchpoint-checklist.md b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/driver-touchpoint-checklist.md new file mode 100644 index 0000000..a3485f3 --- /dev/null +++ b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/driver-touchpoint-checklist.md @@ -0,0 +1,153 @@ +# Driver Touchpoint Checklist + +Before you start a new driver, walk this checklist and mark the +subsystems the driver will actually touch. Unchecked rows are the +sections of Appendix E you can skip for now. Checked rows are the +sections worth rereading *before* you write the first line of code. + +The goal is not completeness. It is orientation: knowing, on paper, +which subsystems will push back on your design and which ones will +be happy to ignore you. + +## Project Metadata + +``` +Driver name: _______________________________ +Parent bus: pci / usbus / iicbus / spibus / acpi / simplebus / nexus +Target arch(s): _______________________________ +FreeBSD version: _______________________________ +Primary purpose: _______________________________ +``` + +## Subsystem Checklist + +### 1. Process and Thread + +``` +[ ] Driver spawns a kernel thread or kproc + (watchdog, poller, deferred work host) +[ ] Driver looks at the calling thread's process credentials + (in d_ioctl, in a sysctl handler, in a privilege check) +[ ] Driver uses curthread for anything other than sleep/wakeup +[ ] Driver runs at a non-default priority +``` + +If any box is checked, re-read Appendix E "Process and Thread +Subsystem" and Chapter 14 (taskqueues) or Chapter 24 (kernel +integration, kprocs). + +### 2. Memory (VM) + +``` +[ ] Driver allocates memory with malloc(9) +[ ] Driver uses a UMA zone for fixed-size objects +[ ] Driver needs contiguous physical memory (contigmalloc) +[ ] Driver does DMA and uses bus_dma(9) +[ ] Driver exposes memory to userland via d_mmap or d_mmap_single +[ ] Driver wires pages of a user buffer across a long I/O +``` + +If any box is checked, re-read Appendix E "Memory Subsystem" and the +corresponding chapter (5 for allocators, 21 for DMA, 16/17 for +bus_space). + +### 3. File and VFS + +``` +[ ] Driver publishes a /dev entry with make_dev_s(9) + cdevsw +[ ] Driver implements d_open, d_close, d_read, d_write, d_ioctl +[ ] Driver publishes a GEOM provider (storage driver) +[ ] Driver receives struct bio on a start routine +[ ] Driver interacts with struct buf (legacy block path) +[ ] Driver needs to respect file-system locking rules +``` + +If any box is checked, re-read Appendix E "File and VFS Subsystem" +and Chapters 7-9 (character driver) or Chapter 27 (storage and +GEOM). + +### 4. Network + +``` +[ ] Driver registers as an ifnet (network driver) +[ ] Driver transmits or receives mbufs +[ ] Driver must be VNET-aware (jails with VIMAGE) +[ ] Driver needs routing or socket knowledge beyond ifnet +[ ] Driver subscribes to ifnet_arrival_event / ifnet_departure_event +[ ] Driver offloads checksums, TSO, LRO, or RSS +``` + +If any box is checked, re-read Appendix E "Network Subsystem" and +Chapter 28 (writing a network driver). + +### 5. Driver Infrastructure (Newbus) + +``` +[ ] Driver declares a device_method_t array +[ ] Driver uses DRIVER_MODULE to bind under a parent bus +[ ] Driver allocates resources with bus_alloc_resource_any +[ ] Driver sets up interrupts with bus_setup_intr +[ ] Driver supports multiple parent buses + (e.g. DRIVER_MODULE twice under pci and under acpi) +[ ] Driver uses kobj directly beyond the standard DEVMETHOD macros +``` + +(Every driver will have at least the first four boxes checked.) +Re-read Appendix E "Driver Infrastructure" and Chapter 6 (anatomy), +Chapter 7 (first driver), Chapter 18 (PCI). + +### 6. Boot and Module System + +``` +[ ] Driver requires another module (MODULE_DEPEND) +[ ] Driver must run early in kernel startup (SYSINIT with low SI_SUB) +[ ] Driver must run late in kernel startup (high SI_SUB, high SI_ORDER) +[ ] Driver must publish its own ABI version for others to depend on +[ ] Driver is a console or early-boot device +[ ] Driver must attach before root mount +``` + +If any box is checked, re-read Appendix E "Boot and Module System" +and Chapter 24 (kernel integration), Chapter 32 (embedded boot if +applicable). + +### 7. Kernel Services + +``` +[ ] Driver registers a shutdown_pre_sync / shutdown_final handler +[ ] Driver reacts to vm_lowmem +[ ] Driver needs to defer work out of an interrupt filter + (use taskqueue) +[ ] Driver needs a timer or a watchdog (use callout) +[ ] Driver uses a grouped taskqueue for per-CPU work +[ ] Driver exposes sysctl counters or tunables +``` + +If any box is checked, re-read Appendix E "Kernel Services" and +Chapter 13 (timers), Chapter 14 (taskqueues), Chapter 24 (kernel +integration). + +## After the Checklist + +Once the checklist is filled in, the shape of the driver is already +visible on the page. A minimal character driver for a small +peripheral might check only Driver Infrastructure and File and VFS +(character path). A PCI network driver with DMA might check +Memory, Network, Driver Infrastructure, and Kernel Services. An +early-boot console driver might check Driver Infrastructure, Boot +and Module System, and a single box under Kernel Services for the +shutdown hook. + +The checked subsystems are where you should concentrate your +reading *before* you start coding. The unchecked ones do not +disappear, but they move to the background, and you can ignore them +until the design tells you otherwise. + +## A Final Habit + +Keep the filled-in checklist in the driver's design notes or at the +top of a `README.md` in your driver tree. Revisit it when the design +changes. A subsystem that sneaks in after the initial design (for +example, DMA that appears late in development) is usually a signal +that you need to revisit the corresponding section of Appendix E +before you write more code. diff --git a/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/manpage-and-source-reading-plan.md b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/manpage-and-source-reading-plan.md new file mode 100644 index 0000000..ce78876 --- /dev/null +++ b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/manpage-and-source-reading-plan.md @@ -0,0 +1,143 @@ +# Manpage and Source Reading Plan + +An eight-step self-study itinerary across the subsystems covered in +Appendix E. Each step names one or two manual pages and one readable +source file. Take one step per session; do not rush. + +The plan assumes a FreeBSD 14.3 system with a checked-out source tree +under `/usr/src/sys/`. Every manual page is accessible with +`man 9 NAME`, every source file with any text editor. + +--- + +## Step 0: Warm-Up + +- `man 9 intro` +- `ls /usr/src/sys/` and `ls /usr/src/sys/sys/` + +Read `intro(9)` once, then scan the directory listings. You are not +trying to memorise anything; you are trying to *notice* which +subdirectories exist and roughly what they are named after. This is +the map your brain will index against for the rest of the plan. + +## Step 1: Process and Thread + +- `man 9 kthread`, `man 9 kproc`, `man 9 curthread` +- Open `/usr/src/sys/sys/proc.h`; read the comment above `struct proc` + and `struct thread`, then skim their fields. +- Read `/usr/src/sys/dev/random/random_harvestq.c`, focusing on where + it creates and joins its kproc. + +Goal: know what a `struct thread` is, know the difference between +`kthread_add(9)` and `kproc_create(9)`, and recognise the signature +pattern for a driver that spawns a background worker. + +## Step 2: Memory (VM) + +- `man 9 malloc`, `man 9 uma`, `man 9 contigmalloc`, `man 9 bus_dma` +- Open `/usr/src/sys/vm/uma.h` and read the header comment. +- Skim the first page or two of `/usr/src/sys/vm/uma_core.c` to see + what an allocator's init path looks like. + +Goal: know the three allocators drivers reach for (`malloc(9)`, +`uma(9)`, `contigmalloc(9)`), know that `bus_dma(9)` is the portable +DMA wrapper, and know that `pmap(9)` is the architecture-specific +page-table layer you do not normally call directly. + +## Step 3: File and VFS (Character Path) + +- `man 9 cdev`, `man 9 make_dev`, `man 5 devfs` +- Read `/usr/src/sys/dev/null/null.c` end to end. +- Open `/usr/src/sys/fs/devfs/devfs_devs.c` and notice how character + device entries are wired into devfs. + +Goal: understand how a `cdevsw` and a `make_dev_s(9)` call combine +into a visible `/dev` entry, and recognise the structure shape of a +character driver. + +## Step 4: File and VFS (Storage Path) + +- `man 9 g_attach`, `man 9 bio`, `man 4 geom` +- Open `/usr/src/sys/sys/bio.h` and read `struct bio`. +- Open `/usr/src/sys/geom/geom.h` and notice the provider and consumer + typedefs. + +Goal: understand that a storage driver receives `struct bio` +requests on a start routine and calls `g_io_deliver()` when it +finishes them, and recognise the GEOM provider/consumer vocabulary. + +## Step 5: Network + +- `man 9 mbuf`, `man 9 ifnet`, `man 9 ether_ifattach`, `man 4 vnet` +- Open `/usr/src/sys/sys/mbuf.h` and read the `struct mbuf` comment. +- Read `/usr/src/sys/net/if_tuntap.c` end to end if you can. + +Goal: recognise an mbuf chain, understand that a driver publishes +itself as an `ifnet` rather than as a `/dev` entry, and notice how +the transmit and receive paths fit together. + +## Step 6: Driver Infrastructure (Newbus) + +- `man 9 device`, `man 9 driver`, `man 9 DRIVER_MODULE`, + `man 9 bus_alloc_resource`, `man 9 bus_setup_intr` +- Open `/usr/src/sys/sys/bus.h` and skim the macro definitions for + `DEVMETHOD`, `DEVMETHOD_END`, and `DRIVER_MODULE`. +- Read `/usr/src/sys/dev/led/led.c`; note how it declares methods, + registers with `DRIVER_MODULE`, and keeps a softc. + +Goal: recognise the Newbus registration pattern in any driver, +know where `device_t` and softc come from, and know the basic +resource-allocation calls. + +## Step 7: Boot and Module System + +- `man 9 SYSINIT`, `man 9 kld`, `man 9 module`, + `man 9 MODULE_VERSION`, `man 9 MODULE_DEPEND` +- Open `/usr/src/sys/sys/kernel.h` and read the `SYSINIT` comment plus + the `SI_SUB_*` list. +- Skim the beginning of `/usr/src/sys/kern/init_main.c` to see how + `mi_startup()` walks the SYSINIT list. + +Goal: understand how kernel initialisation is ordered, why a driver +may need to declare dependencies with `MODULE_DEPEND`, and how +`DRIVER_MODULE` ties into the module event handler. + +## Step 8: Kernel Services + +- `man 9 eventhandler`, `man 9 taskqueue`, `man 9 callout` +- Open `/usr/src/sys/sys/eventhandler.h` and list the standard event + tags defined near the bottom of the file. +- Re-read the kproc and taskqueue sections of + `/usr/src/sys/dev/random/random_harvestq.c` in that light. + +Goal: know when to reach for an eventhandler, a taskqueue, or a +callout, and know where each one is declared. + +--- + +## Suggested Pacing + +| Step | Approximate time | +| :-------------------------------- | :----------------------- | +| 0. Warm-up | 15 minutes | +| 1. Process and Thread | 30 minutes | +| 2. Memory (VM) | 45 minutes | +| 3. File and VFS (character) | 45 minutes | +| 4. File and VFS (storage) | 45 minutes | +| 5. Network | 60 minutes | +| 6. Driver Infrastructure | 45 minutes | +| 7. Boot and Module System | 30 minutes | +| 8. Kernel Services | 30 minutes | + +Total: around five and a half hours of focused reading, spread across +eight sessions. + +## What to Do After the Plan + +The plan is a skeleton. After step 8 you can take any real driver in +`/usr/src/sys/dev/` and read it with roughly the same questions in +mind: which subsystems does it touch, which structures does it +manipulate, which kernel services does it use, and which parts of the +boot-and-module system does it depend on. Appendix E will keep making +more sense each time, because the same seven subsystems keep showing +up. diff --git a/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/source-tree-navigator.md b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/source-tree-navigator.md new file mode 100644 index 0000000..5f9a48c --- /dev/null +++ b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/source-tree-navigator.md @@ -0,0 +1,120 @@ +# FreeBSD Source-Tree Navigator + +A short guide that turns "it must be somewhere under `/usr/src/sys`" +into "open this file first". Use it when you know the name of a +function, a macro, a structure, or a subsystem, but not yet the file +it lives in. + +## Top-Level Map of `/usr/src/sys/` + +| Directory | What lives here | +| :------------------------- | :-------------------------------------------------------------- | +| `/usr/src/sys/sys/` | Cross-kernel headers: proc, mbuf, vnode, bus, queue, callout | +| `/usr/src/sys/kern/` | Machine-independent kernel core: scheduler, VFS, Newbus, syscalls | +| `/usr/src/sys/vm/` | Virtual-memory subsystem: map, object, page, pagers, UMA | +| `/usr/src/sys/net/` | Network-stack core: ifnet, route, vnet | +| `/usr/src/sys/netinet/` | IPv4 stack | +| `/usr/src/sys/netinet6/` | IPv6 stack | +| `/usr/src/sys/geom/` | GEOM framework and its classes | +| `/usr/src/sys/fs/` | Filesystems: devfs, cd9660, tarfs, tmpfs, fusefs, and so on | +| `/usr/src/sys/dev/` | Device drivers, grouped by bus or device family | +| `/usr/src/sys/amd64/` | Machine-dependent code for amd64 (pmap, boot, interrupts) | +| `/usr/src/sys/arm64/` | Machine-dependent code for arm64 | +| `/usr/src/sys/riscv/` | Machine-dependent code for riscv | +| `/usr/src/sys/modules/` | Per-module build glue (`Makefile`s that drive `bsd.kmod.mk`) | +| `/usr/src/sys/conf/` | Kernel build configuration (`GENERIC`, `MINIMAL`, tunables) | +| `/usr/src/stand/` | The boot loader (in FreeBSD 14.x) | + +## Turning a Question Into a File + +### By function name prefix + +| Prefix | Look first in | +| :--------------------- | :--------------------------------------------------------- | +| `vm_`, `uma_`, `pmap_` | `/usr/src/sys/vm/` | +| `bus_`, `device_`, `driver_`, `devclass_`, `resource_` | `/usr/src/sys/kern/subr_bus.c`, `/usr/src/sys/kern/subr_rman.c` | +| `VOP_`, `vfs_`, `vn_` | `/usr/src/sys/kern/vfs_*.c` or `/usr/src/sys/fs/` | +| `g_` | `/usr/src/sys/geom/` (GEOM) | +| `if_`, `ether_` | `/usr/src/sys/net/` | +| `in_`, `ip_`, `tcp_` | `/usr/src/sys/netinet/` | +| `in6_`, `ip6_` | `/usr/src/sys/netinet6/` | +| `kthread_`, `kproc_`, `sched_`, `proc_` | `/usr/src/sys/kern/` | +| `mtx_`, `sx_`, `rm_`, `lockmgr_` | `/usr/src/sys/kern/kern_mutex.c`, `kern_sx.c`, `kern_rmlock.c`, `kern_lock.c` | +| `callout_` | `/usr/src/sys/kern/kern_timeout.c` | +| `taskqueue_`, `gtaskqueue_` | `/usr/src/sys/kern/subr_taskqueue.c`, `subr_gtaskqueue.c` | +| `eventhandler_` | `/usr/src/sys/kern/subr_eventhandler.c` | +| `kld_`, `linker_` | `/usr/src/sys/kern/kern_linker.c` | +| `make_dev_`, `destroy_dev_` | `/usr/src/sys/kern/kern_conf.c` | +| `m_` (mbuf) | `/usr/src/sys/kern/uipc_mbuf.c`, `/usr/src/sys/kern/kern_mbuf.c` | +| `bio_`, `biodone`, `bwrite` | `/usr/src/sys/kern/vfs_bio.c` | + +When nothing matches, the exhaustive one-liner is: + +```sh +grep -rn '\bFUNC_NAME\s*(' /usr/src/sys/ --include='*.c' --include='*.h' +``` + +### By macro name + +| Macro family | Declared in | +| :--------------------------------------------------- | :---------------------------------------- | +| `SYSINIT`, `SYSUNINIT`, `SI_SUB_*`, `SI_ORDER_*` | `/usr/src/sys/sys/kernel.h` | +| `DRIVER_MODULE`, `DEVMETHOD`, `DEVMETHOD_END`, `EARLY_DRIVER_MODULE` | `/usr/src/sys/sys/bus.h` | +| `MODULE_VERSION`, `MODULE_DEPEND`, `MODULE_METADATA` | `/usr/src/sys/sys/module.h` | +| `EVENTHANDLER_DECLARE`, `_REGISTER`, `_INVOKE` | `/usr/src/sys/sys/eventhandler.h` | +| `VNET_DEFINE`, `VNET_DECLARE`, `CURVNET_SET` | `/usr/src/sys/net/vnet.h` | +| `TAILQ_*`, `LIST_*`, `STAILQ_*`, `SLIST_*` | `/usr/src/sys/sys/queue.h` | +| `RB_*`, `SPLAY_*` | `/usr/src/sys/sys/tree.h` | +| `MALLOC_DEFINE`, `MALLOC_DECLARE` | `/usr/src/sys/sys/malloc.h` | +| `KASSERT`, `MPASS`, `INVARIANTS` | `/usr/src/sys/sys/systm.h` | +| `VOP_*` wrappers | generated in `sys/vnode_if.h` from `/usr/src/sys/kern/vnode_if.src` | + +### By structure name + +See the structure-to-subsystem-index cheatsheet. The short rule is: + +1. Core kernel types start under `/usr/src/sys/sys/`. +2. VM types live under `/usr/src/sys/vm/`. +3. Network types start in `/usr/src/sys/net/` and branch into + `/usr/src/sys/netinet/` and `/usr/src/sys/netinet6/`. +4. Bus types (`device_t`, `resource`, `rman`) live in + `/usr/src/sys/sys/bus.h` and `/usr/src/sys/sys/rman.h`. + +### By question + +| Question | Start here | +| :------------------------------------------------ | :-------------------------------------------- | +| How does the kernel boot? | `/usr/src/sys/kern/init_main.c` | +| How is each subsystem initialised? | Walk the `SYSINIT` list in `init_main.c` | +| How is a new syscall dispatched? | `/usr/src/sys/kern/syscalls.master` and `init_sysent.c` | +| What drivers does FreeBSD ship for PCI? | `ls /usr/src/sys/dev/` (a lot of them) | +| What does `open(2)` on `/dev/null` do? | `/usr/src/sys/dev/null/null.c` and `/usr/src/sys/fs/devfs/` | +| How are interrupts registered? | `/usr/src/sys/kern/subr_intr.c`, `/usr/src/sys/kern/kern_intr.c` | +| Where is the scheduler? | `/usr/src/sys/kern/sched_ule.c` | +| Where does UMA live? | `/usr/src/sys/vm/uma_core.c` | +| Where is the buffer cache? | `/usr/src/sys/kern/vfs_bio.c` | +| Where is the KLD loader? | `/usr/src/sys/kern/kern_linker.c` | + +## Small Readable Drivers + +When the tree feels overwhelming, anchor yourself in one of these +small, self-contained drivers. Each is short enough to read in a +single sitting and representative of its subsystem. + +| Driver | What to notice | +| :------------------------------------------------------ | :---------------------------------------------------- | +| `/usr/src/sys/dev/null/null.c` | The minimal character driver (devfs, cdevsw) | +| `/usr/src/sys/dev/led/led.c` | A small bus-attached driver with sysctl exposure | +| `/usr/src/sys/dev/random/random_harvestq.c` | Real use of kproc, eventhandler, taskqueue | +| `/usr/src/sys/net/if_tuntap.c` | A readable network driver with both tun and tap | +| `/usr/src/sys/dev/uart/uart_bus_pci.c` | How a PCI-attached driver binds to a parent bus | +| `/usr/src/sys/kern/tty_info.c` | The `^T` SIGINFO handler; a short kernel-code read | +| `/usr/src/sys/kern/kern_sig.c` | The real `coredump()` path and signal handling | + +## One-Minute Rule + +If you have been grepping for more than a minute, stop and write down +what you actually know so far. Open the relevant header under +`/usr/src/sys/sys/` or the subsystem directory and re-read the +comment at the top of the file. That comment usually points to the +canonical implementation. diff --git a/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/structure-to-subsystem-index.md b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/structure-to-subsystem-index.md new file mode 100644 index 0000000..25daae1 --- /dev/null +++ b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/structure-to-subsystem-index.md @@ -0,0 +1,106 @@ +# Structure-to-Subsystem Index + +A fast lookup table: when you meet an unfamiliar type in FreeBSD +kernel or driver code, which subsystem owns it, and where is it +declared. Use it as a translator while reading `/usr/src/sys/`. + +The groups below follow Appendix E. Within each group, entries are +listed in the order you are likely to meet them in the book. + +## Process and Thread + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `struct proc` | `/usr/src/sys/sys/proc.h` | One running process: PID, credentials, address space | +| `struct thread` | `/usr/src/sys/sys/proc.h` | One runnable thread of execution | +| `curthread` | `/usr/src/sys/sys/proc.h` (macro) | Pointer to the thread currently executing on this CPU | +| `kthread_add` | `/usr/src/sys/sys/kthread.h` | Add a thread to an existing kernel process | +| `kproc_create` | `/usr/src/sys/sys/kthread.h` | Create a new kernel process with one initial thread | + +## Memory (VM) + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `vm_map_t` | `/usr/src/sys/vm/vm.h`, `/usr/src/sys/vm/vm_map.h` | An address space's mapping list | +| `vm_object_t` | `/usr/src/sys/vm/vm.h`, `/usr/src/sys/vm/vm_object.h` | A backing store of pages | +| `vm_page_t` | `/usr/src/sys/vm/vm.h`, `/usr/src/sys/vm/vm_page.h` | One physical page of RAM | +| `uma_zone_t` | `/usr/src/sys/vm/uma.h` | A slab-backed allocator for a fixed-size object | +| `struct malloc_type` | `/usr/src/sys/sys/malloc.h` | A named accounting bucket for `malloc(9)` | +| `pmap_t` | `/usr/src/sys/vm/pmap.h` | A machine-dependent page-table manager | + +## File and VFS + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `struct vnode` | `/usr/src/sys/sys/vnode.h` | A VFS-level handle to a file, directory, or device | +| `struct vop_vector` | generated from `/usr/src/sys/kern/vnode_if.src` | A per-filesystem vnode-operation dispatch table | +| `struct mount` | `/usr/src/sys/sys/mount.h` | A mounted filesystem | +| `struct cdev` | `/usr/src/sys/sys/conf.h` | A character device node managed by devfs | +| `struct cdevsw` | `/usr/src/sys/sys/conf.h` | A character driver's entry-point table | +| `struct buf` | `/usr/src/sys/sys/buf.h` | A buffer-cache descriptor used by the old block path | +| `struct bio` | `/usr/src/sys/sys/bio.h` | A per-operation block I/O request on the GEOM path | +| `struct g_provider` | `/usr/src/sys/geom/geom.h` | A storage surface a GEOM consumer can attach to | +| `struct g_consumer` | `/usr/src/sys/geom/geom.h` | A GEOM client attached to a provider | + +## Network + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `struct mbuf` | `/usr/src/sys/sys/mbuf.h` | A packet fragment; packets are chains of these | +| `struct m_tag` | `/usr/src/sys/sys/mbuf.h` | Extensible metadata attached to an mbuf | +| `if_t` | `/usr/src/sys/net/if.h` | Modern per-interface descriptor handle | +| `struct ifnet` | `/usr/src/sys/net/if_private.h` | Full per-interface state (legacy view of `if_t`) | +| `struct socket` | `/usr/src/sys/sys/socketvar.h` | Kernel state behind a `socket(2)` file descriptor | +| `ifnet_arrival_event` | `/usr/src/sys/net/if_var.h` | Eventhandler fired when an interface appears | +| `ifnet_departure_event` | `/usr/src/sys/net/if_var.h` | Eventhandler fired when an interface goes away | +| `CURVNET_SET`, `VNET_*` | `/usr/src/sys/net/vnet.h` | Macros for per-VNET state | + +## Driver Infrastructure (Newbus) + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `device_t` | `/usr/src/sys/sys/bus.h` | Opaque handle to a Newbus device-tree node | +| `driver_t` | `/usr/src/sys/sys/bus.h` | Descriptor for a driver: name, methods, softc size | +| `devclass_t` | `/usr/src/sys/sys/bus.h` | Registry of device instances for a driver class | +| `device_method_t` | `/usr/src/sys/sys/bus.h` (kobj) | One entry in a driver's method table | +| `DEVMETHOD`, `DEVMETHOD_END` | `/usr/src/sys/sys/bus.h` | Macros to populate a `device_method_t[]` | +| `DRIVER_MODULE` | `/usr/src/sys/sys/bus.h` | The top-level registration macro for a driver | +| `struct resource` | `/usr/src/sys/sys/rman.h` | An allocated memory, I/O, or IRQ window | +| softc | convention, declared in the driver | Your per-instance driver state | + +## Boot and Module System + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `SYSINIT`, `SYSUNINIT` | `/usr/src/sys/sys/kernel.h` | Register a startup/teardown hook at a specific phase | +| `SI_SUB_*` | `/usr/src/sys/sys/kernel.h` | Coarse phase IDs in the init order | +| `SI_ORDER_*` | `/usr/src/sys/sys/kernel.h` | Fine ordering within a phase | +| `MODULE_VERSION` | `/usr/src/sys/sys/module.h` | Declare this module's ABI version | +| `MODULE_DEPEND` | `/usr/src/sys/sys/module.h` | Declare a required module and its version range | +| `kld_file_t` | `/usr/src/sys/sys/linker.h` | A loaded kernel linker file | + +## Kernel Services + +| Type or name | Declared in | What it represents | +| :------------------------ | :----------------------------------------- | :----------------------------------------------------- | +| `eventhandler_tag` | `/usr/src/sys/sys/eventhandler.h` | A subscription token for an event handler | +| `EVENTHANDLER_REGISTER` | `/usr/src/sys/sys/eventhandler.h` | Subscribe to an event | +| `EVENTHANDLER_DEREGISTER` | `/usr/src/sys/sys/eventhandler.h` | Unsubscribe from an event | +| `struct taskqueue` | `/usr/src/sys/sys/taskqueue.h` | A queue of deferred work items | +| `struct task` | `/usr/src/sys/sys/taskqueue.h` | One work item enqueued on a taskqueue | +| `struct gtaskqueue` | `/usr/src/sys/sys/gtaskqueue.h` | A CPU-affinity-aware grouped taskqueue | +| `struct callout` | `/usr/src/sys/sys/callout.h` | A one-shot or periodic kernel timer | + +## When the Type Is Not Here + +Search the tree with the patterns from the source-tree navigator +cheatsheet. The fastest manual command is: + +```sh +grep -n 'struct NAME {' /usr/src/sys/sys/ /usr/src/sys/kern/ \ + /usr/src/sys/vm/ /usr/src/sys/net/ \ + /usr/src/sys/dev/ +``` + +Nine times out of ten the right header is in one of those +directories. diff --git a/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/subsystem-map.md b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/subsystem-map.md new file mode 100644 index 0000000..48e2714 --- /dev/null +++ b/examples/appendices/appendix-e-navigating-freebsd-kernel-internals/cheatsheets/subsystem-map.md @@ -0,0 +1,87 @@ +# FreeBSD Kernel Subsystem Map + +A single-page view of the seven subsystems a driver author meets most +often in FreeBSD, their responsibilities, and their most characteristic +types. Keep it next to the chapter you are reading. + +## The Big Picture + +``` ++-----------------------------------------------------------------+ +| USER SPACE | +| applications, daemons, shells, tools, the libraries | ++-----------------------------------------------------------------+ + | + system-call trap (the boundary) + | ++-----------------------------------------------------------------+ +| KERNEL SPACE | +| | +| +-----------------------+ +-----------------------------+ | +| | VFS / devfs / GEOM | | Network stack | | +| | vnode, buf, bio, | | mbuf, socket, ifnet, | | +| | vop_vector, cdevsw | | 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 | +| 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 | ++-----------------------------------------------------------------+ +``` + +## The Seven Subsystems at a Glance + +| Subsystem | Responsibility (one line) | Characteristic types | Header entry point | +| :----------------------- | :---------------------------------------------------------- | :----------------------------------------- | :------------------------------------ | +| Process and Thread | Who is running, when, and on which CPU | `struct proc`, `struct thread` | `/usr/src/sys/sys/proc.h` | +| Memory (VM) | Virtual-to-physical mappings, pages, allocators | `vm_map_t`, `vm_object_t`, `vm_page_t`, `uma_zone_t` | `/usr/src/sys/vm/vm.h` | +| File and VFS | Files, devices in `/dev`, GEOM stacks, buffer cache | `struct vnode`, `vop_vector`, `struct bio`, `struct buf` | `/usr/src/sys/sys/vnode.h` | +| Network | Packet movement, interfaces, sockets, VNETs | `struct mbuf`, `ifnet` / `if_t`, `struct socket` | `/usr/src/sys/sys/mbuf.h` | +| Driver Infrastructure | Newbus: the device tree and the driver binding machinery | `device_t`, `driver_t`, `devclass_t`, softc | `/usr/src/sys/sys/bus.h` | +| Boot and Module System | How the kernel starts and how modules come and go | `SYSINIT`, `SI_SUB_*`, `MODULE_DEPEND` | `/usr/src/sys/sys/kernel.h`, `/usr/src/sys/sys/module.h` | +| Kernel Services | Cross-cutting services: events, deferred work, timers | `eventhandler_tag`, `struct taskqueue`, `struct callout` | `/usr/src/sys/sys/eventhandler.h` | + +## When Each Subsystem Shows Up + +| You are about to... | You are about to touch... | +| :------------------------------------------------ | :------------------------------------ | +| Allocate memory for a softc or a buffer | Memory (VM) | +| Create or destroy a kernel worker thread | Process and Thread | +| Publish a `/dev` entry | File and VFS (devfs, cdevsw) | +| Accept a block I/O request from a filesystem | File and VFS (GEOM, struct bio) | +| Register a network interface | Network (ifnet) | +| Receive or transmit a packet | Network (mbuf, ifnet) | +| Match a driver to a PCI or USB device | Driver Infrastructure (Newbus) | +| Declare a dependency on another module | Boot and Module System | +| Run a hook at kernel shutdown or at low memory | Kernel Services (eventhandler) | +| Defer work out of an interrupt filter | Kernel Services (taskqueue) | +| Arm a watchdog timer | Kernel Services (callout) | + +## Pattern to Remember + +Every driver begins in Driver Infrastructure (Newbus), borrows from +Memory (VM) for its state, borrows from Process and Thread for the +threads it runs on, and then *publishes itself* to one (or more) of +three subsystems on top: File and VFS for character or storage +drivers, Network for interface drivers, or a specialised framework +(input, sound, crypto) that itself sits on one of those layers. +Kernel Services and the Boot and Module System are the cross-cutting +helpers underneath all of them. + +When a piece of code feels unfamiliar, ask: *which of the seven +subsystems is it in?* Once you can answer that, the rest follows. diff --git a/examples/appendices/appendix-f-benchmarks/dtrace/Makefile b/examples/appendices/appendix-f-benchmarks/dtrace/Makefile new file mode 100644 index 0000000..02b6d31 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/dtrace/Makefile @@ -0,0 +1,28 @@ +# Makefile for Appendix F DTrace / INVARIANTS / WITNESS overhead +# workloads. +# +# Build with BSD make on FreeBSD 14.3-amd64: +# make +# Run (root only for DTrace): +# sh run_overhead_suite.sh +# dtrace -q -s dtrace_overhead.d # in another terminal +# Clean: +# make clean + +CC?= cc +CFLAGS?= -O2 -Wall -Wextra -pedantic -std=c11 + +PROGS= workload_syscalls workload_locks + +all: ${PROGS} + +workload_syscalls: workload_syscalls.c + ${CC} ${CFLAGS} -o $@ workload_syscalls.c + +workload_locks: workload_locks.c + ${CC} ${CFLAGS} -o $@ workload_locks.c -lpthread + +clean: + rm -f ${PROGS} + +.PHONY: all clean diff --git a/examples/appendices/appendix-f-benchmarks/dtrace/dtrace_overhead.d b/examples/appendices/appendix-f-benchmarks/dtrace/dtrace_overhead.d new file mode 100644 index 0000000..dfc764e --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/dtrace/dtrace_overhead.d @@ -0,0 +1,33 @@ +/* + * dtrace_overhead.d - a probe-only DTrace script used to measure + * the per-syscall overhead of attaching DTrace. + * + * The script fires on every syscall entry and return but does not + * print anything per probe. At exit it prints the total counts. + * Attach it while the workload programs run and compare their + * wall-clock times to the baseline. + * + * Usage (as root): + * dtrace -q -s dtrace_overhead.d + * + * Ctrl-C when the workload finishes. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +syscall:::entry +{ + @entries = count(); +} + +syscall:::return +{ + @returns = count(); +} + +END +{ + printa("entries=%@d\n", @entries); + printa("returns=%@d\n", @returns); +} diff --git a/examples/appendices/appendix-f-benchmarks/dtrace/run_overhead_suite.sh b/examples/appendices/appendix-f-benchmarks/dtrace/run_overhead_suite.sh new file mode 100755 index 0000000..65bbec2 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/dtrace/run_overhead_suite.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# +# run_overhead_suite.sh - run the workload programs and print +# their reports, tagged with the current uname and kernel config. +# +# Intended to be run four times: once on a base kernel, once on an +# INVARIANTS kernel, once on a WITNESS kernel, and once on any of +# them with dtrace_overhead.d attached. Compare the result files +# afterward. +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +if [ ! -x ./workload_syscalls ] || [ ! -x ./workload_locks ]; then + echo "error: build the workloads first (run 'make')" >&2 + exit 1 +fi + +# Capture as much of the kernel context as is easy to grab. +echo "# host: $(hostname)" +echo "# uname: $(uname -rmp)" +if sysctl kern.conftxt >/dev/null 2>&1; then + invariants=$(sysctl -n kern.conftxt 2>/dev/null | \ + grep -c '^options.*INVARIANTS$' || true) + witness=$(sysctl -n kern.conftxt 2>/dev/null | \ + grep -c '^options.*WITNESS$' || true) + echo "# kernel_has_INVARIANTS=${invariants}" + echo "# kernel_has_WITNESS=${witness}" +fi +echo "" + +echo "=== syscalls workload ===" +./workload_syscalls +echo "" + +echo "=== locks workload ===" +./workload_locks +echo "" + +echo "# done" diff --git a/examples/appendices/appendix-f-benchmarks/dtrace/workload_locks.c b/examples/appendices/appendix-f-benchmarks/dtrace/workload_locks.c new file mode 100644 index 0000000..fb01dc6 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/dtrace/workload_locks.c @@ -0,0 +1,122 @@ +/* + * workload_locks.c - a lock-heavy multithreaded workload. + * + * Spawns a small pool of threads that repeatedly lock and unlock a + * small set of pthread_mutexes in a rotating pattern. Userland + * pthread_mutex ultimately rides on the kernel's lock primitives + * (via umtx syscalls when contended), so a lock-heavy userland + * workload amplifies the per-lock cost of kernel lock primitives + * in the contention path, and the WITNESS/INVARIANTS overheads + * that sit on top of them. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_THREADS 4 +#define DEFAULT_ITER_PER_THR 10000000ULL +#define NUM_LOCKS 4 + +static pthread_mutex_t locks[NUM_LOCKS]; +static uint64_t per_thread_iter; + +static void * +worker(void *arg) +{ + int tid = (int)(uintptr_t)arg; + uint64_t i; + uint64_t sum = 0; + + for (i = 0; i < per_thread_iter; i++) { + int slot = (tid + i) % NUM_LOCKS; + + if (pthread_mutex_lock(&locks[slot]) != 0) + err(1, "pthread_mutex_lock"); + sum += i; + if (pthread_mutex_unlock(&locks[slot]) != 0) + err(1, "pthread_mutex_unlock"); + } + + return ((void *)(uintptr_t)sum); +} + +static uint64_t +ns_between(const struct timespec *start, const struct timespec *end) +{ + return ((uint64_t)(end->tv_sec - start->tv_sec) * 1000000000ULL + + (uint64_t)(end->tv_nsec - start->tv_nsec)); +} + +int +main(int argc, char **argv) +{ + int nthreads = DEFAULT_THREADS; + uint64_t iter = DEFAULT_ITER_PER_THR; + pthread_t *ts; + struct timespec ts_start, ts_end; + uint64_t total_ns, total_iter; + int i; + + if (argc > 1) + nthreads = atoi(argv[1]); + if (argc > 2) + iter = strtoull(argv[2], NULL, 10); + per_thread_iter = iter; + + if (nthreads < 1 || nthreads > 1024) + errx(1, "threads out of range"); + + for (i = 0; i < NUM_LOCKS; i++) { + if (pthread_mutex_init(&locks[i], NULL) != 0) + err(1, "pthread_mutex_init"); + } + + ts = calloc(nthreads, sizeof(pthread_t)); + if (ts == NULL) + err(1, "calloc"); + + printf("# workload=locks threads=%d iter_per_thread=%" PRIu64 "\n", + nthreads, iter); + + if (clock_gettime(CLOCK_MONOTONIC, &ts_start) != 0) + err(1, "clock_gettime start"); + + for (i = 0; i < nthreads; i++) { + if (pthread_create(&ts[i], NULL, worker, + (void *)(uintptr_t)i) != 0) + err(1, "pthread_create"); + } + for (i = 0; i < nthreads; i++) { + if (pthread_join(ts[i], NULL) != 0) + err(1, "pthread_join"); + } + + if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) + err(1, "clock_gettime end"); + + total_ns = ns_between(&ts_start, &ts_end); + total_iter = (uint64_t)nthreads * iter; + + printf("wall_ns=%" PRIu64 "\n", total_ns); + printf("total_ops=%" PRIu64 "\n", total_iter); + printf("per_op_ns=%.2f\n", + (double)total_ns / (double)total_iter); + + free(ts); + for (i = 0; i < NUM_LOCKS; i++) + pthread_mutex_destroy(&locks[i]); + + return (0); +} diff --git a/examples/appendices/appendix-f-benchmarks/dtrace/workload_syscalls.c b/examples/appendices/appendix-f-benchmarks/dtrace/workload_syscalls.c new file mode 100644 index 0000000..2a10832 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/dtrace/workload_syscalls.c @@ -0,0 +1,72 @@ +/* + * workload_syscalls.c - a tight syscall-call loop. + * + * Hammers the kernel's syscall entry and exit path with a mix of + * trivial system calls. Intended to be run under several kernel + * conditions (base, INVARIANTS, WITNESS, active DTrace) so the + * reader can compare wall-clock times and see the per-condition + * overhead. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_ITERATIONS 1000000ULL + +static uint64_t +ns_between(const struct timespec *start, const struct timespec *end) +{ + return ((uint64_t)(end->tv_sec - start->tv_sec) * 1000000000ULL + + (uint64_t)(end->tv_nsec - start->tv_nsec)); +} + +int +main(int argc, char **argv) +{ + uint64_t iterations = DEFAULT_ITERATIONS; + struct timespec ts_start, ts_end, ts_loop; + struct timeval tv_loop; + uint64_t i, total_ns, sum = 0; + pid_t pid; + uid_t uid; + + if (argc > 1) + iterations = strtoull(argv[1], NULL, 10); + + printf("# workload=syscalls iterations=%" PRIu64 "\n", iterations); + + if (clock_gettime(CLOCK_MONOTONIC, &ts_start) != 0) + err(1, "clock_gettime start"); + + for (i = 0; i < iterations; i++) { + pid = getpid(); + uid = getuid(); + if (gettimeofday(&tv_loop, NULL) != 0) + err(1, "gettimeofday"); + if (clock_gettime(CLOCK_MONOTONIC, &ts_loop) != 0) + err(1, "clock_gettime inner"); + sum += (uint64_t)pid + (uint64_t)uid + + (uint64_t)tv_loop.tv_usec + (uint64_t)ts_loop.tv_nsec; + } + + if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) + err(1, "clock_gettime end"); + + total_ns = ns_between(&ts_start, &ts_end); + printf("wall_ns=%" PRIu64 "\n", total_ns); + printf("per_iter_ns=%.2f\n", (double)total_ns / (double)iterations); + printf("# sum=0x%" PRIx64 " # prevent loop elimination\n", sum); + + return (0); +} diff --git a/examples/appendices/appendix-f-benchmarks/iflib/compare_iflib_corpus.sh b/examples/appendices/appendix-f-benchmarks/iflib/compare_iflib_corpus.sh new file mode 100755 index 0000000..d9667bc --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/iflib/compare_iflib_corpus.sh @@ -0,0 +1,99 @@ +#!/bin/sh +# +# compare_iflib_corpus.sh - walk two curated lists of Ethernet +# driver source files (one iflib-based, one plain-ifnet) and print +# a comparison table plus an aggregate ratio. +# +# Usage: sh compare_iflib_corpus.sh [SRC_ROOT] +# SRC_ROOT defaults to /usr/src. +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +SRC_ROOT=${1:-/usr/src} + +# Drivers that use iflib. Verified by 'grep -l IFDI_ if_*.c'. +CORPUS_IFLIB=" +sys/dev/e1000/if_em.c +sys/dev/ixgbe/if_ix.c +sys/dev/igc/if_igc.c +sys/dev/vmware/vmxnet3/if_vmx.c +" + +# Drivers that do not use iflib. Chosen to span a similar range of +# hardware classes. +CORPUS_PLAIN=" +sys/dev/re/if_re.c +sys/dev/bge/if_bge.c +sys/dev/fxp/if_fxp.c +" + +HERE=$(cd "$(dirname "$0")" && pwd) + +walk_corpus() { + label=$1 + files=$2 + + total_raw=0 + total_code=0 + count=0 + + printf "=== %s ===\n" "${label}" >&2 + for rel in ${files}; do + path="${SRC_ROOT}/${rel}" + if [ ! -f "${path}" ]; then + printf " %s (missing)\n" "${rel}" >&2 + continue + fi + out=$(sh "${HERE}/count_driver_lines.sh" "${path}") + printf " %s\n" "${out}" >&2 + raw=$(echo "${out}" | awk '{print $2}' | cut -d= -f2) + code=$(echo "${out}" | awk '{print $4}' | cut -d= -f2) + total_raw=$((total_raw + raw)) + total_code=$((total_code + code)) + count=$((count + 1)) + done + if [ ${count} -gt 0 ]; then + avg_raw=$((total_raw / count)) + avg_code=$((total_code / count)) + else + avg_raw=0 + avg_code=0 + fi + { + printf " ---\n" + printf " corpus=%s drivers=%d total_raw=%d total_code=%d avg_raw=%d avg_code=%d\n" \ + "${label}" "${count}" "${total_raw}" "${total_code}" \ + "${avg_raw}" "${avg_code}" + echo "" + } >&2 + + echo "${avg_code}" +} + +echo "# SRC_ROOT=${SRC_ROOT}" +echo "# uname=$(uname -rmp 2>/dev/null || echo 'unknown')" +echo "" + +avg_iflib=$(walk_corpus "iflib" "${CORPUS_IFLIB}" | tail -1) +avg_plain=$(walk_corpus "plain-ifnet" "${CORPUS_PLAIN}" | tail -1) + +# Summary. +if [ "${avg_plain}" -gt 0 ] && [ "${avg_iflib}" -gt 0 ]; then + # ratio_percent = 100 * (plain - iflib) / plain + delta=$((avg_plain - avg_iflib)) + pct=$((100 * delta / avg_plain)) + echo "=== summary ===" + echo " iflib avg code lines: ${avg_iflib}" + echo " plain-ifnet avg code lines: ${avg_plain}" + echo " delta: ${delta}" + echo " reduction: ${pct}%" + echo "" + echo " Caveat: raw file size is a noisy proxy for driver" + echo " complexity. A fair per-driver comparison requires the" + echo " before/after conversion diff, which needs Git history." + echo " Run git_conversion_delta.sh on a full freebsd-src.git" + echo " clone for that measurement." +fi diff --git a/examples/appendices/appendix-f-benchmarks/iflib/count_driver_lines.sh b/examples/appendices/appendix-f-benchmarks/iflib/count_driver_lines.sh new file mode 100755 index 0000000..935ffc4 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/iflib/count_driver_lines.sh @@ -0,0 +1,60 @@ +#!/bin/sh +# +# count_driver_lines.sh - emit line counts for one driver source +# file, with three figures: +# raw total wc -l output. +# nonblank lines that contain at least one non-whitespace character. +# code lines that are neither blank nor a pure C comment. +# +# Usage: sh count_driver_lines.sh /path/to/if_foo.c +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +if [ $# -ne 1 ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +file=$1 + +if [ ! -f "${file}" ]; then + echo "error: ${file} does not exist" >&2 + exit 1 +fi + +raw=$(wc -l < "${file}" | tr -d ' ') +nonblank=$(grep -c -v '^[[:space:]]*$' "${file}" || true) + +# Strip C comments with a simple awk pass, then count non-blank. +# This is not a full C parser; it drops /* ... */ blocks (including +# multi-line) and // ... end-of-line comments. Good enough for the +# order-of-magnitude comparison the appendix is after. +code=$(awk ' + BEGIN { in_block = 0 } + { + line = $0 + out = "" + i = 1 + while (i <= length(line)) { + if (in_block) { + j = index(substr(line, i), "*/") + if (j == 0) { i = length(line) + 1 } + else { in_block = 0; i = i + j + 1 } + continue + } + c2 = substr(line, i, 2) + if (c2 == "/*") { in_block = 1; i += 2; continue } + if (c2 == "//") { break } + out = out substr(line, i, 1) + i++ + } + if (out ~ /[^[:space:]]/) count++ + } + END { print count + 0 } +' "${file}") + +printf "%s\traw=%s\tnonblank=%s\tcode=%s\n" \ + "${file}" "${raw}" "${nonblank}" "${code}" diff --git a/examples/appendices/appendix-f-benchmarks/iflib/git_conversion_delta.sh b/examples/appendices/appendix-f-benchmarks/iflib/git_conversion_delta.sh new file mode 100755 index 0000000..bb3046c --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/iflib/git_conversion_delta.sh @@ -0,0 +1,108 @@ +#!/bin/sh +# +# git_conversion_delta.sh - look up the commit that converted a +# specific Ethernet driver to iflib and report the line-count delta +# at that commit. +# +# Needs a full FreeBSD-src Git clone with history. Run against the +# top of the clone. +# +# Usage: sh git_conversion_delta.sh +# e.g.: sh git_conversion_delta.sh /srv/freebsd-src if_em.c +# +# Heuristic: the conversion commit is the one whose subject mentions +# "iflib" AND touches the target file with a large net deletion or +# rewrite. +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +if [ $# -ne 2 ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +repo=$1 +base=$2 + +if [ ! -d "${repo}/.git" ]; then + echo "error: ${repo} is not a Git working copy" >&2 + exit 1 +fi + +cd "${repo}" + +# Find the best candidate commit. +commits=$(git log --all --oneline --grep='iflib' -- "*/${base}" 2>/dev/null | head -20) +if [ -z "${commits}" ]; then + echo "no iflib-related commits touch ${base}" >&2 + exit 1 +fi + +echo "# candidate commits touching ${base} with 'iflib' in the log:" +echo "${commits}" | sed 's/^/ /' +echo "" + +# Pick the largest-diff candidate. +best_sha="" +best_touched=0 +for sha in $(echo "${commits}" | awk '{print $1}'); do + touched=$(git show --numstat "${sha}" 2>/dev/null | \ + awk -v base="${base}" '$3 ~ base { print $1 + $2 }' | head -1) + if [ -z "${touched}" ]; then + continue + fi + if [ "${touched}" -gt "${best_touched}" ]; then + best_touched=${touched} + best_sha=${sha} + fi +done + +if [ -z "${best_sha}" ]; then + echo "no large-diff candidate found" >&2 + exit 1 +fi + +echo "# best candidate: ${best_sha} (touched ${best_touched} lines)" +echo "" + +# Before and after line counts for that path. +path=$(git show --name-only "${best_sha}" | grep "/${base}$" | head -1) +if [ -z "${path}" ]; then + echo "could not resolve path in the commit" >&2 + exit 1 +fi + +before_sha=$(git rev-parse "${best_sha}^" 2>/dev/null || echo "") +if [ -n "${before_sha}" ]; then + before_lines=$(git show "${before_sha}:${path}" 2>/dev/null | wc -l | tr -d ' ') +else + before_lines=0 +fi +after_lines=$(git show "${best_sha}:${path}" 2>/dev/null | wc -l | tr -d ' ') + +if [ "${before_lines}" -gt 0 ] && [ "${after_lines}" -gt 0 ]; then + delta=$((before_lines - after_lines)) + if [ "${delta}" -gt 0 ]; then + pct=$((100 * delta / before_lines)) + change="reduction" + else + pct=$((100 * -delta / before_lines)) + change="growth" + fi +else + delta=0 + pct=0 + change="n/a" +fi + +echo "=== ${base} conversion commit summary ===" +echo " commit: ${best_sha}" +echo " path: ${path}" +echo " before: ${before_lines} lines" +echo " after: ${after_lines} lines" +echo " delta: ${delta} (${pct}% ${change})" +echo "" +echo "# inspect with: git show ${best_sha}" diff --git a/examples/appendices/appendix-f-benchmarks/sync/Makefile b/examples/appendices/appendix-f-benchmarks/sync/Makefile new file mode 100644 index 0000000..3a60cad --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/sync/Makefile @@ -0,0 +1,16 @@ +# Makefile for the Appendix F sync_bench kmod. +# +# Build on FreeBSD 14.3-amd64 with the kernel source under +# /usr/src: +# make +# Load and use: +# kldload ./sync_bench.ko +# sh run_sync_bench.sh +# kldunload sync_bench +# Clean: +# make clean + +KMOD= sync_bench +SRCS= sync_bench.c + +.include diff --git a/examples/appendices/appendix-f-benchmarks/sync/run_sync_bench.sh b/examples/appendices/appendix-f-benchmarks/sync/run_sync_bench.sh new file mode 100755 index 0000000..44c110e --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/sync/run_sync_bench.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# +# run_sync_bench.sh - trigger every sync_bench benchmark and print +# the results as a small table. +# +# Must be run as root, after kldload ./sync_bench.ko succeeds. +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +if [ "$(id -u)" -ne 0 ]; then + echo "error: must run as root" >&2 + exit 1 +fi + +if ! kldstat -n sync_bench >/dev/null 2>&1; then + echo "error: sync_bench is not loaded; kldload ./sync_bench.ko first" >&2 + exit 1 +fi + +run_one() { + label=$1 + trigger=$2 + sysctl_ns=$3 + + sysctl -w "debug.sync_bench.${trigger}=1" >/dev/null + ns=$(sysctl -n "debug.sync_bench.${sysctl_ns}") + printf "%-30s %s ns\n" "${label}" "${ns}" +} + +echo "# host: $(hostname)" +echo "# uname: $(uname -rmp)" +echo "" + +run_one "mtx_lock (uncontended)" run_mtx last_ns_mtx +run_one "sx_slock (uncontended)" run_sx_slock last_ns_sx_slock +run_one "sx_xlock (uncontended)" run_sx_xlock last_ns_sx_xlock +run_one "cv round-trip" run_cv last_ns_cv +run_one "sema round-trip" run_sema last_ns_sema + +echo "" +echo "# done; dmesg has the per-run iteration counts" diff --git a/examples/appendices/appendix-f-benchmarks/sync/sync_bench.c b/examples/appendices/appendix-f-benchmarks/sync/sync_bench.c new file mode 100644 index 0000000..3473069 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/sync/sync_bench.c @@ -0,0 +1,299 @@ +/* + * sync_bench.c - in-kernel microbenchmark for FreeBSD synchronization + * primitives. + * + * Builds as a loadable kernel module. Exposes a small set of sysctls + * under debug.sync_bench.* that trigger benchmarks and report + * results. + * + * Writes trigger the benchmark; reads expose last measured nanosecond + * average. Iterations are fixed per benchmark and reported in the + * module's dmesg output. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SB_MTX_ITER 1000000ULL +#define SB_SX_ITER 1000000ULL +#define SB_CV_ITER 10000ULL +#define SB_SEMA_ITER 10000ULL + +static struct mtx sb_mtx; +static struct sx sb_sx; +static struct mtx sb_cv_mtx; +static struct cv sb_cv_ping; +static struct cv sb_cv_pong; +static struct sema sb_sema_ping; +static struct sema sb_sema_pong; + +static uint64_t sb_last_ns_mtx; +static uint64_t sb_last_ns_sx_slock; +static uint64_t sb_last_ns_sx_xlock; +static uint64_t sb_last_ns_cv; +static uint64_t sb_last_ns_sema; + +static volatile int sb_cv_running; +static volatile int sb_sema_running; +static struct proc *sb_cv_worker; +static struct proc *sb_sema_worker; + +static uint64_t +sbt_to_ns(sbintime_t sbt) +{ + return ((uint64_t)sbttons(sbt)); +} + +static void +sb_run_mtx(void) +{ + sbintime_t start, end; + uint64_t i; + + start = sbinuptime(); + for (i = 0; i < SB_MTX_ITER; i++) { + mtx_lock(&sb_mtx); + mtx_unlock(&sb_mtx); + } + end = sbinuptime(); + sb_last_ns_mtx = sbt_to_ns(end - start) / SB_MTX_ITER; + printf("sync_bench: mtx uncontended avg=%ju ns (%ju iter)\n", + (uintmax_t)sb_last_ns_mtx, (uintmax_t)SB_MTX_ITER); +} + +static void +sb_run_sx_slock(void) +{ + sbintime_t start, end; + uint64_t i; + + start = sbinuptime(); + for (i = 0; i < SB_SX_ITER; i++) { + sx_slock(&sb_sx); + sx_sunlock(&sb_sx); + } + end = sbinuptime(); + sb_last_ns_sx_slock = sbt_to_ns(end - start) / SB_SX_ITER; + printf("sync_bench: sx_slock uncontended avg=%ju ns (%ju iter)\n", + (uintmax_t)sb_last_ns_sx_slock, (uintmax_t)SB_SX_ITER); +} + +static void +sb_run_sx_xlock(void) +{ + sbintime_t start, end; + uint64_t i; + + start = sbinuptime(); + for (i = 0; i < SB_SX_ITER; i++) { + sx_xlock(&sb_sx); + sx_xunlock(&sb_sx); + } + end = sbinuptime(); + sb_last_ns_sx_xlock = sbt_to_ns(end - start) / SB_SX_ITER; + printf("sync_bench: sx_xlock uncontended avg=%ju ns (%ju iter)\n", + (uintmax_t)sb_last_ns_sx_xlock, (uintmax_t)SB_SX_ITER); +} + +static void +sb_cv_worker_loop(void *arg __unused) +{ + mtx_lock(&sb_cv_mtx); + while (sb_cv_running) { + cv_wait(&sb_cv_ping, &sb_cv_mtx); + if (!sb_cv_running) + break; + cv_signal(&sb_cv_pong); + } + mtx_unlock(&sb_cv_mtx); + kproc_exit(0); +} + +static void +sb_run_cv(void) +{ + sbintime_t start, end; + uint64_t i; + int err; + + sb_cv_running = 1; + err = kproc_create(sb_cv_worker_loop, NULL, &sb_cv_worker, 0, 0, + "sync_bench_cv"); + if (err != 0) { + printf("sync_bench: kproc_create failed: %d\n", err); + return; + } + + /* Let the worker reach cv_wait. */ + pause("sbcvup", hz / 10); + + mtx_lock(&sb_cv_mtx); + start = sbinuptime(); + for (i = 0; i < SB_CV_ITER; i++) { + cv_signal(&sb_cv_ping); + cv_wait(&sb_cv_pong, &sb_cv_mtx); + } + end = sbinuptime(); + + sb_cv_running = 0; + cv_broadcast(&sb_cv_ping); + mtx_unlock(&sb_cv_mtx); + + /* Wait for the worker to exit. */ + pause("sbcvdn", hz / 10); + + sb_last_ns_cv = sbt_to_ns(end - start) / SB_CV_ITER; + printf("sync_bench: cv round-trip avg=%ju ns (%ju iter)\n", + (uintmax_t)sb_last_ns_cv, (uintmax_t)SB_CV_ITER); +} + +static void +sb_sema_worker_loop(void *arg __unused) +{ + while (sb_sema_running) { + sema_wait(&sb_sema_ping); + if (!sb_sema_running) + break; + sema_post(&sb_sema_pong); + } + kproc_exit(0); +} + +static void +sb_run_sema(void) +{ + sbintime_t start, end; + uint64_t i; + int err; + + sb_sema_running = 1; + err = kproc_create(sb_sema_worker_loop, NULL, &sb_sema_worker, 0, 0, + "sync_bench_sema"); + if (err != 0) { + printf("sync_bench: kproc_create failed: %d\n", err); + return; + } + + /* Let the worker reach sema_wait. */ + pause("sbseup", hz / 10); + + start = sbinuptime(); + for (i = 0; i < SB_SEMA_ITER; i++) { + sema_post(&sb_sema_ping); + sema_wait(&sb_sema_pong); + } + end = sbinuptime(); + + sb_sema_running = 0; + sema_post(&sb_sema_ping); + + pause("sbsedn", hz / 10); + + sb_last_ns_sema = sbt_to_ns(end - start) / SB_SEMA_ITER; + printf("sync_bench: sema round-trip avg=%ju ns (%ju iter)\n", + (uintmax_t)sb_last_ns_sema, (uintmax_t)SB_SEMA_ITER); +} + +/* sysctl: writing non-zero triggers a run; reading returns 0. */ +#define SB_TRIGGER(name, runfn) \ +static int \ +sb_sysctl_run_##name(SYSCTL_HANDLER_ARGS) \ +{ \ + int val = 0; \ + int error; \ + \ + error = sysctl_handle_int(oidp, &val, 0, req); \ + if (error != 0 || req->newptr == NULL) \ + return (error); \ + if (val != 0) \ + runfn(); \ + return (0); \ +} + +SB_TRIGGER(mtx, sb_run_mtx) +SB_TRIGGER(sx_slock, sb_run_sx_slock) +SB_TRIGGER(sx_xlock, sb_run_sx_xlock) +SB_TRIGGER(cv, sb_run_cv) +SB_TRIGGER(sema, sb_run_sema) + +static SYSCTL_NODE(_debug, OID_AUTO, sync_bench, + CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, + "Appendix F synchronization-primitive benchmarks"); + +SYSCTL_PROC(_debug_sync_bench, OID_AUTO, run_mtx, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + sb_sysctl_run_mtx, "I", "Run mtx uncontended benchmark"); +SYSCTL_PROC(_debug_sync_bench, OID_AUTO, run_sx_slock, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + sb_sysctl_run_sx_slock, "I", "Run sx_slock uncontended benchmark"); +SYSCTL_PROC(_debug_sync_bench, OID_AUTO, run_sx_xlock, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + sb_sysctl_run_sx_xlock, "I", "Run sx_xlock uncontended benchmark"); +SYSCTL_PROC(_debug_sync_bench, OID_AUTO, run_cv, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + sb_sysctl_run_cv, "I", "Run cv round-trip benchmark"); +SYSCTL_PROC(_debug_sync_bench, OID_AUTO, run_sema, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + sb_sysctl_run_sema, "I", "Run sema round-trip benchmark"); + +SYSCTL_QUAD(_debug_sync_bench, OID_AUTO, last_ns_mtx, CTLFLAG_RD, + &sb_last_ns_mtx, 0, "Average ns per mtx_lock/unlock"); +SYSCTL_QUAD(_debug_sync_bench, OID_AUTO, last_ns_sx_slock, CTLFLAG_RD, + &sb_last_ns_sx_slock, 0, "Average ns per sx_slock/sunlock"); +SYSCTL_QUAD(_debug_sync_bench, OID_AUTO, last_ns_sx_xlock, CTLFLAG_RD, + &sb_last_ns_sx_xlock, 0, "Average ns per sx_xlock/xunlock"); +SYSCTL_QUAD(_debug_sync_bench, OID_AUTO, last_ns_cv, CTLFLAG_RD, + &sb_last_ns_cv, 0, "Average ns per cv round-trip"); +SYSCTL_QUAD(_debug_sync_bench, OID_AUTO, last_ns_sema, CTLFLAG_RD, + &sb_last_ns_sema, 0, "Average ns per sema round-trip"); + +static int +sync_bench_load(module_t m __unused, int what, void *arg __unused) +{ + switch (what) { + case MOD_LOAD: + mtx_init(&sb_mtx, "sync_bench_mtx", NULL, MTX_DEF); + sx_init(&sb_sx, "sync_bench_sx"); + mtx_init(&sb_cv_mtx, "sync_bench_cv_mtx", NULL, MTX_DEF); + cv_init(&sb_cv_ping, "sync_bench_cv_ping"); + cv_init(&sb_cv_pong, "sync_bench_cv_pong"); + sema_init(&sb_sema_ping, 0, "sync_bench_sema_ping"); + sema_init(&sb_sema_pong, 0, "sync_bench_sema_pong"); + printf("sync_bench: loaded\n"); + return (0); + case MOD_UNLOAD: + sema_destroy(&sb_sema_ping); + sema_destroy(&sb_sema_pong); + cv_destroy(&sb_cv_ping); + cv_destroy(&sb_cv_pong); + mtx_destroy(&sb_cv_mtx); + sx_destroy(&sb_sx); + mtx_destroy(&sb_mtx); + printf("sync_bench: unloaded\n"); + return (0); + } + return (EOPNOTSUPP); +} + +static moduledata_t sync_bench_mod = { + "sync_bench", + sync_bench_load, + NULL, +}; + +DECLARE_MODULE(sync_bench, sync_bench_mod, SI_SUB_KLD, SI_ORDER_ANY); +MODULE_VERSION(sync_bench, 1); diff --git a/examples/appendices/appendix-f-benchmarks/timecounter/Makefile b/examples/appendices/appendix-f-benchmarks/timecounter/Makefile new file mode 100644 index 0000000..2a99486 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/timecounter/Makefile @@ -0,0 +1,27 @@ +# Makefile for Appendix F timecounter benchmarks. +# +# Build with BSD make on FreeBSD 14.3-amd64: +# make +# Run (requires root for the rotation script): +# sh run_tc_bench.sh +# ./rdtsc_bench +# Clean up: +# make clean + +CC?= cc +CFLAGS?= -O2 -Wall -Wextra -pedantic -std=c11 + +PROGS= tc_bench rdtsc_bench + +all: ${PROGS} + +tc_bench: tc_bench.c + ${CC} ${CFLAGS} -o $@ tc_bench.c + +rdtsc_bench: rdtsc_bench.c + ${CC} ${CFLAGS} -o $@ rdtsc_bench.c + +clean: + rm -f ${PROGS} + +.PHONY: all clean diff --git a/examples/appendices/appendix-f-benchmarks/timecounter/rdtsc_bench.c b/examples/appendices/appendix-f-benchmarks/timecounter/rdtsc_bench.c new file mode 100644 index 0000000..f7d4477 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/timecounter/rdtsc_bench.c @@ -0,0 +1,90 @@ +/* + * rdtsc_bench.c - measure the cost of the rdtsc instruction itself. + * + * On an amd64 system with invariant TSC (essentially every CPU from + * the mid-2000s onward) the TSC is the floor under which no other + * timecounter can go. This program reads rdtsc in a tight loop and + * reports the average cost per read in CPU cycles and nanoseconds. + * + * The nanosecond conversion uses clock_gettime(CLOCK_MONOTONIC) to + * calibrate TSC frequency against wall-clock time. On hosts without + * invariant TSC the calibration is noisy and the output should be + * treated as a rough order-of-magnitude figure only. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_ITERATIONS 100000000ULL +#define DEFAULT_WARMUP 10000000ULL + +static inline uint64_t +read_tsc(void) +{ + uint32_t lo, hi; + + __asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi)); + return (((uint64_t)hi << 32) | lo); +} + +static uint64_t +ns_between(const struct timespec *start, const struct timespec *end) +{ + return ((uint64_t)(end->tv_sec - start->tv_sec) * 1000000000ULL + + (uint64_t)(end->tv_nsec - start->tv_nsec)); +} + +int +main(int argc, char **argv) +{ + uint64_t iterations = DEFAULT_ITERATIONS; + uint64_t warmup = DEFAULT_WARMUP; + struct timespec ts_start, ts_end; + uint64_t tsc_before, tsc_after, tsc_cycles, wall_ns; + uint64_t i, dummy = 0; + + if (argc > 1) + iterations = strtoull(argv[1], NULL, 10); + if (argc > 2) + warmup = strtoull(argv[2], NULL, 10); + + printf("# warmup=%" PRIu64 " iterations=%" PRIu64 "\n", + warmup, iterations); + + for (i = 0; i < warmup; i++) + dummy += read_tsc(); + + if (clock_gettime(CLOCK_MONOTONIC, &ts_start) != 0) + err(1, "clock_gettime start"); + tsc_before = read_tsc(); + + for (i = 0; i < iterations; i++) + dummy += read_tsc(); + + tsc_after = read_tsc(); + if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) + err(1, "clock_gettime end"); + + tsc_cycles = tsc_after - tsc_before; + wall_ns = ns_between(&ts_start, &ts_end); + + printf("tsc_cycles_total=%" PRIu64 "\n", tsc_cycles); + printf("wall_ns_total=%" PRIu64 "\n", wall_ns); + printf("average_cycles_per_read=%.2f\n", + (double)tsc_cycles / (double)iterations); + printf("average_ns_per_read=%.2f\n", + (double)wall_ns / (double)iterations); + printf("dummy=0x%" PRIx64 " # prevent loop elimination\n", dummy); + + return (0); +} diff --git a/examples/appendices/appendix-f-benchmarks/timecounter/run_tc_bench.sh b/examples/appendices/appendix-f-benchmarks/timecounter/run_tc_bench.sh new file mode 100755 index 0000000..aac3b34 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/timecounter/run_tc_bench.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# +# run_tc_bench.sh - rotate kern.timecounter.hardware through every +# available source and run tc_bench under each. +# +# Must be run as root. Restores the original timecounter selection +# on exit. +# +# Companion to Appendix F of "FreeBSD Device Drivers: From First +# Steps to Kernel Mastery". + +set -eu + +if [ "$(id -u)" -ne 0 ]; then + echo "error: must run as root (kern.timecounter.hardware is root-writable)" >&2 + exit 1 +fi + +if [ ! -x ./tc_bench ]; then + echo "error: ./tc_bench not found; run 'make' first" >&2 + exit 1 +fi + +original=$(sysctl -n kern.timecounter.hardware) +choices=$(sysctl -n kern.timecounter.choice) + +cleanup() { + sysctl "kern.timecounter.hardware=${original}" >/dev/null 2>&1 || true +} +trap cleanup EXIT INT TERM + +echo "# host: $(hostname)" +echo "# uname: $(uname -rmp)" +echo "# kern.timecounter.choice: ${choices}" +echo "# original kern.timecounter.hardware: ${original}" +echo "" + +# kern.timecounter.choice is a space-separated list of "name(quality)" +# entries. Extract just the names. +for entry in ${choices}; do + name=$(echo "${entry}" | sed 's/(.*//') + + # Try to select this timecounter; if the kernel refuses (because + # the hardware is not actually usable right now), skip it. + if ! sysctl "kern.timecounter.hardware=${name}" >/dev/null 2>&1; then + echo "# ${name}: could not select, skipping" + continue + fi + + # Give the kernel a moment to settle. + sleep 1 + echo "=== timecounter: ${name} ===" + ./tc_bench + echo "" +done + +echo "# restored kern.timecounter.hardware to ${original}" diff --git a/examples/appendices/appendix-f-benchmarks/timecounter/tc_bench.c b/examples/appendices/appendix-f-benchmarks/timecounter/tc_bench.c new file mode 100644 index 0000000..f0d33e5 --- /dev/null +++ b/examples/appendices/appendix-f-benchmarks/timecounter/tc_bench.c @@ -0,0 +1,91 @@ +/* + * tc_bench.c - measure clock_gettime(CLOCK_MONOTONIC) cost. + * + * The kernel resolves CLOCK_MONOTONIC through sbinuptime(), which + * reads whichever timecounter kern.timecounter.hardware currently + * selects. This program issues a large number of clock_gettime calls + * in a tight loop and reports the average nanoseconds per call. + * + * Combined with a run_tc_bench.sh that rotates the sysctl, this gives + * a measured read cost for each available timecounter. + * + * Companion to Appendix F of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery". + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_ITERATIONS 10000000ULL +#define DEFAULT_WARMUP 1000000ULL + +static uint64_t +ns_between(const struct timespec *start, const struct timespec *end) +{ + return ((uint64_t)(end->tv_sec - start->tv_sec) * 1000000000ULL + + (uint64_t)(end->tv_nsec - start->tv_nsec)); +} + +static void +report_timecounter(void) +{ + char buf[128]; + size_t len = sizeof(buf); + + if (sysctlbyname("kern.timecounter.hardware", buf, &len, + NULL, 0) == 0) { + buf[sizeof(buf) - 1] = '\0'; + printf("# kern.timecounter.hardware = %s\n", buf); + } +} + +int +main(int argc, char **argv) +{ + uint64_t iterations = DEFAULT_ITERATIONS; + uint64_t warmup = DEFAULT_WARMUP; + struct timespec ts_start, ts_end, ts_loop; + uint64_t i, total_ns; + + if (argc > 1) + iterations = strtoull(argv[1], NULL, 10); + if (argc > 2) + warmup = strtoull(argv[2], NULL, 10); + + report_timecounter(); + printf("# warmup=%" PRIu64 " iterations=%" PRIu64 "\n", + warmup, iterations); + + for (i = 0; i < warmup; i++) { + if (clock_gettime(CLOCK_MONOTONIC, &ts_loop) != 0) + err(1, "clock_gettime warmup"); + } + + if (clock_gettime(CLOCK_MONOTONIC, &ts_start) != 0) + err(1, "clock_gettime start"); + + for (i = 0; i < iterations; i++) { + if (clock_gettime(CLOCK_MONOTONIC, &ts_loop) != 0) + err(1, "clock_gettime loop"); + } + + if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) + err(1, "clock_gettime end"); + + total_ns = ns_between(&ts_start, &ts_end); + printf("average_ns_per_call=%.2f\n", + (double)total_ns / (double)iterations); + printf("total_ns=%" PRIu64 "\n", total_ns); + printf("iterations=%" PRIu64 "\n", iterations); + + return (0); +} diff --git a/examples/part-01/ch02-setting-up-your-lab/configs/dot-vimrc b/examples/part-01/ch02-setting-up-your-lab/configs/dot-vimrc new file mode 100644 index 0000000..1410c6d --- /dev/null +++ b/examples/part-01/ch02-setting-up-your-lab/configs/dot-vimrc @@ -0,0 +1,13 @@ +" ~/.vimrc - minimal Vim setup for FreeBSD driver work +" +" Companion for Chapter 2, section "Configuring Vim for Syntax +" Highlighting". Copy this to ~/.vimrc (note the leading dot, which +" is not legal in this repository's filenames, hence the "dot-vimrc" +" name here). + +syntax on +set number +set tabstop=8 +set shiftwidth=8 +set autoindent +set background=dark diff --git a/examples/part-01/ch02-setting-up-your-lab/configs/pf.conf b/examples/part-01/ch02-setting-up-your-lab/configs/pf.conf new file mode 100644 index 0000000..e991408 --- /dev/null +++ b/examples/part-01/ch02-setting-up-your-lab/configs/pf.conf @@ -0,0 +1,17 @@ +# /etc/pf.conf - minimal lab firewall ruleset +# +# Companion for Chapter 2, section "Basic Hardening for Your Lab", +# Option A. Block everything inbound except SSH. +# +# Replace the "ext_if" value with the name of your external network +# interface. In a VM you'll usually see "vtnet0"; on bare metal you +# may see em0, re0, igb0, and so on. Use "ifconfig" to find out. + +set skip on lo + +ext_if = "em0" +tcp_services = "{ ssh }" + +block in all +pass out all keep state +pass in on $ext_if proto tcp to (self) port $tcp_services keep state diff --git a/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/LABLOG.md b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/LABLOG.md new file mode 100644 index 0000000..68a6c78 --- /dev/null +++ b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/LABLOG.md @@ -0,0 +1,25 @@ +# Lab Logbook + +A simple record of what I tried, what worked, and what broke while +working through the book. Chapter 2 recommends keeping one file like +this in the root of each driver project. + +Keep entries short and dated. Future-you will thank present-you. + +## 2025-08-23 + +- Installed FreeBSD 14.3 in a VM. +- Built `hello_world.ko` on the first try. +- Confirmed "Hello World! Kernel module loaded." appears in `dmesg`. +- Tried unloading/reloading three times without errors. +- Next step: experiment with passing an argument to the module. + +## (template) + +``` +YYYY-MM-DD +- What I tried: +- What happened: +- What I learned: +- What I'll do next: +``` diff --git a/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/Makefile b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/Makefile new file mode 100644 index 0000000..e0e3651 --- /dev/null +++ b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/Makefile @@ -0,0 +1,11 @@ +# Makefile for hello_world kernel module +# +# Companion for Chapter 2. The KMOD name is "hello_world", so this +# Makefile produces "hello_world.ko" on build, NOT "hello.ko". +# (The chapter text has a minor phrasing glitch that says "hello.ko"; +# the filename you actually load is hello_world.ko.) + +KMOD= hello_world +SRCS= hello_world.c + +.include diff --git a/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/hello_world.c b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/hello_world.c new file mode 100644 index 0000000..650899f --- /dev/null +++ b/examples/part-01/ch02-setting-up-your-lab/lab01-hello-world/hello_world.c @@ -0,0 +1,51 @@ +/* + * hello_world.c - Simple FreeBSD kernel module + * Prints messages when loaded and unloaded + * + * Companion source for Chapter 2, section "Testing Your Toolkit: + * A Hello Kernel Module". + */ + +#include +#include +#include +#include + +/* + * Load handler - called when the module is loaded + */ +static int +hello_world_load(module_t mod, int cmd, void *arg) +{ + int error = 0; + + switch (cmd) { + case MOD_LOAD: + printf("Hello World! Kernel module loaded.\n"); + break; + case MOD_UNLOAD: + printf("Goodbye World! Kernel module unloaded.\n"); + break; + default: + error = EOPNOTSUPP; + break; + } + + return (error); +} + +/* + * Module declaration + */ +static moduledata_t hello_world_mod = { + "hello_world", /* module name */ + hello_world_load, /* event handler */ + NULL /* extra data */ +}; + +/* + * Register the module with the kernel. + * DECLARE_MODULE(name, data, sub-system, order) + */ +DECLARE_MODULE(hello_world, hello_world_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(hello_world, 1); diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/crontab-examples.txt b/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/crontab-examples.txt new file mode 100644 index 0000000..976a383 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/crontab-examples.txt @@ -0,0 +1,28 @@ +# Sample crontab entries for Chapter 3's "Scheduling and Automation" +# section. These are illustrative lines from the chapter, collected +# here so the reader can copy/paste them into `crontab -e`. +# +# Cron format (five time fields + command): +# +# .----------------- minute (0 - 59) +# | .-------------- hour (0 - 23) +# | | .----------- day of month (1 - 31) +# | | | .-------- month (1 - 12) +# | | | | .----- day of week (0 - 6, Sun = 0) +# | | | | | +# * * * * * command + +# Run every day at midnight +0 0 * * * /usr/bin/date >> /home/dev/midnight.log + +# Run every 15 minutes +*/15 * * * * /home/dev/scripts/check_disk.sh + +# Run every Monday at 8 AM +0 8 * * 1 echo "Weekly meeting" >> /home/dev/reminder.txt + +# Run at 3:30 AM on the first of every month +30 3 1 * * /usr/local/bin/backup.sh + +# Daily backup with output captured (stderr folded into the log file) +0 0 * * * /home/dev/backup.sh >> /home/dev/backup.log 2>&1 diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/periodic.conf.sample b/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/periodic.conf.sample new file mode 100644 index 0000000..d5b271c --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/automation/periodic.conf.sample @@ -0,0 +1,31 @@ +# /etc/periodic.conf - sample overrides for FreeBSD's periodic system +# +# Companion for section "Customizing periodic with periodic.conf" in +# Chapter 3. Copy this file to /etc/periodic.conf (or merge the lines +# into your existing one) as root. Reboot is NOT required; the next +# run of cron's periodic invocation picks up the new settings. +# +# Best practice (from the chapter): never edit the scripts under +# /etc/periodic/ directly. Override their behaviour here instead so +# your changes survive base-system updates. + +# --- Enable or disable jobs ------------------------------------------------- +daily_status_security_enable="YES" +daily_status_network_enable="NO" + +# --- Log handling ----------------------------------------------------------- +daily_clean_hoststat_enable="YES" +weekly_clean_pkg_enable="YES" + +# --- Enable the weekly locate(1) database update ---------------------------- +weekly_locate_enable="YES" + +# --- tmp cleanup: remove files untouched for 3 or more days ----------------- +daily_clean_tmps_enable="YES" +daily_clean_tmps_days="3" + +# --- Security reports (deliver inline as mail to root) ---------------------- +daily_status_security_inline="YES" +daily_status_security_output="mail" + +# See periodic.conf(5) for the full list of knobs. diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files.sh new file mode 100644 index 0000000..964d67e --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# list_files.sh - count files in home directory +# +# DELIBERATELY NAIVE: this version is the "naive approach that breaks" +# in the chapter's "Shell Portability" section. It counts a file with +# a newline in its name as two separate files. Compare with the +# _bash, _posix, and _exec variants in this directory. + +set -eu +cd "${HOME}" + +count=0 +while IFS= read -r f; do + fname=${f#./} + echo "File found: '$fname'" + count=$((count + 1)) +done << EOF +$(find . -maxdepth 1 -type f ! -name ".*" -print) +EOF + +echo "Total files found: $count" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_bash.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_bash.sh new file mode 100644 index 0000000..6b3ea35 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_bash.sh @@ -0,0 +1,17 @@ +#!/usr/local/bin/bash +# list_files_bash.sh - correctly handle unusual filenames with bash +# +# Uses bash-only features: process substitution and `read -d ''` +# with null delimiters. Requires: pkg install bash. + +set -eu +cd "${HOME}" + +count=0 +while IFS= read -r -d '' f; do + fname=${f#./} + echo "File found: '$fname'" + count=$((count + 1)) +done < <(find . -maxdepth 1 -type f ! -name ".*" -print0) + +echo "Total files found: $count" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_exec.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_exec.sh new file mode 100644 index 0000000..310d9ea --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_exec.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# list_files_exec.sh - handle all filenames using find -exec +# +# Pure POSIX, no bash dependency, no temporary file. Works even with +# pathological filenames (embedded newlines) because find -exec +# passes paths as arguments rather than through line-based input. + +set -eu +cd "${HOME}" + +find . -maxdepth 1 -type f ! -name ".*" -exec sh -c ' + for f; do + fname=${f#./} + printf "File found: '\''%s'\''\n" "$fname" + done +' sh {} + diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_posix.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_posix.sh new file mode 100644 index 0000000..d486fde --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/portability/list_files_posix.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# list_files_posix.sh - POSIX-compliant file listing +# +# Uses a temporary file instead of a pipe to preserve the counter +# variable across iterations. Handles filenames with spaces and +# most special characters, but cannot distinguish a filename that +# contains an embedded newline. For most real-world filenames, this +# is enough. + +set -eu +cd "${HOME}" + +# Use a temporary file instead of a pipe +tmpfile=$(mktemp) +trap 'rm -f "$tmpfile"' EXIT + +# Store find results in temporary file +find . -maxdepth 1 -type f ! -name ".*" > "$tmpfile" + +count=0 +while IFS= read -r f; do + fname=${f#./} + [ -z "$fname" ] && continue + + echo "File found: '$fname'" + count=$((count + 1)) +done < "$tmpfile" + +echo "Total files found: $count" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/01-hello.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/01-hello.sh new file mode 100644 index 0000000..d5a7479 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/01-hello.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# hello.sh a first shell script using FreeBSD's native /bin/sh +# Print a friendly message with the current date and the active user. + +# 'date' prints the current date and time +# 'whoami' prints the current user +echo "Hello from FreeBSD!" +echo "Date: $(date)" +echo "User: $(whoami)" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/02-vars.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/02-vars.sh new file mode 100644 index 0000000..bb96ad2 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/02-vars.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# vars.sh demonstrate variables and proper quoting + +name="dev" +greeting="Welcome" +# Double quotes preserve spaces and expand variables. +echo "$greeting, $name" +# Single quotes prevent expansion. This prints the literal characters. +echo '$greeting, $name' + +# Command substitution captures output of a command. +today="$(date +%Y-%m-%d)" +echo "Today is $today" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/03-status.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/03-status.sh new file mode 100644 index 0000000..d1c7b0f --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/03-status.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# status.sh show exit codes and conditional chaining + +# Try to list a directory that exists. 'ls' should return 0. +ls /etc && echo "Listing /etc succeeded" + +# Try something that fails. 'false' always returns nonzero. +false || echo "Previous command failed, so this message appears" + +# You can test the last status explicitly using $? +echo "Last status was $?" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/04-ifs.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/04-ifs.sh new file mode 100644 index 0000000..6a5bc8e --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/04-ifs.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# ifs.sh demonstrate file and numeric tests + +file="/etc/rc.conf" + +# -f tests if a regular file exists +if [ -f "$file" ]; then + echo "$file exists" +else + echo "$file does not exist" +fi + +num=5 +if [ "$num" -gt 3 ]; then + echo "$num is greater than 3" +fi + +# String tests +user="$(whoami)" +if [ "$user" = "root" ]; then + echo "You are root" +else + echo "You are $user" +fi diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/05-loops.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/05-loops.sh new file mode 100644 index 0000000..829295e --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/05-loops.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# loops.sh for and while loops in /bin/sh + +# A 'for' loop over pathnames. Always quote expansions to handle spaces safely. +for f in /etc/*.conf; do + echo "Found conf file: $f" +done + +# A 'while' loop to read lines from a file safely. +# The 'IFS=' and 'read -r' avoid trimming spaces and backslash escapes. +count=0 +while IFS= read -r line; do + count=$((count + 1)) +done < /etc/hosts +echo "The /etc/hosts file has $count lines" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/06-case.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/06-case.sh new file mode 100644 index 0000000..555e25b --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/06-case.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# case.sh handle options with a case statement + +action="$1" # first command line argument + +case "$action" in + start) + echo "Starting service" + ;; + stop) + echo "Stopping service" + ;; + restart) + echo "Restarting service" + ;; + *) + echo "Usage: $0 {start|stop|restart}" >&2 + exit 2 + ;; +esac diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/07-functions.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/07-functions.sh new file mode 100644 index 0000000..85db6b9 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/07-functions.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# functions.sh - Demonstrates using functions and command-line arguments in a shell script. +# +# Usage: +# ./functions.sh NUM1 NUM2 +# Example: +# ./functions.sh 5 7 +# This will output: "[INFO] 5 + 7 = 12" + +# A simple function to print informational messages +say() { + # "$1" represents the first argument passed to the function + echo "[INFO] $1" +} + +# A function to sum two integers +sum() { + # "$1" and "$2" are the first and second arguments + local a="$1" + local b="$2" + + # Perform arithmetic expansion to add them + echo $((a + b)) +} + +# --- Main script execution starts here --- + +# Make sure the user provided two arguments +if [ $# -ne 2 ]; then + echo "Usage: $0 NUM1 NUM2" + exit 1 +fi + +say "Beginning work" + +# Call the sum() function with the provided arguments +result="$(sum "$1" "$2")" + +# Print the result in a nice format +say "$1 + $2 = $result" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/08-backup.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/08-backup.sh new file mode 100644 index 0000000..93e77e3 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/08-backup.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# backup.sh create a timestamped tar archive of a directory +# Usage: ./backup.sh /path/to/source +# Notes: +# - Uses /bin/sh so it runs on a clean FreeBSD 14.x install. +# - Creates ~/backups if it does not exist. +# - Names the archive sourcebasename-YYYYMMDD-HHMMSS.tar.gz + +set -eu +# set -e: exit immediately if any command fails +# set -u: treat use of unset variables as an error + +# Validate input +if [ $# -ne 1 ]; then + echo "Usage: $0 /path/to/source" >&2 + exit 2 +fi + +src="$1" + +# Verify that source is a directory +if [ ! -d "$src" ]; then + echo "Error: $src is not a directory" >&2 + exit 3 +fi + +# Prepare destination directory +dest="${HOME}/backups" +mkdir -p "$dest" + +# Build a safe archive name using only the last path component +base="$(basename "$src")" +stamp="$(date +%Y%m%d-%H%M%S)" +archive="${dest}/${base}-${stamp}.tar.gz" + +# Create the archive +# tar(1) is in the base system. The flags mean: +# - c: create - z: gzip - f: file name - C: change to directory +tar -czf "$archive" -C "$(dirname "$src")" "$base" + +echo "Backup created: $archive" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/09-tmp_demo.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/09-tmp_demo.sh new file mode 100644 index 0000000..06c92aa --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/09-tmp_demo.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# tmp_demo.sh create and clean a temporary file safely + +set -eu + +tmpfile="$(mktemp -t myscript)" +# Arrange cleanup on exit for success or error +cleanup() { + [ -f "$tmpfile" ] && rm -f "$tmpfile" +} +trap cleanup EXIT + +echo "Temporary file is $tmpfile" +echo "Hello temp" > "$tmpfile" +echo "Contents: $(cat "$tmpfile")" diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/10-debug_demo.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/10-debug_demo.sh new file mode 100644 index 0000000..24461da --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/10-debug_demo.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# debug_demo.sh show simple tracing + +# set -x comment to disable verbose trace: +set -x + +echo "Step 1" +ls /etc >/dev/null + +echo "Step 2" +date diff --git a/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/11-organize_downloads.sh b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/11-organize_downloads.sh new file mode 100644 index 0000000..b7f39f6 --- /dev/null +++ b/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/11-organize_downloads.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# organize_downloads.sh - Tidy ~/Downloads by file extension +# +# Usage: +# ./organize_downloads.sh +# +# Creates subdirectories like Documents, Images, Audio, Video, Archives, Other +# and moves matched files into them safely. + +set -eu + +downloads="${HOME}/Downloads" + +# Create a temporary file to store the list of files +tmpfile=$(mktemp) + +# Remove temporary file when script exits (normal or error) +trap 'rm -f "$tmpfile"' EXIT + +# Ensure the Downloads directory exists +if [ ! -d "$downloads" ]; then + echo "Downloads directory not found at $downloads" >&2 + exit 1 +fi + +cd "$downloads" + +# Create target folders if missing +mkdir -p Documents Images Audio Video Archives Other + +# Find all regular files in current directory (non-recursive, excluding hidden files) +# -maxdepth 1: don't search in subdirectories +# -type f: only regular files (not directories or symlinks) +# ! -name ".*": exclude hidden files (those starting with a dot) +count=0 +find . -maxdepth 1 -type f ! -name ".*" > "$tmpfile" +while IFS= read -r f; do + # Strip leading "./" from path + fname=${f#./} + + # Skip if filename is empty (shouldn't happen, but safety check) + [ -z "$fname" ] && continue + + # Convert filename extension to lowercase for matching + lower=$(printf '%s' "$fname" | tr '[:upper:]' '[:lower:]') + + case "$lower" in + *.pdf|*.txt|*.md|*.doc|*.docx) dest="Documents" ;; + *.png|*.jpg|*.jpeg|*.gif|*.bmp) dest="Images" ;; + *.mp3|*.wav|*.flac) dest="Audio" ;; + *.mp4|*.mkv|*.mov|*.avi) dest="Video" ;; + *.zip|*.tar|*.gz|*.tgz|*.bz2) dest="Archives" ;; + *) dest="Other" ;; + esac + + echo "Moving '$fname' -> $dest/" + mv -n -- "$fname" "$dest/" # -n prevents overwriting existing files + count=$((count + 1)) # Increment the counter +done < "$tmpfile" # Feed the temporary file into the while loop + +if [ $count -eq 0 ]; then + echo "No files to organize." +else + echo "Done. Organized $count file(s)." +fi diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.c new file mode 100644 index 0000000..d303357 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.c @@ -0,0 +1,24 @@ +#include "flags.h" + +/* + * Print both the hex value and a friendly list of which flags are set. + * This mirrors how driver debug output often looks in practice. + * + * The `first` variable tracks whether we are printing the first flag + * (no leading comma) or a later one (comma separator). + */ +void +print_state(uint32_t st) +{ + int first = 1; + + printf("State: 0x%08x [", st); + if (test_flag(st, DF_ENABLED)) { printf("%sENABLED", first ? "" : ","); first = 0; } + if (test_flag(st, DF_OPEN)) { printf("%sOPEN", first ? "" : ","); first = 0; } + if (test_flag(st, DF_ERROR)) { printf("%sERROR", first ? "" : ","); first = 0; } + if (test_flag(st, DF_TX_BUSY)) { printf("%sTX_BUSY", first ? "" : ","); first = 0; } + if (test_flag(st, DF_RX_READY)) { printf("%sRX_READY", first ? "" : ","); first = 0; } + if (first) + printf("none"); + printf("]\n"); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.h new file mode 100644 index 0000000..1d969cc --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/flags.h @@ -0,0 +1,29 @@ +#ifndef DEV_FLAGS_H +#define DEV_FLAGS_H + +#include +#include + +/* + * Bit flags emulate how drivers track small on/off facts: + * enabled, open, error, TX busy, RX ready. Each flag is a + * single bit inside an unsigned integer. + */ +enum dev_flags { + DF_ENABLED = 1u << 0, /* 00001 */ + DF_OPEN = 1u << 1, /* 00010 */ + DF_ERROR = 1u << 2, /* 00100 */ + DF_TX_BUSY = 1u << 3, /* 01000 */ + DF_RX_READY = 1u << 4 /* 10000 */ +}; + +/* Small helpers keep bit logic readable and portable. */ +static inline void set_flag(uint32_t *st, uint32_t f) { *st |= f; } +static inline void clear_flag(uint32_t *st, uint32_t f) { *st &= ~f; } +static inline void toggle_flag(uint32_t *st, uint32_t f) { *st ^= f; } +static inline int test_flag(uint32_t st, uint32_t f) { return (st & f) != 0; } + +/* Summary printer lives in flags.c to keep main.c tidy. */ +void print_state(uint32_t st); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/main.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/main.c new file mode 100644 index 0000000..fb90fd3 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab1-bit-flags/main.c @@ -0,0 +1,46 @@ +#include +#include +#include "flags.h" + +/* Map small words to flags to keep the CLI simple. */ +static uint32_t +flag_from_name(const char *s) +{ + if (!strcmp(s, "enable")) return (DF_ENABLED); + if (!strcmp(s, "open")) return (DF_OPEN); + if (!strcmp(s, "error")) return (DF_ERROR); + if (!strcmp(s, "txbusy")) return (DF_TX_BUSY); + if (!strcmp(s, "rxready")) return (DF_RX_READY); + return (0); +} + +/* + * Usage example: + * ./devflags set enable set rxready toggle open + * Try different sequences and confirm your mental model of bits changing. + */ +int +main(int argc, char **argv) +{ + uint32_t st = 0; + + for (int i = 1; i + 1 < argc; i += 2) { + const char *op = argv[i], *name = argv[i + 1]; + uint32_t f = flag_from_name(name); + if (f == 0) { + printf("Unknown flag '%s'\n", name); + return (64); + } + + if (!strcmp(op, "set")) set_flag(&st, f); + else if (!strcmp(op, "clear")) clear_flag(&st, f); + else if (!strcmp(op, "toggle")) toggle_flag(&st, f); + else { + printf("Unknown op '%s'\n", op); + return (64); + } + } + + print_state(st); + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/demo.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/demo.c new file mode 100644 index 0000000..0d4dea1 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/demo.c @@ -0,0 +1,10 @@ +#include "log.h" + +int +main(void) +{ + LOG_INFO("Starting"); + LOG_DEBUG("Internal detail: x=%d", 42); + LOG_ERR("Something went wrong: %s", "timeout"); + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.c new file mode 100644 index 0000000..89ff36a --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.c @@ -0,0 +1,14 @@ +#include "log.h" + +/* Simple printf-style logger that prefixes level, file, and line. */ +void +eb_log(const char *lvl, const char *file, int line, const char *fmt, ...) +{ + va_list ap; + + fprintf(stderr, "[%s] %s:%d: ", lvl, file, line); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.h new file mode 100644 index 0000000..7e57d23 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab2-feature-gated-logging/log.h @@ -0,0 +1,33 @@ +#ifndef EB_LOG_H +#define EB_LOG_H + +#include +#include + +/* + * When compiled with -DDEBUG we enable extra logs. + * This is common in kernel and driver code to keep fast paths quiet. + */ +#ifdef DEBUG +#define LOG_DEBUG(fmt, ...) \ + eb_log("DEBUG", __FILE__, __LINE__, fmt, ##__VA_ARGS__) +#else +#define LOG_DEBUG(fmt, ...) ((void)0) /* compiles away */ +#endif + +#define LOG_INFO(fmt, ...) \ + eb_log("INFO", __FILE__, __LINE__, fmt, ##__VA_ARGS__) +#define LOG_ERR(fmt, ...) \ + eb_log("ERROR", __FILE__, __LINE__, fmt, ##__VA_ARGS__) + +/* Single declaration for the underlying function. */ +void eb_log(const char *lvl, const char *file, int line, const char *fmt, ...); + +/* + * Example compile-time assumption check: + * The code should work on 32- or 64-bit. Fail early otherwise. + */ +_Static_assert(sizeof(void *) == 8 || sizeof(void *) == 4, + "Unsupported pointer size"); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.c new file mode 100644 index 0000000..b114e4b --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include "devname.h" + +/* Safe build: check pointers and capacity; use snprintf to avoid overflow. */ +int +build_devname(char *dst, size_t dstsz, const char *prefix, int unit) +{ + int n; + + if (!dst || !prefix || unit < 0) + return (DN_EINVAL); + + n = snprintf(dst, dstsz, "%s%d", prefix, unit); + + /* + * snprintf returns the number of chars it *wanted* to write. + * If that does not fit in dst, we report DN_ERANGE. + */ + return (n >= 0 && (size_t)n < dstsz) ? DN_OK : DN_ERANGE; +} + +/* Very small validator for practice. Adjust rules if you want stricter checks. */ +int +is_valid_devname(const char *s) +{ + int saw_digit = 0; + + if (!s || !isalpha((unsigned char)s[0])) + return (0); + for (const char *p = s; *p; p++) { + if (isdigit((unsigned char)*p)) + saw_digit = 1; + else if (!isalpha((unsigned char)*p)) + return (0); + } + return (saw_digit); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.h new file mode 100644 index 0000000..6e1112c --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/devname.h @@ -0,0 +1,18 @@ +#ifndef DEVNAME_H +#define DEVNAME_H + +#include + +/* Tiny errno-like set for clarity when reading results. */ +enum dn_err { DN_OK = 0, DN_EINVAL = 22, DN_ERANGE = 34 }; + +/* + * Caller supplies dst and its size. We combine prefix + unit into dst. + * This mirrors common kernel patterns: pointer plus explicit length. + */ +int build_devname(char *dst, size_t dstsz, const char *prefix, int unit); + +/* Quick validator: letters then at least one digit (e.g., ttyu0). */ +int is_valid_devname(const char *s); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/test_devname.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/test_devname.c new file mode 100644 index 0000000..bf21a99 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab3-bounded-device-names/test_devname.c @@ -0,0 +1,32 @@ +#include +#include "devname.h" + +/* + * Table-driven tests: we try several cases and print both code and result. + * Practise reading return codes and not assuming success. + */ +struct case_ { const char *pref; int unit; size_t cap; }; + +int +main(void) +{ + char buf[8]; /* small to force you to think about capacity */ + struct case_ cases[] = { + {"ttyu", 0, sizeof(buf)}, /* fits */ + {"ttyv", 12, sizeof(buf)}, /* just fits or close */ + {"", 1, sizeof(buf)}, /* invalid prefix */ + }; + + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + int rc = build_devname(buf, cases[i].cap, + cases[i].pref, cases[i].unit); + printf("case %u -> rc=%d, buf='%s'\n", + i, rc, (rc == DN_OK) ? buf : ""); + } + + printf("valid? 'ttyu0'=%d, 'u0tty'=%d\n", + is_valid_devname("ttyu0"), + is_valid_devname("u0tty")); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/main_ops.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/main_ops.c new file mode 100644 index 0000000..03279cc --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/main_ops.c @@ -0,0 +1,43 @@ +#include +#include "ops.h" + +/* Choose one implementation based on argv[1]. */ +static const dev_ops_t * +pick(const char *name) +{ + if (!name) + return (NULL); + if (!strcmp(name, "console")) + return (&console_ops); + if (!strcmp(name, "uart")) + return (&uart_ops); + return (NULL); +} + +int +main(int argc, char **argv) +{ + const dev_ops_t *ops; + + if (argc < 2) { + fprintf(stderr, "usage: %s {console|uart}\n", argv[0]); + return (64); + } + + ops = pick(argv[1]); + if (!ops) { + fprintf(stderr, "unknown ops\n"); + return (64); + } + + /* The call sites do not care which backend we picked. */ + if (ops->init() != 0) { + fprintf(stderr, "init failed\n"); + return (1); + } + ops->start(); + printf("[%s] status: %s\n", ops->name, ops->status()); + ops->stop(); + printf("[%s] status: %s\n", ops->name, ops->status()); + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops.h new file mode 100644 index 0000000..ac12676 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops.h @@ -0,0 +1,25 @@ +#ifndef OPS_H +#define OPS_H + +#include + +/* typedefs keep pointer-to-function types readable. */ +typedef int (*ops_init_t)(void); +typedef void (*ops_start_t)(void); +typedef void (*ops_stop_t)(void); +typedef const char *(*ops_status_t)(void); + +/* A tiny vtable of operations for a device. */ +typedef struct { + const char *name; + ops_init_t init; + ops_start_t start; + ops_stop_t stop; + ops_status_t status; +} dev_ops_t; + +/* Two concrete implementations declared here, defined in .c files. */ +extern const dev_ops_t console_ops; +extern const dev_ops_t uart_ops; + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_console.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_console.c new file mode 100644 index 0000000..a7ca855 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_console.c @@ -0,0 +1,39 @@ +#include "ops.h" + +/* Console variant: pretend to manage a simple console device. */ +static int inited; +static const char *state = "stopped"; + +static int +c_init(void) +{ + inited = 1; + return (0); +} + +static void +c_start(void) +{ + if (inited) + state = "console-running"; +} + +static void +c_stop(void) +{ + state = "stopped"; +} + +static const char * +c_status(void) +{ + return (state); +} + +const dev_ops_t console_ops = { + .name = "console", + .init = c_init, + .start = c_start, + .stop = c_stop, + .status = c_status +}; diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_uart.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_uart.c new file mode 100644 index 0000000..6b90fdc --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab4-mini-devsw/ops_uart.c @@ -0,0 +1,39 @@ +#include "ops.h" + +/* UART variant: separate state to show independence between backends. */ +static int ready; +static const char *state = "idle"; + +static int +u_init(void) +{ + ready = 1; + return (0); +} + +static void +u_start(void) +{ + if (ready) + state = "uart-txrx"; +} + +static void +u_stop(void) +{ + state = "idle"; +} + +static const char * +u_status(void) +{ + return (state); +} + +const dev_ops_t uart_ops = { + .name = "uart", + .init = u_init, + .start = u_start, + .stop = u_stop, + .status = u_status +}; diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.c new file mode 100644 index 0000000..2cffba8 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.c @@ -0,0 +1,49 @@ +#include "cbuf.h" + +/* Prepare a buffer wrapper around caller-provided storage. */ +int +cb_init(cbuf_t *cb, int *storage, size_t n) +{ + if (!cb || !storage || n == 0) + return (22); /* EINVAL */ + cb->cap = n; + cb->head = cb->tail = 0; + cb->data = storage; + return (CB_OK); +} + +/* Empty when indices match. */ +int +cb_is_empty(const cbuf_t *cb) +{ + return (cb->head == cb->tail); +} + +/* Full when advancing head would collide with tail. */ +int +cb_is_full(const cbuf_t *cb) +{ + return (((cb->head + 1) % cb->cap) == cb->tail); +} + +/* Write the value, then advance head with wrap-around. */ +int +cb_push(cbuf_t *cb, int v) +{ + if (cb_is_full(cb)) + return (CB_EFULL); + cb->data[cb->head] = v; + cb->head = (cb->head + 1) % cb->cap; + return (CB_OK); +} + +/* Read the value, then advance tail with wrap-around. */ +int +cb_pop(cbuf_t *cb, int *out) +{ + if (cb_is_empty(cb)) + return (CB_EEMPTY); + *out = cb->data[cb->tail]; + cb->tail = (cb->tail + 1) % cb->cap; + return (CB_OK); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.h new file mode 100644 index 0000000..49f455e --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.h @@ -0,0 +1,29 @@ +#ifndef CBUF_H +#define CBUF_H + +#include +#include + +/* Small error codes mirroring common patterns. */ +enum cb_err { CB_OK = 0, CB_EFULL = 28, CB_EEMPTY = 35 }; + +/* + * head points to the next write position. + * tail points to the next read position. + * We leave one slot empty so that head == tail means empty, and + * (head + 1) % cap == tail means full. This keeps the logic simple. + */ +typedef struct { + size_t cap; /* number of slots in 'data' */ + size_t head; /* next write index */ + size_t tail; /* next read index */ + int *data; /* storage owned by the caller */ +} cbuf_t; + +int cb_init(cbuf_t *cb, int *storage, size_t n); +int cb_push(cbuf_t *cb, int v); +int cb_pop(cbuf_t *cb, int *out); +int cb_is_empty(const cbuf_t *cb); +int cb_is_full(const cbuf_t *cb); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/test_cbuf.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/test_cbuf.c new file mode 100644 index 0000000..a6ce582 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/test_cbuf.c @@ -0,0 +1,41 @@ +#include +#include "cbuf.h" + +/* + * We use a 4-slot store. With the "leave one empty" rule, + * the buffer holds at most 3 values at a time. + */ +int +main(void) +{ + int store[4]; + cbuf_t cb; + int v; + + cb_init(&cb, store, 4); + + /* Fill three slots; the fourth remains empty to signal full. */ + for (int i = 1; i <= 3; i++) { + int rc = cb_push(&cb, i); + printf("push %d -> rc=%d\n", i, rc); + } + + printf("full? %d (1 means yes)\n", cb_is_full(&cb)); + + /* Drain to empty. */ + while (cb_pop(&cb, &v) == 0) + printf("pop -> %d\n", v); + + /* Wrap-around scenario: push, push, pop, then push twice more. */ + cb_push(&cb, 7); + cb_push(&cb, 8); + cb_pop(&cb, &v); + printf("pop -> %d\n", v); /* frees one slot */ + cb_push(&cb, 9); + cb_push(&cb, 10); /* should wrap indices */ + + while (cb_pop(&cb, &v) == 0) + printf("pop -> %d\n", v); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-driver-skeleton/driver_skeleton.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-driver-skeleton/driver_skeleton.c new file mode 100644 index 0000000..4cd78c7 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-driver-skeleton/driver_skeleton.c @@ -0,0 +1,47 @@ +/* + * driver_skeleton.c - DELIBERATELY MESSY starter file. + * + * Companion for "Hands-On Lab 4: Putting It All Together" in the + * "Good Practices for C Programming" section of Chapter 4. + * + * The file below compiles, but it is full of problems the chapter + * asks you to find and fix: + * + * - inconsistent indentation and brace placement + * - cryptic variable names (D, nm, ret) + * - misleading comments + * - macro with side effects (DOUB) + * - buffer overflow risk (strcpy into a 5-byte buffer) + * - off-by-one loop (<=) + * - assignment in an if condition (if (ret = 10)) + * - missing argument checks in main() + * - no const on inputs that are never modified + * + * Your job is to rewrite this in FreeBSD KNF style, with safe + * string handling, proper error checking, and small helper + * functions. A short list of tasks appears in the chapter under + * "Hands-On Lab 4: Putting It All Together". + */ + +#include +#include +#include + +#define DOUB(X) X+X + +/* this function tries to init device, but its messy */ +int initDev(int D, char *nm){ +int i=0;char buf[5];int ret; +if(D==0){printf("bad dev\n");return -1;} +strcpy(buf,nm); +for(i=0;i<=D;i++){ret=DOUB(i);} +/* check if ret bigger then 10 */ +if(ret=10){printf("ok\n");} +else{printf("fail\n");} +return ret;} + +/* main func */ +int main(int argc,char **argv){int dev;char*name; +dev=atoi(argv[1]);name=argv[2]; +int r=initDev(dev,name); +printf("r=%d\n",r);} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/Makefile b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/Makefile new file mode 100644 index 0000000..49a435a --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/Makefile @@ -0,0 +1,11 @@ +# Makefile for the memlab kernel module (Chapter 4 Mini-Lab 3). +# +# The chapter shows a long manual compile + link command for +# teaching. In practice, the FreeBSD kernel-module build +# infrastructure handles all of that for you, so a three-line +# Makefile is all you need. + +KMOD= memlab +SRCS= memlab.c + +.include diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/memlab.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/memlab.c new file mode 100644 index 0000000..865ef31 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memlab-kernel/memlab.c @@ -0,0 +1,59 @@ +/* + * memlab.c - simple kernel module demonstrating malloc(9) / free(9). + * + * Companion for "Mini-Lab 3: Memory Allocation in a Kernel Module" + * in Chapter 4. Load the module and then check `vmstat -m | grep + * memlab` to see the allocation recorded; unload it and check again + * to confirm the memory is returned. + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_MEMLAB, "memlab", "Memory Lab Example"); + +static void *buffer = NULL; + +static int +memlab_load(struct module *m, int event, void *arg) +{ + int error = 0; + + switch (event) { + case MOD_LOAD: + printf("memlab: Loading module\n"); + buffer = malloc(128, M_MEMLAB, M_WAITOK | M_ZERO); + if (buffer == NULL) { + printf("memlab: malloc failed!\n"); + error = ENOMEM; + } else { + printf("memlab: allocated 128 bytes\n"); + } + break; + + case MOD_UNLOAD: + printf("memlab: Unloading module\n"); + if (buffer != NULL) { + free(buffer, M_MEMLAB); + printf("memlab: memory freed\n"); + } + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t memlab_mod = { + "memlab", memlab_load, NULL +}; + +DECLARE_MODULE(memlab, memlab_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(memlab, 1); diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_crash.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_crash.c new file mode 100644 index 0000000..ca40b3e --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_crash.c @@ -0,0 +1,34 @@ +/* + * lab1_crash.c - DELIBERATELY BROKEN. + * + * Companion for "Hands-On Lab 1: Crashing with an Uninitialized + * Pointer" in Chapter 4. This program compiles cleanly but almost + * always segfaults at runtime because it dereferences an + * uninitialised pointer. That is the whole point of the exercise. + * + * Compare with lab1_fixed.c in this directory for the correct + * version using malloc(). + */ + +#include + +struct data { + int value; +}; + +int +main(void) +{ + struct data *ptr; /* declared but not initialised */ + + /* + * At this point, 'ptr' points to whatever bytes happened to be + * on the stack when main() started. Writing through it is + * undefined behaviour and will very likely crash. + */ + ptr->value = 42; + + printf("Value: %d\n", ptr->value); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_fixed.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_fixed.c new file mode 100644 index 0000000..8828ef5 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_fixed.c @@ -0,0 +1,33 @@ +/* + * lab1_fixed.c - corrected version of lab1_crash.c. + * + * Allocates memory for a struct data on the heap, checks for + * allocation failure, writes into the structure safely, prints the + * value, and frees the memory before exiting. + */ + +#include +#include /* malloc, free */ + +struct data { + int value; +}; + +int +main(void) +{ + struct data *ptr; + + ptr = malloc(sizeof(struct data)); + if (ptr == NULL) { + printf("Allocation failed!\n"); + return (1); + } + + ptr->value = 42; + printf("Value: %d\n", ptr->value); + + free(ptr); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_fixed.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_fixed.c new file mode 100644 index 0000000..66b1940 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_fixed.c @@ -0,0 +1,25 @@ +/* + * lab2_fixed.c - corrected version of lab2_leak.c. + * + * The only change from lab2_leak.c is the final free(). That one line + * is enough to turn a leaky program into a clean one. + */ + +#include +#include +#include + +int +main(void) +{ + char *buffer = malloc(128); + if (buffer == NULL) + return (1); + + strcpy(buffer, "FreeBSD device drivers are awesome!"); + printf("%s\n", buffer); + + free(buffer); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_leak.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_leak.c new file mode 100644 index 0000000..42f9a41 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab2_leak.c @@ -0,0 +1,31 @@ +/* + * lab2_leak.c - DELIBERATELY LEAKY. + * + * Companion for "Hands-On Lab 2: Memory Leak and the Forgotten Free" + * in Chapter 4. This program works correctly, but it never frees the + * buffer it allocates. In userspace the OS reclaims the memory on + * exit so the leak is invisible. In the kernel, the same bug would + * accumulate until the system was rebooted. + * + * Run with AddressSanitizer to see the leak report: + * cc -fsanitize=address -g -o lab2_leak lab2_leak.c + * ./lab2_leak + */ + +#include +#include +#include + +int +main(void) +{ + char *buffer = malloc(128); + if (buffer == NULL) + return (1); + + strcpy(buffer, "FreeBSD device drivers are awesome!"); + printf("%s\n", buffer); + + /* Intentionally no free(buffer) here. */ + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.c new file mode 100644 index 0000000..af9fa03 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.c @@ -0,0 +1,14 @@ +#include +#include "greetings.h" + +void +say_hello(void) +{ + printf("Hello from greetings.c!\n"); +} + +void +say_goodbye(void) +{ + printf("Goodbye from greetings.c!\n"); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.h new file mode 100644 index 0000000..6f7980e --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/greetings.h @@ -0,0 +1,7 @@ +#ifndef GREETINGS_H +#define GREETINGS_H + +void say_hello(void); +void say_goodbye(void); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/main.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/main.c new file mode 100644 index 0000000..06ea368 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-modular-program/main.c @@ -0,0 +1,9 @@ +#include "greetings.h" + +int +main(void) +{ + say_hello(); + say_goodbye(); + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/main.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/main.c new file mode 100644 index 0000000..8b43c77 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/main.c @@ -0,0 +1,13 @@ +#include +#include "mathutils.h" + +int +main(void) +{ + int x = 10, y = 4; + + printf("Add: %d\n", add(x, y)); + printf("Subtract: %d\n", subtract(x, y)); + + return (0); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.c new file mode 100644 index 0000000..a6a748a --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.c @@ -0,0 +1,13 @@ +#include "mathutils.h" + +int +add(int a, int b) +{ + return (a + b); +} + +int +subtract(int a, int b) +{ + return (a - b); +} diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.h b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.h new file mode 100644 index 0000000..6ceff25 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/multi-file-example/mathutils.h @@ -0,0 +1,7 @@ +#ifndef MATHUTILS_H +#define MATHUTILS_H + +int add(int a, int b); +int subtract(int a, int b); + +#endif diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/Makefile b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/Makefile new file mode 100644 index 0000000..06735c7 --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/Makefile @@ -0,0 +1,13 @@ +# Makefile for hello.c +# +# Companion for Chapter 4's "Using Makefiles" section. +# +# IMPORTANT: each command line below a rule must begin with a TAB +# character, not spaces. If you see "Invalid line type" from make, +# your editor has turned a tab into spaces. Check with `cat -A`. + +hello: hello.c + cc -o hello hello.c + +clean: + rm -f hello diff --git a/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/hello.c b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/hello.c new file mode 100644 index 0000000..f65380a --- /dev/null +++ b/examples/part-01/ch04-a-first-look-at-the-c-programming-language/setup/hello.c @@ -0,0 +1,17 @@ +/* + * hello.c - the "Hello, World!" program used in Chapter 4's + * "Setting Up Your Environment" section. + * + * This is the smallest possible C program that actually does + * something: it prints a message and exits with status 0. + */ + +#include + +int +main(void) +{ + + printf("Hello, World!\n"); + return (0); +} diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/Makefile new file mode 100644 index 0000000..212e441 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= atomic_demo +SRCS= atomic_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/atomic_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/atomic_demo.c new file mode 100644 index 0000000..cbe5c20 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/atomic_demo/atomic_demo.c @@ -0,0 +1,117 @@ +/* + * atomic_demo.c - Atomic operations and inline helpers. + * + * Companion for the "Hands-On Lab: Atomic Operations and Performance" + * section of Chapter 5. + */ + +#include +#include +#include +#include +#include + +static volatile u_int shared_counter = 0; +static volatile u_int shared_flags = 0; + +static __inline void +safe_increment(volatile u_int *counter) +{ + + atomic_add_int(counter, 1); +} + +static __inline void +set_flag_atomically(volatile u_int *flags, u_int flag) +{ + + atomic_set_int(flags, flag); +} + +static __inline void +clear_flag_atomically(volatile u_int *flags, u_int flag) +{ + + atomic_clear_int(flags, flag); +} + +static __inline bool +test_flag_atomically(volatile u_int *flags, u_int flag) +{ + + return ((atomic_load_acq_int(flags) & flag) != 0); +} + +static int +atomic_max_update(volatile u_int *current_max, u_int new_value) +{ + u_int old_value; + + do { + old_value = *current_max; + if (new_value <= old_value) + return (0); + } while (!atomic_cmpset_int(current_max, old_value, new_value)); + return (1); +} + +static int +atomic_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + int i; + + switch (type) { + case MOD_LOAD: + printf("=== Atomic Operations Demo ===\n"); + + atomic_store_rel_int(&shared_counter, 0); + atomic_store_rel_int(&shared_flags, 0); + + for (i = 0; i < 10; i++) + safe_increment(&shared_counter); + printf("counter after 10 increments: %u\n", + atomic_load_acq_int(&shared_counter)); + + set_flag_atomically(&shared_flags, 0x01); + set_flag_atomically(&shared_flags, 0x04); + set_flag_atomically(&shared_flags, 0x10); + printf("flags after set 0x01/0x04/0x10: 0x%02x\n", + atomic_load_acq_int(&shared_flags)); + + printf("flag 0x01 is %s\n", + test_flag_atomically(&shared_flags, 0x01) ? "set" : "clear"); + printf("flag 0x02 is %s\n", + test_flag_atomically(&shared_flags, 0x02) ? "set" : "clear"); + + clear_flag_atomically(&shared_flags, 0x01); + printf("flag 0x01 after clear: %s\n", + test_flag_atomically(&shared_flags, 0x01) ? "set" : "clear"); + + printf("update max to 5: %s\n", + atomic_max_update(&shared_counter, 5) ? "success" : "skipped"); + printf("update max to 15: %s\n", + atomic_max_update(&shared_counter, 15) ? "success" : "skipped"); + printf("final counter: %u\n", + atomic_load_acq_int(&shared_counter)); + + printf("atomic_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + printf("atomic_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t atomic_demo_mod = { + "atomic_demo", + atomic_demo_modevent, + NULL +}; + +DECLARE_MODULE(atomic_demo, atomic_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(atomic_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/Makefile new file mode 100644 index 0000000..6420c12 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= defensive_demo +SRCS= defensive_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/defensive_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/defensive_demo.c new file mode 100644 index 0000000..ae91366 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/defensive_demo/defensive_demo.c @@ -0,0 +1,159 @@ +/* + * defensive_demo.c - Defensive programming in the kernel. + * + * Companion for the "Hands-On Lab: Building Defensive Kernel Code" + * section of Chapter 5. Demonstrates full parameter validation, + * magic-number structure checks, bounded buffer writes, and safe + * reference counting. + */ + +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_DEFTEST, "deftest", "Defensive programming test"); + +#define MAX_BUFFER_SIZE 4096 +#define MAX_NAME_LENGTH 64 +#define DEMO_MAGIC 0x12345678U + +struct demo_buffer { + uint32_t db_magic; + size_t db_size; + size_t db_used; + char db_name[MAX_NAME_LENGTH]; + void *db_data; + volatile u_int db_refcount; +}; + +static struct demo_buffer * +demo_buffer_alloc(const char *name, size_t size) +{ + struct demo_buffer *db; + size_t name_len; + + if (name == NULL) + return (NULL); + name_len = strnlen(name, MAX_NAME_LENGTH); + if (name_len == 0 || name_len >= MAX_NAME_LENGTH) + return (NULL); + if (size == 0 || size > MAX_BUFFER_SIZE) + return (NULL); + if (SIZE_MAX - sizeof(*db) < size) + return (NULL); + + db = malloc(sizeof(*db), M_DEFTEST, M_WAITOK | M_ZERO); + db->db_data = malloc(size, M_DEFTEST, M_WAITOK); + if (db->db_data == NULL) { + free(db, M_DEFTEST); + return (NULL); + } + + db->db_magic = DEMO_MAGIC; + db->db_size = size; + db->db_refcount = 1; + strlcpy(db->db_name, name, sizeof(db->db_name)); + return (db); +} + +static void +demo_buffer_free(struct demo_buffer *db) +{ + + if (db == NULL) + return; + if (db->db_magic != DEMO_MAGIC) { + printf("demo_buffer_free: bad magic\n"); + return; + } + if (db->db_refcount != 0) { + printf("demo_buffer_free: non-zero refcount %u\n", + db->db_refcount); + return; + } + + memset(db->db_data, 0, db->db_size); + free(db->db_data, M_DEFTEST); + db->db_data = NULL; + db->db_magic = 0xDEADBEEFU; + free(db, M_DEFTEST); +} + +static int +demo_buffer_write(struct demo_buffer *db, const void *data, size_t len, + size_t offset) +{ + + if (db == NULL || data == NULL) + return (EINVAL); + if (db->db_magic != DEMO_MAGIC) + return (EINVAL); + if (len == 0) + return (0); + if (offset > db->db_size || len > db->db_size - offset) + return (EOVERFLOW); + + memcpy((char *)db->db_data + offset, data, len); + if (offset + len > db->db_used) + db->db_used = offset + len; + return (0); +} + +static int +defensive_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + struct demo_buffer *db; + const char test[] = "Hello, defensive kernel world!"; + int error; + + switch (type) { + case MOD_LOAD: + printf("=== Defensive Programming Demo ===\n"); + + db = demo_buffer_alloc("test", 256); + if (db == NULL) + return (ENOMEM); + printf("allocated '%s' size=%zu\n", db->db_name, db->db_size); + + error = demo_buffer_write(db, test, sizeof(test) - 1, 0); + printf("write returned %d\n", error); + + /* Negative tests (should all return NULL or an error). */ + if (demo_buffer_alloc(NULL, 100) == NULL) + printf("rejected NULL name (good)\n"); + if (demo_buffer_alloc("t", 0) == NULL) + printf("rejected size=0 (good)\n"); + if (demo_buffer_alloc("t", MAX_BUFFER_SIZE + 1) == NULL) + printf("rejected oversized (good)\n"); + if (demo_buffer_write(db, test, 10000, 0) != 0) + printf("rejected oversized write (good)\n"); + + /* Final release. */ + atomic_subtract_int(&db->db_refcount, 1); + demo_buffer_free(db); + + printf("defensive_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + printf("defensive_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t defensive_demo_mod = { + "defensive_demo", + defensive_demo_modevent, + NULL +}; + +DECLARE_MODULE(defensive_demo, defensive_demo_mod, + SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(defensive_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/Makefile new file mode 100644 index 0000000..b1bbba4 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= error_demo +SRCS= error_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/error_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/error_demo.c new file mode 100644 index 0000000..6bd11b9 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/error_demo/error_demo.c @@ -0,0 +1,174 @@ +/* + * error_demo.c - Error handling and diagnostics. + * + * Companion for the "Hands-On Lab: Error Handling and Diagnostics" + * section of Chapter 5. Shows compiler attributes, debug levels, + * statistics counters, and an error-context struct used on every + * failure path. + */ + +#include +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_ERRTEST, "errtest", "Error handling test structures"); + +#define DEBUG_ERROR 1 +#define DEBUG_WARN 2 +#define DEBUG_INFO 3 +#define DEBUG_VERBOSE 4 + +static int debug_level = DEBUG_INFO; + +#define DPRINTF(level, fmt, ...) \ + do { \ + if ((level) <= debug_level) \ + printf("[%s:%d] " fmt "\n", \ + __func__, __LINE__, ##__VA_ARGS__); \ + } while (0) + +struct error_context { + int error_code; + const char *operation; + const char *file; + int line; + sbintime_t timestamp; +}; + +#define SET_ERROR(ctx, code, op) \ + do { \ + if ((ctx) != NULL) { \ + (ctx)->error_code = (code); \ + (ctx)->operation = (op); \ + (ctx)->file = __FILE__; \ + (ctx)->line = __LINE__; \ + (ctx)->timestamp = sbinuptime(); \ + } \ + } while (0) + +struct operation_stats { + volatile u_long total_attempts; + volatile u_long successes; + volatile u_long failures; +}; + +static struct operation_stats global_stats; + +#define TEST_MAGIC 0xABCDEF00U +struct test_object { + uint32_t magic; + int id; + size_t size; + void *data; +}; + +static struct test_object * +test_object_alloc(int id, size_t size, struct error_context *err_ctx) +{ + struct test_object *obj; + void *data; + + atomic_add_long(&global_stats.total_attempts, 1); + + if (id < 0 || size == 0 || size > 1024U * 1024U) { + SET_ERROR(err_ctx, EINVAL, "parameter validation"); + atomic_add_long(&global_stats.failures, 1); + return (NULL); + } + + obj = malloc(sizeof(*obj), M_ERRTEST, M_NOWAIT | M_ZERO); + if (obj == NULL) { + SET_ERROR(err_ctx, ENOMEM, "structure allocation"); + atomic_add_long(&global_stats.failures, 1); + return (NULL); + } + + data = malloc(size, M_ERRTEST, M_NOWAIT); + if (data == NULL) { + free(obj, M_ERRTEST); + SET_ERROR(err_ctx, ENOMEM, "data buffer allocation"); + atomic_add_long(&global_stats.failures, 1); + return (NULL); + } + + obj->magic = TEST_MAGIC; + obj->id = id; + obj->size = size; + obj->data = data; + + atomic_add_long(&global_stats.successes, 1); + DPRINTF(DEBUG_INFO, "allocated object id=%d size=%zu", id, size); + return (obj); +} + +static void +test_object_free(struct test_object *obj) +{ + + if (obj == NULL) + return; + if (obj->magic != TEST_MAGIC) { + DPRINTF(DEBUG_ERROR, "object bad magic 0x%x", obj->magic); + return; + } + memset(obj->data, 0, obj->size); + free(obj->data, M_ERRTEST); + obj->magic = 0xDEADBEEFU; + free(obj, M_ERRTEST); +} + +static int +error_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + struct test_object *obj; + struct error_context ec = { 0 }; + + switch (type) { + case MOD_LOAD: + printf("=== Error Handling and Diagnostics Demo ===\n"); + + obj = test_object_alloc(1, 1024, &ec); + if (obj != NULL) { + printf("allocated object 1\n"); + test_object_free(obj); + } + + memset(&ec, 0, sizeof(ec)); + if (test_object_alloc(-1, 1024, &ec) == NULL) + printf("rejected invalid id: error=%d op='%s'\n", + ec.error_code, ec.operation); + + memset(&ec, 0, sizeof(ec)); + if (test_object_alloc(2, 0, &ec) == NULL) + printf("rejected invalid size: error=%d op='%s'\n", + ec.error_code, ec.operation); + + printf("stats: attempts=%lu ok=%lu err=%lu\n", + atomic_load_acq_long(&global_stats.total_attempts), + atomic_load_acq_long(&global_stats.successes), + atomic_load_acq_long(&global_stats.failures)); + printf("error_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + printf("error_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t error_demo_mod = { + "error_demo", + error_demo_modevent, + NULL +}; + +DECLARE_MODULE(error_demo, error_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(error_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/Makefile new file mode 100644 index 0000000..00ca319 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= function_demo +SRCS= function_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/function_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/function_demo.c new file mode 100644 index 0000000..213a86c --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/function_demo/function_demo.c @@ -0,0 +1,128 @@ +/* + * function_demo.c - Function design patterns for kernel C. + * + * Companion for the "Hands-On Lab: Function Design Patterns" section + * of Chapter 5. Shows parameter validation, output parameters, and + * the classic errno-style return convention. + */ + +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_FUNCDEMO, "funcdemo", "Function demo allocations"); + +static int +validate_buffer_params(size_t size, int flags) +{ + + if (size == 0) + return (EINVAL); + if (size > 1024 * 1024) + return (EFBIG); + if ((flags & ~(M_WAITOK | M_NOWAIT | M_ZERO)) != 0) + return (EINVAL); + return (0); +} + +static int +demo_buffer_alloc(char **bufp, size_t size, int flags) +{ + char *buffer; + int error; + + if (bufp == NULL) + return (EINVAL); + *bufp = NULL; + + error = validate_buffer_params(size, flags); + if (error != 0) + return (error); + + buffer = malloc(size, M_FUNCDEMO, flags); + if (buffer == NULL) + return (ENOMEM); + + snprintf(buffer, size, "Demo buffer of %zu bytes", size); + *bufp = buffer; + return (0); +} + +static void +demo_buffer_free(char *buffer) +{ + + if (buffer != NULL) + free(buffer, M_FUNCDEMO); +} + +static ssize_t +demo_buffer_process(const char *buffer, size_t size, bool verbose) +{ + size_t len; + + if (buffer == NULL || size == 0) + return (-EINVAL); + + len = strnlen(buffer, size); + if (verbose) + printf("Processing: '%.*s' (length %zu)\n", + (int)len, buffer, len); + return ((ssize_t)len); +} + +static int +function_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + char *buffer = NULL; + ssize_t processed; + int error; + + switch (type) { + case MOD_LOAD: + printf("=== Function Design Demo ===\n"); + + error = demo_buffer_alloc(&buffer, 256, M_WAITOK | M_ZERO); + if (error != 0) { + printf("alloc failed: %d\n", error); + return (error); + } + printf("Allocated buffer: %p\n", buffer); + + processed = demo_buffer_process(buffer, 256, true); + if (processed < 0) + printf("process failed: %zd\n", processed); + else + printf("processed %zd bytes\n", processed); + + demo_buffer_free(buffer); + + error = demo_buffer_alloc(&buffer, 0, M_WAITOK); + if (error != 0) + printf("validation rejected size=0 with %d (good)\n", + error); + + printf("function_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + printf("function_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t function_demo_mod = { + "function_demo", + function_demo_modevent, + NULL +}; + +DECLARE_MODULE(function_demo, function_demo_mod, + SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(function_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/Makefile new file mode 100644 index 0000000..33b80fc --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= memory_demo +SRCS= memory_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/memory_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/memory_demo.c new file mode 100644 index 0000000..37675eb --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/memory_demo/memory_demo.c @@ -0,0 +1,84 @@ +/* + * memory_demo.c - malloc(9), M_NOWAIT vs M_WAITOK, and a UMA zone. + * + * Companion for the "Hands-On Lab: Kernel Memory Management" section + * of Chapter 5. + */ + +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_DEMO, "demo", "Memory demo allocations"); + +static uma_zone_t demo_zone; + +struct demo_object { + int id; + char name[32]; +}; + +static int +memory_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + void *ptr1, *ptr2, *ptr3; + struct demo_object *obj; + + switch (type) { + case MOD_LOAD: + printf("=== Kernel Memory Management Demo ===\n"); + + ptr1 = malloc(1024, M_DEMO, M_WAITOK); + printf("M_WAITOK allocation of 1024 bytes at %p\n", ptr1); + + ptr2 = malloc(512, M_DEMO, M_WAITOK | M_ZERO); + printf("M_WAITOK|M_ZERO allocation of 512 bytes at %p\n", ptr2); + + ptr3 = malloc(2048, M_DEMO, M_NOWAIT); + if (ptr3 != NULL) + printf("M_NOWAIT allocation succeeded at %p\n", ptr3); + else + printf("M_NOWAIT allocation failed (memory pressure)\n"); + + demo_zone = uma_zcreate("demo_objects", sizeof(*obj), + NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); + if (demo_zone != NULL) { + obj = uma_zalloc(demo_zone, M_WAITOK); + obj->id = 42; + strlcpy(obj->name, "demo_object", sizeof(obj->name)); + printf("UMA zone allocation: id=%d name='%s' at %p\n", + obj->id, obj->name, obj); + uma_zfree(demo_zone, obj); + } + + free(ptr1, M_DEMO); + free(ptr2, M_DEMO); + if (ptr3 != NULL) + free(ptr3, M_DEMO); + + printf("memory_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + if (demo_zone != NULL) + uma_zdestroy(demo_zone); + printf("memory_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t memory_demo_mod = { + "memory_demo", + memory_demo_modevent, + NULL +}; + +DECLARE_MODULE(memory_demo, memory_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(memory_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/Makefile new file mode 100644 index 0000000..08e2e8b --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= restrictions_demo +SRCS= restrictions_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/restrictions_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/restrictions_demo.c new file mode 100644 index 0000000..cfb75ed --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/restrictions_demo/restrictions_demo.c @@ -0,0 +1,95 @@ +/* + * restrictions_demo.c - Work around the rules kernel C enforces. + * + * Companion for the "Hands-On Lab: Understanding Restrictions" section + * of Chapter 5. Shows fixed-point arithmetic, bounded recursion, and + * atomic counters, all in one module. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_RESTRICT, "restrict", "Restriction demo"); + +static volatile u_int atomic_counter = 0; +static struct mtx demo_lock; + +static int +safe_recursive_demo(int depth, int max_depth) +{ + + if (depth >= max_depth) + return (depth); + return (safe_recursive_demo(depth + 1, max_depth) + 1); +} + +static int +fixed_point_average(int *values, int count, int scale) +{ + long sum = 0; + int i; + + if (count == 0) + return (0); + for (i = 0; i < count; i++) + sum += values[i]; + return ((int)((sum * scale) / count)); +} + +static int +restrictions_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + int values[] = { 10, 20, 30, 40, 50 }; + void *buffer; + + switch (type) { + case MOD_LOAD: + printf("=== Kernel Restrictions Demo ===\n"); + + mtx_init(&demo_lock, "demo_lock", NULL, MTX_DEF); + + printf("fixed-point average * 100 = %d\n", + fixed_point_average(values, 5, 100)); + + printf("safe recursive depth=10 returned %d\n", + safe_recursive_demo(0, 10)); + + atomic_add_int(&atomic_counter, 42); + printf("atomic counter: %u\n", + atomic_load_acq_int(&atomic_counter)); + + buffer = malloc(1024, M_RESTRICT, M_WAITOK); + if (buffer != NULL) { + printf("allocated 1KB in sleepable context\n"); + free(buffer, M_RESTRICT); + } + + printf("restrictions_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + mtx_destroy(&demo_lock); + printf("restrictions_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t restrictions_demo_mod = { + "restrictions_demo", + restrictions_demo_modevent, + NULL +}; + +DECLARE_MODULE(restrictions_demo, restrictions_demo_mod, + SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(restrictions_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/Makefile new file mode 100644 index 0000000..79d4890 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= strings_demo +SRCS= strings_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/strings_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/strings_demo.c new file mode 100644 index 0000000..4d7c731 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/strings_demo/strings_demo.c @@ -0,0 +1,76 @@ +/* + * strings_demo.c - Safe string and memory operations in the kernel. + * + * Companion for the "Hands-On Lab: Safe String Handling" section of + * Chapter 5. + */ + +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_STRDEMO, "strdemo", "String demo buffers"); + +static int +strings_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + char *buffer1, *buffer2; + const char test_string[] = "FreeBSD Kernel Programming"; + size_t len, copied; + + switch (type) { + case MOD_LOAD: + printf("=== Kernel String Handling Demo ===\n"); + + buffer1 = malloc(64, M_STRDEMO, M_WAITOK | M_ZERO); + buffer2 = malloc(32, M_STRDEMO, M_WAITOK | M_ZERO); + + copied = strlcpy(buffer1, test_string, 64); + printf("strlcpy: copied=%zu result='%s'\n", copied, buffer1); + + copied = strlcpy(buffer2, test_string, 32); + printf("strlcpy small buf: copied=%zu result='%s'\n", + copied, buffer2); + if (copied >= 32) + printf("warning: source truncated\n"); + + len = strnlen(buffer1, 64); + printf("strnlen: length=%zu\n", len); + + strlcat(buffer2, " rocks!", 32); + printf("strlcat: '%s'\n", buffer2); + + memset(buffer1, 'X', 10); + buffer1[10] = '\0'; + printf("memset: '%s'\n", buffer1); + + snprintf(buffer1, 64, "module loaded at ticks=%d", ticks); + printf("snprintf: '%s'\n", buffer1); + + free(buffer1, M_STRDEMO); + free(buffer2, M_STRDEMO); + + printf("strings_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + printf("strings_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t strings_demo_mod = { + "strings_demo", + strings_demo_modevent, + NULL +}; + +DECLARE_MODULE(strings_demo, strings_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(strings_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/Makefile new file mode 100644 index 0000000..ced446b --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= style_demo +SRCS= style_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/style_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/style_demo.c new file mode 100644 index 0000000..da6d96a --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/style_demo/style_demo.c @@ -0,0 +1,140 @@ +/* + * style_demo.c - KNF-style module with refcounted objects. + * + * Companion for the "Hands-On Lab: Implementing Kernel Coding + * Patterns" section of Chapter 5. Demonstrates KNF layout, magic- + * numbered structures, refcounting, and a global TAILQ protected by + * a mutex. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_STYLEDEMO, "styledemo", "Style demo structures"); + +#define DEMO_ITEM_MAGIC 0xDEADBEEFU + +struct demo_item { + TAILQ_ENTRY(demo_item) di_link; + uint32_t di_magic; + int di_id; + char di_name[32]; + int di_refcount; +}; + +TAILQ_HEAD(demo_item_list, demo_item); + +static struct demo_item_list item_list = TAILQ_HEAD_INITIALIZER(item_list); +static struct mtx item_list_lock; +static int next_item_id = 1; + +static void +demo_item_ref(struct demo_item *item) +{ + + KASSERT(item != NULL, ("demo_item_ref: null")); + KASSERT(item->di_magic == DEMO_ITEM_MAGIC, + ("demo_item_ref: bad magic")); + atomic_add_int(&item->di_refcount, 1); +} + +static void +demo_item_unref(struct demo_item *item) +{ + int old; + + if (item == NULL) + return; + KASSERT(item->di_magic == DEMO_ITEM_MAGIC, + ("demo_item_unref: bad magic")); + + old = atomic_fetchadd_int(&item->di_refcount, -1); + if (old != 1) + return; + + mtx_lock(&item_list_lock); + TAILQ_REMOVE(&item_list, item, di_link); + mtx_unlock(&item_list_lock); + + item->di_magic = 0; /* poison */ + free(item, M_STYLEDEMO); +} + +static struct demo_item * +demo_item_alloc(const char *name) +{ + struct demo_item *item; + + if (name == NULL) + return (NULL); + if (strnlen(name, sizeof(item->di_name)) >= sizeof(item->di_name)) + return (NULL); + + item = malloc(sizeof(*item), M_STYLEDEMO, M_WAITOK | M_ZERO); + item->di_magic = DEMO_ITEM_MAGIC; + item->di_refcount = 1; + strlcpy(item->di_name, name, sizeof(item->di_name)); + + mtx_lock(&item_list_lock); + item->di_id = next_item_id++; + TAILQ_INSERT_TAIL(&item_list, item, di_link); + mtx_unlock(&item_list_lock); + + return (item); +} + +static int +style_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + struct demo_item *i1, *i2; + + switch (type) { + case MOD_LOAD: + printf("=== Kernel Style Demo ===\n"); + mtx_init(&item_list_lock, "style_demo_items", NULL, MTX_DEF); + + i1 = demo_item_alloc("first"); + i2 = demo_item_alloc("second"); + if (i1 != NULL) + printf("created item %d '%s'\n", i1->di_id, i1->di_name); + if (i2 != NULL) + printf("created item %d '%s'\n", i2->di_id, i2->di_name); + + if (i1 != NULL) + demo_item_unref(i1); + if (i2 != NULL) + demo_item_unref(i2); + + printf("style_demo: module loaded\n"); + break; + + case MOD_UNLOAD: + mtx_lock(&item_list_lock); + if (!TAILQ_EMPTY(&item_list)) + printf("warning: item list not empty at unload\n"); + mtx_unlock(&item_list_lock); + mtx_destroy(&item_list_lock); + printf("style_demo: module unloaded\n"); + break; + + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t style_demo_mod = { + "style_demo", + style_demo_modevent, + NULL +}; + +DECLARE_MODULE(style_demo, style_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(style_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/Makefile new file mode 100644 index 0000000..a32c183 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/Makefile @@ -0,0 +1,4 @@ +KMOD= types_demo +SRCS= types_demo.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/types_demo.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/types_demo.c new file mode 100644 index 0000000..a11c052 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/demos/types_demo/types_demo.c @@ -0,0 +1,48 @@ +/* + * types_demo.c - Print the sizes of common kernel types at load time. + * + * Companion for the "Hands-On Lab: Exploring Kernel Types" section of + * Chapter 5. + */ + +#include +#include +#include +#include +#include + +static int +types_demo_modevent(module_t mod __unused, int type, void *arg __unused) +{ + + switch (type) { + case MOD_LOAD: + printf("=== FreeBSD Kernel Data Types Demo ===\n"); + printf("uint8_t size: %zu bytes\n", sizeof(uint8_t)); + printf("uint16_t size: %zu bytes\n", sizeof(uint16_t)); + printf("uint32_t size: %zu bytes\n", sizeof(uint32_t)); + printf("uint64_t size: %zu bytes\n", sizeof(uint64_t)); + printf("size_t size: %zu bytes\n", sizeof(size_t)); + printf("off_t size: %zu bytes\n", sizeof(off_t)); + printf("time_t size: %zu bytes\n", sizeof(time_t)); + printf("uintptr_t size: %zu bytes\n", sizeof(uintptr_t)); + printf("void * size: %zu bytes\n", sizeof(void *)); + printf("types_demo: module loaded\n"); + break; + case MOD_UNLOAD: + printf("types_demo: module unloaded\n"); + break; + default: + return (EOPNOTSUPP); + } + return (0); +} + +static moduledata_t types_demo_mod = { + "types_demo", + types_demo_modevent, + NULL +}; + +DECLARE_MODULE(types_demo, types_demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(types_demo, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/Makefile new file mode 100644 index 0000000..32b3155 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 5, Lab 1: Safe Memory Allocation and Cleanup. + +KMOD= memory_safe +SRCS= memory_safe.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/memory_safe.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/memory_safe.c new file mode 100644 index 0000000..486de63 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab1-memory-safe/memory_safe.c @@ -0,0 +1,137 @@ +/* + * memory_safe.c - Safe kernel memory management for Chapter 5, Lab 1. + * + * This module demonstrates the kernel C dialect of memory management: + * - malloc(9) with an explicit malloc_type + * - M_WAITOK versus M_NOWAIT allocation strategies + * - Mandatory cleanup on MOD_UNLOAD + * - Clearing sensitive data before freeing it + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include /* kernel memory allocation */ + +/* + * Define a memory type for debugging and statistics. `vmstat -m` will + * later show allocations under the name "memory_lab". + */ +MALLOC_DEFINE(M_MEMLAB, "memory_lab", "Memory Lab Example Allocations"); + +static void *test_buffer = NULL; +static size_t buffer_size = 1024; + +/* + * safe_allocate - defensive memory allocation. + * + * 1. Validate the requested size. + * 2. Check we are not leaking an existing allocation. + * 3. Request memory with M_WAITOK | M_ZERO. + * 4. Check the return value anyway (a habit worth building). + * 5. Touch the memory so the printout is meaningful. + */ +static int +safe_allocate(size_t size) +{ + + if (size == 0 || size > (1024 * 1024)) { + printf("Memory Lab: Invalid size %zu (must be 1-%d bytes)\n", + size, 1024 * 1024); + return (EINVAL); + } + + if (test_buffer != NULL) { + printf("Memory Lab: Memory already allocated\n"); + return (EBUSY); + } + + test_buffer = malloc(size, M_MEMLAB, M_WAITOK | M_ZERO); + if (test_buffer == NULL) { + /* + * M_WAITOK should not return NULL, but checking is cheap + * and keeps the code defensible if someone later changes + * the flags to M_NOWAIT. + */ + printf("Memory Lab: Allocation failed for %zu bytes\n", size); + return (ENOMEM); + } + + buffer_size = size; + printf("Memory Lab: Successfully allocated %zu bytes at %p\n", + size, test_buffer); + + snprintf((char *)test_buffer, size, "Allocated at ticks=%d", ticks); + printf("Memory Lab: Test data: '%s'\n", (char *)test_buffer); + + return (0); +} + +/* + * safe_deallocate - clean up the allocation. + * + * The kernel C rule: every malloc() must have a matching free(), + * especially during module unload. We also clear the buffer before + * freeing it so that whatever the allocator does with the memory next + * does not leak old contents. + */ +static void +safe_deallocate(void) +{ + + if (test_buffer != NULL) { + printf("Memory Lab: Freeing %zu bytes at %p\n", + buffer_size, test_buffer); + + explicit_bzero(test_buffer, buffer_size); + + free(test_buffer, M_MEMLAB); + test_buffer = NULL; + buffer_size = 0; + + printf("Memory Lab: Memory safely deallocated\n"); + } +} + +static int +memory_safe_handler(module_t mod __unused, int what, void *arg __unused) +{ + int error = 0; + + switch (what) { + case MOD_LOAD: + printf("Memory Lab: Module loading\n"); + error = safe_allocate(1024); + if (error != 0) { + printf("Memory Lab: Failed to allocate memory: %d\n", + error); + return (error); + } + printf("Memory Lab: Module loaded successfully\n"); + break; + + case MOD_UNLOAD: + printf("Memory Lab: Module unloading\n"); + safe_deallocate(); + printf("Memory Lab: Module unloaded safely\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + + return (error); +} + +static moduledata_t memory_safe_mod = { + "memory_safe", + memory_safe_handler, + NULL +}; + +DECLARE_MODULE(memory_safe, memory_safe_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(memory_safe, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/Makefile new file mode 100644 index 0000000..90de11f --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 5, Lab 2: User-Kernel Data Exchange. + +KMOD= echo_safe +SRCS= echo_safe.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/echo_safe.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/echo_safe.c new file mode 100644 index 0000000..8bd1f9c --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab2-echo-safe/echo_safe.c @@ -0,0 +1,148 @@ +/* + * echo_safe.c - Safe user-kernel data exchange for Chapter 5, Lab 2. + * + * This module creates /dev/echolab, which accepts writes from + * userspace into a small kernel buffer and echoes them back on read. + * The point is to practise crossing the user-kernel boundary safely + * with uiomove(9). + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define BUFFER_SIZE 256 + +MALLOC_DEFINE(M_ECHOLAB, "echo_lab", "Echo Lab Allocations"); + +static struct cdev *echo_device; +static char *kernel_buffer; + +static int +echo_write(struct cdev *dev __unused, struct uio *uio, int flag __unused) +{ + size_t bytes_to_copy; + int error; + + printf("Echo Lab: Write request for %zd bytes\n", uio->uio_resid); + + if (kernel_buffer == NULL) + return (ENXIO); + + /* Leave room for the trailing NUL. */ + bytes_to_copy = MIN(uio->uio_resid, BUFFER_SIZE - 1); + + memset(kernel_buffer, 0, BUFFER_SIZE); + + error = uiomove(kernel_buffer, bytes_to_copy, uio); + if (error != 0) { + printf("Echo Lab: uiomove from user failed: %d\n", error); + return (error); + } + + kernel_buffer[bytes_to_copy] = '\0'; + printf("Echo Lab: Received from user: '%s' (%zu bytes)\n", + kernel_buffer, bytes_to_copy); + + return (0); +} + +static int +echo_read(struct cdev *dev __unused, struct uio *uio, int flag __unused) +{ + char response[BUFFER_SIZE + 64]; + size_t response_len; + int error; + + if (kernel_buffer == NULL) + return (ENXIO); + + snprintf(response, sizeof(response), + "Echo: '%s' (received %zu bytes at ticks %d)\n", + kernel_buffer, strnlen(kernel_buffer, BUFFER_SIZE), ticks); + + response_len = strlen(response); + + if (uio->uio_offset >= (off_t)response_len) + return (0); /* EOF */ + + if (uio->uio_offset + uio->uio_resid > (off_t)response_len) + response_len -= uio->uio_offset; + else + response_len = uio->uio_resid; + + printf("Echo Lab: Read request, sending %zu bytes\n", response_len); + + error = uiomove(response + uio->uio_offset, response_len, uio); + if (error != 0) + printf("Echo Lab: uiomove to user failed: %d\n", error); + + return (error); +} + +static struct cdevsw echo_cdevsw = { + .d_version = D_VERSION, + .d_read = echo_read, + .d_write = echo_write, + .d_name = "echolab", +}; + +static int +echo_safe_handler(module_t mod __unused, int what, void *arg __unused) +{ + + switch (what) { + case MOD_LOAD: + printf("Echo Lab: Module loading\n"); + + kernel_buffer = malloc(BUFFER_SIZE, M_ECHOLAB, + M_WAITOK | M_ZERO); + if (kernel_buffer == NULL) + return (ENOMEM); + + echo_device = make_dev(&echo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0666, "echolab"); + if (echo_device == NULL) { + printf("Echo Lab: Failed to create character device\n"); + free(kernel_buffer, M_ECHOLAB); + kernel_buffer = NULL; + return (ENXIO); + } + + printf("Echo Lab: Device /dev/echolab created\n"); + printf("Echo Lab: Test with: echo 'Hello' > /dev/echolab\n"); + printf("Echo Lab: Read with: cat /dev/echolab\n"); + return (0); + + case MOD_UNLOAD: + printf("Echo Lab: Module unloading\n"); + if (echo_device != NULL) { + destroy_dev(echo_device); + echo_device = NULL; + } + if (kernel_buffer != NULL) { + free(kernel_buffer, M_ECHOLAB); + kernel_buffer = NULL; + } + printf("Echo Lab: Module unloaded successfully\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t echo_safe_mod = { + "echo_safe", + echo_safe_handler, + NULL +}; + +DECLARE_MODULE(echo_safe, echo_safe_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(echo_safe, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/Makefile new file mode 100644 index 0000000..bbc7bf4 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 5, Lab 3: Driver-Safe Logging and Device Context. + +KMOD= logging_safe +SRCS= logging_safe.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/logging_safe.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/logging_safe.c new file mode 100644 index 0000000..7fdc1d4 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab3-logging-safe/logging_safe.c @@ -0,0 +1,142 @@ +/* + * logging_safe.c - Kernel logging practices for Chapter 5, Lab 3. + * + * This module demonstrates the three most common logging primitives + * (printf(9), device_printf(9), uprintf(9)) and the discipline that + * goes with them: include context, avoid spam, and rate-limit + * repetitive messages. Because this module is not attached to a real + * device_t, we simulate a softc and log via plain printf() with a + * device-style prefix. + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_LOGLAB, "log_lab", "Logging Lab Allocations"); + +struct log_lab_softc { + char device_name[32]; + int message_count; + int error_count; +}; + +static struct log_lab_softc *lab_softc = NULL; +static struct callout lab_timer; + +static void +demo_printf_variants(struct log_lab_softc *sc) +{ + + printf("Log Lab: General kernel message (printf)\n"); + printf("Log Lab: [%s] Simulated device_printf message\n", + sc->device_name); + printf("Log Lab: [%s] Device message count: %d\n", + sc->device_name, ++sc->message_count); + + printf("Log Lab: INFO - Normal operation message\n"); + printf("Log Lab: WARNING - Something unusual happened\n"); + printf("Log Lab: ERROR - Operation failed, count=%d\n", + ++sc->error_count); + + printf("Log Lab: [%s] status: messages=%d errors=%d ticks=%d\n", + sc->device_name, sc->message_count, sc->error_count, ticks); +} + +static void +demo_logging_safety(struct log_lab_softc *sc) +{ + static int call_count = 0; + + call_count++; + + /* Rate-limit chatter so the kernel log doesn't fill up. */ + if (call_count <= 5 || (call_count % 100) == 0) { + printf("Log Lab: [%s] Safety demo call #%d\n", + sc->device_name, call_count); + } + + if (sc->error_count > 3) { + printf("Log Lab: [%s] ERROR threshold exceeded: %d errors\n", + sc->device_name, sc->error_count); + } + + if ((call_count % 10) == 0) { + printf("Log Lab: [%s] Operational status: %d operations completed\n", + sc->device_name, call_count); + } +} + +static void +lab_timer_cb(void *arg) +{ + struct log_lab_softc *sc = arg; + + if (sc != NULL) { + printf("Log Lab: [%s] Timer tick\n", sc->device_name); + demo_printf_variants(sc); + demo_logging_safety(sc); + + /* Re-arm for another 5 seconds. */ + callout_reset(&lab_timer, hz * 5, lab_timer_cb, sc); + } +} + +static int +logging_safe_handler(module_t mod __unused, int what, void *arg __unused) +{ + + switch (what) { + case MOD_LOAD: + printf("Log Lab: Module loading\n"); + + lab_softc = malloc(sizeof(*lab_softc), M_LOGLAB, + M_WAITOK | M_ZERO); + strlcpy(lab_softc->device_name, "loglab0", + sizeof(lab_softc->device_name)); + + demo_printf_variants(lab_softc); + + callout_init(&lab_timer, 0); + callout_reset(&lab_timer, hz * 5, lab_timer_cb, lab_softc); + + printf("Log Lab: [%s] Module loaded; timer started\n", + lab_softc->device_name); + return (0); + + case MOD_UNLOAD: + printf("Log Lab: Module unloading\n"); + + /* Stop the timer and wait for any in-flight callback. */ + callout_drain(&lab_timer); + + if (lab_softc != NULL) { + printf("Log Lab: [%s] Final stats: messages=%d errors=%d\n", + lab_softc->device_name, + lab_softc->message_count, + lab_softc->error_count); + free(lab_softc, M_LOGLAB); + lab_softc = NULL; + } + + printf("Log Lab: Module unloaded successfully\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t logging_safe_mod = { + "logging_safe", + logging_safe_handler, + NULL +}; + +DECLARE_MODULE(logging_safe, logging_safe_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(logging_safe, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/Makefile b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/Makefile new file mode 100644 index 0000000..6fddac5 --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 5, Lab 4: Error Handling and Graceful Failures. + +KMOD= error_handling +SRCS= error_handling.c + +.include diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/error_handling.c b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/error_handling.c new file mode 100644 index 0000000..fffb49f --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/lab4-error-handling/error_handling.c @@ -0,0 +1,285 @@ +/* + * error_handling.c - Comprehensive error handling for Chapter 5, Lab 4. + * + * This module creates /dev/errorlab, a small control surface that + * accepts a handful of text commands (alloc, free , error_on, + * error_off, status, cleanup) to let you exercise error paths on + * demand. + * + * The kernel C dialect covered here: + * - errno-style return codes + * - resource cleanup on every error path + * - error injection for deliberate failure testing + * - statistics counters updated atomically + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_BUFFERS 5 +#define BUFFER_SIZE 1024 + +MALLOC_DEFINE(M_ERRORLAB, "error_lab", "Error Handling Lab"); + +struct error_lab_state { + void *buffers[MAX_BUFFERS]; + int buffer_count; + int error_injection_enabled; + int operation_count; + int success_count; + int error_count; +}; + +static struct error_lab_state *lab_state = NULL; +static struct cdev *error_device = NULL; + +static void +cleanup_all_resources(struct error_lab_state *state) +{ + int i; + + if (state == NULL) + return; + + printf("Error Lab: Beginning resource cleanup\n"); + for (i = 0; i < MAX_BUFFERS; i++) { + if (state->buffers[i] != NULL) { + printf("Error Lab: Freeing buffer %d at %p\n", + i, state->buffers[i]); + free(state->buffers[i], M_ERRORLAB); + state->buffers[i] = NULL; + } + } + state->buffer_count = 0; + printf("Error Lab: All %d slots cleared\n", MAX_BUFFERS); +} + +static int +allocate_buffer_safe(struct error_lab_state *state) +{ + void *buf; + int slot; + + if (state == NULL) + return (EINVAL); + + state->operation_count++; + + if (state->buffer_count >= MAX_BUFFERS) { + state->error_count++; + return (ENOSPC); + } + + for (slot = 0; slot < MAX_BUFFERS; slot++) { + if (state->buffers[slot] == NULL) + break; + } + if (slot >= MAX_BUFFERS) { + state->error_count++; + return (ENOSPC); + } + + if (state->error_injection_enabled) { + printf("Error Lab: Simulating allocation failure\n"); + state->error_count++; + return (ENOMEM); + } + + buf = malloc(BUFFER_SIZE, M_ERRORLAB, M_NOWAIT | M_ZERO); + if (buf == NULL) { + printf("Error Lab: Real allocation failure for %d bytes\n", + BUFFER_SIZE); + state->error_count++; + return (ENOMEM); + } + + state->buffers[slot] = buf; + state->buffer_count++; + state->success_count++; + + printf("Error Lab: Allocated buffer %d at %p (%d/%d total)\n", + slot, buf, state->buffer_count, MAX_BUFFERS); + return (0); +} + +static int +free_buffer_safe(struct error_lab_state *state, int slot) +{ + + if (state == NULL) + return (EINVAL); + if (slot < 0 || slot >= MAX_BUFFERS) { + printf("Error Lab: Invalid slot %d (must be 0-%d)\n", + slot, MAX_BUFFERS - 1); + return (EINVAL); + } + if (state->buffers[slot] == NULL) + return (ENOENT); + + printf("Error Lab: Freeing buffer %d at %p\n", + slot, state->buffers[slot]); + free(state->buffers[slot], M_ERRORLAB); + state->buffers[slot] = NULL; + state->buffer_count--; + return (0); +} + +static int +error_write(struct cdev *dev __unused, struct uio *uio, int flag __unused) +{ + char command[64]; + size_t len; + int error; + int slot; + + if (lab_state == NULL) + return (EIO); + + len = MIN(uio->uio_resid, sizeof(command) - 1); + error = uiomove(command, len, uio); + if (error != 0) + return (error); + + command[len] = '\0'; + if (len > 0 && command[len - 1] == '\n') + command[len - 1] = '\0'; + + printf("Error Lab: Processing command: '%s'\n", command); + + if (strcmp(command, "alloc") == 0) { + error = allocate_buffer_safe(lab_state); + } else if (strncmp(command, "free ", 5) == 0) { + slot = strtol(command + 5, NULL, 10); + error = free_buffer_safe(lab_state, slot); + } else if (strcmp(command, "error_on") == 0) { + lab_state->error_injection_enabled = 1; + printf("Error Lab: Error injection ENABLED\n"); + } else if (strcmp(command, "error_off") == 0) { + lab_state->error_injection_enabled = 0; + printf("Error Lab: Error injection DISABLED\n"); + } else if (strcmp(command, "status") == 0) { + printf("Error Lab: Status: %d/%d buffers, %d ops, %d ok, %d err\n", + lab_state->buffer_count, MAX_BUFFERS, + lab_state->operation_count, lab_state->success_count, + lab_state->error_count); + } else if (strcmp(command, "cleanup") == 0) { + cleanup_all_resources(lab_state); + } else { + printf("Error Lab: Unknown command '%s'\n", command); + printf("Error Lab: Valid commands: alloc, free , " + "error_on, error_off, status, cleanup\n"); + error = EINVAL; + } + + return (error); +} + +static int +error_read(struct cdev *dev __unused, struct uio *uio, int flag __unused) +{ + char status[512]; + size_t len; + int i; + + if (lab_state == NULL) + return (EIO); + + len = snprintf(status, sizeof(status), + "Error Handling Lab Status\n" + "========================\n" + "Buffers: %d/%d allocated\n" + "Operations: %d total (%d ok, %d err)\n" + "Error injection: %s\n" + "\nBuffer map:\n", + lab_state->buffer_count, MAX_BUFFERS, + lab_state->operation_count, lab_state->success_count, + lab_state->error_count, + lab_state->error_injection_enabled ? "ENABLED" : "disabled"); + + for (i = 0; i < MAX_BUFFERS; i++) { + len += snprintf(status + len, sizeof(status) - len, + " Slot %d: %s\n", i, + lab_state->buffers[i] ? "ALLOCATED" : "free"); + } + + if (uio->uio_offset >= (off_t)len) + return (0); + + return (uiomove(status + uio->uio_offset, + MIN(len - (size_t)uio->uio_offset, uio->uio_resid), uio)); +} + +static struct cdevsw error_cdevsw = { + .d_version = D_VERSION, + .d_read = error_read, + .d_write = error_write, + .d_name = "errorlab", +}; + +static int +error_handling_handler(module_t mod __unused, int what, void *arg __unused) +{ + + switch (what) { + case MOD_LOAD: + printf("Error Lab: Module loading\n"); + + lab_state = malloc(sizeof(*lab_state), M_ERRORLAB, + M_WAITOK | M_ZERO); + if (lab_state == NULL) + return (ENOMEM); + + error_device = make_dev(&error_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0666, "errorlab"); + if (error_device == NULL) { + free(lab_state, M_ERRORLAB); + lab_state = NULL; + return (ENXIO); + } + + printf("Error Lab: Device /dev/errorlab created\n"); + printf("Error Lab: Try: echo 'alloc' > /dev/errorlab\n"); + printf("Error Lab: Status: cat /dev/errorlab\n"); + return (0); + + case MOD_UNLOAD: + printf("Error Lab: Module unloading\n"); + + if (error_device != NULL) { + destroy_dev(error_device); + error_device = NULL; + } + if (lab_state != NULL) { + printf("Error Lab: Final stats: %d total / %d ok / %d err\n", + lab_state->operation_count, + lab_state->success_count, + lab_state->error_count); + cleanup_all_resources(lab_state); + free(lab_state, M_ERRORLAB); + lab_state = NULL; + } + printf("Error Lab: Module unloaded successfully\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t error_handling_mod = { + "error_handling", + error_handling_handler, + NULL +}; + +DECLARE_MODULE(error_handling, error_handling_mod, + SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(error_handling, 1); diff --git a/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/scripts/rebuild.sh b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/scripts/rebuild.sh new file mode 100755 index 0000000..046616d --- /dev/null +++ b/examples/part-01/ch05-understanding-c-for-freebsd-kernel-programming/scripts/rebuild.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# +# rebuild.sh - convenience script for Chapter 5 demos and labs. +# +# Given a directory that contains a Makefile and a kernel module +# source file, this script: +# +# 1. kldunload's the module (if already loaded) +# 2. runs `make clean && make` +# 3. kldload's the freshly built .ko +# 4. prints the tail of dmesg so you can see what happened +# +# Usage: +# ./scripts/rebuild.sh lab1-memory-safe +# ./scripts/rebuild.sh demos/types_demo +# +# Run it as root (or through sudo) because kldload/kldunload require +# privilege. + +set -eu + +if [ $# -ne 1 ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +DIR="$1" +if [ ! -d "$DIR" ]; then + echo "$0: no such directory: $DIR" >&2 + exit 1 +fi + +cd "$DIR" + +MODULE="$(awk '/^KMOD[[:space:]]*=/ { print $NF; exit }' Makefile)" +if [ -z "$MODULE" ]; then + echo "$0: could not parse KMOD from Makefile" >&2 + exit 1 +fi + +if kldstat -q -n "$MODULE" >/dev/null 2>&1; then + echo "==> kldunload $MODULE" + kldunload "$MODULE" +fi + +echo "==> make clean && make in $DIR" +make clean >/dev/null +make + +echo "==> kldload ./$MODULE.ko" +kldload "./$MODULE.ko" + +echo "==> dmesg tail" +dmesg | tail -n 15 diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/Makefile b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/Makefile new file mode 100644 index 0000000..8d0e13c --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/Makefile @@ -0,0 +1,10 @@ +# Makefile for Chapter 6, Lab 2: Minimal Module with Logs Only. +# +# FreeBSD's kernel-module build infrastructure handles the heavy +# lifting. The only variables you set are the module name and the +# list of sources. + +KMOD= hello +SRCS= hello.c + +.include diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/hello.c b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/hello.c new file mode 100644 index 0000000..3148617 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab2-hello-module/hello.c @@ -0,0 +1,75 @@ +/* + * hello.c - Minimal FreeBSD kernel module for Chapter 6, Lab 2. + * + * This module does nothing except print messages when it is loaded + * and unloaded. Its only job is to confirm that your build tools are + * healthy and that you can move a .ko into and out of the kernel + * safely. + * + * Compatible with FreeBSD 14.3. + */ + +#include /* system parameter definitions */ +#include /* kernel module definitions */ +#include /* kernel types and macros */ +#include /* printf and friends */ + +/* + * Module event handler. + * + * The kernel calls this function with a `type` argument describing + * the event: + * + * MOD_LOAD - module is being loaded into the kernel + * MOD_UNLOAD - module is being removed from the kernel + * MOD_SHUTDOWN - system is shutting down (rare, usually ignored) + * MOD_QUIESCE - pre-unload check (advanced, not used here) + * + * Return 0 for success or an errno for failure. Returning a non-zero + * value for MOD_LOAD aborts the load; for MOD_UNLOAD it refuses the + * unload. + */ +static int +hello_modevent(module_t mod __unused, int type, void *arg __unused) +{ + int error = 0; + + switch (type) { + case MOD_LOAD: + printf("Hello: Module loaded successfully!\n"); + printf("Hello: This message appears in dmesg\n"); + printf("Hello: Module address: %p\n", (void *)&hello_modevent); + break; + + case MOD_UNLOAD: + printf("Hello: Module unloaded. Goodbye!\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + + return (error); +} + +/* + * moduledata_t ties the module name to its event handler. The + * `NULL` slot is for optional private data (unused here). + */ +static moduledata_t hello_mod = { + "hello", /* module name */ + hello_modevent, /* event handler */ + NULL /* no private data */ +}; + +/* + * DECLARE_MODULE registers the module with the kernel. + * + * name: "hello" (must match the string above) + * moduledata_t: the struct just above + * subsystem: SI_SUB_DRIVERS is a safe default + * order: SI_ORDER_MIDDLE is a safe default + */ +DECLARE_MODULE(hello, hello_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(hello, 1); diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/Makefile b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/Makefile new file mode 100644 index 0000000..a544a92 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 6, Lab 3: Create and Remove a Device Node. + +KMOD= demo +SRCS= demo.c + +.include diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/demo.c b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/demo.c new file mode 100644 index 0000000..c4173d4 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab3-demo-device/demo.c @@ -0,0 +1,163 @@ +/* + * demo.c - A simple character device for Chapter 6, Lab 3. + * + * This driver creates /dev/demo on load and destroys it on unload. + * It implements the four classic cdevsw entry points: + * + * open - log who opened the device + * close - log who closed it + * read - return a short greeting message + * write - accept (and log) up to 128 bytes from userspace + * + * Everything is deliberately minimal. Real drivers allocate per-open + * state, validate input carefully, and keep much less noisy logs. + * See Chapter 7 onward for that discipline. + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Global handle to the /dev/demo node. NULL until MOD_LOAD creates + * it, cleared back to NULL after MOD_UNLOAD destroys it. + */ +static struct cdev *demo_dev = NULL; + +/* --- entry points ------------------------------------------------ */ + +static int +demo_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + + printf("demo: Device opened (pid=%d, comm=%s)\n", + td->td_proc->p_pid, td->td_proc->p_comm); + return (0); +} + +static int +demo_close(struct cdev *dev __unused, int fflag __unused, + int devtype __unused, struct thread *td) +{ + + printf("demo: Device closed (pid=%d)\n", td->td_proc->p_pid); + return (0); +} + +static int +demo_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + char message[] = "Hello from demo driver!\n"; + size_t len; + int error; + + printf("demo: Read called, uio_resid=%zd bytes requested\n", + uio->uio_resid); + + /* + * Transfer the smaller of "what the user asked for" and + * "what we have available". The message terminator is kept + * out of the transferred count: devices are not strings. + */ + len = MIN(uio->uio_resid, sizeof(message) - 1); + error = uiomove(message, len, uio); + if (error != 0) { + printf("demo: Read failed, error=%d\n", error); + return (error); + } + + printf("demo: Read completed, transferred %zu bytes\n", len); + return (0); +} + +static int +demo_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + char buffer[128]; + size_t len; + int error; + + len = MIN(uio->uio_resid, sizeof(buffer) - 1); + error = uiomove(buffer, len, uio); + if (error != 0) { + printf("demo: Write failed during uiomove, error=%d\n", error); + return (error); + } + + buffer[len] = '\0'; + printf("demo: User wrote %zu bytes: \"%s\"\n", len, buffer); + return (0); +} + +/* --- cdevsw (routing table) -------------------------------------- */ + +static struct cdevsw demo_cdevsw = { + .d_version = D_VERSION, + .d_open = demo_open, + .d_close = demo_close, + .d_read = demo_read, + .d_write = demo_write, + .d_name = "demo", +}; + +/* --- module event handler ---------------------------------------- */ + +static int +demo_modevent(module_t mod __unused, int event, void *arg __unused) +{ + int error = 0; + + switch (event) { + case MOD_LOAD: + demo_dev = make_dev(&demo_cdevsw, + 0, /* unit */ + UID_ROOT, + GID_WHEEL, + 0666, /* rw-rw-rw-, lab use only */ + "demo"); + if (demo_dev == NULL) { + printf("demo: Failed to create device node\n"); + return (ENXIO); + } + printf("demo: /dev/demo created\n"); + break; + + case MOD_UNLOAD: + if (demo_dev != NULL) { + /* + * destroy_dev() removes the node from /dev and + * waits for any in-flight cdev methods to + * return before it comes back. After this + * returns, none of our handlers will ever run + * again for the old cdev. + */ + destroy_dev(demo_dev); + demo_dev = NULL; + printf("demo: /dev/demo destroyed\n"); + } + break; + + default: + error = EOPNOTSUPP; + break; + } + + return (error); +} + +static moduledata_t demo_mod = { + "demo", + demo_modevent, + NULL +}; + +DECLARE_MODULE(demo, demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(demo, 1); diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/Makefile b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/Makefile new file mode 100644 index 0000000..e8b76c2 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/Makefile @@ -0,0 +1,9 @@ +# Makefile for Chapter 6, Lab 4, Experiment 1A (DELIBERATELY BROKEN). +# +# Only load this module in a lab VM. The module leaks /dev/demo on +# unload; reboot the VM to clean up. + +KMOD= demo +SRCS= demo.c + +.include diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/demo.c b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/demo.c new file mode 100644 index 0000000..0607cf2 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/broken/demo.c @@ -0,0 +1,94 @@ +/* + * demo.c - DELIBERATELY BROKEN version for Chapter 6, Lab 4. + * + * This is Experiment 1A from the chapter: the MOD_UNLOAD handler + * forgets to call destroy_dev(). That single missing line leaves + * /dev/demo orphaned in the filesystem after the module is unloaded. + * + * DO NOT USE THIS FILE AS A REFERENCE FOR REAL DRIVERS. + * It is included only so you can reproduce the failure the + * chapter describes, then contrast it with the fixed version + * in ../fixed/demo.c. + * + * Expected observation: + * + * # make && sudo kldload ./demo.ko + * # ls -l /dev/demo # present + * # sudo kldunload demo + * # ls -l /dev/demo # STILL PRESENT -- bug! + * # cat /dev/demo # undefined behaviour + * + * Reboot the lab VM when you are done observing the leak. + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include + +static struct cdev *demo_dev = NULL; + +static int +demo_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + char message[] = "Hello from broken demo!\n"; + size_t len = MIN(uio->uio_resid, sizeof(message) - 1); + + return (uiomove(message, len, uio)); +} + +static struct cdevsw demo_cdevsw = { + .d_version = D_VERSION, + .d_read = demo_read, + .d_name = "demo", +}; + +static int +demo_modevent(module_t mod __unused, int event, void *arg __unused) +{ + + switch (event) { + case MOD_LOAD: + demo_dev = make_dev(&demo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0666, "demo"); + if (demo_dev == NULL) { + printf("demo: Failed to create /dev/demo\n"); + return (ENXIO); + } + printf("demo: /dev/demo created (broken example)\n"); + break; + + case MOD_UNLOAD: + /* + * THE BUG: we clear the pointer and log a lie, but we + * never call destroy_dev(). The kernel still has a + * cdev registered, /dev/demo still exists, and nothing + * will clean up until the system reboots. + */ + if (demo_dev != NULL) { + /* destroy_dev(demo_dev); <-- missing */ + demo_dev = NULL; + printf("demo: /dev/demo destroyed (lie!)\n"); + } + break; + + default: + return (EOPNOTSUPP); + } + + return (0); +} + +static moduledata_t demo_mod = { + "demo", + demo_modevent, + NULL +}; + +DECLARE_MODULE(demo, demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(demo, 1); diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/Makefile b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/Makefile new file mode 100644 index 0000000..a6ef2c1 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/Makefile @@ -0,0 +1,6 @@ +# Makefile for Chapter 6, Lab 4: final template with proper cleanup. + +KMOD= demo +SRCS= demo.c + +.include diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/demo.c b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/demo.c new file mode 100644 index 0000000..514406b --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/lab4-error-handling/fixed/demo.c @@ -0,0 +1,164 @@ +/* + * demo.c - Final template for Chapter 6, Lab 4. + * + * This version is the end state of Lab 4's experiments. It shows + * the habits every production driver should follow: + * + * - always check the return value of make_dev() and malloc() + * - always NULL-check before calling destroy_dev() or free() + * - always clear pointers after freeing them + * - tear down resources in the reverse order of acquisition + * - use a single "fail:" label to centralise error unwinding + * + * The driver creates /dev/demo, keeps a small kernel buffer, and + * tears everything down cleanly on unload. + * + * Use this file as a reference skeleton when you move on to + * Chapter 7. + * + * Compatible with FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* Private memory type for this driver (shows up in `vmstat -m`). */ +static MALLOC_DEFINE(M_DEMO, "demo", "Chapter 6 demo driver"); + +/* + * Global state. In a real driver this would live in a per-device + * softc allocated by Newbus. For the sake of Chapter 6 we keep it + * simple. + */ +static struct cdev *demo_dev = NULL; +static char *demo_buffer = NULL; +#define DEMO_BUFSZ 128 + +/* --- cdev entry points ------------------------------------------- */ + +static int +demo_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + size_t len; + + if (demo_buffer == NULL) + return (ENODEV); + + len = MIN(uio->uio_resid, strlen(demo_buffer)); + return (uiomove(demo_buffer, len, uio)); +} + +static int +demo_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + size_t len; + int error; + + if (demo_buffer == NULL) + return (ENODEV); + + len = MIN(uio->uio_resid, DEMO_BUFSZ - 1); + error = uiomove(demo_buffer, len, uio); + if (error != 0) + return (error); + + demo_buffer[len] = '\0'; + printf("demo: user wrote %zu bytes: \"%s\"\n", len, demo_buffer); + return (0); +} + +static struct cdevsw demo_cdevsw = { + .d_version = D_VERSION, + .d_read = demo_read, + .d_write = demo_write, + .d_name = "demo", +}; + +/* --- module event handler (with unwinding) ----------------------- */ + +static int +demo_modevent(module_t mod __unused, int event, void *arg __unused) +{ + int error = 0; + + switch (event) { + case MOD_LOAD: + /* Step 1: allocate a kernel buffer. */ + demo_buffer = malloc(DEMO_BUFSZ, M_DEMO, + M_WAITOK | M_ZERO); + /* + * M_WAITOK will not return NULL on modern FreeBSD, but + * keeping the check makes the intent explicit and + * survives future API changes. + */ + if (demo_buffer == NULL) { + error = ENOMEM; + goto fail; + } + strlcpy(demo_buffer, "Hello from a disciplined driver!\n", + DEMO_BUFSZ); + + /* Step 2: create the device node. */ + demo_dev = make_dev(&demo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0666, "demo"); + if (demo_dev == NULL) { + printf("demo: make_dev failed\n"); + error = ENXIO; + goto fail; + } + + printf("demo: /dev/demo created\n"); + return (0); + + case MOD_UNLOAD: + /* + * Tear down in reverse order of creation. Each step + * checks for NULL first so MOD_UNLOAD can recover + * cleanly from a partial MOD_LOAD (e.g. make_dev + * failed after malloc succeeded). + */ + if (demo_dev != NULL) { + destroy_dev(demo_dev); + demo_dev = NULL; + } + if (demo_buffer != NULL) { + free(demo_buffer, M_DEMO); + demo_buffer = NULL; + } + printf("demo: /dev/demo destroyed cleanly\n"); + return (0); + + default: + return (EOPNOTSUPP); + } + +fail: + /* + * Centralised error unwinding for MOD_LOAD. Every allocation + * above walks back through this block on the way out. + */ + if (demo_dev != NULL) { + destroy_dev(demo_dev); + demo_dev = NULL; + } + if (demo_buffer != NULL) { + free(demo_buffer, M_DEMO); + demo_buffer = NULL; + } + return (error); +} + +static moduledata_t demo_mod = { + "demo", + demo_modevent, + NULL +}; + +DECLARE_MODULE(demo, demo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(demo, 1); diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/patterns/patterns.c b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/patterns/patterns.c new file mode 100644 index 0000000..68a40f3 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/patterns/patterns.c @@ -0,0 +1,154 @@ +/* + * patterns.c - scratch space for Chapter 6 + * + * Chapter 6 asks you to "type the micro-snippets yourself" so your + * fingers remember the shape of a FreeBSD driver. This file collects + * the recurring fragments in one place so you can look them up, retype + * them, and get a feel for the vocabulary before you build anything in + * Chapter 7. + * + * This file is NOT a working module. It will not compile. Its only + * purpose is to show the shapes; nothing here ever gets linked. + * + * Matches FreeBSD 14.3. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* --------------------------------------------------------------- + * 1. The softc: your per-instance private state. + * --------------------------------------------------------------- */ +struct mydriver_softc { + device_t dev; /* handy back-pointer */ + struct mtx mtx; /* driver-wide lock */ + struct cdev *cdev; /* /dev entry, if any */ + struct resource *mem_res; /* MMIO resource */ + int mem_rid; + uint64_t bytes_rx; /* example statistic */ +}; + +/* --------------------------------------------------------------- + * 2. The minimal probe function. + * + * Probe answers one question only: "am I the driver for this + * device?" It must not allocate resources or touch hardware. + * --------------------------------------------------------------- */ +static int +mydriver_probe(device_t dev) +{ + device_set_desc(dev, "My Example Driver"); + return (BUS_PROBE_DEFAULT); +} + +/* --------------------------------------------------------------- + * 3. A cdevsw skeleton. + * + * Only fill in the entry points you actually implement. Missing + * handlers fall back to kernel defaults (open/close always succeed, + * read returns EOF, write returns ENODEV, and so on). + * --------------------------------------------------------------- */ +static d_read_t mydriver_read; +static d_write_t mydriver_write; +static d_ioctl_t mydriver_ioctl; + +static struct cdevsw mydriver_cdevsw = { + .d_version = D_VERSION, + .d_read = mydriver_read, + .d_write = mydriver_write, + .d_ioctl = mydriver_ioctl, + .d_name = "mydriver", +}; + +/* --------------------------------------------------------------- + * 4. The device method table. + * + * This is the routing table Newbus consults when it needs to call + * probe/attach/detach. DEVMETHOD_END terminates the table. + * --------------------------------------------------------------- */ +static device_method_t mydriver_methods[] = { + DEVMETHOD(device_probe, mydriver_probe), + DEVMETHOD(device_attach, mydriver_attach), + DEVMETHOD(device_detach, mydriver_detach), + DEVMETHOD_END +}; + +static driver_t mydriver_driver = { + "mydriver", + mydriver_methods, + sizeof(struct mydriver_softc) +}; + +/* --------------------------------------------------------------- + * 5. Module registration (FreeBSD 14.3 macro shape). + * + * DRIVER_MODULE takes exactly five arguments: + * name, parent bus, driver_t, event handler, event arg. + * + * Older code you may find online sometimes shows a six-argument + * form with a separate devclass_t; that form no longer compiles. + * --------------------------------------------------------------- */ +DRIVER_MODULE(mydriver, pci, mydriver_driver, NULL, NULL); +MODULE_VERSION(mydriver, 1); + +/* --------------------------------------------------------------- + * 6. The universal first line of any driver method: grab the softc. + * --------------------------------------------------------------- */ +static int +mydriver_attach(device_t dev) +{ + struct mydriver_softc *sc; + + sc = device_get_softc(dev); + sc->dev = dev; + + /* allocate resources, initialise hardware, create /dev, ... */ + + device_printf(dev, "attached\n"); + return (0); +} + +/* --------------------------------------------------------------- + * 7. The failure-unwinding pattern for attach. + * + * Each cleanup label handles exactly the state established by the + * step above it. Labels appear in reverse order of allocation, and + * control jumps to the one matching the last successful step. + * --------------------------------------------------------------- */ +#if 0 /* pseudocode shape only */ +static int +mydriver_attach_unwind(device_t dev) +{ + struct mydriver_softc *sc = device_get_softc(dev); + int error; + + mtx_init(&sc->mtx, "mydriver", NULL, MTX_DEF); + + sc->mem_rid = PCIR_BAR(0); + sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->mem_rid, RF_ACTIVE); + if (sc->mem_res == NULL) { + error = ENXIO; + goto fail_mtx; + } + + error = mydriver_hw_init(sc); + if (error != 0) + goto fail_mem; + + device_printf(dev, "attached\n"); + return (0); + +fail_mem: + bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem_res); +fail_mtx: + mtx_destroy(&sc->mtx); + return (error); +} +#endif diff --git a/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/scripts/rebuild.sh b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/scripts/rebuild.sh new file mode 100755 index 0000000..1b85da9 --- /dev/null +++ b/examples/part-01/ch06-the-anatomy-of-a-freebsd-driver/scripts/rebuild.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# +# rebuild.sh - convenience script for Chapter 6 labs. +# +# Given a directory that contains a Makefile and a .c source, this +# script: +# +# 1. kldunload's the module (if it is already loaded) +# 2. runs `make clean && make` +# 3. kldload's the freshly built .ko +# 4. prints the tail of dmesg so you can see what happened +# +# Usage: +# ./scripts/rebuild.sh lab2-hello-module +# ./scripts/rebuild.sh lab3-demo-device +# +# Run it as root (or through sudo) because kldload/kldunload require +# privilege. + +set -eu + +if [ $# -ne 1 ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +DIR="$1" +if [ ! -d "$DIR" ]; then + echo "$0: no such directory: $DIR" >&2 + exit 1 +fi + +cd "$DIR" + +# Try to derive the module name from KMOD= in the Makefile. +MODULE="$(awk '/^KMOD[[:space:]]*=/ { print $NF; exit }' Makefile)" +if [ -z "$MODULE" ]; then + echo "$0: could not parse KMOD from Makefile" >&2 + exit 1 +fi + +if kldstat -q -n "$MODULE" >/dev/null 2>&1; then + echo "==> kldunload $MODULE" + kldunload "$MODULE" +fi + +echo "==> make clean && make in $DIR" +make clean >/dev/null +make + +echo "==> kldload ./$MODULE.ko" +kldload "./$MODULE.ko" + +echo "==> dmesg tail" +dmesg | tail -n 10 diff --git a/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/Makefile b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/Makefile new file mode 100644 index 0000000..b337bad --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/Makefile @@ -0,0 +1,11 @@ +# Lab 7.4 variant B: deliberate failure right after make_dev_s succeeds. +# +# Loading this driver should fail with ENOMEM. The /dev node was +# created and must be destroyed by the unwind path; verify with +# `ls /dev/myfirst0` (no such file). + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/myfirst.c b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/myfirst.c new file mode 100644 index 0000000..15d67dd --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-dev/myfirst.c @@ -0,0 +1,161 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Lab 7.4, variant B. + * + * Same code as stage2-final/myfirst.c, but attach is rigged to fail + * right after make_dev_s succeeds, before sysctl setup. The failure + * jumps to fail_dev, exercising the destroy_dev() leg of the unwind. + * Loading should fail with ENOMEM, no /dev/myfirst0 should be left + * behind, and no leaked mutex. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + struct mtx mtx; + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + int is_attached; + int is_open; + struct cdev *cdev; + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + /* SIMULATED FAILURE FOR LAB 7.4 (variant B) */ + device_printf(dev, "Simulating failure after dev node creation\n"); + error = ENOMEM; + goto fail_dev; + + /* unreachable in this variant */ + return (0); + +fail_dev: + destroy_dev(sc->cdev); + sc->cdev = NULL; +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/Makefile b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/Makefile new file mode 100644 index 0000000..26fc7d1 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/Makefile @@ -0,0 +1,10 @@ +# Lab 7.4 variant A: deliberate failure right after mutex init. +# +# Loading this driver should fail with ENXIO and leave nothing behind: +# no /dev/myfirst0, no dev.myfirst.0 sysctl tree, no leaked mutex. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/myfirst.c b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/myfirst.c new file mode 100644 index 0000000..2bd6063 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/labs/lab7.4-fail-mtx/myfirst.c @@ -0,0 +1,142 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Lab 7.4, variant A. + * + * Same code as stage2-final/myfirst.c, but attach is rigged to fail + * immediately after mtx_init. The failure jumps to fail_mtx so we + * exercise the very first cleanup label. Loading should fail with + * ENXIO and leave no /dev node, no sysctl tree, and no leaked mutex. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + struct mtx mtx; + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + int is_attached; + int is_open; + struct cdev *cdev; + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + /* SIMULATED FAILURE FOR LAB 7.4 (variant A) */ + device_printf(dev, "Simulating attach failure for testing\n"); + error = ENXIO; + goto fail_mtx; + + /* unreachable in this variant */ + return (0); + +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch07-writing-your-first-driver/scripts/rebuild.sh b/examples/part-02/ch07-writing-your-first-driver/scripts/rebuild.sh new file mode 100755 index 0000000..6d481de --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/scripts/rebuild.sh @@ -0,0 +1,141 @@ +#!/bin/sh +# +# FreeBSD kernel module rebuild script +# Usage: ./rebuild.sh +# +# Drops, rebuilds, reloads, and reports on a kernel module under +# development. Designed for the inner loop of /home/${USER}/drivers +# style work, not for production deployment. + +set -e + +MODULE_NAME="${1}" + +if [ -t 1 ]; then + RED='\033[0;31m' + GREEN='\033[0;32m' + YELLOW='\033[1;33m' + BLUE='\033[0;34m' + NC='\033[0m' +else + RED='' + GREEN='' + YELLOW='' + BLUE='' + NC='' +fi + +print_step() { printf "${BLUE}==>${NC} ${1}\n"; } +print_success() { printf "${GREEN}OK${NC} ${1}\n"; } +print_error() { printf "${RED}ERR${NC} ${1}\n" >&2; } +print_warning() { printf "${YELLOW}!${NC} ${1}\n"; } + +check_root() { + if [ "$(id -u)" -ne 0 ]; then + print_error "This script must be run as root or with sudo" + exit 1 + fi +} + +is_module_loaded() { + kldstat -q -n "${1}" 2>/dev/null +} + +if [ -z "${MODULE_NAME}" ]; then + print_error "Usage: $0 " + exit 1 +fi + +if [ ! -f "${MODULE_NAME}.c" ]; then + print_error "Source file '${MODULE_NAME}.c' not found in current directory" + exit 1 +fi + +check_root + +if [ ! -f "Makefile" ]; then + print_error "Makefile not found in current directory" + exit 1 +fi + +print_step "Checking if module '${MODULE_NAME}' is loaded..." +if is_module_loaded "${MODULE_NAME}"; then + print_warning "Module is loaded, unloading..." + + DMESG_BEFORE_UNLOAD=$(dmesg | wc -l) + + if kldunload "${MODULE_NAME}" 2>/dev/null; then + print_success "Module unloaded successfully" + else + print_error "Failed to unload module" + exit 1 + fi + + sleep 1 + if is_module_loaded "${MODULE_NAME}"; then + print_error "Module still loaded after unload attempt" + exit 1 + fi + print_success "Verified: module removed from memory" + + DMESG_AFTER_UNLOAD=$(dmesg | wc -l) + DMESG_UNLOAD_NEW=$((DMESG_AFTER_UNLOAD - DMESG_BEFORE_UNLOAD)) + if [ ${DMESG_UNLOAD_NEW} -gt 0 ]; then + echo + print_step "Kernel messages from unload:" + dmesg | tail -n ${DMESG_UNLOAD_NEW} + echo + fi +else + print_success "Module not loaded, proceeding..." +fi + +print_step "Cleaning build artifacts..." +make clean +print_success "Clean completed" + +print_step "Building module..." +make +print_success "Build completed" + +if [ ! -f "./${MODULE_NAME}.ko" ]; then + print_error "Module file './${MODULE_NAME}.ko' not found after build" + exit 1 +fi + +print_step "Loading module..." +DMESG_BEFORE=$(dmesg | wc -l) + +if kldload "./${MODULE_NAME}.ko"; then + print_success "Module load command executed" +else + print_error "Failed to load module" + exit 1 +fi + +sleep 1 +print_step "Verifying module load..." +if is_module_loaded "${MODULE_NAME}"; then + print_success "Module is loaded in kernel" + echo + kldstat | head -n 1 + kldstat | grep "${MODULE_NAME}" +else + print_error "Module not found in kldstat output" + exit 1 +fi + +echo +print_step "Recent kernel messages from load:" +DMESG_AFTER=$(dmesg | wc -l) +DMESG_NEW=$((DMESG_AFTER - DMESG_BEFORE)) + +if [ ${DMESG_NEW} -gt 0 ]; then + dmesg | tail -n ${DMESG_NEW} +else + print_warning "No new kernel messages" + dmesg | tail -n 5 +fi + +echo +print_success "Module '${MODULE_NAME}' rebuilt and loaded successfully!" diff --git a/examples/part-02/ch07-writing-your-first-driver/scripts/stress_test.sh b/examples/part-02/ch07-writing-your-first-driver/scripts/stress_test.sh new file mode 100755 index 0000000..a6a1076 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/scripts/stress_test.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# +# Repeatedly load and unload the myfirst module to look for leaks or +# crashes that only show up over many cycles. Run from the same +# directory as your built myfirst.ko. +# +# Usage: sudo ./stress_test.sh [iterations] + +set -e + +ITERATIONS="${1:-100}" +MODULE="myfirst" + +if [ ! -f "./${MODULE}.ko" ]; then + echo "stress_test.sh: ./${MODULE}.ko not found" >&2 + exit 1 +fi + +i=1 +while [ "$i" -le "$ITERATIONS" ]; do + echo "Iteration $i / $ITERATIONS" + kldload "./${MODULE}.ko" + sleep 0.1 + kldunload "${MODULE}" + i=$((i + 1)) +done + +echo "Stress test completed: ${ITERATIONS} cycles without errors." diff --git a/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/Makefile b/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/Makefile new file mode 100644 index 0000000..fa84e75 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/Makefile @@ -0,0 +1,9 @@ +# Makefile for myfirst driver +# +# Stage 0 of Chapter 7: minimal scaffold that loads and unloads, +# without registering any device or creating /dev nodes. + +KMOD= myfirst +SRCS= myfirst.c + +.include diff --git a/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/myfirst.c b/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/myfirst.c new file mode 100644 index 0000000..efe8b67 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage0-scaffold/myfirst.c @@ -0,0 +1,53 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 0 of Chapter 7: minimal kernel module scaffold. + * + * This version does not register a device, does not allocate any + * resources, and does not create /dev nodes. Its only job is to prove + * that the build system works and that kldload/kldunload can call into + * our module event handler. + */ + +#include +#include +#include +#include + +/* + * Module load/unload event handler. + * + * Called with what == MOD_LOAD when the module is loaded and with + * what == MOD_UNLOAD when it is unloaded. + */ +static int +myfirst_loader(module_t mod, int what, void *arg) +{ + int error = 0; + + switch (what) { + case MOD_LOAD: + printf("myfirst: driver loaded\n"); + break; + case MOD_UNLOAD: + printf("myfirst: driver unloaded\n"); + break; + default: + error = EOPNOTSUPP; + break; + } + + return (error); +} + +static moduledata_t myfirst_mod = { + "myfirst", /* module name */ + myfirst_loader, /* event handler */ + NULL /* extra arg (unused here) */ +}; + +DECLARE_MODULE(myfirst, myfirst_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/Makefile b/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/Makefile new file mode 100644 index 0000000..97da483 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/Makefile @@ -0,0 +1,10 @@ +# Makefile for myfirst driver +# +# Stage 1 of Chapter 7: Newbus pseudo-device with identify, probe, +# attach, and detach. No /dev node and no sysctls yet. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/myfirst.c b/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/myfirst.c new file mode 100644 index 0000000..c2fb8da --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage1-newbus/myfirst.c @@ -0,0 +1,93 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 1 of Chapter 7: minimal Newbus pseudo-device. + * + * Adds identify, probe, attach, and detach methods on the nexus bus. + * The driver does not yet allocate locks, /dev nodes, or sysctls. + */ + +#include +#include +#include +#include +#include +#include + +/* + * Per-device state. Newbus zeroes and frees this for us based on the + * size declared in the driver_t below. + */ +struct myfirst_softc { + device_t dev; + uint64_t attach_ticks; + int is_ready; +}; + +/* + * identify creates the myfirst child device on the parent bus. Without + * this, nexus would have no myfirst device to probe and our driver + * would never be called. + */ +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->attach_ticks = ticks; + sc->is_ready = 1; + + device_printf(dev, "Attached at tick %lu\n", + (unsigned long)sc->attach_ticks); + return (0); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + device_printf(dev, "Detaching (was attached for %lu ticks)\n", + (unsigned long)(ticks - sc->attach_ticks)); + sc->is_ready = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch07-writing-your-first-driver/stage2-final/Makefile b/examples/part-02/ch07-writing-your-first-driver/stage2-final/Makefile new file mode 100644 index 0000000..8f3952f --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage2-final/Makefile @@ -0,0 +1,10 @@ +# Makefile for myfirst driver +# +# Stage 2 of Chapter 7: complete driver with softc, lock, /dev node, +# read-only sysctls, and a single-label unwind in attach. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch07-writing-your-first-driver/stage2-final/myfirst.c b/examples/part-02/ch07-writing-your-first-driver/stage2-final/myfirst.c new file mode 100644 index 0000000..5c904f4 --- /dev/null +++ b/examples/part-02/ch07-writing-your-first-driver/stage2-final/myfirst.c @@ -0,0 +1,253 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 2 of Chapter 7: complete minimal pseudo-device driver. + * + * Demonstrates: + * - identify, probe, attach, detach on the nexus bus + * - per-device softc with mutex + * - /dev/myfirst0 node with stub read/write + * - read-only sysctls under dev.myfirst.0.stats + * - single-label unwind for attach error paths + * - exclusive open with EBUSY on second opener + * - detach refuses with EBUSY while the device is open + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + + int is_attached; + int is_open; + + struct cdev *cdev; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + if (sc->is_open) { + mtx_unlock(&sc->mtx); + return (EBUSY); + } + sc->is_open = 1; + sc->open_count++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device opened (count: %lu)\n", + (unsigned long)sc->open_count); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL) + return (ENXIO); + + mtx_lock(&sc->mtx); + sc->is_open = 0; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device closed\n"); + return (0); +} + +/* + * Stub read: immediate EOF. Real read semantics arrive in Chapter 9. + */ +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + return (0); +} + +/* + * Stub write: pretend we accepted everything. Discards user data on + * purpose; real data movement lives in Chapter 9. + */ +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->is_open = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Number of times device was opened"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + device_printf(dev, "Attached successfully at tick %lu\n", + (unsigned long)sc->attach_ticks); + return (0); + +fail_dev: + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + uint64_t uptime_ticks; + + sc = device_get_softc(dev); + + if (sc->is_open) { + device_printf(dev, "Cannot detach: device is open\n"); + return (EBUSY); + } + + uptime_ticks = ticks - sc->attach_ticks; + device_printf(dev, "Detaching: uptime %lu ticks, opened %lu times\n", + (unsigned long)uptime_ticks, + (unsigned long)sc->open_count); + + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch08-working-with-device-files/devfs/devd.conf.example b/examples/part-02/ch08-working-with-device-files/devfs/devd.conf.example new file mode 100644 index 0000000..322184a --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/devfs/devd.conf.example @@ -0,0 +1,15 @@ +# Example /etc/devd.conf rule for the Chapter 8 myfirst driver. +# +# Copy the notify block to /etc/devd.conf (or a fragment under +# /usr/local/etc/devd/ if your system prefers fragment files) and run +# "service devd restart" to install. See devd.conf(5) for details. +# +# Each time /dev/myfirst/0 appears or disappears, devd will log a +# message via logger(1) tagged "myfirst". Watch /var/log/messages. + +notify 100 { + match "system" "DEVFS"; + match "subsystem" "CDEV"; + match "cdev" "myfirst/0"; + action "/usr/bin/logger -t myfirst event=$type"; +}; diff --git a/examples/part-02/ch08-working-with-device-files/devfs/devfs.conf.example b/examples/part-02/ch08-working-with-device-files/devfs/devfs.conf.example new file mode 100644 index 0000000..39bc4da --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/devfs/devfs.conf.example @@ -0,0 +1,23 @@ +# Example /etc/devfs.conf entries for the Chapter 8 myfirst driver. +# +# devfs.conf applies each line once, when a matching node appears +# under /dev. See devfs.conf(5) for the full syntax. To apply changes +# on a running system: +# +# sudo service devfs restart +# +# These entries make sense against the Chapter 7 baseline driver that +# creates /dev/myfirst0 with mode 0600 under root:wheel. They turn that +# node into a root:operator 0660 node and add a /dev/myfirst-primary +# symlink pointing at it. + +own myfirst0 root:operator +perm myfirst0 0660 +link myfirst0 myfirst-primary + +# If you are using the Chapter 8 structured-name driver that creates +# /dev/myfirst/0, use these entries instead: + +# own myfirst/0 root:operator +# perm myfirst/0 0660 +# link myfirst/0 myfirst-primary diff --git a/examples/part-02/ch08-working-with-device-files/devfs/devfs.rules.example b/examples/part-02/ch08-working-with-device-files/devfs/devfs.rules.example new file mode 100644 index 0000000..5f6f256 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/devfs/devfs.rules.example @@ -0,0 +1,15 @@ +# Example /etc/devfs.rules fragment for the Chapter 8 myfirst driver. +# +# devfs.rules defines named rulesets that a jail can reference in +# jail.conf through devfs_ruleset = N. See devfs(8) and +# devfs.rules(5) for the full format. +# +# The ruleset below makes everything under /dev/myfirst/ visible +# inside a jail, with group-readable/writable access for the +# operator group. It is suitable for a lab jail that needs to run +# probe_myfirst against the driver running on the host. + +[myfirst_lab=10] +add path 'myfirst' unhide +add path 'myfirst/*' unhide +add path 'myfirst/*' mode 0660 group operator diff --git a/examples/part-02/ch08-working-with-device-files/jail/jail.conf.example b/examples/part-02/ch08-working-with-device-files/jail/jail.conf.example new file mode 100644 index 0000000..7ee9640 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/jail/jail.conf.example @@ -0,0 +1,25 @@ +# Example /etc/jail.conf fragment for the Chapter 8 Lab 8.7 jail. +# +# Creates a small jail that references ruleset 100 from +# /etc/devfs.rules (see devfs.rules.example). Used to verify that +# /dev/myfirst/0 is visible inside the jail when the ruleset unhides +# it and invisible when it does not. +# +# Before using this fragment: +# 1. Create /jails/myfirstjail and populate it with a base install. +# One quick way is "bsdinstall jail /jails/myfirstjail". +# 2. Install the ruleset from devfs.rules.example into +# /etc/devfs.rules and run "service devfs restart". +# 3. Start the jail with "service jail start myfirstjail". + +myfirstjail { + path = "/jails/myfirstjail"; + host.hostname = "myfirstjail.example.com"; + + mount.devfs; + devfs_ruleset = 100; + + exec.start = "/bin/sh"; + exec.stop = "/bin/sh -c 'exit'"; + persist; +} diff --git a/examples/part-02/ch08-working-with-device-files/stage0-structured-name/Makefile b/examples/part-02/ch08-working-with-device-files/stage0-structured-name/Makefile new file mode 100644 index 0000000..5cf392a --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage0-structured-name/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 8 stage 0 myfirst driver. +# +# Moves the device node from /dev/myfirst0 to /dev/myfirst/0 and +# uses group operator, mode 0660 as the baseline. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch08-working-with-device-files/stage0-structured-name/myfirst.c b/examples/part-02/ch08-working-with-device-files/stage0-structured-name/myfirst.c new file mode 100644 index 0000000..1db6cc3 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage0-structured-name/myfirst.c @@ -0,0 +1,241 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 0 of Chapter 8: the Chapter 7 driver with a structured device + * name and tighter ownership. + * + * Differences from Chapter 7 stage2-final: + * - The /dev node moves from /dev/myfirst0 to /dev/myfirst/0. + * - The node is group-accessible to the operator group (0660). + * - Everything else (softc, sysctls, exclusive open, unwind) + * is unchanged so the diff stays readable. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + + int is_attached; + int is_open; + + struct cdev *cdev; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + if (sc->is_open) { + mtx_unlock(&sc->mtx); + return (EBUSY); + } + sc->is_open = 1; + sc->open_count++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device opened (count: %lu)\n", + (unsigned long)sc->open_count); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL) + return (ENXIO); + + mtx_lock(&sc->mtx); + sc->is_open = 0; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device closed\n"); + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->is_open = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; /* was GID_WHEEL */ + args.mda_mode = 0660; /* was 0600 */ + args.mda_si_drv1 = sc; + + /* Note the "myfirst/%d" form: this creates /dev/myfirst/0 + * rather than /dev/myfirst0. Devfs creates the intermediate + * directory on demand. + */ + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Number of times device was opened"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + device_printf(dev, "Attached; node at /dev/%s\n", + devtoname(sc->cdev)); + return (0); + +fail_dev: + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + if (sc->is_open) { + device_printf(dev, "Cannot detach: device is open\n"); + return (EBUSY); + } + + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch08-working-with-device-files/stage1-alias/Makefile b/examples/part-02/ch08-working-with-device-files/stage1-alias/Makefile new file mode 100644 index 0000000..c91a165 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage1-alias/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 8 stage 1 myfirst driver. +# +# Adds an alias so /dev/myfirst also reaches unit 0. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch08-working-with-device-files/stage1-alias/myfirst.c b/examples/part-02/ch08-working-with-device-files/stage1-alias/myfirst.c new file mode 100644 index 0000000..28752bc --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage1-alias/myfirst.c @@ -0,0 +1,251 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 1 of Chapter 8: add an alias so /dev/myfirst points at + * /dev/myfirst/0. Builds on stage 0 and changes only the pieces that + * manage the alias cdev. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + + int is_attached; + int is_open; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + if (sc->is_open) { + mtx_unlock(&sc->mtx); + return (EBUSY); + } + sc->is_open = 1; + sc->open_count++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device opened via %s (count: %lu)\n", + devtoname(dev), (unsigned long)sc->open_count); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL) + return (ENXIO); + + mtx_lock(&sc->mtx); + sc->is_open = 0; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "Device closed via %s\n", devtoname(dev)); + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->is_open = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + /* + * Create an alias so user programs can also reach the device + * through /dev/myfirst. Alias creation failing is not fatal; + * the primary path still works, so log and continue. + */ + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Number of times device was opened"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + device_printf(dev, "Attached; node at /dev/%s (alias /dev/myfirst)\n", + devtoname(sc->cdev)); + return (0); + +fail_dev: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + if (sc->is_open) { + device_printf(dev, "Cannot detach: device is open\n"); + return (EBUSY); + } + + /* Destroy the alias first, then the primary node. */ + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch08-working-with-device-files/stage2-perhandle/Makefile b/examples/part-02/ch08-working-with-device-files/stage2-perhandle/Makefile new file mode 100644 index 0000000..ee02e33 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage2-perhandle/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 8 stage 2 myfirst driver. +# +# Adds per-open state through devfs_set_cdevpriv() and drops the +# exclusive-open restriction. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch08-working-with-device-files/stage2-perhandle/myfirst.c b/examples/part-02/ch08-working-with-device-files/stage2-perhandle/myfirst.c new file mode 100644 index 0000000..f7eae0b --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage2-perhandle/myfirst.c @@ -0,0 +1,305 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 2 of Chapter 8: per-open state via devfs_set_cdevpriv(). + * + * Differences from stage 1: + * - A small struct myfirst_fh is allocated per open(2) and + * registered with devfs_set_cdevpriv(). A destructor frees it + * automatically when the descriptor closes or the owning + * process exits. + * - The exclusive-open check from Chapter 7 is removed. Two or + * more processes may now hold the device open at the same time. + * - active_fhs tracks the current number of open descriptors so + * detach() can refuse while at least one is still alive. + * - d_read / d_write retrieve the per-open structure via + * devfs_get_cdevpriv(); the actual data path stays a stub until + * Chapter 9. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; /* opens ever seen */ + uint64_t bytes_read; + + int active_fhs; /* currently open descriptors */ + int is_attached; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; /* back-pointer to the softc */ + uint64_t reads; /* bytes this fd has read */ + uint64_t writes;/* bytes this fd has written */ +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + struct myfirst_fh *fh; + int error; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + /* + * Nothing to do here. Per-open cleanup happens in the + * devfs_set_cdevpriv() destructor, which fires exactly once + * per descriptor. + */ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_fh *fh; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + /* Real read semantics arrive in Chapter 9. For now, EOF. */ + (void)fh; + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_fh *fh; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + (void)fh; + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + device_printf(dev, "Attached; node at /dev/%s (alias /dev/myfirst)\n", + devtoname(sc->cdev)); + return (0); + +fail_dev: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/Makefile b/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/Makefile new file mode 100644 index 0000000..11c2839 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 8 stage 3 myfirst driver (two nodes). +# +# Exposes a data node at /dev/myfirst/%d and a control node at +# /dev/myfirst/%d.ctl, each with its own cdevsw and permission mode. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/myfirst.c b/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/myfirst.c new file mode 100644 index 0000000..8f8baaa --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage3-two-nodes/myfirst.c @@ -0,0 +1,341 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 3 of Chapter 8: two-node driver with data and control nodes. + * + * Differences from stage 2: + * - Adds a second cdevsw (myfirst_ctl_cdevsw) with d_ioctl only. + * - Creates two cdevs in attach: data at /dev/myfirst/%d, + * control at /dev/myfirst/%d.ctl. + * - Each node carries its own permission mode: 0660 for the data + * node, 0640 for the control node. + * - Destroy order: control first, then data, on detach. + * + * The ioctl handler is a stub that returns ENOTTY for every command; + * Chapter 25 will revisit ioctl design. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + + int active_fhs; + int is_attached; + + struct cdev *cdev; + struct cdev *cdev_ctl; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_ioctl_t myfirst_ctl_ioctl; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static struct cdevsw myfirst_ctl_cdevsw = { + .d_version = D_VERSION, + .d_ioctl = myfirst_ctl_ioctl, + .d_name = "myfirst_ctl", +}; + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + struct myfirst_fh *fh; + int error; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_fh *fh; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + (void)fh; + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_fh *fh; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + (void)fh; + uio->uio_resid = 0; + return (0); +} + +/* + * Control-node ioctl stub. Chapter 25 will revisit ioctl design. + * For now, every command returns ENOTTY so userland sees a clean + * "not supported" response. + */ +static int +myfirst_ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t data, + int fflag, struct thread *td) +{ + struct myfirst_softc *sc; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + device_printf(sc->dev, "ctl ioctl cmd=0x%lx\n", cmd); + return (ENOTTY); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + /* Data node: /dev/myfirst/%d, 0660 root:operator. */ + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "data cdev make_dev_s: %d\n", error); + goto fail_mtx; + } + + /* Control node: /dev/myfirst/%d.ctl, 0640 root:wheel. */ + make_dev_args_init(&args); + args.mda_devsw = &myfirst_ctl_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0640; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev_ctl, "myfirst/%d.ctl", sc->unit); + if (error != 0) { + device_printf(dev, "ctl cdev make_dev_s: %d\n", error); + goto fail_data; + } + + /* Alias: /dev/myfirst -> /dev/myfirst/0 (primary unit only). */ + if (sc->unit == 0) { + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "alias creation failed\n"); + } + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "sysctl tree creation failed\n"); + error = ENOMEM; + goto fail_ctl; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + + device_printf(dev, "attached; data=/dev/%s ctl=/dev/%s\n", + devtoname(sc->cdev), devtoname(sc->cdev_ctl)); + return (0); + +fail_ctl: + destroy_dev(sc->cdev_ctl); + sc->cdev_ctl = NULL; +fail_data: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); + sc->cdev = NULL; +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, "cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + /* Destroy in reverse order of creation: alias, ctl, data. */ + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev_ctl != NULL) { + destroy_dev(sc->cdev_ctl); + sc->cdev_ctl = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/Makefile b/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/Makefile new file mode 100644 index 0000000..596f481 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/Makefile @@ -0,0 +1,15 @@ +# Makefile for the Chapter 8 stage 4 myfirst driver (destroy-dev-drain). +# +# Exercise the broken path (no drain): +# make clean && make +# +# Exercise the fixed path (with drain): +# make clean && make CFLAGS+=-DUSE_DRAIN=1 +# +# Only run in a throwaway VM. The broken path is deliberately unsafe. + +KMOD= myfirstN +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/myfirst.c b/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/myfirst.c new file mode 100644 index 0000000..9515b2d --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/stage4-destroy-drain/myfirst.c @@ -0,0 +1,174 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2025 Your Name + * All rights reserved. + * + * Stage 4 of Chapter 8: multiple cdevs plus destroy_dev_drain. + * + * This driver creates five cdevs per attach, all served by the same + * cdevsw. It exists to illustrate when destroy_dev_drain is needed: + * a module that uses destroy_dev_sched to tear down many cdevs during + * its detach path must drain the cdevsw before the module is unloaded + * and the cdevsw is freed. + * + * Compile with USE_DRAIN=1 to get the correct behavior: + * + * make CFLAGS+=-DUSE_DRAIN=1 + * + * Compile without USE_DRAIN to exercise the broken path, which may + * log "Still N threads" messages or panic under load. Run only in a + * throwaway VM. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYFIRST_UNITS 5 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + int is_attached; + + struct cdev *cdevs[MYFIRST_UNITS]; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_name = "myfirstN", +}; + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirstN: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (multi-node)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error, i; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirstN", MTX_DEF); + sc->is_attached = 1; + + for (i = 0; i < MYFIRST_UNITS; i++) { + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdevs[i], + "myfirstN/%d", i); + if (error != 0) { + device_printf(dev, + "make_dev_s unit %d: %d\n", i, error); + while (--i >= 0) { + destroy_dev(sc->cdevs[i]); + sc->cdevs[i] = NULL; + } + mtx_destroy(&sc->mtx); + return (error); + } + } + + device_printf(dev, "attached; %d cdevs created\n", MYFIRST_UNITS); + return (0); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + int i; + + sc = device_get_softc(dev); + + for (i = 0; i < MYFIRST_UNITS; i++) { + if (sc->cdevs[i] != NULL) { + destroy_dev_sched(sc->cdevs[i]); + sc->cdevs[i] = NULL; + } + } + +#ifdef USE_DRAIN + /* + * Correct behavior: wait for all cdevs in this cdevsw to + * complete destruction before returning, so the module can + * be safely unloaded and the cdevsw freed. + */ + destroy_dev_drain(&myfirst_cdevsw); +#endif + + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + + device_printf(dev, "detached\n"); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirstN", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirstN, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirstN, 1); diff --git a/examples/part-02/ch08-working-with-device-files/userland/Makefile b/examples/part-02/ch08-working-with-device-files/userland/Makefile new file mode 100644 index 0000000..47fbfd9 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/Makefile @@ -0,0 +1,28 @@ +# Makefile for Chapter 8 userland probes. +# +# Plain userland C programs, not kernel modules. Written to be +# portable between FreeBSD's bmake and GNU make. + +CFLAGS?= -Wall -Werror + +all: probe_myfirst hold_myfirst stat_myfirst parallel_probe stress_probe + +probe_myfirst: probe_myfirst.c + $(CC) $(CFLAGS) -o probe_myfirst probe_myfirst.c + +hold_myfirst: hold_myfirst.c + $(CC) $(CFLAGS) -o hold_myfirst hold_myfirst.c + +stat_myfirst: stat_myfirst.c + $(CC) $(CFLAGS) -o stat_myfirst stat_myfirst.c + +parallel_probe: parallel_probe.c + $(CC) $(CFLAGS) -o parallel_probe parallel_probe.c + +stress_probe: stress_probe.c + $(CC) $(CFLAGS) -o stress_probe stress_probe.c + +clean: + rm -f probe_myfirst hold_myfirst stat_myfirst parallel_probe stress_probe + +.PHONY: all clean diff --git a/examples/part-02/ch08-working-with-device-files/userland/devd_watch.sh b/examples/part-02/ch08-working-with-device-files/userland/devd_watch.sh new file mode 100755 index 0000000..d465e24 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/devd_watch.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# devd_watch.sh: subscribe to the devd event stream and print events +# that match the myfirst driver. Used for Chapter 8 Challenge 5 and +# for debugging driver load/unload behavior. +# +# Run in one terminal while you load and unload the driver in another. +# Requires netcat (base system) to connect to devd's socket. + +SOCKET=/var/run/devd.seqpacket.pipe + +if [ ! -S "${SOCKET}" ]; then + echo "devd socket ${SOCKET} not available" >&2 + echo "ensure devd is running (service devd status)" >&2 + exit 1 +fi + +echo "Listening for myfirst events on ${SOCKET}..." >&2 +nc -U "${SOCKET}" | grep -i 'myfirst' diff --git a/examples/part-02/ch08-working-with-device-files/userland/hold_myfirst.c b/examples/part-02/ch08-working-with-device-files/userland/hold_myfirst.c new file mode 100644 index 0000000..7130b95 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/hold_myfirst.c @@ -0,0 +1,48 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * hold_myfirst: open /dev/myfirst/0 and sleep. Used for Challenge 2 to + * prove that the per-open destructor fires on process exit even without + * an explicit close(2) call. + * + * Usage: + * hold_myfirst [seconds] [path] + * + * Default: sleep 30 seconds, path /dev/myfirst/0. Exits without calling + * close(2) on purpose. The kernel should still fire the per-open + * destructor; watch dmesg to confirm. + * + * Compile: + * cc -Wall -Werror -o hold_myfirst hold_myfirst.c + */ + +#include +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + unsigned int seconds = 30; + const char *path = "/dev/myfirst/0"; + int fd; + + if (argc > 1) + seconds = (unsigned int)strtoul(argv[1], NULL, 10); + if (argc > 2) + path = argv[2]; + + fd = open(path, O_RDWR); + if (fd < 0) + err(1, "open %s", path); + + printf("opened %s on fd %d; sleeping %u seconds then exiting " + "without close(2)\n", path, fd, seconds); + + sleep(seconds); + + /* Intentionally skip close(fd): let the kernel do it. */ + return (0); +} diff --git a/examples/part-02/ch08-working-with-device-files/userland/parallel_probe.c b/examples/part-02/ch08-working-with-device-files/userland/parallel_probe.c new file mode 100644 index 0000000..45d4659 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/parallel_probe.c @@ -0,0 +1,53 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * parallel_probe: open a device node multiple times from a single + * process, hold all descriptors simultaneously, then close them all. + * + * Used for Chapter 8 Lab 8.6 to verify that per-open state is truly + * per-descriptor. + * + * Usage: + * parallel_probe [path] [count] + * + * Default: path=/dev/myfirst/0, count=4. Count must be 1..MAX_FDS. + * + * Compile: + * cc -Wall -Werror -o parallel_probe parallel_probe.c + */ + +#include +#include +#include +#include +#include + +#define MAX_FDS 8 + +int +main(int argc, char **argv) +{ + const char *path = (argc > 1) ? argv[1] : "/dev/myfirst/0"; + int fds[MAX_FDS]; + int i, n; + + n = (argc > 2) ? atoi(argv[2]) : 4; + if (n < 1 || n > MAX_FDS) + errx(1, "count must be 1..%d", MAX_FDS); + + for (i = 0; i < n; i++) { + fds[i] = open(path, O_RDWR); + if (fds[i] < 0) + err(1, "open %s (fd %d of %d)", path, i + 1, n); + printf("opened %s as fd %d\n", path, fds[i]); + } + + printf("holding %d descriptors; press enter to close\n", n); + (void)getchar(); + + for (i = 0; i < n; i++) { + if (close(fds[i]) != 0) + warn("close fd %d", fds[i]); + } + return (0); +} diff --git a/examples/part-02/ch08-working-with-device-files/userland/probe_myfirst.c b/examples/part-02/ch08-working-with-device-files/userland/probe_myfirst.c new file mode 100644 index 0000000..34ab067 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/probe_myfirst.c @@ -0,0 +1,44 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * probe_myfirst: a tiny userland probe for the Chapter 8 myfirst driver. + * + * Usage: + * probe_myfirst [path] + * + * With no argument, opens /dev/myfirst/0. With an argument, opens the + * given path. Performs one read(2) into a fixed buffer, reports the + * number of bytes, closes, and exits. + * + * Compile: + * cc -Wall -Werror -o probe_myfirst probe_myfirst.c + */ + +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + const char *path = (argc > 1) ? argv[1] : "/dev/myfirst/0"; + char buf[64]; + ssize_t n; + int fd; + + fd = open(path, O_RDWR); + if (fd < 0) + err(1, "open %s", path); + + n = read(fd, buf, sizeof(buf)); + if (n < 0) + err(1, "read %s", path); + + printf("read %zd bytes from %s\n", n, path); + + if (close(fd) != 0) + err(1, "close %s", path); + + return (0); +} diff --git a/examples/part-02/ch08-working-with-device-files/userland/stat_myfirst.c b/examples/part-02/ch08-working-with-device-files/userland/stat_myfirst.c new file mode 100644 index 0000000..2bdf537 --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/stat_myfirst.c @@ -0,0 +1,43 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * stat_myfirst: print stat(2) metadata for one or more device-file + * paths. Useful to confirm that a primary node and its alias resolve + * to the same cdev (same rdev) and that the advertised mode and + * ownership match what the driver asked for. + * + * Usage: + * stat_myfirst path [path ...] + * + * Compile: + * cc -Wall -Werror -o stat_myfirst stat_myfirst.c + */ + +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + struct stat sb; + int i; + + if (argc < 2) { + fprintf(stderr, "usage: %s path [path ...]\n", argv[0]); + return (1); + } + + for (i = 1; i < argc; i++) { + if (stat(argv[i], &sb) != 0) + err(1, "stat %s", argv[i]); + printf("%s: mode=%06o uid=%u gid=%u rdev=%#jx\n", + argv[i], + (unsigned)(sb.st_mode & 07777), + (unsigned)sb.st_uid, + (unsigned)sb.st_gid, + (uintmax_t)sb.st_rdev); + } + return (0); +} diff --git a/examples/part-02/ch08-working-with-device-files/userland/stress_probe.c b/examples/part-02/ch08-working-with-device-files/userland/stress_probe.c new file mode 100644 index 0000000..71e451d --- /dev/null +++ b/examples/part-02/ch08-working-with-device-files/userland/stress_probe.c @@ -0,0 +1,42 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * stress_probe: loop open() and close() on a device node many times. + * Used as a rough correctness and leak test for the per-open state + * path in Chapter 8. + * + * Usage: + * stress_probe [path] [iterations] + * + * Default: path=/dev/myfirst/0, iterations=1000. + * + * Compile: + * cc -Wall -Werror -o stress_probe stress_probe.c + */ + +#include +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + const char *path = (argc > 1) ? argv[1] : "/dev/myfirst/0"; + int iters = (argc > 2) ? atoi(argv[2]) : 1000; + int i, fd; + + if (iters < 1) + errx(1, "iterations must be >= 1"); + + for (i = 0; i < iters; i++) { + fd = open(path, O_RDWR); + if (fd < 0) + err(1, "open (iter %d)", i); + if (close(fd) != 0) + err(1, "close (iter %d)", i); + } + printf("%d iterations completed\n", iters); + return (0); +} diff --git a/examples/part-02/ch09-reading-and-writing/stage1-static-message/Makefile b/examples/part-02/ch09-reading-and-writing/stage1-static-message/Makefile new file mode 100644 index 0000000..254cd40 --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage1-static-message/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 9 Stage 1 myfirst driver. +# +# Serves a static kernel-space message through uiomove_frombuf(9). + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch09-reading-and-writing/stage1-static-message/myfirst.c b/examples/part-02/ch09-reading-and-writing/stage1-static-message/myfirst.c new file mode 100644 index 0000000..45d36ff --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage1-static-message/myfirst.c @@ -0,0 +1,329 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * All rights reserved. + * + * Chapter 9, Stage 1: a static-message read path. + * + * The driver carries a fixed kernel-side message and serves it to + * readers through uiomove_frombuf(9). Each open descriptor starts at + * offset zero and reads its way through the message; a second read on + * the same descriptor returns zero bytes (EOF). Writes are still + * discarded, the same /dev/null shape as Chapter 8 left us with. + * + * Differences from the Chapter 8 stage 2 source: + * - struct myfirst_softc gains a message pointer and its length. + * - struct myfirst_fh gains a per-descriptor read offset. + * - myfirst_read calls uiomove_frombuf(9) against the message. + * - myfirst_write stays a stub that consumes all bytes and returns + * zero. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char myfirst_message[] = + "Hello from myfirst.\n" + "This is your first real read path.\n" + "Chapter 9, Stage 1.\n"; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + + int active_fhs; + int is_attached; + + const char *message; + size_t message_len; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; + off_t read_off; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, + "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + struct myfirst_fh *fh; + int error; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + off_t before; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + before = uio->uio_offset; + error = uiomove_frombuf(__DECONST(void *, sc->message), + sc->message_len, uio); + if (error == 0) { + size_t moved = uio->uio_offset - before; + fh->reads += moved; + mtx_lock(&sc->mtx); + sc->bytes_read += moved; + mtx_unlock(&sc->mtx); + } + fh->read_off = uio->uio_offset; + return (error); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_fh *fh; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + + (void)fh; + uio->uio_resid = 0; + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 9 Stage 1)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + + sc->message = myfirst_message; + sc->message_len = sizeof(myfirst_message) - 1; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_mtx; + } + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + device_printf(dev, + "Attached; node at /dev/%s (alias /dev/myfirst), message=%zu bytes\n", + devtoname(sc->cdev), sc->message_len); + return (0); + +fail_dev: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch09-reading-and-writing/stage2-readwrite/Makefile b/examples/part-02/ch09-reading-and-writing/stage2-readwrite/Makefile new file mode 100644 index 0000000..666c516 --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage2-readwrite/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 9 Stage 2 myfirst driver. +# +# Introduces a malloc(9)-backed kernel buffer that d_write appends +# into and d_read serves out of, with per-descriptor offsets. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch09-reading-and-writing/stage2-readwrite/myfirst.c b/examples/part-02/ch09-reading-and-writing/stage2-readwrite/myfirst.c new file mode 100644 index 0000000..04a9db2 --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage2-readwrite/myfirst.c @@ -0,0 +1,368 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * All rights reserved. + * + * Chapter 9, Stage 2: a write-once / read-many buffer. + * + * The driver allocates a kernel buffer at attach time. Writes append + * into the buffer; reads serve from the caller's per-descriptor offset + * up to the current high-water mark (bufused). When the buffer fills, + * further writes return ENOSPC. Each reader owns its own offset, so + * two concurrent readers see independent progress through the same + * accumulating stream. + * + * Differences from Stage 1: + * - A malloc(9)'d buffer of size MYFIRST_BUFSIZE. + * - myfirst_write appends data into the buffer under sc->mtx. + * - myfirst_read honours uio->uio_offset against bufused. + * - New sysctl nodes expose bytes_written and bufused. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYFIRST_BUFSIZE 4096 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + char *buf; + size_t buflen; + size_t bufused; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; + off_t read_off; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, + "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + struct myfirst_fh *fh; + int error; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + off_t before; + size_t have; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + have = sc->bufused; + before = uio->uio_offset; + error = uiomove_frombuf(sc->buf, have, uio); + if (error == 0) { + size_t moved = uio->uio_offset - before; + sc->bytes_read += moved; + fh->reads += moved; + } + fh->read_off = uio->uio_offset; + mtx_unlock(&sc->mtx); + return (error); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + size_t avail, towrite; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + if (sc->bufused >= sc->buflen) { + mtx_unlock(&sc->mtx); + return (ENOSPC); + } + avail = sc->buflen - sc->bufused; + towrite = MIN((size_t)uio->uio_resid, avail); + error = uiomove(sc->buf + sc->bufused, towrite, uio); + if (error == 0) { + sc->bufused += towrite; + sc->bytes_written += towrite; + fh->writes += towrite; + } + mtx_unlock(&sc->mtx); + return (error); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 9 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + sc->buflen = MYFIRST_BUFSIZE; + sc->buf = malloc(sc->buflen, M_DEVBUF, M_WAITOK | M_ZERO); + if (sc->buf == NULL) { + error = ENOMEM; + goto fail_mtx; + } + sc->bufused = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_buf; + } + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes read from device"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes written into the buffer"); + + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bufused", CTLFLAG_RD, + (unsigned int *)&sc->bufused, 0, "Current buffer occupancy"); + + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "buflen", CTLFLAG_RD, + (unsigned int *)&sc->buflen, 0, "Buffer capacity"); + + device_printf(dev, + "Attached; node at /dev/%s (alias /dev/myfirst), buffer=%zu bytes\n", + devtoname(sc->cdev), sc->buflen); + return (0); + +fail_dev: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); +fail_buf: + free(sc->buf, M_DEVBUF); + sc->buf = NULL; +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + if (sc->buf != NULL) { + free(sc->buf, M_DEVBUF); + sc->buf = NULL; + } + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch09-reading-and-writing/stage3-echo/Makefile b/examples/part-02/ch09-reading-and-writing/stage3-echo/Makefile new file mode 100644 index 0000000..96a5c28 --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage3-echo/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 9 Stage 3 myfirst driver. +# +# A first-in / first-out echo driver: writes append, reads drain. + +KMOD= myfirst +SRCS= myfirst.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch09-reading-and-writing/stage3-echo/myfirst.c b/examples/part-02/ch09-reading-and-writing/stage3-echo/myfirst.c new file mode 100644 index 0000000..12abb1b --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/stage3-echo/myfirst.c @@ -0,0 +1,382 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * All rights reserved. + * + * Chapter 9, Stage 3: a first-in / first-out echo driver. + * + * Writes append to the tail of a kernel buffer; reads drain bytes + * from the head. The driver maintains two indices: bufhead (next + * byte to deliver) and bufused (count of live bytes from bufhead + * onward). When bufused reaches zero, bufhead is reset to zero so + * subsequent writes start at the beginning again. + * + * The buffer does not wrap. A proper circular buffer with wrap- + * around, along with blocking reads and poll/kqueue integration, + * arrives in Chapter 10. + * + * Differences from Stage 2: + * - New bufhead index in the softc. + * - myfirst_read drains from bufhead and advances it. + * - myfirst_write appends at bufhead + bufused. + * - uio->uio_offset is no longer used as a per-descriptor position; + * the FIFO has a single shared stream. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYFIRST_BUFSIZE 4096 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + char *buf; + size_t buflen; + size_t bufhead; + size_t bufused; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, + "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc; + struct myfirst_fh *fh; + int error; + + sc = dev->si_drv1; + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + size_t toread; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + if (sc->bufused == 0) { + mtx_unlock(&sc->mtx); + return (0); /* EOF on empty FIFO */ + } + toread = MIN((size_t)uio->uio_resid, sc->bufused); + error = uiomove(sc->buf + sc->bufhead, toread, uio); + if (error == 0) { + sc->bufhead += toread; + sc->bufused -= toread; + sc->bytes_read += toread; + fh->reads += toread; + if (sc->bufused == 0) + sc->bufhead = 0; + } + mtx_unlock(&sc->mtx); + return (error); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + size_t tail, avail, towrite; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + mtx_lock(&sc->mtx); + tail = sc->bufhead + sc->bufused; + if (tail >= sc->buflen) { + mtx_unlock(&sc->mtx); + return (ENOSPC); + } + avail = sc->buflen - tail; + towrite = MIN((size_t)uio->uio_resid, avail); + error = uiomove(sc->buf + tail, towrite, uio); + if (error == 0) { + sc->bufused += towrite; + sc->bytes_written += towrite; + fh->writes += towrite; + } + mtx_unlock(&sc->mtx); + return (error); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 9 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + sc->buflen = MYFIRST_BUFSIZE; + sc->buf = malloc(sc->buflen, M_DEVBUF, M_WAITOK | M_ZERO); + if (sc->buf == NULL) { + error = ENOMEM; + goto fail_mtx; + } + sc->bufhead = 0; + sc->bufused = 0; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) { + device_printf(dev, "Failed to create device node: %d\n", + error); + goto fail_buf; + } + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + if (sc->sysctl_tree == NULL) { + device_printf(dev, "Failed to create sysctl tree\n"); + error = ENOMEM; + goto fail_dev; + } + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the FIFO"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the FIFO"); + + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bufused", CTLFLAG_RD, + (unsigned int *)&sc->bufused, 0, "Live bytes in the FIFO"); + + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bufhead", CTLFLAG_RD, + (unsigned int *)&sc->bufhead, 0, "Index of next byte to read"); + + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "buflen", CTLFLAG_RD, + (unsigned int *)&sc->buflen, 0, "FIFO capacity"); + + device_printf(dev, + "Attached; node at /dev/%s (alias /dev/myfirst), FIFO=%zu bytes\n", + devtoname(sc->cdev), sc->buflen); + return (0); + +fail_dev: + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + destroy_dev(sc->cdev); +fail_buf: + free(sc->buf, M_DEVBUF); + sc->buf = NULL; +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + if (sc->buf != NULL) { + free(sc->buf, M_DEVBUF); + sc->buf = NULL; + } + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch09-reading-and-writing/userland/Makefile b/examples/part-02/ch09-reading-and-writing/userland/Makefile new file mode 100644 index 0000000..8f17d1c --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/userland/Makefile @@ -0,0 +1,19 @@ +# Makefile for Chapter 9 userland exercisers. +# +# Plain userland C programs, not kernel modules. Written to be +# portable between FreeBSD's bmake and GNU make. + +CFLAGS?= -Wall -Werror + +all: rw_myfirst stress_rw + +rw_myfirst: rw_myfirst.c + $(CC) $(CFLAGS) -o rw_myfirst rw_myfirst.c + +stress_rw: stress_rw.c + $(CC) $(CFLAGS) -o stress_rw stress_rw.c + +clean: + rm -f rw_myfirst stress_rw + +.PHONY: all clean diff --git a/examples/part-02/ch09-reading-and-writing/userland/rw_myfirst.c b/examples/part-02/ch09-reading-and-writing/userland/rw_myfirst.c new file mode 100644 index 0000000..1c7c01d --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/userland/rw_myfirst.c @@ -0,0 +1,139 @@ +/* + * rw_myfirst.c - small exerciser for the Chapter 9 myfirst driver. + * + * Usage: + * rw_myfirst read -- open, read until EOF twice + * rw_myfirst write TEXT -- open, write TEXT, close + * rw_myfirst rt -- write payload, close, read back, verify + * + * Build: cc -o rw_myfirst rw_myfirst.c + */ + +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst/0" + +static int +do_read(void) +{ + int fd; + ssize_t n; + char buf[256]; + int round; + + fd = open(DEVPATH, O_RDONLY); + if (fd < 0) { + perror("open " DEVPATH); + return (1); + } + + for (round = 1; round <= 2; round++) { + n = read(fd, buf, sizeof(buf) - 1); + if (n < 0) { + perror("read"); + close(fd); + return (2); + } + if (n == 0) { + printf("[read %d] 0 bytes (EOF)\n", round); + continue; + } + buf[n] = '\0'; + printf("[read %d] %zd bytes:\n%s", round, n, buf); + } + + close(fd); + return (0); +} + +static int +do_write(const char *text) +{ + int fd; + ssize_t n; + size_t len; + + if (text == NULL) { + fprintf(stderr, "write: missing text argument\n"); + return (1); + } + fd = open(DEVPATH, O_WRONLY); + if (fd < 0) { + perror("open " DEVPATH); + return (1); + } + len = strlen(text); + n = write(fd, text, len); + if (n < 0) { + perror("write"); + close(fd); + return (2); + } + if ((size_t)n != len) { + fprintf(stderr, "short write: %zd of %zu\n", n, len); + } + printf("[write] %zd bytes accepted\n", n); + close(fd); + return (0); +} + +static const char payload[] = + "round-trip test payload, 24b\n"; + +static int +do_roundtrip(void) +{ + int fd; + ssize_t n; + char buf[256]; + size_t plen = sizeof(payload) - 1; + + fd = open(DEVPATH, O_WRONLY); + if (fd < 0) { perror("open W"); return (1); } + n = write(fd, payload, plen); + if (n < 0) { perror("write"); close(fd); return (2); } + if ((size_t)n != plen) { + fprintf(stderr, "short write: %zd\n", n); + close(fd); + return (3); + } + close(fd); + + memset(buf, 0, sizeof(buf)); + fd = open(DEVPATH, O_RDONLY); + if (fd < 0) { perror("open R"); return (4); } + n = read(fd, buf, sizeof(buf) - 1); + if (n < 0) { perror("read"); close(fd); return (5); } + close(fd); + + if ((size_t)n != plen || memcmp(buf, payload, n) != 0) { + fprintf(stderr, "mismatch: wrote %zu, read %zd\n", plen, n); + return (6); + } + printf("round-trip OK: %zd bytes\n", n); + return (0); +} + +int +main(int argc, char *argv[]) +{ + if (argc < 2) { + fprintf(stderr, + "usage: %s read | write TEXT | rt\n", argv[0]); + return (1); + } + if (strcmp(argv[1], "read") == 0) + return (do_read()); + if (strcmp(argv[1], "write") == 0) + return (do_write(argc > 2 ? argv[2] : NULL)); + if (strcmp(argv[1], "rt") == 0) + return (do_roundtrip()); + fprintf(stderr, "unknown mode: %s\n", argv[1]); + return (1); +} diff --git a/examples/part-02/ch09-reading-and-writing/userland/stress_rw.c b/examples/part-02/ch09-reading-and-writing/userland/stress_rw.c new file mode 100644 index 0000000..2ee9e28 --- /dev/null +++ b/examples/part-02/ch09-reading-and-writing/userland/stress_rw.c @@ -0,0 +1,138 @@ +/* + * stress_rw.c - simple producer/consumer stress test for the + * Chapter 9 myfirst Stage 3 driver. + * + * Usage: + * stress_rw -- fork one writer and one reader for 2 seconds + * stress_rw -s SECONDS -- run for the given number of seconds + * + * The writer pushes fixed 64-byte chunks as fast as the driver will + * accept them; the reader drains as fast as the driver produces. + * Both processes exit after SECONDS and report their totals. + * + * Build: cc -o stress_rw stress_rw.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst/0" +#define CHUNK 64 + +static volatile int running; + +static int +run_writer(int seconds) +{ + int fd; + unsigned char chunk[CHUNK]; + size_t total; + ssize_t n; + time_t deadline; + int i; + + for (i = 0; i < CHUNK; i++) + chunk[i] = (unsigned char)('A' + (i % 26)); + + fd = open(DEVPATH, O_WRONLY); + if (fd < 0) { perror("writer open"); return (1); } + + deadline = time(NULL) + seconds; + total = 0; + while (time(NULL) < deadline) { + n = write(fd, chunk, CHUNK); + if (n < 0) { + if (errno == ENOSPC) { + usleep(1000); + continue; + } + perror("writer write"); + break; + } + total += n; + } + close(fd); + printf("[writer] total bytes written: %zu\n", total); + return (0); +} + +static int +run_reader(int seconds) +{ + int fd; + unsigned char chunk[CHUNK]; + size_t total; + ssize_t n; + time_t deadline; + + fd = open(DEVPATH, O_RDONLY); + if (fd < 0) { perror("reader open"); return (1); } + + deadline = time(NULL) + seconds; + total = 0; + while (time(NULL) < deadline) { + n = read(fd, chunk, sizeof(chunk)); + if (n < 0) { + perror("reader read"); + break; + } + if (n == 0) { + usleep(1000); + continue; + } + total += n; + } + close(fd); + printf("[reader] total bytes read: %zu\n", total); + return (0); +} + +int +main(int argc, char *argv[]) +{ + int seconds = 2; + int opt; + pid_t writer, reader; + + while ((opt = getopt(argc, argv, "s:")) != -1) { + switch (opt) { + case 's': + seconds = atoi(optarg); + if (seconds <= 0) { + fprintf(stderr, + "bad seconds: %s\n", optarg); + return (1); + } + break; + default: + fprintf(stderr, + "usage: %s [-s SECONDS]\n", argv[0]); + return (1); + } + } + + printf("[stress] running for %d second(s) against %s\n", + seconds, DEVPATH); + + writer = fork(); + if (writer < 0) { perror("fork writer"); return (2); } + if (writer == 0) + return (run_writer(seconds)); + + reader = fork(); + if (reader < 0) { perror("fork reader"); return (3); } + if (reader == 0) + return (run_reader(seconds)); + + while (waitpid(-1, NULL, 0) > 0) + ; + + return (0); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/Makefile b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/Makefile new file mode 100644 index 0000000..94320fb --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/Makefile @@ -0,0 +1,14 @@ +# Makefile for the userland cbuf test program. + +PROG= cb_test +SRCS= cbuf.c cb_test.c +CFLAGS?= -O2 -Wall -Wextra + +.PHONY: all clean +all: ${PROG} + +${PROG}: ${SRCS} cbuf.h + ${CC} ${CFLAGS} -o $@ ${SRCS} + +clean: + rm -f ${PROG} diff --git a/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cb_test.c b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cb_test.c new file mode 100644 index 0000000..2f513c1 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cb_test.c @@ -0,0 +1,126 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cb_test.c: simple sanity tests for the cbuf userland implementation. + */ + +#include "cbuf.h" + +#include +#include +#include + +#define CHECK(cond, msg) \ + do { if (!(cond)) { fprintf(stderr, "FAIL: %s\n", msg); exit(1); } } while (0) + +static void +test_basic(void) +{ + struct cbuf cb; + char in[8] = "ABCDEFGH"; + char out[8] = {0}; + size_t n; + + CHECK(cbuf_init(&cb, 8) == 0, "init"); + CHECK(cbuf_used(&cb) == 0, "init used"); + CHECK(cbuf_free(&cb) == 8, "init free"); + + n = cbuf_write(&cb, in, 4); + CHECK(n == 4, "write 4"); + CHECK(cbuf_used(&cb) == 4, "used after write 4"); + + n = cbuf_read(&cb, out, 2); + CHECK(n == 2, "read 2"); + CHECK(memcmp(out, "AB", 2) == 0, "AB content"); + CHECK(cbuf_used(&cb) == 2, "used after read 2"); + + cbuf_destroy(&cb); + printf("test_basic OK\n"); +} + +static void +test_wrap(void) +{ + struct cbuf cb; + char in[8] = "ABCDEFGH"; + char out[8] = {0}; + size_t n; + + CHECK(cbuf_init(&cb, 8) == 0, "init"); + + /* Push head forward by writing and reading 6 bytes. */ + n = cbuf_write(&cb, in, 6); + CHECK(n == 6, "write 6"); + n = cbuf_read(&cb, out, 6); + CHECK(n == 6, "read 6"); + + /* Now write 6 more, which should wrap. */ + n = cbuf_write(&cb, in, 6); + CHECK(n == 6, "write 6 after wrap"); + CHECK(cbuf_used(&cb) == 6, "used after wrap write"); + + /* Read all of it back; should return ABCDEF. */ + memset(out, 0, sizeof(out)); + n = cbuf_read(&cb, out, 6); + CHECK(n == 6, "read 6 after wrap"); + CHECK(memcmp(out, "ABCDEF", 6) == 0, "content after wrap"); + CHECK(cbuf_used(&cb) == 0, "empty after drain"); + + cbuf_destroy(&cb); + printf("test_wrap OK\n"); +} + +static void +test_partial(void) +{ + struct cbuf cb; + char in[8] = "12345678"; + char out[8] = {0}; + size_t n; + + CHECK(cbuf_init(&cb, 4) == 0, "init small"); + + n = cbuf_write(&cb, in, 8); + CHECK(n == 4, "write clamps to free space"); + CHECK(cbuf_used(&cb) == 4, "buffer full"); + + n = cbuf_read(&cb, out, 8); + CHECK(n == 4, "read clamps to live data"); + CHECK(memcmp(out, "1234", 4) == 0, "content of partial"); + CHECK(cbuf_used(&cb) == 0, "buffer empty after partial drain"); + + cbuf_destroy(&cb); + printf("test_partial OK\n"); +} + +static void +test_alternation(void) +{ + struct cbuf cb; + char c, out; + int i; + + CHECK(cbuf_init(&cb, 16) == 0, "init alt"); + for (i = 0; i < 100; i++) { + c = (char)('a' + (i % 26)); + CHECK(cbuf_write(&cb, &c, 1) == 1, "alt write"); + CHECK(cbuf_read(&cb, &out, 1) == 1, "alt read"); + CHECK(out == c, "alt match"); + } + CHECK(cbuf_used(&cb) == 0, "alt empty"); + cbuf_destroy(&cb); + printf("test_alternation OK\n"); +} + +int +main(void) +{ + test_basic(); + test_wrap(); + test_partial(); + test_alternation(); + printf("all tests OK\n"); + return (0); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.c b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.c new file mode 100644 index 0000000..c5028c1 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.c @@ -0,0 +1,113 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: userland implementation of the byte-oriented circular buffer. + */ + +#include "cbuf.h" + +#include +#include +#include + +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size); + if (cb->cb_data == NULL) + return (ENOMEM); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL) + return; + free(cb->cb_data); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.h b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.h new file mode 100644 index 0000000..9d157d4 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/cbuf-userland/cbuf.h @@ -0,0 +1,35 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-02/ch10-handling-io-efficiently/stage2-circular/Makefile b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/Makefile new file mode 100644 index 0000000..fff9bed --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 10 Stage 2 myfirst driver. +# +# Splices the cbuf abstraction into the Chapter 9 Stage 3 echo driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.c b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.h b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-02/ch10-handling-io-efficiently/stage2-circular/myfirst.c b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/myfirst.c new file mode 100644 index 0000000..4d876dc --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage2-circular/myfirst.c @@ -0,0 +1,378 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 10, Stage 2: circular-buffer integration. + * + * Replaces the Stage 3 linear FIFO from Chapter 9 with a true + * circular buffer (cbuf). The handlers loop over a stack-resident + * bounce buffer so that the wrap-around logic stays inside cbuf_*(). + * + * No blocking or non-blocking semantics yet; an empty buffer returns + * 0 to the reader, a full buffer causes a short write. Stage 3 adds + * mtx_sleep + IO_NDELAY support on top of this base. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_used(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, + "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, "open via %s fh=%p (active=%d)\n", + devtoname(dev), fh, sc->active_fhs); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = cbuf_read(&sc->cb, bounce, take); + if (got == 0) { + mtx_unlock(&sc->mtx); + break; + } + sc->bytes_read += got; + fh->reads += got; + mtx_unlock(&sc->mtx); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + room = cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + if (room == 0) + break; + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + mtx_lock(&sc->mtx); + put = cbuf_write(&sc->cb, bounce, want); + sc->bytes_written += put; + fh->writes += put; + mtx_unlock(&sc->mtx); + + if (put < want) + break; + } + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 10 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the FIFO"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the FIFO"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/Makefile b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/Makefile new file mode 100644 index 0000000..fff9bed --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 10 Stage 2 myfirst driver. +# +# Splices the cbuf abstraction into the Chapter 9 Stage 3 echo driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.c b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.h b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/myfirst.c b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/myfirst.c new file mode 100644 index 0000000..f50117a --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage3-blocking/myfirst.c @@ -0,0 +1,416 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 10, Stage 3: blocking and non-blocking I/O. + * + * Builds on Stage 2 by adding mtx_sleep(9) on the empty/full + * condition, IO_NDELAY interpretation as EAGAIN, and wakeup(9) + * matching every state transition. Detach now sets is_attached=0 + * and wakes any sleepers before tearing the mutex down. + * + * Stage 4 layers d_poll/selrecord/selwakeup on top of this. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_name = "myfirst", +}; + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_used(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + device_printf(sc->dev, + "per-open dtor fh=%p reads=%lu writes=%lu\n", + fh, (unsigned long)fh->reads, (unsigned long)fh->writes); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) { + mtx_unlock(&sc->mtx); + return (0); + } + if (ioflag & IO_NDELAY) { + mtx_unlock(&sc->mtx); + return (EAGAIN); + } + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, + "myfrd", 0); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error); + } + if (!sc->is_attached) { + mtx_unlock(&sc->mtx); + return (ENXIO); + } + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = cbuf_read(&sc->cb, bounce, take); + sc->bytes_read += got; + fh->reads += got; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + while ((room = cbuf_free(&sc->cb)) == 0) { + if (uio->uio_resid != nbefore) { + mtx_unlock(&sc->mtx); + return (0); + } + if (ioflag & IO_NDELAY) { + mtx_unlock(&sc->mtx); + return (EAGAIN); + } + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, + "myfwr", 0); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error); + } + if (!sc->is_attached) { + mtx_unlock(&sc->mtx); + return (ENXIO); + } + } + mtx_unlock(&sc->mtx); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + mtx_lock(&sc->mtx); + put = cbuf_write(&sc->cb, bounce, want); + sc->bytes_written += put; + fh->writes += put; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + } + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 10 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the FIFO"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the FIFO"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + mtx_unlock(&sc->mtx); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/Makefile b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/Makefile new file mode 100644 index 0000000..fff9bed --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 10 Stage 2 myfirst driver. +# +# Splices the cbuf abstraction into the Chapter 9 Stage 3 echo driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.c b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.h b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/myfirst.c b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/myfirst.c new file mode 100644 index 0000000..afc9162 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage4-poll-refactor/myfirst.c @@ -0,0 +1,499 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 10, Stage 4: poll support and refactor. + * + * Adds d_poll, selinfo for read and write readiness, and refactors + * the I/O handlers to go through a small set of mutex-asserting + * helpers (myfirst_buf_read, myfirst_buf_write, myfirst_wait_data, + * myfirst_wait_room). + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->bytes_read, sc->bytes_written + * - sc->open_count, sc->active_fhs + * - sc->is_attached + * + * Locking discipline: + * - The mutex is acquired with mtx_lock and released with mtx_unlock. + * - mtx_sleep(&sc->cb, &sc->mtx, PCATCH, ...) is used to block while + * waiting on buffer state. wakeup(&sc->cb) is the matching call. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9), + * all of which may sleep. + * - The mutex is held when calling cbuf_*() helpers; the cbuf module is + * intentionally lock-free by itself and relies on the caller for safety. + * - selwakeup(9) and wakeup(9) are called with the mutex DROPPED, after + * the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + mtx_assert(&sc->mtx, MA_OWNED); + got = cbuf_read(&sc->cb, dst, n); + sc->bytes_read += got; + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + mtx_assert(&sc->mtx, MA_OWNED); + put = cbuf_write(&sc->cb, src, n); + sc->bytes_written += put; + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + mtx_assert(&sc->mtx, MA_OWNED); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + mtx_assert(&sc->mtx, MA_OWNED); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_used(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + mtx_lock(&sc->mtx); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + mtx_lock(&sc->mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + mtx_unlock(&sc->mtx); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 10 Stage 4)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the buffer"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + mtx_unlock(&sc->mtx); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/Makefile b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/Makefile new file mode 100644 index 0000000..fff9bed --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 10 Stage 2 myfirst driver. +# +# Splices the cbuf abstraction into the Chapter 9 Stage 3 echo driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.c b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.h b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/myfirst.c b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/myfirst.c new file mode 100644 index 0000000..8481285 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/stage5-mmap/myfirst.c @@ -0,0 +1,524 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 10, Stage 5: minimal d_mmap on top of Stage 4. + * + * Lets user space mmap(2) the cbuf's backing memory read-only. + * Writable mappings are refused; the cbuf would otherwise race + * with the I/O handlers. vtophys(9) translates the kernel virtual + * buffer into the physical address the VM system needs. + * + * Stage 4 features (d_poll, selinfo, helper refactor) are inherited + * unchanged. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->bytes_read, sc->bytes_written + * - sc->open_count, sc->active_fhs + * - sc->is_attached + * + * Locking discipline: + * - The mutex is acquired with mtx_lock and released with mtx_unlock. + * - mtx_sleep(&sc->cb, &sc->mtx, PCATCH, ...) is used to block while + * waiting on buffer state. wakeup(&sc->cb) is the matching call. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9), + * all of which may sleep. + * - The mutex is held when calling cbuf_*() helpers; the cbuf module is + * intentionally lock-free by itself and relies on the caller for safety. + * - selwakeup(9) and wakeup(9) are called with the mutex DROPPED, after + * the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; +static d_mmap_t myfirst_mmap; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_mmap = myfirst_mmap, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + mtx_assert(&sc->mtx, MA_OWNED); + got = cbuf_read(&sc->cb, dst, n); + sc->bytes_read += got; + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + mtx_assert(&sc->mtx, MA_OWNED); + put = cbuf_write(&sc->cb, src, n); + sc->bytes_written += put; + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + mtx_assert(&sc->mtx, MA_OWNED); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + mtx_assert(&sc->mtx, MA_OWNED); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_used(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + mtx_lock(&sc->mtx); + val = (unsigned int)cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + mtx_lock(&sc->mtx); + sc->active_fhs--; + mtx_unlock(&sc->mtx); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + mtx_lock(&sc->mtx); + sc->open_count++; + sc->active_fhs++; + mtx_unlock(&sc->mtx); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + mtx_lock(&sc->mtx); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + mtx_unlock(&sc->mtx); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + mtx_unlock(&sc->mtx); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + mtx_lock(&sc->mtx); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + mtx_unlock(&sc->mtx); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + mtx_lock(&sc->mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + mtx_unlock(&sc->mtx); + return (revents); +} + +static int +myfirst_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr, + int nprot, vm_memattr_t *memattr __unused) +{ + struct myfirst_softc *sc = dev->si_drv1; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + if ((nprot & VM_PROT_WRITE) != 0) + return (EACCES); + if (offset >= sc->cb.cb_size) + return (-1); + *paddr = vtophys((char *)sc->cb.cb_data + (offset & ~PAGE_MASK)); + return (0); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 10 Stage 5)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the buffer"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + mtx_lock(&sc->mtx); + if (sc->active_fhs > 0) { + mtx_unlock(&sc->mtx); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + mtx_unlock(&sc->mtx); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/Makefile b/examples/part-02/ch10-handling-io-efficiently/userland/Makefile new file mode 100644 index 0000000..f456479 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/Makefile @@ -0,0 +1,26 @@ +# Makefile for Chapter 10 userland test programs. + +PROGS= rw_myfirst_v2 rw_myfirst_nb producer_consumer stress_rw mmap_myfirst + +CFLAGS?= -O2 -Wall -Wextra -Wno-unused-parameter + +.PHONY: all clean +all: ${PROGS} + +rw_myfirst_v2: rw_myfirst_v2.c + ${CC} ${CFLAGS} -o $@ $< + +rw_myfirst_nb: rw_myfirst_nb.c + ${CC} ${CFLAGS} -o $@ $< + +producer_consumer: producer_consumer.c + ${CC} ${CFLAGS} -o $@ $< + +stress_rw: stress_rw.c + ${CC} ${CFLAGS} -o $@ $< + +mmap_myfirst: mmap_myfirst.c + ${CC} ${CFLAGS} -o $@ $< + +clean: + rm -f ${PROGS} diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/mmap_myfirst.c b/examples/part-02/ch10-handling-io-efficiently/userland/mmap_myfirst.c new file mode 100644 index 0000000..8cd922d --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/mmap_myfirst.c @@ -0,0 +1,45 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * mmap_myfirst.c: read-only mmap tester for /dev/myfirst (Stage 5). + * + * Maps the cbuf's backing memory and dumps the first 64 bytes. The + * raw bytes do not necessarily match a sequential read; the cbuf + * lives at unspecified positions inside the mapping. Use this tool + * mainly to confirm that the mapping itself works. + */ + +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" +#define MAPSIZE 4096 + +int +main(void) +{ + int fd = open(DEVPATH, O_RDONLY); + if (fd < 0) + err(1, "open %s", DEVPATH); + + char *map = mmap(NULL, MAPSIZE, PROT_READ, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) + err(1, "mmap"); + + printf("first 64 bytes:\n"); + for (int i = 0; i < 64; i++) { + printf(" %02x", (unsigned char)map[i]); + if ((i + 1) % 16 == 0) + putchar('\n'); + } + + munmap(map, MAPSIZE); + close(fd); + return (0); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/producer_consumer.c b/examples/part-02/ch10-handling-io-efficiently/userland/producer_consumer.c new file mode 100644 index 0000000..c9f5932 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/producer_consumer.c @@ -0,0 +1,139 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * producer_consumer.c: a two-process load test for /dev/myfirst. + * + * Forks a child writer and uses the parent as the reader. Each side + * generates / verifies a known per-position byte pattern and computes + * a rolling checksum. Mismatches and checksum disagreements indicate + * either a wrap-around bug or a locking bug in the driver. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" +#define TOTAL_BYTES (1024 * 1024) +#define BLOCK 4096 + +static uint32_t +checksum(const char *p, size_t n) +{ + uint32_t s = 0; + for (size_t i = 0; i < n; i++) + s = s * 31u + (uint8_t)p[i]; + return (s); +} + +static int +do_writer(void) +{ + int fd = open(DEVPATH, O_WRONLY); + if (fd < 0) + err(1, "writer: open"); + + char *buf = malloc(BLOCK); + if (buf == NULL) + err(1, "writer: malloc"); + + size_t written = 0; + uint32_t sum = 0; + while (written < TOTAL_BYTES) { + size_t left = TOTAL_BYTES - written; + size_t block = left < BLOCK ? left : BLOCK; + for (size_t i = 0; i < block; i++) + buf[i] = (char)((written + i) & 0xff); + sum += checksum(buf, block); + + const char *p = buf; + size_t remain = block; + while (remain > 0) { + ssize_t n = write(fd, p, remain); + if (n < 0) { + if (errno == EINTR) + continue; + warn("writer: write"); + close(fd); + free(buf); + return (1); + } + p += n; + remain -= n; + } + written += block; + } + + printf("writer: %zu bytes, checksum 0x%08x\n", written, sum); + close(fd); + free(buf); + return (0); +} + +static int +do_reader(void) +{ + int fd = open(DEVPATH, O_RDONLY); + if (fd < 0) + err(1, "reader: open"); + + char *buf = malloc(BLOCK); + if (buf == NULL) + err(1, "reader: malloc"); + + size_t got = 0; + uint32_t sum = 0; + int mismatches = 0; + while (got < TOTAL_BYTES) { + ssize_t n = read(fd, buf, BLOCK); + if (n < 0) { + if (errno == EINTR) + continue; + warn("reader: read"); + break; + } + if (n == 0) { + printf("reader: EOF at %zu\n", got); + break; + } + for (ssize_t i = 0; i < n; i++) { + if ((uint8_t)buf[i] != (uint8_t)((got + i) & 0xff)) + mismatches++; + } + sum += checksum(buf, n); + got += n; + } + + printf("reader: %zu bytes, checksum 0x%08x, mismatches %d\n", + got, sum, mismatches); + close(fd); + free(buf); + return (mismatches == 0 ? 0 : 2); +} + +int +main(void) +{ + pid_t pid = fork(); + if (pid < 0) + err(1, "fork"); + if (pid == 0) + _exit(do_writer()); + + int rc = do_reader(); + int status; + waitpid(pid, &status, 0); + int wexit = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + printf("exit: reader=%d writer=%d\n", rc, wexit); + return (rc || wexit); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_nb.c b/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_nb.c new file mode 100644 index 0000000..88a853f --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_nb.c @@ -0,0 +1,74 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * rw_myfirst_nb.c: non-blocking behaviour tester for /dev/myfirst. + * + * Exercises Stage 3+ of Chapter 10: + * - O_NONBLOCK + empty buffer -> EAGAIN + * - poll(POLLIN, 0) on empty buffer -> 0 + * - write + * - poll(POLLIN, 0) on non-empty buffer -> POLLIN | POLLRDNORM + * - non-blocking read returns the bytes + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" + +int +main(void) +{ + int fd, error; + ssize_t n; + char rbuf[128]; + struct pollfd pfd; + + fd = open(DEVPATH, O_RDWR | O_NONBLOCK); + if (fd < 0) + err(1, "open %s", DEVPATH); + + n = read(fd, rbuf, sizeof(rbuf)); + if (n < 0 && errno == EAGAIN) + printf("step 1: empty-read returned EAGAIN (expected)\n"); + else + printf("step 1: UNEXPECTED read returned %zd errno=%d\n", + n, errno); + + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + error = poll(&pfd, 1, 0); + printf("step 2: poll(POLLIN, 0) = %d revents=0x%x\n", + error, pfd.revents); + + n = write(fd, "hello world\n", 12); + printf("step 3: wrote %zd bytes\n", n); + + pfd.events = POLLIN; + pfd.revents = 0; + error = poll(&pfd, 1, 0); + printf("step 4: poll(POLLIN, 0) = %d revents=0x%x\n", + error, pfd.revents); + + memset(rbuf, 0, sizeof(rbuf)); + n = read(fd, rbuf, sizeof(rbuf)); + if (n > 0) { + rbuf[n] = '\0'; + printf("step 5: read %zd bytes: %s", n, rbuf); + } else { + printf("step 5: UNEXPECTED read returned %zd errno=%d\n", + n, errno); + } + + close(fd); + return (0); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_v2.c b/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_v2.c new file mode 100644 index 0000000..7c30eda --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/rw_myfirst_v2.c @@ -0,0 +1,110 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * rw_myfirst_v2.c: sized fill/drain tester for /dev/myfirst. + * + * Usage: + * rw_myfirst_v2 fill BYTES + * rw_myfirst_v2 drain BYTES + * + * "fill" writes a known per-position pattern up to BYTES bytes. + * "drain" reads up to BYTES bytes and reports the count. + * Both honour partial transfers via the read_all/write_all loops. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" + +static int +do_fill(size_t bytes) +{ + int fd = open(DEVPATH, O_WRONLY); + if (fd < 0) + err(1, "open %s", DEVPATH); + + char *buf = malloc(bytes); + if (buf == NULL) + err(1, "malloc %zu", bytes); + for (size_t i = 0; i < bytes; i++) + buf[i] = (char)('A' + (i % 26)); + + size_t left = bytes; + const char *p = buf; + while (left > 0) { + ssize_t n = write(fd, p, left); + if (n < 0) { + if (errno == EINTR) + continue; + warn("write at %zu left", left); + break; + } + p += n; + left -= n; + } + size_t wrote = bytes - left; + printf("fill: wrote %zu of %zu\n", wrote, bytes); + free(buf); + close(fd); + return (0); +} + +static int +do_drain(size_t bytes) +{ + int fd = open(DEVPATH, O_RDONLY); + if (fd < 0) + err(1, "open %s", DEVPATH); + + char *buf = malloc(bytes); + if (buf == NULL) + err(1, "malloc %zu", bytes); + + size_t left = bytes; + char *p = buf; + while (left > 0) { + ssize_t n = read(fd, p, left); + if (n < 0) { + if (errno == EINTR) + continue; + warn("read at %zu left", left); + break; + } + if (n == 0) { + printf("drain: EOF at %zu left\n", left); + break; + } + p += n; + left -= n; + } + size_t got = bytes - left; + printf("drain: read %zu of %zu\n", got, bytes); + free(buf); + close(fd); + return (0); +} + +int +main(int argc, char *argv[]) +{ + if (argc != 3) { + fprintf(stderr, "usage: %s fill|drain BYTES\n", argv[0]); + return (1); + } + size_t bytes = strtoul(argv[2], NULL, 0); + if (strcmp(argv[1], "fill") == 0) + return (do_fill(bytes)); + if (strcmp(argv[1], "drain") == 0) + return (do_drain(bytes)); + fprintf(stderr, "unknown mode: %s\n", argv[1]); + return (1); +} diff --git a/examples/part-02/ch10-handling-io-efficiently/userland/stress_rw.c b/examples/part-02/ch10-handling-io-efficiently/userland/stress_rw.c new file mode 100644 index 0000000..397b4b3 --- /dev/null +++ b/examples/part-02/ch10-handling-io-efficiently/userland/stress_rw.c @@ -0,0 +1,119 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * stress_rw.c: a single-process stress harness for /dev/myfirst. + * + * Runs through a small table of (block size, repeat count) pairs. + * For each pair, performs N round-trips of: + * - write(BLOCK) of a known pattern + * - read(BLOCK) and compare + * Reports timing and any data mismatches. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" + +struct probe { + size_t block; + int iters; +}; + +static const struct probe table[] = { + { 64, 1000 }, + { 256, 500 }, + { 1024, 200 }, + { 4096, 100 }, +}; + +static double +seconds(struct timeval *t) +{ + return (t->tv_sec + t->tv_usec / 1e6); +} + +static int +run_probe(int rfd, int wfd, size_t block, int iters) +{ + char *src = malloc(block); + char *dst = malloc(block); + if (src == NULL || dst == NULL) + err(1, "malloc"); + + int mismatches = 0; + struct timeval t0, t1; + gettimeofday(&t0, NULL); + + for (int it = 0; it < iters; it++) { + for (size_t i = 0; i < block; i++) + src[i] = (char)((it + i) & 0xff); + + size_t left = block; + const char *p = src; + while (left > 0) { + ssize_t n = write(wfd, p, left); + if (n < 0) { + if (errno == EINTR) continue; + warn("write"); + goto out; + } + p += n; left -= n; + } + + left = block; + char *q = dst; + while (left > 0) { + ssize_t n = read(rfd, q, left); + if (n < 0) { + if (errno == EINTR) continue; + warn("read"); + goto out; + } + if (n == 0) { + warn("EOF before draining"); + goto out; + } + q += n; left -= n; + } + + if (memcmp(src, dst, block) != 0) + mismatches++; + } + +out: + gettimeofday(&t1, NULL); + double elapsed = seconds(&t1) - seconds(&t0); + double bytes = (double)block * iters; + printf("block=%zu iters=%d mismatches=%d %.3f sec %.2f MB/s\n", + block, iters, mismatches, elapsed, + elapsed > 0 ? (bytes / elapsed) / (1024 * 1024) : 0); + free(src); free(dst); + return (mismatches); +} + +int +main(void) +{ + int rfd = open(DEVPATH, O_RDONLY); + int wfd = open(DEVPATH, O_WRONLY); + if (rfd < 0 || wfd < 0) + err(1, "open %s", DEVPATH); + + int total = 0; + for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) + total += run_probe(rfd, wfd, table[i].block, table[i].iters); + + close(rfd); close(wfd); + return (total == 0 ? 0 : 1); +} diff --git a/examples/part-03/ch11-concurrency/LOCKING.md b/examples/part-03/ch11-concurrency/LOCKING.md new file mode 100644 index 0000000..00da08d --- /dev/null +++ b/examples/part-03/ch11-concurrency/LOCKING.md @@ -0,0 +1,98 @@ +# myfirst Locking Strategy + +Chapter 11 driver, version 0.5-concurrency. + +## Overview + +The driver uses a single sleep mutex (`sc->mtx`) to serialize all +accesses to the circular buffer, the sleep channel, the selinfo +structures, and several per-softc fields. Byte counters are migrated +to `counter(9)` per-CPU counters in Stage 3 and protected there by +the `counter(9)` API itself. + +## What sc->mtx Protects + +- `sc->cb` (the circular buffer's internal state: `cb_head`, + `cb_used`, `cb_data`). +- `sc->open_count`, `sc->active_fhs`. +- `sc->is_attached` (writes; reads at handler entry may be + unprotected as an optimization, re-checked after every sleep). +- `sc->rsel`, `sc->wsel` (indirectly: `selrecord` is called inside + a critical section; `selwakeup` is called with the mutex dropped). + +## Lock-Free Fields (Stage 3 and later) + +- `sc->bytes_read`, `sc->bytes_written`: `counter_u64_t`. Updates + via `counter_u64_add`; reads via `counter_u64_fetch`. + +## Locking Discipline + +1. Acquire with `MYFIRST_LOCK(sc)` and release with + `MYFIRST_UNLOCK(sc)`. These are macros around `mtx_lock` and + `mtx_unlock` respectively; they can be changed to a different + lock class without touching call sites. +2. Wait with `mtx_sleep(&sc->cb, &sc->mtx, PCATCH, wmesg, 0)`. + Wake with `wakeup(&sc->cb)`. +3. NEVER hold `sc->mtx` across `uiomove(9)`, `copyin(9)`, `copyout(9)`, + `selwakeup(9)`, or `wakeup(9)`. Each of these may sleep or take + other locks. +4. All `myfirst_buf_*` and `myfirst_wait_*` helpers assert + `MYFIRST_ASSERT(sc)` at entry (compiles to `mtx_assert(MA_OWNED)`). + +## Known Non-Locked Accesses + +### `sc->is_attached` (reads at handler entry) + +Unprotected plain read. Safe because: +- A stale "true" is re-checked after every sleep via + `if (!sc->is_attached) return (ENXIO)`. +- A stale "false" causes the handler to return ENXIO early, which + is also what it would do with a fresh false. + +### `sc->open_count`, `sc->active_fhs` (sysctl reads) + +Unprotected plain loads. Safe on amd64 and arm64 (aligned 64-bit +loads are atomic). Acceptable on i386 and armv7 because the torn +read, if it ever happened, would produce a single bad statistic +with no correctness impact. + +## Lock Order + +Currently, the driver holds only `sc->mtx`. There are no lock-order +rules. When Chapter 12 introduces additional locks (`sx(9)` is a +likely candidate), the order will be documented here as: + +``` +sc->mtx -> sc->other_lock +``` + +meaning: a thread holding `sc->mtx` may acquire `sc->other_lock`, +but not the reverse. + +## Wait Channels + +- `&sc->cb`: signals that the buffer state has changed (space or + data has become available). Used by both read and write paths. + +## Rules Summary + +1. Never sleep while holding `sc->mtx` except via `mtx_sleep`, which + atomically drops and reacquires. +2. Never call `uiomove`, `copyin`, `copyout`, `selwakeup`, or + `wakeup` while holding `sc->mtx`. +3. Every `cbuf_*` call must happen with `sc->mtx` held. +4. The detach path clears `sc->is_attached` under the mutex and + then wakes any sleepers before destroying the mutex. +5. `counter_u64_add` does not require the mutex. + +## History + +- 0.5-concurrency (Chapter 11, Stage 2): MYFIRST_LOCK/UNLOCK/ASSERT + macros; explicit version string. +- 0.5-counter9 (Chapter 11, Stage 3): byte counters migrated to + counter(9). +- 0.5-kasserts (Chapter 11, Stage 5): KASSERT calls added for every + invariant on the cbuf and helper paths. +- 0.4-poll-refactor (Chapter 10, Stage 4): wait helpers; locking + strategy documented inline. +- Earlier versions: see Chapter 10 history. diff --git a/examples/part-03/ch11-concurrency/stage1-race-demo/Makefile b/examples/part-03/ch11-concurrency/stage1-race-demo/Makefile new file mode 100644 index 0000000..4dcbe34 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage1-race-demo/Makefile @@ -0,0 +1,14 @@ +# Makefile for the Chapter 11 Stage 1 race-demo driver. +# +# DANGEROUS: this driver has had its mutex removed from the I/O path +# deliberately to demonstrate the corruption that results. It exists +# for the Section 2 lab only. Do not run in production. Expect +# inconsistent data, possible kernel warnings, and (rarely) panics. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +CFLAGS+= -DRACE_DEMO + +.include diff --git a/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.c b/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.h b/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage1-race-demo/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch11-concurrency/stage1-race-demo/myfirst.c b/examples/part-03/ch11-concurrency/stage1-race-demo/myfirst.c new file mode 100644 index 0000000..f0a5f6e --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage1-race-demo/myfirst.c @@ -0,0 +1,514 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 11, Stage 1: DELIBERATELY UNSAFE race-demo driver. + * + * This driver is structurally identical to the Chapter 10 Stage 4 driver, + * except that compiling with -DRACE_DEMO (the default in this directory's + * Makefile) makes MYFIRST_LOCK/UNLOCK/ASSERT expand to no-ops. The mutex + * is initialized and destroyed correctly so that mtx_sleep continues to + * work, but the I/O paths run with no mutual exclusion. + * + * The purpose of the driver is to demonstrate the data corruption that + * arises in a circular buffer when multiple threads can read and write + * concurrently without synchronization. See Section 2 of Chapter 11 for + * the exercise that uses it. + * + * DO NOT load this module on a production machine. Expect inconsistent + * data, possible kernel warnings, and (rarely) panics. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.5-race-demo" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#ifdef RACE_DEMO +#define MYFIRST_LOCK(sc) do { (void)(sc); } while (0) +#else +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#endif +#ifdef RACE_DEMO +#define MYFIRST_UNLOCK(sc) do { (void)(sc); } while (0) +#else +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#endif +#ifdef RACE_DEMO +#define MYFIRST_ASSERT(sc) do { (void)(sc); } while (0) +#else +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) +#endif + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + got = cbuf_read(&sc->cb, dst, n); + sc->bytes_read += got; + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + put = cbuf_write(&sc->cb, src, n); + sc->bytes_written += put; + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 11 Stage 1 (UNSAFE))"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the buffer"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch11-concurrency/stage2-concurrent-safe/Makefile b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/Makefile new file mode 100644 index 0000000..ae66039 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 11 Stage 2 myfirst driver. +# +# Concurrent-safe driver with explicit MYFIRST_LOCK/UNLOCK/ASSERT +# macros and mtx_assert throughout. Functionally identical to +# Chapter 10 Stage 4; the changes are in comments, assertions, +# and the macro indirection that sets up for future lock changes. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.c b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.h b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch11-concurrency/stage2-concurrent-safe/myfirst.c b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/myfirst.c new file mode 100644 index 0000000..d5a71cc --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage2-concurrent-safe/myfirst.c @@ -0,0 +1,514 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 11, Stage 2: concurrent-safe with documented locking. + * + * Functionally identical to the Chapter 10 Stage 4 driver. The + * MYFIRST_LOCK/UNLOCK/ASSERT macros add a single point of indirection + * around the mutex so that future stages (sx locks, finer-grained + * mutexes) can change the lock class without touching the call sites. + * The version string is bumped to "0.5-concurrency" to reflect the + * fact that the locking story is now explicit. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->bytes_read, sc->bytes_written + * - sc->open_count, sc->active_fhs + * - sc->is_attached + * + * Locking discipline: + * - The mutex is acquired with mtx_lock and released with mtx_unlock. + * - mtx_sleep(&sc->cb, &sc->mtx, PCATCH, ...) is used to block while + * waiting on buffer state. wakeup(&sc->cb) is the matching call. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9), + * all of which may sleep. + * - The mutex is held when calling cbuf_*() helpers; the cbuf module is + * intentionally lock-free by itself and relies on the caller for safety. + * - selwakeup(9) and wakeup(9) are called with the mutex DROPPED, after + * the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.5-concurrency" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + uint64_t bytes_read; + uint64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + got = cbuf_read(&sc->cb, dst, n); + sc->bytes_read += got; + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + put = cbuf_write(&sc->cb, src, n); + sc->bytes_written += put; + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 11 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = 0; + sc->bytes_written = 0; + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + &sc->bytes_read, 0, "Total bytes drained from the buffer"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + &sc->bytes_written, 0, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch11-concurrency/stage3-counter9/Makefile b/examples/part-03/ch11-concurrency/stage3-counter9/Makefile new file mode 100644 index 0000000..ae66039 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage3-counter9/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 11 Stage 2 myfirst driver. +# +# Concurrent-safe driver with explicit MYFIRST_LOCK/UNLOCK/ASSERT +# macros and mtx_assert throughout. Functionally identical to +# Chapter 10 Stage 4; the changes are in comments, assertions, +# and the macro indirection that sets up for future lock changes. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.c b/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.h b/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage3-counter9/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch11-concurrency/stage3-counter9/myfirst.c b/examples/part-03/ch11-concurrency/stage3-counter9/myfirst.c new file mode 100644 index 0000000..7229c74 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage3-counter9/myfirst.c @@ -0,0 +1,520 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 11, Stage 3: migrate byte counters to counter(9). + * + * Builds on Stage 2 by replacing sc->bytes_read and sc->bytes_written, + * which were plain uint64_t fields protected by sc->mtx, with per-CPU + * counter_u64_t handles managed by the counter(9) API. The migration + * removes those two fields from the set protected by sc->mtx and lets + * the data path update them lock-free via counter_u64_add. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters and + * protect themselves; the mutex is no longer required to update them. + * + * Locking discipline (unchanged from Stage 2 except for the counters): + * - The mutex is acquired with mtx_lock and released with mtx_unlock. + * - mtx_sleep(&sc->cb, &sc->mtx, PCATCH, ...) is used to block while + * waiting on buffer state. wakeup(&sc->cb) is the matching call. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9), + * all of which may sleep. + * - The mutex is held when calling cbuf_*() helpers; the cbuf module is + * intentionally lock-free by itself and relies on the caller for safety. + * - selwakeup(9) and wakeup(9) are called with the mutex DROPPED, after + * the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.5-concurrency" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + got = cbuf_read(&sc->cb, dst, n); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + put = cbuf_write(&sc->cb, src, n); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 11 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch11-concurrency/stage5-kasserts/Makefile b/examples/part-03/ch11-concurrency/stage5-kasserts/Makefile new file mode 100644 index 0000000..ae66039 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage5-kasserts/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 11 Stage 2 myfirst driver. +# +# Concurrent-safe driver with explicit MYFIRST_LOCK/UNLOCK/ASSERT +# macros and mtx_assert throughout. Functionally identical to +# Chapter 10 Stage 4; the changes are in comments, assertions, +# and the macro indirection that sets up for future lock changes. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.c b/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.h b/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage5-kasserts/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch11-concurrency/stage5-kasserts/myfirst.c b/examples/part-03/ch11-concurrency/stage5-kasserts/myfirst.c new file mode 100644 index 0000000..f4a7f75 --- /dev/null +++ b/examples/part-03/ch11-concurrency/stage5-kasserts/myfirst.c @@ -0,0 +1,537 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 11, Stage 5: KASSERTs throughout, ready for a debug kernel. + * + * Builds on Chapter 11 Stage 3 (counter(9) migration) by adding KASSERT + * calls to every cbuf helper, every wait helper, and every transition that + * has an invariant worth checking. With INVARIANTS enabled in the kernel, + * any logic bug that violates one of these invariants becomes an immediate, + * loud panic with a backtrace, instead of silent corruption that might + * surface much later. + * + * Adds MYFIRST_LOCK/UNLOCK/ASSERT + * macros for future lock-class changes, plus an explicit version string. + * + * Adds d_poll, selinfo for read and write readiness, and refactors + * the I/O handlers to go through a small set of mutex-asserting + * helpers (myfirst_buf_read, myfirst_buf_write, myfirst_wait_data, + * myfirst_wait_room). + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached + * + * sc->bytes_read and sc->bytes_written are counter(9) per-CPU + * counters; they protect themselves and do not need sc->mtx. + * + * Locking discipline: + * - The mutex is acquired with mtx_lock and released with mtx_unlock. + * - mtx_sleep(&sc->cb, &sc->mtx, PCATCH, ...) is used to block while + * waiting on buffer state. wakeup(&sc->cb) is the matching call. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9), + * all of which may sleep. + * - The mutex is held when calling cbuf_*() helpers; the cbuf module is + * intentionally lock-free by itself and relies on the caller for safety. + * - selwakeup(9) and wakeup(9) are called with the mutex DROPPED, after + * the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.5-kasserts" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfrd", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = mtx_sleep(&sc->cb, &sc->mtx, PCATCH, "myfwr", 0); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->wsel); + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + wakeup(&sc->cb); + selwakeup(&sc->rsel); + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 11 Stage 5)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; node /dev/%s (alias /dev/myfirst), cbuf=%zu bytes\n", + devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + wakeup(&sc->cb); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch11-concurrency/userland/Makefile b/examples/part-03/ch11-concurrency/userland/Makefile new file mode 100644 index 0000000..bc811d4 --- /dev/null +++ b/examples/part-03/ch11-concurrency/userland/Makefile @@ -0,0 +1,21 @@ +# Makefile for Chapter 11 userland concurrency testers. + +PROGS= mp_stress mt_reader lat_tester + +.PHONY: all +all: ${PROGS} + +CFLAGS?= -O2 -Wall -Wextra -Wno-unused-parameter + +mp_stress: mp_stress.c + ${CC} ${CFLAGS} -o $@ $< + +mt_reader: mt_reader.c + ${CC} ${CFLAGS} -pthread -o $@ $< + +lat_tester: lat_tester.c + ${CC} ${CFLAGS} -o $@ $< + +.PHONY: clean +clean: + rm -f ${PROGS} diff --git a/examples/part-03/ch11-concurrency/userland/lat_tester.c b/examples/part-03/ch11-concurrency/userland/lat_tester.c new file mode 100644 index 0000000..932f43b --- /dev/null +++ b/examples/part-03/ch11-concurrency/userland/lat_tester.c @@ -0,0 +1,82 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * lat_tester.c: measure read latency against /dev/myfirst and print + * a simple bucketed histogram. Useful for observing the cost of + * the driver's mutex under various load conditions. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" +#define NSAMPLES 10000 +#define BLOCK 1024 + +static uint64_t +nanos(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ((uint64_t)ts.tv_sec * 1000000000ULL + ts.tv_nsec); +} + +int +main(void) +{ + int fd; + char buf[BLOCK]; + uint64_t samples[NSAMPLES]; + int nvalid = 0; + uint64_t buckets[8] = {0}; + const char *labels[8] = { + "<1us ", "<10us ", "<100us ", "<1ms ", + "<10ms ", "<100ms ", "<1s ", ">=1s " + }; + + fd = open(DEVPATH, O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open"); + + for (int i = 0; i < NSAMPLES; i++) { + uint64_t t0 = nanos(); + ssize_t n = read(fd, buf, sizeof(buf)); + uint64_t t1 = nanos(); + if (n > 0) + samples[nvalid++] = t1 - t0; + else + usleep(100); + } + close(fd); + + for (int i = 0; i < nvalid; i++) { + uint64_t ns = samples[i]; + int b; + if (ns < 1000) b = 0; + else if (ns < 10000) b = 1; + else if (ns < 100000) b = 2; + else if (ns < 1000000) b = 3; + else if (ns < 10000000) b = 4; + else if (ns < 100000000) b = 5; + else if (ns < 1000000000) b = 6; + else b = 7; + buckets[b]++; + } + + printf("Latency histogram (%d samples):\n", nvalid); + for (int i = 0; i < 8; i++) + printf(" %s %6llu\n", + labels[i], (unsigned long long)buckets[i]); + return (0); +} diff --git a/examples/part-03/ch11-concurrency/userland/mp_stress.c b/examples/part-03/ch11-concurrency/userland/mp_stress.c new file mode 100644 index 0000000..d28b683 --- /dev/null +++ b/examples/part-03/ch11-concurrency/userland/mp_stress.c @@ -0,0 +1,126 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * mp_stress.c: a multi-process stress tester for /dev/myfirst. + * + * Forks NWRITERS writer children and NREADERS reader children. + * Each runs for SECONDS seconds and reports its total byte count. + * The sum across writers should match the sum across readers plus + * whatever remains in the buffer when the run ends. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" +#define NWRITERS 2 +#define NREADERS 2 +#define SECONDS 30 + +static volatile sig_atomic_t stop; + +static void +sigalrm(int s __unused) +{ + stop = 1; +} + +static int +child_writer(int id) +{ + int fd; + char buf[1024]; + unsigned long long written = 0; + + fd = open(DEVPATH, O_WRONLY); + if (fd < 0) + err(1, "writer %d: open", id); + + memset(buf, 'a' + id, sizeof(buf)); + + while (!stop) { + ssize_t n = write(fd, buf, sizeof(buf)); + if (n < 0) { + if (errno == EINTR) + continue; + break; + } + written += n; + } + close(fd); + printf("writer %d: %llu bytes\n", id, written); + return (0); +} + +static int +child_reader(int id) +{ + int fd; + char buf[1024]; + unsigned long long got = 0; + + fd = open(DEVPATH, O_RDONLY); + if (fd < 0) + err(1, "reader %d: open", id); + + while (!stop) { + ssize_t n = read(fd, buf, sizeof(buf)); + if (n < 0) { + if (errno == EINTR) + continue; + break; + } + got += n; + } + close(fd); + printf("reader %d: %llu bytes\n", id, got); + return (0); +} + +int +main(void) +{ + pid_t pids[NWRITERS + NREADERS]; + int n = 0; + + signal(SIGALRM, sigalrm); + + for (int i = 0; i < NWRITERS; i++) { + pid_t pid = fork(); + if (pid < 0) + err(1, "fork"); + if (pid == 0) { + signal(SIGALRM, sigalrm); + alarm(SECONDS); + _exit(child_writer(i)); + } + pids[n++] = pid; + } + for (int i = 0; i < NREADERS; i++) { + pid_t pid = fork(); + if (pid < 0) + err(1, "fork"); + if (pid == 0) { + signal(SIGALRM, sigalrm); + alarm(SECONDS); + _exit(child_reader(i)); + } + pids[n++] = pid; + } + + for (int i = 0; i < n; i++) { + int status; + waitpid(pids[i], &status, 0); + } + return (0); +} diff --git a/examples/part-03/ch11-concurrency/userland/mt_reader.c b/examples/part-03/ch11-concurrency/userland/mt_reader.c new file mode 100644 index 0000000..4dd84b9 --- /dev/null +++ b/examples/part-03/ch11-concurrency/userland/mt_reader.c @@ -0,0 +1,95 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * mt_reader.c: multiple threads reading from one descriptor of + * /dev/myfirst. Exercises the driver's handling of multiple + * concurrent readers on the same fh. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" +#define NTHREADS 4 +#define BYTES_PER_THR (256 * 1024) +#define BLOCK 4096 + +static int g_fd; +static uint64_t total[NTHREADS]; +static uint32_t sum[NTHREADS]; + +static uint32_t +checksum(const char *p, size_t n) +{ + uint32_t s = 0; + for (size_t i = 0; i < n; i++) + s = s * 31u + (uint8_t)p[i]; + return (s); +} + +static void * +reader(void *arg) +{ + int tid = *(int *)arg; + char buf[BLOCK]; + uint64_t got = 0; + uint32_t sm = 0; + + while (got < BYTES_PER_THR) { + ssize_t n = read(g_fd, buf, sizeof(buf)); + if (n < 0) { + if (errno == EINTR) + continue; + warn("thread %d: read", tid); + break; + } + if (n == 0) + break; + sm += checksum(buf, n); + got += n; + } + total[tid] = got; + sum[tid] = sm; + return (NULL); +} + +int +main(void) +{ + pthread_t tids[NTHREADS]; + int ids[NTHREADS]; + + g_fd = open(DEVPATH, O_RDONLY); + if (g_fd < 0) + err(1, "open %s", DEVPATH); + + for (int i = 0; i < NTHREADS; i++) { + ids[i] = i; + if (pthread_create(&tids[i], NULL, reader, &ids[i]) != 0) + err(1, "pthread_create"); + } + for (int i = 0; i < NTHREADS; i++) + pthread_join(tids[i], NULL); + + uint64_t grand = 0; + for (int i = 0; i < NTHREADS; i++) { + printf("thread %d: %" PRIu64 " bytes, checksum 0x%08x\n", + i, total[i], sum[i]); + grand += total[i]; + } + printf("grand total: %" PRIu64 "\n", grand); + + close(g_fd); + return (0); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/LOCKING.md b/examples/part-03/ch12-synchronization-mechanisms/LOCKING.md new file mode 100644 index 0000000..f7499d9 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/LOCKING.md @@ -0,0 +1,160 @@ +# myfirst Locking Strategy + +Chapter 12 driver, version 0.6-sync. + +## Overview + +The driver uses three synchronization primitives: a sleep mutex +(`sc->mtx`) for the data path, an sx lock (`sc->cfg_sx`) for the +configuration subsystem, and two condition variables (`sc->data_cv`, +`sc->room_cv`) for blocking reads and writes. Byte counters use +`counter(9)` per-CPU counters and protect themselves. + +## Locks Owned by This Driver + +### sc->mtx (mutex(9), MTX_DEF) + +Protects: +- `sc->cb` (the circular buffer's internal state) +- `sc->open_count`, `sc->active_fhs` +- `sc->is_attached` (writes; reads at handler entry may be unprotected + as an optimization, re-checked after every sleep) + +(Note: the timeout fields `sc->read_timeout_ms` and `sc->write_timeout_ms` +are *not* protected by `sc->mtx`. They are plain ints, written by the +sysctl framework via direct `CTLFLAG_RW` binding and read by the wait +helpers without locking. See "Known Non-Locked Accesses" below.) + +### sc->cfg_sx (sx(9)) + +Protects: +- `sc->cfg.debug_level` +- `sc->cfg.soft_byte_limit` +- `sc->cfg.nickname` + +Shared mode: every read of any cfg field. +Exclusive mode: every write of any cfg field, plus the reset sysctl +in Stage 4. + +### sc->data_cv (cv(9)) + +Wait condition: data is available in the cbuf (`cbuf_used > 0`). +Interlock: `sc->mtx`. +Signalled by: `myfirst_write` after a successful cbuf write. +Broadcast by: `myfirst_detach`. +Waiters: `myfirst_read` in `myfirst_wait_data`. + +### sc->room_cv (cv(9)) + +Wait condition: room is available in the cbuf (`cbuf_free > 0`). +Interlock: `sc->mtx`. +Signalled by: `myfirst_read` after a successful cbuf read, and by +`myfirst_sysctl_reset` after resetting the cbuf. +Broadcast by: `myfirst_detach`. +Waiters: `myfirst_write` in `myfirst_wait_room`. + +## Lock-Free Fields + +- `sc->bytes_read`, `sc->bytes_written`: `counter_u64_t`. Updates via + `counter_u64_add`; reads via `counter_u64_fetch`. + +## Lock Order + +``` +sc->mtx -> sc->cfg_sx +``` + +A thread holding `sc->mtx` may acquire `sc->cfg_sx` in either mode. +A thread holding `sc->cfg_sx` may NOT acquire `sc->mtx`. + +Rationale: the data path always holds `sc->mtx` and may need to read +configuration during its critical section. The configuration path +(sysctl writers) does not need the data mutex; the only path that +holds both is `myfirst_sysctl_reset`, which acquires them in the +canonical order. + +## Locking Discipline + +1. Acquire mutex with `MYFIRST_LOCK(sc)`, release with + `MYFIRST_UNLOCK(sc)`. +2. Acquire sx in shared mode with `MYFIRST_CFG_SLOCK(sc)`, exclusive + with `MYFIRST_CFG_XLOCK(sc)`. Release with the matching unlock. +3. Wait on a cv with `cv_wait_sig` (interruptible) or + `cv_timedwait_sig` (interruptible + bounded). +4. Signal a cv with `cv_signal` (one waiter) or `cv_broadcast` (all + waiters). Use `cv_broadcast` only for state changes that affect + all waiters (detach, configuration reset). +5. NEVER hold `sc->mtx` across `uiomove(9)`, `copyin(9)`, `copyout(9)`, + `selwakeup(9)`, or any potentially-sleeping call. `cv_wait_sig` is + the exception (it atomically drops the interlock). +6. NEVER hold `sc->cfg_sx` across `uiomove(9)`, `sysctl_handle_*`, or + any other potentially-sleeping call. +7. All `cbuf_*` calls must happen with `sc->mtx` held (the helpers + assert MA_OWNED). +8. The detach path clears `sc->is_attached` under `sc->mtx`, + broadcasts both cvs, and refuses detach while `active_fhs > 0`. + +## Snapshot-and-Apply Pattern + +When a path needs both `sc->mtx` and `sc->cfg_sx`, prefer the +snapshot-and-apply pattern over holding both at once: + + 1. `sx_slock(&sc->cfg_sx)`; read cfg fields into local variables; + `sx_sunlock(&sc->cfg_sx)`. + 2. `MYFIRST_LOCK(sc)`; do cbuf operations using the snapshot; + `MYFIRST_UNLOCK(sc)`. + +The snapshot may be slightly stale by the time it is used. For +configuration values that are advisory (debug level, soft byte +limit), this is acceptable. + +The reset sysctl in Stage 4 is the exception: it holds both locks +together because it must atomically clear the buffer, the counters, +and the debug level. The acquisition order is mtx first, sx second; +the release order is the reverse. + +## Wait Channels + +- `sc->data_cv`: data has become available. +- `sc->room_cv`: room has become available. + +The legacy `&sc->cb` wakeup channel from Chapter 10 has been retired. + +## Known Non-Locked Accesses + +### `sc->is_attached` at handler entry + +Unprotected plain read. Safe because: +- A stale "true" is re-checked after every sleep via + `if (!sc->is_attached) return (ENXIO)`. +- A stale "false" causes the handler to return ENXIO early, which is + also what it would do with a fresh false. + +### `sc->open_count`, `sc->active_fhs` at sysctl read time + +Unprotected plain loads. Safe on amd64 and arm64 (aligned 64-bit +loads are atomic). Acceptable on i386 because the torn read, if it +ever happened, would produce a single bad statistic with no +correctness impact. + +### `sc->read_timeout_ms`, `sc->write_timeout_ms` + +The wait helpers read these without taking any lock. The sysctl +framework writes them as plain integer stores. Tearing is impossible +on aligned ints on every architecture FreeBSD supports. A stale read +results only in a slightly different timeout for the next wait, which +is acceptable. + +## History + +- 0.6-sync (Chapter 12, Stage 4): combined version with cv channels, + bounded reads, sx-protected configuration, and reset sysctl. +- 0.6-sx-config (Stage 3): sx for configuration subsystem; debug, + soft_byte_limit, nickname sysctls. +- 0.6-bounded-read (Stage 2): cv_timedwait_sig with read_timeout_ms + and write_timeout_ms sysctls. +- 0.6-cv-channels (Stage 1): cv replaces anonymous wakeup channels. +- 0.5-kasserts (Chapter 11, Stage 5): KASSERT calls added. +- 0.5-counter9 (Chapter 11, Stage 3): byte counters via counter(9). +- 0.5-concurrency (Chapter 11, Stage 2): macros, locking strategy. +- Earlier versions: see Chapter 10 and Chapter 11 history. diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/Makefile b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/Makefile new file mode 100644 index 0000000..ea67fe7 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 12 Stage 1 myfirst driver. +# +# Replaces the anonymous mtx_sleep/wakeup channel from Chapter 11 +# with two named condition variables (data_cv, room_cv). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.c b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.h b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/myfirst.c b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/myfirst.c new file mode 100644 index 0000000..7290726 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage1-cv-channels/myfirst.c @@ -0,0 +1,547 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 12, Stage 1: condition variables replace anonymous channels. + * + * Builds on Chapter 11 Stage 5 (counter9 + KASSERTs). Replaces the + * shared anonymous wakeup channel (&sc->cb) with two named condition + * variables: data_cv ("data is available") and room_cv ("room is + * available"). Wait helpers use cv_wait_sig; signallers target the + * appropriate cv only. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.6-cv-channels" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 12 Stage 1)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/Makefile b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/Makefile new file mode 100644 index 0000000..195267a --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 12 Stage 2 myfirst driver. +# +# Adds a read_timeout_ms sysctl that bounds blocking reads via +# cv_timedwait_sig. Symmetric write_timeout_ms is also exposed. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.c b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.h b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/myfirst.c b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/myfirst.c new file mode 100644 index 0000000..c767239 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage2-bounded-read/myfirst.c @@ -0,0 +1,581 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 12, Stage 2: bounded reads via cv_timedwait_sig. + * + * Builds on Chapter 12 Stage 1 (cv channels) by adding two new sysctls: + * read_timeout_ms and write_timeout_ms. When non-zero, the wait + * helpers use cv_timedwait_sig and translate EWOULDBLOCK to EAGAIN. + * Default (0) preserves the indefinite-wait behaviour from Stage 1. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.6-bounded-read" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 12 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/Makefile b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/Makefile new file mode 100644 index 0000000..69c3060 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 12 Stage 3 myfirst driver. +# +# Adds an sx-protected configuration subsystem (debug_level, +# soft_byte_limit, nickname) on top of Stage 2's bounded reads. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.c b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.h b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/myfirst.c b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/myfirst.c new file mode 100644 index 0000000..4ec0343 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage3-sx-config/myfirst.c @@ -0,0 +1,723 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 12, Stage 3: sx-protected configuration subsystem. + * + * Builds on Stage 2 (bounded reads) by adding a runtime configuration + * subsystem protected by sc->cfg_sx, an sx(9) lock. Three configurable + * fields: debug_level, soft_byte_limit, nickname. Lock order: sc->mtx + * before sc->cfg_sx (mutex first, sx second). + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.6-sx-config" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 12 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage4-final/Makefile b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/Makefile new file mode 100644 index 0000000..3be0b30 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/Makefile @@ -0,0 +1,11 @@ +# Makefile for the Chapter 12 Stage 4 myfirst driver. +# +# The final Chapter 12 driver. Combines cv channels, bounded reads, +# sx-protected configuration, and a reset sysctl that exercises the +# canonical lock order (mtx first, sx second). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.c b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.h b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch12-synchronization-mechanisms/stage4-final/myfirst.c b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/myfirst.c new file mode 100644 index 0000000..325dc94 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/stage4-final/myfirst.c @@ -0,0 +1,760 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 12, Stage 4: the final synchronized driver. + * + * Combines all of Chapter 12: cv channels (Stage 1), bounded reads + * (Stage 2), sx-protected configuration (Stage 3), plus a reset + * sysctl that exercises both lock classes in the canonical order + * (mtx first, sx second). This is the version the chapter's + * regression suite expects to pass. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.6-sync" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + /* Both locks held; canonical order: mtx first, sx second. */ + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); /* room is now available */ + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 12 Stage 4)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch12-synchronization-mechanisms/userland/Makefile b/examples/part-03/ch12-synchronization-mechanisms/userland/Makefile new file mode 100644 index 0000000..d13159a --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/userland/Makefile @@ -0,0 +1,18 @@ +# Makefile for Chapter 12 userland synchronization testers. + +PROGS= timeout_tester config_writer + +.PHONY: all +all: ${PROGS} + +CFLAGS?= -O2 -Wall -Wextra -Wno-unused-parameter + +timeout_tester: timeout_tester.c + ${CC} ${CFLAGS} -o $@ $< + +config_writer: config_writer.c + ${CC} ${CFLAGS} -o $@ $< + +.PHONY: clean +clean: + rm -f ${PROGS} diff --git a/examples/part-03/ch12-synchronization-mechanisms/userland/config_writer.c b/examples/part-03/ch12-synchronization-mechanisms/userland/config_writer.c new file mode 100644 index 0000000..38c74aa --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/userland/config_writer.c @@ -0,0 +1,48 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * config_writer.c: stress the Chapter 12 driver's configuration + * sysctls by toggling debug_level and soft_byte_limit at high + * frequency for a configurable duration. + * + * Usage: + * config_writer [seconds] + * + * Default duration is 30 seconds. Run in parallel with mp_stress + * (from Chapter 11) to verify that data-path I/O and configuration + * updates can coexist without lock-order reversals. + */ + +#include +#include +#include +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + int seconds = (argc > 1) ? atoi(argv[1]) : 30; + time_t end = time(NULL) + seconds; + int v = 0; + int limit; + + while (time(NULL) < end) { + v = (v + 1) % 4; + if (sysctlbyname("dev.myfirst.0.debug_level", + NULL, NULL, &v, sizeof(v)) != 0) + warn("sysctl debug_level"); + + limit = (v == 0) ? 0 : 4096; + if (sysctlbyname("dev.myfirst.0.soft_byte_limit", + NULL, NULL, &limit, sizeof(limit)) != 0) + warn("sysctl soft_byte_limit"); + + usleep(10000); /* 10 ms */ + } + return (0); +} diff --git a/examples/part-03/ch12-synchronization-mechanisms/userland/timeout_tester.c b/examples/part-03/ch12-synchronization-mechanisms/userland/timeout_tester.c new file mode 100644 index 0000000..5331277 --- /dev/null +++ b/examples/part-03/ch12-synchronization-mechanisms/userland/timeout_tester.c @@ -0,0 +1,64 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * timeout_tester.c: verify that the Chapter 12 driver's bounded + * read returns EAGAIN after approximately the configured timeout + * when no data is available. + * + * Usage: + * timeout_tester [timeout_ms] + * + * Sets dev.myfirst.0.read_timeout_ms to the supplied value (default + * 100), opens the device, calls read(2), and prints the elapsed time + * and the resulting errno. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVPATH "/dev/myfirst" + +int +main(int argc, char **argv) +{ + int timeout_ms = 100; + int fd; + char buf[1024]; + struct timeval t0, t1; + ssize_t n; + int saved; + long elapsed_ms; + + if (argc > 1) + timeout_ms = atoi(argv[1]); + + if (sysctlbyname("dev.myfirst.0.read_timeout_ms", + NULL, NULL, &timeout_ms, sizeof(timeout_ms)) != 0) + err(1, "sysctlbyname set read_timeout_ms"); + + fd = open(DEVPATH, O_RDONLY); + if (fd < 0) + err(1, "open %s", DEVPATH); + + gettimeofday(&t0, NULL); + n = read(fd, buf, sizeof(buf)); + gettimeofday(&t1, NULL); + saved = errno; + + elapsed_ms = (t1.tv_sec - t0.tv_sec) * 1000 + + (t1.tv_usec - t0.tv_usec) / 1000; + printf("read returned %zd, errno=%d (%s) after %ld ms\n", + n, saved, strerror(saved), elapsed_ms); + + close(fd); + return (0); +} diff --git a/examples/part-03/ch13-timers-and-delayed-work/LOCKING.md b/examples/part-03/ch13-timers-and-delayed-work/LOCKING.md new file mode 100644 index 0000000..117897c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/LOCKING.md @@ -0,0 +1,163 @@ +# myfirst Locking Strategy + +Chapter 13 driver, version 0.7-timers. + +## Overview + +The driver uses three synchronization primitives plus three callouts: +a sleep mutex (`sc->mtx`) for the data path, an sx lock (`sc->cfg_sx`) +for the configuration subsystem, two condition variables +(`sc->data_cv`, `sc->room_cv`) for blocking reads and writes, and +three callouts (`sc->heartbeat_co`, `sc->watchdog_co`, +`sc->tick_source_co`) for periodic work. Byte counters use +`counter(9)` per-CPU counters. + +## Locks Owned by This Driver + +### sc->mtx (mutex(9), MTX_DEF) + +Protects: +- `sc->cb` (the circular buffer's internal state) +- `sc->open_count`, `sc->active_fhs` +- `sc->is_attached` (writes; reads at handler entry may be unprotected + as an optimization, re-checked after every sleep) +- `sc->heartbeat_interval_ms`, `sc->watchdog_interval_ms`, + `sc->tick_source_interval_ms` (writes via sysctl handlers; reads + inside callout callbacks) +- `sc->watchdog_last_used` (callout callback only) +- `sc->tick_source_byte` (callout callback only) + +### sc->cfg_sx (sx(9)) + +Protects: +- `sc->cfg.debug_level` +- `sc->cfg.soft_byte_limit` +- `sc->cfg.nickname` + +Shared mode: every read of any cfg field. +Exclusive mode: every write of any cfg field. + +### sc->data_cv (cv(9)) + +Wait condition: data is available in the cbuf (`cbuf_used > 0`). +Interlock: `sc->mtx`. +Signalled by: `myfirst_write` and `myfirst_tick_source` after a + successful cbuf write. +Broadcast by: `myfirst_detach`. +Waiters: `myfirst_read` in `myfirst_wait_data`. + +### sc->room_cv (cv(9)) + +Wait condition: room is available in the cbuf (`cbuf_free > 0`). +Interlock: `sc->mtx`. +Signalled by: `myfirst_read` after a successful cbuf read, and by + `myfirst_sysctl_reset` after resetting the cbuf. +Broadcast by: `myfirst_detach`. +Waiters: `myfirst_write` in `myfirst_wait_room`. + +## Callouts Owned by This Driver + +### sc->heartbeat_co (callout(9), MYFIRST_CO_INIT) + +Lock: `sc->mtx`. +Callback: `myfirst_heartbeat`. +Behaviour: periodic; re-arms itself at the end of each firing if + `sc->heartbeat_interval_ms > 0`. +Started by: the heartbeat sysctl handler (transition 0 -> non-zero). +Stopped by: the heartbeat sysctl handler (transition non-zero -> 0) + via `callout_stop`, and by `myfirst_detach` via `callout_drain`. +Lifetime: initialised in attach via `MYFIRST_CO_INIT`; drained in + detach via `MYFIRST_CO_DRAIN`. + +### sc->watchdog_co (callout(9), MYFIRST_CO_INIT) + +Lock: `sc->mtx`. +Callback: `myfirst_watchdog`. +Behaviour: periodic; emits a warning if `cb_used` has not changed + and is non-zero between firings. +Started/stopped: via the watchdog sysctl handler and detach, + parallel to the heartbeat. + +### sc->tick_source_co (callout(9), MYFIRST_CO_INIT) + +Lock: `sc->mtx`. +Callback: `myfirst_tick_source`. +Behaviour: periodic; injects a single byte into the cbuf each firing + if there is room. +Started/stopped: via the tick_source sysctl handler and detach, + parallel to the heartbeat. + +## Callout Discipline + +1. Every callout uses `sc->mtx` as its lock via `callout_init_mtx` + (wrapped in the `MYFIRST_CO_INIT` macro). +2. Every callout callback asserts `MYFIRST_ASSERT(sc)` at entry. +3. Every callout callback checks `!sc->is_attached` at entry and + returns early without re-arming. +4. The detach path clears `sc->is_attached` under `sc->mtx`, + broadcasts both cvs, drops the mutex, and then calls + `callout_drain` on every callout. +5. `callout_stop` is used to cancel pending callouts in normal + driver operation (sysctl handlers); `callout_drain` is used at + detach. +6. NEVER call `selwakeup`, `uiomove`, `copyin`, `copyout`, + `malloc(M_WAITOK)`, or any sleeping primitive from a callout + callback. The mutex is held during the callback, and these calls + would violate the sleep-with-mutex rule. The tick source omits + `selwakeup` for exactly this reason. + +## Lock-Free Fields + +- `sc->bytes_read`, `sc->bytes_written`: `counter_u64_t`. Updates + via `counter_u64_add`; reads via `counter_u64_fetch`. +- `sc->read_timeout_ms`, `sc->write_timeout_ms`: plain ints, + accessed without locking. Safe because aligned int reads and writes + are atomic, and the values are advisory. + +## Lock Order + +``` +sc->mtx -> sc->cfg_sx +``` + +A thread holding `sc->mtx` may acquire `sc->cfg_sx` in either mode. +A thread holding `sc->cfg_sx` may NOT acquire `sc->mtx`. + +The callouts run with `sc->mtx` already held by the kernel; their +callbacks must respect this rule when accessing config (which is +fine, since they would acquire `sc->cfg_sx` second). + +## Locking Discipline (Recap) + +1. Acquire mutex with `MYFIRST_LOCK(sc)`, release with + `MYFIRST_UNLOCK(sc)`. +2. Acquire sx in shared mode with `MYFIRST_CFG_SLOCK(sc)`, exclusive + with `MYFIRST_CFG_XLOCK(sc)`. Release with the matching unlock. +3. Wait on a cv with `cv_wait_sig` (interruptible) or + `cv_timedwait_sig` (interruptible + bounded). +4. Signal a cv with `cv_signal` (one waiter) or `cv_broadcast` (all + waiters). +5. NEVER hold `sc->mtx` across `uiomove(9)`, `copyin(9)`, + `copyout(9)`, `selwakeup(9)`, or any potentially-sleeping call. + `cv_wait_sig` is the exception (it atomically drops the + interlock). +6. NEVER hold `sc->cfg_sx` across `uiomove(9)`, `sysctl_handle_*`, + or any other potentially-sleeping call. +7. The detach path clears `sc->is_attached` under `sc->mtx`, + broadcasts both cvs, drains all callouts, then destroys + primitives in reverse order. + +## History + +- 0.7-timers (Chapter 13): added heartbeat, watchdog, and tick-source + callouts; documented callout discipline; standardised callout + detach pattern via `MYFIRST_CO_INIT` and `MYFIRST_CO_DRAIN` macros. +- 0.6-sync (Chapter 12, Stage 4): combined version with cv channels, + bounded reads, sx-protected configuration, reset sysctl. +- 0.5-kasserts (Chapter 11, Stage 5): KASSERT calls added throughout + cbuf helpers and wait helpers. +- 0.5-counter9 (Chapter 11, Stage 3): byte counters migrated to + counter(9). +- 0.5-concurrency (Chapter 11, Stage 2): MYFIRST_LOCK/UNLOCK/ASSERT + macros, explicit locking strategy. +- Earlier versions: see Chapter 10 / Chapter 11 history. diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/Makefile b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/Makefile new file mode 100644 index 0000000..92bce33 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/Makefile @@ -0,0 +1,11 @@ +# Makefile for the Chapter 13 Stage 1 myfirst driver. +# +# Adds the heartbeat callout to the Chapter 12 Stage 4 driver. +# Stage 2 will add the watchdog; Stage 3 will add the tick source; +# Stage 4 is the integrated final driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.c b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.h b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/myfirst.c b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/myfirst.c new file mode 100644 index 0000000..75986b5 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage1-heartbeat/myfirst.c @@ -0,0 +1,850 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 13, Stage 1: heartbeat callout only. + * + * Builds on Chapter 12 Stage 4 by adding one callout: + * - heartbeat_co: periodic logging of cbuf usage and byte counts. + * + * The callout uses sc->mtx as its lock (via callout_init_mtx) and + * is drained at detach via callout_drain. The sysctl + * heartbeat_interval_ms enables, disables, and configures the firing + * interval. The default is 0 (disabled), preserving the Chapter 12 + * default behaviour for users who do not opt in. + * + * Stage 2 will add the watchdog callout. Stage 3 will add the tick + * source. Stage 4 is the integrated final driver with the standard + * macro vocabulary and the seven-phase detach pattern. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.7-heartbeat" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + /* Chapter 13 Stage 1: heartbeat callout. */ + struct callout heartbeat_co; + int heartbeat_interval_ms; /* 0 = disabled */ + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +/* + * Chapter 13: callout callbacks. Each runs with sc->mtx held (the + * kernel acquires it via callout_init_mtx). Each must check + * is_attached at the top and exit without re-arming if false. + */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +/* Sysctl handler for the heartbeat interval (Stage 1). */ + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, + myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + /* Both locks held; canonical order: mtx first, sx second. */ + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); /* room is now available */ + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 13 Stage 1)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 13 Stage 1: heartbeat callout. */ + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + /* Chapter 13 Stage 1: heartbeat sysctl. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Chapter 13 Stage 1: drain the heartbeat callout. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/Makefile b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/Makefile new file mode 100644 index 0000000..1452cdb --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 13 Stage 2 myfirst driver. +# +# Adds the watchdog callout on top of Stage 1's heartbeat. Stage 3 +# will add the tick source; Stage 4 is the integrated final driver. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.c b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.h b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/myfirst.c b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/myfirst.c new file mode 100644 index 0000000..763c231 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage2-watchdog/myfirst.c @@ -0,0 +1,917 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 13, Stage 2: heartbeat + watchdog callouts. + * + * Builds on Stage 1 by adding the watchdog callout: + * - heartbeat_co: periodic logging of cbuf usage and byte counts. + * - watchdog_co: periodic detection of stalled buffer drainage. + * + * Each callout uses sc->mtx as its lock (via callout_init_mtx) and + * is drained at detach via callout_drain. Each has a sysctl + * (heartbeat_interval_ms, watchdog_interval_ms) that enables, + * disables, and configures the firing interval. The default for + * each interval is 0 (disabled). + * + * Stage 3 will add the tick source callout. Stage 4 is the + * integrated final driver with the standard macro vocabulary and + * the seven-phase detach pattern. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.7-watchdog" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + /* Chapter 13 Stage 2: heartbeat + watchdog callouts. */ + struct callout heartbeat_co; + int heartbeat_interval_ms; /* 0 = disabled */ + struct callout watchdog_co; + int watchdog_interval_ms; /* 0 = disabled */ + size_t watchdog_last_used; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +/* + * Chapter 13: callout callbacks. Each runs with sc->mtx held (the + * kernel acquires it via callout_init_mtx). Each must check + * is_attached at the top and exit without re-arming if false. + */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +/* Sysctl handlers for the heartbeat and watchdog intervals. */ + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, + myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, + myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + /* Both locks held; canonical order: mtx first, sx second. */ + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); /* room is now available */ + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 13 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 13 Stage 2: heartbeat + watchdog callouts. */ + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + /* Chapter 13: callout interval sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Chapter 13 Stage 2: drain heartbeat + watchdog callouts. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/Makefile b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/Makefile new file mode 100644 index 0000000..80c2710 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/Makefile @@ -0,0 +1,11 @@ +# Makefile for the Chapter 13 Stage 3 myfirst driver. +# +# Adds the tick source callout on top of Stage 2's heartbeat + +# watchdog. Stage 4 is the integrated final driver with the standard +# macro vocabulary and the seven-phase detach pattern documented. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.c b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.h b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/myfirst.c b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/myfirst.c new file mode 100644 index 0000000..c52328c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage3-tick-source/myfirst.c @@ -0,0 +1,986 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 13, Stage 3: heartbeat + watchdog + tick source. + * + * Builds on Stage 2 by adding the tick source callout: + * - heartbeat_co: periodic logging of cbuf usage and byte counts. + * - watchdog_co: periodic detection of stalled buffer drainage. + * - tick_source_co: periodic injection of synthetic bytes. + * + * Each callout uses sc->mtx as its lock (via callout_init_mtx) and + * is drained at detach via callout_drain. Each has a sysctl + * (heartbeat_interval_ms, watchdog_interval_ms, + * tick_source_interval_ms) that enables, disables, and configures + * the firing interval. The default for each is 0 (disabled). + * + * Stage 4 is the integrated final driver with the standard macro + * vocabulary and the seven-phase detach pattern documented in + * comments. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.7-tick-source" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + /* Chapter 13: callouts and their tunables. */ + struct callout heartbeat_co; + int heartbeat_interval_ms; /* 0 = disabled */ + struct callout watchdog_co; + int watchdog_interval_ms; /* 0 = disabled */ + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; /* 0 = disabled */ + char tick_source_byte; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +/* + * Chapter 13: callout callbacks. Each runs with sc->mtx held (the + * kernel acquires it via callout_init_mtx). Each must check + * is_attached at the top and exit without re-arming if false. + */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + /* selwakeup omitted: cannot be called from a + * callout callback while sc->mtx is held. */ + } + } + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for the three timer intervals. */ + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, + myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, + myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, + myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + /* Both locks held; canonical order: mtx first, sx second. */ + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); /* room is now available */ + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 13 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 13: callouts. */ + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + /* Chapter 13: callout interval sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Chapter 13: drain every callout. No lock held; safe to sleep. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage4-final/Makefile b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/Makefile new file mode 100644 index 0000000..c21a458 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/Makefile @@ -0,0 +1,13 @@ +# Makefile for the Chapter 13 Stage 4 (final) myfirst driver. +# +# Combines all of Chapter 12 Stage 4 (cv channels, bounded reads, +# sx-protected configuration, reset sysctl) with Chapter 13's three +# callouts (heartbeat, watchdog, tick source). This is the canonical +# integrated driver with the standard macro vocabulary and the +# seven-phase detach pattern documented in comments. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.c b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.h b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch13-timers-and-delayed-work/stage4-final/myfirst.c b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/myfirst.c new file mode 100644 index 0000000..ef0758a --- /dev/null +++ b/examples/part-03/ch13-timers-and-delayed-work/stage4-final/myfirst.c @@ -0,0 +1,983 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 13, Stage 4: the final timer-enhanced driver. + * + * Builds on Chapter 12 Stage 4 by adding three callouts: + * - heartbeat_co: periodic logging of cbuf usage and byte counts. + * - watchdog_co: periodic detection of stalled buffer drainage. + * - tick_source_co: periodic injection of synthetic bytes. + * + * Each callout uses sc->mtx as its lock (via callout_init_mtx) and + * is drained at detach via callout_drain. Each has a sysctl + * (heartbeat_interval_ms, watchdog_interval_ms, tick_source_interval_ms) + * that enables, disables, and configures the firing interval. + * The default for each interval is 0 (disabled), preserving the + * Chapter 12 default behaviour for users who do not opt in. + * + * Locking strategy. + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Locking discipline (unchanged from Chapter 11 except for cvs): + * - mtx is acquired with mtx_lock and released with mtx_unlock. + * - cv_wait_sig(&cv, &sc->mtx) is used to block; the cv is the + * named replacement for the old &sc->cb channel. + * - cv_signal wakes one waiter when state changes per-event. + * - cv_broadcast wakes all waiters at detach. + * - The mutex is NEVER held across uiomove(9), copyin(9), or copyout(9). + * - The mutex is held when calling cbuf_*() helpers; the cbuf module + * is intentionally lock-free by itself and relies on the caller. + * - selwakeup(9), cv_signal(9), and cv_broadcast(9) are called with + * the mutex DROPPED, after the state change that warrants the wake. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.7-timers" + +/* + * Locking abstraction. One point of indirection around the mutex. + */ +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; /* 0-3 */ + int soft_byte_limit; /* 0 = no limit */ + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; /* 0 = no timeout */ + int write_timeout_ms; /* 0 = no timeout */ + + /* Chapter 13: callouts and their tunables. */ + struct callout heartbeat_co; + int heartbeat_interval_ms; /* 0 = disabled */ + struct callout watchdog_co; + int watchdog_interval_ms; /* 0 = disabled */ + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; /* 0 = disabled */ + char tick_source_byte; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +/* Configuration accessors. Each takes sc->cfg_sx briefly. */ +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +/* Helpers, all called with sc->mtx held. */ +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +/* + * Chapter 13: callout callbacks. Each runs with sc->mtx held (the + * kernel acquires it via callout_init_mtx). Each must check + * is_attached at the top and exit without re-arming if false. + */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + /* selwakeup omitted: cannot be called from a + * callout callback while sc->mtx is held. */ + } + } + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for the three timer intervals. */ + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, + myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, + myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, + myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + /* Both locks held; canonical order: mtx first, sx second. */ + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); /* room is now available */ + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 13 Stage 4)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 13: callouts. */ + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + /* Chapter 13: callout interval sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Chapter 13: drain every callout. No lock held; safe to sleep. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/LOCKING.md b/examples/part-03/ch14-taskqueues-and-deferred-work/LOCKING.md new file mode 100644 index 0000000..e51c1b5 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/LOCKING.md @@ -0,0 +1,115 @@ +# LOCKING.md — Chapter 14 Stage 4 (`myfirst` v0.8-taskqueues) + +Extension of the Chapter 13 `LOCKING.md`. Adds a Tasks section and an +updated Detach Ordering section reflecting the Chapter 14 changes. + +## Primitives Owned by the Driver + +| Primitive | Kind | Member | Purpose | +|---|---|---|---| +| `sc->mtx` | `struct mtx` (MTX_DEF) | data-path mutex | Protects `sc->cb`, `sc->open_count`, `sc->active_fhs`, `sc->is_attached`, task-related counters. | +| `sc->data_cv` | `struct cv` | on `sc->mtx` | Signals readers when bytes arrive. | +| `sc->room_cv` | `struct cv` | on `sc->mtx` | Signals writers when room appears. | +| `sc->cfg_sx` | `struct sx` | configuration lock | Protects `sc->cfg`. | +| `sc->heartbeat_co` | `struct callout` | periodic | Logs stats. Lock: `sc->mtx`. | +| `sc->watchdog_co` | `struct callout` | periodic | Detects stalled drainage. Lock: `sc->mtx`. | +| `sc->tick_source_co` | `struct callout` | periodic | Injects synthetic bytes. Lock: `sc->mtx`. | +| `sc->tq` | `struct taskqueue *` | private | One worker thread at `PWAIT`. Owns every task below. | +| `sc->selwake_task` | `struct task` | plain | Runs `selwakeup(&sc->rsel)` in thread context. | +| `sc->bulk_writer_task` | `struct task` | plain | Writes a fixed batch of bytes per firing. | +| `sc->reset_delayed_task` | `struct timeout_task` | scheduled | Delayed reset in thread context. | + +## Tasks + +### `selwake_task` (plain) + +- Callback: `myfirst_selwake_task`. +- Enqueued from: `myfirst_tick_source` (callout callback) when a byte + was written. +- Cancelled by: nothing. Enqueue is unconditional when work is done. +- Drained at detach: yes, after callouts are drained and before + `seldrain`. +- Locks acquired in callback: `sc->mtx` briefly, only when the + coalescing counter needs updating. `selwakeup(&sc->rsel)` is called + with no driver lock held. + +### `bulk_writer_task` (plain) + +- Callback: `myfirst_bulk_writer_task`. +- Enqueued from: `myfirst_sysctl_bulk_writer_flood` (the sysctl + handler, in syscall context). +- Cancelled by: nothing. +- Drained at detach: yes. +- Locks acquired in callback: `sc->mtx` twice: once to read + `sc->bulk_writer_batch`, once to write to the cbuf and signal + `data_cv`. `selwakeup(&sc->rsel)` is called with no lock held. + +### `reset_delayed_task` (timeout_task) + +- Callback: `myfirst_reset_delayed_task`. +- Armed by: `myfirst_sysctl_reset_delayed` with a non-zero millisecond + value. +- Cancelled by: `myfirst_sysctl_reset_delayed` with a zero value. +- Drained at detach: yes, via `taskqueue_drain_timeout`. +- Locks acquired in callback: `sc->mtx` and `sc->cfg_sx` in the + canonical order (mtx first, sx second). +- `cv_broadcast(&sc->room_cv)` is called with no lock held. + +## Detach Ordering + +The detach sequence is: + +1. Refuse detach if `sc->active_fhs > 0` (`EBUSY`). +2. Clear `sc->is_attached` under `sc->mtx`. +3. `cv_broadcast(&sc->data_cv)`; `cv_broadcast(&sc->room_cv)`. +4. Release `sc->mtx`. +5. `callout_drain(&sc->heartbeat_co)`, + `callout_drain(&sc->watchdog_co)`, + `callout_drain(&sc->tick_source_co)`. +6. `taskqueue_drain(sc->tq, &sc->selwake_task)`, + `taskqueue_drain(sc->tq, &sc->bulk_writer_task)`, + `taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task)`. +7. `seldrain(&sc->rsel)`, `seldrain(&sc->wsel)`. +8. `taskqueue_free(sc->tq); sc->tq = NULL`. +9. Destroy cdev and cdev alias. +10. `sysctl_ctx_free(&sc->sysctl_ctx)`. +11. `cbuf_destroy(&sc->cb)`, free `bytes_read`/`bytes_written` + counters. +12. `cv_destroy(&sc->data_cv)`, `cv_destroy(&sc->room_cv)`. +13. `sx_destroy(&sc->cfg_sx)`. +14. `mtx_destroy(&sc->mtx)`. + +Why the order matters: + +- Step 2 prevents callouts from re-arming after they fire. +- Step 5 guarantees no callout callback is in flight, so no new tasks + can be enqueued from callouts. +- Step 6 guarantees no task callback is running. Safe to do only + after Step 5 because callouts are enqueue producers. +- Step 7 guarantees no `selwakeup` is in progress. Safe to do only + after Step 6 because tasks are `selwakeup` callers. +- Step 8 frees the taskqueue. Safe because every task has been + drained. +- Steps 9-14 unwind the rest of the softc in the reverse order of + attach. + +Violating the order risks use-after-free in task callbacks or +`selwakeup` on a drained selinfo. + +## Lock Order + +The driver's documented lock order, unchanged from Chapter 13: + +```text +sc->mtx -> sc->cfg_sx +``` + +`WITNESS` enforces this order at runtime. Task callbacks obey it +exactly like any other thread-context code. + +The taskqueue's internal `tq_mutex` is not ordered against `sc->mtx`; +taking one does not restrict the other. A task callback may acquire +`sc->mtx`; a sysctl handler may call `taskqueue_enqueue` while holding +`sc->mtx` (as the `bulk_writer_flood` handler does). `WITNESS` +accepts both because the two locks are never held in conflicting +orders by the same thread. diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/labs/Makefile b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/Makefile new file mode 100644 index 0000000..db0d1fb --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/Makefile @@ -0,0 +1,14 @@ +# Makefile for the Chapter 14 lab helpers. + +CFLAGS?= -Wall -Wextra -O2 +PROGS= poll_waiter + +all: $(PROGS) + +poll_waiter: poll_waiter.c + $(CC) $(CFLAGS) -o $@ $< + +clean: + rm -f $(PROGS) + +.PHONY: all clean diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/labs/coalesce-stress.sh b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/coalesce-stress.sh new file mode 100755 index 0000000..83636a8 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/coalesce-stress.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# +# coalesce-stress.sh: Lab 2 companion script. +# +# Drives the Stage 4 driver hard enough to trigger task coalescing, +# then reports the selwake_pending_drops counter. Assumes the driver +# is loaded and instance 0 exists. + +set -u + +DEV=dev.myfirst.0 + +echo "Baseline selwake_pending_drops: $(sysctl -n $DEV.stats.selwake_pending_drops 2>/dev/null || echo 0)" + +echo "Enabling tick_source at 1 ms..." +sysctl $DEV.tick_source_interval_ms=1 >/dev/null + +echo "Running 20 bulk_writer floods of 1000 enqueues each..." +sysctl $DEV.bulk_writer_batch=32 >/dev/null +for i in $(jot 20 1); do + sysctl $DEV.bulk_writer_flood=1000 >/dev/null +done + +sleep 2 + +echo "Final selwake_pending_drops: $(sysctl -n $DEV.stats.selwake_pending_drops)" + +echo "Stopping tick_source..." +sysctl $DEV.tick_source_interval_ms=0 >/dev/null +sysctl $DEV.bulk_writer_batch=0 >/dev/null + +echo +echo "bytes_read: $(sysctl -n $DEV.stats.bytes_read)" +echo "bytes_written: $(sysctl -n $DEV.stats.bytes_written)" diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/labs/observe-taskqueue.sh b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/observe-taskqueue.sh new file mode 100755 index 0000000..6aa2dfd --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/observe-taskqueue.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# +# observe-taskqueue.sh: Lab 1 companion script. +# +# Lists every taskqueue thread on the system, highlights the myfirst +# one, and samples procstat -t for a few seconds to show state +# transitions as the driver's tasks fire. + +set -u + +echo "=== Taskqueue threads currently on the system ===" +procstat -t 0 2>/dev/null | awk '/taskq/ { print }' || \ + ps ax | awk '/taskq/ { print }' + +echo +echo "=== Watching 'myfirst.*taskq' for 10 seconds ===" +echo "(Tip: in another terminal, run" +echo " sysctl dev.myfirst.0.tick_source_interval_ms=100" +echo " to see the thread oscillate between sleep and run.)" +echo + +for i in 1 2 3 4 5 6 7 8 9 10; do + procstat -t 0 2>/dev/null | grep 'myfirst.*taskq' || \ + ps ax | grep '\[myfirst.*taskq\]' | grep -v grep + sleep 1 +done diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/labs/poll_waiter.c b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/poll_waiter.c new file mode 100644 index 0000000..2466e9f --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/labs/poll_waiter.c @@ -0,0 +1,65 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * poll_waiter.c: a trivial poll(2) client for /dev/myfirst. + * + * Compile with: + * cc -Wall -Wextra -o poll_waiter poll_waiter.c + * + * Usage: + * ./poll_waiter -> prints every byte the driver delivers. + * ./poll_waiter > /dev/null -> drains silently (for stress tests). + * + * Used in Chapter 14 Lab 1 and Lab 2 to verify that selwakeup(9) is + * correctly delivered from the driver's task callback. + */ + +#include +#include +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + int fd, n; + struct pollfd pfd; + char c; + + (void)argc; + (void)argv; + + fd = open("/dev/myfirst", O_RDONLY); + if (fd < 0) + err(1, "open /dev/myfirst"); + + pfd.fd = fd; + pfd.events = POLLIN; + + for (;;) { + n = poll(&pfd, 1, -1); + if (n < 0) { + if (errno == EINTR) + continue; + err(1, "poll"); + } + if (pfd.revents & POLLIN) { + n = read(fd, &c, 1); + if (n == 0) + break; + if (n < 0) { + if (errno == EINTR) + continue; + err(1, "read"); + } + (void)write(STDOUT_FILENO, &c, 1); + } + } + + (void)close(fd); + return (0); +} diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/Makefile b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.h b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/myfirst.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/myfirst.c new file mode 100644 index 0000000..a397a98 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage1-first-task/myfirst.c @@ -0,0 +1,740 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 14, Stage 1: the first task. + * + * Starts from Chapter 13 Stage 4 and adds one task, enqueued from the + * tick_source callout callback so that selwakeup() runs in thread + * context. The task uses the shared taskqueue_thread; Stage 2 moves + * it to a private taskqueue. + * + * The detach ordering adds one drain step (taskqueue_drain after the + * callouts are drained and before seldrain). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.8-taskqueues-stage1" + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14 Stage 1: one task on the shared taskqueue_thread. */ + struct task selwake_task; + int selwake_pending_drops; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + got = cbuf_read(&sc->cb, dst, n); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + put = cbuf_write(&sc->cb, src, n); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* Chapter 14 Stage 1: the selwake task. */ +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14 Stage 1: defer selwakeup via the shared taskqueue. */ + if (wake_sel) + taskqueue_enqueue(taskqueue_thread, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 14 Stage 1)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_mtx; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst)\n", + MYFIRST_VERSION, devtoname(sc->cdev)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_mtx: + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Callouts first, then task, then seldrain. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + taskqueue_drain(taskqueue_thread, &sc->selwake_task); + + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + if (sc->cdev_alias != NULL) + destroy_dev(sc->cdev_alias); + if (sc->cdev != NULL) + destroy_dev(sc->cdev); + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/Makefile b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.h b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/myfirst.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/myfirst.c new file mode 100644 index 0000000..907cbea --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage2-private-taskqueue/myfirst.c @@ -0,0 +1,1035 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 14, Stage 2: the private taskqueue. + * + * Builds on Chapter 14 Stage 1 by creating a private taskqueue + * (sc->tq) serviced by one worker thread at PWAIT. Only selwake_task + * lives here; Stage 3 adds coalescing demonstrations and Stage 4 adds + * the delayed-reset timeout task. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain selwake_task. + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.8-taskqueues-stage2" + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14 Stage 2: private taskqueue and one task. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 14 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sx; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14 Stage 2: initialise the task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/Makefile b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.h b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/myfirst.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/myfirst.c new file mode 100644 index 0000000..1666c56 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage3-coalescing/myfirst.c @@ -0,0 +1,1198 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 14, Stage 3: deliberate coalescing and a delayed reset. + * + * Builds on Stage 2 by adding bulk_writer_task (to demonstrate + * deliberate coalescing via the ta_pending rule) and + * reset_delayed_task (a timeout_task that fires in thread context). + * Stage 4 is this same driver with consolidated documentation and the + * final version string. + * + * The driver owns a private taskqueue and the following tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.8-taskqueues-stage3" +#define MYFIRST_BULK_MAX 64 + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 14 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sx; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/Makefile b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.h b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/myfirst.c b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/myfirst.c new file mode 100644 index 0000000..62db7c1 --- /dev/null +++ b/examples/part-03/ch14-taskqueues-and-deferred-work/stage4-final/myfirst.c @@ -0,0 +1,1193 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 14, Stage 4: the final taskqueue-enhanced driver. + * + * Builds on Chapter 13 Stage 4 by adding a private taskqueue and three + * tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.8-taskqueues" +#define MYFIRST_BULK_MAX 64 + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + return (error); + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 14 Stage 4)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sx; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sx: + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch15-more-synchronization/LOCKING.md b/examples/part-03/ch15-more-synchronization/LOCKING.md new file mode 100644 index 0000000..1da2b89 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/LOCKING.md @@ -0,0 +1,159 @@ +# LOCKING.md — Chapter 15 Stage 4 (`myfirst` v0.9-coordination) + +Extension of the Chapter 14 `LOCKING.md`. Adds Semaphores, Stats +Cache, Coordination, and updated Detach Ordering sections. + +## Primitives Owned by the Driver + +| Primitive | Kind | Member | Purpose | +|---|---|---|---| +| `sc->mtx` | `struct mtx` (MTX_DEF) | data-path mutex | Protects `sc->cb`, `open_count`, `active_fhs`, counters, state flags. | +| `sc->data_cv` | `struct cv` | on `sc->mtx` | Signals readers when bytes arrive. | +| `sc->room_cv` | `struct cv` | on `sc->mtx` | Signals writers when room appears. | +| `sc->cfg_sx` | `struct sx` | configuration | Protects `sc->cfg`. | +| `sc->stats_cache_sx` | `struct sx` | stats cache | Protects cached bytes_written_10s. | +| `sc->writers_sema` | `struct sema` | writer admission | Caps concurrent writers at `writers_limit`. | +| `sc->heartbeat_co` | `struct callout` | periodic | Heartbeat log. Lock: `sc->mtx`. | +| `sc->watchdog_co` | `struct callout` | periodic | Stall detection. Enqueues `recovery_task` on stall. Lock: `sc->mtx`. | +| `sc->tick_source_co` | `struct callout` | periodic | Synthetic byte injection. Lock: `sc->mtx`. | +| `sc->tq` | `struct taskqueue *` | private | Private taskqueue. Owns every task below. | +| `sc->selwake_task` | `struct task` | plain | Deferred `selwakeup`. | +| `sc->bulk_writer_task` | `struct task` | plain | Fixed-batch writes. | +| `sc->reset_delayed_task` | `struct timeout_task` | scheduled | Delayed reset. | +| `sc->recovery_task` | `struct task` | plain | Stall recovery. Coordinated via `recovery_in_progress`. | +| `sc->is_attached` | atomic int | lifecycle flag | `atomic_load_acq_int` on reads; `atomic_store_rel_int` on writes. | +| `sc->recovery_in_progress` | int under `sc->mtx` | state flag | "At most one recovery" invariant. | + +## Semaphores + +### `writers_sema` + +- Initial value: `writers_limit` (default 4; tunable 1-64). +- Drained by: writers on entry via `myfirst_sync_writer_enter`. +- Posted by: writers on exit via `myfirst_sync_writer_leave`; also + by the detach path to wake any blocked waiters (they then see + `is_attached=0` and return ENXIO). +- Not signal-interruptible (uses `cv_wait` internally). Users + expecting SIGINT on blocked writes should set a short writer + timeout or use `O_NONBLOCK`. +- Destroyed in detach after every task is drained and every + potential waiter has been woken. + +### Raising/Lowering the Limit + +- Raising posts additional slots immediately. +- Lowering is best-effort: the new lower limit takes effect as new + writers enter and the counter drains below the new cap. + +### Sema Drain Discipline (writers_inflight) + +`sc->writers_inflight` is an atomic int that counts threads currently +somewhere between `myfirst_sync_writer_enter` and +`myfirst_sync_writer_leave`. Detach waits for this counter to reach +zero before calling `sema_destroy`. + +Why: `sema_destroy` calls `mtx_destroy` on the internal +`sema_mtx`. A woken waiter returning from `cv_wait` still holds that +mutex briefly (for `sema_waiters--` and the final unlock). Racing +`mtx_destroy` against that unlock is a use-after-free. The drain +counter closes the race. + +Pattern: + +- `myfirst_sync_writer_enter`: + 1. `atomic_add_int(&writers_inflight, 1)`. + 2. Check `is_attached`; if zero, decrement and return ENXIO. + 3. `sema_wait` (or `sema_trywait` for NDELAY). + 4. Check `is_attached` again after wake; if zero, `sema_post`, + decrement, return ENXIO. +- `myfirst_sync_writer_leave`: + 1. `sema_post(&writers_sema)`. + 2. `atomic_subtract_int(&writers_inflight, 1)`. +- Detach, in order: + 1. `atomic_store_rel_int(&is_attached, 0)`. + 2. Post `writers_limit` wake-up slots to `writers_sema`. + 3. `while (atomic_load_acq_int(&writers_inflight) > 0) pause("myfwrd", 1);`. + 4. Drain callouts and tasks. + 5. `sema_destroy(&writers_sema)`. + +## Stats Cache + +### `stats_cache_sx` + +- Shared (read) mode: readers of the cached stat. +- Exclusive (write) mode: refreshing the cache. +- Upgrade pattern: `sx_try_upgrade` fast path; `sx_sunlock` + + `sx_xlock` + re-check fallback; always ends with `sx_downgrade` + back to shared before final `sx_sunlock`. +- Refresh frequency: at most once per `MYFIRST_CACHE_STALE_HZ * hz` + ticks (1 second by default). + +## Coordination + +### Atomic `is_attached` + +- Written only once during the life of the softc (0 → 1 on attach, + 1 → 0 on detach or attach failure). +- Read from every context: handlers via + `myfirst_sync_is_attached`, callback callbacks via the same. +- Memory ordering: `atomic_store_rel_int` on writes ensures + preceding state changes are visible before the flag becomes 0; + `atomic_load_acq_int` on reads ensures subsequent reads see + post-flag state. + +### `recovery_in_progress` + +- Set by: `myfirst_watchdog` (callout callback, under `sc->mtx`). +- Cleared by: `myfirst_recovery_task` (task callback, under + `sc->mtx`). +- Invariant: at most one recovery task pending or running at a + time. +- Accounting: `recovery_task_runs` counts invocations. + +## Lock Order + +The documented lock order is: + +```text +sc->mtx -> sc->cfg_sx -> sc->stats_cache_sx +``` + +`WITNESS` enforces this order. The `writers_sema`'s internal mutex +is not in the graph because the driver never holds `sc->mtx` (or +any other driver lock) across a `sema_wait`/`sema_post`. + +## Detach Ordering + +1. Refuse detach if `active_fhs > 0` (EBUSY). +2. Under `sc->mtx`: `atomic_store_rel_int(&sc->is_attached, 0)`; + `cv_broadcast` both cvs. +3. Release `sc->mtx`. +4. Post `writers_limit` slots to `writers_sema` to wake any + blocked waiters (they return ENXIO). +5. Wait for `writers_inflight == 0` + (`myfirst_sync_writers_drain`). +6. `callout_drain` the three callouts. +7. `taskqueue_drain` every task: selwake, bulk_writer, + reset_delayed (timeout variant), recovery. +8. `seldrain` rsel and wsel. +9. `taskqueue_free(sc->tq)`; `sc->tq = NULL`. +10. `sema_destroy(&sc->writers_sema)` (safe: writers_inflight is 0). +11. Destroy cdev and cdev alias. +12. `sysctl_ctx_free`. +13. `cbuf_destroy`, free counters. +14. `sx_destroy(&sc->stats_cache_sx)`. +15. `cv_destroy` twice. +16. `sx_destroy(&sc->cfg_sx)`. +17. `mtx_destroy(&sc->mtx)`. + +## Summary of Discipline + +- Every primitive has a named wrapper in `myfirst_sync.h`. +- Every mutex-held critical section is short and never includes + sleepable calls. +- Every cv wait in a syscall context uses the signal-aware variant + with explicit EINTR/ERESTART handling and a partial-progress + sentinel. +- Every sema-draining context holds no driver lock during the wait. +- Every destroy happens after every possible user of the primitive + has been quiesced. diff --git a/examples/part-03/ch15-more-synchronization/labs/Makefile b/examples/part-03/ch15-more-synchronization/labs/Makefile new file mode 100644 index 0000000..8b46a80 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/labs/Makefile @@ -0,0 +1,17 @@ +# Makefile for Chapter 15 lab helpers. + +CFLAGS?= -Wall -Wextra -O2 +PROGS= writer_cap_test signal_read + +all: $(PROGS) + +writer_cap_test: writer_cap_test.c + $(CC) $(CFLAGS) -o $@ $< + +signal_read: signal_read.c + $(CC) $(CFLAGS) -o $@ $< + +clean: + rm -f $(PROGS) + +.PHONY: all clean diff --git a/examples/part-03/ch15-more-synchronization/labs/signal_read.c b/examples/part-03/ch15-more-synchronization/labs/signal_read.c new file mode 100644 index 0000000..0d86bba --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/labs/signal_read.c @@ -0,0 +1,71 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * signal_read: start a blocking read on /dev/myfirst, receive a + * signal after a delay, report how many bytes were delivered before + * the signal interrupted the read. + * + * Used in Chapter 15 Lab 3 to confirm the partial-progress + * convention. + * + * Compile: + * cc -Wall -Wextra -o signal_read signal_read.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t got_sig = 0; + +static void +on_sig(int sig) +{ + (void)sig; + got_sig = 1; +} + +int +main(int argc, char **argv) +{ + int fd; + char buf[4096]; + ssize_t n; + struct sigaction sa; + + (void)argc; + (void)argv; + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_sig; + sigaction(SIGINT, &sa, NULL); + + fd = open("/dev/myfirst", O_RDONLY); + if (fd < 0) + err(1, "open"); + + fprintf(stderr, "reading up to %zu bytes; send SIGINT with kill -INT %d\n", + sizeof(buf), getpid()); + + n = read(fd, buf, sizeof(buf)); + if (n < 0) { + if (errno == EINTR) + fprintf(stderr, "read returned EINTR, 0 bytes\n"); + else + err(1, "read"); + } else { + fprintf(stderr, "read returned %zd bytes (got_sig=%d)\n", + n, (int)got_sig); + } + + close(fd); + return (0); +} diff --git a/examples/part-03/ch15-more-synchronization/labs/stress_all.sh b/examples/part-03/ch15-more-synchronization/labs/stress_all.sh new file mode 100755 index 0000000..65a0cc9 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/labs/stress_all.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# +# stress_all.sh: the Chapter 15 Lab 4 stress kit. +# +# Runs every Part 3 primitive simultaneously: writers, readers, tick +# source, heartbeat, watchdog, bulk_writer floods, writers_limit +# adjustments, and stats-cache reads. Used to stress-test detach +# under maximum load. +# +# Usage: +# ./stress_all.sh [run_seconds] +# Defaults to 30 seconds. + +DURATION=${1:-30} +DEV=dev.myfirst.0 + +echo "Enabling Chapter 13/14 primitives..." +sysctl $DEV.tick_source_interval_ms=1 >/dev/null +sysctl $DEV.heartbeat_interval_ms=100 >/dev/null +sysctl $DEV.watchdog_interval_ms=1000 >/dev/null + +# Background writers. +./writer_cap_test 8 128 200 & +WRITERS=$! + +# Background readers. +for i in 1 2 3 4; do + (cat /dev/myfirst >/dev/null 2>&1) & +done + +# Bulk_writer flood every 100ms. +(while :; do + sysctl $DEV.bulk_writer_batch=32 >/dev/null + sysctl $DEV.bulk_writer_flood=1000 >/dev/null + sleep 0.1 +done) & +FLOODER=$! + +# Limit adjustment every 500ms. +(while :; do + for lim in 1 2 4 8; do + sysctl $DEV.writers_limit=$lim >/dev/null + sleep 0.5 + done +done) & +ADJUSTER=$! + +# Stats cache reads. +(while :; do + sysctl -n $DEV.stats.bytes_written_10s >/dev/null +done) & +READER=$! + +echo "Stress running for $DURATION seconds..." +sleep "$DURATION" + +echo "Stopping stressors..." +kill $WRITERS $FLOODER $ADJUSTER $READER 2>/dev/null +wait 2>/dev/null + +echo "Stress ended. Driver stats:" +sysctl $DEV.stats diff --git a/examples/part-03/ch15-more-synchronization/labs/writer_cap_test.c b/examples/part-03/ch15-more-synchronization/labs/writer_cap_test.c new file mode 100644 index 0000000..fc174be --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/labs/writer_cap_test.c @@ -0,0 +1,66 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * writer_cap_test: start N concurrent writers that open /dev/myfirst + * and write a short burst. Used to stress the writer-cap semaphore + * introduced in Chapter 15 Stage 1. + * + * Usage: + * ./writer_cap_test [num_writers] [bytes_per_write] [writes_per_proc] + * + * Compile: + * cc -Wall -Wextra -o writer_cap_test writer_cap_test.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +int +main(int argc, char **argv) +{ + int fd, i, j; + int writers = (argc > 1) ? atoi(argv[1]) : 16; + int bytes = (argc > 2) ? atoi(argv[2]) : 64; + int writes = (argc > 3) ? atoi(argv[3]) : 100; + char *buf; + + buf = malloc(bytes); + if (buf == NULL) + err(1, "malloc"); + + for (i = 0; i < writers; i++) { + pid_t pid = fork(); + if (pid < 0) + err(1, "fork"); + if (pid == 0) { + fd = open("/dev/myfirst", O_WRONLY); + if (fd < 0) + err(1, "writer %d: open", i); + snprintf(buf, bytes, "writer-%d-data", i); + for (j = 0; j < writes; j++) { + if (write(fd, buf, bytes) < 0) { + if (errno == ENXIO) + break; + err(1, "writer %d: write", i); + } + usleep(1000); + } + close(fd); + _exit(0); + } + } + + while (wait(NULL) > 0) + ; + + free(buf); + return (0); +} diff --git a/examples/part-03/ch15-more-synchronization/stage1-writers-sema/Makefile b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.c b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.h b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch15-more-synchronization/stage1-writers-sema/myfirst.c b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/myfirst.c new file mode 100644 index 0000000..080761e --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage1-writers-sema/myfirst.c @@ -0,0 +1,1346 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 15, Stage 1: add the writer-cap semaphore. + * + * Builds on Chapter 14 Stage 4 by adding one primitive: + * sc->writers_sema counts available writer slots + * sc->writers_limit current configured cap + * sc->writers_trywait_failures diagnostic counter + * + * Stage 2 adds the stats cache sx; Stage 3 refines EINTR/ERESTART + * handling; Stage 4 adds recovery coordination and the + * myfirst_sync.h wrapper layer. + * + * Original Chapter 14 header preserved below: + * + * Chapter 14, Stage 4: the final taskqueue-enhanced driver. + * + * Builds on Chapter 13 Stage 4 by adding a private taskqueue and three + * tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* Chapter 15 Stage 1 */ +#include /* Chapter 15 Stage 1: writers_inflight */ +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.9-coordination-stage1" +#define MYFIRST_WRITERS_DEFAULT 4 +#define MYFIRST_BULK_MAX 64 + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + /* Chapter 15 Stage 1: writer-cap semaphore. + * writers_inflight is incremented before sema_wait and + * decremented after the matching sema_post on every exit path. + * Detach uses it to wait for all writers to leave sema code + * before calling sema_destroy, which closes the sema_destroy + * use-after-free race described in Section 8. + */ + struct sema writers_sema; + int writers_limit; + int writers_trywait_failures; + int writers_inflight; /* atomic int */ + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +/* Chapter 15 Stage 1: configure the writer-cap semaphore. */ +static int +myfirst_sysctl_writers_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, delta, error, i; + + new = sc->writers_limit; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 1 || new > 64) + return (EINVAL); + + MYFIRST_LOCK(sc); + delta = new - sc->writers_limit; + sc->writers_limit = new; + MYFIRST_UNLOCK(sc); + + /* Raising: post extra slots immediately. Lowering: best-effort + * (new entries observe the lower cap as the counter drains). */ + for (i = 0; i < delta; i++) + sema_post(&sc->writers_sema); + return (0); +} + +/* Chapter 15 Stage 1: read the current semaphore value. */ +static int +myfirst_sysctl_writers_sema_value(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int val; + + val = sema_value(&sc->writers_sema); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL) + return (ENXIO); + + /* Chapter 15 Stage 1: mark this thread as potentially using + * the writers_sema. Detach waits for writers_inflight to + * drop to zero before calling sema_destroy, so every path + * past this point and through the matching decrement is + * included in the drain. */ + atomic_add_int(&sc->writers_inflight, 1); + if (!sc->is_attached) { + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + /* Chapter 15 Stage 1: admission control. */ + if (ioflag & IO_NDELAY) { + if (!sema_trywait(&sc->writers_sema)) { + MYFIRST_LOCK(sc); + sc->writers_trywait_failures++; + MYFIRST_UNLOCK(sc); + atomic_subtract_int(&sc->writers_inflight, 1); + return (EAGAIN); + } + } else { + sema_wait(&sc->writers_sema); + } + if (!sc->is_attached) { + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + nbefore = uio->uio_resid; + error = 0; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + if (uio->uio_resid != nbefore) + error = 0; + else + error = EAGAIN; + goto out; + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + if (error == -1) + error = 0; + goto out; + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + goto out; + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + +out: + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (error); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 15 Stage 1)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 15 Stage 1: writer-cap semaphore and its drain counter. */ + sema_init(&sc->writers_sema, MYFIRST_WRITERS_DEFAULT, "myfirst writers"); + sc->writers_limit = MYFIRST_WRITERS_DEFAULT; + sc->writers_trywait_failures = 0; + sc->writers_inflight = 0; + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sema; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + /* Chapter 15 Stage 1: writer-cap sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "writers_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_limit, "I", + "Maximum concurrent writers (1-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_sema_value", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_sema_value, "I", + "Current writer semaphore counter value"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_trywait_failures", CTLFLAG_RD, + &sc->writers_trywait_failures, 0, + "Non-blocking writer sema_trywait failures"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_inflight", CTLFLAG_RD, + &sc->writers_inflight, 0, + "Threads currently using writers_sema (used by detach drain)"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sema: + sema_destroy(&sc->writers_sema); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Chapter 15 Stage 1: wake any writer blocked in sema_wait so it + * can observe is_attached=0 and return ENXIO. writers_limit + * slots are an upper bound on the number of simultaneously + * blocked waiters. */ + for (int i = 0; i < sc->writers_limit; i++) + sema_post(&sc->writers_sema); + + /* Chapter 15 Stage 1: drain in-flight writers. Every path + * that may be inside sema_wait, in the critical section, or + * between sema_wait return and the matching sema_post is + * counted by writers_inflight. Waiting for the counter to + * reach zero ensures no thread is still using the sema's + * internal mutex or condition variable when we later call + * sema_destroy. */ + while (atomic_load_acq_int(&sc->writers_inflight) > 0) + pause("myfwrd", 1); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + /* Chapter 15 Stage 1: destroy the writer-cap semaphore. */ + sema_destroy(&sc->writers_sema); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch15-more-synchronization/stage2-stats-cache/Makefile b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.c b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.h b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch15-more-synchronization/stage2-stats-cache/myfirst.c b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/myfirst.c new file mode 100644 index 0000000..80cb950 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage2-stats-cache/myfirst.c @@ -0,0 +1,1422 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 15, Stage 2: add the stats cache with sx upgrade pattern. + * + * Builds on Stage 1 by adding a read-mostly statistics cache: + * sc->stats_cache_sx sx lock protecting the cache + * sc->stats_cache_bytes_10s cached bytes_written snapshot + * sc->stats_cache_last_refresh_ticks cache freshness timestamp + * sc->stats_cache_refreshes diagnostic counter + * + * Readers of dev.myfirst.N.stats.bytes_written_10s take the sx shared; + * when the cache is stale they attempt sx_try_upgrade; on failure they + * drop-and-reacquire with sx_xlock, re-check, refresh, downgrade, and + * serve the value. + * + * Stage 3 refines EINTR/ERESTART handling; Stage 4 adds recovery + * coordination and the myfirst_sync.h wrapper layer. + * + * Original Chapter 14 header preserved below: + * + * Chapter 14, Stage 4: the final taskqueue-enhanced driver. + * + * Builds on Chapter 13 Stage 4 by adding a private taskqueue and three + * tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* Chapter 15 Stage 1 */ +#include /* Chapter 15 Stage 1: writers_inflight */ +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.9-coordination-stage2" +#define MYFIRST_WRITERS_DEFAULT 4 +#define MYFIRST_BULK_MAX 64 +#define MYFIRST_CACHE_STALE_HZ 1 /* Stage 2: stale after 1 second. */ + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + /* Chapter 15 Stage 1: writer-cap semaphore. + * writers_inflight is incremented before sema_wait and + * decremented after the matching sema_post on every exit path. + * Detach uses it to wait for all writers to leave sema code + * before calling sema_destroy, which closes the sema_destroy + * use-after-free race described in Section 8. + */ + struct sema writers_sema; + int writers_limit; + int writers_trywait_failures; + int writers_inflight; /* atomic int */ + + /* Chapter 15 Stage 2: stats cache sx. */ + struct sx stats_cache_sx; + uint64_t stats_cache_bytes_10s; + uint64_t stats_cache_last_refresh_ticks; + int stats_cache_refreshes; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (-1); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + if (error == EWOULDBLOCK) + return (EAGAIN); + if (error != 0) + return (error); + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +/* Chapter 15 Stage 1: configure the writer-cap semaphore. */ +static int +myfirst_sysctl_writers_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, delta, error, i; + + new = sc->writers_limit; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 1 || new > 64) + return (EINVAL); + + MYFIRST_LOCK(sc); + delta = new - sc->writers_limit; + sc->writers_limit = new; + MYFIRST_UNLOCK(sc); + + /* Raising: post extra slots immediately. Lowering: best-effort + * (new entries observe the lower cap as the counter drains). */ + for (i = 0; i < delta; i++) + sema_post(&sc->writers_sema); + return (0); +} + +/* Chapter 15 Stage 1: read the current semaphore value. */ +static int +myfirst_sysctl_writers_sema_value(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int val; + + val = sema_value(&sc->writers_sema); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 15 Stage 2: refresh the cached bytes_written statistic. + * Must be called with stats_cache_sx held exclusively. */ +static void +myfirst_stats_cache_refresh(struct myfirst_softc *sc) +{ + KASSERT(sx_xlocked(&sc->stats_cache_sx), + ("stats cache not exclusively locked")); + sc->stats_cache_bytes_10s = counter_u64_fetch(sc->bytes_written); + sc->stats_cache_last_refresh_ticks = ticks; + sc->stats_cache_refreshes++; +} + +/* Chapter 15 Stage 2: read the cached value using the + * upgrade-promote-downgrade pattern. Readers share the sx; the + * staleness check may promote briefly to refresh; a failed + * try_upgrade drops and re-acquires exclusively, then re-checks. */ +static int +myfirst_sysctl_bytes_written_10s(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + uint64_t value; + int stale; + + sx_slock(&sc->stats_cache_sx); + stale = (ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz); + if (stale) { + if (sx_try_upgrade(&sc->stats_cache_sx)) { + myfirst_stats_cache_refresh(sc); + sx_downgrade(&sc->stats_cache_sx); + } else { + sx_sunlock(&sc->stats_cache_sx); + sx_xlock(&sc->stats_cache_sx); + if ((ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz)) + myfirst_stats_cache_refresh(sc); + sx_downgrade(&sc->stats_cache_sx); + } + } + value = sc->stats_cache_bytes_10s; + sx_sunlock(&sc->stats_cache_sx); + + return (sysctl_handle_64(oidp, &value, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == -1 ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL) + return (ENXIO); + + /* Chapter 15 Stage 1: mark this thread as potentially using + * the writers_sema. Detach waits for writers_inflight to + * drop to zero before calling sema_destroy, so every path + * past this point and through the matching decrement is + * included in the drain. */ + atomic_add_int(&sc->writers_inflight, 1); + if (!sc->is_attached) { + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + /* Chapter 15 Stage 1: admission control. */ + if (ioflag & IO_NDELAY) { + if (!sema_trywait(&sc->writers_sema)) { + MYFIRST_LOCK(sc); + sc->writers_trywait_failures++; + MYFIRST_UNLOCK(sc); + atomic_subtract_int(&sc->writers_inflight, 1); + return (EAGAIN); + } + } else { + sema_wait(&sc->writers_sema); + } + if (!sc->is_attached) { + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + nbefore = uio->uio_resid; + error = 0; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + if (uio->uio_resid != nbefore) + error = 0; + else + error = EAGAIN; + goto out; + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + if (error == -1) + error = 0; + goto out; + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + goto out; + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + +out: + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (error); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 15 Stage 2)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 15 Stage 2: stats cache sx. */ + sx_init(&sc->stats_cache_sx, "myfirst stats cache"); + sc->stats_cache_bytes_10s = 0; + sc->stats_cache_last_refresh_ticks = 0; + sc->stats_cache_refreshes = 0; + + /* Chapter 15 Stage 1: writer-cap semaphore and its drain counter. */ + sema_init(&sc->writers_sema, MYFIRST_WRITERS_DEFAULT, "myfirst writers"); + sc->writers_limit = MYFIRST_WRITERS_DEFAULT; + sc->writers_trywait_failures = 0; + sc->writers_inflight = 0; + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sema; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + /* Chapter 15 Stage 1: writer-cap sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "writers_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_limit, "I", + "Maximum concurrent writers (1-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_sema_value", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_sema_value, "I", + "Current writer semaphore counter value"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_trywait_failures", CTLFLAG_RD, + &sc->writers_trywait_failures, 0, + "Non-blocking writer sema_trywait failures"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_inflight", CTLFLAG_RD, + &sc->writers_inflight, 0, + "Threads currently using writers_sema (used by detach drain)"); + + /* Chapter 15 Stage 2: stats cache sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written_10s", + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bytes_written_10s, "Q", + "Cached bytes_written snapshot (refresh cadence: 1 Hz)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "stats_cache_refreshes", CTLFLAG_RD, + &sc->stats_cache_refreshes, 0, + "Number of times the stats cache was refreshed"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sema: + sema_destroy(&sc->writers_sema); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Chapter 15 Stage 1: wake any writer blocked in sema_wait so it + * can observe is_attached=0 and return ENXIO. writers_limit + * slots are an upper bound on the number of simultaneously + * blocked waiters. */ + for (int i = 0; i < sc->writers_limit; i++) + sema_post(&sc->writers_sema); + + /* Chapter 15 Stage 1: drain in-flight writers. Every path + * that may be inside sema_wait, in the critical section, or + * between sema_wait return and the matching sema_post is + * counted by writers_inflight. Waiting for the counter to + * reach zero ensures no thread is still using the sema's + * internal mutex or condition variable when we later call + * sema_destroy. */ + while (atomic_load_acq_int(&sc->writers_inflight) > 0) + pause("myfwrd", 1); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + /* Chapter 15 Stage 1: destroy the writer-cap semaphore. */ + sema_destroy(&sc->writers_sema); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch15-more-synchronization/stage3-interruptible/Makefile b/examples/part-03/ch15-more-synchronization/stage3-interruptible/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage3-interruptible/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.c b/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.h b/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage3-interruptible/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch15-more-synchronization/stage3-interruptible/myfirst.c b/examples/part-03/ch15-more-synchronization/stage3-interruptible/myfirst.c new file mode 100644 index 0000000..a368234 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage3-interruptible/myfirst.c @@ -0,0 +1,1439 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 15, Stage 3: refine EINTR/ERESTART handling. + * + * Builds on Stage 2 by: + * - introducing the MYFIRST_WAIT_PARTIAL sentinel to replace the + * magic -1 return value on the partial-progress path, + * - making the cv_wait return-value switch explicit + * (0 / EWOULDBLOCK / EINTR / ERESTART / default), + * - preserving partial progress on signal interruption. + * + * Stage 4 adds recovery coordination and the myfirst_sync.h wrapper + * layer. + * + * Original Chapter 14 header preserved below: + * + * Chapter 14, Stage 4: the final taskqueue-enhanced driver. + * + * Builds on Chapter 13 Stage 4 by adding a private taskqueue and three + * tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* Chapter 15 Stage 1 */ +#include /* Chapter 15 Stage 1: writers_inflight */ +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.9-coordination-stage3" +#define MYFIRST_WRITERS_DEFAULT 4 +#define MYFIRST_BULK_MAX 64 +#define MYFIRST_CACHE_STALE_HZ 1 /* Stage 2: stale after 1 second. */ +#define MYFIRST_WAIT_PARTIAL (-1) /* Stage 3: partial-progress sentinel. */ + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + /* Chapter 15 Stage 1: writer-cap semaphore. + * writers_inflight is incremented before sema_wait and + * decremented after the matching sema_post on every exit path. + * Detach uses it to wait for all writers to leave sema code + * before calling sema_destroy, which closes the sema_destroy + * use-after-free race described in Section 8. + */ + struct sema writers_sema; + int writers_limit; + int writers_trywait_failures; + int writers_inflight; /* atomic int */ + + /* Chapter 15 Stage 2: stats cache sx. */ + struct sx stats_cache_sx; + uint64_t stats_cache_bytes_10s; + uint64_t stats_cache_last_refresh_ticks; + int stats_cache_refreshes; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + /* Chapter 15 Stage 3: explicit handling of every + * cv_*_sig return value. */ + switch (error) { + case 0: + break; + case EWOULDBLOCK: + return (EAGAIN); + case EINTR: + case ERESTART: + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + return (error); + default: + return (error); + } + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + switch (error) { + case 0: + break; + case EWOULDBLOCK: + return (EAGAIN); + case EINTR: + case ERESTART: + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + return (error); + default: + return (error); + } + if (!sc->is_attached) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +/* Chapter 15 Stage 1: configure the writer-cap semaphore. */ +static int +myfirst_sysctl_writers_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, delta, error, i; + + new = sc->writers_limit; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 1 || new > 64) + return (EINVAL); + + MYFIRST_LOCK(sc); + delta = new - sc->writers_limit; + sc->writers_limit = new; + MYFIRST_UNLOCK(sc); + + /* Raising: post extra slots immediately. Lowering: best-effort + * (new entries observe the lower cap as the counter drains). */ + for (i = 0; i < delta; i++) + sema_post(&sc->writers_sema); + return (0); +} + +/* Chapter 15 Stage 1: read the current semaphore value. */ +static int +myfirst_sysctl_writers_sema_value(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int val; + + val = sema_value(&sc->writers_sema); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 15 Stage 2: refresh the cached bytes_written statistic. + * Must be called with stats_cache_sx held exclusively. */ +static void +myfirst_stats_cache_refresh(struct myfirst_softc *sc) +{ + KASSERT(sx_xlocked(&sc->stats_cache_sx), + ("stats cache not exclusively locked")); + sc->stats_cache_bytes_10s = counter_u64_fetch(sc->bytes_written); + sc->stats_cache_last_refresh_ticks = ticks; + sc->stats_cache_refreshes++; +} + +/* Chapter 15 Stage 2: read the cached value using the + * upgrade-promote-downgrade pattern. Readers share the sx; the + * staleness check may promote briefly to refresh; a failed + * try_upgrade drops and re-acquires exclusively, then re-checks. */ +static int +myfirst_sysctl_bytes_written_10s(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + uint64_t value; + int stale; + + sx_slock(&sc->stats_cache_sx); + stale = (ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz); + if (stale) { + if (sx_try_upgrade(&sc->stats_cache_sx)) { + myfirst_stats_cache_refresh(sc); + sx_downgrade(&sc->stats_cache_sx); + } else { + sx_sunlock(&sc->stats_cache_sx); + sx_xlock(&sc->stats_cache_sx); + if ((ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz)) + myfirst_stats_cache_refresh(sc); + sx_downgrade(&sc->stats_cache_sx); + } + } + value = sc->stats_cache_bytes_10s; + sx_sunlock(&sc->stats_cache_sx); + + return (sysctl_handle_64(oidp, &value, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !sc->is_attached) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == MYFIRST_WAIT_PARTIAL ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL) + return (ENXIO); + + /* Chapter 15 Stage 1: mark this thread as potentially using + * the writers_sema. Detach waits for writers_inflight to + * drop to zero before calling sema_destroy, so every path + * past this point and through the matching decrement is + * included in the drain. */ + atomic_add_int(&sc->writers_inflight, 1); + if (!sc->is_attached) { + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + /* Chapter 15 Stage 1: admission control. */ + if (ioflag & IO_NDELAY) { + if (!sema_trywait(&sc->writers_sema)) { + MYFIRST_LOCK(sc); + sc->writers_trywait_failures++; + MYFIRST_UNLOCK(sc); + atomic_subtract_int(&sc->writers_inflight, 1); + return (EAGAIN); + } + } else { + sema_wait(&sc->writers_sema); + } + if (!sc->is_attached) { + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + nbefore = uio->uio_resid; + error = 0; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + if (uio->uio_resid != nbefore) + error = 0; + else + error = EAGAIN; + goto out; + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + if (error == MYFIRST_WAIT_PARTIAL) + error = 0; + goto out; + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) + goto out; + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + +out: + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (error); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !sc->is_attached) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 15 Stage 3)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 15 Stage 2: stats cache sx. */ + sx_init(&sc->stats_cache_sx, "myfirst stats cache"); + sc->stats_cache_bytes_10s = 0; + sc->stats_cache_last_refresh_ticks = 0; + sc->stats_cache_refreshes = 0; + + /* Chapter 15 Stage 1: writer-cap semaphore and its drain counter. */ + sema_init(&sc->writers_sema, MYFIRST_WRITERS_DEFAULT, "myfirst writers"); + sc->writers_limit = MYFIRST_WRITERS_DEFAULT; + sc->writers_trywait_failures = 0; + sc->writers_inflight = 0; + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sema; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->is_attached = 1; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + /* Chapter 15 Stage 1: writer-cap sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "writers_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_limit, "I", + "Maximum concurrent writers (1-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_sema_value", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_sema_value, "I", + "Current writer semaphore counter value"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_trywait_failures", CTLFLAG_RD, + &sc->writers_trywait_failures, 0, + "Non-blocking writer sema_trywait failures"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_inflight", CTLFLAG_RD, + &sc->writers_inflight, 0, + "Threads currently using writers_sema (used by detach drain)"); + + /* Chapter 15 Stage 2: stats cache sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written_10s", + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bytes_written_10s, "Q", + "Cached bytes_written snapshot (refresh cadence: 1 Hz)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "stats_cache_refreshes", CTLFLAG_RD, + &sc->stats_cache_refreshes, 0, + "Number of times the stats cache was refreshed"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sema: + sema_destroy(&sc->writers_sema); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + sc->is_attached = 0; + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + sc->is_attached = 0; + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* Chapter 15 Stage 1: wake any writer blocked in sema_wait so it + * can observe is_attached=0 and return ENXIO. writers_limit + * slots are an upper bound on the number of simultaneously + * blocked waiters. */ + for (int i = 0; i < sc->writers_limit; i++) + sema_post(&sc->writers_sema); + + /* Chapter 15 Stage 1: drain in-flight writers. Every path + * that may be inside sema_wait, in the critical section, or + * between sema_wait return and the matching sema_post is + * counted by writers_inflight. Waiting for the counter to + * reach zero ensures no thread is still using the sema's + * internal mutex or condition variable when we later call + * sema_destroy. */ + while (atomic_load_acq_int(&sc->writers_inflight) > 0) + pause("myfwrd", 1); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + /* Chapter 15 Stage 1: destroy the writer-cap semaphore. */ + sema_destroy(&sc->writers_sema); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch15-more-synchronization/stage4-final/Makefile b/examples/part-03/ch15-more-synchronization/stage4-final/Makefile new file mode 100644 index 0000000..c01284d --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage4-final/Makefile @@ -0,0 +1,12 @@ +# Makefile for the Chapter 14 Stage 4 (final) myfirst driver. +# +# Combines every earlier stage: the Chapter 12 cv channels and sx +# configuration, the Chapter 13 callouts, and the Chapter 14 private +# taskqueue with three tasks (selwake_task, bulk_writer_task, +# reset_delayed_task). + +KMOD= myfirst +SRCS= myfirst.c cbuf.c +SRCS+= device_if.h bus_if.h + +.include diff --git a/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.c b/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.c new file mode 100644 index 0000000..c92b247 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.c: kernel-side implementation of the byte-oriented circular + * buffer for the Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller (the driver's I/O handlers) + * holds sc->mtx around every cbuf_*() call. + */ + +#include +#include +#include +#include + +#include "cbuf.h" + +MALLOC_DEFINE(M_CBUF, "cbuf", "Chapter 10 circular buffer"); + +int +cbuf_init(struct cbuf *cb, size_t size) +{ + if (cb == NULL || size == 0) + return (EINVAL); + cb->cb_data = malloc(size, M_CBUF, M_WAITOK | M_ZERO); + cb->cb_size = size; + cb->cb_head = 0; + cb->cb_used = 0; + return (0); +} + +void +cbuf_destroy(struct cbuf *cb) +{ + if (cb == NULL || cb->cb_data == NULL) + return; + free(cb->cb_data, M_CBUF); + cb->cb_data = NULL; + cb->cb_size = 0; + cb->cb_head = 0; + cb->cb_used = 0; +} + +void +cbuf_reset(struct cbuf *cb) +{ + if (cb == NULL) + return; + cb->cb_head = 0; + cb->cb_used = 0; +} + +size_t +cbuf_size(const struct cbuf *cb) +{ + return (cb->cb_size); +} + +size_t +cbuf_used(const struct cbuf *cb) +{ + return (cb->cb_used); +} + +size_t +cbuf_free(const struct cbuf *cb) +{ + return (cb->cb_size - cb->cb_used); +} + +size_t +cbuf_write(struct cbuf *cb, const void *src, size_t n) +{ + size_t avail, tail, first, second; + + avail = cbuf_free(cb); + if (n > avail) + n = avail; + if (n == 0) + return (0); + + tail = (cb->cb_head + cb->cb_used) % cb->cb_size; + first = MIN(n, cb->cb_size - tail); + memcpy(cb->cb_data + tail, src, first); + second = n - first; + if (second > 0) + memcpy(cb->cb_data, (const char *)src + first, second); + + cb->cb_used += n; + return (n); +} + +size_t +cbuf_read(struct cbuf *cb, void *dst, size_t n) +{ + size_t first, second; + + if (n > cb->cb_used) + n = cb->cb_used; + if (n == 0) + return (0); + + first = MIN(n, cb->cb_size - cb->cb_head); + memcpy(dst, cb->cb_data + cb->cb_head, first); + second = n - first; + if (second > 0) + memcpy((char *)dst + first, cb->cb_data, second); + + cb->cb_head = (cb->cb_head + n) % cb->cb_size; + cb->cb_used -= n; + return (n); +} diff --git a/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.h b/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.h new file mode 100644 index 0000000..da7038c --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage4-final/cbuf.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * cbuf.h: a fixed-size byte-oriented circular buffer for the + * Chapter 10 myfirst driver. + * + * The buffer does not lock; the caller is responsible for whatever + * synchronization the surrounding system requires. + */ + +#ifndef CBUF_H +#define CBUF_H + +#include + +struct cbuf { + char *cb_data; /* backing storage */ + size_t cb_size; /* total capacity */ + size_t cb_head; /* next byte to read */ + size_t cb_used; /* live byte count */ +}; + +int cbuf_init(struct cbuf *cb, size_t size); +void cbuf_destroy(struct cbuf *cb); +void cbuf_reset(struct cbuf *cb); + +size_t cbuf_size(const struct cbuf *cb); +size_t cbuf_used(const struct cbuf *cb); +size_t cbuf_free(const struct cbuf *cb); + +size_t cbuf_write(struct cbuf *cb, const void *src, size_t n); +size_t cbuf_read(struct cbuf *cb, void *dst, size_t n); + +#endif /* CBUF_H */ diff --git a/examples/part-03/ch15-more-synchronization/stage4-final/myfirst.c b/examples/part-03/ch15-more-synchronization/stage4-final/myfirst.c new file mode 100644 index 0000000..a1e4220 --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage4-final/myfirst.c @@ -0,0 +1,1455 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * Chapter 15, Stage 4: the coordinated driver (v0.9-coordination). + * + * Adds to Chapter 14 Stage 4: + * - A counting semaphore (writers_sema) capping concurrent writers. + * - A stats-cache sx (stats_cache_sx) with upgrade-promote-downgrade + * for a read-mostly cached statistic. + * - Refined cv_timedwait_sig handling with partial-progress sentinel. + * - A recovery_task plus recovery_in_progress state flag for + * cross-component coordination. + * - Atomic is_attached flag (atomic_load_acq_int/atomic_store_rel_int). + * - Encapsulated synchronisation vocabulary in myfirst_sync.h. + * + * Original header preserved below for context: + * + * Chapter 14, Stage 4: the final taskqueue-enhanced driver. + * + * Builds on Chapter 13 Stage 4 by adding a private taskqueue and three + * tasks: + * + * - selwake_task (plain): defers selwakeup() out of the + * tick_source callout callback. + * - bulk_writer_task (plain): demonstrates deliberate coalescing + * via the ta_pending rule; writes a + * configurable batch of bytes per firing. + * - reset_delayed_task (timeout_task): performs a delayed reset in + * thread context, scheduled via a sysctl. + * + * The taskqueue is created in attach with taskqueue_create and serviced + * by a single worker thread started at PWAIT via taskqueue_start_threads. + * All tasks are drained at detach before the taskqueue is freed. + * + * Detach ordering: + * 1. Refuse detach if active_fhs > 0. + * 2. Clear is_attached under sc->mtx; broadcast cvs; release mtx. + * 3. Drain all three callouts. + * 4. Drain all three tasks (the timeout_task via taskqueue_drain_timeout). + * 5. seldrain(&sc->rsel), seldrain(&sc->wsel). + * 6. taskqueue_free(sc->tq); sc->tq = NULL. + * 7. Destroy cdev, free sysctl context, destroy cbuf, counters, cvs, + * sx, mutex. + * + * Locking strategy (unchanged from Chapter 13 except for the task + * additions): + * + * sc->mtx protects: + * - sc->cb (the circular buffer's internal state) + * - sc->open_count, sc->active_fhs + * - sc->is_attached (writes; reads at handler entry may be unprotected) + * - sc->selwake_pending_drops, sc->bulk_writer_batch + * + * sc->bytes_read, sc->bytes_written are counter(9) per-CPU counters. + * + * sc->data_cv: cv signalled when bytes are added to the cbuf. + * sc->room_cv: cv signalled when room is freed in the cbuf. + * Both use sc->mtx as their interlock. + * + * Task callbacks run in thread context on the private taskqueue; they + * acquire sc->mtx explicitly when needed and never hold it across + * selwakeup(9). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cbuf.h" + +#define MYFIRST_BUFSIZE 4096 +#define MYFIRST_BOUNCE 256 +#define MYFIRST_VERSION "0.9-coordination" +#define MYFIRST_BULK_MAX 64 +#define MYFIRST_WAIT_PARTIAL (-1) /* sentinel: partial-progress exit */ +#define MYFIRST_WRITERS_DEFAULT 4 +#define MYFIRST_CACHE_STALE_HZ 1 + +#define MYFIRST_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYFIRST_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYFIRST_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +#define MYFIRST_CFG_SLOCK(sc) sx_slock(&(sc)->cfg_sx) +#define MYFIRST_CFG_SUNLOCK(sc) sx_sunlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XLOCK(sc) sx_xlock(&(sc)->cfg_sx) +#define MYFIRST_CFG_XUNLOCK(sc) sx_xunlock(&(sc)->cfg_sx) + +#define MYFIRST_CO_INIT(sc, co) callout_init_mtx((co), &(sc)->mtx, 0) +#define MYFIRST_CO_DRAIN(co) callout_drain((co)) + +struct myfirst_config { + int debug_level; + int soft_byte_limit; + char nickname[32]; +}; + +struct myfirst_softc { + device_t dev; + int unit; + + struct mtx mtx; + struct cv data_cv; + struct cv room_cv; + + struct sx cfg_sx; + struct myfirst_config cfg; + + uint64_t attach_ticks; + uint64_t open_count; + counter_u64_t bytes_read; + counter_u64_t bytes_written; + + int active_fhs; + int is_attached; + int read_timeout_ms; + int write_timeout_ms; + + /* Callouts (from Chapter 13). */ + struct callout heartbeat_co; + int heartbeat_interval_ms; + struct callout watchdog_co; + int watchdog_interval_ms; + size_t watchdog_last_used; + struct callout tick_source_co; + int tick_source_interval_ms; + char tick_source_byte; + + /* Chapter 14: private taskqueue and tasks. */ + struct taskqueue *tq; + struct task selwake_task; + int selwake_pending_drops; + struct task bulk_writer_task; + int bulk_writer_batch; + struct timeout_task reset_delayed_task; + int reset_delay_ms; + + /* Chapter 15: writer-cap semaphore (Stage 1). */ + struct sema writers_sema; + int writers_limit; + int writers_trywait_failures; + int writers_inflight; /* atomic int; drain counter */ + + /* Chapter 15: stats cache with upgrade-promote-downgrade (Stage 2). */ + struct sx stats_cache_sx; + uint64_t stats_cache_bytes_10s; + uint64_t stats_cache_last_refresh_ticks; + int stats_cache_refreshes; + + /* Chapter 15: recovery coordination (Stage 4). */ + int recovery_in_progress; /* under mtx */ + struct task recovery_task; + int recovery_task_runs; + + struct cbuf cb; + + struct selinfo rsel; + struct selinfo wsel; + + struct cdev *cdev; + struct cdev *cdev_alias; + + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; +}; + +#include "myfirst_sync.h" + +struct myfirst_fh { + struct myfirst_softc *sc; + uint64_t reads; + uint64_t writes; +}; + +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; +static d_poll_t myfirst_poll; + +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_poll = myfirst_poll, + .d_name = "myfirst", +}; + +static int +myfirst_get_debug_level(struct myfirst_softc *sc) +{ + int level; + + MYFIRST_CFG_SLOCK(sc); + level = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + return (level); +} + +static int +myfirst_get_soft_byte_limit(struct myfirst_softc *sc) +{ + int limit; + + MYFIRST_CFG_SLOCK(sc); + limit = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + return (limit); +} + +#define MYFIRST_DBG(sc, level, fmt, ...) do { \ + if (myfirst_get_debug_level(sc) >= (level)) \ + device_printf((sc)->dev, fmt, ##__VA_ARGS__); \ +} while (0) + +static size_t +myfirst_buf_read(struct myfirst_softc *sc, void *dst, size_t n) +{ + size_t got; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_read called after detach")); + got = cbuf_read(&sc->cb, dst, n); + KASSERT(got <= n, + ("cbuf_read returned %zu > n=%zu", got, n)); + counter_u64_add(sc->bytes_read, got); + return (got); +} + +static size_t +myfirst_buf_write(struct myfirst_softc *sc, const void *src, size_t n) +{ + size_t put; + + MYFIRST_ASSERT(sc); + KASSERT(sc->is_attached, + ("myfirst_buf_write called after detach")); + put = cbuf_write(&sc->cb, src, n); + KASSERT(put <= n, + ("cbuf_write returned %zu > n=%zu", put, n)); + counter_u64_add(sc->bytes_written, put); + return (put); +} + +static int +myfirst_wait_data(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_used(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->read_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->data_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->data_cv, &sc->mtx); + } + switch (error) { + case 0: + break; + case EWOULDBLOCK: + return (EAGAIN); + case EINTR: + case ERESTART: + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + return (error); + default: + return (error); + } + if (!myfirst_sync_is_attached(sc)) + return (ENXIO); + } + return (0); +} + +static int +myfirst_wait_room(struct myfirst_softc *sc, int ioflag, ssize_t nbefore, + struct uio *uio) +{ + int error, timo; + + MYFIRST_ASSERT(sc); + while (cbuf_free(&sc->cb) == 0) { + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + if (ioflag & IO_NDELAY) + return (EAGAIN); + + timo = sc->write_timeout_ms; + if (timo > 0) { + int ticks_total = (timo * hz + 999) / 1000; + error = cv_timedwait_sig(&sc->room_cv, &sc->mtx, + ticks_total); + } else { + error = cv_wait_sig(&sc->room_cv, &sc->mtx); + } + switch (error) { + case 0: + break; + case EWOULDBLOCK: + return (EAGAIN); + case EINTR: + case ERESTART: + if (uio->uio_resid != nbefore) + return (MYFIRST_WAIT_PARTIAL); + return (error); + default: + return (error); + } + if (!myfirst_sync_is_attached(sc)) + return (ENXIO); + } + return (0); +} + +/* + * Chapter 14 task callbacks. Each runs in thread context on sc->tq with + * no driver lock held. Callbacks acquire sc->mtx explicitly if they + * need to touch mutex-protected state, and release it before making + * calls like selwakeup(9) that must be invoked without unrelated locks. + */ + +static void +myfirst_selwake_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + if (pending > 1) { + MYFIRST_LOCK(sc); + sc->selwake_pending_drops += pending - 1; + MYFIRST_UNLOCK(sc); + } + + selwakeup(&sc->rsel); +} + +static void +myfirst_bulk_writer_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + char buf[MYFIRST_BULK_MAX]; + int batch, written; + + (void)pending; + + MYFIRST_LOCK(sc); + batch = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + if (batch <= 0) + return; + + if (batch > (int)sizeof(buf)) + batch = sizeof(buf); + memset(buf, 'B', batch); + + MYFIRST_LOCK(sc); + written = (int)cbuf_write(&sc->cb, buf, batch); + if (written > 0) { + counter_u64_add(sc->bytes_written, written); + cv_signal(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); + + if (written > 0) + selwakeup(&sc->rsel); +} + +static void +myfirst_reset_delayed_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + device_printf(sc->dev, "delayed reset fired (pending=%d)\n", pending); +} + +/* + * Chapter 15 Stage 2: refresh the cached bytes-written statistic. + * Must be called with stats_cache_sx held exclusively. + */ +static void +myfirst_stats_cache_refresh(struct myfirst_softc *sc) +{ + KASSERT(sx_xlocked(&sc->stats_cache_sx), + ("stats cache not exclusively locked")); + sc->stats_cache_bytes_10s = counter_u64_fetch(sc->bytes_written); + sc->stats_cache_last_refresh_ticks = ticks; + sc->stats_cache_refreshes++; +} + +/* + * Chapter 15 Stage 4: the recovery task. Enqueued by the watchdog + * callback when a stall is detected. Runs in thread context. + */ +static void +myfirst_recovery_task(void *arg, int pending) +{ + struct myfirst_softc *sc = arg; + + (void)pending; + device_printf(sc->dev, "recovery task firing\n"); + /* + * A real driver would perform the recovery action here. + * The didactic version just logs and clears the flag. + */ + myfirst_sync_lock(sc); + sc->recovery_in_progress = 0; + sc->recovery_task_runs++; + myfirst_sync_unlock(sc); +} + +/* Callout callbacks (unchanged from Chapter 13 except tick_source). */ + +static void +myfirst_heartbeat(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + uint64_t br, bw; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + br = counter_u64_fetch(sc->bytes_read); + bw = counter_u64_fetch(sc->bytes_written); + device_printf(sc->dev, + "heartbeat: cb_used=%zu, bytes_read=%ju, bytes_written=%ju\n", + used, (uintmax_t)br, (uintmax_t)bw); + + interval = sc->heartbeat_interval_ms; + if (interval > 0) + callout_reset(&sc->heartbeat_co, + (interval * hz + 999) / 1000, + myfirst_heartbeat, sc); +} + +static void +myfirst_watchdog(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t used; + int interval; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + used = cbuf_used(&sc->cb); + if (used > 0 && used == sc->watchdog_last_used) { + device_printf(sc->dev, + "watchdog: buffer has %zu bytes, no progress in last " + "interval; reader stuck?\n", used); + /* Chapter 15: trigger the recovery task, at most one at a + * time. Lock is held because callout_init_mtx acquires it. */ + if (!sc->recovery_in_progress) { + sc->recovery_in_progress = 1; + taskqueue_enqueue(sc->tq, &sc->recovery_task); + } + } + sc->watchdog_last_used = used; + + interval = sc->watchdog_interval_ms; + if (interval > 0) + callout_reset(&sc->watchdog_co, + (interval * hz + 999) / 1000, + myfirst_watchdog, sc); +} + +static void +myfirst_tick_source(void *arg) +{ + struct myfirst_softc *sc = arg; + size_t put; + int interval; + bool wake_sel = false; + + MYFIRST_ASSERT(sc); + if (!sc->is_attached) + return; + + if (cbuf_free(&sc->cb) > 0) { + put = cbuf_write(&sc->cb, &sc->tick_source_byte, 1); + if (put > 0) { + counter_u64_add(sc->bytes_written, put); + cv_signal(&sc->data_cv); + wake_sel = true; + } + } + + /* Chapter 14: defer selwakeup to thread context via sc->tq. */ + if (wake_sel) + taskqueue_enqueue(sc->tq, &sc->selwake_task); + + interval = sc->tick_source_interval_ms; + if (interval > 0) + callout_reset(&sc->tick_source_co, + (interval * hz + 999) / 1000, + myfirst_tick_source, sc); +} + +/* Sysctl handlers for configuration, timers, and Chapter 14 additions. */ + +static int +myfirst_sysctl_debug_level(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.debug_level; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > 3) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.debug_level = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_soft_byte_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_CFG_SLOCK(sc); + new = sc->cfg.soft_byte_limit; + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_CFG_XLOCK(sc); + sc->cfg.soft_byte_limit = new; + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_nickname(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + char buf[sizeof(sc->cfg.nickname)]; + int error; + + MYFIRST_CFG_SLOCK(sc); + strlcpy(buf, sc->cfg.nickname, sizeof(buf)); + MYFIRST_CFG_SUNLOCK(sc); + + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error || req->newptr == NULL) + return (error); + + MYFIRST_CFG_XLOCK(sc); + strlcpy(sc->cfg.nickname, buf, sizeof(sc->cfg.nickname)); + MYFIRST_CFG_XUNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_heartbeat_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->heartbeat_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->heartbeat_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->heartbeat_co, + (new * hz + 999) / 1000, myfirst_heartbeat, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->heartbeat_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_watchdog_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->watchdog_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->watchdog_interval_ms = new; + if (new > 0 && old == 0) { + sc->watchdog_last_used = cbuf_used(&sc->cb); + callout_reset(&sc->watchdog_co, + (new * hz + 999) / 1000, myfirst_watchdog, sc); + } else if (new == 0 && old > 0) { + callout_stop(&sc->watchdog_co); + } + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_tick_source_interval_ms(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, old, error; + + old = sc->tick_source_interval_ms; + new = old; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->tick_source_interval_ms = new; + if (new > 0 && old == 0) + callout_reset(&sc->tick_source_co, + (new * hz + 999) / 1000, myfirst_tick_source, sc); + else if (new == 0 && old > 0) + callout_stop(&sc->tick_source_co); + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_reset(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int reset = 0; + int error; + + error = sysctl_handle_int(oidp, &reset, 0, req); + if (error || req->newptr == NULL) + return (error); + if (reset != 1) + return (0); + + MYFIRST_LOCK(sc); + MYFIRST_CFG_XLOCK(sc); + + cbuf_reset(&sc->cb); + sc->cfg.debug_level = 0; + counter_u64_zero(sc->bytes_read); + counter_u64_zero(sc->bytes_written); + + MYFIRST_CFG_XUNLOCK(sc); + MYFIRST_UNLOCK(sc); + + cv_broadcast(&sc->room_cv); + return (0); +} + +static int +myfirst_sysctl_cb_used(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_used(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +static int +myfirst_sysctl_cb_free(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int val; + + MYFIRST_LOCK(sc); + val = (unsigned int)cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 14: sysctls for task-driven features. */ + +static int +myfirst_sysctl_bulk_writer_batch(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, error; + + MYFIRST_LOCK(sc); + new = sc->bulk_writer_batch; + MYFIRST_UNLOCK(sc); + + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 0 || new > MYFIRST_BULK_MAX) + return (EINVAL); + + MYFIRST_LOCK(sc); + sc->bulk_writer_batch = new; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_sysctl_bulk_writer_flood(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int flood = 0; + int error, i; + + error = sysctl_handle_int(oidp, &flood, 0, req); + if (error || req->newptr == NULL) + return (error); + if (flood < 1 || flood > 10000) + return (EINVAL); + + for (i = 0; i < flood; i++) + taskqueue_enqueue(sc->tq, &sc->bulk_writer_task); + return (0); +} + +static int +myfirst_sysctl_reset_delayed(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int ms = 0; + int error; + + error = sysctl_handle_int(oidp, &ms, 0, req); + if (error || req->newptr == NULL) + return (error); + if (ms < 0) + return (EINVAL); + if (ms == 0) { + (void)taskqueue_cancel_timeout(sc->tq, + &sc->reset_delayed_task, NULL); + return (0); + } + + sc->reset_delay_ms = ms; + taskqueue_enqueue_timeout(sc->tq, &sc->reset_delayed_task, + (ms * hz + 999) / 1000); + return (0); +} + +/* Chapter 15 Stage 1: configure the writer-cap semaphore. */ +static int +myfirst_sysctl_writers_limit(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int new, delta, error, i; + + new = sc->writers_limit; + error = sysctl_handle_int(oidp, &new, 0, req); + if (error || req->newptr == NULL) + return (error); + if (new < 1 || new > 64) + return (EINVAL); + + myfirst_sync_lock(sc); + delta = new - sc->writers_limit; + sc->writers_limit = new; + myfirst_sync_unlock(sc); + + /* Raising the limit: post the extra slots immediately. */ + for (i = 0; i < delta; i++) + sema_post(&sc->writers_sema); + /* + * Lowering the limit is best-effort: new entries observe the + * lower cap as the counter drains naturally. + */ + return (0); +} + +/* Chapter 15 Stage 1: observe the semaphore's current value. */ +static int +myfirst_sysctl_writers_sema_value(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + int val; + + val = sema_value(&sc->writers_sema); + return (sysctl_handle_int(oidp, &val, 0, req)); +} + +/* Chapter 15 Stage 2: read the cached bytes_written_10s via the + * upgrade-promote-downgrade pattern. */ +static int +myfirst_sysctl_bytes_written_10s(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + uint64_t value; + int stale; + + myfirst_sync_stats_cache_read_begin(sc); + stale = (ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz); + if (stale) { + if (myfirst_sync_stats_cache_try_promote(sc)) { + myfirst_stats_cache_refresh(sc); + myfirst_sync_stats_cache_downgrade(sc); + } else { + myfirst_sync_stats_cache_read_end(sc); + myfirst_sync_stats_cache_write_begin(sc); + if ((ticks - (int)sc->stats_cache_last_refresh_ticks) > + (MYFIRST_CACHE_STALE_HZ * hz)) + myfirst_stats_cache_refresh(sc); + myfirst_sync_stats_cache_downgrade(sc); + } + } + value = sc->stats_cache_bytes_10s; + myfirst_sync_stats_cache_read_end(sc); + + return (sysctl_handle_64(oidp, &value, 0, req)); +} + +static void +myfirst_fh_dtor(void *data) +{ + struct myfirst_fh *fh = data; + struct myfirst_softc *sc = fh->sc; + + MYFIRST_LOCK(sc); + sc->active_fhs--; + MYFIRST_UNLOCK(sc); + + free(fh, M_DEVBUF); +} + +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + int error; + + if (sc == NULL || !myfirst_sync_is_attached(sc)) + return (ENXIO); + + fh = malloc(sizeof(*fh), M_DEVBUF, M_WAITOK | M_ZERO); + fh->sc = sc; + + error = devfs_set_cdevpriv(fh, myfirst_fh_dtor); + if (error != 0) { + free(fh, M_DEVBUF); + return (error); + } + + MYFIRST_LOCK(sc); + sc->open_count++; + sc->active_fhs++; + MYFIRST_UNLOCK(sc); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t take, got; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !myfirst_sync_is_attached(sc)) + return (ENXIO); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + MYFIRST_LOCK(sc); + error = myfirst_wait_data(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + return (error == MYFIRST_WAIT_PARTIAL ? 0 : error); + } + take = MIN((size_t)uio->uio_resid, sizeof(bounce)); + got = myfirst_buf_read(sc, bounce, take); + fh->reads += got; + MYFIRST_UNLOCK(sc); + + if (got > 0) { + cv_signal(&sc->room_cv); + selwakeup(&sc->wsel); + } + + error = uiomove(bounce, got, uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + struct myfirst_fh *fh; + char bounce[MYFIRST_BOUNCE]; + size_t want, put, room; + ssize_t nbefore; + int error; + + error = devfs_get_cdevpriv((void **)&fh); + if (error != 0) + return (error); + if (sc == NULL || !myfirst_sync_is_attached(sc)) + return (ENXIO); + + /* Chapter 15 Stage 1: admission control via writer-cap semaphore. */ + error = myfirst_sync_writer_enter(sc, ioflag); + if (error != 0) + return (error); + + nbefore = uio->uio_resid; + while (uio->uio_resid > 0) { + int limit = myfirst_get_soft_byte_limit(sc); + + MYFIRST_LOCK(sc); + if (limit > 0 && cbuf_used(&sc->cb) + sizeof(bounce) > + (size_t)limit) { + MYFIRST_UNLOCK(sc); + myfirst_sync_writer_leave(sc); + return (uio->uio_resid != nbefore ? 0 : EAGAIN); + } + error = myfirst_wait_room(sc, ioflag, nbefore, uio); + if (error != 0) { + MYFIRST_UNLOCK(sc); + myfirst_sync_writer_leave(sc); + return (error == MYFIRST_WAIT_PARTIAL ? 0 : error); + } + room = cbuf_free(&sc->cb); + MYFIRST_UNLOCK(sc); + + want = MIN((size_t)uio->uio_resid, sizeof(bounce)); + want = MIN(want, room); + error = uiomove(bounce, want, uio); + if (error != 0) { + myfirst_sync_writer_leave(sc); + return (error); + } + + MYFIRST_LOCK(sc); + put = myfirst_buf_write(sc, bounce, want); + fh->writes += put; + MYFIRST_UNLOCK(sc); + + if (put > 0) { + cv_signal(&sc->data_cv); + selwakeup(&sc->rsel); + MYFIRST_DBG(sc, 2, "wrote %zu bytes\n", put); + } + } + myfirst_sync_writer_leave(sc); + return (0); +} + +static int +myfirst_poll(struct cdev *dev, int events, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int revents = 0; + + if (sc == NULL || !myfirst_sync_is_attached(sc)) + return (POLLERR); + + MYFIRST_LOCK(sc); + if (events & (POLLIN | POLLRDNORM)) { + if (cbuf_used(&sc->cb) > 0) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->rsel); + } + if (events & (POLLOUT | POLLWRNORM)) { + if (cbuf_free(&sc->cb) > 0) + revents |= events & (POLLOUT | POLLWRNORM); + else + selrecord(td, &sc->wsel); + } + MYFIRST_UNLOCK(sc); + return (revents); +} + +static void +myfirst_identify(driver_t *driver, device_t parent) +{ + if (device_find_child(parent, driver->name, -1) != NULL) + return; + if (BUS_ADD_CHILD(parent, 0, driver->name, -1) == NULL) + device_printf(parent, "myfirst: BUS_ADD_CHILD failed\n"); +} + +static int +myfirst_probe(device_t dev) +{ + device_set_desc(dev, "My First FreeBSD Driver (Chapter 15 Stage 4)"); + return (BUS_PROBE_DEFAULT); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->dev = dev; + sc->unit = device_get_unit(dev); + + mtx_init(&sc->mtx, device_get_nameunit(dev), "myfirst", MTX_DEF); + cv_init(&sc->data_cv, "myfirst data"); + cv_init(&sc->room_cv, "myfirst room"); + sx_init(&sc->cfg_sx, "myfirst cfg"); + + /* Chapter 15 Stage 2: stats cache sx. */ + sx_init(&sc->stats_cache_sx, "myfirst stats cache"); + + /* Chapter 15 Stage 1: writer-cap semaphore. */ + sema_init(&sc->writers_sema, MYFIRST_WRITERS_DEFAULT, "myfirst writers"); + sc->writers_limit = MYFIRST_WRITERS_DEFAULT; + + /* Chapter 14: create the private taskqueue before anything that + * could enqueue onto it. */ + sc->tq = taskqueue_create("myfirst taskq", M_WAITOK, + taskqueue_thread_enqueue, &sc->tq); + if (sc->tq == NULL) { + error = ENOMEM; + goto fail_sema; + } + error = taskqueue_start_threads(&sc->tq, 1, PWAIT, + "%s taskq", device_get_nameunit(dev)); + if (error != 0) + goto fail_tq; + + MYFIRST_CO_INIT(sc, &sc->heartbeat_co); + MYFIRST_CO_INIT(sc, &sc->watchdog_co); + MYFIRST_CO_INIT(sc, &sc->tick_source_co); + + /* Chapter 14: initialise every task. */ + TASK_INIT(&sc->selwake_task, 0, myfirst_selwake_task, sc); + TASK_INIT(&sc->bulk_writer_task, 0, myfirst_bulk_writer_task, sc); + TIMEOUT_TASK_INIT(sc->tq, &sc->reset_delayed_task, 0, + myfirst_reset_delayed_task, sc); + + /* Chapter 15: initialise the recovery task. */ + TASK_INIT(&sc->recovery_task, 0, myfirst_recovery_task, sc); + + sc->cfg.debug_level = 0; + sc->cfg.soft_byte_limit = 0; + strlcpy(sc->cfg.nickname, "myfirst", sizeof(sc->cfg.nickname)); + + sc->attach_ticks = ticks; + sc->active_fhs = 0; + sc->open_count = 0; + sc->read_timeout_ms = 0; + sc->write_timeout_ms = 0; + sc->heartbeat_interval_ms = 0; + sc->watchdog_interval_ms = 0; + sc->watchdog_last_used = 0; + sc->tick_source_interval_ms = 0; + sc->tick_source_byte = 't'; + sc->selwake_pending_drops = 0; + sc->bulk_writer_batch = 0; + sc->reset_delay_ms = 0; + sc->writers_trywait_failures = 0; + sc->writers_inflight = 0; + sc->stats_cache_bytes_10s = 0; + sc->stats_cache_last_refresh_ticks = 0; + sc->stats_cache_refreshes = 0; + sc->recovery_in_progress = 0; + sc->recovery_task_runs = 0; + sc->bytes_read = counter_u64_alloc(M_WAITOK); + sc->bytes_written = counter_u64_alloc(M_WAITOK); + + /* Chapter 15 Stage 4: make_attached atomically, visible to all + * contexts with correct memory ordering. */ + myfirst_sync_mark_attached(sc); + + error = cbuf_init(&sc->cb, MYFIRST_BUFSIZE); + if (error != 0) + goto fail_tq; + + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_OPERATOR; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + + error = make_dev_s(&args, &sc->cdev, "myfirst/%d", sc->unit); + if (error != 0) + goto fail_cb; + + sc->cdev_alias = make_dev_alias(sc->cdev, "myfirst"); + if (sc->cdev_alias == NULL) + device_printf(dev, "failed to create /dev/myfirst alias\n"); + + sysctl_ctx_init(&sc->sysctl_ctx); + sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "Driver statistics"); + + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "attach_ticks", CTLFLAG_RD, + &sc->attach_ticks, 0, "Tick count when driver attached"); + SYSCTL_ADD_U64(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "open_count", CTLFLAG_RD, + &sc->open_count, 0, "Lifetime number of opens"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "active_fhs", CTLFLAG_RD, + &sc->active_fhs, 0, "Currently open descriptors"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_read", CTLFLAG_RD, + sc->bytes_read, "Total bytes drained from the buffer"); + SYSCTL_ADD_COUNTER_U64(&sc->sysctl_ctx, + SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written", CTLFLAG_RD, + sc->bytes_written, "Total bytes appended to the buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_used", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_used, "IU", + "Live bytes currently held in the circular buffer"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_free", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_cb_free, "IU", + "Free bytes available in the circular buffer"); + SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "cb_size", CTLFLAG_RD, + (unsigned int *)&sc->cb.cb_size, 0, + "Capacity of the circular buffer"); + + /* Chapter 14: expose the task coalescing counter. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "selwake_pending_drops", CTLFLAG_RD, + &sc->selwake_pending_drops, 0, + "Times selwake_task coalesced two or more enqueues"); + + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "read_timeout_ms", CTLFLAG_RW, + &sc->read_timeout_ms, 0, + "Read timeout in milliseconds (0 = block indefinitely)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "write_timeout_ms", CTLFLAG_RW, + &sc->write_timeout_ms, 0, + "Write timeout in milliseconds (0 = block indefinitely)"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "debug_level", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_debug_level, "I", + "Debug verbosity (0-3)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "soft_byte_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_soft_byte_limit, "I", + "Soft limit on cb_used; writes refused above this"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "nickname", + CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_nickname, "A", + "Human-readable nickname for log lines"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset, "I", + "Write 1 to reset cbuf, counters, and configuration"); + + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "heartbeat_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_heartbeat_interval_ms, "I", + "Heartbeat interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "watchdog_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_watchdog_interval_ms, "I", + "Watchdog interval in milliseconds (0 = disabled)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "tick_source_interval_ms", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_tick_source_interval_ms, "I", + "Tick-source interval in milliseconds (0 = disabled)"); + + /* Chapter 14: task sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_batch", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_batch, "I", + "Bytes the bulk_writer_task writes per firing (0-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "bulk_writer_flood", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bulk_writer_flood, "I", + "Write N to enqueue bulk_writer_task N times (demonstrates " + "coalescing)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "reset_delayed", + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_reset_delayed, "I", + "Write N (ms) to arm a delayed reset; 0 cancels any pending " + "delayed reset"); + + /* Chapter 15 Stage 1 sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "writers_limit", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_limit, "I", + "Maximum concurrent writers (1-64)"); + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_sema_value", + CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_writers_sema_value, "I", + "Current semaphore counter value"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_trywait_failures", CTLFLAG_RD, + &sc->writers_trywait_failures, 0, + "Non-blocking writer sema_trywait failures"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "writers_inflight", CTLFLAG_RD, + &sc->writers_inflight, 0, + "Threads currently using writers_sema (used by detach drain)"); + + /* Chapter 15 Stage 2 sysctls. */ + SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "bytes_written_10s", + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_bytes_written_10s, "Q", + "Cached bytes_written snapshot (refresh cadence: 1 Hz)"); + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "stats_cache_refreshes", CTLFLAG_RD, + &sc->stats_cache_refreshes, 0, + "Total stats cache refreshes"); + + /* Chapter 15 Stage 4 sysctls. */ + SYSCTL_ADD_INT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree), + OID_AUTO, "recovery_task_runs", CTLFLAG_RD, + &sc->recovery_task_runs, 0, + "Number of times the recovery task has run"); + + device_printf(dev, + "Attached; version %s, node /dev/%s (alias /dev/myfirst), " + "cbuf=%zu bytes\n", + MYFIRST_VERSION, devtoname(sc->cdev), cbuf_size(&sc->cb)); + return (0); + +fail_cb: + cbuf_destroy(&sc->cb); +fail_tq: + if (sc->tq != NULL) + taskqueue_free(sc->tq); +fail_sema: + sema_destroy(&sc->writers_sema); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + atomic_store_rel_int(&sc->is_attached, 0); + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc; + + sc = device_get_softc(dev); + + MYFIRST_LOCK(sc); + if (sc->active_fhs > 0) { + MYFIRST_UNLOCK(sc); + device_printf(dev, + "Cannot detach: %d open descriptor(s)\n", + sc->active_fhs); + return (EBUSY); + } + /* Chapter 15 Stage 4: atomic store-release marks shutdown. */ + myfirst_sync_mark_detaching(sc); + cv_broadcast(&sc->data_cv); + cv_broadcast(&sc->room_cv); + MYFIRST_UNLOCK(sc); + + /* + * Chapter 15: wake any thread blocked in sema_wait so it can + * observe is_attached=0 and return ENXIO. We post writers_limit + * extra slots, which is an upper bound on the number of + * possible waiters. Each waker re-posts on the ENXIO exit + * path, so the extra slots drain naturally. + */ + for (int i = 0; i < sc->writers_limit; i++) + sema_post(&sc->writers_sema); + + /* + * Chapter 15: drain every in-flight writer before proceeding. + * After this loop returns, no thread is inside + * myfirst_sync_writer_enter/leave or between them, so + * sema_destroy below is safe. + */ + myfirst_sync_writers_drain(sc); + + /* Callouts first: guarantees no more enqueues come from timers. */ + MYFIRST_CO_DRAIN(&sc->heartbeat_co); + MYFIRST_CO_DRAIN(&sc->watchdog_co); + MYFIRST_CO_DRAIN(&sc->tick_source_co); + + /* Tasks second: guarantees no callback is executing. */ + taskqueue_drain(sc->tq, &sc->selwake_task); + taskqueue_drain(sc->tq, &sc->bulk_writer_task); + taskqueue_drain_timeout(sc->tq, &sc->reset_delayed_task); + taskqueue_drain(sc->tq, &sc->recovery_task); + + /* selinfo third: safe now that no task will call selwakeup. */ + seldrain(&sc->rsel); + seldrain(&sc->wsel); + + /* Free the taskqueue last, after every task is drained. */ + taskqueue_free(sc->tq); + sc->tq = NULL; + + /* Chapter 15: destroy the semaphore (no waiters: is_attached=0 + * and cv broadcast guarantee no new waiters; existing waiters + * already returned ENXIO). */ + sema_destroy(&sc->writers_sema); + + if (sc->cdev_alias != NULL) { + destroy_dev(sc->cdev_alias); + sc->cdev_alias = NULL; + } + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + sysctl_ctx_free(&sc->sysctl_ctx); + cbuf_destroy(&sc->cb); + counter_u64_free(sc->bytes_read); + counter_u64_free(sc->bytes_written); + sx_destroy(&sc->stats_cache_sx); + cv_destroy(&sc->data_cv); + cv_destroy(&sc->room_cv); + sx_destroy(&sc->cfg_sx); + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_identify, myfirst_identify), + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc) +}; + +static SYSCTL_NODE(_hw, OID_AUTO, myfirst, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "myfirst driver"); +SYSCTL_STRING(_hw_myfirst, OID_AUTO, version, CTLFLAG_RD, + MYFIRST_VERSION, 0, "Driver version string"); + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-03/ch15-more-synchronization/stage4-final/myfirst_sync.h b/examples/part-03/ch15-more-synchronization/stage4-final/myfirst_sync.h new file mode 100644 index 0000000..e97dc1e --- /dev/null +++ b/examples/part-03/ch15-more-synchronization/stage4-final/myfirst_sync.h @@ -0,0 +1,201 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_sync.h: the named synchronisation vocabulary of the + * myfirst driver at Chapter 15 Stage 4. + * + * Every primitive the driver uses has a wrapper here. The main + * source calls these wrappers; the wrappers are inlined away, so + * the runtime cost is zero. The benefit is a readable, + * centralised, and easily-changeable synchronisation strategy. + * + * This file depends on the definition of `struct myfirst_softc` + * in myfirst.c. Include this header after the softc definition. + */ + +#ifndef MYFIRST_SYNC_H +#define MYFIRST_SYNC_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Data-path mutex wrappers. + */ +static __inline void +myfirst_sync_lock(struct myfirst_softc *sc) +{ + mtx_lock(&sc->mtx); +} + +static __inline void +myfirst_sync_unlock(struct myfirst_softc *sc) +{ + mtx_unlock(&sc->mtx); +} + +static __inline void +myfirst_sync_assert_locked(struct myfirst_softc *sc) +{ + mtx_assert(&sc->mtx, MA_OWNED); +} + +/* + * Configuration sx wrappers (read-mostly state). + */ +static __inline void +myfirst_sync_cfg_read_begin(struct myfirst_softc *sc) +{ + sx_slock(&sc->cfg_sx); +} + +static __inline void +myfirst_sync_cfg_read_end(struct myfirst_softc *sc) +{ + sx_sunlock(&sc->cfg_sx); +} + +static __inline void +myfirst_sync_cfg_write_begin(struct myfirst_softc *sc) +{ + sx_xlock(&sc->cfg_sx); +} + +static __inline void +myfirst_sync_cfg_write_end(struct myfirst_softc *sc) +{ + sx_xunlock(&sc->cfg_sx); +} + +/* + * Writer-cap semaphore wrappers. + * + * Returns 0 on success, EAGAIN for O_NONBLOCK when the semaphore is + * exhausted, or ENXIO when detach occurred at any point. + * + * writers_inflight is incremented before any sema operation and + * decremented by myfirst_sync_writer_leave. Detach waits for it to + * drop to zero before destroying the semaphore, which closes the + * sema_destroy use-after-free race documented in Section 8. + * + * Every path that calls myfirst_sync_writer_enter and returns 0 MUST + * later call myfirst_sync_writer_leave. Paths that return non-zero + * already decremented the inflight counter and must not call leave. + */ +static __inline int +myfirst_sync_writer_enter(struct myfirst_softc *sc, int ioflag) +{ + atomic_add_int(&sc->writers_inflight, 1); + if (!atomic_load_acq_int(&sc->is_attached)) { + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + + if (ioflag & IO_NDELAY) { + if (!sema_trywait(&sc->writers_sema)) { + mtx_lock(&sc->mtx); + sc->writers_trywait_failures++; + mtx_unlock(&sc->mtx); + atomic_subtract_int(&sc->writers_inflight, 1); + return (EAGAIN); + } + } else { + sema_wait(&sc->writers_sema); + } + if (!atomic_load_acq_int(&sc->is_attached)) { + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); + return (ENXIO); + } + return (0); +} + +static __inline void +myfirst_sync_writer_leave(struct myfirst_softc *sc) +{ + sema_post(&sc->writers_sema); + atomic_subtract_int(&sc->writers_inflight, 1); +} + +/* + * Wait for every in-flight writer to leave the semaphore region. + * Called from detach AFTER is_attached has been cleared and wake-up + * slots have been posted, and BEFORE sema_destroy. + */ +static __inline void +myfirst_sync_writers_drain(struct myfirst_softc *sc) +{ + while (atomic_load_acq_int(&sc->writers_inflight) > 0) + pause("myfwrd", 1); +} + +/* + * Stats-cache sx wrappers (upgrade-promote-downgrade pattern). + */ +static __inline void +myfirst_sync_stats_cache_read_begin(struct myfirst_softc *sc) +{ + sx_slock(&sc->stats_cache_sx); +} + +static __inline void +myfirst_sync_stats_cache_read_end(struct myfirst_softc *sc) +{ + sx_sunlock(&sc->stats_cache_sx); +} + +static __inline int +myfirst_sync_stats_cache_try_promote(struct myfirst_softc *sc) +{ + return (sx_try_upgrade(&sc->stats_cache_sx)); +} + +static __inline void +myfirst_sync_stats_cache_downgrade(struct myfirst_softc *sc) +{ + sx_downgrade(&sc->stats_cache_sx); +} + +static __inline void +myfirst_sync_stats_cache_write_begin(struct myfirst_softc *sc) +{ + sx_xlock(&sc->stats_cache_sx); +} + +static __inline void +myfirst_sync_stats_cache_write_end(struct myfirst_softc *sc) +{ + sx_xunlock(&sc->stats_cache_sx); +} + +/* + * Atomic is_attached flag wrappers. + */ +static __inline int +myfirst_sync_is_attached(struct myfirst_softc *sc) +{ + return (atomic_load_acq_int(&sc->is_attached)); +} + +static __inline void +myfirst_sync_mark_detaching(struct myfirst_softc *sc) +{ + atomic_store_rel_int(&sc->is_attached, 0); +} + +static __inline void +myfirst_sync_mark_attached(struct myfirst_softc *sc) +{ + atomic_store_rel_int(&sc->is_attached, 1); +} + +#endif /* MYFIRST_SYNC_H */ diff --git a/examples/part-04/ch16-accessing-hardware/hwsim-standalone/Makefile b/examples/part-04/ch16-accessing-hardware/hwsim-standalone/Makefile new file mode 100644 index 0000000..6824f6b --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/hwsim-standalone/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 16 stand-alone hwsim practice module. +# +# Builds a minimal kernel module that demonstrates bus_space(9) on +# a malloc'd register block, exposing four 32-bit registers through +# sysctl at dev.hwsim.reg{0,4,8,c}. + +KMOD= hwsim +SRCS= hwsim.c + +.include diff --git a/examples/part-04/ch16-accessing-hardware/hwsim-standalone/hwsim.c b/examples/part-04/ch16-accessing-hardware/hwsim-standalone/hwsim.c new file mode 100644 index 0000000..81553f0 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/hwsim-standalone/hwsim.c @@ -0,0 +1,114 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * hwsim.c -- Chapter 16 stand-alone bus_space(9) practice module. + * + * Demonstrates the bus_space(9) API on a simulated register block + * allocated with malloc(9). Exposes two 32-bit registers through + * sysctl so the reader can read and write them from user space. + * + * This module is x86-specific. On x86, bus_space_tag_t is an integer + * and the memory-space bus_space_*_4 functions reduce to a volatile + * dereference of (handle + offset), which lets us back them with + * plain kernel memory. On other architectures the tag has different + * semantics and the shortcut does not apply. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_HWSIM, "hwsim", "hwsim test module"); + +#define HWSIM_SIZE 0x40 + +static uint8_t *hwsim_buf; +static bus_space_tag_t hwsim_tag; +static bus_space_handle_t hwsim_handle; + +static SYSCTL_NODE(_dev, OID_AUTO, hwsim, + CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, "hwsim practice module"); + +static int +hwsim_sysctl_reg(SYSCTL_HANDLER_ARGS) +{ + bus_size_t offset = arg2; + uint32_t value; + int error; + + if (hwsim_buf == NULL) + return (ENODEV); + + value = bus_space_read_4(hwsim_tag, hwsim_handle, offset); + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + bus_space_write_4(hwsim_tag, hwsim_handle, offset, value); + return (0); +} + +static int +hwsim_modevent(module_t mod, int event, void *arg) +{ + switch (event) { + case MOD_LOAD: +#if !defined(__amd64__) && !defined(__i386__) + printf("hwsim: unsupported architecture\n"); + return (EOPNOTSUPP); +#else + hwsim_buf = malloc(HWSIM_SIZE, M_HWSIM, M_WAITOK | M_ZERO); + hwsim_tag = X86_BUS_SPACE_MEM; + hwsim_handle = (bus_space_handle_t)(uintptr_t)hwsim_buf; + + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim), + OID_AUTO, "reg0", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + NULL, 0x00, hwsim_sysctl_reg, "IU", + "Register at offset 0x00 (32-bit)"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim), + OID_AUTO, "reg4", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + NULL, 0x04, hwsim_sysctl_reg, "IU", + "Register at offset 0x04 (32-bit)"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim), + OID_AUTO, "reg8", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + NULL, 0x08, hwsim_sysctl_reg, "IU", + "Register at offset 0x08 (32-bit)"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim), + OID_AUTO, "regc", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + NULL, 0x0c, hwsim_sysctl_reg, "IU", + "Register at offset 0x0c (32-bit)"); + + printf("hwsim: loaded, %d bytes at %p\n", + HWSIM_SIZE, hwsim_buf); + return (0); +#endif + + case MOD_UNLOAD: + if (hwsim_buf != NULL) { + free(hwsim_buf, M_HWSIM); + hwsim_buf = NULL; + } + printf("hwsim: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t hwsim_mod = { + "hwsim", + hwsim_modevent, + NULL +}; + +DECLARE_MODULE(hwsim, hwsim_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(hwsim, 1); diff --git a/examples/part-04/ch16-accessing-hardware/labs/Makefile b/examples/part-04/ch16-accessing-hardware/labs/Makefile new file mode 100644 index 0000000..d342307 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/labs/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 16 user-space lab tools. + +PROG= register_dump +SRCS= register_dump.c +MAN= +WARNS= 6 +CSTD= c11 +NO_MAN= + +.include diff --git a/examples/part-04/ch16-accessing-hardware/labs/full_regression.sh b/examples/part-04/ch16-accessing-hardware/labs/full_regression.sh new file mode 100755 index 0000000..d523f42 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/labs/full_regression.sh @@ -0,0 +1,94 @@ +#!/bin/sh +# +# full_regression.sh -- Chapter 16 regression pass. +# +# Runs every Chapter 11 through Chapter 16 check against the +# Stage 4 driver. Designed to be quick and tell the caller +# whether the driver's composition is sound. +# +# Usage: +# ./full_regression.sh +# +# Requires: +# - The myfirst driver loaded at 0.9-mmio. +# - The labs/ register_dump tool built. + +set -eu + +DEV=/dev/myfirst0 + +echo "Chapter 16 regression pass" +echo "==========================" + +if [ ! -c "$DEV" ]; then + echo "FAIL: $DEV not present" + exit 1 +fi + +echo "--- Step 1: Register-level sanity ---" +./register_dump + +# Confirm DEVICE_ID matches. +devid=$(sysctl -n dev.myfirst.0.reg_device_id) +if [ "$devid" -ne 1298498121 ]; then + echo "FAIL: DEVICE_ID mismatch (got $devid, expected 1298498121)" + exit 1 +fi +echo "OK: DEVICE_ID correct." + +# Confirm STATUS has READY bit set. +status=$(sysctl -n dev.myfirst.0.reg_status) +if [ $(( status & 1 )) -ne 1 ]; then + echo "FAIL: STATUS.READY not set" + exit 1 +fi +echo "OK: STATUS.READY set." + +echo "--- Step 2: Data path produces register updates ---" +echo -n "ABCDEF" > "$DEV" +data_in=$(sysctl -n dev.myfirst.0.reg_data_in) +if [ "$data_in" -ne 70 ]; then + echo "FAIL: DATA_IN should be 70 ('F'), got $data_in" + exit 1 +fi +echo "OK: DATA_IN reflects last written byte." + +dd if="$DEV" bs=6 count=1 of=/dev/null 2>/dev/null +data_out=$(sysctl -n dev.myfirst.0.reg_data_out) +if [ "$data_out" -ne 70 ]; then + echo "FAIL: DATA_OUT should be 70 ('F'), got $data_out" + exit 1 +fi +echo "OK: DATA_OUT reflects last read byte." + +echo "--- Step 3: Ticker task updates SCRATCH_A ---" +before=$(sysctl -n dev.myfirst.0.reg_scratch_a) +sysctl dev.myfirst.0.reg_ticker_enabled=1 > /dev/null +sleep 3 +after=$(sysctl -n dev.myfirst.0.reg_scratch_a) +sysctl dev.myfirst.0.reg_ticker_enabled=0 > /dev/null +if [ "$after" -le "$before" ]; then + echo "FAIL: ticker did not advance SCRATCH_A ($before -> $after)" + exit 1 +fi +echo "OK: ticker advanced SCRATCH_A ($before -> $after)." + +echo "--- Step 4: Access log records events ---" +sysctl dev.myfirst.0.access_log_enabled=1 > /dev/null +echo -n "xyz" > "$DEV" +dd if="$DEV" bs=3 count=1 of=/dev/null 2>/dev/null +log=$(sysctl -n dev.myfirst.0.access_log) +sysctl dev.myfirst.0.access_log_enabled=0 > /dev/null +n=$(printf "%s\n" "$log" | grep -c "^") +if [ "$n" -lt 4 ]; then + echo "FAIL: access log has only $n lines" + exit 1 +fi +echo "OK: access log recorded $n events." + +echo "--- Step 5: Short stress pass (5 seconds) ---" +./reg_stress.sh 5 +echo "OK: stress pass completed." + +echo +echo "Chapter 16 regression: all checks passed." diff --git a/examples/part-04/ch16-accessing-hardware/labs/reg_stress.sh b/examples/part-04/ch16-accessing-hardware/labs/reg_stress.sh new file mode 100755 index 0000000..173a1ad --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/labs/reg_stress.sh @@ -0,0 +1,89 @@ +#!/bin/sh +# +# reg_stress.sh -- Chapter 16 register-access stress test. +# +# Exercises concurrent writers, concurrent readers, concurrent +# sysctl queries, and the ticker task against the Chapter 16 driver. +# Runs for the number of seconds given on the command line (default +# 30). On a debug kernel with INVARIANTS and WITNESS, any locking +# violation or out-of-bounds access should produce an immediate +# warning or panic. +# +# Usage: +# ./reg_stress.sh [duration] +# +# Run as root; requires the myfirst driver to be loaded. + +set -eu + +DEV=/dev/myfirst0 +DURATION=${1:-30} + +if [ ! -c "$DEV" ]; then + echo "Device $DEV not present. Did you kldload myfirst?" + exit 1 +fi + +echo "Stress test running for ${DURATION}s..." + +# Enable access logging for the duration of the run. +sysctl dev.myfirst.0.access_log_enabled=1 > /dev/null + +# Enable the ticker. +sysctl dev.myfirst.0.reg_ticker_enabled=1 > /dev/null + +# Background writers: each emits bytes to the device file. +for i in 1 2 3 4 5 6 7 8; do + ( + end=$(( $(date +%s) + DURATION )) + while [ $(date +%s) -lt $end ]; do + printf "W%d" "$i" > "$DEV" + done + ) & +done + +# Background readers. +for i in 1 2 3 4; do + ( + end=$(( $(date +%s) + DURATION )) + while [ $(date +%s) -lt $end ]; do + dd if="$DEV" bs=16 count=1 of=/dev/null 2>/dev/null || true + done + ) & +done + +# Background sysctl queries. +( + end=$(( $(date +%s) + DURATION )) + while [ $(date +%s) -lt $end ]; do + sysctl dev.myfirst.0.reg_data_in > /dev/null + sysctl dev.myfirst.0.reg_status > /dev/null + sysctl dev.myfirst.0.reg_scratch_a > /dev/null + done +) & + +# Background sysctl CTRL writer. +( + end=$(( $(date +%s) + DURATION )) + v=1 + while [ $(date +%s) -lt $end ]; do + sysctl dev.myfirst.0.reg_ctrl_set="$v" > /dev/null + v=$(( (v + 1) % 256 )) + done +) & + +wait + +echo "Stress test complete." + +# Disable ticker and access log, print the last few access-log lines. +sysctl dev.myfirst.0.reg_ticker_enabled=0 > /dev/null +sysctl dev.myfirst.0.access_log_enabled=0 > /dev/null + +echo "Final register state:" +./register_dump 2>/dev/null || sysctl dev.myfirst.0 | grep reg_ + +echo "Last few access-log lines:" +sysctl dev.myfirst.0.access_log 2>/dev/null | tail -n 10 + +exit 0 diff --git a/examples/part-04/ch16-accessing-hardware/labs/register_dump.c b/examples/part-04/ch16-accessing-hardware/labs/register_dump.c new file mode 100644 index 0000000..8ca08a2 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/labs/register_dump.c @@ -0,0 +1,106 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * register_dump.c -- Chapter 16 user-space register dump tool. + * + * Queries every Chapter 16 register sysctl from dev.myfirst.0 and + * prints a formatted summary. Useful for Labs 1 and 4. + * + * Build: make + * Run: ./register_dump + */ + +#include +#include +#include +#include +#include +#include + +struct reg_desc { + const char *sysctl_name; + const char *pretty_name; + unsigned int offset; +}; + +static const struct reg_desc regs[] = { + { "dev.myfirst.0.reg_ctrl", "CTRL", 0x00 }, + { "dev.myfirst.0.reg_status", "STATUS", 0x04 }, + { "dev.myfirst.0.reg_data_in", "DATA_IN", 0x08 }, + { "dev.myfirst.0.reg_data_out", "DATA_OUT", 0x0c }, + { "dev.myfirst.0.reg_intr_mask", "INTR_MASK", 0x10 }, + { "dev.myfirst.0.reg_intr_status", "INTR_STATUS", 0x14 }, + { "dev.myfirst.0.reg_device_id", "DEVICE_ID", 0x18 }, + { "dev.myfirst.0.reg_firmware_rev", "FIRMWARE_REV", 0x1c }, + { "dev.myfirst.0.reg_scratch_a", "SCRATCH_A", 0x20 }, + { "dev.myfirst.0.reg_scratch_b", "SCRATCH_B", 0x24 }, +}; + +static int +read_reg(const char *name, unsigned int *value) +{ + size_t len = sizeof(*value); + + if (sysctlbyname(name, value, &len, NULL, 0) != 0) + return (-1); + if (len != sizeof(*value)) + return (-1); + return (0); +} + +int +main(int argc, char **argv) +{ + unsigned int value; + size_t i; + + (void)argc; + (void)argv; + + printf("myfirst register dump\n"); + printf("---------------------\n"); + printf("%-14s %-6s %-10s %s\n", "Name", "Offset", "Value", "Decoded"); + + for (i = 0; i < sizeof(regs)/sizeof(regs[0]); i++) { + if (read_reg(regs[i].sysctl_name, &value) != 0) { + printf("%-14s 0x%02x (unavailable: %s)\n", + regs[i].pretty_name, regs[i].offset, + regs[i].sysctl_name); + continue; + } + printf("%-14s 0x%02x 0x%08x ", + regs[i].pretty_name, regs[i].offset, value); + + /* Small decoded view for a few well-known registers. */ + if (regs[i].offset == 0x00) { + printf("["); + if (value & 0x1) printf(" ENABLE"); + if (value & 0x2) printf(" RESET"); + if (value & 0x100) printf(" LOOPBACK"); + if ((value & 0xf0) != 0) printf(" mode=%u", (value>>4)&0xf); + printf(" ]"); + } else if (regs[i].offset == 0x04) { + printf("["); + if (value & 0x1) printf(" READY"); + if (value & 0x2) printf(" BUSY"); + if (value & 0x4) printf(" ERROR"); + if (value & 0x8) printf(" DATA_AV"); + printf(" ]"); + } else if (regs[i].offset == 0x18) { + char id[5]; + id[0] = (value >> 0) & 0xff; + id[1] = (value >> 8) & 0xff; + id[2] = (value >> 16) & 0xff; + id[3] = (value >> 24) & 0xff; + id[4] = '\0'; + printf("[ '%s' ]", id); + } else if (regs[i].offset == 0x1c) { + printf("[ v%u.%u ]", + (value >> 16) & 0xffff, + value & 0xffff); + } + printf("\n"); + } + + return (0); +} diff --git a/examples/part-04/ch16-accessing-hardware/stage4-final/HARDWARE.md b/examples/part-04/ch16-accessing-hardware/stage4-final/HARDWARE.md new file mode 100644 index 0000000..e514550 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/stage4-final/HARDWARE.md @@ -0,0 +1,149 @@ +# myfirst Hardware Interface + +## Version + +`0.9-mmio`. Chapter 16 complete. + +## Overview + +The `myfirst` driver exposes a simulated 64-byte register block +through the FreeBSD `bus_space(9)` API. On x86 the block is backed +by kernel memory allocated with `malloc(9)`; the `bus_space_tag_t` +is `X86_BUS_SPACE_MEM` and the `bus_space_handle_t` is the kernel +virtual address of the allocation. + +All register access is lock-protected by the driver's main mutex +`sc->mtx`. The accessor helpers assert lock ownership, so bugs +that skip locking are caught on debug kernels via `WITNESS`. + +## Register Map + +| Offset | Width | Name | Direction | Reset value | +|--------|--------|-----------------|-----------|-----------------------| +| 0x00 | 32 bit | CTRL | R/W | 0x00000000 | +| 0x04 | 32 bit | STATUS | R/W | 0x00000001 (READY) | +| 0x08 | 32 bit | DATA_IN | R/W | 0x00000000 | +| 0x0c | 32 bit | DATA_OUT | R/W | 0x00000000 | +| 0x10 | 32 bit | INTR_MASK | R/W | 0x00000000 | +| 0x14 | 32 bit | INTR_STATUS | R/W | 0x00000000 | +| 0x18 | 32 bit | DEVICE_ID | R | 0x4D594649 ('MYFI') | +| 0x1c | 32 bit | FIRMWARE_REV | R | 0x00010000 (1.0) | +| 0x20 | 32 bit | SCRATCH_A | R/W | 0x00000000 | +| 0x24 | 32 bit | SCRATCH_B | R/W | 0x00000000 | + +Offsets 0x28 through 0x3f are reserved. Reads return 0; writes are +accepted but ignored by driver policy. + +## Bit Fields + +### CTRL (0x00) + +| Bit | Name | Description | +|------|------------------|---------------------------------------| +| 0 | ENABLE | Device enabled | +| 1 | RESET | Reset (Chapter 17) | +| 4..7 | MODE | Operating mode | +| 8 | LOOPBACK | Route DATA_IN to DATA_OUT | + +### STATUS (0x04) + +| Bit | Name | Description | +|------|------------------|---------------------------------------| +| 0 | READY | Device attached and operational | +| 1 | BUSY | Operation in progress (Chapter 17) | +| 2 | ERROR | Error latch (Chapter 17) | +| 3 | DATA_AV | DATA_OUT has data | + +### INTR_MASK and INTR_STATUS (0x10, 0x14) + +| Bit | Name | Description | +|------|------------------|---------------------------------------| +| 0 | DATA_AV | Data available | +| 1 | ERROR | Error condition | +| 2 | COMPLETE | Operation complete | + +Chapter 19 wires interrupts to these bits. Chapter 16 leaves them +static. + +## Per-Register Owners + +| Register | Who writes it | +|----------------|---------------------------------------------------| +| CTRL | sysctl writer; `myfirst_ctrl_update` side effect | +| STATUS | driver (via write/read paths) | +| DATA_IN | syscall write path | +| DATA_OUT | syscall read path | +| INTR_MASK | sysctl writer (Chapter 19 will add attach path) | +| INTR_STATUS | sysctl writer (Chapter 17 will add write-1-clear) | +| DEVICE_ID | attach only | +| FIRMWARE_REV | attach only | +| SCRATCH_A | reg_ticker task; sysctl writer | +| SCRATCH_B | sysctl writer | + +## API + +All register access goes through macros defined in `myfirst_hw.h`: + +```c +uint32_t v = CSR_READ_4(sc, MYFIRST_REG_STATUS); +CSR_WRITE_4(sc, MYFIRST_REG_CTRL, MYFIRST_CTRL_ENABLE); +CSR_UPDATE_4(sc, MYFIRST_REG_STATUS, MYFIRST_STATUS_DATA_AV, 0); +``` + +Every call must be made with `sc->mtx` held. The accessors assert +this with `MYFIRST_ASSERT`. + +For barrier-aware writes: + +```c +myfirst_reg_write_barrier(sc, MYFIRST_REG_CTRL, value, + BUS_SPACE_BARRIER_WRITE); +``` + +## Observability + +| Sysctl | Purpose | +|--------------------------------------------|-------------------------------------------| +| `dev.myfirst.0.reg_*` | Read each register | +| `dev.myfirst.0.reg_ctrl_set` | Write CTRL (Stage 1 test aid) | +| `dev.myfirst.0.reg_ticker_enabled` | Toggle the SCRATCH_A ticker | +| `dev.myfirst.0.access_log_enabled` | Start/stop access logging | +| `dev.myfirst.0.access_log` | Dump the access ring buffer | + +DTrace probes (if the driver is built with `MYFIRST_DEBUG_REG_TRACE`): + +```text +# dtrace -n 'fbt::myfirst_reg_write:entry { + printf("off=%#x val=%#x", arg1, arg2); +}' +``` + +## Architecture Portability + +The simulation shortcut (tag = `X86_BUS_SPACE_MEM`, handle = kernel +VA) is x86-only. On other architectures the build fails loudly +(`#error`). Chapter 17 introduces a portable simulation; Chapter 18 +replaces the simulation with real PCI hardware, which is portable +by design. + +## Lock Order + +Hardware access does not introduce a new lock. Chapter 15's order +remains: + +```text +sc->mtx -> sc->cfg_sx -> sc->stats_cache_sx +``` + +All register access happens under `sc->mtx`. + +## Detach Ordering (hardware-relevant entries) + +The full detach ordering is documented in `LOCKING.md`. The +hardware-relevant steps are: + +1. Clear `is_attached`. +2. Drain callouts (heartbeat, watchdog, tick_source). +3. Drain tasks, including `reg_ticker_task`. +4. `myfirst_hw_detach(sc)`: frees `regs_buf`. +5. Destroy cvs, sx, semaphore, mutex. diff --git a/examples/part-04/ch16-accessing-hardware/stage4-final/Makefile b/examples/part-04/ch16-accessing-hardware/stage4-final/Makefile new file mode 100644 index 0000000..d6874a5 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/stage4-final/Makefile @@ -0,0 +1,13 @@ +# Makefile for the Chapter 16 Stage 4 myfirst driver. +# +# Adds the Chapter 16 hardware-access layer (myfirst_hw.c) to the +# Chapter 15 Stage 4 source list. The additional include flag allows +# myfirst_hw.c to pick up the shared myfirst.h header. + +KMOD= myfirst +SRCS= myfirst.c cbuf.c myfirst_hw.c +SRCS+= device_if.h bus_if.h + +CFLAGS+= -I. + +.include diff --git a/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.c b/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.c new file mode 100644 index 0000000..6c41caf --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.c @@ -0,0 +1,414 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_hw.c -- Chapter 16 Stage 4 hardware access layer. + * + * Implements: + * - Allocation/teardown of the simulated register block. + * - The bus_space(9)-based accessor functions. + * - The register ticker task. + * - The sysctl handlers for register views and the access log. + * + * The main driver in myfirst.c calls myfirst_hw_attach in attach and + * myfirst_hw_detach in detach. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" /* struct myfirst_softc, MYFIRST_LOCK, ASSERT */ +#include "myfirst_hw.h" + +/* + * Use the driver's per-module malloc type. The MALLOC_DEFINE lives in + * myfirst.c (the main driver file); this declaration just makes the + * identifier visible here. If you prefer to keep M_DEVBUF (Chapter 15's + * convention) you can simply replace M_MYFIRST with M_DEVBUF in this + * file and drop both the MALLOC_DEFINE and MALLOC_DECLARE lines. + */ +MALLOC_DECLARE(M_MYFIRST); + +/* + * Helper: convert a nanouptime timespec to a single 64-bit value for + * the access log's timestamp field. + */ +static inline uint64_t +myfirst_hw_now_ns(void) +{ + struct timespec ts; + + nanouptime(&ts); + return ((uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec); +} + +/* + * Context-tag helper. Returns a single-character code describing the + * caller's context. Used only for diagnostics; the classification is + * approximate. + */ +static inline uint8_t +myfirst_hw_context_tag(void) +{ + /* The simple version. A richer one would inspect curthread. */ + return ('d'); +} + +uint32_t +myfirst_reg_read(struct myfirst_softc *sc, bus_size_t offset) +{ + struct myfirst_hw *hw; + uint32_t value; + + MYFIRST_ASSERT(sc); + hw = sc->hw; + KASSERT(hw != NULL, + ("myfirst: reg_read with hw==NULL")); + KASSERT(offset + 4 <= hw->regs_size, + ("myfirst: register read past end: offset=%#x size=%zu", + (unsigned)offset, hw->regs_size)); + + value = bus_space_read_4(hw->regs_tag, hw->regs_handle, offset); + + if (hw->access_log_enabled) { + unsigned int idx; + struct myfirst_access_log_entry *e; + + idx = hw->access_log_head++ % MYFIRST_ACCESS_LOG_SIZE; + e = &hw->access_log[idx]; + e->timestamp_ns = myfirst_hw_now_ns(); + e->value = value; + e->offset = offset; + e->is_write = 0; + e->width = 4; + e->context_tag = myfirst_hw_context_tag(); + } + + return (value); +} + +void +myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, uint32_t value) +{ + struct myfirst_hw *hw; + + MYFIRST_ASSERT(sc); + hw = sc->hw; + KASSERT(hw != NULL, + ("myfirst: reg_write with hw==NULL")); + KASSERT(offset + 4 <= hw->regs_size, + ("myfirst: register write past end: offset=%#x size=%zu", + (unsigned)offset, hw->regs_size)); + + bus_space_write_4(hw->regs_tag, hw->regs_handle, offset, value); + + if (hw->access_log_enabled) { + unsigned int idx; + struct myfirst_access_log_entry *e; + + idx = hw->access_log_head++ % MYFIRST_ACCESS_LOG_SIZE; + e = &hw->access_log[idx]; + e->timestamp_ns = myfirst_hw_now_ns(); + e->value = value; + e->offset = offset; + e->is_write = 1; + e->width = 4; + e->context_tag = myfirst_hw_context_tag(); + } +} + +void +myfirst_reg_update(struct myfirst_softc *sc, bus_size_t offset, + uint32_t clear_mask, uint32_t set_mask) +{ + uint32_t v; + + MYFIRST_ASSERT(sc); + v = myfirst_reg_read(sc, offset); + v &= ~clear_mask; + v |= set_mask; + myfirst_reg_write(sc, offset, v); +} + +void +myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, + uint32_t value, int flags) +{ + struct myfirst_hw *hw; + + MYFIRST_ASSERT(sc); + hw = sc->hw; + myfirst_reg_write(sc, offset, value); + bus_space_barrier(hw->regs_tag, hw->regs_handle, 0, hw->regs_size, + flags); +} + +/* + * The register ticker task: increments SCRATCH_A per invocation. + * Enqueued from the tick_source callout when reg_ticker_enabled is + * non-zero. + */ +static void +myfirst_hw_ticker_cb(void *arg, int pending __unused) +{ + struct myfirst_softc *sc = arg; + + if (!myfirst_is_attached(sc)) + return; + + MYFIRST_LOCK(sc); + if (sc->hw != NULL && sc->hw->regs_buf != NULL) { + uint32_t v = CSR_READ_4(sc, MYFIRST_REG_SCRATCH_A); + CSR_WRITE_4(sc, MYFIRST_REG_SCRATCH_A, v + 1); + } + MYFIRST_UNLOCK(sc); +} + +int +myfirst_hw_attach(struct myfirst_softc *sc) +{ + struct myfirst_hw *hw; + + hw = malloc(sizeof(*hw), M_MYFIRST, M_WAITOK | M_ZERO); + + hw->regs_size = MYFIRST_REG_SIZE; + hw->regs_buf = malloc(hw->regs_size, M_MYFIRST, M_WAITOK | M_ZERO); +#if defined(__amd64__) || defined(__i386__) + hw->regs_tag = X86_BUS_SPACE_MEM; +#else +#error "Chapter 16 simulation path supports x86 only; see chapter text." +#endif + hw->regs_handle = (bus_space_handle_t)(uintptr_t)hw->regs_buf; + + /* Initialise the task. */ + TASK_INIT(&hw->reg_ticker_task, 0, myfirst_hw_ticker_cb, sc); + + /* + * Initialise the fixed registers. We do this outside the mutex + * because nothing else can see the hw struct yet. + */ + bus_space_write_4(hw->regs_tag, hw->regs_handle, + MYFIRST_REG_DEVICE_ID, MYFIRST_DEVICE_ID_VALUE); + bus_space_write_4(hw->regs_tag, hw->regs_handle, + MYFIRST_REG_FIRMWARE_REV, MYFIRST_FW_REV_VALUE); + bus_space_write_4(hw->regs_tag, hw->regs_handle, + MYFIRST_REG_STATUS, MYFIRST_STATUS_READY); + + sc->hw = hw; + device_printf(sc->dev, + "hardware layer attached: %zu bytes at %p\n", + hw->regs_size, hw->regs_buf); + return (0); +} + +void +myfirst_hw_detach(struct myfirst_softc *sc) +{ + struct myfirst_hw *hw; + + if (sc->hw == NULL) + return; + + hw = sc->hw; + + /* + * Drain the ticker task before freeing anything it touches. + * The main detach has already cleared is_attached, which stops + * the tick_source callout from enqueuing new work. Anything + * already in flight completes here. + */ + if (sc->tq != NULL) + taskqueue_drain(sc->tq, &hw->reg_ticker_task); + + /* Clear sc->hw before freeing so concurrent readers see NULL. */ + sc->hw = NULL; + + if (hw->regs_buf != NULL) { + free(hw->regs_buf, M_MYFIRST); + hw->regs_buf = NULL; + } + free(hw, M_MYFIRST); + + device_printf(sc->dev, "hardware layer detached\n"); +} + +/* + * Sysctl handler for read-only register views. arg1 is the softc, + * arg2 is the register offset. + */ +static int +myfirst_hw_sysctl_reg(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + bus_size_t offset = arg2; + uint32_t value; + + if (!myfirst_is_attached(sc)) + return (ENODEV); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL) { + MYFIRST_UNLOCK(sc); + return (ENODEV); + } + value = CSR_READ_4(sc, offset); + MYFIRST_UNLOCK(sc); + + return (sysctl_handle_int(oidp, &value, 0, req)); +} + +/* + * Sysctl handler for writeable register views. arg1 is the softc, + * arg2 is the register offset. + */ +static int +myfirst_hw_sysctl_reg_write(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + bus_size_t offset = arg2; + uint32_t oldval, newval; + int error; + + if (!myfirst_is_attached(sc)) + return (ENODEV); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL) { + MYFIRST_UNLOCK(sc); + return (ENODEV); + } + oldval = CSR_READ_4(sc, offset); + MYFIRST_UNLOCK(sc); + + newval = oldval; + error = sysctl_handle_int(oidp, &newval, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL) { + MYFIRST_UNLOCK(sc); + return (ENODEV); + } + CSR_WRITE_4(sc, offset, newval); + MYFIRST_UNLOCK(sc); + + return (0); +} + +/* + * Sysctl handler for the access log dump. Walks the ring and formats + * each entry as a line. + */ +static int +myfirst_hw_sysctl_access_log(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + struct sbuf *sb; + unsigned int i, start; + int error; + + sb = sbuf_new_for_sysctl(NULL, NULL, + 256 * MYFIRST_ACCESS_LOG_SIZE, req); + if (sb == NULL) + return (ENOMEM); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL) { + MYFIRST_UNLOCK(sc); + sbuf_printf(sb, "(hardware layer not attached)\n"); + error = sbuf_finish(sb); + sbuf_delete(sb); + return (error); + } + + start = sc->hw->access_log_head; + for (i = 0; i < MYFIRST_ACCESS_LOG_SIZE; i++) { + unsigned int idx = (start + i) % MYFIRST_ACCESS_LOG_SIZE; + struct myfirst_access_log_entry *e = &sc->hw->access_log[idx]; + + if (e->timestamp_ns == 0) + continue; + sbuf_printf(sb, + "%16ju ns %s%1u off=%#04x val=%#010x ctx=%c\n", + (uintmax_t)e->timestamp_ns, + e->is_write ? "W" : "R", (unsigned)e->width, + (unsigned)e->offset, e->value, e->context_tag); + } + MYFIRST_UNLOCK(sc); + + error = sbuf_finish(sb); + sbuf_delete(sb); + return (error); +} + +/* + * Register the Chapter 16 sysctls. Called from myfirst_attach after + * the sysctl tree and context are ready. + */ +void +myfirst_hw_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid_list *kids = SYSCTL_CHILDREN(sc->sysctl_tree); + +#define ADD_REG_RD(name, offset, desc) \ + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, name, \ + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, \ + sc, offset, myfirst_hw_sysctl_reg, "IU", desc) + + ADD_REG_RD("reg_ctrl", MYFIRST_REG_CTRL, + "Control register (read-only view)"); + ADD_REG_RD("reg_status", MYFIRST_REG_STATUS, + "Status register (read-only view)"); + ADD_REG_RD("reg_data_in", MYFIRST_REG_DATA_IN, + "DATA_IN register (read-only view)"); + ADD_REG_RD("reg_data_out", MYFIRST_REG_DATA_OUT, + "DATA_OUT register (read-only view)"); + ADD_REG_RD("reg_intr_mask", MYFIRST_REG_INTR_MASK, + "INTR_MASK register (read-only view)"); + ADD_REG_RD("reg_intr_status", MYFIRST_REG_INTR_STATUS, + "INTR_STATUS register (read-only view)"); + ADD_REG_RD("reg_device_id", MYFIRST_REG_DEVICE_ID, + "DEVICE_ID register (read-only)"); + ADD_REG_RD("reg_firmware_rev", MYFIRST_REG_FIRMWARE_REV, + "FIRMWARE_REV register (read-only)"); + ADD_REG_RD("reg_scratch_a", MYFIRST_REG_SCRATCH_A, + "SCRATCH_A register (read-only view)"); + ADD_REG_RD("reg_scratch_b", MYFIRST_REG_SCRATCH_B, + "SCRATCH_B register (read-only view)"); + +#undef ADD_REG_RD + + /* Writeable CTRL register for Stage 1 demonstration. */ + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "reg_ctrl_set", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, MYFIRST_REG_CTRL, myfirst_hw_sysctl_reg_write, "IU", + "Control register (writeable, Stage 1 test aid)"); + + /* Ticker enable. */ + SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "reg_ticker_enabled", + CTLFLAG_RW, &sc->hw->reg_ticker_enabled, 0, + "Enable the periodic SCRATCH_A ticker"); + + /* Access log controls. */ + SYSCTL_ADD_BOOL(ctx, kids, OID_AUTO, "access_log_enabled", + CTLFLAG_RW, &sc->hw->access_log_enabled, 0, + "Enable register access ring-buffer logging"); + + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "access_log", + CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_hw_sysctl_access_log, "A", + "Dump the register access ring buffer"); +} diff --git a/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.h b/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.h new file mode 100644 index 0000000..4dbf743 --- /dev/null +++ b/examples/part-04/ch16-accessing-hardware/stage4-final/myfirst_hw.h @@ -0,0 +1,128 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_hw.h -- Chapter 16 Stage 4 simulated hardware interface. + * + * Adds hardware-access layer to the Chapter 15 Stage 4 driver: + * - Register offset and bit-mask definitions. + * - A struct myfirst_hw grouping hardware state. + * - API for attach/detach of the hardware layer. + * - Accessor helpers (myfirst_reg_read, myfirst_reg_write, ...). + * - CSR_READ_4, CSR_WRITE_4, CSR_UPDATE_4 macros. + */ + +#ifndef _MYFIRST_HW_H_ +#define _MYFIRST_HW_H_ + +#include +#include +#include +#include + +/* + * Register offsets for the simulated myfirst widget. Total register + * block size is 64 bytes, though only offsets 0x00..0x27 are + * currently defined; the remaining bytes are reserved for Chapter 17 + * expansion. + */ +#define MYFIRST_REG_CTRL 0x00 /* 32-bit, R/W: control */ +#define MYFIRST_REG_STATUS 0x04 /* 32-bit, R/W: status */ +#define MYFIRST_REG_DATA_IN 0x08 /* 32-bit, R/W: input data */ +#define MYFIRST_REG_DATA_OUT 0x0c /* 32-bit, R/W: output data */ +#define MYFIRST_REG_INTR_MASK 0x10 /* 32-bit, R/W: intr enables */ +#define MYFIRST_REG_INTR_STATUS 0x14 /* 32-bit, R/W: intr flags */ +#define MYFIRST_REG_DEVICE_ID 0x18 /* 32-bit, R-only: device id */ +#define MYFIRST_REG_FIRMWARE_REV 0x1c /* 32-bit, R-only: fw rev */ +#define MYFIRST_REG_SCRATCH_A 0x20 /* 32-bit, R/W: scratch A */ +#define MYFIRST_REG_SCRATCH_B 0x24 /* 32-bit, R/W: scratch B */ + +#define MYFIRST_REG_SIZE 0x40 /* total 64 bytes */ + +/* CTRL register bits. */ +#define MYFIRST_CTRL_ENABLE 0x00000001u /* bit 0: enable */ +#define MYFIRST_CTRL_RESET 0x00000002u /* bit 1: reset */ +#define MYFIRST_CTRL_MODE_MASK 0x000000f0u /* bits 4..7: mode */ +#define MYFIRST_CTRL_MODE_SHIFT 4 +#define MYFIRST_CTRL_LOOPBACK 0x00000100u /* bit 8: loopback */ + +/* STATUS register bits. */ +#define MYFIRST_STATUS_READY 0x00000001u /* bit 0: ready */ +#define MYFIRST_STATUS_BUSY 0x00000002u /* bit 1: busy */ +#define MYFIRST_STATUS_ERROR 0x00000004u /* bit 2: error latch */ +#define MYFIRST_STATUS_DATA_AV 0x00000008u /* bit 3: data in out */ + +/* INTR_MASK / INTR_STATUS bits. */ +#define MYFIRST_INTR_DATA_AV 0x00000001u /* bit 0: data avail. */ +#define MYFIRST_INTR_ERROR 0x00000002u /* bit 1: error */ +#define MYFIRST_INTR_COMPLETE 0x00000004u /* bit 2: op complete */ + +/* Fixed identifier values. */ +#define MYFIRST_DEVICE_ID_VALUE 0x4D594649u /* 'MYFI' LE */ +#define MYFIRST_FW_REV_MAJOR 1 +#define MYFIRST_FW_REV_MINOR 0 +#define MYFIRST_FW_REV_VALUE \ + ((MYFIRST_FW_REV_MAJOR << 16) | MYFIRST_FW_REV_MINOR) + +/* Access log. */ +#define MYFIRST_ACCESS_LOG_SIZE 64 + +struct myfirst_access_log_entry { + uint64_t timestamp_ns; + uint32_t value; + bus_size_t offset; + uint8_t is_write; + uint8_t width; + uint8_t context_tag; + uint8_t _pad; +}; + +/* + * Hardware state, grouped. A single allocation per softc; sc->hw + * points at this struct when the hardware layer is attached. + */ +struct myfirst_hw { + uint8_t *regs_buf; + size_t regs_size; + bus_space_tag_t regs_tag; + bus_space_handle_t regs_handle; + + struct task reg_ticker_task; + int reg_ticker_enabled; + + struct myfirst_access_log_entry access_log[MYFIRST_ACCESS_LOG_SIZE]; + unsigned int access_log_head; + bool access_log_enabled; +}; + +/* Forward declaration. */ +struct myfirst_softc; + +/* Attach/detach the hardware layer. Called from the main driver. */ +int myfirst_hw_attach(struct myfirst_softc *sc); +void myfirst_hw_detach(struct myfirst_softc *sc); + +/* Register sysctls for the hardware layer. */ +void myfirst_hw_add_sysctls(struct myfirst_softc *sc); + +/* Accessor functions. Must be called with sc->mtx held. */ +uint32_t myfirst_reg_read(struct myfirst_softc *sc, bus_size_t offset); +void myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, + uint32_t value); +void myfirst_reg_update(struct myfirst_softc *sc, bus_size_t offset, + uint32_t clear_mask, uint32_t set_mask); +void myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, + uint32_t value, int flags); + +/* + * CSR_* macros matching the idiom used in production FreeBSD drivers + * such as /usr/src/sys/dev/ale/if_alevar.h. Short names at call sites, + * standard semantics. + */ +#define CSR_READ_4(sc, off) myfirst_reg_read((sc), (off)) +#define CSR_WRITE_4(sc, off, val) myfirst_reg_write((sc), (off), (val)) +#define CSR_UPDATE_4(sc, off, clear, set) \ + myfirst_reg_update((sc), (off), (clear), (set)) + +#endif /* _MYFIRST_HW_H_ */ diff --git a/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/Makefile b/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/Makefile new file mode 100644 index 0000000..e4cb325 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/Makefile @@ -0,0 +1,10 @@ +# Makefile for the Chapter 17 stand-alone hwsim2 practice module. +# +# Builds a minimal kernel module that demonstrates callout-driven +# hardware simulation: an oscillating sensor register, a delayed +# command completion, and optional error injection. + +KMOD= hwsim2 +SRCS= hwsim2.c + +.include diff --git a/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/hwsim2.c b/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/hwsim2.c new file mode 100644 index 0000000..0c0140e --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/hwsim2-standalone/hwsim2.c @@ -0,0 +1,255 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * hwsim2.c -- Chapter 17 stand-alone simulation practice module. + * + * Demonstrates callout-driven hardware simulation without the myfirst + * driver. Exposes: + * - a SENSOR value that oscillates, updated every 100 ms + * - a simulated command cycle with a configurable delay + * - a fault-injection flag + * - sysctls for control and observation + * + * This module is x86-specific. See the discussion in Chapter 16 about + * the simulation shortcut for bus_space_tag_t. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(__amd64__) && !defined(__i386__) +#error "hwsim2 simulation supports x86 only" +#endif + +MALLOC_DEFINE(M_HWSIM2, "hwsim2", "hwsim2 simulation module"); + +#define HWSIM2_SIZE 0x40 +#define HWSIM2_REG_SENSOR 0x00 +#define HWSIM2_REG_CMD_DATA 0x04 +#define HWSIM2_REG_CMD_GO 0x08 +#define HWSIM2_REG_RESULT 0x0c +#define HWSIM2_REG_STATUS 0x10 + +#define HWSIM2_STATUS_BUSY 0x00000001u +#define HWSIM2_STATUS_DONE 0x00000002u +#define HWSIM2_STATUS_ERROR 0x00000004u + +static uint8_t *hwsim2_buf; +static bus_space_tag_t hwsim2_tag; +static bus_space_handle_t hwsim2_handle; + +static struct mtx hwsim2_mtx; +static struct callout hwsim2_sensor_co; +static struct callout hwsim2_cmd_co; + +static uint32_t hwsim2_sensor_tick; +static uint32_t hwsim2_sensor_baseline = 0x1000; +static uint32_t hwsim2_delay_ms = 500; +static bool hwsim2_inject_error; +static bool hwsim2_running; + +static void +hwsim2_sensor_cb(void *arg __unused) +{ + uint32_t phase, value; + + mtx_assert(&hwsim2_mtx, MA_OWNED); + + if (!hwsim2_running) + return; + + hwsim2_sensor_tick++; + phase = hwsim2_sensor_tick & 0x7; + value = hwsim2_sensor_baseline + + ((phase < 4) ? phase : (7 - phase)) * 16; + + bus_space_write_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_SENSOR, value); + + callout_reset_sbt(&hwsim2_sensor_co, + 100 * SBT_1MS, 0, hwsim2_sensor_cb, NULL, 0); +} + +static void +hwsim2_cmd_cb(void *arg __unused) +{ + uint32_t data, status; + + mtx_assert(&hwsim2_mtx, MA_OWNED); + + if (!hwsim2_running) + return; + + data = bus_space_read_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_CMD_DATA); + bus_space_write_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_RESULT, data); + + status = HWSIM2_STATUS_DONE; + if (hwsim2_inject_error) { + status |= HWSIM2_STATUS_ERROR; + hwsim2_inject_error = false; + } + bus_space_write_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_STATUS, status); +} + +static int +hwsim2_sysctl_sensor(SYSCTL_HANDLER_ARGS) +{ + uint32_t value; + + mtx_lock(&hwsim2_mtx); + value = bus_space_read_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_SENSOR); + mtx_unlock(&hwsim2_mtx); + return (sysctl_handle_int(oidp, &value, 0, req)); +} + +static int +hwsim2_sysctl_result(SYSCTL_HANDLER_ARGS) +{ + uint32_t value; + + mtx_lock(&hwsim2_mtx); + value = bus_space_read_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_RESULT); + mtx_unlock(&hwsim2_mtx); + return (sysctl_handle_int(oidp, &value, 0, req)); +} + +static int +hwsim2_sysctl_status(SYSCTL_HANDLER_ARGS) +{ + uint32_t value; + + mtx_lock(&hwsim2_mtx); + value = bus_space_read_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_STATUS); + mtx_unlock(&hwsim2_mtx); + return (sysctl_handle_int(oidp, &value, 0, req)); +} + +static int +hwsim2_sysctl_do_command(SYSCTL_HANDLER_ARGS) +{ + uint32_t value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + mtx_lock(&hwsim2_mtx); + bus_space_write_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_CMD_DATA, value); + bus_space_write_4(hwsim2_tag, hwsim2_handle, + HWSIM2_REG_STATUS, HWSIM2_STATUS_BUSY); + callout_reset_sbt(&hwsim2_cmd_co, + hwsim2_delay_ms * SBT_1MS, 0, hwsim2_cmd_cb, NULL, 0); + mtx_unlock(&hwsim2_mtx); + return (0); +} + +static SYSCTL_NODE(_dev, OID_AUTO, hwsim2, + CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, "hwsim2 simulation module"); + +static int +hwsim2_modevent(module_t mod, int event, void *arg) +{ + switch (event) { + case MOD_LOAD: + hwsim2_buf = malloc(HWSIM2_SIZE, M_HWSIM2, + M_WAITOK | M_ZERO); + hwsim2_tag = X86_BUS_SPACE_MEM; + hwsim2_handle = (bus_space_handle_t)(uintptr_t)hwsim2_buf; + + mtx_init(&hwsim2_mtx, "hwsim2", NULL, MTX_DEF); + callout_init_mtx(&hwsim2_sensor_co, &hwsim2_mtx, 0); + callout_init_mtx(&hwsim2_cmd_co, &hwsim2_mtx, 0); + + hwsim2_running = true; + + mtx_lock(&hwsim2_mtx); + callout_reset_sbt(&hwsim2_sensor_co, + 100 * SBT_1MS, 0, hwsim2_sensor_cb, NULL, 0); + mtx_unlock(&hwsim2_mtx); + + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "sensor", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, hwsim2_sysctl_sensor, "IU", + "Oscillating sensor value"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "result", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, hwsim2_sysctl_result, "IU", + "Last command result"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "status", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, hwsim2_sysctl_status, "IU", + "Command status register"); + SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "do_command", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + NULL, 0, hwsim2_sysctl_do_command, "IU", + "Trigger a simulated command with this data"); + SYSCTL_ADD_UINT(NULL, + SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "delay_ms", CTLFLAG_RW, + &hwsim2_delay_ms, 0, + "Command processing delay in ms"); + SYSCTL_ADD_BOOL(NULL, + SYSCTL_STATIC_CHILDREN(_dev_hwsim2), + OID_AUTO, "inject_error", CTLFLAG_RW, + &hwsim2_inject_error, 0, + "Set to true to inject an error on next command"); + + printf("hwsim2: loaded, %d bytes at %p\n", + HWSIM2_SIZE, hwsim2_buf); + return (0); + + case MOD_UNLOAD: + mtx_lock(&hwsim2_mtx); + hwsim2_running = false; + callout_stop(&hwsim2_sensor_co); + callout_stop(&hwsim2_cmd_co); + mtx_unlock(&hwsim2_mtx); + + callout_drain(&hwsim2_sensor_co); + callout_drain(&hwsim2_cmd_co); + + mtx_destroy(&hwsim2_mtx); + + if (hwsim2_buf != NULL) { + free(hwsim2_buf, M_HWSIM2); + hwsim2_buf = NULL; + } + printf("hwsim2: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t hwsim2_mod = { + "hwsim2", + hwsim2_modevent, + NULL +}; + +DECLARE_MODULE(hwsim2, hwsim2_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(hwsim2, 1); diff --git a/examples/part-04/ch17-simulating-hardware/labs/full_regression_ch17.sh b/examples/part-04/ch17-simulating-hardware/labs/full_regression_ch17.sh new file mode 100755 index 0000000..858c501 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/full_regression_ch17.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# full_regression_ch17.sh -- Chapter 17 regression suite. +# +# Runs every Chapter 17 test script in sequence. Exits non-zero if any +# test fails. Intended to be run after loading the Chapter 17 Stage 5 +# driver (myfirst at version 1.0-simulated). + +set -e + +DIR=$(dirname "$0") + +TESTS=' +sim_sensor_oscillates.sh +sim_command_cycle.sh +sim_timeout_fault.sh +sim_error_fault.sh +sim_stuck_busy_fault.sh +sim_mixed_faults_under_load.sh +sim_sensor_during_load.sh +' + +FAILED=0 + +for t in ${TESTS}; do + echo "--- Running ${t}" + if ! "${DIR}/${t}"; then + echo "--- FAILED: ${t}" + FAILED=$((FAILED + 1)) + fi +done + +if [ "${FAILED}" -ne 0 ]; then + echo "--- ${FAILED} test(s) failed" >&2 + exit 1 +fi + +echo "--- All Chapter 17 regression tests passed" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_command_cycle.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_command_cycle.sh new file mode 100755 index 0000000..ab453db --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_command_cycle.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# sim_command_cycle.sh -- Chapter 17 Lab: command cycle works under load. +# +# Runs 50 write commands, then checks that cmd_successes and +# reg_op_counter both grew by at least 50. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present. Load myfirst.ko first." >&2 + exit 2 +fi + +# Configure fast commands and clean counters. +sysctl -q "${DEV}.reg_delay_ms_set=20" >/dev/null + +before_succ=$(sysctl -n "${DEV}.cmd_successes") +before_op=$(sysctl -n "${DEV}.reg_op_counter") + +# 50 single-byte writes. +for i in $(jot 50); do + echo -n "X" > ${DEVNODE} +done + +after_succ=$(sysctl -n "${DEV}.cmd_successes") +after_op=$(sysctl -n "${DEV}.reg_op_counter") + +delta_succ=$((after_succ - before_succ)) +delta_op=$((after_op - before_op)) + +sysctl -q "${DEV}.reg_delay_ms_set=500" >/dev/null + +if [ "${delta_succ}" -lt 50 ]; then + echo "FAIL: cmd_successes grew by ${delta_succ}, expected >= 50" >&2 + exit 1 +fi + +if [ "${delta_op}" -lt 50 ]; then + echo "FAIL: op_counter grew by ${delta_op}, expected >= 50" >&2 + exit 1 +fi + +echo "PASS: command cycle OK. successes=+${delta_succ} ops=+${delta_op}" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_error_fault.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_error_fault.sh new file mode 100755 index 0000000..44208d7 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_error_fault.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# sim_error_fault.sh -- Chapter 17 Lab: error fault detection. +# +# Enables the error fault at 25% probability, runs 40 writes, +# verifies cmd_errors grew by roughly the expected number. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present." >&2 + exit 2 +fi + +before=$(sysctl -n "${DEV}.cmd_errors") + +sysctl -q "${DEV}.reg_fault_mask_set=4" >/dev/null +sysctl -q "${DEV}.reg_fault_prob_set=2500" >/dev/null +sysctl -q "${DEV}.reg_delay_ms_set=20" >/dev/null + +ok=0 +err=0 +for i in $(jot 40); do + if echo -n "X" > ${DEVNODE} 2>/dev/null; then + ok=$((ok + 1)) + else + err=$((err + 1)) + fi +done + +after=$(sysctl -n "${DEV}.cmd_errors") +delta=$((after - before)) + +sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null +sysctl -q "${DEV}.reg_fault_prob_set=0" >/dev/null +sysctl -q "${DEV}.reg_delay_ms_set=500" >/dev/null + +if [ "${delta}" -lt 3 ] || [ "${delta}" -gt 25 ]; then + echo "FAIL: cmd_errors grew by ${delta}, expected ~10" >&2 + exit 1 +fi + +echo "PASS: error fault detected. user: ${err} errors, counter: +${delta}" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_mixed_faults_under_load.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_mixed_faults_under_load.sh new file mode 100755 index 0000000..2c68bb8 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_mixed_faults_under_load.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# sim_mixed_faults_under_load.sh -- Chapter 17 Lab: mixed faults under load. +# +# Enables TIMEOUT and ERROR faults at 2% probability. Runs 8 parallel +# workers each doing 100 commands. Verifies that a reasonable number +# of faults fired and the driver made progress overall. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present." >&2 + exit 2 +fi + +before_succ=$(sysctl -n "${DEV}.cmd_successes") +before_fault=$(sysctl -n "${DEV}.fault_injected") + +sysctl -q "${DEV}.reg_fault_mask_set=5" >/dev/null # TIMEOUT | ERROR +sysctl -q "${DEV}.reg_fault_prob_set=200" >/dev/null # 2% +sysctl -q "${DEV}.reg_delay_ms_set=10" >/dev/null +sysctl -q "${DEV}.cmd_timeout_ms=100" >/dev/null + +for i in 1 2 3 4 5 6 7 8; do + ( + for j in $(jot 100); do + echo -n "X" > ${DEVNODE} 2>/dev/null || true + done + ) & +done +wait + +after_succ=$(sysctl -n "${DEV}.cmd_successes") +after_fault=$(sysctl -n "${DEV}.fault_injected") + +sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null +sysctl -q "${DEV}.reg_fault_prob_set=0" >/dev/null +sysctl -q "${DEV}.reg_delay_ms_set=500" >/dev/null +sysctl -q "${DEV}.cmd_timeout_ms=2000" >/dev/null + +delta_succ=$((after_succ - before_succ)) +delta_fault=$((after_fault - before_fault)) + +# Most commands should succeed. +if [ "${delta_succ}" -lt 500 ]; then + echo "FAIL: only ${delta_succ} commands succeeded (expected >=500)" >&2 + exit 1 +fi + +# At least a few faults should have fired. +if [ "${delta_fault}" -lt 3 ]; then + echo "FAIL: only ${delta_fault} faults injected (expected ~16)" >&2 + exit 1 +fi + +echo "PASS: mixed-fault load test. successes=+${delta_succ} faults=+${delta_fault}" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_during_load.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_during_load.sh new file mode 100755 index 0000000..f0c8089 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_during_load.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# sim_sensor_during_load.sh -- Chapter 17 Lab: sensor updates under load. +# +# Starts a heavy command load in the background and verifies the sensor +# register continues to receive autonomous updates. Fails if the sensor +# value stops changing during the load. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present." >&2 + exit 2 +fi + +sysctl -q "${DEV}.reg_delay_ms_set=5" >/dev/null + +# Background load: many writes for ~5 seconds. +( + for i in $(jot 1000); do + echo -n "X" > ${DEVNODE} 2>/dev/null || true + done +) & +LOADPID=$! + +# Sample sensor a few times while load runs. +prev="" +changes=0 +for i in $(jot 10); do + cur=$(sysctl -n "${DEV}.reg_sensor") + if [ -n "${prev}" ] && [ "${cur}" != "${prev}" ]; then + changes=$((changes + 1)) + fi + prev="${cur}" + sleep 0.3 +done + +# Wait for load to finish. +wait ${LOADPID} 2>/dev/null || true + +sysctl -q "${DEV}.reg_delay_ms_set=500" >/dev/null + +if [ "${changes}" -lt 3 ]; then + echo "FAIL: sensor only changed ${changes} times under load" >&2 + exit 1 +fi + +echo "PASS: sensor updated ${changes} times under load" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_oscillates.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_oscillates.sh new file mode 100755 index 0000000..fa2e6cd --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_sensor_oscillates.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# sim_sensor_oscillates.sh -- Chapter 17 Lab: sensor breathes. +# +# Confirms that the SENSOR register value changes autonomously over +# time. Samples the register several times with sleeps between samples +# and fails if all samples are identical. + +set -e + +DEV=dev.myfirst.0 + +if ! sysctl -q "${DEV}" >/dev/null 2>&1; then + echo "FAIL: ${DEV} not present. Load myfirst.ko first." >&2 + exit 2 +fi + +sensor_value() { + sysctl -n "${DEV}.reg_sensor" +} + +first=$(sensor_value) +sleep 0.5 +second=$(sensor_value) +sleep 0.5 +third=$(sensor_value) + +if [ "${first}" = "${second}" ] && [ "${second}" = "${third}" ]; then + echo "FAIL: sensor value did not change: ${first}" >&2 + exit 1 +fi + +echo "PASS: sensor oscillates. Samples: ${first} ${second} ${third}" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_stuck_busy_fault.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_stuck_busy_fault.sh new file mode 100755 index 0000000..d83641c --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_stuck_busy_fault.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# sim_stuck_busy_fault.sh -- Chapter 17 Lab: STUCK_BUSY latch. +# +# Enables the stuck-busy fault, verifies a write times out on +# wait_for_ready, clears the fault, verifies a subsequent write +# succeeds. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present." >&2 + exit 2 +fi + +before=$(sysctl -n "${DEV}.cmd_rdy_timeouts") + +sysctl -q "${DEV}.reg_fault_mask_set=8" >/dev/null +sysctl -q "${DEV}.rdy_timeout_ms=200" >/dev/null + +# Wait for the busy callout to assert BUSY. +sleep 0.2 + +# The write must fail (on wait_for_ready). +if echo -n "X" > ${DEVNODE} 2>/dev/null; then + echo "FAIL: write succeeded despite STUCK_BUSY" >&2 + sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null + sysctl -q "${DEV}.rdy_timeout_ms=100" >/dev/null + exit 1 +fi + +after=$(sysctl -n "${DEV}.cmd_rdy_timeouts") + +# Clear the fault and wait for BUSY to naturally clear. +sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null +sleep 0.2 +sysctl -q "${DEV}.rdy_timeout_ms=100" >/dev/null + +# The write should now succeed. +if ! echo -n "X" > ${DEVNODE} 2>/dev/null; then + echo "FAIL: write still failed after clearing STUCK_BUSY" >&2 + exit 1 +fi + +if [ "${after}" -le "${before}" ]; then + echo "FAIL: cmd_rdy_timeouts did not grow" >&2 + exit 1 +fi + +echo "PASS: STUCK_BUSY detected, recovered (rdy_timeouts=${after})" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/labs/sim_timeout_fault.sh b/examples/part-04/ch17-simulating-hardware/labs/sim_timeout_fault.sh new file mode 100755 index 0000000..3913cb4 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/labs/sim_timeout_fault.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# sim_timeout_fault.sh -- Chapter 17 Lab: timeout fault and recovery. +# +# Enables the timeout fault at 100% probability, issues a write, +# verifies the driver reports an error, counters increment, and a +# subsequent write after clearing the fault succeeds. + +set -e + +DEV=dev.myfirst.0 +DEVNODE=/dev/myfirst0 + +if [ ! -c "${DEVNODE}" ]; then + echo "FAIL: ${DEVNODE} not present." >&2 + exit 2 +fi + +before_to=$(sysctl -n "${DEV}.cmd_data_timeouts") +before_rec=$(sysctl -n "${DEV}.cmd_recoveries" 2>/dev/null || echo 0) + +# Enable timeout fault at 100%. +sysctl -q "${DEV}.reg_fault_mask_set=1" >/dev/null +sysctl -q "${DEV}.reg_fault_prob_set=10000" >/dev/null +sysctl -q "${DEV}.cmd_timeout_ms=200" >/dev/null + +# This write must fail. +if echo -n "X" > ${DEVNODE} 2>/dev/null; then + echo "FAIL: write succeeded when a timeout fault was enabled" >&2 + sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null + sysctl -q "${DEV}.reg_fault_prob_set=0" >/dev/null + sysctl -q "${DEV}.cmd_timeout_ms=2000" >/dev/null + exit 1 +fi + +after_to=$(sysctl -n "${DEV}.cmd_data_timeouts") + +# Clear the fault. +sysctl -q "${DEV}.reg_fault_mask_set=0" >/dev/null +sysctl -q "${DEV}.reg_fault_prob_set=0" >/dev/null +sysctl -q "${DEV}.cmd_timeout_ms=2000" >/dev/null + +# This write should succeed. +if ! echo -n "X" > ${DEVNODE} 2>/dev/null; then + echo "FAIL: write still failed after clearing the fault" >&2 + exit 1 +fi + +if [ "${after_to}" -le "${before_to}" ]; then + echo "FAIL: cmd_data_timeouts did not grow" >&2 + exit 1 +fi + +echo "PASS: timeout fault handled and recovered (timeouts=${after_to})" +exit 0 diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/HARDWARE.md b/examples/part-04/ch17-simulating-hardware/stage5-final/HARDWARE.md new file mode 100644 index 0000000..a531b30 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/HARDWARE.md @@ -0,0 +1,168 @@ +# myfirst Hardware Interface + +## Version + +1.0-simulated. Chapter 17 complete. + +## Register Block + +- Size: 64 bytes (`MYFIRST_REG_SIZE`). +- Access: 32-bit reads and writes on 32-bit-aligned offsets. +- Storage: `malloc(9)`, `M_WAITOK|M_ZERO`, allocated in + `myfirst_hw_attach`, freed in `myfirst_hw_detach`. +- `bus_space_tag_t`: `X86_BUS_SPACE_MEM` (x86 only, simulation shortcut). +- `bus_space_handle_t`: pointer to the malloc'd block. + +## API + +All register access goes through: + +- `CSR_READ_4(sc, off)`: read a 32-bit register. +- `CSR_WRITE_4(sc, off, val)`: write a 32-bit register. +- `CSR_UPDATE_4(sc, off, clear, set)`: read-modify-write. + +The driver's main mutex (`sc->mtx`) must be held for every register +access. Accessor macros assert this via `MYFIRST_ASSERT`. + +## Register Map + +| Offset | Width | Name | Access | Default | Notes | +|--------|--------|-----------------|------------|----------------|------------------------------------------| +| 0x00 | 32 bit | CTRL | R/W | 0 | Control; GO bit triggers command. | +| 0x04 | 32 bit | STATUS | R/W | 0x1 (READY) | Status; dynamic Ch17 updates. | +| 0x08 | 32 bit | DATA_IN | R/W | 0 | Command input data. | +| 0x0c | 32 bit | DATA_OUT | R/W | 0 | Command output data. | +| 0x10 | 32 bit | INTR_MASK | R/W | 0 | Interrupt enables. | +| 0x14 | 32 bit | INTR_STATUS | R/W | 0 | Pending interrupts (RC in real HW). | +| 0x18 | 32 bit | DEVICE_ID | RO | 0x4D594649 | Fixed identifier. | +| 0x1c | 32 bit | FIRMWARE_REV | RO | 0x00010000 | Fixed FW rev (major<<16|minor). | +| 0x20 | 32 bit | SCRATCH_A | R/W | 0 | Scratch register. | +| 0x24 | 32 bit | SCRATCH_B | R/W | 0 | Scratch register. | +| 0x28 | 32 bit | SENSOR | RO (dyn) | 0 | Oscillating value (Ch17 callout). | +| 0x2c | 32 bit | SENSOR_CONFIG | R/W | 0x00400064 | Low 16: interval ms; high 16: amplitude. | +| 0x30 | 32 bit | DELAY_MS | R/W | 500 | Command completion delay. | +| 0x34 | 32 bit | FAULT_MASK | R/W | 0 | Enabled fault bits. | +| 0x38 | 32 bit | FAULT_PROB | R/W | 0 | Fault probability 0..10000. | +| 0x3c | 32 bit | OP_COUNTER | RO | 0 | Count of processed commands. | + +## CTRL register fields + +| Bit | Name | Purpose | +|-----|-------------------------|------------------------------------------| +| 0 | `MYFIRST_CTRL_ENABLE` | Device enable. | +| 1 | `MYFIRST_CTRL_RESET` | Write 1 to reset; self-clears. | +| 4-7 | `MYFIRST_CTRL_MODE` | Operating mode (0..15). | +| 8 | `MYFIRST_CTRL_LOOPBACK` | Loopback mode (challenge). | +| 9 | `MYFIRST_CTRL_GO` | Start a command; self-clearing. | + +## STATUS register fields + +| Bit | Name | Set by | Cleared by | +|-----|--------------------------|---------------------------|---------------------------| +| 0 | `MYFIRST_STATUS_READY` | `myfirst_hw_attach` | `myfirst_hw_detach` | +| 1 | `MYFIRST_STATUS_BUSY` | `sim_start_command`, `busy_cb` | `command_cb`, recovery | +| 2 | `MYFIRST_STATUS_ERROR` | `command_cb` (fault path) | driver error handler | +| 3 | `MYFIRST_STATUS_DATA_AV` | `command_cb` | driver after DATA_OUT read | + +## INTR_MASK / INTR_STATUS fields + +| Bit | Name | Interrupt source | +|-----|--------------------------|------------------------------------------| +| 0 | `MYFIRST_INTR_DATA_AV` | Data available for read. | +| 1 | `MYFIRST_INTR_ERROR` | Error condition detected. | +| 2 | `MYFIRST_INTR_COMPLETE` | Operation complete. | + +## SENSOR_CONFIG fields + +| Bits | Name | Purpose | +|-------|-----------|---------------------------------| +| 0-15 | interval | Sensor update interval in ms. | +| 16-31 | amplitude | Oscillation amplitude (0..65535).| + +## FAULT_MASK fields + +| Bit | Name | Effect | +|-----|----------------------------|-------------------------------------------------| +| 0 | `MYFIRST_FAULT_TIMEOUT` | Command never completes. | +| 1 | `MYFIRST_FAULT_READ_1S` | `DATA_OUT` returns `0xFFFFFFFF`. | +| 2 | `MYFIRST_FAULT_ERROR` | `STATUS.ERROR` set instead of `DATA_AV`. | +| 3 | `MYFIRST_FAULT_STUCK_BUSY` | `STATUS.BUSY` latched on. | + +## Common Sequences + +### Issuing a command + +``` +1. Wait for STATUS.BUSY == 0 (driver poll) +2. Write DATA_IN (driver) +3. Write CTRL |= GO (driver; self-clears) +4. Simulation schedules command_callout after DELAY_MS +5. command_callout sets DATA_OUT, STATUS.DATA_AV, clears BUSY +6. Wait for STATUS.DATA_AV == 1 (driver poll) +7. Read DATA_OUT (driver) +8. Clear STATUS.DATA_AV (driver) +``` + +### Reading a sensor sample + +``` +1. Wait for STATUS.BUSY == 0 +2. Write DATA_IN = 0xCAFE (marker) +3. Write CTRL |= GO +4. Wait for STATUS.DATA_AV == 1 +5. Read DATA_OUT +6. Push low byte into the ring buffer +``` + +### Error recovery + +``` +1. On ETIMEDOUT from wait_for_data: + a. Increment cmd_data_timeouts + b. Call myfirst_recover_from_stuck + c. Return ETIMEDOUT to the caller +2. recover_from_stuck: + a. Stop sim->command_callout + b. Clear sim->command_pending + c. Clear STATUS.BUSY, STATUS.DATA_AV +``` + +## Observability + +| Sysctl | Purpose | +|---------------------------------------|--------------------------------------------| +| `dev.myfirst.0.reg_*` | Read each register. | +| `dev.myfirst.0.reg_ctrl_set` | Write CTRL. | +| `dev.myfirst.0.reg_delay_ms_set` | Write DELAY_MS. | +| `dev.myfirst.0.reg_sensor_config_set` | Write SENSOR_CONFIG. | +| `dev.myfirst.0.reg_fault_mask_set` | Write FAULT_MASK. | +| `dev.myfirst.0.reg_fault_prob_set` | Write FAULT_PROB. | +| `dev.myfirst.0.access_log_enabled` | Toggle access logging. | +| `dev.myfirst.0.access_log` | Dump the access log. | +| `dev.myfirst.0.cmd_*` | Per-outcome statistics counters. | +| `dev.myfirst.0.fault_*` | Fault-injection counters. | +| `dev.myfirst.0.sim_running` | Simulation running flag. | + +## Simulation Dynamics (Chapter 17) + +Registers that are modified autonomously by the simulation: + +- `SENSOR`: updated every `SENSOR_CONFIG.interval` ms. +- `STATUS.BUSY`: set by `sim_start_command`; cleared by `command_cb` or + recovery; re-asserted by `busy_cb` when `FAULT_STUCK_BUSY`. +- `STATUS.DATA_AV`: set by `command_cb`; cleared by driver after reading + `DATA_OUT`. +- `STATUS.ERROR`: set by `command_cb` under `FAULT_ERROR`; cleared by + driver. +- `DATA_OUT`: set by `command_cb`. +- `OP_COUNTER`: incremented on each completed command. + +All updates happen under `sc->mtx` (which all callouts acquire +automatically via `callout_init_mtx`). + +## Architecture Portability + +The simulation path uses `X86_BUS_SPACE_MEM` as the tag and a kernel +virtual address as the handle. On non-x86 platforms, `bus_space_tag_t` +is a pointer to a structure and this shortcut does not compile. +Chapter 18 introduces real PCI, which is portable by design. diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/Makefile b/examples/part-04/ch17-simulating-hardware/stage5-final/Makefile new file mode 100644 index 0000000..8471647 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/Makefile @@ -0,0 +1,15 @@ +# Makefile for the Chapter 17 Stage 5 myfirst driver. +# +# Combines Chapter 11-15 driver, Chapter 16 hardware layer, and the +# new Chapter 17 simulation layer. The build takes place inside the +# chapter's driver directory; this Makefile assumes the full driver +# source tree (myfirst.c, myfirst_hw.c, myfirst_sim.c, cbuf.c) is +# present in the same directory as the Chapter 16 Stage 4 files. + +KMOD= myfirst +SRCS= myfirst.c myfirst_hw.c myfirst_sim.c cbuf.c + +# Chapter 17 specifies x86 only for the simulation shortcut. +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.0-simulated\" + +.include diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/SIMULATION.md b/examples/part-04/ch17-simulating-hardware/stage5-final/SIMULATION.md new file mode 100644 index 0000000..58560b2 --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/SIMULATION.md @@ -0,0 +1,108 @@ +# myfirst Simulation Interface + +## Version + +1.0-simulated. Chapter 17 complete. + +## What the Simulation Is + +A kernel-memory-backed simulated device that mimics a minimal +command-response hardware protocol, used to teach driver development +without requiring real hardware. The simulation lives in +`myfirst_sim.c` and is driven by three callouts: + +- `sensor_callout`: periodic, updates `SENSOR` every configurable interval. +- `command_callout`: one-shot, fires after `DELAY_MS` to complete a command. +- `busy_callout`: periodic, re-asserts `STATUS.BUSY` when `FAULT_STUCK_BUSY` is set. + +## What the Simulation Does + +- Produces an oscillating sensor value autonomously. +- Accepts commands via `CTRL.GO` and completes them after a delay. +- Implements read-to-clear-style semantics when the fault framework enables them. +- Injects four distinct fault modes under controllable probability. +- Tracks every operation in a per-device counter. + +## What the Simulation Does Not Do + +- No DMA. No interrupts. No PCI configuration space. +- No real-silicon timing precision (limited to the kernel's timer resolution). +- No sub-microsecond delays. +- No coalescing of commands (one at a time). +- No queued commands (overlapping writes are rejected). + +## Callout Map + +| Callout | Interval | Purpose | +|--------------------|----------------------|---------------------------------------| +| `sensor_callout` | `SENSOR_CONFIG`.interval ms (default 100) | Updates `SENSOR`. | +| `command_callout` | `DELAY_MS` (default 500) | Completes a single command. | +| `busy_callout` | 50 ms | Re-asserts `STATUS.BUSY` under `FAULT_STUCK_BUSY`. | + +All three callouts are initialised with `callout_init_mtx(&co, &sc->mtx, 0)`. +Every callback runs with `sc->mtx` held. + +## Fault Modes + +| Bit | Name | Effect | +|-----|----------------------------|-------------------------------------------------| +| 0 | `MYFIRST_FAULT_TIMEOUT` | Command never completes; driver times out. | +| 1 | `MYFIRST_FAULT_READ_1S` | `DATA_OUT` returns `0xFFFFFFFF`. | +| 2 | `MYFIRST_FAULT_ERROR` | `STATUS.ERROR` set instead of `DATA_AV`. | +| 3 | `MYFIRST_FAULT_STUCK_BUSY` | `STATUS.BUSY` latched on by the busy callout. | + +Multiple bits may be set; each operation independently consults +`should_fault()` which uses `arc4random_uniform(10000)` against +`FAULT_PROB`. + +## Sysctl Reference (simulation-added) + +| Sysctl | Type | Default | Purpose | +|-------------------------------------------|------|---------|----------------------------------| +| `dev.myfirst.0.sim_running` | RO | true | Simulation callouts active. | +| `dev.myfirst.0.sim_sensor_baseline` | RW | 0x1000 | Sensor oscillation baseline. | +| `dev.myfirst.0.sim_op_counter_mirror` | RO | 0 | Mirror of `OP_COUNTER`. | +| `dev.myfirst.0.reg_delay_ms_set` | RW | 500 | Writable `DELAY_MS`. | +| `dev.myfirst.0.reg_sensor_config_set` | RW | 0x00400064 | Writable `SENSOR_CONFIG`. | +| `dev.myfirst.0.reg_fault_mask_set` | RW | 0 | Writable `FAULT_MASK`. | +| `dev.myfirst.0.reg_fault_prob_set` | RW | 0 | Writable `FAULT_PROB`. | +| `dev.myfirst.0.cmd_timeout_ms` | RW | 2000 | Command completion timeout. | +| `dev.myfirst.0.rdy_timeout_ms` | RW | 100 | Device-ready polling timeout. | +| `dev.myfirst.0.cmd_successes` | RO | 0 | Successful commands. | +| `dev.myfirst.0.cmd_rdy_timeouts` | RO | 0 | Ready-wait timeouts. | +| `dev.myfirst.0.cmd_data_timeouts` | RO | 0 | Data-wait timeouts. | +| `dev.myfirst.0.cmd_errors` | RO | 0 | Commands with `STATUS.ERROR`. | +| `dev.myfirst.0.cmd_recoveries` | RO | 0 | Recovery invocations. | +| `dev.myfirst.0.fault_injected` | RO | 0 | Total faults injected. | + +## Development Guidance + +When adding a new simulation behaviour: + +1. Decide whether the behaviour needs a new callout or can fit in an + existing one. +2. If new, follow the six-step template in the Chapter 17 "Anatomy of + a Simulation Callout" reference. +3. Document the callout in the Callout Map table above. +4. If the behaviour exposes a new register, extend the register map in + `myfirst_hw.h` and document it in `HARDWARE.md`. +5. If the behaviour introduces a new fault mode, add a new bit to + `FAULT_MASK` definitions, implement the check in the appropriate + callback, and document it in the Fault Modes table above. +6. Add a sysctl where appropriate. +7. Add a test script under `examples/part-04/ch17-simulating-hardware/labs/`. + +## Relationship to Real Hardware + +The simulation is deliberately designed to match patterns in real +FreeBSD drivers: + +- `STATUS.READY` clears while busy; sets when ready. Common. +- `STATUS.DATA_AV` latches until read; driver clears. Common. +- `STATUS.ERROR` is sticky until cleared. Common. +- `CTRL.GO` is self-clearing. Common (called "start" or "trigger" on real devices). +- `INTR_STATUS` is RW in Chapter 17; many real devices make it RC or W1C. + +When Chapter 18 introduces real PCI hardware, the simulation is +retired and the driver's accessors point at the real device's BAR. +The driver's high-level logic does not change. diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_hw.h b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_hw.h new file mode 100644 index 0000000..b90380f --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_hw.h @@ -0,0 +1,144 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_hw.h -- Chapter 17 Stage 5 hardware interface. + * + * Extended from Chapter 16: + * - Register map grows with Chapter 17 additions (0x28..0x3c) + * - CTRL.GO bit added for command triggering + * - Fault-mode constants added + */ + +#ifndef _MYFIRST_HW_H_ +#define _MYFIRST_HW_H_ + +#include +#include +#include +#include + +/* + * Register offsets. Total register block is 64 bytes. + */ +#define MYFIRST_REG_CTRL 0x00 /* 32-bit, R/W: control */ +#define MYFIRST_REG_STATUS 0x04 /* 32-bit, R/W: status */ +#define MYFIRST_REG_DATA_IN 0x08 /* 32-bit, R/W: input data */ +#define MYFIRST_REG_DATA_OUT 0x0c /* 32-bit, R/W: output data */ +#define MYFIRST_REG_INTR_MASK 0x10 /* 32-bit, R/W: intr enables */ +#define MYFIRST_REG_INTR_STATUS 0x14 /* 32-bit, R/W: intr flags */ +#define MYFIRST_REG_DEVICE_ID 0x18 /* 32-bit, RO: device id */ +#define MYFIRST_REG_FIRMWARE_REV 0x1c /* 32-bit, RO: fw rev */ +#define MYFIRST_REG_SCRATCH_A 0x20 /* 32-bit, R/W: scratch A */ +#define MYFIRST_REG_SCRATCH_B 0x24 /* 32-bit, R/W: scratch B */ + +/* Chapter 17 additions. */ +#define MYFIRST_REG_SENSOR 0x28 /* 32-bit, RO: sensor value */ +#define MYFIRST_REG_SENSOR_CONFIG 0x2c /* 32-bit, R/W: sensor config */ +#define MYFIRST_REG_DELAY_MS 0x30 /* 32-bit, R/W: cmd delay */ +#define MYFIRST_REG_FAULT_MASK 0x34 /* 32-bit, R/W: fault mask */ +#define MYFIRST_REG_FAULT_PROB 0x38 /* 32-bit, R/W: fault prob */ +#define MYFIRST_REG_OP_COUNTER 0x3c /* 32-bit, RO: op counter */ + +#define MYFIRST_REG_SIZE 0x40 /* total 64 bytes */ + +/* CTRL register bits. */ +#define MYFIRST_CTRL_ENABLE 0x00000001u +#define MYFIRST_CTRL_RESET 0x00000002u +#define MYFIRST_CTRL_MODE_MASK 0x000000f0u +#define MYFIRST_CTRL_MODE_SHIFT 4 +#define MYFIRST_CTRL_LOOPBACK 0x00000100u +#define MYFIRST_CTRL_GO 0x00000200u /* Ch17: start command */ + +/* STATUS register bits. */ +#define MYFIRST_STATUS_READY 0x00000001u +#define MYFIRST_STATUS_BUSY 0x00000002u +#define MYFIRST_STATUS_ERROR 0x00000004u +#define MYFIRST_STATUS_DATA_AV 0x00000008u + +/* INTR_MASK / INTR_STATUS bits. */ +#define MYFIRST_INTR_DATA_AV 0x00000001u +#define MYFIRST_INTR_ERROR 0x00000002u +#define MYFIRST_INTR_COMPLETE 0x00000004u + +/* Fixed identifier values. */ +#define MYFIRST_DEVICE_ID_VALUE 0x4D594649u +#define MYFIRST_FW_REV_MAJOR 1 +#define MYFIRST_FW_REV_MINOR 0 +#define MYFIRST_FW_REV_VALUE \ + ((MYFIRST_FW_REV_MAJOR << 16) | MYFIRST_FW_REV_MINOR) + +/* SENSOR_CONFIG register fields. */ +#define MYFIRST_SCFG_INTERVAL_MASK 0x0000ffffu +#define MYFIRST_SCFG_INTERVAL_SHIFT 0 +#define MYFIRST_SCFG_AMPLITUDE_MASK 0xffff0000u +#define MYFIRST_SCFG_AMPLITUDE_SHIFT 16 + +/* FAULT_MASK register bits. */ +#define MYFIRST_FAULT_TIMEOUT 0x00000001u +#define MYFIRST_FAULT_READ_1S 0x00000002u +#define MYFIRST_FAULT_ERROR 0x00000004u +#define MYFIRST_FAULT_STUCK_BUSY 0x00000008u + +/* Access log. */ +#define MYFIRST_ACCESS_LOG_SIZE 64 + +struct myfirst_access_log_entry { + uint64_t timestamp_ns; + uint32_t value; + bus_size_t offset; + uint8_t is_write; + uint8_t width; + uint8_t context_tag; + uint8_t _pad; +}; + +/* + * Hardware state, grouped. Pointed at from sc->hw. + */ +struct myfirst_hw { + uint8_t *regs_buf; + size_t regs_size; + bus_space_tag_t regs_tag; + bus_space_handle_t regs_handle; + + struct task reg_ticker_task; + int reg_ticker_enabled; + + struct myfirst_access_log_entry access_log[MYFIRST_ACCESS_LOG_SIZE]; + unsigned int access_log_head; + bool access_log_enabled; +}; + +struct myfirst_softc; + +/* Hardware layer API. */ +int myfirst_hw_attach(struct myfirst_softc *sc); +void myfirst_hw_detach(struct myfirst_softc *sc); +void myfirst_hw_add_sysctls(struct myfirst_softc *sc); + +/* Accessors. sc->mtx must be held. */ +uint32_t myfirst_reg_read(struct myfirst_softc *sc, bus_size_t offset); +void myfirst_reg_write(struct myfirst_softc *sc, bus_size_t offset, + uint32_t value); +void myfirst_reg_update(struct myfirst_softc *sc, bus_size_t offset, + uint32_t clear_mask, uint32_t set_mask); +void myfirst_reg_write_barrier(struct myfirst_softc *sc, bus_size_t offset, + uint32_t value, int flags); + +/* Side-effect helper for CTRL writes. Chapter 17 extends it. */ +void myfirst_ctrl_update(struct myfirst_softc *sc, uint32_t old, + uint32_t new); + +/* Shared sysctl write handler used by both hw and sim layers. */ +int myfirst_sysctl_reg_write(struct sysctl_oid *oidp, void *arg1, + intmax_t arg2, struct sysctl_req *req); + +/* CSR_* macros mirroring the idiom used in production FreeBSD drivers. */ +#define CSR_READ_4(sc, off) myfirst_reg_read((sc), (off)) +#define CSR_WRITE_4(sc, off, val) myfirst_reg_write((sc), (off), (val)) +#define CSR_UPDATE_4(sc, off, clear, set) \ + myfirst_reg_update((sc), (off), (clear), (set)) + +#endif /* _MYFIRST_HW_H_ */ diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.c b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.c new file mode 100644 index 0000000..47b472d --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.c @@ -0,0 +1,390 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_sim.c -- Chapter 17 simulated hardware backend. + * + * Adds callouts that drive autonomous register changes, a + * command-scheduling callout for command-triggered delays, and the + * fault-injection framework. Depends on Chapter 16's register access + * layer (myfirst_hw.h, myfirst_hw.c). + * + * Simulation architecture: + * - sensor_callout: periodic, updates SENSOR every SENSOR_CONFIG.interval ms + * - command_callout: one-shot, scheduled by CTRL.GO, fires after DELAY_MS ms + * - busy_callout: periodic 50 ms, re-asserts STATUS.BUSY when FAULT_STUCK_BUSY + * + * Locking: all three callouts are initialised with sc->mtx, so every + * callback runs with sc->mtx held automatically. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_sim.h" + +static void myfirst_sim_sensor_cb(void *arg); +static void myfirst_sim_command_cb(void *arg); +static void myfirst_sim_busy_cb(void *arg); +static bool myfirst_sim_should_fault(struct myfirst_softc *sc); + +/* + * Attach: allocate state, initialise callouts, seed default + * configuration registers. The simulation is not started yet; the + * caller calls myfirst_sim_enable under the lock after attach finishes. + */ +int +myfirst_sim_attach(struct myfirst_softc *sc) +{ + struct myfirst_sim *sim; + + sim = malloc(sizeof(*sim), M_MYFIRST, M_WAITOK | M_ZERO); + + callout_init_mtx(&sim->sensor_callout, &sc->mtx, 0); + callout_init_mtx(&sim->command_callout, &sc->mtx, 0); + callout_init_mtx(&sim->busy_callout, &sc->mtx, 0); + + sim->sensor_baseline = 0x1000; + + MYFIRST_LOCK(sc); + CSR_WRITE_4(sc, MYFIRST_REG_SENSOR_CONFIG, + (100u << MYFIRST_SCFG_INTERVAL_SHIFT) | + (64u << MYFIRST_SCFG_AMPLITUDE_SHIFT)); + CSR_WRITE_4(sc, MYFIRST_REG_DELAY_MS, 500); + CSR_WRITE_4(sc, MYFIRST_REG_FAULT_MASK, 0); + CSR_WRITE_4(sc, MYFIRST_REG_FAULT_PROB, 0); + CSR_WRITE_4(sc, MYFIRST_REG_OP_COUNTER, 0); + MYFIRST_UNLOCK(sc); + + sc->sim = sim; + return (0); +} + +/* + * Detach: stop callouts, drain them, free state. Must be called with + * sc->mtx NOT held; callout_drain will sleep. + */ +void +myfirst_sim_detach(struct myfirst_softc *sc) +{ + struct myfirst_sim *sim; + + if (sc->sim == NULL) + return; + + sim = sc->sim; + sc->sim = NULL; + + callout_drain(&sim->sensor_callout); + callout_drain(&sim->command_callout); + callout_drain(&sim->busy_callout); + + free(sim, M_MYFIRST); +} + +/* + * Enable: start the periodic callouts. sc->mtx must be held. + */ +void +myfirst_sim_enable(struct myfirst_softc *sc) +{ + struct myfirst_sim *sim = sc->sim; + uint32_t config, interval_ms; + + MYFIRST_LOCK_ASSERT(sc); + + if (sim->running) + return; + + sim->running = true; + + config = CSR_READ_4(sc, MYFIRST_REG_SENSOR_CONFIG); + interval_ms = (config & MYFIRST_SCFG_INTERVAL_MASK) >> + MYFIRST_SCFG_INTERVAL_SHIFT; + if (interval_ms == 0) + interval_ms = 100; + + callout_reset_sbt(&sim->sensor_callout, + interval_ms * SBT_1MS, 0, + myfirst_sim_sensor_cb, sc, 0); + + callout_reset_sbt(&sim->busy_callout, + 50 * SBT_1MS, 0, + myfirst_sim_busy_cb, sc, 0); +} + +/* + * Disable: stop (do not drain) the callouts. sc->mtx must be held. + */ +void +myfirst_sim_disable(struct myfirst_softc *sc) +{ + struct myfirst_sim *sim = sc->sim; + + MYFIRST_LOCK_ASSERT(sc); + + if (!sim->running) + return; + + sim->running = false; + + callout_stop(&sim->sensor_callout); + callout_stop(&sim->command_callout); + callout_stop(&sim->busy_callout); +} + +/* + * Sensor callout: fires periodically, updates the SENSOR register + * with an oscillating value, re-arms itself. + */ +static void +myfirst_sim_sensor_cb(void *arg) +{ + struct myfirst_softc *sc = arg; + struct myfirst_sim *sim = sc->sim; + uint32_t config, interval_ms, amplitude, phase, value; + + MYFIRST_LOCK_ASSERT(sc); + + if (!sim->running) + return; + + config = CSR_READ_4(sc, MYFIRST_REG_SENSOR_CONFIG); + interval_ms = (config & MYFIRST_SCFG_INTERVAL_MASK) >> + MYFIRST_SCFG_INTERVAL_SHIFT; + amplitude = (config & MYFIRST_SCFG_AMPLITUDE_MASK) >> + MYFIRST_SCFG_AMPLITUDE_SHIFT; + + sim->sensor_tick++; + phase = sim->sensor_tick & 0x7; + value = sim->sensor_baseline + + ((phase < 4) ? phase : (7 - phase)) * (amplitude / 4); + + CSR_WRITE_4(sc, MYFIRST_REG_SENSOR, value); + + if (interval_ms == 0) + interval_ms = 100; + + callout_reset_sbt(&sim->sensor_callout, + interval_ms * SBT_1MS, 0, + myfirst_sim_sensor_cb, sc, 0); +} + +/* + * Command completion callout: one-shot. Honours any saved fault + * state; otherwise completes the command by copying pending data + * to DATA_OUT and setting STATUS.DATA_AV. + */ +static void +myfirst_sim_command_cb(void *arg) +{ + struct myfirst_softc *sc = arg; + struct myfirst_sim *sim = sc->sim; + uint32_t status, fault; + + MYFIRST_LOCK_ASSERT(sc); + + if (!sim->running || !sim->command_pending) + return; + + fault = sim->pending_fault; + + status = CSR_READ_4(sc, MYFIRST_REG_STATUS); + status &= ~MYFIRST_STATUS_BUSY; + + if (fault & MYFIRST_FAULT_ERROR) { + status |= MYFIRST_STATUS_ERROR; + sc->stats.fault_injected++; + sc->stats.fault_error++; + } else if (fault & MYFIRST_FAULT_READ_1S) { + CSR_WRITE_4(sc, MYFIRST_REG_DATA_OUT, 0xFFFFFFFFu); + status |= MYFIRST_STATUS_DATA_AV; + sc->stats.fault_injected++; + sc->stats.fault_read_1s++; + } else { + CSR_WRITE_4(sc, MYFIRST_REG_DATA_OUT, sim->pending_data); + status |= MYFIRST_STATUS_DATA_AV; + } + + CSR_WRITE_4(sc, MYFIRST_REG_STATUS, status); + + sim->op_counter++; + CSR_WRITE_4(sc, MYFIRST_REG_OP_COUNTER, sim->op_counter); + + sim->command_pending = false; + sim->pending_fault = 0; +} + +/* + * Busy callout: periodic. When FAULT_STUCK_BUSY is set, re-assert + * STATUS.BUSY so every command times out on wait_for_ready. + */ +static void +myfirst_sim_busy_cb(void *arg) +{ + struct myfirst_softc *sc = arg; + struct myfirst_sim *sim = sc->sim; + uint32_t fault_mask, status; + + MYFIRST_LOCK_ASSERT(sc); + + if (!sim->running) + return; + + fault_mask = CSR_READ_4(sc, MYFIRST_REG_FAULT_MASK); + if (fault_mask & MYFIRST_FAULT_STUCK_BUSY) { + status = CSR_READ_4(sc, MYFIRST_REG_STATUS); + if (!(status & MYFIRST_STATUS_BUSY)) { + status |= MYFIRST_STATUS_BUSY; + CSR_WRITE_4(sc, MYFIRST_REG_STATUS, status); + sc->stats.fault_injected++; + sc->stats.fault_stuck_busy++; + } + } + + callout_reset_sbt(&sim->busy_callout, + 50 * SBT_1MS, 0, + myfirst_sim_busy_cb, sc, 0); +} + +/* + * Should this operation have a fault injected? Consults FAULT_PROB. + */ +static bool +myfirst_sim_should_fault(struct myfirst_softc *sc) +{ + uint32_t prob, r; + + MYFIRST_LOCK_ASSERT(sc); + + prob = CSR_READ_4(sc, MYFIRST_REG_FAULT_PROB); + if (prob == 0) + return (false); + if (prob >= 10000) + return (true); + + r = arc4random_uniform(10000); + return (r < prob); +} + +/* + * Called from myfirst_ctrl_update when CTRL.GO is written. Samples + * DATA_IN, sets STATUS.BUSY, clears DATA_AV, schedules completion. + */ +void +myfirst_sim_start_command(struct myfirst_softc *sc) +{ + struct myfirst_sim *sim = sc->sim; + uint32_t data_in, delay_ms, fault_mask, status; + bool fault; + + MYFIRST_LOCK_ASSERT(sc); + + if (!sim->running) + return; + + if (sim->command_pending) { + sc->stats.cmd_rejected++; + device_printf(sc->dev, + "sim: overlapping command; ignored\n"); + return; + } + + data_in = CSR_READ_4(sc, MYFIRST_REG_DATA_IN); + sim->pending_data = data_in; + + status = CSR_READ_4(sc, MYFIRST_REG_STATUS); + status |= MYFIRST_STATUS_BUSY; + status &= ~MYFIRST_STATUS_DATA_AV; + CSR_WRITE_4(sc, MYFIRST_REG_STATUS, status); + + delay_ms = CSR_READ_4(sc, MYFIRST_REG_DELAY_MS); + if (delay_ms == 0) + delay_ms = 1; + + sim->command_pending = true; + + fault_mask = CSR_READ_4(sc, MYFIRST_REG_FAULT_MASK); + fault = (fault_mask != 0) && myfirst_sim_should_fault(sc); + + if (fault && (fault_mask & MYFIRST_FAULT_TIMEOUT)) { + /* + * Inject a timeout: do not schedule the completion + * callout. The driver's wait_for_data will time out + * and the recovery path will clean up. + */ + sc->stats.fault_injected++; + sc->stats.fault_timeout++; + device_printf(sc->dev, + "sim: injecting TIMEOUT fault\n"); + return; + } + + sim->pending_fault = fault ? fault_mask : 0; + + callout_reset_sbt(&sim->command_callout, + delay_ms * SBT_1MS, 0, + myfirst_sim_command_cb, sc, 0); +} + +/* + * Register sysctls specific to the simulation. + */ +void +myfirst_sim_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid *tree = sc->sysctl_tree; + + SYSCTL_ADD_BOOL(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "sim_running", CTLFLAG_RD, + &sc->sim->running, 0, + "Whether the simulation callouts are active"); + + SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "sim_sensor_baseline", CTLFLAG_RW, + &sc->sim->sensor_baseline, 0, + "Baseline value around which SENSOR oscillates"); + + SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "sim_op_counter_mirror", CTLFLAG_RD, + &sc->sim->op_counter, 0, + "Mirror of OP_COUNTER (for observability)"); + + SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "reg_delay_ms_set", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, MYFIRST_REG_DELAY_MS, myfirst_sysctl_reg_write, + "IU", "Command delay in ms (writeable)"); + + SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "reg_sensor_config_set", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, MYFIRST_REG_SENSOR_CONFIG, myfirst_sysctl_reg_write, + "IU", "Sensor config interval|amplitude (writeable)"); + + SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "reg_fault_mask_set", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, MYFIRST_REG_FAULT_MASK, myfirst_sysctl_reg_write, + "IU", "Fault mask (writeable)"); + + SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, + "reg_fault_prob_set", + CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, + sc, MYFIRST_REG_FAULT_PROB, myfirst_sysctl_reg_write, + "IU", "Fault probability 0..10000 (writeable)"); +} diff --git a/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.h b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.h new file mode 100644 index 0000000..90e157f --- /dev/null +++ b/examples/part-04/ch17-simulating-hardware/stage5-final/myfirst_sim.h @@ -0,0 +1,73 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_sim.h -- Chapter 17 simulation API. + * + * The simulation layer turns the Chapter 16 static register block into + * a dynamic device: autonomous sensor updates, command-triggered + * delayed completions, read-to-clear semantics for INTR_STATUS, and a + * fault-injection framework. The API is small; most of the simulation + * is in myfirst_sim.c. + */ + +#ifndef _MYFIRST_SIM_H_ +#define _MYFIRST_SIM_H_ + +#include +#include +#include + +struct myfirst_softc; + +/* + * Simulation state. One per driver instance. Allocated in + * myfirst_sim_attach, freed in myfirst_sim_detach. + */ +struct myfirst_sim { + /* The three simulation callouts. */ + struct callout sensor_callout; + struct callout command_callout; + struct callout busy_callout; + + /* Last scheduled command's data. Saved so command_cb can + * latch DATA_OUT when it fires. */ + uint32_t pending_data; + + /* Saved fault state for this command. Set in start_command, + * consumed by command_cb. */ + uint32_t pending_fault; + + /* Whether a command is currently in flight. */ + bool command_pending; + + /* Baseline sensor value; the sensor callout oscillates + * around this. */ + uint32_t sensor_baseline; + + /* Counter used by the sensor oscillation algorithm. */ + uint32_t sensor_tick; + + /* Local operation counter; mirrors OP_COUNTER register. */ + uint32_t op_counter; + + /* Whether the simulation callouts are running. Checked by + * every callout before doing work. */ + bool running; +}; + +/* + * API. All functions assume sc->sim is valid (that is, + * myfirst_sim_attach has been called successfully) unless noted + * otherwise. + */ + +int myfirst_sim_attach(struct myfirst_softc *sc); +void myfirst_sim_detach(struct myfirst_softc *sc); +void myfirst_sim_enable(struct myfirst_softc *sc); +void myfirst_sim_disable(struct myfirst_softc *sc); +void myfirst_sim_start_command(struct myfirst_softc *sc); +void myfirst_sim_add_sysctls(struct myfirst_softc *sc); + +#endif /* _MYFIRST_SIM_H_ */ diff --git a/examples/part-04/ch18-writing-pci-driver/labs/attach_detach_cycle.sh b/examples/part-04/ch18-writing-pci-driver/labs/attach_detach_cycle.sh new file mode 100755 index 0000000..32c5816 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/attach_detach_cycle.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# +# attach_detach_cycle.sh -- stress the attach/detach path. +# +# Runs N detach/attach cycles against the myfirst0 device. Reports +# any failed cycle and any malloc leak observed afterwards. + +set -eu + +CYCLES="${1:-50}" + +say() { printf '=== %s ===\n' "$1"; } +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } + +SELECTOR=$(pciconf -l | awk '/^myfirst0/{print $1}' \ + | sed 's/myfirst0@//') +[ -n "$SELECTOR" ] || fail "myfirst0 not present; load the driver first" + +say "Cycling $CYCLES times" + +i=1 +while [ "$i" -le "$CYCLES" ]; do + devctl detach myfirst0 || fail "detach on cycle $i" + sleep 0.1 + devctl attach "$SELECTOR" || fail "attach on cycle $i" + sleep 0.1 + i=$((i + 1)) +done + +say "Cycle complete; checking leaks" + +LEAK=$(vmstat -m | awk '/^ *myfirst /{print $3}') +if [ "${LEAK:-0}" -gt 0 ]; then + fail "$LEAK live myfirst allocations after cycle" +fi + +say "Success" diff --git a/examples/part-04/ch18-writing-pci-driver/labs/full_regression_ch18.sh b/examples/part-04/ch18-writing-pci-driver/labs/full_regression_ch18.sh new file mode 100755 index 0000000..6342b35 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/full_regression_ch18.sh @@ -0,0 +1,84 @@ +#!/bin/sh +# +# Chapter 18 full regression script. +# +# Verifies the Stage 4 driver's behaviour end-to-end inside a bhyve +# or QEMU guest that exposes a virtio-rnd device. +# +# Runs: +# - Unload the base-system virtio_random driver if present. +# - Load ./myfirst.ko (expected to be in the current directory). +# - Verify attach: myfirst0 present with a BAR resource. +# - Exercise the cdev via myfirst_test. +# - Run ten detach/attach cycles. +# - Unload the driver. +# - Check for leaks via vmstat -m. + +set -eu + +DRIVER="$(dirname "$0")/../stage4-final/myfirst.ko" +TESTER="$(dirname "$0")/myfirst_test" +if [ ! -f "$DRIVER" ]; then + DRIVER="./myfirst.ko" +fi + +say() { printf '=== %s ===\n' "$1"; } +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } + +say "Checking prerequisites" +[ -f "$DRIVER" ] || fail "driver module not found: $DRIVER" +[ -x "$TESTER" ] || { + say "Compiling myfirst_test" + cc -o "$TESTER" "$(dirname "$0")/myfirst_test.c" +} + +say "Unloading virtio_random if present" +kldstat | grep -q virtio_random && kldunload virtio_random || true + +say "Loading myfirst" +kldload "$DRIVER" +sleep 1 + +say "Verifying attach" +devinfo -v | grep -q 'myfirst0' || fail "myfirst0 not attached" + +say "Verifying BAR claim" +devinfo -v | grep -A 3 'myfirst0' | grep -q 'memory:' \ + || fail "BAR not claimed" + +say "Verifying cdev" +[ -c /dev/myfirst0 ] || fail "/dev/myfirst0 missing" + +say "Exercising cdev" +"$TESTER" || fail "myfirst_test failed" + +say "Running detach/attach cycles" +SELECTOR=$(devinfo -r -v | awk '/^myfirst0@pci/{print $1}' \ + | sed 's/myfirst0@//') +if [ -z "$SELECTOR" ]; then + SELECTOR=$(pciconf -l | awk '/^myfirst0/{print $1}' \ + | sed 's/myfirst0@//') +fi +[ -n "$SELECTOR" ] || fail "could not determine PCI selector" + +i=1 +while [ $i -le 10 ]; do + devctl detach myfirst0 || fail "detach #$i failed" + sleep 0.3 + devctl attach "$SELECTOR" || fail "attach #$i failed" + sleep 0.3 + i=$((i + 1)) +done + +say "Unloading myfirst" +kldunload myfirst + +say "Checking for leaks" +if vmstat -m | grep -q myfirst; then + USE=$(vmstat -m | awk '/myfirst/{print $3}') + if [ "${USE:-0}" -gt 0 ]; then + fail "myfirst has $USE live allocations after unload" + fi +fi + +say "Success" diff --git a/examples/part-04/ch18-writing-pci-driver/labs/launch_bhyve_guest.sh b/examples/part-04/ch18-writing-pci-driver/labs/launch_bhyve_guest.sh new file mode 100755 index 0000000..244dee9 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/launch_bhyve_guest.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# +# Example bhyve command to launch a FreeBSD 14.3 guest with a +# virtio-rnd device exposed on PCI slot 4. Adapt paths and device +# names to your environment. +# +# Prerequisites (on the host): +# - A FreeBSD guest image (zfs zvol or a raw disk file). +# - bhyve's kernel modules loaded: vmm, nmdm, if_bridge, if_tap. +# - A bridged tap network interface if the guest needs networking. +# - BHYVE_UEFI.fd available (from the uefi-edk2-bhyve package). + +set -eu + +GUEST="fbsd-14.3-lab" +DISK="/dev/zvol/zroot/vm/${GUEST}/disk0" +TAP="tap0" +UEFI="/usr/local/share/uefi-firmware/BHYVE_UEFI.fd" +NMDM="/dev/nmdm${GUEST}A" + +kldload -n vmm nmdm if_bridge if_tap + +bhyve -c 2 -m 2048 -H -w \ + -s 0:0,hostbridge \ + -s 1:0,lpc \ + -s 2:0,virtio-net,"$TAP" \ + -s 3:0,virtio-blk,"$DISK" \ + -s 4:0,virtio-rnd \ + -l com1,"$NMDM" \ + -l bootrom,"$UEFI" \ + "$GUEST" diff --git a/examples/part-04/ch18-writing-pci-driver/labs/launch_qemu_guest.sh b/examples/part-04/ch18-writing-pci-driver/labs/launch_qemu_guest.sh new file mode 100755 index 0000000..4c54e26 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/launch_qemu_guest.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# +# Example QEMU command to launch a FreeBSD 14.3 guest with a +# virtio-rng-pci device. Runs on Linux or macOS hosts. Adapt paths +# to your environment. + +set -eu + +IMAGE="freebsd-14.3-lab.img" +TAP="tap0" +BIOS_DIR="/usr/share/qemu" + +qemu-system-x86_64 \ + -cpu host -m 2048 -smp 2 \ + -drive file="$IMAGE",if=virtio \ + -netdev tap,id=net0,ifname="$TAP" \ + -device virtio-net,netdev=net0 \ + -device virtio-rng-pci \ + -bios "${BIOS_DIR}/OVMF_CODE.fd" \ + -serial stdio diff --git a/examples/part-04/ch18-writing-pci-driver/labs/myfirst_test.c b/examples/part-04/ch18-writing-pci-driver/labs/myfirst_test.c new file mode 100644 index 0000000..9b1a7a9 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/myfirst_test.c @@ -0,0 +1,43 @@ +/* + * myfirst_test.c -- Chapter 18 user-space smoke test. + * + * Opens /dev/myfirst0, reads up to 64 bytes, writes 16 bytes, and + * closes the descriptor. Exits non-zero on any failure. + * + * Build: + * cc -o myfirst_test myfirst_test.c + */ + +#include +#include +#include +#include +#include + +int +main(void) +{ + int fd; + ssize_t n; + char rbuf[64]; + char wbuf[16] = "hello-ch18\n"; + + fd = open("/dev/myfirst0", O_RDWR); + if (fd < 0) { + fprintf(stderr, "open: %s\n", strerror(errno)); + return (1); + } + + n = read(fd, rbuf, sizeof(rbuf)); + printf("read returned %zd\n", n); + + n = write(fd, wbuf, sizeof(wbuf)); + printf("write returned %zd\n", n); + + if (close(fd) < 0) { + fprintf(stderr, "close: %s\n", strerror(errno)); + return (1); + } + + return (0); +} diff --git a/examples/part-04/ch18-writing-pci-driver/labs/pci_dump_config.sh b/examples/part-04/ch18-writing-pci-driver/labs/pci_dump_config.sh new file mode 100755 index 0000000..7c3c1b3 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/labs/pci_dump_config.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# +# pci_dump_config.sh -- dump the first 64 bytes of PCI configuration +# space for the named device in a readable 4-byte-per-row format. +# +# Usage: ./pci_dump_config.sh +# +# Example: ./pci_dump_config.sh myfirst0 +# ./pci_dump_config.sh pci0:0:4:0 + +set -eu + +SEL="${1:-myfirst0}" + +printf 'PCI configuration space for %s:\n' "$SEL" +printf 'offset value\n' + +off=0 +while [ "$off" -lt 64 ]; do + printf '0x%02x %s\n' "$off" \ + "$(pciconf -r "$SEL" "${off}:4" | tr -d ' \n')" + off=$((off + 4)) +done diff --git a/examples/part-04/ch18-writing-pci-driver/stage1-probe/Makefile b/examples/part-04/ch18-writing-pci-driver/stage1-probe/Makefile new file mode 100644 index 0000000..95fa3f2 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage1-probe/Makefile @@ -0,0 +1,13 @@ +# Makefile for the Chapter 18 Stage 1 myfirst driver. +# +# The build assumes that the Chapter 17 Stage 5 files +# (myfirst.c, myfirst_hw.c, myfirst_sim.c, cbuf.c, and their +# associated headers) are present in the same directory as the +# Chapter 18 Stage 1 files (myfirst_pci.c, myfirst_pci.h). + +KMOD= myfirst +SRCS= myfirst.c myfirst_hw.c myfirst_sim.c myfirst_pci.c cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.1-pci-stage1\" + +.include diff --git a/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.c b/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.c new file mode 100644 index 0000000..4fc8980 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.c @@ -0,0 +1,87 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.c -- Chapter 18 Stage 1 PCI probe/attach/detach skeleton. + * + * Stage 1's job is to prove the probe-attach-detach dance against a + * real PCI bus. The driver matches a specific vendor/device ID pair, + * prints a banner in dmesg, and unloads cleanly. No BAR claim. No + * register access. Those come in later stages. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "myfirst.h" /* struct myfirst_softc */ +#include "myfirst_pci.h" + +static const struct myfirst_pci_id myfirst_pci_ids[] = { + { MYFIRST_VENDOR_REDHAT, MYFIRST_DEVICE_VIRTIO_RNG, + "Red Hat Virtio entropy source (myfirst demo target)" }, + { 0, 0, NULL } +}; + +static int +myfirst_pci_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct myfirst_pci_id *id; + + for (id = myfirst_pci_ids; id->desc != NULL; id++) { + if (id->vendor == vendor && id->device == device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +myfirst_pci_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + sc->dev = dev; + device_printf(dev, + "attaching: vendor=0x%04x device=0x%04x revid=0x%02x\n", + pci_get_vendor(dev), pci_get_device(dev), pci_get_revid(dev)); + device_printf(dev, + " subvendor=0x%04x subdevice=0x%04x class=0x%02x\n", + pci_get_subvendor(dev), pci_get_subdevice(dev), + pci_get_class(dev)); + + return (0); +} + +static int +myfirst_pci_detach(device_t dev) +{ + device_printf(dev, "detaching\n"); + return (0); +} + +static device_method_t myfirst_pci_methods[] = { + DEVMETHOD(device_probe, myfirst_pci_probe), + DEVMETHOD(device_attach, myfirst_pci_attach), + DEVMETHOD(device_detach, myfirst_pci_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_pci_driver = { + "myfirst", + myfirst_pci_methods, + sizeof(struct myfirst_softc), +}; + +DRIVER_MODULE(myfirst, pci, myfirst_pci_driver, NULL, NULL); +MODULE_DEPEND(myfirst, pci, 1, 1, 1); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.h b/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.h new file mode 100644 index 0000000..e354917 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage1-probe/myfirst_pci.h @@ -0,0 +1,38 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.h -- Chapter 18 PCI interface for the myfirst driver. + * + * Stage 1: minimal probe/attach/detach. Declares the vendor/device + * ID match table structure and the IDs the probe recognises. + */ + +#ifndef _MYFIRST_PCI_H_ +#define _MYFIRST_PCI_H_ + +#include + +/* + * Target vendor and device IDs for the Chapter 18 demo. + * + * Both bhyve's and QEMU's virtio-rnd device use these values. A + * reader with different test hardware should replace them with the + * IDs their device advertises (visible through pciconf -lv). + */ +#define MYFIRST_VENDOR_REDHAT 0x1af4 +#define MYFIRST_DEVICE_VIRTIO_RNG 0x1005 + +/* + * One entry in the supported-device table. The driver iterates this + * table in its probe routine and returns BUS_PROBE_DEFAULT on the + * first match. + */ +struct myfirst_pci_id { + uint16_t vendor; + uint16_t device; + const char *desc; +}; + +#endif /* _MYFIRST_PCI_H_ */ diff --git a/examples/part-04/ch18-writing-pci-driver/stage2-bar/Makefile b/examples/part-04/ch18-writing-pci-driver/stage2-bar/Makefile new file mode 100644 index 0000000..7a22db9 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage2-bar/Makefile @@ -0,0 +1,8 @@ +# Makefile for the Chapter 18 Stage 2 myfirst driver. + +KMOD= myfirst +SRCS= myfirst.c myfirst_hw.c myfirst_sim.c myfirst_pci.c cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.1-pci-stage2\" + +.include diff --git a/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.c b/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.c new file mode 100644 index 0000000..4eef00e --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.c @@ -0,0 +1,108 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.c -- Chapter 18 Stage 2 PCI driver. + * + * Stage 2 extends Stage 1 by claiming BAR 0 as a SYS_RES_MEMORY + * resource. The tag and handle are not yet wired to the Chapter 16 + * accessor layer (that is Stage 3). Detach releases the BAR. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_pci.h" + +static const struct myfirst_pci_id myfirst_pci_ids[] = { + { MYFIRST_VENDOR_REDHAT, MYFIRST_DEVICE_VIRTIO_RNG, + "Red Hat Virtio entropy source (myfirst demo target)" }, + { 0, 0, NULL } +}; + +static int +myfirst_pci_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct myfirst_pci_id *id; + + for (id = myfirst_pci_ids; id->desc != NULL; id++) { + if (id->vendor == vendor && id->device == device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +myfirst_pci_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + sc->dev = dev; + device_printf(dev, + "attaching: vendor=0x%04x device=0x%04x revid=0x%02x\n", + pci_get_vendor(dev), pci_get_device(dev), pci_get_revid(dev)); + + /* Allocate BAR 0 as a memory resource. */ + sc->bar_rid = PCIR_BAR(0); + sc->bar_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->bar_rid, RF_ACTIVE); + if (sc->bar_res == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + return (ENXIO); + } + + device_printf(dev, "BAR0 allocated: %#jx bytes at %#jx\n", + (uintmax_t)rman_get_size(sc->bar_res), + (uintmax_t)rman_get_start(sc->bar_res)); + + sc->pci_attached = true; + return (0); +} + +static int +myfirst_pci_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + if (sc->bar_res != NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->bar_rid, + sc->bar_res); + sc->bar_res = NULL; + } + sc->pci_attached = false; + device_printf(dev, "detaching\n"); + return (0); +} + +static device_method_t myfirst_pci_methods[] = { + DEVMETHOD(device_probe, myfirst_pci_probe), + DEVMETHOD(device_attach, myfirst_pci_attach), + DEVMETHOD(device_detach, myfirst_pci_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_pci_driver = { + "myfirst", + myfirst_pci_methods, + sizeof(struct myfirst_softc), +}; + +DRIVER_MODULE(myfirst, pci, myfirst_pci_driver, NULL, NULL); +MODULE_DEPEND(myfirst, pci, 1, 1, 1); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.h b/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.h new file mode 100644 index 0000000..b6566f4 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage2-bar/myfirst_pci.h @@ -0,0 +1,25 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.h -- Chapter 18 PCI interface for the myfirst driver. + * + * Stage 2: adds BAR allocation via bus_alloc_resource_any(9). + */ + +#ifndef _MYFIRST_PCI_H_ +#define _MYFIRST_PCI_H_ + +#include + +#define MYFIRST_VENDOR_REDHAT 0x1af4 +#define MYFIRST_DEVICE_VIRTIO_RNG 0x1005 + +struct myfirst_pci_id { + uint16_t vendor; + uint16_t device; + const char *desc; +}; + +#endif /* _MYFIRST_PCI_H_ */ diff --git a/examples/part-04/ch18-writing-pci-driver/stage3-integrated/Makefile b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/Makefile new file mode 100644 index 0000000..60b5234 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/Makefile @@ -0,0 +1,9 @@ +# Makefile for the Chapter 18 Stage 3 myfirst driver. + +KMOD= myfirst +SRCS= myfirst.c myfirst_hw.c myfirst_hw_pci.c myfirst_sim.c \ + myfirst_pci.c cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.1-pci-stage3\" + +.include diff --git a/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_hw_pci.c b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_hw_pci.c new file mode 100644 index 0000000..e86fcc8 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_hw_pci.c @@ -0,0 +1,63 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_hw_pci.c -- Chapter 18 Stage 3 addition to the Chapter 16 + * hardware layer. + * + * Defines myfirst_hw_attach_pci(), which takes an already-allocated + * struct resource * (from bus_alloc_resource_any) and stores its + * tag and handle in the hardware wrapper struct so the Chapter 16 + * accessors operate on the real BAR. + * + * This file is a small addition; the rest of the hardware layer + * (in myfirst_hw.c) remains unchanged from Chapter 16. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" + +MALLOC_DECLARE(M_MYFIRST); + +int +myfirst_hw_attach_pci(struct myfirst_softc *sc, struct resource *bar, + bus_size_t bar_size) +{ + struct myfirst_hw *hw; + + if (bar_size < MYFIRST_REG_SIZE) { + device_printf(sc->dev, + "BAR is too small: %ju bytes, need at least %u\n", + (uintmax_t)bar_size, (unsigned)MYFIRST_REG_SIZE); + return (ENXIO); + } + + hw = malloc(sizeof(*hw), M_MYFIRST, M_WAITOK | M_ZERO); + + hw->regs_buf = NULL; /* no malloc block; BAR is real */ + hw->regs_size = (size_t)bar_size; + hw->regs_tag = rman_get_bustag(bar); + hw->regs_handle = rman_get_bushandle(bar); + hw->access_log_enabled = true; + hw->access_log_head = 0; + + sc->hw = hw; + + device_printf(sc->dev, + "hardware layer attached to BAR: %zu bytes (tag=%p handle=%p)\n", + hw->regs_size, (void *)hw->regs_tag, (void *)hw->regs_handle); + return (0); +} diff --git a/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.c b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.c new file mode 100644 index 0000000..2aeb6b5 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.c @@ -0,0 +1,186 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.c -- Chapter 18 Stage 3 PCI driver. + * + * Stage 3 wires everything together. Attach allocates BAR 0, walks + * the PCI capability list (informational), hands the BAR to the + * hardware layer, creates the cdev, and performs a diagnostic + * register read. Detach undoes all of that in reverse order. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_sim.h" +#include "myfirst_pci.h" + +static const struct myfirst_pci_id myfirst_pci_ids[] = { + { MYFIRST_VENDOR_REDHAT, MYFIRST_DEVICE_VIRTIO_RNG, + "Red Hat Virtio entropy source (myfirst demo target)" }, + { 0, 0, NULL } +}; + +static int +myfirst_pci_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct myfirst_pci_id *id; + + for (id = myfirst_pci_ids; id->desc != NULL; id++) { + if (id->vendor == vendor && id->device == device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static void +myfirst_pci_walk_caps(device_t dev) +{ + int capreg; + + if (pci_find_cap(dev, PCIY_EXPRESS, &capreg) == 0) + device_printf(dev, "PCIe capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_MSI, &capreg) == 0) + device_printf(dev, "MSI capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_MSIX, &capreg) == 0) + device_printf(dev, "MSI-X capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_PMG, &capreg) == 0) + device_printf(dev, "Power Management at 0x%x\n", capreg); + if (pci_find_extcap(dev, PCIZ_AER, &capreg) == 0) + device_printf(dev, "PCIe AER extended cap at 0x%x\n", capreg); +} + +static int +myfirst_pci_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + int error; + + sc->dev = dev; + sc->unit = device_get_unit(dev); + + error = myfirst_init_softc(sc); + if (error != 0) + return (error); + + /* Step 1: allocate BAR0. */ + sc->bar_rid = PCIR_BAR(0); + sc->bar_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->bar_rid, RF_ACTIVE); + if (sc->bar_res == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + error = ENXIO; + goto fail_softc; + } + + /* Step 2: walk PCI capabilities (informational). */ + myfirst_pci_walk_caps(dev); + + /* Step 3: hand the BAR to the hardware layer. */ + error = myfirst_hw_attach_pci(sc, sc->bar_res, + rman_get_size(sc->bar_res)); + if (error != 0) + goto fail_release; + + /* Step 4: create the cdev. */ + sc->cdev = make_dev(&myfirst_cdevsw, sc->unit, UID_ROOT, + GID_WHEEL, 0600, "myfirst%d", sc->unit); + if (sc->cdev == NULL) { + error = ENXIO; + goto fail_hw; + } + sc->cdev->si_drv1 = sc; + + /* Step 5: read a diagnostic word from the BAR. */ + MYFIRST_LOCK(sc); + sc->bar_first_word = CSR_READ_4(sc, 0x00); + MYFIRST_UNLOCK(sc); + device_printf(dev, "BAR[0x00] = 0x%08x\n", sc->bar_first_word); + + sc->pci_attached = true; + return (0); + +fail_hw: + myfirst_hw_detach(sc); +fail_release: + bus_release_resource(dev, SYS_RES_MEMORY, sc->bar_rid, sc->bar_res); + sc->bar_res = NULL; +fail_softc: + myfirst_deinit_softc(sc); + return (error); +} + +static int +myfirst_pci_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + if (myfirst_is_busy(sc)) + return (EBUSY); + + sc->pci_attached = false; + + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + + myfirst_quiesce(sc); + + /* + * Release the simulation backend if it was attached. The PCI + * path leaves sc->sim == NULL, so this is a no-op on the + * default build. + */ + if (sc->sim != NULL) + myfirst_sim_detach(sc); + + myfirst_hw_detach(sc); + + if (sc->bar_res != NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->bar_rid, + sc->bar_res); + sc->bar_res = NULL; + } + + myfirst_deinit_softc(sc); + + device_printf(dev, "detached\n"); + return (0); +} + +static device_method_t myfirst_pci_methods[] = { + DEVMETHOD(device_probe, myfirst_pci_probe), + DEVMETHOD(device_attach, myfirst_pci_attach), + DEVMETHOD(device_detach, myfirst_pci_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_pci_driver = { + "myfirst", + myfirst_pci_methods, + sizeof(struct myfirst_softc), +}; + +DRIVER_MODULE(myfirst, pci, myfirst_pci_driver, NULL, NULL); +MODULE_DEPEND(myfirst, pci, 1, 1, 1); +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.h b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.h new file mode 100644 index 0000000..35f49e4 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage3-integrated/myfirst_pci.h @@ -0,0 +1,36 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.h -- Chapter 18 PCI interface for the myfirst driver. + * + * Stage 3: hw layer bridged to the BAR, capability walk, cdev + * creation per PCI unit. + */ + +#ifndef _MYFIRST_PCI_H_ +#define _MYFIRST_PCI_H_ + +#include + +#define MYFIRST_VENDOR_REDHAT 0x1af4 +#define MYFIRST_DEVICE_VIRTIO_RNG 0x1005 + +struct myfirst_pci_id { + uint16_t vendor; + uint16_t device; + const char *desc; +}; + +/* + * Forward declarations for the hw layer's PCI-backed attach helper, + * introduced in Chapter 18. See myfirst_hw.c for the definition. + */ +struct myfirst_softc; +struct resource; + +int myfirst_hw_attach_pci(struct myfirst_softc *sc, struct resource *bar, + bus_size_t bar_size); + +#endif /* _MYFIRST_PCI_H_ */ diff --git a/examples/part-04/ch18-writing-pci-driver/stage4-final/Makefile b/examples/part-04/ch18-writing-pci-driver/stage4-final/Makefile new file mode 100644 index 0000000..56eb9cc --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage4-final/Makefile @@ -0,0 +1,32 @@ +# Makefile for the Chapter 18 myfirst driver. +# +# Combines: +# - The Chapter 10-15 driver (cdev, softc, locks, callouts, sx, +# taskqueue, sema). +# - The Chapter 16 hardware access layer (myfirst_hw.c and the +# Chapter 18 addition myfirst_hw_pci.c). +# - The Chapter 17 simulation backend (myfirst_sim.c). +# - The Chapter 18 PCI attach layer (myfirst_pci.c). +# +# The driver is loadable as a standalone kernel module via +# kldload(8). When loaded, it participates in PCI probe for every +# device the pci(4) subsystem enumerates; it attaches to any device +# whose vendor/device ID matches an entry in myfirst_pci_ids[]. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + cbuf.c + +# Version string. Update this line alongside any user-visible change. +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.1-pci\" + +# Optional: build without PCI support (simulation only). +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +# Optional: build without simulation fallback (PCI only). +# CFLAGS+= -DMYFIRST_PCI_ONLY + +.include diff --git a/examples/part-04/ch18-writing-pci-driver/stage4-final/PCI.md b/examples/part-04/ch18-writing-pci-driver/stage4-final/PCI.md new file mode 100644 index 0000000..e728587 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage4-final/PCI.md @@ -0,0 +1,92 @@ +# PCI Support in the myfirst Driver + +## Supported Devices + +As of version `1.1-pci`, `myfirst` attaches to PCI devices matching +the following vendor/device ID pairs: + +| Vendor | Device | Description | +| ------ | ------ | ------------------------------------------- | +| 0x1af4 | 0x1005 | Red Hat/virtio-rnd (demo target; see README) | + +The table is maintained in `myfirst_pci.c` as the static array +`myfirst_pci_ids[]`. Adding a new supported device requires: + +1. Appending an entry to `myfirst_pci_ids[]` with the vendor and + device IDs and a human-readable description. +2. Verifying that the driver's BAR layout and register map are + compatible with the new device. +3. Running the Chapter 18 regression script against the new device. +4. Updating this file. + +## Attach Behaviour + +The driver's probe routine (`myfirst_pci_probe`) returns +`BUS_PROBE_DEFAULT` on a match against `myfirst_pci_ids[]` and +`ENXIO` otherwise. Its priority matches the base-system drivers for +the same IDs; readers must ensure no other driver (for example, +`virtio_random` for the demo target) is loaded before `myfirst` can +attach. + +Attach (`myfirst_pci_attach`) follows this sequence: + +1. Store the `device_t` and assigned unit number. +2. Initialise the softc (`myfirst_init_softc`): locks, condition + variables, callouts, taskqueue, statistics. +3. Allocate BAR 0 as `SYS_RES_MEMORY` with `RF_ACTIVE`. +4. Walk the PCI capability list and PCIe extended capability list, + logging the offsets of any recognised capabilities. +5. Attach the Chapter 16 hardware layer against the BAR + (`myfirst_hw_attach_pci`), which stores the tag and handle so + the `CSR_*` accessors operate on real silicon. +6. Create the per-instance cdev `/dev/myfirst`. +7. Read a diagnostic 32-bit value from BAR offset 0 and log it. + +On any failure after step 2 the attach path unwinds through a goto +cascade, undoing exactly the steps that had succeeded. + +## Detach Behaviour + +Detach (`myfirst_pci_detach`) refuses to proceed if the driver is +busy (open file descriptors, in-flight commands) by returning +`EBUSY`. Otherwise it executes in the reverse of attach order: + +1. Mark the driver as no longer PCI-attached. +2. Destroy the cdev. +3. Quiesce callouts and taskqueue tasks. +4. Detach the hardware layer (frees the wrapper struct; does not + touch the BAR). +5. Release the BAR resource. +6. Deinit the softc. + +## Module Dependencies + +- `pci`, version 1: the kernel's PCI subsystem. + +## Compile-Time Options + +- `-DMYFIRST_SIMULATION_ONLY` disables the PCI attach layer. The + driver builds as a simulation-only module, indistinguishable from + the Chapter 17 Stage 5 driver. +- `-DMYFIRST_PCI_ONLY` disables the simulation fallback. The driver + attaches only when a matching PCI device is present; `kldload` + without a matching device produces no attach. + +## Known Limitations + +- The driver does not handle interrupts. A later chapter adds a + real interrupt handler through `bus_setup_intr(9)`. +- The driver does not support DMA. A later chapter adds `bus_dma(9)` + tags and descriptor rings. +- The Chapter 17 simulation backend is not attached on the PCI + path; `sc->sim` remains NULL and the simulation's callouts do not + run. A simulation-only build (`-DMYFIRST_SIMULATION_ONLY`) keeps + the Chapter 17 behaviour for readers who load the driver without a + matching PCI device. + +## See Also + +- `HARDWARE.md` for the register map. +- `SIMULATION.md` for the simulation backend. +- `LOCKING.md` for the lock discipline. +- `README.md` for build and test instructions. diff --git a/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_hw_pci.c b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_hw_pci.c new file mode 100644 index 0000000..34a9cba --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_hw_pci.c @@ -0,0 +1,63 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_hw_pci.c -- Chapter 18 addition to the Chapter 16 + * hardware layer. Provides myfirst_hw_attach_pci(), which binds an + * existing struct resource * (allocated by myfirst_pci.c) to the + * hardware layer's tag and handle fields. + * + * The rest of the Chapter 16 hardware layer (myfirst_hw.c) is + * unchanged. The detach path (myfirst_hw_detach) handles both the + * simulation-backed and the PCI-backed hardware wrappers because it + * checks `hw->regs_buf != NULL` before attempting to free the buffer. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" + +MALLOC_DECLARE(M_MYFIRST); + +int +myfirst_hw_attach_pci(struct myfirst_softc *sc, struct resource *bar, + bus_size_t bar_size) +{ + struct myfirst_hw *hw; + + if (bar_size < MYFIRST_REG_SIZE) { + device_printf(sc->dev, + "BAR is too small: %ju bytes, need at least %u\n", + (uintmax_t)bar_size, (unsigned)MYFIRST_REG_SIZE); + return (ENXIO); + } + + hw = malloc(sizeof(*hw), M_MYFIRST, M_WAITOK | M_ZERO); + hw->regs_buf = NULL; + hw->regs_size = (size_t)bar_size; + hw->regs_tag = rman_get_bustag(bar); + hw->regs_handle = rman_get_bushandle(bar); + hw->access_log_enabled = true; + hw->access_log_head = 0; + + sc->hw = hw; + + device_printf(sc->dev, + "hardware layer attached to BAR: %zu bytes " + "(tag=%p handle=%p)\n", + hw->regs_size, (void *)hw->regs_tag, + (void *)hw->regs_handle); + return (0); +} diff --git a/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.c b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.c new file mode 100644 index 0000000..c25d694 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.c @@ -0,0 +1,216 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.c -- Chapter 18 final PCI attach layer. + * + * Registers the myfirst driver against the pci(4) bus. Probe matches + * a static table of vendor/device ID pairs. Attach claims BAR 0, + * walks the PCI capability list, hands the BAR to the Chapter 16 + * hardware layer, creates the per-instance cdev, and performs a + * diagnostic register read. Detach undoes every step in reverse. + * + * See PCI.md for the user-facing documentation. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_sim.h" +#include "myfirst_pci.h" + +/* ------------------------------------------------------------------ */ +/* ID table */ +/* ------------------------------------------------------------------ */ + +static const struct myfirst_pci_id myfirst_pci_ids[] = { + { MYFIRST_VENDOR_REDHAT, MYFIRST_DEVICE_VIRTIO_RNG, + "Red Hat Virtio entropy source (myfirst demo target)" }, + { 0, 0, NULL } +}; + +/* ------------------------------------------------------------------ */ +/* Probe */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_pci_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct myfirst_pci_id *id; + + for (id = myfirst_pci_ids; id->desc != NULL; id++) { + if (id->vendor == vendor && id->device == device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +/* ------------------------------------------------------------------ */ +/* Capability walk (informational) */ +/* ------------------------------------------------------------------ */ + +static void +myfirst_pci_walk_caps(device_t dev) +{ + int capreg; + + if (pci_find_cap(dev, PCIY_EXPRESS, &capreg) == 0) + device_printf(dev, "PCIe capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_MSI, &capreg) == 0) + device_printf(dev, "MSI capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_MSIX, &capreg) == 0) + device_printf(dev, "MSI-X capability at 0x%x\n", capreg); + if (pci_find_cap(dev, PCIY_PMG, &capreg) == 0) + device_printf(dev, "Power Management at 0x%x\n", capreg); + if (pci_find_extcap(dev, PCIZ_AER, &capreg) == 0) + device_printf(dev, "PCIe AER extended cap at 0x%x\n", capreg); +} + +/* ------------------------------------------------------------------ */ +/* Attach */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_pci_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + int error; + + sc->dev = dev; + sc->unit = device_get_unit(dev); + + device_printf(dev, + "attaching: vendor=0x%04x device=0x%04x revid=0x%02x\n", + pci_get_vendor(dev), pci_get_device(dev), pci_get_revid(dev)); + + error = myfirst_init_softc(sc); + if (error != 0) + return (error); + + sc->bar_rid = PCIR_BAR(0); + sc->bar_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->bar_rid, RF_ACTIVE); + if (sc->bar_res == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + error = ENXIO; + goto fail_softc; + } + + myfirst_pci_walk_caps(dev); + + error = myfirst_hw_attach_pci(sc, sc->bar_res, + rman_get_size(sc->bar_res)); + if (error != 0) + goto fail_release; + + sc->cdev = make_dev(&myfirst_cdevsw, sc->unit, UID_ROOT, + GID_WHEEL, 0600, "myfirst%d", sc->unit); + if (sc->cdev == NULL) { + device_printf(dev, "cannot create cdev\n"); + error = ENXIO; + goto fail_hw; + } + sc->cdev->si_drv1 = sc; + + MYFIRST_LOCK(sc); + sc->bar_first_word = CSR_READ_4(sc, 0x00); + MYFIRST_UNLOCK(sc); + device_printf(dev, "BAR[0x00] = 0x%08x\n", sc->bar_first_word); + + sc->pci_attached = true; + return (0); + +fail_hw: + myfirst_hw_detach(sc); +fail_release: + bus_release_resource(dev, SYS_RES_MEMORY, sc->bar_rid, sc->bar_res); + sc->bar_res = NULL; +fail_softc: + myfirst_deinit_softc(sc); + return (error); +} + +/* ------------------------------------------------------------------ */ +/* Detach */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_pci_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + if (myfirst_is_busy(sc)) + return (EBUSY); + + sc->pci_attached = false; + + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + + myfirst_quiesce(sc); + + /* + * Release the simulation backend if it was attached. The PCI + * attach path leaves sc->sim == NULL, so this is a no-op on + * the default build. A simulation-only build has sc->sim set + * and needs the full teardown. + */ + if (sc->sim != NULL) + myfirst_sim_detach(sc); + + myfirst_hw_detach(sc); + + if (sc->bar_res != NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->bar_rid, + sc->bar_res); + sc->bar_res = NULL; + } + + myfirst_deinit_softc(sc); + + device_printf(dev, "detached\n"); + return (0); +} + +/* ------------------------------------------------------------------ */ +/* Newbus registration */ +/* ------------------------------------------------------------------ */ + +static device_method_t myfirst_pci_methods[] = { + DEVMETHOD(device_probe, myfirst_pci_probe), + DEVMETHOD(device_attach, myfirst_pci_attach), + DEVMETHOD(device_detach, myfirst_pci_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_pci_driver = { + "myfirst", + myfirst_pci_methods, + sizeof(struct myfirst_softc), +}; + +#ifndef MYFIRST_SIMULATION_ONLY +DRIVER_MODULE(myfirst, pci, myfirst_pci_driver, NULL, NULL); +MODULE_DEPEND(myfirst, pci, 1, 1, 1); +#endif +MODULE_VERSION(myfirst, 1); diff --git a/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.h b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.h new file mode 100644 index 0000000..9530c73 --- /dev/null +++ b/examples/part-04/ch18-writing-pci-driver/stage4-final/myfirst_pci.h @@ -0,0 +1,37 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_pci.h -- Chapter 18 PCI interface for the myfirst driver. + * + * Final stage. See PCI.md for the user-facing documentation. + */ + +#ifndef _MYFIRST_PCI_H_ +#define _MYFIRST_PCI_H_ + +#include + +/* + * Target vendor and device IDs for the Chapter 18 demo. Readers + * adapting this driver to real hardware should replace these with + * the IDs advertised by their target device (visible through + * pciconf -lv). + */ +#define MYFIRST_VENDOR_REDHAT 0x1af4 +#define MYFIRST_DEVICE_VIRTIO_RNG 0x1005 + +struct myfirst_pci_id { + uint16_t vendor; + uint16_t device; + const char *desc; +}; + +struct myfirst_softc; +struct resource; + +int myfirst_hw_attach_pci(struct myfirst_softc *sc, struct resource *bar, + bus_size_t bar_size); + +#endif /* _MYFIRST_PCI_H_ */ diff --git a/examples/part-04/ch19-handling-interrupts/labs/full_regression_ch19.sh b/examples/part-04/ch19-handling-interrupts/labs/full_regression_ch19.sh new file mode 100755 index 0000000..7e9da59 --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/labs/full_regression_ch19.sh @@ -0,0 +1,105 @@ +#!/bin/sh +# +# Chapter 19 full regression script. +# +# Verifies the Stage 4 driver's interrupt path end-to-end: +# - Load the module. +# - Verify attach, filter registration, no GIANT-LOCKED. +# - Fire simulated interrupts, check counters. +# - Run the attach/detach cycle. +# - Unload cleanly, check for leaks. + +set -eu + +DRIVER="$(dirname "$0")/../stage4-final/myfirst.ko" +if [ ! -f "$DRIVER" ]; then + DRIVER="./myfirst.ko" +fi + +say() { printf '=== %s ===\n' "$1"; } +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } + +say "Checking prerequisites" +[ -f "$DRIVER" ] || fail "driver module not found: $DRIVER" + +say "Unloading virtio_random if present" +kldstat | grep -q virtio_random && kldunload virtio_random || true + +say "Loading myfirst" +kldload "$DRIVER" +sleep 1 + +say "Verifying attach" +devinfo -v | grep -q 'myfirst0' || fail "myfirst0 not attached" + +say "Verifying GIANT-LOCKED is NOT set" +if dmesg | grep -q 'myfirst0: \[GIANT-LOCKED\]'; then + fail "filter is missing INTR_MPSAFE" +fi + +say "Verifying interrupt event is present" +vmstat -i | grep -q myfirst || fail "no interrupt event for myfirst" + +say "Simulating DATA_AV interrupt" +sysctl dev.myfirst.0.intr_simulate=1 >/dev/null +sleep 0.2 +BEFORE=$(sysctl -n dev.myfirst.0.intr_count) +[ "$BEFORE" -ge 1 ] || fail "intr_count did not increment" + +say "Simulating ten interrupts in a loop" +i=1 +while [ "$i" -le 10 ]; do + sysctl dev.myfirst.0.intr_simulate=1 >/dev/null + i=$((i + 1)) +done +sleep 0.5 +AFTER=$(sysctl -n dev.myfirst.0.intr_count) +[ "$AFTER" -ge $((BEFORE + 10)) ] || fail "intr_count did not reach expected value" + +say "Verifying task invocations" +TASKS=$(sysctl -n dev.myfirst.0.intr_task_invocations) +[ "$TASKS" -ge 1 ] || fail "task never ran" + +say "Simulating all three event types" +sysctl dev.myfirst.0.intr_simulate=2 >/dev/null +sysctl dev.myfirst.0.intr_simulate=4 >/dev/null +sysctl dev.myfirst.0.intr_simulate=7 >/dev/null +sleep 0.2 + +say "Verifying each per-bit counter is non-zero" +DAV=$(sysctl -n dev.myfirst.0.intr_data_av_count) +ERR=$(sysctl -n dev.myfirst.0.intr_error_count) +COMP=$(sysctl -n dev.myfirst.0.intr_complete_count) +[ "$DAV" -ge 1 ] || fail "intr_data_av_count is zero" +[ "$ERR" -ge 1 ] || fail "intr_error_count is zero" +[ "$COMP" -ge 1 ] || fail "intr_complete_count is zero" + +say "Running detach/attach cycles" +SELECTOR=$(pciconf -l | awk '/^myfirst0/{print $1}' \ + | sed 's/myfirst0@//') +[ -n "$SELECTOR" ] || fail "could not determine PCI selector" + +i=1 +while [ "$i" -le 5 ]; do + devctl detach myfirst0 || fail "detach #$i failed" + sleep 0.3 + devctl attach "$SELECTOR" || fail "attach #$i failed" + sleep 0.3 + i=$((i + 1)) +done + +say "Unloading myfirst" +kldunload myfirst + +say "Checking for leaks" +if vmstat -m | awk '/^ *myfirst /{exit ($3 > 0)}'; then + : +else + fail "myfirst allocations still present after unload" +fi + +if vmstat -i | grep -q myfirst; then + fail "interrupt event remains after unload" +fi + +say "Success" diff --git a/examples/part-04/ch19-handling-interrupts/labs/intr_latency_test.c b/examples/part-04/ch19-handling-interrupts/labs/intr_latency_test.c new file mode 100644 index 0000000..76b977c --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/labs/intr_latency_test.c @@ -0,0 +1,87 @@ +/* + * intr_latency_test.c -- Chapter 19 latency harness. + * + * Fires N simulated interrupts via dev.myfirst.0.intr_simulate and + * records the time between the sysctl write and the subsequent + * increment of dev.myfirst.0.intr_task_invocations. + * + * This is a rough measurement: the task runs asynchronously on the + * taskqueue worker thread, so the measurement picks up scheduling + * plus filter plus task. Typical values on a modern system are tens + * of microseconds. + * + * Build: + * cc -o intr_latency_test intr_latency_test.c + * + * Run: + * sudo ./intr_latency_test [iterations] + */ + +#include +#include +#include +#include +#include +#include +#include + +static uint64_t +read_u64_sysctl(const char *name) +{ + uint64_t value = 0; + size_t len = sizeof(value); + + if (sysctlbyname(name, &value, &len, NULL, 0) != 0) { + fprintf(stderr, "sysctlbyname %s: %s\n", name, + strerror(errno)); + exit(1); + } + return (value); +} + +static void +fire_simulate(uint32_t mask) +{ + const char *name = "dev.myfirst.0.intr_simulate"; + + if (sysctlbyname(name, NULL, NULL, &mask, sizeof(mask)) != 0) { + fprintf(stderr, "sysctlbyname %s (write): %s\n", name, + strerror(errno)); + exit(1); + } +} + +int +main(int argc, char **argv) +{ + long iterations = (argc > 1) ? atol(argv[1]) : 100; + struct timespec ts_before, ts_after; + uint64_t tasks_before, tasks_after; + uint64_t total_ns = 0; + + for (long i = 0; i < iterations; i++) { + tasks_before = read_u64_sysctl( + "dev.myfirst.0.intr_task_invocations"); + + clock_gettime(CLOCK_REALTIME, &ts_before); + fire_simulate(1); + + do { + tasks_after = read_u64_sysctl( + "dev.myfirst.0.intr_task_invocations"); + } while (tasks_after == tasks_before); + + clock_gettime(CLOCK_REALTIME, &ts_after); + + uint64_t ns = (uint64_t)(ts_after.tv_sec - + ts_before.tv_sec) * 1000000000ULL + + (uint64_t)(ts_after.tv_nsec - ts_before.tv_nsec); + total_ns += ns; + } + + printf("iterations: %ld\n", iterations); + printf("total ns: %ju\n", (uintmax_t)total_ns); + printf("average ns: %ju\n", (uintmax_t)(total_ns / iterations)); + + return (0); +} diff --git a/examples/part-04/ch19-handling-interrupts/labs/stress_simulate.sh b/examples/part-04/ch19-handling-interrupts/labs/stress_simulate.sh new file mode 100755 index 0000000..36fe715 --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/labs/stress_simulate.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# +# stress_simulate.sh -- fire intr_simulate in a tight loop to +# stress the filter and task pipeline. +# +# Usage: ./stress_simulate.sh [iterations] +# +# Default 10000 iterations. + +set -eu + +ITER="${1:-10000}" + +say() { printf '=== %s ===\n' "$1"; } +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } + +[ -e /dev/myfirst0 ] || fail "/dev/myfirst0 missing; load the driver first" + +say "Firing $ITER simulated interrupts" +START=$(date +%s) +i=1 +while [ "$i" -le "$ITER" ]; do + sysctl dev.myfirst.0.intr_simulate=1 >/dev/null + i=$((i + 1)) +done +END=$(date +%s) +ELAPSED=$((END - START)) + +say "Elapsed: $ELAPSED seconds" + +sleep 1 # give the task a chance to drain + +COUNT=$(sysctl -n dev.myfirst.0.intr_count) +TASKS=$(sysctl -n dev.myfirst.0.intr_task_invocations) + +say "Final counters: intr_count=$COUNT intr_task_invocations=$TASKS" + +if [ "$COUNT" -lt "$ITER" ]; then + fail "intr_count ($COUNT) < iterations ($ITER)" +fi + +say "Success" diff --git a/examples/part-04/ch19-handling-interrupts/labs/vmstat_interrupt_rate.sh b/examples/part-04/ch19-handling-interrupts/labs/vmstat_interrupt_rate.sh new file mode 100755 index 0000000..2de08f5 --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/labs/vmstat_interrupt_rate.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# +# vmstat_interrupt_rate.sh -- sample vmstat -i twice and compute +# per-source interrupt rates over the sampling interval. +# +# Usage: ./vmstat_interrupt_rate.sh [interval_seconds] +# Default interval: 10 seconds. + +set -eu + +INTERVAL="${1:-10}" + +TMP1=$(mktemp) +TMP2=$(mktemp) +trap 'rm -f "$TMP1" "$TMP2"' EXIT + +vmstat -i > "$TMP1" +sleep "$INTERVAL" +vmstat -i > "$TMP2" + +awk -v interval="$INTERVAL" ' + BEGIN { + print "source" "\t" "delta" "\t" "rate (intr/s)" + } + NR==FNR { + if (NR <= 1) next # skip header + before[$1] = $(NF-1) + next + } + { + if (FNR <= 1) next + name = $1 + count_after = $(NF-1) + if (name in before) { + delta = count_after - before[name] + if (delta > 0) { + printf "%-30s\t%d\t%.1f\n", name, delta, + delta / interval + } + } + } +' "$TMP1" "$TMP2" diff --git a/examples/part-04/ch19-handling-interrupts/stage4-final/INTERRUPTS.md b/examples/part-04/ch19-handling-interrupts/stage4-final/INTERRUPTS.md new file mode 100644 index 0000000..e0c0dbb --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/stage4-final/INTERRUPTS.md @@ -0,0 +1,116 @@ +# Interrupt Handling in the myfirst Driver + +## Summary + +The driver registers a single filter handler on the legacy PCI INTx +line through `bus_setup_intr(9)` with `INTR_TYPE_MISC | INTR_MPSAFE`. +The filter reads `INTR_STATUS`, handles each recognised bit +inline (atomically incrementing per-bit counters and writing back +to acknowledge), and enqueues a deferred task on a dedicated +taskqueue for `DATA_AV` events. + +## Files + +- `myfirst_intr.c`: the filter handler, the deferred task, the + setup and teardown helpers, and the interrupt-related sysctls. +- `myfirst_intr.h`: the interface exported to `myfirst_pci.c`, + plus the `ICSR_READ_4` / `ICSR_WRITE_4` interrupt-context + accessor macros. + +## Setup Sequence + +`myfirst_intr_setup()`: + +1. Initialise the deferred-work task (`TASK_INIT`). +2. Create a taskqueue named `"myfirst_intr"` with one worker at + `PI_NET` priority. +3. Allocate an IRQ resource with `rid = 0`, `SYS_RES_IRQ`, + `RF_SHAREABLE | RF_ACTIVE`. +4. Register the filter handler via `bus_setup_intr(9)`. +5. Describe the handler via `bus_describe_intr(9)` as "legacy". +6. Write the device's `INTR_MASK` to enable `DATA_AV | ERROR | + COMPLETE`. + +On any step failing, the function unwinds in reverse. + +## Teardown Sequence + +`myfirst_intr_teardown()`: + +1. Clear the device's `INTR_MASK` (stop the device from asserting). +2. `bus_teardown_intr(9)` (stop the kernel from running the handler). +3. `taskqueue_drain(9)` on the data task (finish in-flight work). +4. `taskqueue_free(9)` (release the taskqueue). +5. `bus_release_resource(9)` on the IRQ (free the resource). + +Safe to call at any stage of attach failure. + +## Filter Behaviour + +`myfirst_intr_filter(sc)`: + +1. Read `INTR_STATUS`. Return `FILTER_STRAY` if zero. +2. Increment `intr_count` atomically. +3. For each of `DATA_AV`, `ERROR`, `COMPLETE`: + - Increment the per-bit counter atomically. + - Write the bit back to `INTR_STATUS` to acknowledge. + - For `DATA_AV`, enqueue the deferred task. +4. Return `FILTER_HANDLED` if any bit was recognised, or + `FILTER_STRAY` otherwise. + +## Deferred Task + +`myfirst_intr_data_task_fn(sc, npending)`: + +1. Acquire `sc->mtx`. +2. If the driver is no longer attached, release the lock and return. +3. Read `DATA_OUT`, store in `sc->intr_last_data`. +4. Increment `intr_task_invocations`. +5. Broadcast `sc->data_cv` to wake any pending readers. +6. Release the lock. + +## Sysctls + +- `dev.myfirst.N.intr_count` (RD, uint64): total filter invocations. +- `dev.myfirst.N.intr_data_av_count` (RD, uint64): DATA_AV events. +- `dev.myfirst.N.intr_error_count` (RD, uint64): ERROR events. +- `dev.myfirst.N.intr_complete_count` (RD, uint64): COMPLETE events. +- `dev.myfirst.N.intr_task_invocations` (RD, uint64): task runs. +- `dev.myfirst.N.intr_last_data` (RD, uint): last `DATA_OUT` value. +- `dev.myfirst.N.intr_simulate` (WR, uint): write a bitmask to set + those bits in `INTR_STATUS` and invoke the filter. Exercises the + full pipeline without real IRQ events. + +## Interrupt-Context Accessor Macros + +The filter cannot take `sc->mtx` (a sleep mutex). Use +`ICSR_READ_4(sc, off)` and `ICSR_WRITE_4(sc, off, val)` from +`myfirst_intr.h` for BAR accesses inside the filter. Outside the +filter, use the usual `CSR_READ_4` and `CSR_WRITE_4` macros, which +assert the lock is held. + +## Lock Ordering + +The filter takes no locks (atomics only). The task takes `sc->mtx`. +The simulated-interrupt sysctl takes `sc->mtx` briefly to set state +and releases before invoking the filter. The existing Chapter 15 +order (`sc->mtx -> sc->cfg_sx -> sc->stats_cache_sx`) is unchanged. + +## Known Limitations + +- Only the legacy PCI INTx line is handled. MSI and MSI-X are Chapter 20. +- The driver does not implement its own interrupt-storm mitigation. + The kernel's `hw.intr_storm_threshold` machinery applies. +- The Chapter 17 register semantics are assumed. On the bhyve + virtio-rnd target, the `INTR_MASK` write at offset 0x10 overlaps + virtio's `queue_notify` + `device_status` + `isr_status` fields + and acts as a harmless virtio device reset; it does not enable any + real interrupt. Exercise the pipeline through the simulated-interrupt + sysctl. + +## See Also + +- `HARDWARE.md` for the register map. +- `LOCKING.md` for the full lock discipline. +- `PCI.md` for the PCI attach behaviour. +- `SIMULATION.md` for the Chapter 17 simulation backend. diff --git a/examples/part-04/ch19-handling-interrupts/stage4-final/Makefile b/examples/part-04/ch19-handling-interrupts/stage4-final/Makefile new file mode 100644 index 0000000..52423d6 --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/stage4-final/Makefile @@ -0,0 +1,27 @@ +# Makefile for the Chapter 19 myfirst driver. +# +# Combines: +# - Ch10-15 driver (cdev, softc, locks, callouts, sx, taskqueue, sema). +# - Ch16 hardware access layer. +# - Ch17 simulation backend (inactive on PCI build). +# - Ch18 PCI attach. +# - Ch19 interrupt handler (NEW). + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + cbuf.c + +# Version string. Update this line alongside any user-visible change. +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.2-intr\" + +# Optional: build without PCI support (simulation only). +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +# Optional: build without simulation fallback (PCI only). +# CFLAGS+= -DMYFIRST_PCI_ONLY + +.include diff --git a/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.c b/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.c new file mode 100644 index 0000000..f30a56c --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.c @@ -0,0 +1,263 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_intr.c -- Chapter 19 interrupt-handling layer. + * + * Implements: + * - The filter handler (myfirst_intr_filter). + * - The deferred taskqueue task (myfirst_intr_data_task_fn). + * - The setup and teardown helpers called from the PCI layer. + * - The interrupt-related sysctls, including the simulated- + * interrupt sysctl for testing. + * + * The filter runs in primary interrupt context: it must not sleep, + * must not take sc->mtx, and should return quickly. The deferred + * task runs in thread context on a single-worker taskqueue. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_intr.h" + +/* Forward declarations. */ +static void myfirst_intr_data_task_fn(void *arg, int npending); +static int myfirst_intr_simulate_sysctl(SYSCTL_HANDLER_ARGS); + +/* ------------------------------------------------------------------ */ +/* Filter handler */ +/* ------------------------------------------------------------------ */ + +int +myfirst_intr_filter(void *arg) +{ + struct myfirst_softc *sc = arg; + uint32_t status; + int rv = 0; + + status = ICSR_READ_4(sc, MYFIRST_REG_INTR_STATUS); + if (status == 0) + return (FILTER_STRAY); + + atomic_add_64(&sc->intr_count, 1); + + if (status & MYFIRST_INTR_DATA_AV) { + atomic_add_64(&sc->intr_data_av_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, + MYFIRST_INTR_DATA_AV); + if (sc->intr_tq != NULL) + taskqueue_enqueue(sc->intr_tq, &sc->intr_data_task); + rv |= FILTER_HANDLED; + } + + if (status & MYFIRST_INTR_ERROR) { + atomic_add_64(&sc->intr_error_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, + MYFIRST_INTR_ERROR); + rv |= FILTER_HANDLED; + } + + if (status & MYFIRST_INTR_COMPLETE) { + atomic_add_64(&sc->intr_complete_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, + MYFIRST_INTR_COMPLETE); + rv |= FILTER_HANDLED; + } + + if (rv == 0) + return (FILTER_STRAY); + + return (rv); +} + +/* ------------------------------------------------------------------ */ +/* Deferred task */ +/* ------------------------------------------------------------------ */ + +static void +myfirst_intr_data_task_fn(void *arg, int npending) +{ + struct myfirst_softc *sc = arg; + uint32_t data; + + MYFIRST_LOCK(sc); + if (sc->hw == NULL || !sc->pci_attached) { + MYFIRST_UNLOCK(sc); + return; + } + data = CSR_READ_4(sc, MYFIRST_REG_DATA_OUT); + sc->intr_last_data = data; + sc->intr_task_invocations++; + cv_broadcast(&sc->data_cv); + MYFIRST_UNLOCK(sc); +} + +/* ------------------------------------------------------------------ */ +/* Setup */ +/* ------------------------------------------------------------------ */ + +int +myfirst_intr_setup(struct myfirst_softc *sc) +{ + int error; + + TASK_INIT(&sc->intr_data_task, 0, myfirst_intr_data_task_fn, sc); + sc->intr_tq = taskqueue_create("myfirst_intr", M_WAITOK, + taskqueue_thread_enqueue, &sc->intr_tq); + taskqueue_start_threads(&sc->intr_tq, 1, PI_NET, + "myfirst intr taskq"); + + sc->irq_rid = 0; + sc->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, + &sc->irq_rid, RF_SHAREABLE | RF_ACTIVE); + if (sc->irq_res == NULL) { + device_printf(sc->dev, "cannot allocate IRQ\n"); + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + return (ENXIO); + } + + error = bus_setup_intr(sc->dev, sc->irq_res, + INTR_TYPE_MISC | INTR_MPSAFE, + myfirst_intr_filter, NULL, sc, + &sc->intr_cookie); + if (error != 0) { + device_printf(sc->dev, "bus_setup_intr failed (%d)\n", + error); + bus_release_resource(sc->dev, SYS_RES_IRQ, sc->irq_rid, + sc->irq_res); + sc->irq_res = NULL; + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + return (error); + } + + bus_describe_intr(sc->dev, sc->irq_res, sc->intr_cookie, + "legacy"); + + /* Enable the interrupts we care about at the device. */ + MYFIRST_LOCK(sc); + if (sc->hw != NULL) + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, + MYFIRST_INTR_DATA_AV | MYFIRST_INTR_ERROR | + MYFIRST_INTR_COMPLETE); + MYFIRST_UNLOCK(sc); + + device_printf(sc->dev, + "attached filter handler on IRQ resource\n"); + return (0); +} + +/* ------------------------------------------------------------------ */ +/* Teardown */ +/* ------------------------------------------------------------------ */ + +void +myfirst_intr_teardown(struct myfirst_softc *sc) +{ + /* Disable device-side interrupts first. */ + MYFIRST_LOCK(sc); + if (sc->hw != NULL && sc->bar_res != NULL) + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, 0); + MYFIRST_UNLOCK(sc); + + /* Tear down the kernel handler. */ + if (sc->intr_cookie != NULL) { + bus_teardown_intr(sc->dev, sc->irq_res, sc->intr_cookie); + sc->intr_cookie = NULL; + } + + /* Drain and destroy the deferred-work taskqueue. */ + if (sc->intr_tq != NULL) { + taskqueue_drain(sc->intr_tq, &sc->intr_data_task); + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + } + + /* Release the IRQ resource. */ + if (sc->irq_res != NULL) { + bus_release_resource(sc->dev, SYS_RES_IRQ, sc->irq_rid, + sc->irq_res); + sc->irq_res = NULL; + } +} + +/* ------------------------------------------------------------------ */ +/* Simulated interrupts */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_intr_simulate_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + uint32_t mask = 0; + int error; + + error = sysctl_handle_int(oidp, &mask, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL || sc->bar_res == NULL) { + MYFIRST_UNLOCK(sc); + return (ENODEV); + } + bus_write_4(sc->bar_res, MYFIRST_REG_INTR_STATUS, mask); + MYFIRST_UNLOCK(sc); + + (void)myfirst_intr_filter(sc); + return (0); +} + +/* ------------------------------------------------------------------ */ +/* sysctl registration */ +/* ------------------------------------------------------------------ */ + +void +myfirst_intr_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid_list *kids = SYSCTL_CHILDREN(sc->sysctl_tree); + + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "intr_count", + CTLFLAG_RD, &sc->intr_count, 0, + "Total interrupt filter invocations"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "intr_data_av_count", + CTLFLAG_RD, &sc->intr_data_av_count, 0, + "DATA_AV events seen"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "intr_error_count", + CTLFLAG_RD, &sc->intr_error_count, 0, + "ERROR events seen"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "intr_complete_count", + CTLFLAG_RD, &sc->intr_complete_count, 0, + "COMPLETE events seen"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "intr_task_invocations", + CTLFLAG_RD, &sc->intr_task_invocations, 0, + "Deferred task runs"); + SYSCTL_ADD_UINT(ctx, kids, OID_AUTO, "intr_last_data", + CTLFLAG_RD, &sc->intr_last_data, 0, + "Last DATA_OUT value read by the task"); + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "intr_simulate", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, + sc, 0, myfirst_intr_simulate_sysctl, "IU", + "Simulate an interrupt by setting INTR_STATUS bits and " + "invoking the filter"); +} diff --git a/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.h b/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.h new file mode 100644 index 0000000..f789a76 --- /dev/null +++ b/examples/part-04/ch19-handling-interrupts/stage4-final/myfirst_intr.h @@ -0,0 +1,62 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_intr.h -- Chapter 19 interrupt-handler interface. + * + * Exposes the three functions the PCI layer calls to bring up and + * tear down the interrupt path, the sysctl-registration helper, and + * a pair of interrupt-context accessor macros that do not assert + * sc->mtx is held (so they are safe inside the filter). + */ + +#ifndef _MYFIRST_INTR_H_ +#define _MYFIRST_INTR_H_ + +#include +#include + +struct myfirst_softc; +struct resource; + +/* + * Allocate the IRQ resource, register the filter handler, create + * the deferred-work taskqueue, and enable the device's interrupts + * (by writing to INTR_MASK). Returns 0 on success, errno on failure. + * On failure, the function undoes any partial setup. + */ +int myfirst_intr_setup(struct myfirst_softc *sc); + +/* + * Disable the device's interrupts, tear down the handler, drain + * and destroy the taskqueue, and release the IRQ resource. Safe + * to call against a partially-set-up state. + */ +void myfirst_intr_teardown(struct myfirst_softc *sc); + +/* + * Register the interrupt-related sysctls (counters and the + * intr_simulate sysctl). Call after the softc's sysctl tree is + * established. + */ +void myfirst_intr_add_sysctls(struct myfirst_softc *sc); + +/* + * Interrupt-context accessor macros. These use bus_read_4 / + * bus_write_4 directly against the resource without asserting + * any lock. Safe in the filter; use CSR_READ_4 / CSR_WRITE_4 in + * every other context. + */ +#define ICSR_READ_4(sc, off) \ + bus_read_4((sc)->bar_res, (off)) +#define ICSR_WRITE_4(sc, off, val) \ + bus_write_4((sc)->bar_res, (off), (val)) + +/* + * The filter handler is exported so the simulated-interrupt + * sysctl can invoke it directly. + */ +int myfirst_intr_filter(void *arg); + +#endif /* _MYFIRST_INTR_H_ */ diff --git a/examples/part-04/ch20-advanced-interrupts/labs/discover_msi.sh b/examples/part-04/ch20-advanced-interrupts/labs/discover_msi.sh new file mode 100755 index 0000000..c0d4487 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/labs/discover_msi.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# +# discover_msi.sh -- list MSI and MSI-X capabilities of all PCI +# devices on the current host. + +set -eu + +pciconf -lvc | awk ' +/^[a-z]/ { device = $0; msi = ""; msix = "" } +/cap 05\[/ { msi = $0 } +/cap 11\[/ { msix = $0 } +/^$/ { + if (msi != "" || msix != "") { + print device + if (msi != "") print " " msi + if (msix != "") print " " msix + print "" + } +}' diff --git a/examples/part-04/ch20-advanced-interrupts/labs/full_regression_ch20.sh b/examples/part-04/ch20-advanced-interrupts/labs/full_regression_ch20.sh new file mode 100755 index 0000000..e96cd84 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/labs/full_regression_ch20.sh @@ -0,0 +1,111 @@ +#!/bin/sh +# +# Chapter 20 full regression script. +# +# Verifies the Stage 4 driver's multi-vector interrupt path end to end: +# - Load the module. +# - Verify attach and the reported interrupt mode. +# - Fire per-vector simulated interrupts, check per-vector counters. +# - Run detach/attach cycle, ensuring mode persists across. +# - Unload cleanly, check for leaks. + +set -eu + +DRIVER="$(dirname "$0")/../stage4-final/myfirst.ko" +if [ ! -f "$DRIVER" ]; then + DRIVER="./myfirst.ko" +fi + +say() { printf '=== %s ===\n' "$1"; } +fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; } + +say "Checking prerequisites" +[ -f "$DRIVER" ] || fail "driver module not found: $DRIVER" + +say "Unloading virtio_random if present" +kldstat | grep -q virtio_random && kldunload virtio_random || true + +say "Loading myfirst" +kldload "$DRIVER" +sleep 1 + +say "Verifying attach" +devinfo -v | grep -q 'myfirst0' || fail "myfirst0 not attached" + +say "Verifying interrupt mode" +MODE=$(sysctl -n dev.myfirst.0.intr_mode) +case "$MODE" in + 0) say "mode: legacy INTx";; + 1) say "mode: MSI";; + 2) say "mode: MSI-X";; + *) fail "unexpected intr_mode: $MODE";; +esac + +say "Verifying no GIANT-LOCKED" +if dmesg | grep -q 'myfirst0: \[GIANT-LOCKED\]'; then + fail "driver registered without INTR_MPSAFE" +fi + +say "Verifying vmstat -i entry exists" +vmstat -i | grep -q myfirst || fail "no interrupt entry" + +say "Simulating admin interrupt" +sysctl dev.myfirst.0.intr_simulate_admin=2 >/dev/null +sleep 0.2 + +say "Simulating rx interrupt" +sysctl dev.myfirst.0.intr_simulate_rx=1 >/dev/null +sleep 0.2 + +say "Simulating tx interrupt" +sysctl dev.myfirst.0.intr_simulate_tx=4 >/dev/null +sleep 0.2 + +say "Verifying per-vector counters ticked" +AD=$(sysctl -n dev.myfirst.0.vec0_fire_count) +RX=$(sysctl -n dev.myfirst.0.vec1_fire_count 2>/dev/null || echo 0) +TX=$(sysctl -n dev.myfirst.0.vec2_fire_count 2>/dev/null || echo 0) +[ "$AD" -ge 1 ] || fail "admin counter did not tick" + +# Only MSI-X (mode 2) has three distinct per-vector filters. The MSI +# tier (mode 1) uses one vector with the Chapter 19 single-handler, +# and the legacy tier (mode 0) is the same single-handler case; on +# both of those, the rx and tx per-vector counters stay at zero +# because slot 0's filter handles every bit. The Chapter 19 global +# counters (intr_count, intr_data_av_count, etc.) are what move. +if [ "$MODE" = "2" ]; then + [ "$RX" -ge 1 ] || fail "rx counter did not tick (MSI-X)" + [ "$TX" -ge 1 ] || fail "tx counter did not tick (MSI-X)" +fi + +say "Running detach/attach cycles" +SELECTOR=$(pciconf -l | awk '/^myfirst0/{print $1}' \ + | sed 's/myfirst0@//') +[ -n "$SELECTOR" ] || fail "could not determine PCI selector" + +i=1 +while [ "$i" -le 3 ]; do + devctl detach myfirst0 || fail "detach #$i" + sleep 0.3 + devctl attach "$SELECTOR" || fail "attach #$i" + sleep 0.3 + NEW_MODE=$(sysctl -n dev.myfirst.0.intr_mode) + [ "$NEW_MODE" = "$MODE" ] || fail "mode changed across reattach" + i=$((i + 1)) +done + +say "Unloading" +kldunload myfirst + +say "Checking for leaks" +if vmstat -m | awk '/^ *myfirst /{exit ($3 > 0)}'; then + : +else + fail "myfirst allocations remain after unload" +fi + +if vmstat -i | grep -q myfirst; then + fail "interrupt event remains after unload" +fi + +say "Success" diff --git a/examples/part-04/ch20-advanced-interrupts/labs/show_vector_bindings.sh b/examples/part-04/ch20-advanced-interrupts/labs/show_vector_bindings.sh new file mode 100755 index 0000000..7315d84 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/labs/show_vector_bindings.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# +# show_vector_bindings.sh -- show each myfirst vector's IRQ number, +# descriptor, CPU binding, and fire count. +# +# Requires the myfirst driver to be loaded. + +set -eu + +UNIT="${1:-0}" + +if ! sysctl -n "dev.myfirst.${UNIT}.intr_mode" >/dev/null 2>&1; then + echo "myfirst${UNIT} is not loaded or not attached" >&2 + exit 1 +fi + +mode=$(sysctl -n "dev.myfirst.${UNIT}.intr_mode") +case "$mode" in + 0) mode_str="legacy INTx" ;; + 1) mode_str="MSI" ;; + 2) mode_str="MSI-X" ;; +esac +echo "myfirst${UNIT} interrupt mode: $mode_str" + +printf '%-25s %-10s %-15s %-10s\n' \ + "name" "irq" "cpu mask" "fires" + +vmstat -i | awk -v unit="$UNIT" ' +/myfirst/ && $0 ~ "myfirst" unit { + # vmstat -i format: "irqN: name total rate" + # Parse the irq number and the handler name. + split($0, fields, /[[:space:]]+/) + irq = fields[1] + gsub(":", "", irq) + sub(/^irq/, "", irq) + name = fields[2] + total = fields[3] + print irq "|" name "|" total +}' | while IFS='|' read irq name total; do + mask=$(cpuset -g -x "$irq" 2>/dev/null | awk '{print $NF}') + printf '%-25s %-10s %-15s %-10s\n' "$name" "$irq" "$mask" "$total" +done diff --git a/examples/part-04/ch20-advanced-interrupts/labs/stress_per_vector.sh b/examples/part-04/ch20-advanced-interrupts/labs/stress_per_vector.sh new file mode 100755 index 0000000..8010103 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/labs/stress_per_vector.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# +# stress_per_vector.sh -- fire N simulated interrupts at each vector +# and report per-vector counters. +# +# Usage: stress_per_vector.sh [iterations] +# Default: 1000 per vector. + +set -eu + +N="${1:-1000}" + +BEFORE_ADMIN=$(sysctl -n dev.myfirst.0.vec0_fire_count 2>/dev/null || echo 0) +BEFORE_RX=$(sysctl -n dev.myfirst.0.vec1_fire_count 2>/dev/null || echo 0) +BEFORE_TX=$(sysctl -n dev.myfirst.0.vec2_fire_count 2>/dev/null || echo 0) + +say() { printf '=== %s ===\n' "$1"; } + +say "Firing $N admin interrupts" +i=1 +while [ "$i" -le "$N" ]; do + sysctl dev.myfirst.0.intr_simulate_admin=2 >/dev/null + i=$((i + 1)) +done + +say "Firing $N rx interrupts" +i=1 +while [ "$i" -le "$N" ]; do + sysctl dev.myfirst.0.intr_simulate_rx=1 >/dev/null + i=$((i + 1)) +done + +say "Firing $N tx interrupts" +i=1 +while [ "$i" -le "$N" ]; do + sysctl dev.myfirst.0.intr_simulate_tx=4 >/dev/null + i=$((i + 1)) +done + +sleep 1 + +AFTER_ADMIN=$(sysctl -n dev.myfirst.0.vec0_fire_count 2>/dev/null || echo 0) +AFTER_RX=$(sysctl -n dev.myfirst.0.vec1_fire_count 2>/dev/null || echo 0) +AFTER_TX=$(sysctl -n dev.myfirst.0.vec2_fire_count 2>/dev/null || echo 0) + +say "Per-vector deltas" +echo "admin: $((AFTER_ADMIN - BEFORE_ADMIN))" +echo "rx: $((AFTER_RX - BEFORE_RX ))" +echo "tx: $((AFTER_TX - BEFORE_TX ))" + +if [ $((AFTER_ADMIN - BEFORE_ADMIN)) -lt "$N" ]; then + echo "WARN: admin delta less than requested" >&2 +fi diff --git a/examples/part-04/ch20-advanced-interrupts/stage4-final/MSIX.md b/examples/part-04/ch20-advanced-interrupts/stage4-final/MSIX.md new file mode 100644 index 0000000..e250692 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/stage4-final/MSIX.md @@ -0,0 +1,72 @@ +# MSI and MSI-X Support in the myfirst Driver + +## Summary + +The driver probes the device's MSI-X, MSI, and legacy INTx capabilities +in that order, and uses the first one that allocates successfully. + +## Fallback Ladder + +1. **MSI-X** with `MYFIRST_MAX_VECTORS` (3) vectors. On success: + - Per-vector IRQ resources at rid=1, 2, 3. + - Distinct filter function per vector. + - `bus_describe_intr` with per-vector name ("admin", "rx", "tx"). + - `bus_bind_intr` round-robin across CPUs. +2. **MSI** with 1 vector (single-handler fallback). MSI requires a + power-of-two vector count (PCI spec; `pci_alloc_msi_method` returns + `EINVAL` for count=3), so the driver requests 1 MSI vector and uses + the Chapter 19 `myfirst_intr_filter` at rid=1. This matches the + fallback used in `sys/dev/virtio/pci/virtio_pci.c`. +3. **Legacy INTx** with a single handler at rid=0 using the Chapter 19 + `myfirst_intr_filter`. + +## Per-Vector Assignment + +| Vector | ID | Purpose | Handles | Inline/Deferred | +|--------|----|---------|---------------------------|-----------------| +| 0 | admin | admin/error | INTR_STATUS.ERROR | Inline | +| 1 | rx | receive | INTR_STATUS.DATA_AV | Deferred (task) | +| 2 | tx | transmit | INTR_STATUS.COMPLETE | Inline | + +## sysctls + +- `dev.myfirst.N.intr_mode`: 0=legacy, 1=MSI, 2=MSI-X. +- `dev.myfirst.N.vec{0,1,2}_fire_count`: per-vector fire counts. +- `dev.myfirst.N.vec{0,1,2}_stray_count`: per-vector stray counts. +- `dev.myfirst.N.intr_simulate_admin|rx|tx`: simulated interrupts. + +## Teardown Sequence + +1. Disable interrupts at the device (clear INTR_MASK). +2. Per-vector in reverse: `bus_teardown_intr`, `bus_release_resource`. +3. Drain each per-vector task, then `taskqueue_free`. +4. `pci_release_msi(dev)` if mode is MSI or MSI-X. + +## dmesg Summary + +On attach one of: +- `interrupt mode: MSI-X, 3 vectors` +- `interrupt mode: MSI, 3 vectors` +- `interrupt mode: legacy INTx (1 handler for all events)` + +## Known Limitations + +- `MYFIRST_MAX_VECTORS` is hardcoded at 3. Dynamic adaptation is a + challenge exercise. +- CPU binding is round-robin. NUMA-aware binding via `bus_get_cpus` is + a challenge exercise. +- DMA is Chapter 21. +- iflib integration is out of scope. + +## Test Environments + +- **bhyve with virtio-rnd**: legacy INTx fallback. The device does + not expose MSI-X in this configuration. +- **QEMU with `-device virtio-rng-pci`**: MSI-X path. + +## See Also + +- `INTERRUPTS.md`: Chapter 19 single-vector details. +- `HARDWARE.md`: register map. +- `LOCKING.md`: lock discipline. +- `PCI.md`: PCI attach. diff --git a/examples/part-04/ch20-advanced-interrupts/stage4-final/Makefile b/examples/part-04/ch20-advanced-interrupts/stage4-final/Makefile new file mode 100644 index 0000000..c33b95d --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/stage4-final/Makefile @@ -0,0 +1,25 @@ +# Makefile for the Chapter 20 myfirst driver. +# +# Combines: +# - Ch10-15 driver. +# - Ch16 hardware layer. +# - Ch17 simulation backend. +# - Ch18 PCI attach. +# - Ch19 single-vector interrupt handler (legacy INTx fallback). +# - Ch20 multi-vector MSI/MSI-X layer (NEW). + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.3-msi\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.c b/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.c new file mode 100644 index 0000000..81cd938 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.c @@ -0,0 +1,443 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_msix.c -- Chapter 20 multi-vector interrupt layer. + * + * Implements the three-tier fallback ladder (MSI-X -> MSI -> legacy), + * per-vector filter handlers (admin, rx, tx), per-vector counters, + * per-vector deferred task for RX, CPU binding on MSI-X, and the + * simulated-interrupt sysctl per vector. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_intr.h" +#include "myfirst_msix.h" + +/* Forward declarations. */ +static int myfirst_msix_setup_vector(struct myfirst_softc *sc, + int idx, int rid); +static void myfirst_msix_teardown_vector(struct myfirst_softc *sc, + int idx); +static void myfirst_msix_bind_vectors(struct myfirst_softc *sc); +static void myfirst_msix_rx_task_fn(void *arg, int npending); +static int myfirst_msix_admin_filter(void *arg); +static int myfirst_msix_rx_filter(void *arg); +static int myfirst_msix_tx_filter(void *arg); +static int myfirst_intr_simulate_vector_sysctl(SYSCTL_HANDLER_ARGS); + +/* ------------------------------------------------------------------ */ +/* Per-vector helpers */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_msix_setup_vector(struct myfirst_softc *sc, int idx, int rid) +{ + struct myfirst_vector *vec = &sc->vectors[idx]; + int error; + + vec->irq_rid = rid; + vec->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, + &vec->irq_rid, RF_ACTIVE); + if (vec->irq_res == NULL) + return (ENXIO); + + error = bus_setup_intr(sc->dev, vec->irq_res, + INTR_TYPE_MISC | INTR_MPSAFE, + vec->filter, NULL, vec, &vec->intr_cookie); + if (error != 0) { + bus_release_resource(sc->dev, SYS_RES_IRQ, + vec->irq_rid, vec->irq_res); + vec->irq_res = NULL; + return (error); + } + + bus_describe_intr(sc->dev, vec->irq_res, vec->intr_cookie, + "%s", vec->name); + return (0); +} + +static void +myfirst_msix_teardown_vector(struct myfirst_softc *sc, int idx) +{ + struct myfirst_vector *vec = &sc->vectors[idx]; + + if (vec->intr_cookie != NULL) { + bus_teardown_intr(sc->dev, vec->irq_res, vec->intr_cookie); + vec->intr_cookie = NULL; + } + if (vec->irq_res != NULL) { + bus_release_resource(sc->dev, SYS_RES_IRQ, + vec->irq_rid, vec->irq_res); + vec->irq_res = NULL; + } +} + +static void +myfirst_msix_bind_vectors(struct myfirst_softc *sc) +{ + int i, cpu, err; + + if (mp_ncpus < 2) + return; + + for (i = 0; i < sc->num_vectors; i++) { + cpu = i % mp_ncpus; + err = bus_bind_intr(sc->dev, sc->vectors[i].irq_res, cpu); + if (err != 0) + device_printf(sc->dev, + "bus_bind_intr vec %d to CPU %d: %d\n", + i, cpu, err); + } +} + +/* ------------------------------------------------------------------ */ +/* Per-vector filters */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_msix_admin_filter(void *arg) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + uint32_t status; + + status = ICSR_READ_4(sc, MYFIRST_REG_INTR_STATUS); + if ((status & MYFIRST_INTR_ERROR) == 0) { + atomic_add_64(&vec->stray_count, 1); + return (FILTER_STRAY); + } + + atomic_add_64(&vec->fire_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, MYFIRST_INTR_ERROR); + atomic_add_64(&sc->intr_error_count, 1); + return (FILTER_HANDLED); +} + +static int +myfirst_msix_rx_filter(void *arg) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + uint32_t status; + + status = ICSR_READ_4(sc, MYFIRST_REG_INTR_STATUS); + if ((status & MYFIRST_INTR_DATA_AV) == 0) { + atomic_add_64(&vec->stray_count, 1); + return (FILTER_STRAY); + } + + atomic_add_64(&vec->fire_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, MYFIRST_INTR_DATA_AV); + atomic_add_64(&sc->intr_data_av_count, 1); + if (sc->intr_tq != NULL) + taskqueue_enqueue(sc->intr_tq, &vec->task); + return (FILTER_HANDLED); +} + +static int +myfirst_msix_tx_filter(void *arg) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + uint32_t status; + + status = ICSR_READ_4(sc, MYFIRST_REG_INTR_STATUS); + if ((status & MYFIRST_INTR_COMPLETE) == 0) { + atomic_add_64(&vec->stray_count, 1); + return (FILTER_STRAY); + } + + atomic_add_64(&vec->fire_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, MYFIRST_INTR_COMPLETE); + atomic_add_64(&sc->intr_complete_count, 1); + return (FILTER_HANDLED); +} + +/* ------------------------------------------------------------------ */ +/* Deferred task (RX only) */ +/* ------------------------------------------------------------------ */ + +static void +myfirst_msix_rx_task_fn(void *arg, int npending) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + + MYFIRST_LOCK(sc); + if (sc->hw != NULL && sc->pci_attached) { + sc->intr_last_data = CSR_READ_4(sc, MYFIRST_REG_DATA_OUT); + sc->intr_task_invocations++; + cv_broadcast(&sc->data_cv); + } + MYFIRST_UNLOCK(sc); +} + +/* ------------------------------------------------------------------ */ +/* Setup (three-tier fallback ladder) */ +/* ------------------------------------------------------------------ */ + +int +myfirst_msix_setup(struct myfirst_softc *sc) +{ + int error, wanted, allocated, i; + + /* Initialise per-vector state common to all tiers. */ + for (i = 0; i < MYFIRST_MAX_VECTORS; i++) { + sc->vectors[i].id = i; + sc->vectors[i].sc = sc; + } + TASK_INIT(&sc->vectors[MYFIRST_VECTOR_RX].task, 0, + myfirst_msix_rx_task_fn, + &sc->vectors[MYFIRST_VECTOR_RX]); + sc->vectors[MYFIRST_VECTOR_RX].has_task = true; + sc->vectors[MYFIRST_VECTOR_ADMIN].filter = myfirst_msix_admin_filter; + sc->vectors[MYFIRST_VECTOR_RX].filter = myfirst_msix_rx_filter; + sc->vectors[MYFIRST_VECTOR_TX].filter = myfirst_msix_tx_filter; + sc->vectors[MYFIRST_VECTOR_ADMIN].name = "admin"; + sc->vectors[MYFIRST_VECTOR_RX].name = "rx"; + sc->vectors[MYFIRST_VECTOR_TX].name = "tx"; + + sc->intr_tq = taskqueue_create("myfirst_intr", M_WAITOK, + taskqueue_thread_enqueue, &sc->intr_tq); + taskqueue_start_threads(&sc->intr_tq, 1, PI_NET, + "myfirst intr taskq"); + + wanted = MYFIRST_MAX_VECTORS; + + /* Tier 0: MSI-X. */ + if (pci_msix_count(sc->dev) >= wanted) { + allocated = wanted; + if (pci_alloc_msix(sc->dev, &allocated) == 0 && + allocated == wanted) { + for (i = 0; i < wanted; i++) { + error = myfirst_msix_setup_vector(sc, i, + i + 1); + if (error != 0) { + for (i -= 1; i >= 0; i--) + myfirst_msix_teardown_vector( + sc, i); + pci_release_msi(sc->dev); + goto try_msi; + } + } + sc->intr_mode = MYFIRST_INTR_MSIX; + sc->num_vectors = wanted; + myfirst_msix_bind_vectors(sc); + device_printf(sc->dev, + "interrupt mode: MSI-X, %d vectors\n", wanted); + goto enabled; + } + if (allocated > 0) + pci_release_msi(sc->dev); + } + +try_msi: + /* + * Tier 1: MSI with a single vector. MSI requires a power-of-two + * count (PCI spec enforced by pci_alloc_msi_method); we cannot + * request MYFIRST_MAX_VECTORS here, so we ask for 1 and fall back + * to the Chapter 19 single-handler pattern. This matches + * vtpci_alloc_msi() in sys/dev/virtio/pci/virtio_pci.c. + */ + allocated = 1; + if (pci_msi_count(sc->dev) >= 1 && + pci_alloc_msi(sc->dev, &allocated) == 0 && allocated >= 1) { + sc->vectors[MYFIRST_VECTOR_ADMIN].filter = myfirst_intr_filter; + sc->vectors[MYFIRST_VECTOR_ADMIN].name = "msi"; + error = myfirst_msix_setup_vector(sc, MYFIRST_VECTOR_ADMIN, 1); + if (error == 0) { + sc->intr_mode = MYFIRST_INTR_MSI; + sc->num_vectors = 1; + device_printf(sc->dev, + "interrupt mode: MSI, 1 vector " + "(single-handler fallback)\n"); + goto enabled; + } + pci_release_msi(sc->dev); + } + +try_legacy: + /* Tier 2: legacy INTx. Use the Chapter 19 single filter on rid 0. */ + sc->vectors[MYFIRST_VECTOR_ADMIN].filter = myfirst_intr_filter; + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_rid = 0; + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res = bus_alloc_resource_any( + sc->dev, SYS_RES_IRQ, + &sc->vectors[MYFIRST_VECTOR_ADMIN].irq_rid, + RF_SHAREABLE | RF_ACTIVE); + if (sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res == NULL) { + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + return (ENXIO); + } + error = bus_setup_intr(sc->dev, + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res, + INTR_TYPE_MISC | INTR_MPSAFE, + myfirst_intr_filter, NULL, sc, + &sc->vectors[MYFIRST_VECTOR_ADMIN].intr_cookie); + if (error != 0) { + bus_release_resource(sc->dev, SYS_RES_IRQ, + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_rid, + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res); + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res = NULL; + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + return (error); + } + bus_describe_intr(sc->dev, + sc->vectors[MYFIRST_VECTOR_ADMIN].irq_res, + sc->vectors[MYFIRST_VECTOR_ADMIN].intr_cookie, "legacy"); + sc->intr_mode = MYFIRST_INTR_LEGACY; + sc->num_vectors = 1; + device_printf(sc->dev, + "interrupt mode: legacy INTx (1 handler for all events)\n"); + +enabled: + MYFIRST_LOCK(sc); + if (sc->hw != NULL) + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, + MYFIRST_INTR_DATA_AV | MYFIRST_INTR_ERROR | + MYFIRST_INTR_COMPLETE); + MYFIRST_UNLOCK(sc); + + return (0); +} + +/* ------------------------------------------------------------------ */ +/* Teardown */ +/* ------------------------------------------------------------------ */ + +void +myfirst_msix_teardown(struct myfirst_softc *sc) +{ + int i; + + MYFIRST_LOCK(sc); + if (sc->hw != NULL && sc->bar_res != NULL) + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, 0); + MYFIRST_UNLOCK(sc); + + for (i = sc->num_vectors - 1; i >= 0; i--) + myfirst_msix_teardown_vector(sc, i); + + if (sc->intr_tq != NULL) { + for (i = 0; i < sc->num_vectors; i++) { + if (sc->vectors[i].has_task) + taskqueue_drain(sc->intr_tq, + &sc->vectors[i].task); + } + taskqueue_free(sc->intr_tq); + sc->intr_tq = NULL; + } + + if (sc->intr_mode == MYFIRST_INTR_MSI || + sc->intr_mode == MYFIRST_INTR_MSIX) + pci_release_msi(sc->dev); + + sc->num_vectors = 0; + sc->intr_mode = MYFIRST_INTR_LEGACY; +} + +/* ------------------------------------------------------------------ */ +/* Simulated per-vector interrupts */ +/* ------------------------------------------------------------------ */ + +static int +myfirst_intr_simulate_vector_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_vector *vec = arg1; + struct myfirst_softc *sc = vec->sc; + uint32_t mask = 0; + int error; + + error = sysctl_handle_int(oidp, &mask, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + MYFIRST_LOCK(sc); + if (sc->hw == NULL || sc->bar_res == NULL) { + MYFIRST_UNLOCK(sc); + return (ENODEV); + } + bus_write_4(sc->bar_res, MYFIRST_REG_INTR_STATUS, mask); + MYFIRST_UNLOCK(sc); + + /* + * On MSI-X each vector has its own filter. On MSI with 1 vector + * or legacy INTx, only slot 0 has a filter (the Chapter 19 + * single-handler), so route slots 1 and 2 through it as well. + */ + if (vec->filter != NULL) + (void)vec->filter(vec); + else if (sc->vectors[MYFIRST_VECTOR_ADMIN].filter != NULL) + (void)sc->vectors[MYFIRST_VECTOR_ADMIN].filter( + &sc->vectors[MYFIRST_VECTOR_ADMIN]); + return (0); +} + +/* ------------------------------------------------------------------ */ +/* sysctl registration */ +/* ------------------------------------------------------------------ */ + +void +myfirst_msix_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid_list *kids = SYSCTL_CHILDREN(sc->sysctl_tree); + char name[32]; + int i; + + SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "intr_mode", + CTLFLAG_RD, &sc->intr_mode, 0, + "Interrupt mode: 0=legacy, 1=MSI, 2=MSI-X"); + + for (i = 0; i < MYFIRST_MAX_VECTORS; i++) { + snprintf(name, sizeof(name), "vec%d_fire_count", i); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, name, + CTLFLAG_RD, &sc->vectors[i].fire_count, 0, + "Times this vector's filter was called"); + snprintf(name, sizeof(name), "vec%d_stray_count", i); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, name, + CTLFLAG_RD, &sc->vectors[i].stray_count, 0, + "Stray returns from this vector"); + } + + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "intr_simulate_admin", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, + &sc->vectors[MYFIRST_VECTOR_ADMIN], 0, + myfirst_intr_simulate_vector_sysctl, "IU", + "Simulate admin vector interrupt (write the INTR_STATUS bits)"); + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "intr_simulate_rx", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, + &sc->vectors[MYFIRST_VECTOR_RX], 0, + myfirst_intr_simulate_vector_sysctl, "IU", + "Simulate rx vector interrupt (write the INTR_STATUS bits)"); + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "intr_simulate_tx", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, + &sc->vectors[MYFIRST_VECTOR_TX], 0, + myfirst_intr_simulate_vector_sysctl, "IU", + "Simulate tx vector interrupt (write the INTR_STATUS bits)"); +} diff --git a/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.h b/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.h new file mode 100644 index 0000000..9315184 --- /dev/null +++ b/examples/part-04/ch20-advanced-interrupts/stage4-final/myfirst_msix.h @@ -0,0 +1,62 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Edson Brandi + * + * myfirst_msix.h -- Chapter 20 multi-vector interrupt interface. + * + * Adds a three-tier fallback ladder (MSI-X, MSI, legacy INTx) to the + * Chapter 19 single-vector filter+task design. On MSI-X or MSI, the + * driver registers three per-vector filter handlers (admin, rx, tx) + * with per-vector state and per-vector CPU binding. On legacy INTx, + * the driver falls back to the Chapter 19 single-filter path. + */ + +#ifndef _MYFIRST_MSIX_H_ +#define _MYFIRST_MSIX_H_ + +#include +#include + +struct myfirst_softc; + +enum myfirst_intr_mode { + MYFIRST_INTR_LEGACY = 0, + MYFIRST_INTR_MSI = 1, + MYFIRST_INTR_MSIX = 2, +}; + +enum myfirst_vector_id { + MYFIRST_VECTOR_ADMIN = 0, + MYFIRST_VECTOR_RX = 1, + MYFIRST_VECTOR_TX = 2, + MYFIRST_MAX_VECTORS = 3 +}; + +/* + * Per-vector state. One instance per allocated vector, stored in an + * array in the softc. On MSI-X or MSI each vector's filter takes a + * pointer to its own instance as the argument to bus_setup_intr. + */ +struct myfirst_vector { + struct resource *irq_res; + int irq_rid; + void *intr_cookie; + enum myfirst_vector_id id; + struct myfirst_softc *sc; + uint64_t fire_count; + uint64_t stray_count; + const char *name; + driver_filter_t *filter; + struct task task; + bool has_task; +}; + +/* + * Public API. Called from myfirst_pci.c during attach and detach. + */ +int myfirst_msix_setup(struct myfirst_softc *sc); +void myfirst_msix_teardown(struct myfirst_softc *sc); +void myfirst_msix_add_sysctls(struct myfirst_softc *sc); + +#endif /* _MYFIRST_MSIX_H_ */ diff --git a/examples/part-04/ch21-dma/labs/dma_smoke_test.sh b/examples/part-04/ch21-dma/labs/dma_smoke_test.sh new file mode 100755 index 0000000..640d2d6 --- /dev/null +++ b/examples/part-04/ch21-dma/labs/dma_smoke_test.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# dma_smoke_test.sh - Quick sanity check of the myfirst DMA path. +# +# Runs one host-to-device transfer and one device-to-host transfer. +# Verifies the counters incremented correctly. + +set -e + +DEV="dev.myfirst.0" + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present. Is the driver loaded?" + exit 1 +fi + +# Record starting counters. +before_w=$(sysctl -n ${DEV}.dma_transfers_write) +before_r=$(sysctl -n ${DEV}.dma_transfers_read) + +# Host-to-device. +sysctl -n ${DEV}.dma_test_write=0xaa >/dev/null +# Device-to-host. +sysctl -n ${DEV}.dma_test_read=1 >/dev/null + +# Record ending counters. +after_w=$(sysctl -n ${DEV}.dma_transfers_write) +after_r=$(sysctl -n ${DEV}.dma_transfers_read) + +# Check the increments. +delta_w=$((after_w - before_w)) +delta_r=$((after_r - before_r)) + +if [ ${delta_w} -eq 1 ] && [ ${delta_r} -eq 1 ]; then + echo "PASS: one write and one read transfer completed" + echo " dma_transfers_write: ${before_w} -> ${after_w}" + echo " dma_transfers_read: ${before_r} -> ${after_r}" + echo "" + echo "=== Recent dmesg lines ===" + dmesg | tail -4 + exit 0 +else + echo "FAIL: counters did not increment as expected" + echo " dma_transfers_write: ${before_w} -> ${after_w} (delta ${delta_w}, expected 1)" + echo " dma_transfers_read: ${before_r} -> ${after_r} (delta ${delta_r}, expected 1)" + exit 1 +fi diff --git a/examples/part-04/ch21-dma/labs/dma_stress_test.sh b/examples/part-04/ch21-dma/labs/dma_stress_test.sh new file mode 100755 index 0000000..68e4cb8 --- /dev/null +++ b/examples/part-04/ch21-dma/labs/dma_stress_test.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# dma_stress_test.sh - Run 1000 DMA transfers in each direction and +# check counter invariants at the end. + +set -e + +DEV="dev.myfirst.0" +ITERS=${1:-1000} + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present. Is the driver loaded?" + exit 1 +fi + +echo "Running ${ITERS} write transfers and ${ITERS} read transfers..." + +before_w=$(sysctl -n ${DEV}.dma_transfers_write) +before_r=$(sysctl -n ${DEV}.dma_transfers_read) +before_e=$(sysctl -n ${DEV}.dma_errors) +before_t=$(sysctl -n ${DEV}.dma_timeouts) +before_ci=$(sysctl -n ${DEV}.dma_complete_intrs) +before_ct=$(sysctl -n ${DEV}.dma_complete_tasks) + +i=1 +while [ $i -le ${ITERS} ]; do + sysctl -n ${DEV}.dma_test_write=$((i & 0xFF)) >/dev/null 2>&1 + sysctl -n ${DEV}.dma_test_read=1 >/dev/null 2>&1 + i=$((i + 1)) +done + +after_w=$(sysctl -n ${DEV}.dma_transfers_write) +after_r=$(sysctl -n ${DEV}.dma_transfers_read) +after_e=$(sysctl -n ${DEV}.dma_errors) +after_t=$(sysctl -n ${DEV}.dma_timeouts) +after_ci=$(sysctl -n ${DEV}.dma_complete_intrs) +after_ct=$(sysctl -n ${DEV}.dma_complete_tasks) + +d_w=$((after_w - before_w)) +d_r=$((after_r - before_r)) +d_e=$((after_e - before_e)) +d_t=$((after_t - before_t)) +d_ci=$((after_ci - before_ci)) +d_ct=$((after_ct - before_ct)) + +echo "" +echo "Deltas:" +echo " dma_transfers_write: ${d_w} (expected ${ITERS})" +echo " dma_transfers_read: ${d_r} (expected ${ITERS})" +echo " dma_errors: ${d_e} (expected 0)" +echo " dma_timeouts: ${d_t} (expected 0)" +echo " dma_complete_intrs: ${d_ci} (expected $((ITERS * 2)))" +echo " dma_complete_tasks: ${d_ct} (expected $((ITERS * 2)))" + +fail=0 +if [ ${d_w} -ne ${ITERS} ]; then fail=1; fi +if [ ${d_r} -ne ${ITERS} ]; then fail=1; fi +if [ ${d_e} -ne 0 ]; then fail=1; fi +if [ ${d_t} -ne 0 ]; then fail=1; fi +if [ ${d_ci} -ne ${d_ct} ]; then fail=1; fi + +if [ ${fail} -eq 0 ]; then + echo "" + echo "PASS: invariants hold" + exit 0 +else + echo "" + echo "FAIL: one or more invariants violated" + exit 1 +fi diff --git a/examples/part-04/ch21-dma/labs/full_regression_ch21.sh b/examples/part-04/ch21-dma/labs/full_regression_ch21.sh new file mode 100755 index 0000000..bc44346 --- /dev/null +++ b/examples/part-04/ch21-dma/labs/full_regression_ch21.sh @@ -0,0 +1,86 @@ +#!/bin/sh +# full_regression_ch21.sh - Complete Chapter 21 regression pass. +# +# Steps: +# 1. Verify the driver is loaded and at version 1.4-dma. +# 2. Smoke test: one write, one read. +# 3. Stress test: 1000 transfers. +# 4. Load/unload cycle: 10 iterations, check for leaks. +# 5. Print a summary. +# +# Prints PASS at the end on success, or FAIL with the step that failed. + +set -e + +DEV="dev.myfirst.0" +MOD_PATH="${MOD_PATH:-./myfirst.ko}" +SCRIPT_DIR=$(dirname "$0") + +fail() { + echo "FAIL at step $1: $2" + exit 1 +} + +# Step 1: driver loaded and at correct version. +echo "Step 1: version check..." +if ! kldstat | grep -q myfirst; then + fail 1 "myfirst driver not loaded" +fi +# The version sysctl is added in Chapter 20+ via the version string. +if sysctl -a 2>/dev/null | grep -q '^dev\.myfirst\.0\.version'; then + ver=$(sysctl -n dev.myfirst.0.version 2>/dev/null) + echo " Driver version: ${ver}" + case "${ver}" in + 1.4-dma*) ;; + *) fail 1 "unexpected version ${ver} (expected 1.4-dma)" ;; + esac +fi + +# Step 2: smoke test. +echo "Step 2: smoke test..." +if ! sh "${SCRIPT_DIR}/dma_smoke_test.sh" >/dev/null 2>&1; then + fail 2 "smoke test failed" +fi + +# Step 3: stress test. +echo "Step 3: stress test (1000 transfers)..." +if ! sh "${SCRIPT_DIR}/dma_stress_test.sh" 1000 >/dev/null 2>&1; then + fail 3 "stress test failed" +fi + +# Step 4: load/unload cycle. +echo "Step 4: load/unload cycle..." +# Record starting bus_dma memory usage. +before=$(vmstat -m 2>/dev/null | awk '/bus_dma/ { print $2 }' | head -1) +before=${before:-0} + +# Unload, then load/unload 10 times. +kldunload myfirst 2>/dev/null || true + +i=1 +while [ $i -le 10 ]; do + if ! kldload ${MOD_PATH} 2>/dev/null; then + fail 4 "kldload failed on iteration $i" + fi + if ! kldunload myfirst 2>/dev/null; then + fail 4 "kldunload failed on iteration $i" + fi + i=$((i + 1)) +done + +# Reload for any subsequent manual checks. +kldload ${MOD_PATH} 2>/dev/null || true + +after=$(vmstat -m 2>/dev/null | awk '/bus_dma/ { print $2 }' | head -1) +after=${after:-0} + +if [ "${after}" != "${before}" ]; then + echo " warning: vmstat -m shows bus_dma count changed (${before} -> ${after})" + echo " (may be noise; investigate if persistent)" +fi + +# Step 5: summary. +echo "" +echo "==========================================" +echo "PASS: Chapter 21 regression complete" +echo "==========================================" diff --git a/examples/part-04/ch21-dma/labs/measure_dma_latency.sh b/examples/part-04/ch21-dma/labs/measure_dma_latency.sh new file mode 100755 index 0000000..1ad52a7 --- /dev/null +++ b/examples/part-04/ch21-dma/labs/measure_dma_latency.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# measure_dma_latency.sh - Measure DMA transfer latency from user space. +# +# Runs N transfers, measures wall-clock elapsed time, and prints +# per-transfer latency. Useful for comparing Stage 2 (polling) vs +# Stage 3 (interrupt-driven), or for verifying that the simulation's +# 10 ms callout delay dominates the timing. + +set -e + +DEV="dev.myfirst.0" +N=${1:-100} + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "ERROR: ${DEV} not present." + exit 1 +fi + +start=$(date +%s) +i=1 +while [ $i -le ${N} ]; do + sysctl -n ${DEV}.dma_test_write=$((i & 0xFF)) >/dev/null 2>&1 + i=$((i + 1)) +done +end=$(date +%s) + +elapsed=$((end - start)) +if [ ${elapsed} -eq 0 ]; then elapsed=1; fi + +avg_ms=$(((elapsed * 1000) / ${N})) + +echo "Iterations: ${N}" +echo "Elapsed: ${elapsed} seconds" +echo "Per-transfer: ~${avg_ms} ms" +echo "" +echo "Note: the simulation uses a 10 ms callout, so ~10 ms per" +echo "transfer is the expected steady-state value. Higher values" +echo "indicate per-transfer overhead; lower values may indicate" +echo "batching (if the driver happens to coalesce completions)." diff --git a/examples/part-04/ch21-dma/labs/show_dma_devices.sh b/examples/part-04/ch21-dma/labs/show_dma_devices.sh new file mode 100755 index 0000000..9f3bda0 --- /dev/null +++ b/examples/part-04/ch21-dma/labs/show_dma_devices.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# show_dma_devices.sh - Identify DMA-capable devices on the lab host. +# +# Part of Chapter 21 Lab 1. Shows which PCI devices have bus-mastering +# enabled and are therefore actively using DMA. + +set -e + +echo "=== PCI devices with BUSMASTEREN set ===" +pciconf -lvc | awk ' + /^[^ ]/ { dev = $1 } + /BUSMASTEREN/ { print dev } +' | sort -u + +echo "" +echo "=== Bounce-buffer subsystem status ===" +sysctl -a | grep -E '^hw\.busdma\.' || echo "(no hw.busdma sysctls found)" + +echo "" +echo "=== myfirst driver DMA state (if loaded) ===" +if sysctl -a | grep -q '^dev\.myfirst\.'; then + sysctl dev.myfirst. | grep -E 'dma_' || echo "(no dma_ sysctls; driver may be pre-Chapter-21)" +else + echo "(myfirst not loaded)" +fi + +echo "" +echo "=== Summary ===" +bm_count=$(pciconf -lvc | grep -c BUSMASTEREN || true) +echo "Devices with bus-mastering enabled: ${bm_count}" diff --git a/examples/part-04/ch21-dma/stage1-alloc/Makefile b/examples/part-04/ch21-dma/stage1-alloc/Makefile new file mode 100644 index 0000000..fcedd20 --- /dev/null +++ b/examples/part-04/ch21-dma/stage1-alloc/Makefile @@ -0,0 +1,21 @@ +# Makefile for the Chapter 21 Stage 1 myfirst driver. +# +# Same source set as the Chapter 20 Stage 4 driver; only the version +# string differs. Stage 1 adds DMA allocation and teardown but keeps +# all the code in myfirst.c (no new files). + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.4-dma-stage1\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch21-dma/stage1-alloc/myfirst_dma_snippet.c b/examples/part-04/ch21-dma/stage1-alloc/myfirst_dma_snippet.c new file mode 100644 index 0000000..9d83438 --- /dev/null +++ b/examples/part-04/ch21-dma/stage1-alloc/myfirst_dma_snippet.c @@ -0,0 +1,144 @@ +/*- + * Chapter 21 Stage 1 snippet: DMA allocation and teardown. + * + * This file contains only the Chapter 21 Stage 1 additions to + * myfirst.c. In the actual Stage 1 driver, these functions live + * inside myfirst.c alongside the Chapter 20 Stage 4 code. + * + * Stage 4 (stage4-final/) splits the DMA code into its own + * myfirst_dma.c file. Stage 1 keeps it in myfirst.c for visibility. + * + * The code shown here is didactic: it shows what lines to insert + * into myfirst.c. It will not compile by itself; it depends on the + * softc definition and the surrounding attach/detach code. + */ + +#include +#include +#include +#include + +#include + +#include "myfirst.h" + +/* The single-segment callback for bus_dmamap_load. */ +static void +myfirst_dma_single_map(void *arg, bus_dma_segment_t *segs, int nseg, + int error) +{ + bus_addr_t *addr = arg; + + if (error != 0) { + printf("myfirst: dma load callback error %d\n", error); + *addr = 0; + return; + } + + KASSERT(nseg == 1, + ("myfirst: unexpected DMA segment count %d", nseg)); + *addr = segs[0].ds_addr; +} + +/* + * myfirst_dma_setup: create a DMA tag, allocate a buffer, load a map, + * record the bus address. + * + * Called from the attach path after the BAR is mapped but before the + * interrupt setup runs. On failure, returns non-zero with the softc's + * DMA fields left NULL/zero. + */ +int +myfirst_dma_setup(struct myfirst_softc *sc) +{ + int err; + + err = bus_dma_tag_create(bus_get_dma_tag(sc->dev), + /* alignment */ 4, + /* boundary */ 0, + /* lowaddr */ BUS_SPACE_MAXADDR, + /* highaddr */ BUS_SPACE_MAXADDR, + /* filtfunc */ NULL, + /* filtfuncarg */ NULL, + /* maxsize */ MYFIRST_DMA_BUFFER_SIZE, + /* nsegments */ 1, + /* maxsegsz */ MYFIRST_DMA_BUFFER_SIZE, + /* flags */ 0, + /* lockfunc */ NULL, + /* lockfuncarg */ NULL, + &sc->dma_tag); + if (err != 0) { + device_printf(sc->dev, + "bus_dma_tag_create failed: %d\n", err); + return (err); + } + + err = bus_dmamem_alloc(sc->dma_tag, &sc->dma_vaddr, + BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, + &sc->dma_map); + if (err != 0) { + device_printf(sc->dev, + "bus_dmamem_alloc failed: %d\n", err); + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + return (err); + } + + sc->dma_bus_addr = 0; + err = bus_dmamap_load(sc->dma_tag, sc->dma_map, + sc->dma_vaddr, MYFIRST_DMA_BUFFER_SIZE, + myfirst_dma_single_map, &sc->dma_bus_addr, + BUS_DMA_NOWAIT); + if (err != 0 || sc->dma_bus_addr == 0) { + device_printf(sc->dev, + "bus_dmamap_load failed: %d\n", err); + bus_dmamem_free(sc->dma_tag, sc->dma_vaddr, sc->dma_map); + sc->dma_vaddr = NULL; + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + return (err != 0 ? err : ENOMEM); + } + + /* + * Register the buffer with the simulated backend so it can + * resolve the bus address back to a KVA for the simulated + * transfer. See myfirst_sim_dma_stage2.c for the sim-side helper. + * A real-hardware-only build would not make this call. + */ + if (sc->sim != NULL) + myfirst_sim_register_dma_buffer(sc->sim, sc->dma_vaddr, + sc->dma_bus_addr, MYFIRST_DMA_BUFFER_SIZE); + + device_printf(sc->dev, + "DMA buffer %zu bytes at KVA %p bus addr %#jx\n", + (size_t)MYFIRST_DMA_BUFFER_SIZE, + sc->dma_vaddr, (uintmax_t)sc->dma_bus_addr); + + return (0); +} + +/* + * myfirst_dma_teardown: reverse of myfirst_dma_setup. + * + * Safe to call with any subset of fields set (partial-setup unwind). + * Called from the detach path after the interrupt teardown runs. + */ +void +myfirst_dma_teardown(struct myfirst_softc *sc) +{ + if (sc->sim != NULL) + myfirst_sim_unregister_dma_buffer(sc->sim); + if (sc->dma_bus_addr != 0) { + bus_dmamap_unload(sc->dma_tag, sc->dma_map); + sc->dma_bus_addr = 0; + } + if (sc->dma_vaddr != NULL) { + bus_dmamem_free(sc->dma_tag, sc->dma_vaddr, sc->dma_map); + sc->dma_vaddr = NULL; + sc->dma_map = NULL; + } + if (sc->dma_tag != NULL) { + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + } +} diff --git a/examples/part-04/ch21-dma/stage1-alloc/myfirst_softc_additions.h b/examples/part-04/ch21-dma/stage1-alloc/myfirst_softc_additions.h new file mode 100644 index 0000000..c6e483c --- /dev/null +++ b/examples/part-04/ch21-dma/stage1-alloc/myfirst_softc_additions.h @@ -0,0 +1,23 @@ +/*- + * Chapter 21 Stage 1: additions to myfirst.h. + * + * Append these declarations to myfirst.h after the Chapter 20 softc + * fields. They add the DMA-related state the Stage 1 setup uses. + */ + +/* Add to struct myfirst_softc: */ +/* + bus_dma_tag_t dma_tag; + bus_dmamap_t dma_map; + void *dma_vaddr; + bus_addr_t dma_bus_addr; + */ + +/* DMA buffer size. A single 4 KB buffer, matching a page and avoiding + * bounce-buffer corner cases. Increase if the simulation is extended + * to larger transfers. */ +#define MYFIRST_DMA_BUFFER_SIZE 4096u + +/* Public Stage 1 DMA API (called from attach and detach). */ +int myfirst_dma_setup(struct myfirst_softc *sc); +void myfirst_dma_teardown(struct myfirst_softc *sc); diff --git a/examples/part-04/ch21-dma/stage2-polling/Makefile b/examples/part-04/ch21-dma/stage2-polling/Makefile new file mode 100644 index 0000000..f993968 --- /dev/null +++ b/examples/part-04/ch21-dma/stage2-polling/Makefile @@ -0,0 +1,20 @@ +# Makefile for the Chapter 21 Stage 2 myfirst driver. +# +# Same source set as Stage 1. Stage 2's changes are confined to +# myfirst.c (DMA transfer helper) and myfirst_sim.c (simulated engine). + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.4-dma-stage2\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch21-dma/stage2-polling/myfirst_dma_stage2.c b/examples/part-04/ch21-dma/stage2-polling/myfirst_dma_stage2.c new file mode 100644 index 0000000..b837353 --- /dev/null +++ b/examples/part-04/ch21-dma/stage2-polling/myfirst_dma_stage2.c @@ -0,0 +1,156 @@ +/*- + * Chapter 21 Stage 2: DMA transfer helper (polling-based). + * + * This snippet shows the Stage 2 addition to myfirst.c. It assumes + * that the softc has dma_tag, dma_map, dma_vaddr, dma_bus_addr, + * dma_transfers_write, dma_transfers_read, dma_errors, and + * dma_timeouts fields, and that the register accessor macros + * (CSR_READ_4, CSR_WRITE_4) are in scope via myfirst_hw.h. + * + * This file is for didactic reading, not for direct compilation. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "myfirst.h" +#include "myfirst_hw.h" + +int +myfirst_dma_do_transfer(struct myfirst_softc *sc, int direction, + size_t length) +{ + uint32_t status; + int timeout; + + if (length == 0 || length > MYFIRST_DMA_BUFFER_SIZE) + return (EINVAL); + + if (direction == MYFIRST_DMA_DIR_WRITE) { + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREWRITE); + } else { + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREREAD); + } + + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_LOW, + (uint32_t)(sc->dma_bus_addr & 0xFFFFFFFFu)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_HIGH, + (uint32_t)(sc->dma_bus_addr >> 32)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_LEN, (uint32_t)length); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_DIR, (uint32_t)direction); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, MYFIRST_DMA_CTRL_START); + + for (timeout = 500; timeout > 0; timeout--) { + pause("dma", hz / 1000); + status = CSR_READ_4(sc, MYFIRST_REG_DMA_STATUS); + if ((status & MYFIRST_DMA_STATUS_DONE) != 0) + break; + if ((status & MYFIRST_DMA_STATUS_ERR) != 0) { + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + atomic_add_64(&sc->dma_errors, 1); + return (EIO); + } + } + + if (timeout == 0) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + atomic_add_64(&sc->dma_timeouts, 1); + return (ETIMEDOUT); + } + + /* Acknowledge the completion bit in INTR_STATUS. */ + CSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, MYFIRST_INTR_COMPLETE); + + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + + if (direction == MYFIRST_DMA_DIR_WRITE) + atomic_add_64(&sc->dma_transfers_write, 1); + else + atomic_add_64(&sc->dma_transfers_read, 1); + + return (0); +} + +/* + * Sysctl handlers. Registered from myfirst_dma_add_sysctls (Stage 4). + * Shown here inline for readability. + */ + +static int +myfirst_dma_sysctl_test_write(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int pattern; + int err; + + err = sysctl_handle_int(oidp, &pattern, 0, req); + if (err != 0 || req->newptr == NULL) + return (err); + + memset(sc->dma_vaddr, (int)(pattern & 0xFF), + MYFIRST_DMA_BUFFER_SIZE); + err = myfirst_dma_do_transfer(sc, MYFIRST_DMA_DIR_WRITE, + MYFIRST_DMA_BUFFER_SIZE); + if (err != 0) + device_printf(sc->dev, + "dma_test_write: err %d\n", err); + else + device_printf(sc->dev, + "dma_test_write: pattern 0x%02x transferred\n", + pattern & 0xFF); + return (err); +} + +static int +myfirst_dma_sysctl_test_read(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int ignore; + int err; + uint8_t *bytes; + + err = sysctl_handle_int(oidp, &ignore, 0, req); + if (err != 0 || req->newptr == NULL) + return (err); + + err = myfirst_dma_do_transfer(sc, MYFIRST_DMA_DIR_READ, + MYFIRST_DMA_BUFFER_SIZE); + if (err != 0) { + device_printf(sc->dev, "dma_test_read: err %d\n", err); + return (err); + } + + bytes = (uint8_t *)sc->dma_vaddr; + device_printf(sc->dev, + "dma_test_read: first bytes %02x %02x %02x %02x " + "%02x %02x %02x %02x\n", + bytes[0], bytes[1], bytes[2], bytes[3], + bytes[4], bytes[5], bytes[6], bytes[7]); + return (0); +} diff --git a/examples/part-04/ch21-dma/stage2-polling/myfirst_header_additions.h b/examples/part-04/ch21-dma/stage2-polling/myfirst_header_additions.h new file mode 100644 index 0000000..981dfe7 --- /dev/null +++ b/examples/part-04/ch21-dma/stage2-polling/myfirst_header_additions.h @@ -0,0 +1,41 @@ +/*- + * Chapter 21 Stage 2: header additions. + * + * Append to myfirst.h after the Chapter 20 register map. + * These values are read by both the driver (programming the engine) + * and the simulation backend (implementing the engine). + */ + +/* DMA register offsets (on the MMIO BAR). */ +#define MYFIRST_REG_DMA_ADDR_LOW 0x20 +#define MYFIRST_REG_DMA_ADDR_HIGH 0x24 +#define MYFIRST_REG_DMA_LEN 0x28 +#define MYFIRST_REG_DMA_DIR 0x2C +#define MYFIRST_REG_DMA_CTRL 0x30 +#define MYFIRST_REG_DMA_STATUS 0x34 + +/* DMA_DIR values. */ +#define MYFIRST_DMA_DIR_WRITE 0u /* host-to-device */ +#define MYFIRST_DMA_DIR_READ 1u /* device-to-host */ + +/* DMA_CTRL bits. */ +#define MYFIRST_DMA_CTRL_START (1u << 0) +#define MYFIRST_DMA_CTRL_ABORT (1u << 1) +#define MYFIRST_DMA_CTRL_RESET (1u << 31) + +/* DMA_STATUS bits. */ +#define MYFIRST_DMA_STATUS_DONE (1u << 0) +#define MYFIRST_DMA_STATUS_ERR (1u << 1) +#define MYFIRST_DMA_STATUS_RUNNING (1u << 2) + +/* Stage 2 public API. */ +int myfirst_dma_do_transfer(struct myfirst_softc *sc, + int direction, size_t length); + +/* Add the following fields to struct myfirst_softc: */ +/* + uint64_t dma_transfers_write; + uint64_t dma_transfers_read; + uint64_t dma_errors; + uint64_t dma_timeouts; + */ diff --git a/examples/part-04/ch21-dma/stage2-polling/myfirst_sim_dma_stage2.c b/examples/part-04/ch21-dma/stage2-polling/myfirst_sim_dma_stage2.c new file mode 100644 index 0000000..77ce3d4 --- /dev/null +++ b/examples/part-04/ch21-dma/stage2-polling/myfirst_sim_dma_stage2.c @@ -0,0 +1,239 @@ +/*- + * Chapter 21 Stage 2: simulated DMA engine. + * + * This snippet shows the Stage 2 additions to myfirst_sim.c. It + * extends the Chapter 17 simulation backend with a DMA engine whose + * completion is driven by a callout(9). + * + * A simulation running inside the kernel cannot physically reach host + * memory through the memory controller. Instead, the driver registers + * a (KVA, bus address, size) triple with the sim at myfirst_dma_setup + * time. When the callout fires, it looks up the KVA by bus address + * and uses it directly for the memcpy. + * + * This file is for didactic reading, not for direct compilation. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include "myfirst.h" +#include "myfirst_sim.h" + +/* Add to struct myfirst_sim (defined in myfirst_sim.h): */ +/* + struct myfirst_sim_dma { + uint32_t addr_low; + uint32_t addr_high; + uint32_t len; + uint32_t dir; + uint32_t ctrl; + uint32_t status; + struct callout done_co; + bool armed; + } dma; + + /* Back-channel: the driver registers its DMA buffer here so the + * sim can reach the CPU-visible side during the simulated + * transfer. Real hardware never uses this path. */ + void *dma_host_kva; + bus_addr_t dma_host_bus_addr; + size_t dma_host_size; + + void *dma_scratch; + size_t dma_scratch_size; + */ + +static void myfirst_sim_dma_done_co(void *arg); +static void myfirst_sim_dma_ctrl_written(struct myfirst_sim *sim, + uint32_t val); +static void myfirst_sim_dma_raise_complete(struct myfirst_sim *sim); + +/* Called from myfirst_sim_init (Chapter 17). */ +void +myfirst_sim_dma_init(struct myfirst_sim *sim) +{ + sim->dma_scratch_size = MYFIRST_DMA_BUFFER_SIZE; + sim->dma_scratch = malloc(sim->dma_scratch_size, M_MYFIRST, + M_WAITOK | M_ZERO); + memset(sim->dma_scratch, 0x5A, sim->dma_scratch_size); + callout_init(&sim->dma.done_co, 1); + sim->dma.armed = false; + sim->dma.status = 0; + sim->dma_host_kva = NULL; + sim->dma_host_bus_addr = 0; + sim->dma_host_size = 0; +} + +/* Called from myfirst_sim_destroy (Chapter 17). */ +void +myfirst_sim_dma_destroy(struct myfirst_sim *sim) +{ + callout_drain(&sim->dma.done_co); + if (sim->dma_scratch != NULL) { + free(sim->dma_scratch, M_MYFIRST); + sim->dma_scratch = NULL; + } + sim->dma_host_kva = NULL; + sim->dma_host_bus_addr = 0; + sim->dma_host_size = 0; +} + +/* + * Back-channel: register the driver's DMA buffer with the sim. + * Called from myfirst_dma_setup after bus_dmamap_load has filled in + * the bus address. In a real driver this call does not exist; it is + * only needed because the sim is software and cannot physically reach + * the host through the memory controller. + */ +void +myfirst_sim_register_dma_buffer(struct myfirst_sim *sim, void *kva, + bus_addr_t bus_addr, size_t size) +{ + sim->dma_host_kva = kva; + sim->dma_host_bus_addr = bus_addr; + sim->dma_host_size = size; +} + +/* Symmetrical teardown, called from myfirst_dma_teardown. */ +void +myfirst_sim_unregister_dma_buffer(struct myfirst_sim *sim) +{ + sim->dma_host_kva = NULL; + sim->dma_host_bus_addr = 0; + sim->dma_host_size = 0; +} + +/* + * Called from myfirst_sim_write_4 (Chapter 17) when the write targets + * one of the DMA registers. Extend the switch statement. + */ +void +myfirst_sim_dma_write(struct myfirst_sim *sim, bus_size_t off, + uint32_t val) +{ + switch (off) { + case MYFIRST_REG_DMA_ADDR_LOW: + sim->dma.addr_low = val; + break; + case MYFIRST_REG_DMA_ADDR_HIGH: + sim->dma.addr_high = val; + break; + case MYFIRST_REG_DMA_LEN: + sim->dma.len = val; + break; + case MYFIRST_REG_DMA_DIR: + sim->dma.dir = val; + break; + case MYFIRST_REG_DMA_CTRL: + sim->dma.ctrl = val; + myfirst_sim_dma_ctrl_written(sim, val); + break; + default: + break; + } +} + +/* + * Called from myfirst_sim_read_4 (Chapter 17) when the read targets + * MYFIRST_REG_DMA_STATUS. + */ +uint32_t +myfirst_sim_dma_read(struct myfirst_sim *sim, bus_size_t off) +{ + if (off == MYFIRST_REG_DMA_STATUS) + return (sim->dma.status); + return (0); +} + +static void +myfirst_sim_dma_ctrl_written(struct myfirst_sim *sim, uint32_t val) +{ + if ((val & MYFIRST_DMA_CTRL_RESET) != 0) { + if (sim->dma.armed) { + callout_stop(&sim->dma.done_co); + sim->dma.armed = false; + } + sim->dma.status = 0; + sim->dma.addr_low = 0; + sim->dma.addr_high = 0; + sim->dma.len = 0; + sim->dma.dir = 0; + return; + } + if ((val & MYFIRST_DMA_CTRL_ABORT) != 0) { + if (sim->dma.armed) { + callout_stop(&sim->dma.done_co); + sim->dma.armed = false; + } + sim->dma.status &= ~MYFIRST_DMA_STATUS_RUNNING; + sim->dma.status |= MYFIRST_DMA_STATUS_ERR; + return; + } + if ((val & MYFIRST_DMA_CTRL_START) != 0) { + if ((sim->dma.status & MYFIRST_DMA_STATUS_RUNNING) != 0) { + sim->dma.status |= MYFIRST_DMA_STATUS_ERR; + return; + } + sim->dma.status = MYFIRST_DMA_STATUS_RUNNING; + sim->dma.armed = true; + callout_reset(&sim->dma.done_co, hz / 100, + myfirst_sim_dma_done_co, sim); + return; + } +} + +static void +myfirst_sim_dma_done_co(void *arg) +{ + struct myfirst_sim *sim = arg; + bus_addr_t bus_addr; + uint32_t len; + void *kva; + + bus_addr = ((bus_addr_t)sim->dma.addr_high << 32) | + sim->dma.addr_low; + len = sim->dma.len; + + /* + * Back-channel lookup: find the KVA for this bus address. + * A real device would not need this; the device's own DMA + * engine would perform the memory-controller access. + */ + if (sim->dma_host_kva == NULL || + bus_addr != sim->dma_host_bus_addr || + len == 0 || len > sim->dma_host_size || + len > sim->dma_scratch_size) { + sim->dma.status = MYFIRST_DMA_STATUS_ERR; + sim->dma.armed = false; + myfirst_sim_dma_raise_complete(sim); + return; + } + kva = sim->dma_host_kva; + + if (sim->dma.dir == MYFIRST_DMA_DIR_WRITE) { + /* Host-to-device: sim reads from host KVA, writes scratch. */ + memcpy(sim->dma_scratch, kva, len); + } else { + /* Device-to-host: sim reads from scratch, writes to host. */ + memcpy(kva, sim->dma_scratch, len); + } + + sim->dma.status = MYFIRST_DMA_STATUS_DONE; + sim->dma.armed = false; + myfirst_sim_dma_raise_complete(sim); +} + +static void +myfirst_sim_dma_raise_complete(struct myfirst_sim *sim) +{ + sim->intr_status |= MYFIRST_INTR_COMPLETE; + if ((sim->intr_mask & MYFIRST_INTR_COMPLETE) != 0) + myfirst_sim_raise_intr(sim); +} diff --git a/examples/part-04/ch21-dma/stage3-interrupt/Makefile b/examples/part-04/ch21-dma/stage3-interrupt/Makefile new file mode 100644 index 0000000..2b27b8f --- /dev/null +++ b/examples/part-04/ch21-dma/stage3-interrupt/Makefile @@ -0,0 +1,17 @@ +# Makefile for the Chapter 21 Stage 3 myfirst driver. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.4-dma-stage3\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch21-dma/stage3-interrupt/myfirst_dma_stage3.c b/examples/part-04/ch21-dma/stage3-interrupt/myfirst_dma_stage3.c new file mode 100644 index 0000000..db4be52 --- /dev/null +++ b/examples/part-04/ch21-dma/stage3-interrupt/myfirst_dma_stage3.c @@ -0,0 +1,94 @@ +/*- + * Chapter 21 Stage 3: interrupt-driven DMA transfer helper. + * + * Replaces the Stage 2 polling helper with a condition-variable-based + * wait. The rx task (myfirst_intr_additions.c) issues the POST sync + * and broadcasts dma_cv; the helper wakes, checks status, returns. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "myfirst.h" +#include "myfirst_hw.h" + +/* Add to struct myfirst_softc: */ +/* + bool dma_in_flight; + int dma_last_direction; + uint32_t dma_last_status; + struct cv dma_cv; + uint64_t dma_complete_intrs; + uint64_t dma_complete_tasks; + */ + +int +myfirst_dma_do_transfer_intr(struct myfirst_softc *sc, int direction, + size_t length) +{ + int err; + + if (length == 0 || length > MYFIRST_DMA_BUFFER_SIZE) + return (EINVAL); + + MYFIRST_LOCK(sc); + if (sc->dma_in_flight) { + MYFIRST_UNLOCK(sc); + return (EBUSY); + } + + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREREAD); + + sc->dma_last_direction = direction; + sc->dma_in_flight = true; + + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_LOW, + (uint32_t)(sc->dma_bus_addr & 0xFFFFFFFFu)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_HIGH, + (uint32_t)(sc->dma_bus_addr >> 32)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_LEN, (uint32_t)length); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_DIR, (uint32_t)direction); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, MYFIRST_DMA_CTRL_START); + + err = cv_timedwait(&sc->dma_cv, &sc->mtx, hz); /* 1 s */ + if (err == EWOULDBLOCK) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + sc->dma_in_flight = false; + atomic_add_64(&sc->dma_timeouts, 1); + MYFIRST_UNLOCK(sc); + return (ETIMEDOUT); + } + + if ((sc->dma_last_status & MYFIRST_DMA_STATUS_ERR) != 0) { + atomic_add_64(&sc->dma_errors, 1); + MYFIRST_UNLOCK(sc); + return (EIO); + } + + if (direction == MYFIRST_DMA_DIR_WRITE) + atomic_add_64(&sc->dma_transfers_write, 1); + else + atomic_add_64(&sc->dma_transfers_read, 1); + + MYFIRST_UNLOCK(sc); + return (0); +} diff --git a/examples/part-04/ch21-dma/stage3-interrupt/myfirst_intr_additions.c b/examples/part-04/ch21-dma/stage3-interrupt/myfirst_intr_additions.c new file mode 100644 index 0000000..ec2c380 --- /dev/null +++ b/examples/part-04/ch21-dma/stage3-interrupt/myfirst_intr_additions.c @@ -0,0 +1,111 @@ +/*- + * Chapter 21 Stage 3: interrupt filter and task additions. + * + * Extends the Chapter 20 rx filter and task to handle + * MYFIRST_INTR_COMPLETE as well as MYFIRST_INTR_DATA_AV. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_msix.h" + +/* + * Replaces the Chapter 20 myfirst_msix_rx_filter. The new version + * checks both MYFIRST_INTR_DATA_AV (Chapter 19/20 path) and + * MYFIRST_INTR_COMPLETE (Chapter 21 completion path). + */ +int +myfirst_msix_rx_filter(void *arg) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + uint32_t status; + bool handled = false; + + status = ICSR_READ_4(sc, MYFIRST_REG_INTR_STATUS); + + if ((status & MYFIRST_INTR_DATA_AV) != 0) { + atomic_add_64(&vec->fire_count, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, + MYFIRST_INTR_DATA_AV); + atomic_add_64(&sc->intr_data_av_count, 1); + handled = true; + } + + if ((status & MYFIRST_INTR_COMPLETE) != 0) { + atomic_add_64(&sc->dma_complete_intrs, 1); + ICSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, + MYFIRST_INTR_COMPLETE); + handled = true; + } + + if (!handled) { + atomic_add_64(&vec->stray_count, 1); + return (FILTER_STRAY); + } + + if (sc->intr_tq != NULL) + taskqueue_enqueue(sc->intr_tq, &vec->task); + return (FILTER_HANDLED); +} + +/* + * Replaces the Chapter 20 myfirst_msix_rx_task_fn. The new version + * performs the Chapter 19/20 data-available work and then calls + * myfirst_dma_handle_complete (Stage 4 centralises this helper). + */ +void +myfirst_msix_rx_task_fn(void *arg, int npending) +{ + struct myfirst_vector *vec = arg; + struct myfirst_softc *sc = vec->sc; + + MYFIRST_LOCK(sc); + if (sc->hw == NULL || !sc->pci_attached) { + MYFIRST_UNLOCK(sc); + return; + } + + /* Chapter 19/20 data-available work. */ + sc->intr_last_data = CSR_READ_4(sc, MYFIRST_REG_DATA_OUT); + sc->intr_task_invocations++; + cv_broadcast(&sc->data_cv); + + /* Chapter 21 DMA completion work (inlined in Stage 3; + * extracted to myfirst_dma_handle_complete in Stage 4). */ + if (sc->dma_in_flight) { + sc->dma_in_flight = false; + if (sc->dma_last_direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + sc->dma_last_status = CSR_READ_4(sc, + MYFIRST_REG_DMA_STATUS); + atomic_add_64(&sc->dma_complete_tasks, 1); + cv_broadcast(&sc->dma_cv); + } + + MYFIRST_UNLOCK(sc); +} + +/* + * Don't forget to enable MYFIRST_INTR_COMPLETE in the INTR_MASK + * write at the end of myfirst_msix_setup: + * + * CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, + * MYFIRST_INTR_DATA_AV | MYFIRST_INTR_ERROR | + * MYFIRST_INTR_COMPLETE); + */ diff --git a/examples/part-04/ch21-dma/stage4-final/DMA.md b/examples/part-04/ch21-dma/stage4-final/DMA.md new file mode 100644 index 0000000..961992b --- /dev/null +++ b/examples/part-04/ch21-dma/stage4-final/DMA.md @@ -0,0 +1,126 @@ +# DMA Subsystem + +## Purpose + +The DMA layer allows the driver to transfer data between host memory +and the device without CPU-per-byte involvement. It is used for every +transfer larger than a few words; smaller register reads and writes +still use MMIO directly. + +## Public API + +- `myfirst_dma_setup(sc)`: called from attach. Creates the tag, + allocates the buffer, loads the map, populates `sc->dma_bus_addr`. + Initialises the `dma_cv` condition variable. +- `myfirst_dma_teardown(sc)`: called from detach. Reverses setup. + Destroys the `dma_cv`. +- `myfirst_dma_do_transfer(sc, dir, len)`: triggers one DMA transfer + and polls for completion (legacy; kept for comparison). +- `myfirst_dma_do_transfer_intr(sc, dir, len)`: triggers one DMA + transfer and sleeps on `dma_cv` for completion (preferred). +- `myfirst_dma_handle_complete(sc)`: called from the rx task when + `MYFIRST_INTR_COMPLETE` was observed. +- `myfirst_dma_add_sysctls(sc)`: registers the DMA counters and test + sysctls under `dev.myfirst.N.`. + +## Register Layout + +| Offset | Name | R/W | Meaning | +|--------|------------------|-----|-----------------------------------------------| +| 0x20 | `DMA_ADDR_LOW` | RW | Low 32 bits of the DMA bus address. | +| 0x24 | `DMA_ADDR_HIGH` | RW | High 32 bits. | +| 0x28 | `DMA_LEN` | RW | Transfer length in bytes. | +| 0x2C | `DMA_DIR` | RW | 0 = host-to-device, 1 = device-to-host. | +| 0x30 | `DMA_CTRL` | RW | 1 = start, 2 = abort, bit 31 = reset. | +| 0x34 | `DMA_STATUS` | RO | bit 0 = DONE, bit 1 = ERR, bit 2 = RUNNING. | + +## Transfer Flow (Host-to-Device) + +``` +CPU fills dma_vaddr with data +bus_dmamap_sync(PREWRITE) +write DMA_ADDR_LOW/HIGH, DMA_LEN, DMA_DIR=0, DMA_CTRL=START +cv_timedwait on dma_cv +--- interrupt fires --- +filter: acknowledge INTR_COMPLETE, enqueue task +task: myfirst_dma_handle_complete -> bus_dmamap_sync(POSTWRITE) -> cv_broadcast +helper: wake, check status, return +``` + +## Transfer Flow (Device-to-Host) + +``` +bus_dmamap_sync(PREREAD) +write DMA_ADDR_LOW/HIGH, DMA_LEN, DMA_DIR=1, DMA_CTRL=START +cv_timedwait on dma_cv +--- interrupt fires --- +filter: acknowledge INTR_COMPLETE, enqueue task +task: myfirst_dma_handle_complete -> bus_dmamap_sync(POSTREAD) -> cv_broadcast +helper: wake, check status, return +CPU reads dma_vaddr +``` + +## Counters + +- `dev.myfirst.N.dma_transfers_write`: successful host-to-device transfers. +- `dev.myfirst.N.dma_transfers_read`: successful device-to-host transfers. +- `dev.myfirst.N.dma_errors`: transfers that returned EIO. +- `dev.myfirst.N.dma_timeouts`: transfers that hit the 1-second timeout. +- `dev.myfirst.N.dma_complete_intrs`: completion-bit observations in the filter. +- `dev.myfirst.N.dma_complete_tasks`: completion processing in the task. +- `dev.myfirst.N.dma_bus_addr`: read-only view of the allocated bus address. + +## Invariants + +- `dma_complete_intrs == dma_complete_tasks` at all times. +- `dma_complete_intrs == dma_transfers_write + dma_transfers_read + dma_errors + dma_timeouts`. + +The regression test verifies both. + +## Testing + +The sysctls `dma_test_write` and `dma_test_read` trigger transfers +from user space: + +```sh +sysctl dev.myfirst.0.dma_test_write=0xAA +sysctl dev.myfirst.0.dma_test_read=1 +``` + +The first fills the buffer with 0xAA and runs host-to-device; the +second runs device-to-host and logs the first eight bytes of the +buffer to `dmesg`. + +## Locking + +- `sc->mtx` protects every DMA field that is read or written outside + attach/detach: `dma_in_flight`, `dma_last_direction`, + `dma_last_status`. +- Per-transfer counters are updated with `atomic_add_64` so the + filter can increment them without the mutex. +- `dma_cv` is waited on and broadcast under `sc->mtx`. + +## Detach Safety + +Detach order: +1. Mask `MYFIRST_INTR_COMPLETE` in the device register. +2. Drain the simulation's callout (`callout_drain`). +3. Drain the rx task (`taskqueue_drain`). +4. Wait for `dma_in_flight == false` under `sc->mtx`. +5. Call `myfirst_dma_teardown`. + +## Known Limitations + +- Single buffer, single transfer at a time. +- No descriptor-ring support. +- No per-NUMA-node allocation. +- No partial-transfer reporting. + +These are natural extensions documented in the chapter text. + +## See Also + +- `bus_dma(9)`, `/usr/src/sys/sys/bus_dma.h`. +- `/usr/src/sys/dev/re/if_re.c` for a production descriptor-ring driver. +- `INTERRUPTS.md`, `MSIX.md` for the interrupt path the completion uses. +- The chapter text at `content/chapters/part4/chapter-21.md`. diff --git a/examples/part-04/ch21-dma/stage4-final/Makefile b/examples/part-04/ch21-dma/stage4-final/Makefile new file mode 100644 index 0000000..1bbac8c --- /dev/null +++ b/examples/part-04/ch21-dma/stage4-final/Makefile @@ -0,0 +1,22 @@ +# Makefile for the Chapter 21 Stage 4 myfirst driver. +# +# Stage 4 adds myfirst_dma.c to the build and bumps the version to +# 1.4-dma. Structurally identical to Stage 3 except for this one new +# source file. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + myfirst_dma.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.4-dma\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch21-dma/stage4-final/myfirst_dma.c b/examples/part-04/ch21-dma/stage4-final/myfirst_dma.c new file mode 100644 index 0000000..7aa3d08 --- /dev/null +++ b/examples/part-04/ch21-dma/stage4-final/myfirst_dma.c @@ -0,0 +1,392 @@ +/*- + * Chapter 21 Stage 4: myfirst_dma.c + * + * Consolidated DMA subsystem for the myfirst driver. Moves the DMA + * code from myfirst.c (Stage 1-3) into its own compilation unit with + * a documented public API. + * + * This file implements the API declared in myfirst_dma.h: + * - myfirst_dma_setup / myfirst_dma_teardown: lifecycle. + * - myfirst_dma_do_transfer (polling) / do_transfer_intr (interrupt). + * - myfirst_dma_handle_complete: called from the rx task. + * - myfirst_dma_add_sysctls: registers the test and counter sysctls. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_dma.h" + +static void myfirst_dma_single_map(void *arg, bus_dma_segment_t *segs, + int nseg, int error); +static int myfirst_dma_sysctl_test_write(SYSCTL_HANDLER_ARGS); +static int myfirst_dma_sysctl_test_read(SYSCTL_HANDLER_ARGS); + +static void +myfirst_dma_single_map(void *arg, bus_dma_segment_t *segs, int nseg, + int error) +{ + bus_addr_t *addr = arg; + + if (error != 0) { + printf("myfirst: dma load callback error %d\n", error); + *addr = 0; + return; + } + + KASSERT(nseg == 1, + ("myfirst: unexpected DMA segment count %d", nseg)); + *addr = segs[0].ds_addr; +} + +int +myfirst_dma_setup(struct myfirst_softc *sc) +{ + int err; + + err = bus_dma_tag_create(bus_get_dma_tag(sc->dev), + /* alignment */ 4, + /* boundary */ 0, + /* lowaddr */ BUS_SPACE_MAXADDR, + /* highaddr */ BUS_SPACE_MAXADDR, + /* filtfunc */ NULL, + /* filtfuncarg */ NULL, + /* maxsize */ MYFIRST_DMA_BUFFER_SIZE, + /* nsegments */ 1, + /* maxsegsz */ MYFIRST_DMA_BUFFER_SIZE, + /* flags */ 0, + /* lockfunc */ NULL, + /* lockfuncarg */ NULL, + &sc->dma_tag); + if (err != 0) { + device_printf(sc->dev, + "bus_dma_tag_create failed: %d\n", err); + return (err); + } + + err = bus_dmamem_alloc(sc->dma_tag, &sc->dma_vaddr, + BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, + &sc->dma_map); + if (err != 0) { + device_printf(sc->dev, + "bus_dmamem_alloc failed: %d\n", err); + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + return (err); + } + + sc->dma_bus_addr = 0; + err = bus_dmamap_load(sc->dma_tag, sc->dma_map, + sc->dma_vaddr, MYFIRST_DMA_BUFFER_SIZE, + myfirst_dma_single_map, &sc->dma_bus_addr, + BUS_DMA_NOWAIT); + if (err != 0 || sc->dma_bus_addr == 0) { + device_printf(sc->dev, + "bus_dmamap_load failed: %d\n", err); + bus_dmamem_free(sc->dma_tag, sc->dma_vaddr, sc->dma_map); + sc->dma_vaddr = NULL; + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + return (err != 0 ? err : ENOMEM); + } + + cv_init(&sc->dma_cv, "myfirst_dma"); + + /* + * Register the buffer with the simulation backend so it can + * resolve the bus address back to a KVA when the simulated + * engine runs. This call exists only for the simulated backend; + * a real-hardware build would omit it. + */ + if (sc->sim != NULL) + myfirst_sim_register_dma_buffer(sc->sim, sc->dma_vaddr, + sc->dma_bus_addr, MYFIRST_DMA_BUFFER_SIZE); + + device_printf(sc->dev, + "DMA buffer %zu bytes at KVA %p bus addr %#jx\n", + (size_t)MYFIRST_DMA_BUFFER_SIZE, + sc->dma_vaddr, (uintmax_t)sc->dma_bus_addr); + + return (0); +} + +void +myfirst_dma_teardown(struct myfirst_softc *sc) +{ + if (sc->sim != NULL) + myfirst_sim_unregister_dma_buffer(sc->sim); + if (sc->dma_bus_addr != 0) { + bus_dmamap_unload(sc->dma_tag, sc->dma_map); + sc->dma_bus_addr = 0; + } + if (sc->dma_vaddr != NULL) { + bus_dmamem_free(sc->dma_tag, sc->dma_vaddr, sc->dma_map); + sc->dma_vaddr = NULL; + sc->dma_map = NULL; + } + if (sc->dma_tag != NULL) { + bus_dma_tag_destroy(sc->dma_tag); + sc->dma_tag = NULL; + } + cv_destroy(&sc->dma_cv); +} + +int +myfirst_dma_do_transfer(struct myfirst_softc *sc, int direction, + size_t length) +{ + uint32_t status; + int timeout; + + if (length == 0 || length > MYFIRST_DMA_BUFFER_SIZE) + return (EINVAL); + + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREREAD); + + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_LOW, + (uint32_t)(sc->dma_bus_addr & 0xFFFFFFFFu)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_HIGH, + (uint32_t)(sc->dma_bus_addr >> 32)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_LEN, (uint32_t)length); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_DIR, (uint32_t)direction); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, MYFIRST_DMA_CTRL_START); + + for (timeout = 500; timeout > 0; timeout--) { + pause("dma", hz / 1000); + status = CSR_READ_4(sc, MYFIRST_REG_DMA_STATUS); + if ((status & MYFIRST_DMA_STATUS_DONE) != 0) + break; + if ((status & MYFIRST_DMA_STATUS_ERR) != 0) { + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + atomic_add_64(&sc->dma_errors, 1); + return (EIO); + } + } + + if (timeout == 0) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + atomic_add_64(&sc->dma_timeouts, 1); + return (ETIMEDOUT); + } + + CSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, MYFIRST_INTR_COMPLETE); + + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + + if (direction == MYFIRST_DMA_DIR_WRITE) + atomic_add_64(&sc->dma_transfers_write, 1); + else + atomic_add_64(&sc->dma_transfers_read, 1); + + return (0); +} + +int +myfirst_dma_do_transfer_intr(struct myfirst_softc *sc, int direction, + size_t length) +{ + int err; + + if (length == 0 || length > MYFIRST_DMA_BUFFER_SIZE) + return (EINVAL); + + MYFIRST_LOCK(sc); + if (sc->dma_in_flight) { + MYFIRST_UNLOCK(sc); + return (EBUSY); + } + + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_PREREAD); + + sc->dma_last_direction = direction; + sc->dma_in_flight = true; + + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_LOW, + (uint32_t)(sc->dma_bus_addr & 0xFFFFFFFFu)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_ADDR_HIGH, + (uint32_t)(sc->dma_bus_addr >> 32)); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_LEN, (uint32_t)length); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_DIR, (uint32_t)direction); + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, MYFIRST_DMA_CTRL_START); + + err = cv_timedwait(&sc->dma_cv, &sc->mtx, hz); + if (err == EWOULDBLOCK) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + if (direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + sc->dma_in_flight = false; + atomic_add_64(&sc->dma_timeouts, 1); + MYFIRST_UNLOCK(sc); + return (ETIMEDOUT); + } + + if ((sc->dma_last_status & MYFIRST_DMA_STATUS_ERR) != 0) { + atomic_add_64(&sc->dma_errors, 1); + MYFIRST_UNLOCK(sc); + return (EIO); + } + + if (direction == MYFIRST_DMA_DIR_WRITE) + atomic_add_64(&sc->dma_transfers_write, 1); + else + atomic_add_64(&sc->dma_transfers_read, 1); + + MYFIRST_UNLOCK(sc); + return (0); +} + +void +myfirst_dma_handle_complete(struct myfirst_softc *sc) +{ + MYFIRST_ASSERT_LOCKED(sc); + + if (!sc->dma_in_flight) + return; + + sc->dma_in_flight = false; + if (sc->dma_last_direction == MYFIRST_DMA_DIR_WRITE) + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTWRITE); + else + bus_dmamap_sync(sc->dma_tag, sc->dma_map, + BUS_DMASYNC_POSTREAD); + + sc->dma_last_status = CSR_READ_4(sc, MYFIRST_REG_DMA_STATUS); + atomic_add_64(&sc->dma_complete_tasks, 1); + cv_broadcast(&sc->dma_cv); +} + +static int +myfirst_dma_sysctl_test_write(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int pattern; + int err; + + err = sysctl_handle_int(oidp, &pattern, 0, req); + if (err != 0 || req->newptr == NULL) + return (err); + + memset(sc->dma_vaddr, (int)(pattern & 0xFF), + MYFIRST_DMA_BUFFER_SIZE); + err = myfirst_dma_do_transfer_intr(sc, MYFIRST_DMA_DIR_WRITE, + MYFIRST_DMA_BUFFER_SIZE); + if (err != 0) + device_printf(sc->dev, + "dma_test_write: err %d\n", err); + else + device_printf(sc->dev, + "dma_test_write: pattern 0x%02x transferred\n", + pattern & 0xFF); + return (err); +} + +static int +myfirst_dma_sysctl_test_read(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + unsigned int ignore; + int err; + uint8_t *bytes; + + err = sysctl_handle_int(oidp, &ignore, 0, req); + if (err != 0 || req->newptr == NULL) + return (err); + + err = myfirst_dma_do_transfer_intr(sc, MYFIRST_DMA_DIR_READ, + MYFIRST_DMA_BUFFER_SIZE); + if (err != 0) { + device_printf(sc->dev, "dma_test_read: err %d\n", err); + return (err); + } + + bytes = (uint8_t *)sc->dma_vaddr; + device_printf(sc->dev, + "dma_test_read: first bytes %02x %02x %02x %02x " + "%02x %02x %02x %02x\n", + bytes[0], bytes[1], bytes[2], bytes[3], + bytes[4], bytes[5], bytes[6], bytes[7]); + return (0); +} + +void +myfirst_dma_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid_list *kids = SYSCTL_CHILDREN(sc->sysctl_tree); + + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_transfers_write", + CTLFLAG_RD, &sc->dma_transfers_write, 0, + "Successful host-to-device DMA transfers"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_transfers_read", + CTLFLAG_RD, &sc->dma_transfers_read, 0, + "Successful device-to-host DMA transfers"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_errors", + CTLFLAG_RD, &sc->dma_errors, 0, + "DMA transfers that returned EIO"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_timeouts", + CTLFLAG_RD, &sc->dma_timeouts, 0, + "DMA transfers that timed out"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_complete_intrs", + CTLFLAG_RD, &sc->dma_complete_intrs, 0, + "DMA completion interrupts observed"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "dma_complete_tasks", + CTLFLAG_RD, &sc->dma_complete_tasks, 0, + "DMA completion task invocations"); + SYSCTL_ADD_UQUAD(ctx, kids, OID_AUTO, "dma_bus_addr", + CTLFLAG_RD, &sc->dma_bus_addr, + "Bus address of the DMA buffer"); + + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "dma_test_write", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, sc, 0, + myfirst_dma_sysctl_test_write, "IU", + "Trigger a host-to-device DMA transfer"); + SYSCTL_ADD_PROC(ctx, kids, OID_AUTO, "dma_test_read", + CTLTYPE_UINT | CTLFLAG_WR | CTLFLAG_MPSAFE, sc, 0, + myfirst_dma_sysctl_test_read, "IU", + "Trigger a device-to-host DMA transfer"); +} diff --git a/examples/part-04/ch21-dma/stage4-final/myfirst_dma.h b/examples/part-04/ch21-dma/stage4-final/myfirst_dma.h new file mode 100644 index 0000000..57feab4 --- /dev/null +++ b/examples/part-04/ch21-dma/stage4-final/myfirst_dma.h @@ -0,0 +1,55 @@ +/*- + * Chapter 21 Stage 4: public DMA API for the myfirst driver. + * + * The DMA subsystem manages a single 4 KB host-visible buffer that + * is also reachable by the simulated (or real) device via DMA. The + * subsystem is set up at attach time, torn down at detach, and used + * for both host-to-device and device-to-host transfers through the + * public API below. + */ + +#ifndef _MYFIRST_DMA_H_ +#define _MYFIRST_DMA_H_ + +/* + * DMA buffer size used by myfirst. Matches the Chapter 21 simulated + * engine's scratch size. A real device would use a value from the + * hardware's documented capabilities. + */ +#define MYFIRST_DMA_BUFFER_SIZE 4096u + +/* DMA register offsets (relative to the BAR base). */ +#define MYFIRST_REG_DMA_ADDR_LOW 0x20 +#define MYFIRST_REG_DMA_ADDR_HIGH 0x24 +#define MYFIRST_REG_DMA_LEN 0x28 +#define MYFIRST_REG_DMA_DIR 0x2C +#define MYFIRST_REG_DMA_CTRL 0x30 +#define MYFIRST_REG_DMA_STATUS 0x34 + +/* DMA_DIR values. */ +#define MYFIRST_DMA_DIR_WRITE 0u /* host-to-device */ +#define MYFIRST_DMA_DIR_READ 1u /* device-to-host */ + +/* DMA_CTRL bits. */ +#define MYFIRST_DMA_CTRL_START (1u << 0) +#define MYFIRST_DMA_CTRL_ABORT (1u << 1) +#define MYFIRST_DMA_CTRL_RESET (1u << 31) + +/* DMA_STATUS bits. */ +#define MYFIRST_DMA_STATUS_DONE (1u << 0) +#define MYFIRST_DMA_STATUS_ERR (1u << 1) +#define MYFIRST_DMA_STATUS_RUNNING (1u << 2) + +/* Public API. */ +struct myfirst_softc; + +int myfirst_dma_setup(struct myfirst_softc *sc); +void myfirst_dma_teardown(struct myfirst_softc *sc); +int myfirst_dma_do_transfer(struct myfirst_softc *sc, + int direction, size_t length); +int myfirst_dma_do_transfer_intr(struct myfirst_softc *sc, + int direction, size_t length); +void myfirst_dma_handle_complete(struct myfirst_softc *sc); +void myfirst_dma_add_sysctls(struct myfirst_softc *sc); + +#endif /* _MYFIRST_DMA_H_ */ diff --git a/examples/part-04/ch22-power/labs/ch22-full-regression.sh b/examples/part-04/ch22-power/labs/ch22-full-regression.sh new file mode 100755 index 0000000..5a9f107 --- /dev/null +++ b/examples/part-04/ch22-power/labs/ch22-full-regression.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# ch22-full-regression.sh - combined regression for Chapter 22. +# +# Runs the cycle, stress, and cross-cycle tests in sequence. Also runs +# the runtime-PM test when the driver is built with runtime PM enabled. + +set -e + +HERE=$(dirname "$0") +DEV="dev.myfirst.0" + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present. Is the driver loaded?" + exit 1 +fi + +echo "=== Single cycle ===" +sh "${HERE}/ch22-suspend-resume-cycle.sh" + +echo "" +echo "=== 100-cycle stress ===" +sh "${HERE}/ch22-suspend-stress.sh" 100 + +echo "" +echo "=== Transfer across cycle ===" +sh "${HERE}/ch22-transfer-across-cycle.sh" + +echo "" +if sysctl -N ${DEV}.runtime_state >/dev/null 2>&1; then + echo "=== Runtime PM ===" + sh "${HERE}/ch22-runtime-pm.sh" +else + echo "=== Runtime PM: skipped (not enabled) ===" +fi + +echo "" +echo "=== Counter check ===" +s=$(sysctl -n ${DEV}.power_suspend_count) +r=$(sysctl -n ${DEV}.power_resume_count) +if [ "${s}" != "${r}" ]; then + echo "FAIL: suspend_count (${s}) != resume_count (${r})" + exit 1 +fi +echo "OK: suspend_count == resume_count == ${s}" + +echo "" +echo "FULL REGRESSION PASSED" diff --git a/examples/part-04/ch22-power/labs/ch22-runtime-pm.sh b/examples/part-04/ch22-power/labs/ch22-runtime-pm.sh new file mode 100755 index 0000000..3716188 --- /dev/null +++ b/examples/part-04/ch22-power/labs/ch22-runtime-pm.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# ch22-runtime-pm.sh - exercise the runtime-PM path. +# +# Requires the driver built with -DMYFIRST_ENABLE_RUNTIME_PM. + +set -e + +DEV="dev.myfirst.0" + +# Check that runtime PM is enabled. +if ! sysctl -N ${DEV}.runtime_state >/dev/null 2>&1; then + echo "SKIP: runtime PM is not enabled (rebuild with -DMYFIRST_ENABLE_RUNTIME_PM)" + exit 0 +fi + +# Set a short idle threshold so the test is quick. +sysctl -n ${DEV}.idle_threshold_seconds=3 > /dev/null + +before_s=$(sysctl -n ${DEV}.runtime_suspend_count) +before_r=$(sysctl -n ${DEV}.runtime_resume_count) + +# Trigger one transfer to set last_activity. +sysctl -n ${DEV}.dma_test_read=1 > /dev/null + +# Wait for the idle watcher to fire. +sleep 5 + +state=$(sysctl -n ${DEV}.runtime_state) +if [ "${state}" != "1" ]; then + echo "FAIL: runtime_state not suspended after idle (got '${state}')" + exit 1 +fi + +after_s=$(sysctl -n ${DEV}.runtime_suspend_count) +if [ $((after_s - before_s)) -ne 1 ]; then + echo "FAIL: runtime_suspend_count did not increment" + exit 1 +fi + +# Trigger a transfer to wake the device. +sysctl -n ${DEV}.dma_test_read=1 > /dev/null + +state=$(sysctl -n ${DEV}.runtime_state) +if [ "${state}" != "0" ]; then + echo "FAIL: runtime_state not running after transfer (got '${state}')" + exit 1 +fi + +after_r=$(sysctl -n ${DEV}.runtime_resume_count) +if [ $((after_r - before_r)) -ne 1 ]; then + echo "FAIL: runtime_resume_count did not increment" + exit 1 +fi + +echo "PASS: runtime PM cycle completed" diff --git a/examples/part-04/ch22-power/labs/ch22-suspend-resume-cycle.sh b/examples/part-04/ch22-power/labs/ch22-suspend-resume-cycle.sh new file mode 100755 index 0000000..d50b99b --- /dev/null +++ b/examples/part-04/ch22-power/labs/ch22-suspend-resume-cycle.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# ch22-suspend-resume-cycle.sh - one clean suspend-resume cycle. +# +# Triggers devctl suspend followed by devctl resume and verifies that +# the driver's counters and state flag move through the expected values. + +set -e + +DEV="dev.myfirst.0" +DEVNAME="myfirst0" + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present. Is the driver loaded?" + exit 1 +fi + +before_s=$(sysctl -n ${DEV}.power_suspend_count) +before_r=$(sysctl -n ${DEV}.power_resume_count) +before_x=$(sysctl -n ${DEV}.dma_transfers_read) + +# Baseline: run one transfer to prove the device works. +sysctl -n ${DEV}.dma_test_read=1 > /dev/null + +# Suspend. +devctl suspend ${DEVNAME} + +state=$(sysctl -n ${DEV}.suspended) +if [ "${state}" != "1" ]; then + echo "FAIL: device not marked suspended after devctl suspend (got '${state}')" + exit 1 +fi + +# Resume. +devctl resume ${DEVNAME} + +state=$(sysctl -n ${DEV}.suspended) +if [ "${state}" != "0" ]; then + echo "FAIL: device still marked suspended after devctl resume (got '${state}')" + exit 1 +fi + +# Post-resume transfer. +sysctl -n ${DEV}.dma_test_read=1 > /dev/null + +after_s=$(sysctl -n ${DEV}.power_suspend_count) +after_r=$(sysctl -n ${DEV}.power_resume_count) +after_x=$(sysctl -n ${DEV}.dma_transfers_read) + +delta_s=$((after_s - before_s)) +delta_r=$((after_r - before_r)) +delta_x=$((after_x - before_x)) + +fail=0 +if [ ${delta_s} -ne 1 ]; then + echo "FAIL: power_suspend_count delta=${delta_s}, expected 1" + fail=1 +fi +if [ ${delta_r} -ne 1 ]; then + echo "FAIL: power_resume_count delta=${delta_r}, expected 1" + fail=1 +fi +if [ ${delta_x} -ne 2 ]; then + echo "FAIL: dma_transfers_read delta=${delta_x}, expected 2" + fail=1 +fi + +if [ ${fail} -ne 0 ]; then + exit 1 +fi + +echo "PASS: one suspend-resume cycle completed cleanly" diff --git a/examples/part-04/ch22-power/labs/ch22-suspend-stress.sh b/examples/part-04/ch22-power/labs/ch22-suspend-stress.sh new file mode 100755 index 0000000..8e4a0a3 --- /dev/null +++ b/examples/part-04/ch22-power/labs/ch22-suspend-stress.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ch22-suspend-stress.sh - run 100 suspend-resume cycles. +# +# A regression test that exercises the suspend and resume paths many +# times in a row, watching for resource leaks, counter drift, and +# edge-case failures that only show up under repetition. + +N=${1:-100} +DEV="dev.myfirst.0" +DEVNAME="myfirst0" + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present." + exit 1 +fi + +before_s=$(sysctl -n ${DEV}.power_suspend_count) +before_r=$(sysctl -n ${DEV}.power_resume_count) + +echo "Running ${N} suspend-resume cycles..." + +i=0 +while [ $i -lt $N ]; do + if ! devctl suspend ${DEVNAME} >/dev/null 2>&1; then + echo "FAIL: suspend failed on iteration $i" + exit 1 + fi + if ! devctl resume ${DEVNAME} >/dev/null 2>&1; then + echo "FAIL: resume failed on iteration $i" + exit 1 + fi + i=$((i + 1)) +done + +after_s=$(sysctl -n ${DEV}.power_suspend_count) +after_r=$(sysctl -n ${DEV}.power_resume_count) + +delta_s=$((after_s - before_s)) +delta_r=$((after_r - before_r)) + +if [ ${delta_s} -ne ${N} ] || [ ${delta_r} -ne ${N} ]; then + echo "FAIL: expected ${N} each, got suspend=${delta_s} resume=${delta_r}" + exit 1 +fi + +# Final transfer to prove the device still works. +if ! sysctl -n ${DEV}.dma_test_read=1 > /dev/null; then + echo "FAIL: dma_test_read failed after ${N} cycles" + exit 1 +fi + +echo "PASS: ${N} cycles completed cleanly" diff --git a/examples/part-04/ch22-power/labs/ch22-transfer-across-cycle.sh b/examples/part-04/ch22-power/labs/ch22-transfer-across-cycle.sh new file mode 100755 index 0000000..4481d57 --- /dev/null +++ b/examples/part-04/ch22-power/labs/ch22-transfer-across-cycle.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# ch22-transfer-across-cycle.sh - suspend in the middle of a transfer. +# +# Starts a DMA transfer, immediately calls devctl suspend, and verifies +# that the quiesce path aborted the transfer cleanly. Then resumes and +# verifies that a post-resume transfer succeeds. + +set -e + +DEV="dev.myfirst.0" +DEVNAME="myfirst0" + +if ! sysctl -a | grep -q "^${DEV}"; then + echo "FAIL: ${DEV} not present." + exit 1 +fi + +# Start a transfer in the background. +(sysctl -n ${DEV}.dma_test_read=1 > /dev/null 2>&1 || true) & +BG=$! + +# Give it a moment to enter the engine. +sleep 0.001 2>/dev/null || : + +# Suspend immediately. +devctl suspend ${DEVNAME} + +# Wait for the background to finish (aborted, possibly). +wait ${BG} 2>/dev/null || : + +# Check the state. +state=$(sysctl -n ${DEV}.suspended) +if [ "${state}" != "1" ]; then + echo "FAIL: device not marked suspended (got '${state}')" + exit 1 +fi + +in_flight=$(sysctl -n ${DEV}.dma_in_flight) +if [ "${in_flight}" != "0" ]; then + echo "FAIL: dma_in_flight still 1 after suspend" + exit 1 +fi + +# Resume. +devctl resume ${DEVNAME} + +# A post-resume transfer should succeed. +if ! sysctl -n ${DEV}.dma_test_read=1 > /dev/null 2>&1; then + echo "FAIL: post-resume dma_test_read failed" + exit 1 +fi + +echo "PASS: transfer-across-cycle completed" diff --git a/examples/part-04/ch22-power/stage1-skeleton/Makefile b/examples/part-04/ch22-power/stage1-skeleton/Makefile new file mode 100644 index 0000000..02de4f3 --- /dev/null +++ b/examples/part-04/ch22-power/stage1-skeleton/Makefile @@ -0,0 +1,22 @@ +# Makefile for the Chapter 22 Stage 1 myfirst driver. +# +# Stage 1 adds skeleton DEVICE_SUSPEND/RESUME/SHUTDOWN methods that +# only log and count transitions. The source file list is unchanged +# from Chapter 21 Stage 4; the new code lives inside myfirst_pci.c. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + myfirst_dma.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.5-power-stage1\" + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch22-power/stage1-skeleton/myfirst_header_additions.h b/examples/part-04/ch22-power/stage1-skeleton/myfirst_header_additions.h new file mode 100644 index 0000000..8bd7e41 --- /dev/null +++ b/examples/part-04/ch22-power/stage1-skeleton/myfirst_header_additions.h @@ -0,0 +1,16 @@ +/*- + * Chapter 22 Stage 1: header additions. + * + * Append these fields to struct myfirst_softc in myfirst.h. + * Stage 1 only needs counters; Stage 2 and 3 add more fields. + */ + +/* + * Power-management counters. Expose through sysctls under + * dev.myfirst.N. + */ +/* + uint64_t power_suspend_count; + uint64_t power_resume_count; + uint64_t power_shutdown_count; + */ diff --git a/examples/part-04/ch22-power/stage1-skeleton/myfirst_pci_stage1.c b/examples/part-04/ch22-power/stage1-skeleton/myfirst_pci_stage1.c new file mode 100644 index 0000000..1809f6c --- /dev/null +++ b/examples/part-04/ch22-power/stage1-skeleton/myfirst_pci_stage1.c @@ -0,0 +1,63 @@ +/*- + * Chapter 22 Stage 1: skeleton power-management methods for the + * myfirst driver. + * + * These three functions should be added near the end of myfirst_pci.c, + * and the matching DEVMETHOD lines should be added to the + * myfirst_pci_methods[] array: + * + * DEVMETHOD(device_suspend, myfirst_pci_suspend), + * DEVMETHOD(device_resume, myfirst_pci_resume), + * DEVMETHOD(device_shutdown, myfirst_pci_shutdown), + * + * Stage 1 intentionally does no real work; it only logs and increments + * counters. Stage 2 turns the suspend path into a real quiesce; + * Stage 3 turns the resume path into a real restore; Stage 4 refactors + * everything into myfirst_power.c. + */ + +static int +myfirst_pci_suspend(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + device_printf(dev, "suspend (stage 1 skeleton)\n"); + atomic_add_64(&sc->power_suspend_count, 1); + return (0); +} + +static int +myfirst_pci_resume(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + device_printf(dev, "resume (stage 1 skeleton)\n"); + atomic_add_64(&sc->power_resume_count, 1); + return (0); +} + +static int +myfirst_pci_shutdown(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + device_printf(dev, "shutdown (stage 1 skeleton)\n"); + atomic_add_64(&sc->power_shutdown_count, 1); + return (0); +} + +/* + * Add these sysctl lines to the function that already creates the + * myfirst sysctl tree (usually myfirst_add_sysctls in myfirst.c). + */ +#if 0 +SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_suspend_count", + CTLFLAG_RD, &sc->power_suspend_count, 0, + "Number of times DEVICE_SUSPEND has been called"); +SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_resume_count", + CTLFLAG_RD, &sc->power_resume_count, 0, + "Number of times DEVICE_RESUME has been called"); +SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_shutdown_count", + CTLFLAG_RD, &sc->power_shutdown_count, 0, + "Number of times DEVICE_SHUTDOWN has been called"); +#endif diff --git a/examples/part-04/ch22-power/stage2-quiesce/Makefile b/examples/part-04/ch22-power/stage2-quiesce/Makefile new file mode 100644 index 0000000..f6e01ce --- /dev/null +++ b/examples/part-04/ch22-power/stage2-quiesce/Makefile @@ -0,0 +1,19 @@ +# Makefile for the Chapter 22 Stage 2 myfirst driver. +# +# Stage 2 turns the Stage 1 suspend skeleton into a real quiesce: +# mask interrupts, drain DMA, drain workers. The resume path is still +# the Stage 1 skeleton. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + myfirst_dma.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.5-power-stage2\" + +.include diff --git a/examples/part-04/ch22-power/stage2-quiesce/myfirst_header_additions.h b/examples/part-04/ch22-power/stage2-quiesce/myfirst_header_additions.h new file mode 100644 index 0000000..400bf23 --- /dev/null +++ b/examples/part-04/ch22-power/stage2-quiesce/myfirst_header_additions.h @@ -0,0 +1,11 @@ +/*- + * Chapter 22 Stage 2: header additions. + * + * Append these fields to struct myfirst_softc in myfirst.h. + */ + +/* + bool suspended; + uint32_t saved_intr_mask; + uint64_t power_resume_errors; + */ diff --git a/examples/part-04/ch22-power/stage2-quiesce/myfirst_pci_stage2.c b/examples/part-04/ch22-power/stage2-quiesce/myfirst_pci_stage2.c new file mode 100644 index 0000000..849c848 --- /dev/null +++ b/examples/part-04/ch22-power/stage2-quiesce/myfirst_pci_stage2.c @@ -0,0 +1,124 @@ +/*- + * Chapter 22 Stage 2: quiesce helpers and rewritten suspend for + * the myfirst driver. + * + * These functions extend Stage 1. The mask/drain helpers are used + * by the suspend path (this stage) and will also be used by the + * detach path (a refactor step left to Stage 4, where the code moves + * into myfirst_power.c). + */ + +static void +myfirst_mask_interrupts(struct myfirst_softc *sc) +{ + MYFIRST_ASSERT_UNLOCKED(sc); + + /* Save current mask for later restore. */ + sc->saved_intr_mask = CSR_READ_4(sc, MYFIRST_REG_INTR_MASK); + + /* + * Disable all interrupt sources at the device, and clear any + * pending status bits so we don't see a stale interrupt on resume. + */ + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, 0xFFFFFFFF); + CSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, 0xFFFFFFFF); +} + +static int +myfirst_drain_dma(struct myfirst_softc *sc) +{ + int err = 0; + + MYFIRST_LOCK(sc); + if (sc->dma_in_flight) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + + err = cv_timedwait(&sc->dma_cv, &sc->mtx, hz); + if (err == EWOULDBLOCK) { + device_printf(sc->dev, + "drain_dma: timeout waiting for abort\n"); + sc->dma_in_flight = false; + } + } + MYFIRST_UNLOCK(sc); + + return (err == EWOULDBLOCK ? ETIMEDOUT : 0); +} + +static void +myfirst_drain_workers(struct myfirst_softc *sc) +{ + /* + * Drain must happen with no driver lock held, because + * taskqueue_drain and callout_drain may wait on tasks that + * acquire the same lock. + */ + + if (sc->sim != NULL) + myfirst_sim_drain_dma_callout(sc->sim); + + if (sc->rx_vector.has_task) + taskqueue_drain(taskqueue_thread, &sc->rx_vector.task); +} + +static int +myfirst_quiesce(struct myfirst_softc *sc) +{ + int err; + + MYFIRST_LOCK(sc); + if (sc->suspended) { + MYFIRST_UNLOCK(sc); + return (0); + } + sc->suspended = true; + MYFIRST_UNLOCK(sc); + + myfirst_mask_interrupts(sc); + + err = myfirst_drain_dma(sc); + if (err != 0) { + device_printf(sc->dev, + "quiesce: DMA did not stop cleanly (err %d)\n", err); + } + + myfirst_drain_workers(sc); + + KASSERT(sc->dma_in_flight == false, + ("myfirst: dma_in_flight still true after drain")); + + return (err); +} + +static int +myfirst_pci_suspend(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + int err; + + device_printf(dev, "suspend: starting\n"); + + err = myfirst_quiesce(sc); + if (err != 0) { + device_printf(dev, + "suspend: quiesce returned %d; continuing anyway\n", + err); + } + + atomic_add_64(&sc->power_suspend_count, 1); + device_printf(dev, + "suspend: complete (dma in flight=%d, suspended=%d)\n", + sc->dma_in_flight, sc->suspended); + return (0); +} + +/* + * Suspended-flag sysctl. Add to the function that creates the + * sysctl tree. + */ +#if 0 +SYSCTL_ADD_BOOL(ctx, kids, OID_AUTO, "suspended", + CTLFLAG_RD, &sc->suspended, 0, + "Whether the driver is in the suspended state"); +#endif diff --git a/examples/part-04/ch22-power/stage3-restore/Makefile b/examples/part-04/ch22-power/stage3-restore/Makefile new file mode 100644 index 0000000..3cc7487 --- /dev/null +++ b/examples/part-04/ch22-power/stage3-restore/Makefile @@ -0,0 +1,18 @@ +# Makefile for the Chapter 22 Stage 3 myfirst driver. +# +# Stage 3 adds a real resume path that restores device state after a +# suspend-resume cycle. The suspend path is unchanged from Stage 2. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + myfirst_dma.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.5-power-stage3\" + +.include diff --git a/examples/part-04/ch22-power/stage3-restore/myfirst_pci_stage3.c b/examples/part-04/ch22-power/stage3-restore/myfirst_pci_stage3.c new file mode 100644 index 0000000..21e3242 --- /dev/null +++ b/examples/part-04/ch22-power/stage3-restore/myfirst_pci_stage3.c @@ -0,0 +1,66 @@ +/*- + * Chapter 22 Stage 3: restore helper and rewritten resume/shutdown + * for the myfirst driver. + * + * Replace the Stage 1 resume/shutdown skeletons with these. The + * quiesce helpers (mask_interrupts, drain_dma, drain_workers, + * myfirst_quiesce) from Stage 2 are still in place. + */ + +static int +myfirst_restore(struct myfirst_softc *sc) +{ + /* Step 1: defensively re-enable bus-master. */ + pci_enable_busmaster(sc->dev); + + /* Step 2: restore the interrupt mask. */ + if (sc->saved_intr_mask == 0xFFFFFFFF) { + /* + * saved_intr_mask is 0xFFFFFFFF only if the suspend + * happened before the driver had configured its mask. + * Fall back to a sensible default: enable DMA + * completion only, mask everything else. + */ + sc->saved_intr_mask = ~MYFIRST_INTR_COMPLETE; + } + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, sc->saved_intr_mask); + + /* Step 3: clear the suspended flag. */ + MYFIRST_LOCK(sc); + sc->suspended = false; + MYFIRST_UNLOCK(sc); + + return (0); +} + +static int +myfirst_pci_resume(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + int err; + + device_printf(dev, "resume: starting\n"); + + err = myfirst_restore(sc); + if (err != 0) { + device_printf(dev, + "resume: restore failed (err %d)\n", err); + atomic_add_64(&sc->power_resume_errors, 1); + } + + atomic_add_64(&sc->power_resume_count, 1); + device_printf(dev, "resume: complete\n"); + return (0); +} + +static int +myfirst_pci_shutdown(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + device_printf(dev, "shutdown: starting\n"); + (void)myfirst_quiesce(sc); + atomic_add_64(&sc->power_shutdown_count, 1); + device_printf(dev, "shutdown: complete\n"); + return (0); +} diff --git a/examples/part-04/ch22-power/stage4-final/Makefile b/examples/part-04/ch22-power/stage4-final/Makefile new file mode 100644 index 0000000..ffb682c --- /dev/null +++ b/examples/part-04/ch22-power/stage4-final/Makefile @@ -0,0 +1,26 @@ +# Makefile for the Chapter 22 Stage 4 myfirst driver. +# +# Stage 4 adds myfirst_power.c to the build and bumps the version to +# 1.5-power. Structurally identical to Stage 3 except for this one new +# source file and the Chapter 21 Stage 4 list. + +KMOD= myfirst +SRCS= myfirst.c \ + myfirst_hw.c myfirst_hw_pci.c \ + myfirst_sim.c \ + myfirst_pci.c \ + myfirst_intr.c \ + myfirst_msix.c \ + myfirst_dma.c \ + myfirst_power.c \ + cbuf.c + +CFLAGS+= -DMYFIRST_VERSION_STRING=\"1.5-power\" + +# Optional: enable runtime PM. +# CFLAGS+= -DMYFIRST_ENABLE_RUNTIME_PM + +# Optional: simulation-only build. +# CFLAGS+= -DMYFIRST_SIMULATION_ONLY + +.include diff --git a/examples/part-04/ch22-power/stage4-final/POWER.md b/examples/part-04/ch22-power/stage4-final/POWER.md new file mode 100644 index 0000000..0f355dc --- /dev/null +++ b/examples/part-04/ch22-power/stage4-final/POWER.md @@ -0,0 +1,189 @@ +# Power-Management Subsystem + +## Purpose + +The power layer lets the `myfirst` driver participate correctly in +system suspend, system resume, system shutdown, and optional +per-device runtime power management. It quiesces the device's +activity before a power transition and restores the device's state +after resume, so that a suspend-resume cycle is invisible to the +user space clients of the driver. + +## Public API + +- `myfirst_power_setup(sc)`: called from attach. Initialises softc + fields, optionally starts the idle watcher callout. +- `myfirst_power_teardown(sc)`: called from detach. Stops the idle + watcher, brings the device out of runtime suspend if needed. +- `myfirst_power_suspend(sc)`: kobj DEVICE_SUSPEND implementation. +- `myfirst_power_resume(sc)`: kobj DEVICE_RESUME implementation. +- `myfirst_power_shutdown(sc)`: kobj DEVICE_SHUTDOWN implementation. +- `myfirst_power_runtime_suspend(sc)`, `myfirst_power_runtime_resume(sc)`: + optional runtime PM; compiled only with `-DMYFIRST_ENABLE_RUNTIME_PM`. +- `myfirst_power_mark_active(sc)`: optional runtime PM; record + activity to reset the idle timer. +- `myfirst_power_add_sysctls(sc)`: registers counter and policy + sysctls under `dev.myfirst.N.`. + +## State Model + +The driver's lifecycle extends as follows: + +``` + +---- runtime_suspend ----+ + | | + attach -> RUNNING <---> RUNTIME_SUSPENDED (D3) + | ^ ^ + | resume| suspend| + v | | + detach <-- SUSPENDED -------- system_suspend +``` + +- `RUNNING`: normal operation (D0). +- `SUSPENDED`: system has suspended the device (D3 typically). +- `RUNTIME_SUSPENDED`: driver has suspended the device in response + to idleness (D3). + +The `suspended` flag distinguishes the current state for quick user- +space observation. The `runtime_state` enum tracks runtime PM. + +## Transition Flows + +### System Suspend (devctl suspend or acpiconf -s 3) + +``` +1. kernel calls myfirst_pci_suspend(dev) +2. myfirst_pci_suspend calls myfirst_power_suspend(sc) +3. myfirst_quiesce: + - lock; set suspended=true; unlock + - mask_interrupts: save mask, write 0xFFFFFFFF + - drain_dma: abort if in flight, wait on cv + - drain_workers: drain callout, drain taskqueue +4. PCI layer saves config space and transitions to D3 (if default) +5. method returns 0 +``` + +### System Resume + +``` +1. PCI layer transitions to D0 and restores config space +2. kernel calls myfirst_pci_resume(dev) +3. myfirst_pci_resume calls myfirst_power_resume(sc) +4. myfirst_restore: + - pci_enable_busmaster (defensive) + - write saved_intr_mask back to INTR_MASK register + - lock; set suspended=false; unlock +5. method returns 0 +``` + +### System Shutdown + +``` +1. kernel calls myfirst_pci_shutdown(dev) +2. forwards to myfirst_power_shutdown(sc) +3. calls myfirst_quiesce(sc) +4. method returns 0 +``` + +### Runtime Suspend (optional) + +``` +1. idle watcher callout fires +2. detects idle > idle_threshold_seconds +3. calls myfirst_power_runtime_suspend(sc) +4. quiesce; pci_save_state; pci_set_powerstate(D3) +``` + +### Runtime Resume (optional) + +``` +1. activity arrives (DMA test sysctl write) +2. calls myfirst_power_runtime_resume(sc) if suspended +3. pci_set_powerstate(D0); pci_restore_state; myfirst_restore +``` + +## Counters and Sysctls + +- `dev.myfirst.N.suspended`: driver-level suspended flag (0/1). +- `dev.myfirst.N.power_suspend_count`: DEVICE_SUSPEND invocations. +- `dev.myfirst.N.power_resume_count`: DEVICE_RESUME invocations. +- `dev.myfirst.N.power_shutdown_count`: DEVICE_SHUTDOWN invocations. +- `dev.myfirst.N.power_resume_errors`: resume attempts with errors. +- `dev.myfirst.N.idle_threshold_seconds` (runtime PM): policy knob. +- `dev.myfirst.N.runtime_suspend_count` (runtime PM): transitions. +- `dev.myfirst.N.runtime_resume_count` (runtime PM): transitions. +- `dev.myfirst.N.runtime_state` (runtime PM): 0=running, 1=suspended. + +## Invariants + +- `power_suspend_count == power_resume_count` at all times except + during an active suspension (when the counters differ by 1). +- `runtime_suspend_count == runtime_resume_count` at steady state + (when the device is RUNNING). +- `sc->suspended == false` whenever the device is in RUNNING state. +- `sc->dma_in_flight == false` after `myfirst_quiesce` returns. + +The regression test `ch22-full-regression.sh` verifies these. + +## Locking + +- `sc->mtx` protects `suspended`, `saved_intr_mask`, and the runtime + PM state. +- Counters use `atomic_add_64` so they can be updated from filter + context without the mutex. +- `cv_timedwait` in `myfirst_drain_dma` holds the mutex while + sleeping, then releases it. +- `taskqueue_drain` and `callout_drain` must be called without the + driver mutex held, because the drained work may acquire the same + mutex. + +## Interaction with Other Subsystems + +- **DMA (`myfirst_dma.c`)**: suspend calls `myfirst_drain_dma`, + which reuses the Chapter 21 `dma_cv` and `dma_in_flight` state. + The DMA tag, map, and buffer remain allocated across suspend. +- **Interrupts (`myfirst_intr.c`, `myfirst_msix.c`)**: suspend masks + all vectors; resume unmasks via `saved_intr_mask`. Vector + allocations remain valid across the transition; the PCI layer + restores MSI/MSI-X configuration automatically. +- **Simulation (`myfirst_sim.c`)**: the simulation's callout is + drained as part of `myfirst_drain_workers`. The simulation's + state survives suspend. +- **PCI (`myfirst_pci.c`)**: the method table forwards kobj + invocations to the power subsystem. Configuration-space save and + restore is handled by the PCI layer itself. + +## Testing + +The `labs/` directory contains: + +- `ch22-suspend-resume-cycle.sh`: one cycle with counter checks. +- `ch22-suspend-stress.sh`: 100 cycles in a row. +- `ch22-transfer-across-cycle.sh`: transfer + suspend + resume. +- `ch22-runtime-pm.sh`: runtime PM path (requires -DMYFIRST_ENABLE_RUNTIME_PM). +- `ch22-full-regression.sh`: combined regression. + +## Known Limitations + +- Single global suspend state; no per-subsystem suspend. +- No wake-on-X support (no wake source in the simulation). +- No descriptor-ring state to restore (the driver uses a single + DMA buffer). +- Runtime PM idle detection is timer-based; a production driver + might use reference counting or queue-empty signals instead. + +These are natural extensions documented in the chapter text. + +## See Also + +- `device(9)`, `bus(9)`, `pci(9)`. +- `/usr/src/sys/kern/device_if.m` for the kobj method definitions. +- `/usr/src/sys/kern/subr_bus.c` for `bus_generic_suspend` and + `device_quiesce`. +- `/usr/src/sys/dev/pci/pci.c` for `pci_suspend_child` and + `pci_resume_child`. +- `/usr/src/sys/dev/re/if_re.c` for a production driver with full + power management. +- `INTERRUPTS.md`, `MSIX.md`, `DMA.md` for the subsystems the + power path interacts with. +- The chapter text at `content/chapters/part4/chapter-22.md`. diff --git a/examples/part-04/ch22-power/stage4-final/myfirst_power.c b/examples/part-04/ch22-power/stage4-final/myfirst_power.c new file mode 100644 index 0000000..7ad1b82 --- /dev/null +++ b/examples/part-04/ch22-power/stage4-final/myfirst_power.c @@ -0,0 +1,384 @@ +/*- + * Chapter 22 Stage 4: myfirst_power.c + * + * Consolidated power-management subsystem for the myfirst driver. + * Moves the power code from myfirst_pci.c (Stage 1-3) into its own + * compilation unit with a documented public API. + * + * This file implements the API declared in myfirst_power.h: + * - myfirst_power_setup / myfirst_power_teardown: lifecycle. + * - myfirst_power_suspend / _resume / _shutdown: the three kobj + * power-management methods. + * - myfirst_power_runtime_suspend / _resume / mark_active: optional + * runtime PM, compiled only with -DMYFIRST_ENABLE_RUNTIME_PM. + * - myfirst_power_add_sysctls: registers counters and policy knobs. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "myfirst.h" +#include "myfirst_hw.h" +#include "myfirst_dma.h" +#include "myfirst_msix.h" +#include "myfirst_power.h" + +static void myfirst_mask_interrupts(struct myfirst_softc *sc); +static int myfirst_drain_dma(struct myfirst_softc *sc); +static void myfirst_drain_workers(struct myfirst_softc *sc); +static int myfirst_quiesce(struct myfirst_softc *sc); +static int myfirst_restore(struct myfirst_softc *sc); + +#ifdef MYFIRST_ENABLE_RUNTIME_PM +static void myfirst_idle_watcher_cb(void *arg); +#endif + +/* ----- Quiesce helpers ----- */ + +static void +myfirst_mask_interrupts(struct myfirst_softc *sc) +{ + MYFIRST_ASSERT_UNLOCKED(sc); + + sc->saved_intr_mask = CSR_READ_4(sc, MYFIRST_REG_INTR_MASK); + + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, 0xFFFFFFFF); + CSR_WRITE_4(sc, MYFIRST_REG_INTR_STATUS, 0xFFFFFFFF); +} + +static int +myfirst_drain_dma(struct myfirst_softc *sc) +{ + int err = 0; + + MYFIRST_LOCK(sc); + if (sc->dma_in_flight) { + CSR_WRITE_4(sc, MYFIRST_REG_DMA_CTRL, + MYFIRST_DMA_CTRL_ABORT); + + err = cv_timedwait(&sc->dma_cv, &sc->mtx, hz); + if (err == EWOULDBLOCK) { + device_printf(sc->dev, + "drain_dma: timeout waiting for abort\n"); + sc->dma_in_flight = false; + } + } + MYFIRST_UNLOCK(sc); + + return (err == EWOULDBLOCK ? ETIMEDOUT : 0); +} + +static void +myfirst_drain_workers(struct myfirst_softc *sc) +{ + if (sc->sim != NULL) + myfirst_sim_drain_dma_callout(sc->sim); + + if (sc->rx_vector.has_task) + taskqueue_drain(taskqueue_thread, &sc->rx_vector.task); +} + +static int +myfirst_quiesce(struct myfirst_softc *sc) +{ + int err; + + MYFIRST_LOCK(sc); + if (sc->suspended) { + MYFIRST_UNLOCK(sc); + return (0); + } + sc->suspended = true; + MYFIRST_UNLOCK(sc); + + myfirst_mask_interrupts(sc); + + err = myfirst_drain_dma(sc); + if (err != 0) { + device_printf(sc->dev, + "quiesce: DMA did not stop cleanly (err %d)\n", err); + } + + myfirst_drain_workers(sc); + + KASSERT(sc->dma_in_flight == false, + ("myfirst: dma_in_flight still true after drain")); + + return (err); +} + +/* ----- Restore helper ----- */ + +static int +myfirst_restore(struct myfirst_softc *sc) +{ + pci_enable_busmaster(sc->dev); + + if (sc->saved_intr_mask == 0xFFFFFFFF) { + sc->saved_intr_mask = ~MYFIRST_INTR_COMPLETE; + } + CSR_WRITE_4(sc, MYFIRST_REG_INTR_MASK, sc->saved_intr_mask); + + MYFIRST_LOCK(sc); + sc->suspended = false; + MYFIRST_UNLOCK(sc); + + return (0); +} + +/* ----- Public kobj-method implementations ----- */ + +int +myfirst_power_suspend(struct myfirst_softc *sc) +{ + int err; + + device_printf(sc->dev, "suspend: starting\n"); + + err = myfirst_quiesce(sc); + if (err != 0) { + device_printf(sc->dev, + "suspend: quiesce returned %d; continuing\n", err); + } + + atomic_add_64(&sc->power_suspend_count, 1); + device_printf(sc->dev, + "suspend: complete (dma in flight=%d, suspended=%d)\n", + sc->dma_in_flight, sc->suspended); + return (0); +} + +int +myfirst_power_resume(struct myfirst_softc *sc) +{ + int err; + + device_printf(sc->dev, "resume: starting\n"); + + err = myfirst_restore(sc); + if (err != 0) { + device_printf(sc->dev, + "resume: restore failed (err %d)\n", err); + atomic_add_64(&sc->power_resume_errors, 1); + } + + atomic_add_64(&sc->power_resume_count, 1); + device_printf(sc->dev, "resume: complete\n"); + return (0); +} + +int +myfirst_power_shutdown(struct myfirst_softc *sc) +{ + device_printf(sc->dev, "shutdown: starting\n"); + (void)myfirst_quiesce(sc); + atomic_add_64(&sc->power_shutdown_count, 1); + device_printf(sc->dev, "shutdown: complete\n"); + return (0); +} + +/* ----- Runtime PM ----- */ + +#ifdef MYFIRST_ENABLE_RUNTIME_PM + +int +myfirst_power_runtime_suspend(struct myfirst_softc *sc) +{ + int err; + + device_printf(sc->dev, "runtime suspend: starting\n"); + + err = myfirst_quiesce(sc); + if (err != 0) { + device_printf(sc->dev, + "runtime suspend: quiesce failed (err %d)\n", err); + MYFIRST_LOCK(sc); + sc->suspended = false; + MYFIRST_UNLOCK(sc); + return (err); + } + + pci_save_state(sc->dev); + err = pci_set_powerstate(sc->dev, PCI_POWERSTATE_D3); + if (err != 0) { + device_printf(sc->dev, + "runtime suspend: set_powerstate(D3) failed (err %d)\n", + err); + pci_restore_state(sc->dev); + myfirst_restore(sc); + return (err); + } + + MYFIRST_LOCK(sc); + sc->runtime_state = MYFIRST_RT_SUSPENDED; + MYFIRST_UNLOCK(sc); + atomic_add_64(&sc->runtime_suspend_count, 1); + + device_printf(sc->dev, "runtime suspend: device in D3\n"); + return (0); +} + +int +myfirst_power_runtime_resume(struct myfirst_softc *sc) +{ + int err; + + MYFIRST_LOCK(sc); + if (sc->runtime_state != MYFIRST_RT_SUSPENDED) { + MYFIRST_UNLOCK(sc); + return (0); + } + MYFIRST_UNLOCK(sc); + + device_printf(sc->dev, "runtime resume: starting\n"); + + err = pci_set_powerstate(sc->dev, PCI_POWERSTATE_D0); + if (err != 0) { + device_printf(sc->dev, + "runtime resume: set_powerstate(D0) failed (err %d)\n", + err); + return (err); + } + pci_restore_state(sc->dev); + + err = myfirst_restore(sc); + if (err != 0) { + device_printf(sc->dev, + "runtime resume: restore failed (err %d)\n", err); + return (err); + } + + MYFIRST_LOCK(sc); + sc->runtime_state = MYFIRST_RT_RUNNING; + MYFIRST_UNLOCK(sc); + atomic_add_64(&sc->runtime_resume_count, 1); + + device_printf(sc->dev, "runtime resume: device in D0\n"); + return (0); +} + +void +myfirst_power_mark_active(struct myfirst_softc *sc) +{ + MYFIRST_LOCK(sc); + microtime(&sc->last_activity); + MYFIRST_UNLOCK(sc); +} + +static void +myfirst_idle_watcher_cb(void *arg) +{ + struct myfirst_softc *sc = arg; + struct timeval now, diff; + + MYFIRST_ASSERT_LOCKED(sc); + + if (sc->runtime_state == MYFIRST_RT_RUNNING && !sc->suspended) { + microtime(&now); + timersub(&now, &sc->last_activity, &diff); + + if (diff.tv_sec >= sc->idle_threshold_seconds) { + MYFIRST_UNLOCK(sc); + (void)myfirst_power_runtime_suspend(sc); + MYFIRST_LOCK(sc); + } + } + + callout_reset(&sc->idle_watcher, hz, myfirst_idle_watcher_cb, sc); +} + +#endif /* MYFIRST_ENABLE_RUNTIME_PM */ + +/* ----- Subsystem lifecycle ----- */ + +int +myfirst_power_setup(struct myfirst_softc *sc) +{ + sc->suspended = false; + sc->saved_intr_mask = 0; + sc->power_suspend_count = 0; + sc->power_resume_count = 0; + sc->power_shutdown_count = 0; + sc->power_resume_errors = 0; + +#ifdef MYFIRST_ENABLE_RUNTIME_PM + sc->runtime_state = MYFIRST_RT_RUNNING; + sc->idle_threshold_seconds = 5; + sc->runtime_suspend_count = 0; + sc->runtime_resume_count = 0; + microtime(&sc->last_activity); + callout_init_mtx(&sc->idle_watcher, &sc->mtx, 0); + callout_reset(&sc->idle_watcher, hz, myfirst_idle_watcher_cb, sc); +#endif + + return (0); +} + +void +myfirst_power_teardown(struct myfirst_softc *sc) +{ +#ifdef MYFIRST_ENABLE_RUNTIME_PM + callout_drain(&sc->idle_watcher); + + /* If we were runtime-suspended, bring the device back before the + * rest of detach runs. */ + if (sc->runtime_state == MYFIRST_RT_SUSPENDED) + (void)myfirst_power_runtime_resume(sc); +#endif +} + +/* ----- Sysctls ----- */ + +void +myfirst_power_add_sysctls(struct myfirst_softc *sc) +{ + struct sysctl_ctx_list *ctx = &sc->sysctl_ctx; + struct sysctl_oid_list *kids = SYSCTL_CHILDREN(sc->sysctl_tree); + + SYSCTL_ADD_BOOL(ctx, kids, OID_AUTO, "suspended", + CTLFLAG_RD, &sc->suspended, 0, + "Whether the driver is in the suspended state"); + + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_suspend_count", + CTLFLAG_RD, &sc->power_suspend_count, 0, + "Number of times DEVICE_SUSPEND has been called"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_resume_count", + CTLFLAG_RD, &sc->power_resume_count, 0, + "Number of times DEVICE_RESUME has been called"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_shutdown_count", + CTLFLAG_RD, &sc->power_shutdown_count, 0, + "Number of times DEVICE_SHUTDOWN has been called"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "power_resume_errors", + CTLFLAG_RD, &sc->power_resume_errors, 0, + "Number of resume attempts that encountered an error"); + +#ifdef MYFIRST_ENABLE_RUNTIME_PM + SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "idle_threshold_seconds", + CTLFLAG_RW, &sc->idle_threshold_seconds, 0, + "Runtime PM idle threshold (seconds)"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "runtime_suspend_count", + CTLFLAG_RD, &sc->runtime_suspend_count, 0, + "Runtime suspends performed"); + SYSCTL_ADD_U64(ctx, kids, OID_AUTO, "runtime_resume_count", + CTLFLAG_RD, &sc->runtime_resume_count, 0, + "Runtime resumes performed"); + SYSCTL_ADD_INT(ctx, kids, OID_AUTO, "runtime_state", + CTLFLAG_RD, (int *)&sc->runtime_state, 0, + "Runtime state: 0=running, 1=suspended"); +#endif +} diff --git a/examples/part-04/ch22-power/stage4-final/myfirst_power.h b/examples/part-04/ch22-power/stage4-final/myfirst_power.h new file mode 100644 index 0000000..24c284e --- /dev/null +++ b/examples/part-04/ch22-power/stage4-final/myfirst_power.h @@ -0,0 +1,36 @@ +/*- + * Chapter 22 Stage 4: public power-management API for the + * myfirst driver. + * + * The power subsystem implements DEVICE_SUSPEND, DEVICE_RESUME, and + * DEVICE_SHUTDOWN by coordinating a quiesce (mask interrupts, drain + * DMA, drain workers) and a restore (re-enable bus-master, restore + * registers, clear suspended flag). It optionally implements runtime + * power management when built with -DMYFIRST_ENABLE_RUNTIME_PM. + */ + +#ifndef _MYFIRST_POWER_H_ +#define _MYFIRST_POWER_H_ + +struct myfirst_softc; + +/* Subsystem lifecycle. */ +int myfirst_power_setup(struct myfirst_softc *sc); +void myfirst_power_teardown(struct myfirst_softc *sc); + +/* Power-management method implementations. Called from myfirst_pci.c. */ +int myfirst_power_suspend(struct myfirst_softc *sc); +int myfirst_power_resume(struct myfirst_softc *sc); +int myfirst_power_shutdown(struct myfirst_softc *sc); + +#ifdef MYFIRST_ENABLE_RUNTIME_PM +/* Runtime power management: idle-triggered D0 <-> D3 transitions. */ +int myfirst_power_runtime_suspend(struct myfirst_softc *sc); +int myfirst_power_runtime_resume(struct myfirst_softc *sc); +void myfirst_power_mark_active(struct myfirst_softc *sc); +#endif + +/* Sysctl registration. */ +void myfirst_power_add_sysctls(struct myfirst_softc *sc); + +#endif /* _MYFIRST_POWER_H_ */ diff --git a/examples/part-05/ch23-debug/labs/lab23_1_ddb.sh b/examples/part-05/ch23-debug/labs/lab23_1_ddb.sh new file mode 100755 index 0000000..8ba2626 --- /dev/null +++ b/examples/part-05/ch23-debug/labs/lab23_1_ddb.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# +# lab23_1_ddb.sh - Lab 23.1: A First DDB Session +# +# This script does not automate DDB itself (DDB is interactive by +# nature). It prepares the environment and prints the commands the +# reader should run step by step. + +set -e + +echo "=== Lab 23.1: A First DDB Session ===" +echo +echo "1. Confirm the kernel is a debug kernel with KDB/DDB:" +echo " sysctl kern.version" +echo " sysctl debug.kdb" +echo +echo "2. Load the myfirst driver:" +echo " sudo kldload ./myfirst.ko # or the full path to your module" +echo " ls /dev/myfirst0" +echo +echo "3. Enter DDB from this shell (safe on a test system):" +echo " sudo sysctl debug.kdb.enter=1" +echo +echo "4. At the 'db>' prompt, run these commands:" +echo " db> show pcpu" +echo " db> ps" +echo " db> bt" +echo " db> show locks" +echo +echo "5. Return to normal operation:" +echo " db> continue" +echo +echo "6. Confirm the system is running again:" +echo " dmesg | tail" +echo +echo "7. Unload the driver:" +echo " sudo kldunload myfirst" +echo +echo "=== End of Lab 23.1 ===" diff --git a/examples/part-05/ch23-debug/labs/lab23_2_dtrace.sh b/examples/part-05/ch23-debug/labs/lab23_2_dtrace.sh new file mode 100755 index 0000000..2a9a1c2 --- /dev/null +++ b/examples/part-05/ch23-debug/labs/lab23_2_dtrace.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# +# lab23_2_dtrace.sh - Lab 23.2: Measuring the Driver with DTrace +# +# Exercises the driver while DTrace counts function entries. + +set -e + +if [ "$(id -u)" -ne 0 ]; then + echo "This script must run as root (for dtrace and kldload)" >&2 + exit 1 +fi + +echo "=== Lab 23.2: Measuring the Driver with DTrace ===" +echo + +MODULE=${1:-./myfirst.ko} +if ! kldstat | grep -q myfirst; then + echo "Loading module: $MODULE" + kldload "$MODULE" +fi + +echo +echo "Starting DTrace count in the background..." +dtrace -q -n 'fbt::myfirst_*:entry { @[probefunc] = count(); } + tick-5s { exit(0); }' & +DT_PID=$! + +sleep 1 +echo +echo "Exercising the driver (100 reads)..." +for i in $(seq 1 100); do + cat /dev/myfirst0 > /dev/null +done + +wait $DT_PID +echo +echo "Expected: 100 open, 100 close, 100 read entries." +echo +echo "=== End of Lab 23.2 ===" diff --git a/examples/part-05/ch23-debug/labs/lab23_3_ktrace.sh b/examples/part-05/ch23-debug/labs/lab23_3_ktrace.sh new file mode 100755 index 0000000..5284231 --- /dev/null +++ b/examples/part-05/ch23-debug/labs/lab23_3_ktrace.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# +# lab23_3_ktrace.sh - Lab 23.3: User-Side Tracing with ktrace +# +# Compiles a small test program, traces it with ktrace, and shows the +# resulting kdump output. + +set -e + +WORKDIR=$(mktemp -d) +trap "rm -rf '$WORKDIR'" EXIT + +cat > "$WORKDIR/myftest.c" <<'CEOF' +#include +#include +#include +#include + +int +main(void) +{ + int fd; + char buf[64]; + int arg = 0; + + fd = open("/dev/myfirst0", O_RDONLY); + if (fd < 0) { + perror("open"); + return (1); + } + /* A harmless ioctl that may or may not be supported */ + (void)ioctl(fd, _IOR('f', 99, int), &arg); + read(fd, buf, sizeof(buf)); + close(fd); + return (0); +} +CEOF + +echo "=== Lab 23.3: User-Side Tracing with ktrace ===" +echo +echo "Compiling myftest.c in $WORKDIR" +cc -o "$WORKDIR/myftest" "$WORKDIR/myftest.c" + +echo "Tracing the program..." +sudo ktrace -di -f "$WORKDIR/mytrace.out" "$WORKDIR/myftest" +echo +echo "Dumping the trace (relevant syscalls):" +kdump -f "$WORKDIR/mytrace.out" | grep -E 'myfirst0|CALL|RET' | head -40 + +echo +echo "=== End of Lab 23.3 ===" diff --git a/examples/part-05/ch23-debug/labs/lab23_4_leak.sh b/examples/part-05/ch23-debug/labs/lab23_4_leak.sh new file mode 100755 index 0000000..a4e37bf --- /dev/null +++ b/examples/part-05/ch23-debug/labs/lab23_4_leak.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# +# lab23_4_leak.sh - Lab 23.4: Finding a Memory Leak with vmstat -m +# +# This script does not automatically modify source files. It runs the +# workload and checks vmstat -m, but the lab expects the reader to +# introduce the deliberate leak in myfirst_open() themselves, reload, +# run this script, fix the leak in myfirst_close(), reload, and run +# again. + +set -e + +echo "=== Lab 23.4: Finding a Memory Leak with vmstat -m ===" +echo +echo "Snapshot 1: baseline memory pool state for myfirst" +vmstat -m | grep -E 'Type|myfirst' || echo "(no myfirst pool - is the driver loaded?)" +echo +echo "Running workload: 1000 open/read/close cycles..." +for i in $(seq 1 1000); do + cat /dev/myfirst0 > /dev/null +done +sync +echo +echo "Snapshot 2: memory pool state after workload" +vmstat -m | grep -E 'Type|myfirst' +echo +echo "Expected behaviour:" +echo " - If the leak is present, InUse grew by ~1000 since snapshot 1." +echo " - If the leak is fixed, InUse is essentially unchanged." +echo +echo "=== End of Lab 23.4 ===" diff --git a/examples/part-05/ch23-debug/labs/lab23_5_refactor.sh b/examples/part-05/ch23-debug/labs/lab23_5_refactor.sh new file mode 100755 index 0000000..d62ea9c --- /dev/null +++ b/examples/part-05/ch23-debug/labs/lab23_5_refactor.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# +# lab23_5_refactor.sh - Lab 23.5: Installing the 1.6-debug Refactor +# +# Walks the reader through loading the refactored driver and confirming +# the new debug infrastructure is active. + +set -e + +if [ "$(id -u)" -ne 0 ]; then + echo "This script must run as root" >&2 + exit 1 +fi + +echo "=== Lab 23.5: Installing the 1.6-debug Refactor ===" +echo +echo "1. Unload any previous myfirst driver:" +kldunload myfirst 2>/dev/null || true + +echo +echo "2. Load the refactored driver:" +MODULE=${1:-./myfirst.ko} +kldload "$MODULE" + +echo +echo "3. Confirm the version:" +kldstat -v | grep -i myfirst | head -5 + +echo +echo "4. Confirm the sysctl is present:" +sysctl dev.myfirst.0.debug.mask + +echo +echo "5. Enable full debug:" +sysctl dev.myfirst.0.debug.mask=0xFFFFFFFF + +echo +echo "6. Exercise the device:" +cat /dev/myfirst0 > /dev/null + +echo +echo "7. Read the log:" +dmesg | tail -20 + +echo +echo "8. Disable debug:" +sysctl dev.myfirst.0.debug.mask=0 + +echo +echo "9. Count SDT probes via DTrace (5 seconds):" +dtrace -q -n 'myfirst::: { @[probename] = count(); } + tick-5s { exit(0); }' & +DT_PID=$! +sleep 1 +for i in $(seq 1 50); do + cat /dev/myfirst0 > /dev/null +done +wait $DT_PID + +echo +echo "=== End of Lab 23.5 ===" diff --git a/examples/part-05/ch23-debug/stage1-logging/myfirst_logging.patch b/examples/part-05/ch23-debug/stage1-logging/myfirst_logging.patch new file mode 100644 index 0000000..47efd1f --- /dev/null +++ b/examples/part-05/ch23-debug/stage1-logging/myfirst_logging.patch @@ -0,0 +1,86 @@ +--- a/myfirst.c ++++ b/myfirst.c +@@ -1,5 +1,6 @@ + /* +- * myfirst driver - version 1.5-power ++ * myfirst driver - version 1.5-power (Chapter 23 Stage 1: unconditional ++ * logging at key points) + */ + + static int + myfirst_open(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + int error = 0; + ++ device_printf(sc->sc_dev, ++ "open entry: pid=%d flags=0x%x\n", ++ td->td_proc->p_pid, flags); ++ + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count >= MYFIRST_MAX_OPENS) { + error = EBUSY; + goto out; + } + sc->sc_open_count++; + out: + mtx_unlock(&sc->sc_mtx); ++ ++ if (error != 0) ++ device_printf(sc->sc_dev, "open failed: error=%d\n", error); ++ else ++ device_printf(sc->sc_dev, "open ok: count=%d\n", ++ sc->sc_open_count); ++ + return (error); + } + + static int + myfirst_close(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + ++ device_printf(sc->sc_dev, ++ "close entry: pid=%d\n", td->td_proc->p_pid); ++ + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count > 0) + sc->sc_open_count--; + mtx_unlock(&sc->sc_mtx); + ++ device_printf(sc->sc_dev, "close ok: count=%d\n", sc->sc_open_count); ++ + return (0); + } + + static int + myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + ++ device_printf(sc->sc_dev, ++ "read: resid=%zu off=%jd\n", ++ (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); ++ + error = myfirst_read_impl(sc, uio); ++ ++ device_printf(sc->sc_dev, "read ok: error=%d\n", error); + return (error); + } + + static int + myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + ++ device_printf(sc->sc_dev, ++ "write: resid=%zu off=%jd\n", ++ (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); ++ + error = myfirst_write_impl(sc, uio); ++ ++ device_printf(sc->sc_dev, "write ok: error=%d\n", error); + return (error); + } diff --git a/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt.patch b/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt.patch new file mode 100644 index 0000000..8bcf167 --- /dev/null +++ b/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt.patch @@ -0,0 +1,72 @@ +--- a/myfirst.c ++++ b/myfirst.c +@@ -1,3 +1,5 @@ ++#include ++ + /* + * myfirst driver - Chapter 23 Stage 2: add SDT probes + */ + ++SDT_PROVIDER_DEFINE(myfirst); ++SDT_PROBE_DEFINE2(myfirst, , , open, ++ "struct myfirst_softc *", "int"); ++SDT_PROBE_DEFINE2(myfirst, , , close, ++ "struct myfirst_softc *", "int"); ++SDT_PROBE_DEFINE4(myfirst, , , io, ++ "struct myfirst_softc *", "int", "size_t", "off_t"); ++ + static int + myfirst_open(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + int error = 0; + + device_printf(sc->sc_dev, + "open entry: pid=%d flags=0x%x\n", + td->td_proc->p_pid, flags); + ++ SDT_PROBE2(myfirst, , , open, sc, flags); ++ + mtx_lock(&sc->sc_mtx); + + static int + myfirst_close(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + + device_printf(sc->sc_dev, + "close entry: pid=%d\n", td->td_proc->p_pid); + ++ SDT_PROBE2(myfirst, , , close, sc, flags); ++ + mtx_lock(&sc->sc_mtx); + + static int + myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + + device_printf(sc->sc_dev, + "read: resid=%zu off=%jd\n", + (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); + ++ SDT_PROBE4(myfirst, , , io, sc, 0, ++ (size_t)uio->uio_resid, uio->uio_offset); ++ + error = myfirst_read_impl(sc, uio); + + static int + myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + + device_printf(sc->sc_dev, + "write: resid=%zu off=%jd\n", + (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); + ++ SDT_PROBE4(myfirst, , , io, sc, 1, ++ (size_t)uio->uio_resid, uio->uio_offset); ++ + error = myfirst_write_impl(sc, uio); diff --git a/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt_demo.d b/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt_demo.d new file mode 100644 index 0000000..5b7b5fe --- /dev/null +++ b/examples/part-05/ch23-debug/stage2-sdt/myfirst_sdt_demo.d @@ -0,0 +1,43 @@ +/* + * myfirst_sdt_demo.d - a small DTrace script that demonstrates attaching + * to the SDT probes in the myfirst driver. + * + * Run with: sudo dtrace -s myfirst_sdt_demo.d + */ + +#pragma D option quiet + +BEGIN +{ + printf("myfirst DTrace demo: counting open, close, and io probes\n"); + printf("press Ctrl-C to stop\n"); +} + +myfirst:::open +{ + @opens[pid] = count(); +} + +myfirst:::close +{ + @closes[pid] = count(); +} + +myfirst:::io +{ + @io_bytes = sum(arg2); + @io_events = count(); +} + +END +{ + printf("\n=== Opens per PID ===\n"); + printa(" pid=%-10d count=%@d\n", @opens); + + printf("\n=== Closes per PID ===\n"); + printa(" pid=%-10d count=%@d\n", @closes); + + printf("\n=== Total I/O ===\n"); + printa(" events=%@d\n", @io_events); + printa(" bytes=%@d\n", @io_bytes); +} diff --git a/examples/part-05/ch23-debug/stage3-refactor/DEBUG.md b/examples/part-05/ch23-debug/stage3-refactor/DEBUG.md new file mode 100644 index 0000000..04f6d3f --- /dev/null +++ b/examples/part-05/ch23-debug/stage3-refactor/DEBUG.md @@ -0,0 +1,137 @@ +# Debug and Tracing Subsystem for the myfirst Driver + +This document describes the debug and tracing infrastructure introduced +in Chapter 23 of *FreeBSD Device Drivers: From First Steps to Kernel +Mastery*. The subsystem covers both human-readable logging (via the +`DPRINTF` macro) and machine-readable events (via SDT probes). + +## Runtime Verbosity: `DPRINTF` + +The driver carries a `sc_debug` field in its softc, a 32-bit bitmask. +Each bit enables a category of log output. The operator sets the mask +at runtime: + +```sh +sysctl dev.myfirst.0.debug.mask=0xFF +``` + +Messages appear in `dmesg` prefixed by the device name, for example: + +``` +myfirst0: open: pid=1234 uid=1001 flags=0x0 +``` + +### Class Bits + +| Bit | Name | Covers | +|--------------|----------------|-------------------------------------------| +| `0x00000001` | `MYF_DBG_INIT` | Probe, attach, detach lifecycle | +| `0x00000002` | `MYF_DBG_OPEN` | open/close calls | +| `0x00000004` | `MYF_DBG_IO` | read/write paths | +| `0x00000008` | `MYF_DBG_IOCTL`| ioctl handling | +| `0x00000010` | `MYF_DBG_INTR` | Interrupt handler | +| `0x00000020` | `MYF_DBG_DMA` | DMA mapping and sync | +| `0x00000040` | `MYF_DBG_PWR` | Power-management events | +| `0x00000080` | `MYF_DBG_MEM` | malloc/free trace | + +### Useful Combinations + +| Command | Effect | +|-------------------------------------------------|----------------------------------| +| `sysctl dev.myfirst.0.debug.mask=0x0` | Disable all debug output. | +| `sysctl dev.myfirst.0.debug.mask=0x3` | Init + open/close lifecycle. | +| `sysctl dev.myfirst.0.debug.mask=0xF` | Init + open/close + I/O + ioctl. | +| `sysctl dev.myfirst.0.debug.mask=0xFFFFFFFF` | All classes. | + +### Cost When Disabled + +A `DPRINTF` call with its bit clear costs one load and one branch, +which compilers typically execute in a single cycle. The cost is +effectively zero in production. + +### Cost When Enabled + +A `DPRINTF` with its bit set is equivalent to a normal `device_printf` +call, which itself is not free: writing to the kernel message buffer +involves a lock and a format operation. The operator should set debug +bits only for the categories they are actively investigating, not as a +long-term production setting. + +## Static Tracing: SDT Probes + +The driver declares three SDT probes: + +| Probe | Fires on | Arguments | +|--------------------------|------------------------|-----------------------------------------------| +| `myfirst:::open` | Every device open | arg0 = softc*, arg1 = flags | +| `myfirst:::close` | Every device close | arg0 = softc*, arg1 = flags | +| `myfirst:::io` | Every read or write | arg0 = softc*, arg1 = is_write, arg2 = resid, arg3 = off | + +When no DTrace script has attached to a probe, the probe is a no-op, +and the runtime cost is negligible. + +### Listing the Probes + +```sh +sudo dtrace -l -P myfirst +``` + +### Example One-Liners + +```sh +# Count every event, grouped by probe name, for 10 seconds +sudo dtrace -n 'myfirst::: { @[probename] = count(); } + tick-10s { exit(0); }' + +# Show each open with the pid and flags +sudo dtrace -n 'myfirst:::open { printf("open pid=%d flags=0x%x", + pid, arg1); }' + +# Aggregate I/O sizes +sudo dtrace -n 'myfirst:::io { @ = quantize(arg2); }' + +# Measure latency between open and close per pid +sudo dtrace -n ' +myfirst:::open { self->t = timestamp; } +myfirst:::close /self->t/ { + @[pid] = quantize(timestamp - self->t); self->t = 0; +}' +``` + +## Combined Debug Workflow + +The two systems complement one another. A typical debug session: + +1. Set the debug mask to a broad value to see events in `dmesg`: + ```sh + sudo sysctl dev.myfirst.0.debug.mask=0x7 + ``` +2. Reproduce the problem. +3. Inspect `dmesg | tail -200` to see the event flow. +4. Attach a DTrace script to quantify frequencies or timings. +5. Disable the debug mask when the diagnosis is complete: + ```sh + sudo sysctl dev.myfirst.0.debug.mask=0 + ``` + +## Extending the Subsystem + +To add a new class, edit `myfirst_debug.h`: + +1. Define the new constant, using the next unused bit. +2. Update this document's table. +3. Use the new class in `DPRINTF` calls throughout the driver. + +To add a new SDT probe: + +1. Declare the probe in `myfirst_debug.h` with `SDT_PROBE_DECLARE`. +2. Define the probe in `myfirst_debug.c` with `SDT_PROBE_DEFINEn`. +3. Fire the probe in the driver source with `SDT_PROBEn(...)`. + +Both extensions are additive; existing users of the driver see no +difference until they choose to attach scripts or enable mask bits. + +## Version + +This infrastructure was introduced in the `1.6-debug` release of the +driver. diff --git a/examples/part-05/ch23-debug/stage3-refactor/Makefile b/examples/part-05/ch23-debug/stage3-refactor/Makefile new file mode 100644 index 0000000..7fc945b --- /dev/null +++ b/examples/part-05/ch23-debug/stage3-refactor/Makefile @@ -0,0 +1,16 @@ +# Makefile for the myfirst driver - Chapter 23 Stage 3 (1.6-debug) +# +# Builds the kernel module with the debug and SDT infrastructure +# introduced in Chapter 23. + +KMOD= myfirst +SRCS= myfirst.c myfirst_debug.c + +# Include current directory for the myfirst_debug.h header. +CFLAGS+= -I${.CURDIR} + +# Build against the running kernel's sources. Adjust if the kernel +# source is in a non-default location. +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.c b/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.c new file mode 100644 index 0000000..d635892 --- /dev/null +++ b/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.c @@ -0,0 +1,44 @@ +/* + * myfirst_debug.c - storage for the SDT probe entries. + * + * This file holds the SDT_PROVIDER_DEFINE and SDT_PROBE_DEFINE + * declarations. By convention in the myfirst driver, these live in a + * dedicated source file to keep the main driver uncluttered. + */ + +#include +#include +#include +#include "myfirst_debug.h" + +/* + * The provider "myfirst" exposes all of our static probes to DTrace. + * Scripts select probes with "myfirst:::". + */ +SDT_PROVIDER_DEFINE(myfirst); + +/* + * open: fired on every device open. + * arg0 = struct myfirst_softc * + * arg1 = int flags from the open call + */ +SDT_PROBE_DEFINE2(myfirst, , , open, + "struct myfirst_softc *", "int"); + +/* + * close: fired on every device close. + * arg0 = struct myfirst_softc * + * arg1 = int flags + */ +SDT_PROBE_DEFINE2(myfirst, , , close, + "struct myfirst_softc *", "int"); + +/* + * io: fired on every read or write call, at function entry. + * arg0 = struct myfirst_softc * + * arg1 = int is_write (0 for read, 1 for write) + * arg2 = size_t resid (bytes requested) + * arg3 = off_t offset + */ +SDT_PROBE_DEFINE4(myfirst, , , io, + "struct myfirst_softc *", "int", "size_t", "off_t"); diff --git a/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.h b/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.h new file mode 100644 index 0000000..711856e --- /dev/null +++ b/examples/part-05/ch23-debug/stage3-refactor/myfirst_debug.h @@ -0,0 +1,72 @@ +/* + * myfirst_debug.h - debug and tracing infrastructure for the myfirst driver + * + * This header is included from the driver's source files. It provides: + * - a bitmask of debug verbosity classes + * - the DPRINTF macro for conditional device_printf + * - declarations for SDT probes that the driver fires at key points + * + * The matching SDT_PROVIDER_DEFINE and SDT_PROBE_DEFINE calls live in + * myfirst_debug.c, which owns the storage for the probe entries. + */ + +#ifndef _MYFIRST_DEBUG_H_ +#define _MYFIRST_DEBUG_H_ + +#include +#include +#include + +/* + * Debug verbosity classes. Each class is a single bit in sc->sc_debug. + * The operator sets sysctl dev.myfirst.0.debug.mask to a combination of + * these bits to enable the corresponding categories of output. + * + * Add new classes here when the driver grows new subsystems. Use the + * next unused bit and update DEBUG.md accordingly. + */ +#define MYF_DBG_INIT 0x00000001 /* probe/attach/detach */ +#define MYF_DBG_OPEN 0x00000002 /* open/close lifecycle */ +#define MYF_DBG_IO 0x00000004 /* read/write paths */ +#define MYF_DBG_IOCTL 0x00000008 /* ioctl handling */ +#define MYF_DBG_INTR 0x00000010 /* interrupt handler */ +#define MYF_DBG_DMA 0x00000020 /* DMA mapping/sync */ +#define MYF_DBG_PWR 0x00000040 /* power-management events */ +#define MYF_DBG_MEM 0x00000080 /* malloc/free trace */ +/* Bits 0x0100..0x8000 reserved for future driver subsystems */ + +#define MYF_DBG_ANY 0xFFFFFFFF +#define MYF_DBG_NONE 0x00000000 + +/* + * DPRINTF - conditionally log a message via device_printf when the + * given class bit is set in the softc's debug mask. + * + * Usage: DPRINTF(sc, MYF_DBG_OPEN, "open: pid=%d\n", pid); + * + * When the bit is clear, the cost is one load and one branch, which is + * negligible in practice. When the bit is set, the cost equals a + * normal device_printf call. + */ +#ifdef _KERNEL +#define DPRINTF(sc, m, ...) do { \ + if ((sc)->sc_debug & (m)) \ + device_printf((sc)->sc_dev, __VA_ARGS__); \ +} while (0) +#endif + +/* + * SDT probe declarations. The matching SDT_PROBE_DEFINE calls are in + * myfirst_debug.c. + * + * Probe argument conventions: + * open (softc *, flags) -- entry, before access check + * close (softc *, flags) -- entry, before state update + * io (softc *, is_write, resid, off) -- entry, into read or write + */ +SDT_PROVIDER_DECLARE(myfirst); +SDT_PROBE_DECLARE(myfirst, , , open); +SDT_PROBE_DECLARE(myfirst, , , close); +SDT_PROBE_DECLARE(myfirst, , , io); + +#endif /* _MYFIRST_DEBUG_H_ */ diff --git a/examples/part-05/ch23-debug/stage3-refactor/refactor.patch b/examples/part-05/ch23-debug/stage3-refactor/refactor.patch new file mode 100644 index 0000000..4f2aedb --- /dev/null +++ b/examples/part-05/ch23-debug/stage3-refactor/refactor.patch @@ -0,0 +1,172 @@ +--- a/myfirst.c ++++ b/myfirst.c +@@ -1,10 +1,20 @@ + /* +- * myfirst driver - Chapter 23 Stage 2: SDT probes added ++ * myfirst driver - version 1.6-debug ++ * ++ * Added in this revision: ++ * - DPRINTF macro with 8 verbosity classes ++ * - sysctl dev.myfirst.0.debug.mask for runtime control ++ * - SDT probes for open, close, io (carried over from Stage 2) ++ * - Entry/exit/error pattern across all methods + */ + +-#include ++#include "myfirst_debug.h" + +-/* SDT provider and probes now live in myfirst_debug.c */ ++static const char myfirst_version[] = "myfirst 1.6-debug"; + + struct myfirst_softc { + device_t sc_dev; + struct mtx sc_mtx; + struct cdev *sc_cdev; ++ uint32_t sc_debug; /* debug class bitmask */ ++ struct sysctl_ctx_list sc_sysctl_ctx; ++ struct sysctl_oid *sc_sysctl_tree; + /* ... other fields ... */ + }; + +@@ -60,25 +70,38 @@ + static int + myfirst_attach(device_t dev) + { + struct myfirst_softc *sc = device_get_softc(dev); + + sc->sc_dev = dev; ++ sc->sc_debug = 0; + mtx_init(&sc->sc_mtx, "myfirst", NULL, MTX_DEF); + ++ DPRINTF(sc, MYF_DBG_INIT, "attach: %s loaded\n", myfirst_version); ++ ++ sysctl_ctx_init(&sc->sc_sysctl_ctx); ++ sc->sc_sysctl_tree = SYSCTL_ADD_NODE(&sc->sc_sysctl_ctx, ++ SYSCTL_CHILDREN(device_get_sysctl_tree(sc->sc_dev)), ++ OID_AUTO, "debug", ++ CTLFLAG_RW, 0, "debug and tracing controls"); ++ SYSCTL_ADD_U32(&sc->sc_sysctl_ctx, ++ SYSCTL_CHILDREN(sc->sc_sysctl_tree), ++ OID_AUTO, "mask", ++ CTLFLAG_RW, &sc->sc_debug, 0, ++ "debug class bitmask (see myfirst_debug.h)"); ++ + /* ... cdev create, resource allocation, etc. ... */ + + return (0); + } + +@@ -100,6 +123,8 @@ + static int + myfirst_detach(device_t dev) + { + struct myfirst_softc *sc = device_get_softc(dev); + ++ DPRINTF(sc, MYF_DBG_INIT, "detach entry\n"); ++ sysctl_ctx_free(&sc->sc_sysctl_ctx); + destroy_dev(sc->sc_cdev); + mtx_destroy(&sc->sc_mtx); + return (0); + } + +@@ -130,9 +155,13 @@ + static int + myfirst_open(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + int error = 0; + +- device_printf(sc->sc_dev, "open entry: pid=%d flags=0x%x\n", ++ DPRINTF(sc, MYF_DBG_OPEN, "open: pid=%d uid=%d flags=0x%x\n", +- td->td_proc->p_pid, flags); ++ td->td_proc->p_pid, td->td_ucred->cr_uid, flags); + + SDT_PROBE2(myfirst, , , open, sc, flags); + +@@ -145,17 +174,20 @@ + out: + mtx_unlock(&sc->sc_mtx); + +- device_printf(sc->sc_dev, "open ok: count=%d\n", sc->sc_open_count); ++ if (error != 0) ++ DPRINTF(sc, MYF_DBG_OPEN, "open failed: error=%d\n", error); ++ else ++ DPRINTF(sc, MYF_DBG_OPEN, "open ok: count=%d\n", ++ sc->sc_open_count); + + return (error); + } + + static int + myfirst_close(struct cdev *dev, int flags, int devtype, struct thread *td) + { + struct myfirst_softc *sc = dev->si_drv1; + +- device_printf(sc->sc_dev, "close entry: pid=%d\n", ++ DPRINTF(sc, MYF_DBG_OPEN, "close: pid=%d flags=0x%x\n", +- td->td_proc->p_pid); ++ td->td_proc->p_pid, flags); + + SDT_PROBE2(myfirst, , , close, sc, flags); + +@@ -164,7 +196,7 @@ + if (sc->sc_open_count > 0) + sc->sc_open_count--; ++ DPRINTF(sc, MYF_DBG_OPEN, "close ok: count=%d\n", sc->sc_open_count); + mtx_unlock(&sc->sc_mtx); + +- device_printf(sc->sc_dev, "close ok: count=%d\n", sc->sc_open_count); + return (0); + } + +@@ -172,18 +204,20 @@ + static int + myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + +- device_printf(sc->sc_dev, "read: resid=%zu off=%jd\n", ++ DPRINTF(sc, MYF_DBG_IO, "read: pid=%d resid=%zu off=%jd\n", +- (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); ++ curthread->td_proc->p_pid, ++ (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); + + SDT_PROBE4(myfirst, , , io, sc, 0, + (size_t)uio->uio_resid, uio->uio_offset); + + error = myfirst_read_impl(sc, uio); + +- device_printf(sc->sc_dev, "read ok: error=%d\n", error); ++ if (error != 0) ++ DPRINTF(sc, MYF_DBG_IO, "read failed: error=%d\n", error); + return (error); + } + +@@ -191,14 +225,16 @@ + static int + myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) + { + struct myfirst_softc *sc = dev->si_drv1; + int error; + +- device_printf(sc->sc_dev, "write: resid=%zu off=%jd\n", ++ DPRINTF(sc, MYF_DBG_IO, "write: pid=%d resid=%zu off=%jd\n", +- (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); ++ curthread->td_proc->p_pid, ++ (size_t)uio->uio_resid, (intmax_t)uio->uio_offset); + + SDT_PROBE4(myfirst, , , io, sc, 1, + (size_t)uio->uio_resid, uio->uio_offset); + + error = myfirst_write_impl(sc, uio); + +- device_printf(sc->sc_dev, "write ok: error=%d\n", error); ++ if (error != 0) ++ DPRINTF(sc, MYF_DBG_IO, "write failed: error=%d\n", error); + return (error); + } + +@@ -230,4 +266,4 @@ +-MODULE_VERSION(myfirst, 15); ++MODULE_VERSION(myfirst, 16); diff --git a/examples/part-05/ch24-integration/INTEGRATION.md b/examples/part-05/ch24-integration/INTEGRATION.md new file mode 100644 index 0000000..2f0b14b --- /dev/null +++ b/examples/part-05/ch24-integration/INTEGRATION.md @@ -0,0 +1,87 @@ +# Chapter 24 Integration Concept Map + +This document maps every concept introduced in Chapter 24 to the file +under this directory where the concept first appears. Use it as a +lookup table when working through the chapter. + +## Section 1: Why Integration Matters + +Conceptual material only; no code in this stage. The chapter explains +the difference between a working module and an integrated driver. + +## Section 2: Working With devfs and the Device Tree + +| Concept | File | +|---------|------| +| `make_dev_args_init` and `make_dev_s` | `stage1-devfs/myfirst.c` (in `myfirst_attach`) | +| `D_TRACKCLOSE` flag | `stage1-devfs/myfirst.c` (in `myfirst_cdevsw`) | +| `si_drv1` per-cdev state | `stage1-devfs/myfirst.c` (set in `mda_si_drv1`, read in cdevsw callbacks) | +| `destroy_dev` drain semantics | `stage1-devfs/myfirst.c` (in `myfirst_detach`) | + +## Section 3: Implementing ioctl() Support + +| Concept | File | +|---------|------| +| `_IO`, `_IOR`, `_IOW`, `_IOWR` macros | `stage2-ioctl/myfirst_ioctl.h` | +| Group letter `'M'` choice | `stage2-ioctl/myfirst_ioctl.h` | +| Public header convention | `stage2-ioctl/myfirst_ioctl.h` (no kernel-only headers included) | +| `d_ioctl` callback | `stage2-ioctl/myfirst_ioctl.c` (function `myfirst_ioctl`) | +| `ENOIOCTL` for unknown commands | `stage2-ioctl/myfirst_ioctl.c` (default branch) | +| `fflag & FWRITE` check | `stage2-ioctl/myfirst_ioctl.c` (in `MYFIRSTIOC_SETMSG` and `MYFIRSTIOC_RESET`) | +| User-space companion | `stage2-ioctl/myfirstctl.c` | +| Build of the companion | `stage2-ioctl/Makefile.user` | + +## Section 4: Exposing Metrics Through sysctl() + +| Concept | File | +|---------|------| +| Per-device sysctl context | `stage3-sysctl/myfirst_sysctl.c` (function `myfirst_sysctl_attach`) | +| `SYSCTL_ADD_UINT` for counters | `stage3-sysctl/myfirst_sysctl.c` (open_count, total_reads, total_writes) | +| `SYSCTL_ADD_STRING` for version | `stage3-sysctl/myfirst_sysctl.c` (version, message, debug.classes) | +| `SYSCTL_ADD_PROC` with handler | `stage3-sysctl/myfirst_sysctl.c` (message_len) | +| `SYSCTL_ADD_NODE` for subtree | `stage3-sysctl/myfirst_sysctl.c` (debug subtree) | +| `CTLFLAG_RW \| CTLFLAG_TUN` | `stage3-sysctl/myfirst_sysctl.c` (debug.mask OID) | +| `TUNABLE_INT_FETCH` | `stage3-sysctl/myfirst.c` (in `myfirst_attach`, before the sysctl call) | +| `/boot/loader.conf` example | `labs/loader.conf.example` | + +## Section 5: Networking Integration (Optional) + +No code in this directory. The chapter cites +`/usr/src/sys/net/if_disc.c` as the canonical example of `if_alloc`, +`if_attach`, and `bpfattach`. + +## Section 6: CAM Storage Integration (Optional) + +No code in this directory. The chapter cites +`/usr/src/sys/dev/ahci/ahci.c` as the canonical example of +`cam_sim_alloc`, `xpt_bus_register`, and the action callback. + +## Section 7: Registration, Teardown, Cleanup Discipline + +| Concept | File | +|---------|------| +| `goto err` chain in attach | `stage3-sysctl/myfirst.c` (in `myfirst_attach`) | +| Reverse-order teardown | `stage3-sysctl/myfirst.c` (in `myfirst_detach`) | +| Soft refusal on open count | `stage3-sysctl/myfirst.c` (early `EBUSY` return) | + +## Section 8: Refactoring and Versioning + +| Concept | File | +|---------|------| +| Source-tree split by concern | All `stage3-sysctl/` files | +| Public vs private headers | `stage2-ioctl/myfirst_ioctl.h` is public; everything else is private | +| `MYFIRST_VERSION` release string | `stage3-sysctl/myfirst_sysctl.c` | +| `MODULE_VERSION` integer | `stage3-sysctl/myfirst.c` | +| `MYFIRST_IOCTL_VERSION` API integer | `stage2-ioctl/myfirst_ioctl.h` | + +## Section 9: Hands-on Labs + +| Lab | Script | +|-----|--------| +| Lab 24.1 (build stage 1) | `labs/lab24_1_stage1.sh` | +| Lab 24.2 (add ioctls) | `labs/lab24_2_stage2.sh` | +| Lab 24.3 (add sysctl) | `labs/lab24_3_stage3.sh` | +| Lab 24.4 (inject failure) | `labs/lab24_4_failure.sh` | +| Lab 24.5 (DTrace traces) | `labs/lab24_5_dtrace.sh` | +| Lab 24.6 (smoke test) | `labs/lab24_6_smoke.sh` | +| Lab 24.7 (reload test) | `labs/lab24_7_reload.sh` | diff --git a/examples/part-05/ch24-integration/labs/lab24_1_stage1.sh b/examples/part-05/ch24-integration/labs/lab24_1_stage1.sh new file mode 100755 index 0000000..d2c2c0e --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_1_stage1.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# +# lab24_1_stage1.sh - Build and load the Stage 1 myfirst driver. +# +# Lab 24.1: bring the driver from the Chapter 23 baseline (1.6-debug) +# up to the Stage 1 milestone of Chapter 24 (a properly constructed +# cdev under /dev/myfirst0). +# +# This script does not modify the driver source. Apply the Stage 1 +# changes from examples/part-05/ch24-integration/stage1-devfs/myfirst.c +# to your working tree before running it. + +set -e + +WORKDIR=${WORKDIR:-${HOME}/myfirst-lab1} + +echo "=== Lab 24.1: Stage 1 build and load ===" +echo "Working directory: ${WORKDIR}" + +if [ ! -d "${WORKDIR}" ]; then + echo "ERROR: ${WORKDIR} does not exist." + echo "Copy your Chapter 23 Stage 3 driver tree into ${WORKDIR}" + echo "and apply the Stage 1 changes from" + echo "examples/part-05/ch24-integration/stage1-devfs/ first." + exit 1 +fi + +cd "${WORKDIR}" + +echo +echo "--- make ---" +make clean +make + +echo +echo "--- kldload ---" +sudo kldload ./myfirst.ko + +echo +echo "--- expected: device node exists with mode 0660 ---" +ls -l /dev/myfirst0 + +echo +echo "--- expected: cat returns the default greeting ---" +sudo cat /dev/myfirst0 + +echo +echo "--- expected: kldstat shows the loaded module ---" +kldstat | grep myfirst || true + +echo +echo "--- recent dmesg from the driver ---" +sudo dmesg | tail + +echo +echo "Stage 1 verification PASSED if the device exists, the cat" +echo "returned the greeting, and kldstat shows myfirst.ko." +echo +echo "To clean up: sudo kldunload myfirst" diff --git a/examples/part-05/ch24-integration/labs/lab24_2_stage2.sh b/examples/part-05/ch24-integration/labs/lab24_2_stage2.sh new file mode 100755 index 0000000..c5da6dd --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_2_stage2.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# +# lab24_2_stage2.sh - Add the ioctl interface to the myfirst driver. +# +# Lab 24.2: extend the Stage 1 driver with the four ioctl commands +# (GETVER, GETMSG, SETMSG, RESET) and the user-space companion +# myfirstctl(8). +# +# Before running this script, copy the following files from +# examples/part-05/ch24-integration/stage2-ioctl/ into your working +# tree: +# - myfirst_ioctl.h +# - myfirst_ioctl.c +# - myfirstctl.c +# - Makefile (replaces the Stage 1 Makefile) +# - Makefile.user + +set -e + +WORKDIR=${WORKDIR:-${HOME}/myfirst-lab2} + +echo "=== Lab 24.2: Stage 2 ioctl interface ===" +echo "Working directory: ${WORKDIR}" + +if [ ! -d "${WORKDIR}" ]; then + echo "ERROR: ${WORKDIR} does not exist." + echo "Copy your Stage 1 driver tree into ${WORKDIR} and apply" + echo "the Stage 2 changes first." + exit 1 +fi + +cd "${WORKDIR}" + +echo +echo "--- make (kernel module) ---" +make clean +make + +echo +echo "--- make (user-space companion) ---" +make -f Makefile.user clean || true +make -f Makefile.user + +echo +echo "--- kldload ---" +sudo kldload ./myfirst.ko + +echo +echo "--- expected: ioctl version is 1 ---" +./myfirstctl get-version + +echo +echo "--- expected: default greeting ---" +./myfirstctl get-message + +echo +echo "--- set, get, reset round-trip ---" +sudo ./myfirstctl set-message "drivers are fun" +./myfirstctl get-message +sudo ./myfirstctl reset +./myfirstctl get-message +echo "(an empty line above means the message buffer is cleared)" + +echo +echo "Stage 2 verification PASSED if all four ioctls returned" +echo "without errors and the round-trip showed the new message." +echo +echo "To clean up: sudo kldunload myfirst" diff --git a/examples/part-05/ch24-integration/labs/lab24_3_stage3.sh b/examples/part-05/ch24-integration/labs/lab24_3_stage3.sh new file mode 100755 index 0000000..94129e7 --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_3_stage3.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# +# lab24_3_stage3.sh - Add the sysctl tree and loader-time tunable. +# +# Lab 24.3: extend the Stage 2 driver with the sysctl OIDs from +# Chapter 24 Section 4 and read a tunable from the loader environment. +# +# Before running this script, copy the following files from +# examples/part-05/ch24-integration/stage3-sysctl/ into your working +# tree: +# - myfirst_sysctl.c +# - myfirst.c (replaces the Stage 2 attach/detach) +# - Makefile (replaces the Stage 2 Makefile) + +set -e + +WORKDIR=${WORKDIR:-${HOME}/myfirst-lab3} + +echo "=== Lab 24.3: Stage 3 sysctl tree ===" +echo "Working directory: ${WORKDIR}" + +if [ ! -d "${WORKDIR}" ]; then + echo "ERROR: ${WORKDIR} does not exist." + echo "Copy your Stage 2 driver tree into ${WORKDIR} and apply" + echo "the Stage 3 changes first." + exit 1 +fi + +cd "${WORKDIR}" + +echo +echo "--- make ---" +make clean +make + +echo +echo "--- set the loader-time tunable before load ---" +sudo kenv hw.myfirst.debug_mask_default=0x06 + +echo +echo "--- kldload ---" +sudo kldload ./myfirst.ko + +echo +echo "--- expected: full sysctl tree below dev.myfirst.0 ---" +sysctl -a dev.myfirst.0 + +echo +echo "--- expected: debug.mask reflects the tunable (0x06 = 6) ---" +sysctl dev.myfirst.0.debug.mask + +echo +echo "--- drive a read and check the counter increments ---" +sudo cat /dev/myfirst0 > /dev/null +sysctl dev.myfirst.0.total_reads + +echo +echo "Stage 3 verification PASSED if the sysctl tree showed all OIDs," +echo "debug.mask was 6, and total_reads incremented after the cat." +echo +echo "To clean up: sudo kldunload myfirst" +echo "To remove the tunable: sudo kenv -u hw.myfirst.debug_mask_default" diff --git a/examples/part-05/ch24-integration/labs/lab24_4_failure.sh b/examples/part-05/ch24-integration/labs/lab24_4_failure.sh new file mode 100755 index 0000000..831066f --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_4_failure.sh @@ -0,0 +1,74 @@ +#!/bin/sh +# +# lab24_4_failure.sh - Walk the lifecycle by injecting a failure. +# +# Lab 24.4: verify that the goto err chain in myfirst_attach actually +# unwinds by deliberately failing one of the steps. This script does +# not edit the driver for you; it documents the change and runs the +# load attempt that should fail cleanly. +# +# To prepare: +# 1. Copy your Stage 3 driver into ${WORKDIR} (default: ~/myfirst-lab4). +# 2. Edit myfirst.c. After the make_dev_s success path, insert: +# +# device_printf(dev, "Lab 4: injected failure after make_dev_s\n"); +# error = ENXIO; +# goto fail_cdev; +# +# Add the matching label and destroy_dev call to the failure tail +# of myfirst_attach. + +set -e + +WORKDIR=${WORKDIR:-${HOME}/myfirst-lab4} + +echo "=== Lab 24.4: failure injection ===" +echo "Working directory: ${WORKDIR}" + +if [ ! -d "${WORKDIR}" ]; then + echo "ERROR: ${WORKDIR} does not exist." + echo "Copy your Stage 3 driver tree into ${WORKDIR} and inject" + echo "the deliberate failure as documented above." + exit 1 +fi + +cd "${WORKDIR}" + +echo +echo "--- make ---" +make clean +make + +echo +echo "--- kldload should FAIL because of the injected ENXIO ---" +if sudo kldload ./myfirst.ko; then + echo "WARNING: load succeeded; did you forget the injected failure?" + sudo kldunload myfirst + exit 1 +fi +echo "kldload returned an error as expected." + +echo +echo "--- expected: device node was destroyed by the cleanup chain ---" +if [ -e /dev/myfirst0 ]; then + echo "FAIL: /dev/myfirst0 still exists; cleanup chain missed destroy_dev." + exit 1 +fi +echo "/dev/myfirst0 is absent." + +echo +echo "--- expected: module is not loaded ---" +if kldstat | grep -q myfirst; then + echo "FAIL: myfirst still listed in kldstat." + exit 1 +fi +echo "myfirst is not in kldstat." + +echo +echo "--- recent dmesg, including the injected message ---" +sudo dmesg | tail + +echo +echo "Lab 24.4 PASSED. The cleanup chain unwound correctly: the" +echo "cdev was destroyed, the mutex was destroyed, no resources" +echo "leaked. Remove the injected failure before continuing." diff --git a/examples/part-05/ch24-integration/labs/lab24_5_dtrace.sh b/examples/part-05/ch24-integration/labs/lab24_5_dtrace.sh new file mode 100755 index 0000000..0cbcdb5 --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_5_dtrace.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# +# lab24_5_dtrace.sh - Trace the integration surfaces with DTrace. +# +# Lab 24.5: use the SDT probes from Chapter 23 (open, close, io) and +# the Chapter 24 ioctl probe to watch driver traffic in real time. +# +# Run with the Stage 3 driver loaded. The script starts a DTrace +# session in the foreground; press Ctrl-C to stop. + +set -e + +DEV=${DEV:-/dev/myfirst0} + +echo "=== Lab 24.5: DTrace integration trace ===" + +if [ ! -c "${DEV}" ]; then + echo "ERROR: ${DEV} does not exist. Load the Stage 3 driver first." + exit 1 +fi + +echo +echo "--- registered myfirst SDT probes ---" +sudo dtrace -l -P myfirst + +echo +echo "--- starting trace (Ctrl-C to stop) ---" +echo "In another terminal, exercise the driver, e.g.:" +echo " cat /dev/myfirst0" +echo " ./myfirstctl get-version" +echo " sudo ./myfirstctl set-message 'hello DTrace'" +echo " sudo ./myfirstctl reset" +echo + +sudo dtrace -n ' + myfirst:::open { printf("open pid=%d", pid); } + myfirst:::close { printf("close pid=%d", pid); } + myfirst:::io { printf("io pid=%d write=%d resid=%d", pid, arg1, arg2); } + myfirst:::ioctl { printf("ioctl pid=%d cmd=0x%x", pid, arg1); } +' diff --git a/examples/part-05/ch24-integration/labs/lab24_6_smoke.sh b/examples/part-05/ch24-integration/labs/lab24_6_smoke.sh new file mode 100755 index 0000000..0e3ff1e --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_6_smoke.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# +# lab24_6_smoke.sh - End-to-end smoke test for the myfirst driver. +# +# Lab 24.6: run a single shell script that exercises every +# integration surface and prints a green/red summary. Run with the +# Stage 3 driver loaded and ./myfirstctl built in the working dir. +# +# Exit code is 0 if every check passed and non-zero otherwise. + +set -u +fail=0 + +check() { + if eval "$1" >/dev/null 2>&1; then + printf " PASS %s\n" "$2" + else + printf " FAIL %s\n" "$2" + fail=$((fail + 1)) + fi +} + +echo "=== myfirst integration smoke test ===" + +# 1. Module is loaded. +check "kldstat | grep -q myfirst" "module is loaded" + +# 2. /dev node exists with the right mode. +check "test -c /dev/myfirst0" "/dev/myfirst0 exists as a character device" +check "test \"\$(stat -f %Lp /dev/myfirst0)\" = \"660\"" "/dev/myfirst0 is mode 0660" + +# 3. Sysctl tree is present. +check "sysctl -N dev.myfirst.0.version" "version OID is present" +check "sysctl -N dev.myfirst.0.debug.mask" "debug.mask OID is present" +check "sysctl -N dev.myfirst.0.open_count" "open_count OID is present" + +# 4. Ioctls work (requires myfirstctl built in CWD). +check "./myfirstctl get-version" "MYFIRSTIOC_GETVER returns success" +check "./myfirstctl get-message" "MYFIRSTIOC_GETMSG returns success" +check "sudo ./myfirstctl set-message smoke && [ \"\$(./myfirstctl get-message)\" = smoke ]" "MYFIRSTIOC_SETMSG round-trip works" +check "sudo ./myfirstctl reset && [ -z \"\$(./myfirstctl get-message)\" ]" "MYFIRSTIOC_RESET clears state" + +# 5. Read/write basic path. +check "echo hello | sudo tee /dev/myfirst0" "write to /dev/myfirst0 succeeds" +check "[ \"\$(cat /dev/myfirst0)\" = hello ]" "read returns the previously written message" + +# 6. Counters update. +sudo ./myfirstctl reset >/dev/null +cat /dev/myfirst0 >/dev/null +check "[ \"\$(sysctl -n dev.myfirst.0.total_reads)\" = 1 ]" "total_reads incremented after one read" + +# 7. SDT probes are registered. +check "sudo dtrace -l -P myfirst | grep -q open" "myfirst:::open SDT probe is visible" + +echo "=== summary ===" +if [ $fail -eq 0 ]; then + echo "ALL PASS" + exit 0 +else + printf "%d FAIL\n" "$fail" + exit 1 +fi diff --git a/examples/part-05/ch24-integration/labs/lab24_7_reload.sh b/examples/part-05/ch24-integration/labs/lab24_7_reload.sh new file mode 100755 index 0000000..1e95513 --- /dev/null +++ b/examples/part-05/ch24-integration/labs/lab24_7_reload.sh @@ -0,0 +1,72 @@ +#!/bin/sh +# +# lab24_7_reload.sh - Reload without restarting user-space programs. +# +# Lab 24.7: confirm that the driver's soft-detach pattern correctly +# refuses unload while a user-space program holds the device open, +# and that the unload succeeds once the file descriptor is released. +# +# Run with the Stage 3 driver loaded. The script forks a sleep +# process that holds /dev/myfirst0 open, attempts an unload (which +# must fail), kills the holder, then attempts the unload again +# (which must succeed). + +set -e + +DEV=${DEV:-/dev/myfirst0} + +echo "=== Lab 24.7: soft-detach / reload test ===" + +if [ ! -c "${DEV}" ]; then + echo "ERROR: ${DEV} does not exist. Load the Stage 3 driver first." + exit 1 +fi + +echo +echo "--- holding ${DEV} open in the background ---" +sleep 30 < "${DEV}" & +HOLDER=$! +sleep 1 +echo "holder pid: ${HOLDER}" + +echo +echo "--- expected: kldunload should FAIL with Device busy ---" +if sudo kldunload myfirst 2>&1 | grep -q "Device busy"; then + echo "PASS: unload was correctly refused while ${DEV} was open." +else + echo "FAIL: unload was not refused." + kill ${HOLDER} 2>/dev/null || true + exit 1 +fi + +echo +echo "--- open_count reflects the held fd ---" +sysctl dev.myfirst.0.open_count + +echo +echo "--- releasing the holder ---" +kill ${HOLDER} +wait ${HOLDER} 2>/dev/null || true +sleep 1 + +echo +echo "--- expected: kldunload should SUCCEED now ---" +if sudo kldunload myfirst; then + echo "PASS: unload succeeded after the fd was released." +else + echo "FAIL: unload still failed." + exit 1 +fi + +echo +echo "--- expected: sysctl tree is gone ---" +if sysctl dev.myfirst.0 >/dev/null 2>&1; then + echo "FAIL: dev.myfirst.0 still present after unload." + exit 1 +fi +echo "PASS: sysctl tree was removed by Newbus after detach." + +echo +echo "Lab 24.7 PASSED. The soft-detach contract is honoured: the" +echo "driver refused to unload while open, and unloaded cleanly" +echo "once the fd was released." diff --git a/examples/part-05/ch24-integration/labs/loader.conf.example b/examples/part-05/ch24-integration/labs/loader.conf.example new file mode 100644 index 0000000..47b5c58 --- /dev/null +++ b/examples/part-05/ch24-integration/labs/loader.conf.example @@ -0,0 +1,23 @@ +# /boot/loader.conf snippet for the Chapter 24 myfirst driver. +# +# Append the lines below to /boot/loader.conf to load myfirst +# automatically at boot and to set its initial debug mask. + +# Load the module on boot. +myfirst_load="YES" + +# Initial debug mask, applied before the dev.myfirst..debug.mask +# sysctl OID becomes accessible. The bit values are documented in +# myfirst_debug.h: +# +# MYF_DBG_INIT 0x01 probe/attach/detach +# MYF_DBG_OPEN 0x02 open/close lifecycle +# MYF_DBG_IO 0x04 read/write paths +# MYF_DBG_IOCTL 0x08 ioctl handling +# MYF_DBG_INTR 0x10 interrupt handler +# MYF_DBG_DMA 0x20 DMA mapping/sync +# MYF_DBG_PWR 0x40 power-management events +# MYF_DBG_MEM 0x80 malloc/free trace +# +# 0x06 enables OPEN and IO; 0xff enables every defined class. +hw.myfirst.debug_mask_default="0x06" diff --git a/examples/part-05/ch24-integration/stage1-devfs/Makefile b/examples/part-05/ch24-integration/stage1-devfs/Makefile new file mode 100644 index 0000000..5442fc2 --- /dev/null +++ b/examples/part-05/ch24-integration/stage1-devfs/Makefile @@ -0,0 +1,14 @@ +# Makefile for the myfirst driver - Chapter 24 Stage 1 (1.6-debug). +# +# Stage 1 modernises the cdev construction path but does not yet add +# the ioctl or sysctl source files. The build is identical to the +# Chapter 23 Stage 3 build. + +KMOD= myfirst +SRCS= myfirst.c myfirst_debug.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-05/ch24-integration/stage1-devfs/myfirst.c b/examples/part-05/ch24-integration/stage1-devfs/myfirst.c new file mode 100644 index 0000000..7675a3c --- /dev/null +++ b/examples/part-05/ch24-integration/stage1-devfs/myfirst.c @@ -0,0 +1,169 @@ +/* + * myfirst.c - Chapter 24 Stage 1: modernised cdev construction. + * + * This stage takes the Chapter 23 Stage 3 driver (version 1.6-debug) + * and converts the cdev creation path from the old ad-hoc make_dev() + * pattern to the modern make_dev_args / make_dev_s pattern. The + * cdevsw gains the D_TRACKCLOSE flag so close fires once per last fd. + * The mda_si_drv1 field wires the per-cdev pointer to the softc + * atomically, closing the race between cdev creation and assignment. + * + * No version bump in this stage; the driver remains at 1.6-debug. + * The version bump happens in Stage 2 when the ioctl interface is + * introduced. + * + * This file shows only the pieces that change in Stage 1. Merge the + * excerpts below into the corresponding locations in your Chapter 23 + * Stage 3 myfirst.c. The full driver is reconstructed in Stage 3. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" + +/* Forward declarations of cdevsw callbacks. */ +static d_open_t myfirst_open; +static d_close_t myfirst_close; +static d_read_t myfirst_read; +static d_write_t myfirst_write; + +/* + * The cdevsw with D_TRACKCLOSE. The d_ioctl slot is left empty for + * Stage 1 and is filled in Stage 2 once the dispatcher exists. + */ +static struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_flags = D_TRACKCLOSE, + .d_name = "myfirst", + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, +}; + +/* + * Stage 1 attach. The headline change is the use of make_dev_args / + * make_dev_s and the assignment of mda_si_drv1 at creation time. + */ +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc; + struct make_dev_args args; + int error; + + sc = device_get_softc(dev); + sc->sc_dev = dev; + mtx_init(&sc->sc_mtx, "myfirst", NULL, MTX_DEF); + + /* + * Build the cdev for /dev/myfirstN. mda_si_drv1 ties the + * per-cdev pointer to the softc, so cdevsw callbacks can + * recover the softc with dev->si_drv1 and never see a NULL. + */ + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + args.mda_unit = device_get_unit(dev); + + error = make_dev_s(&args, &sc->sc_cdev, "myfirst%d", + device_get_unit(dev)); + if (error != 0) { + device_printf(dev, "make_dev_s failed: %d\n", error); + mtx_destroy(&sc->sc_mtx); + return (error); + } + + DPRINTF(sc, MYF_DBG_INIT, "cdev created at /dev/myfirst%d\n", + device_get_unit(dev)); + return (0); +} + +/* + * Stage 1 detach. Soft refusal if the device is open, then destroy + * the cdev (which drains any in-flight callbacks) before tearing + * down anything that the cdevsw callbacks depended on. + */ +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count > 0) { + mtx_unlock(&sc->sc_mtx); + device_printf(dev, + "detach refused: %u open(s) outstanding\n", + sc->sc_open_count); + return (EBUSY); + } + mtx_unlock(&sc->sc_mtx); + + if (sc->sc_cdev != NULL) { + destroy_dev(sc->sc_cdev); + sc->sc_cdev = NULL; + DPRINTF(sc, MYF_DBG_INIT, "cdev destroyed\n"); + } + + mtx_destroy(&sc->sc_mtx); + return (0); +} + +/* + * Open and close use si_drv1 to recover the softc and bump the + * per-instance counter under the softc mutex. + */ +static int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + + SDT_PROBE2(myfirst, , , open, sc, oflags); + + mtx_lock(&sc->sc_mtx); + sc->sc_open_count++; + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_OPEN, + "open: pid=%d flags=%#x open_count=%u\n", + td->td_proc->p_pid, oflags, sc->sc_open_count); + return (0); +} + +static int +myfirst_close(struct cdev *dev, int fflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + + SDT_PROBE2(myfirst, , , close, sc, fflags); + + mtx_lock(&sc->sc_mtx); + KASSERT(sc->sc_open_count > 0, + ("myfirst_close: open_count underflow")); + sc->sc_open_count--; + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_OPEN, + "close: pid=%d flags=%#x open_count=%u\n", + td->td_proc->p_pid, fflags, sc->sc_open_count); + return (0); +} + +/* + * Read and write are unchanged from Chapter 23. They are listed + * here as forward declarations for completeness; the actual bodies + * remain in the Chapter 23 source you copied alongside this file. + */ +static int myfirst_read(struct cdev *dev, struct uio *uio, int ioflag); +static int myfirst_write(struct cdev *dev, struct uio *uio, int ioflag); diff --git a/examples/part-05/ch24-integration/stage2-ioctl/Makefile b/examples/part-05/ch24-integration/stage2-ioctl/Makefile new file mode 100644 index 0000000..64cebf9 --- /dev/null +++ b/examples/part-05/ch24-integration/stage2-ioctl/Makefile @@ -0,0 +1,14 @@ +# Makefile for the myfirst driver - Chapter 24 Stage 2 +# (1.7-integration-stage-2). +# +# Stage 2 adds the ioctl interface. The new myfirst_ioctl.c file +# joins the SRCS list; nothing else in the build changes. + +KMOD= myfirst +SRCS= myfirst.c myfirst_debug.c myfirst_ioctl.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-05/ch24-integration/stage2-ioctl/Makefile.user b/examples/part-05/ch24-integration/stage2-ioctl/Makefile.user new file mode 100644 index 0000000..44b464b --- /dev/null +++ b/examples/part-05/ch24-integration/stage2-ioctl/Makefile.user @@ -0,0 +1,18 @@ +# Makefile.user - build the myfirstctl(8) user-space companion. +# +# Use this Makefile from the same directory that holds the public +# header myfirst_ioctl.h. The companion has no library dependencies +# beyond libc. + +PROG= myfirstctl +SRCS= myfirstctl.c +NO_MAN= yes + +CFLAGS+= -I${.CURDIR} + +# We do not install the binary by default; readers run it from the +# build directory. Override BINDIR if you want to install it under +# /usr/local/sbin or similar. +BINDIR?= /usr/local/sbin + +.include diff --git a/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.c b/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.c new file mode 100644 index 0000000..02bb009 --- /dev/null +++ b/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.c @@ -0,0 +1,107 @@ +/* + * myfirst_ioctl.c - ioctl dispatcher for the myfirst driver. + * + * The d_ioctl callback in myfirst_cdevsw points at myfirst_ioctl. + * Per-command argument layout is documented in myfirst_ioctl.h, which + * is shared with user space. + * + * The dispatcher takes the softc mutex once at the top and releases + * it once at the bottom, so every command is serialised against + * read/write/close and against other ioctls. Every command is short + * enough that holding the mutex for the whole switch statement is + * fine; a real driver that needed slow hardware operations would + * release the mutex around them. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" +#include "myfirst_ioctl.h" + +/* + * The ioctl SDT probe is defined here rather than in myfirst_debug.c + * because the probe arguments depend on the ioctl interface, which is + * a Stage 2 addition. The myfirst_debug.c file owns only the probes + * that the Chapter 23 debug refactor introduced. + */ +SDT_PROBE_DEFINE3(myfirst, , , ioctl, + "struct myfirst_softc *", "u_long", "int"); + +int +myfirst_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int error = 0; + + SDT_PROBE3(myfirst, , , ioctl, sc, cmd, fflag); + DPRINTF(sc, MYF_DBG_IOCTL, "ioctl: cmd=0x%08lx fflag=0x%x\n", + cmd, fflag); + + mtx_lock(&sc->sc_mtx); + + switch (cmd) { + case MYFIRSTIOC_GETVER: + *(uint32_t *)data = MYFIRST_IOCTL_VERSION; + break; + + case MYFIRSTIOC_GETMSG: + /* + * Copy the current message into the caller's buffer. + * The buffer is MYFIRST_MSG_MAX bytes; we always emit + * a NUL-terminated string. + */ + strlcpy((char *)data, sc->sc_msg, MYFIRST_MSG_MAX); + break; + + case MYFIRSTIOC_SETMSG: + if ((fflag & FWRITE) == 0) { + error = EBADF; + break; + } + /* + * The kernel has copied MYFIRST_MSG_MAX bytes into + * data. Take the prefix up to the first NUL. + */ + strlcpy(sc->sc_msg, (const char *)data, MYFIRST_MSG_MAX); + sc->sc_msglen = strlen(sc->sc_msg); + DPRINTF(sc, MYF_DBG_IOCTL, + "SETMSG: new message is %zu bytes\n", sc->sc_msglen); + break; + + case MYFIRSTIOC_RESET: + if ((fflag & FWRITE) == 0) { + error = EBADF; + break; + } + sc->sc_open_count = 0; + sc->sc_total_reads = 0; + sc->sc_total_writes = 0; + bzero(sc->sc_msg, sizeof(sc->sc_msg)); + sc->sc_msglen = 0; + DPRINTF(sc, MYF_DBG_IOCTL, + "RESET: counters and message cleared\n"); + break; + + default: + /* + * ENOIOCTL, never EINVAL. Returning EINVAL would + * suppress the kernel's generic ioctl fallback for + * commands such as FIONBIO and FIOASYNC. + */ + error = ENOIOCTL; + break; + } + + mtx_unlock(&sc->sc_mtx); + return (error); +} diff --git a/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.h b/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.h new file mode 100644 index 0000000..a1da49e --- /dev/null +++ b/examples/part-05/ch24-integration/stage2-ioctl/myfirst_ioctl.h @@ -0,0 +1,71 @@ +/* + * myfirst_ioctl.h - public ioctl interface for the myfirst driver. + * + * This header is included by both the kernel module and any user-space + * program that talks to the driver. Keep it self-contained: no kernel + * headers, no kernel types, no inline functions that pull kernel state. + * + * The header is the contract between the driver and the outside world. + * Bumping MYFIRST_IOCTL_VERSION is the signal that this contract has + * changed in a way that may not be backward-compatible. + */ + +#ifndef _MYFIRST_IOCTL_H_ +#define _MYFIRST_IOCTL_H_ + +#include +#include + +/* + * Maximum length of the in-driver message, including the trailing NUL. + * The driver enforces this on SETMSG; user-space programs that build + * larger buffers will see EINVAL. + * + * Well under IOCPARM_MAX (8192), so the kernel's automatic copyin / + * copyout machinery will move the buffer without complaint. + */ +#define MYFIRST_MSG_MAX 256 + +/* + * The interface version. Bumped when this header changes in a way + * that is not backward-compatible. User-space programs should call + * MYFIRSTIOC_GETVER first and refuse to operate on an unexpected + * version. + */ +#define MYFIRST_IOCTL_VERSION 1 + +/* + * MYFIRSTIOC_GETVER - return the driver's interface version. + * + * uint32_t ver; + * ioctl(fd, MYFIRSTIOC_GETVER, &ver); // ver == 1, 2, ... + * + * No FREAD or FWRITE flag is required. + */ +#define MYFIRSTIOC_GETVER _IOR('M', 1, uint32_t) + +/* + * MYFIRSTIOC_GETMSG - copy the current in-driver message into the + * caller's buffer. The buffer must be MYFIRST_MSG_MAX bytes; the + * message is NUL-terminated. + */ +#define MYFIRSTIOC_GETMSG _IOR('M', 2, char[MYFIRST_MSG_MAX]) + +/* + * MYFIRSTIOC_SETMSG - replace the in-driver message. The buffer must + * be MYFIRST_MSG_MAX bytes; the kernel takes the prefix up to the + * first NUL or to MYFIRST_MSG_MAX - 1 bytes. + * + * Requires FWRITE on the file descriptor. + */ +#define MYFIRSTIOC_SETMSG _IOW('M', 3, char[MYFIRST_MSG_MAX]) + +/* + * MYFIRSTIOC_RESET - reset all per-instance counters and clear the + * message. Returns 0 on success. + * + * Requires FWRITE on the file descriptor. + */ +#define MYFIRSTIOC_RESET _IO('M', 4) + +#endif /* _MYFIRST_IOCTL_H_ */ diff --git a/examples/part-05/ch24-integration/stage2-ioctl/myfirstctl.c b/examples/part-05/ch24-integration/stage2-ioctl/myfirstctl.c new file mode 100644 index 0000000..17806c0 --- /dev/null +++ b/examples/part-05/ch24-integration/stage2-ioctl/myfirstctl.c @@ -0,0 +1,93 @@ +/* + * myfirstctl.c - command-line front end to the myfirst driver's ioctls. + * + * Build: cc -o myfirstctl myfirstctl.c + * Usage: myfirstctl get-version + * myfirstctl get-message + * myfirstctl set-message "" + * myfirstctl reset + * + * The program opens the device with the minimum flags required for + * the requested operation: O_RDONLY for the read-only commands and + * O_RDWR for the writers. The kernel's dispatcher returns EBADF on + * a write-class command issued through a read-only fd. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst_ioctl.h" + +#define DEVPATH "/dev/myfirst0" + +static void +usage(void) +{ + fprintf(stderr, + "usage: myfirstctl get-version\n" + " myfirstctl get-message\n" + " myfirstctl set-message \n" + " myfirstctl reset\n"); + exit(EX_USAGE); +} + +int +main(int argc, char **argv) +{ + int fd, flags; + const char *cmd; + + if (argc < 2) + usage(); + cmd = argv[1]; + + /* + * SETMSG and RESET need write access; the others only need + * read. Open the device with the right flags so the + * dispatcher does not return EBADF. + */ + if (strcmp(cmd, "set-message") == 0 || + strcmp(cmd, "reset") == 0) + flags = O_RDWR; + else + flags = O_RDONLY; + + fd = open(DEVPATH, flags); + if (fd < 0) + err(EX_OSERR, "open %s", DEVPATH); + + if (strcmp(cmd, "get-version") == 0) { + uint32_t ver; + if (ioctl(fd, MYFIRSTIOC_GETVER, &ver) < 0) + err(EX_OSERR, "MYFIRSTIOC_GETVER"); + printf("driver ioctl version: %u\n", ver); + } else if (strcmp(cmd, "get-message") == 0) { + char buf[MYFIRST_MSG_MAX]; + if (ioctl(fd, MYFIRSTIOC_GETMSG, buf) < 0) + err(EX_OSERR, "MYFIRSTIOC_GETMSG"); + printf("%s\n", buf); + } else if (strcmp(cmd, "set-message") == 0) { + char buf[MYFIRST_MSG_MAX]; + if (argc < 3) + usage(); + strlcpy(buf, argv[2], sizeof(buf)); + if (ioctl(fd, MYFIRSTIOC_SETMSG, buf) < 0) + err(EX_OSERR, "MYFIRSTIOC_SETMSG"); + } else if (strcmp(cmd, "reset") == 0) { + if (ioctl(fd, MYFIRSTIOC_RESET) < 0) + err(EX_OSERR, "MYFIRSTIOC_RESET"); + } else { + usage(); + } + + close(fd); + return (0); +} diff --git a/examples/part-05/ch24-integration/stage3-sysctl/Makefile b/examples/part-05/ch24-integration/stage3-sysctl/Makefile new file mode 100644 index 0000000..4e973a5 --- /dev/null +++ b/examples/part-05/ch24-integration/stage3-sysctl/Makefile @@ -0,0 +1,14 @@ +# Makefile for the myfirst driver - Chapter 24 Stage 3 (1.7-integration). +# +# Stage 3 is the chapter's final milestone. The new myfirst_sysctl.c +# joins the SRCS list alongside the Stage 2 myfirst_ioctl.c. This is +# the version of myfirst.ko that Chapter 25 builds on. + +KMOD= myfirst +SRCS= myfirst.c myfirst_debug.c myfirst_ioctl.c myfirst_sysctl.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-05/ch24-integration/stage3-sysctl/myfirst.c b/examples/part-05/ch24-integration/stage3-sysctl/myfirst.c new file mode 100644 index 0000000..33542d1 --- /dev/null +++ b/examples/part-05/ch24-integration/stage3-sysctl/myfirst.c @@ -0,0 +1,142 @@ +/* + * myfirst.c - Chapter 24 Stage 3: complete attach and detach. + * + * This is the final shape of myfirst_attach and myfirst_detach for + * the chapter. They tie every previous section together: the cdev + * construction from Section 2, the ioctl wiring from Section 3, the + * sysctl tree from Section 4, the lifecycle discipline from Section + * 7, and the version handling from Section 8. + * + * Driver version: 1.7-integration. + * + * This file shows only the attach and detach functions. Merge the + * functions below into your driver alongside myfirst_ioctl.c and + * myfirst_sysctl.c. The cdevsw, the read/write callbacks, and the + * SDT probe definitions remain in their existing locations. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" +#include "myfirst_ioctl.h" + +/* + * MODULE_VERSION integer. Numerically 17 (1.7). Independent of + * MYFIRST_VERSION (the human string in myfirst_sysctl.c) and of + * MYFIRST_IOCTL_VERSION (the wire-format integer in myfirst_ioctl.h). + */ +MODULE_VERSION(myfirst, 17); + +extern struct cdevsw myfirst_cdevsw; +extern void myfirst_sysctl_attach(struct myfirst_softc *); + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + struct make_dev_args args; + int error; + + /* 1. Stash the device pointer and initialise the lock. */ + sc->sc_dev = dev; + mtx_init(&sc->sc_mtx, "myfirst", NULL, MTX_DEF); + + /* 2. Initialise the in-driver state to its defaults. */ + strlcpy(sc->sc_msg, "Hello from myfirst", sizeof(sc->sc_msg)); + sc->sc_msglen = strlen(sc->sc_msg); + sc->sc_open_count = 0; + sc->sc_total_reads = 0; + sc->sc_total_writes = 0; + sc->sc_debug = 0; + + /* + * 3. Read the boot-time tunable for the debug mask. If the + * operator set hw.myfirst.debug_mask_default in + * /boot/loader.conf, sc_debug now holds that value; + * otherwise sc_debug remains zero. + */ + TUNABLE_INT_FETCH("hw.myfirst.debug_mask_default", &sc->sc_debug); + + /* + * 4. Construct the cdev. The args struct gives us a typed, + * versionable interface; mda_si_drv1 wires the per-cdev + * pointer to the softc atomically, closing the race window + * between creation and assignment. + */ + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + args.mda_unit = device_get_unit(dev); + + error = make_dev_s(&args, &sc->sc_cdev, + "myfirst%d", device_get_unit(dev)); + if (error != 0) + goto fail_mtx; + + /* + * 5. Build the sysctl tree. The framework owns the per-device + * context, so we do not need to track or destroy it + * ourselves; detach below does not call sysctl_ctx_free. + */ + myfirst_sysctl_attach(sc); + + DPRINTF(sc, MYF_DBG_INIT, + "attach: stage 3 complete, version 1.7-integration\n"); + return (0); + +fail_mtx: + mtx_destroy(&sc->sc_mtx); + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + /* + * 1. Refuse detach if anyone holds the device open. The + * chapter's pattern is the simple soft refusal; Challenge 3 + * walks through the more elaborate dev_ref/dev_rel pattern + * that drains in-flight references rather than refusing. + */ + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count > 0) { + mtx_unlock(&sc->sc_mtx); + return (EBUSY); + } + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_INIT, "detach: tearing down\n"); + + /* + * 2. Destroy the cdev. destroy_dev blocks until every + * in-flight cdevsw callback returns; after this call, + * no new open/close/read/write/ioctl can arrive. + */ + destroy_dev(sc->sc_cdev); + + /* + * 3. The per-device sysctl context is torn down automatically + * by the framework after detach returns successfully. + * Nothing to do here. + */ + + /* + * 4. Destroy the lock. Safe now because the cdev is gone and + * no other code path can take it. + */ + mtx_destroy(&sc->sc_mtx); + + return (0); +} diff --git a/examples/part-05/ch24-integration/stage3-sysctl/myfirst_sysctl.c b/examples/part-05/ch24-integration/stage3-sysctl/myfirst_sysctl.c new file mode 100644 index 0000000..6c3ef00 --- /dev/null +++ b/examples/part-05/ch24-integration/stage3-sysctl/myfirst_sysctl.c @@ -0,0 +1,122 @@ +/* + * myfirst_sysctl.c - sysctl tree for the myfirst driver. + * + * Builds dev.myfirst..* with version, counters, message, and a + * debug subtree (debug.mask, debug.classes). The per-device sysctl + * context is owned by Newbus, so the driver does not have to track + * or destroy the OIDs explicitly. myfirst_detach can stay quiet + * about sysctl: the framework cleans up after detach returns. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" + +/* + * MYFIRST_VERSION - human-readable release string. Read by the + * dev.myfirst..version OID. Bumped per the convention in + * Section 8: major.minor with a -tag suffix that names the chapter + * milestone. + */ +#define MYFIRST_VERSION "1.7-integration" + +/* + * Handler for the message_len OID. Static OIDs work for fields the + * kernel can dereference directly; message_len is computed from + * sc_msglen under the softc mutex, so it needs a custom handler. + */ +static int +myfirst_sysctl_message_len(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + u_int len; + + mtx_lock(&sc->sc_mtx); + len = (u_int)sc->sc_msglen; + mtx_unlock(&sc->sc_mtx); + + return (sysctl_handle_int(oidp, &len, 0, req)); +} + +void +myfirst_sysctl_attach(struct myfirst_softc *sc) +{ + device_t dev = sc->sc_dev; + struct sysctl_ctx_list *ctx; + struct sysctl_oid *tree; + struct sysctl_oid_list *child; + struct sysctl_oid *debug_node; + struct sysctl_oid_list *debug_child; + + /* + * Use the per-device context that Newbus already created. The + * tree corresponds to dev.myfirst.; child is its OID list. + */ + ctx = device_get_sysctl_ctx(dev); + tree = device_get_sysctl_tree(dev); + child = SYSCTL_CHILDREN(tree); + + /* Read-only: driver version. */ + SYSCTL_ADD_STRING(ctx, child, OID_AUTO, "version", + CTLFLAG_RD, MYFIRST_VERSION, 0, + "Driver version string"); + + /* Read-only: counters. */ + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "open_count", + CTLFLAG_RD, &sc->sc_open_count, 0, + "Number of currently open file descriptors"); + + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "total_reads", + CTLFLAG_RD, &sc->sc_total_reads, 0, + "Total read() calls since attach"); + + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "total_writes", + CTLFLAG_RD, &sc->sc_total_writes, 0, + "Total write() calls since attach"); + + /* Read-only: message buffer (no copy through user). */ + SYSCTL_ADD_STRING(ctx, child, OID_AUTO, "message", + CTLFLAG_RD, sc->sc_msg, sizeof(sc->sc_msg), + "Current in-driver message"); + + /* Read-only handler: message length, computed. */ + SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "message_len", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_message_len, "IU", + "Current length of the in-driver message in bytes"); + + /* Subtree: debug.* */ + debug_node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "debug", + CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, + "Debug controls and class enumeration"); + debug_child = SYSCTL_CHILDREN(debug_node); + + /* + * debug.mask is read-write at runtime and tunable at boot. + * The TUN flag tells the kernel to consult the loader env + * for hw.myfirst.debug_mask_default before this OID becomes + * accessible. + */ + SYSCTL_ADD_UINT(ctx, debug_child, OID_AUTO, "mask", + CTLFLAG_RW | CTLFLAG_TUN, &sc->sc_debug, 0, + "Bitmask of enabled debug classes"); + + /* + * debug.classes is a static read-only string that lists the + * symbolic names and bit values. Useful for operators who + * do not want to hunt through the source for the bits. + */ + SYSCTL_ADD_STRING(ctx, debug_child, OID_AUTO, "classes", + CTLFLAG_RD, + "INIT(0x1) OPEN(0x2) IO(0x4) IOCTL(0x8) " + "INTR(0x10) DMA(0x20) PWR(0x40) MEM(0x80)", + 0, "Names and bit values of debug classes"); +} diff --git a/examples/part-05/ch25-advanced/MAINTENANCE.md b/examples/part-05/ch25-advanced/MAINTENANCE.md new file mode 100644 index 0000000..8b3292e --- /dev/null +++ b/examples/part-05/ch25-advanced/MAINTENANCE.md @@ -0,0 +1,71 @@ +# myfirst + +A demonstration character driver that carries the book's running +example. This file is the operator-facing reference. + +## Overview + +myfirst registers a pseudo-device at /dev/myfirst0 and serves a +read-write message buffer, a set of ioctls, a sysctl tree, and a +configurable debug-class logger. + +## Tunables + +- hw.myfirst.debug_mask_default (int, default 0) + Initial value of dev.myfirst..debug.mask. +- hw.myfirst.timeout_sec (int, default 5) + Initial value of dev.myfirst..timeout_sec. +- hw.myfirst.max_retries (int, default 3) + Initial value of dev.myfirst..max_retries. +- hw.myfirst.log_ratelimit_pps (int, default 10) + Initial rate-limit ceiling (prints per second per class). + +## Sysctls + +All sysctls live under dev.myfirst.. + +Read-only: version, open_count, total_reads, total_writes, +message, message_len. + +Read-write: debug.mask (mirror of debug_mask_default), timeout_sec, +max_retries, log_ratelimit_pps. + +## Ioctls + +Defined in myfirst_ioctl.h. Command magic 'M'. + +- MYFIRSTIOC_GETVER (0): returns MYFIRST_IOCTL_VERSION. +- MYFIRSTIOC_RESET (1): zeros read/write counters. +- MYFIRSTIOC_GETMSG (2): reads the in-driver message. +- MYFIRSTIOC_SETMSG (3): writes the in-driver message. +- MYFIRSTIOC_GETCAPS (5): returns MYF_CAP_* bitmask. + +Command 4 was reserved during Chapter 23 draft work and retired +before release. Do not reuse the number. + +## Events + +Emitted through devctl_notify(9). + +- system=myfirst subsystem= type=MSG_CHANGED + The operator-visible message was rewritten. + +## Version History + +See Change Log below. + +## Change Log + +### 1.8-maintenance +- Added MYFIRSTIOC_GETCAPS (command 5). +- Added tunables for timeout_sec, max_retries, log_ratelimit_pps. +- Added rate-limited logging via ppsratecheck(9). +- Added devctl_notify for MSG_CHANGED. +- No breaking changes from 1.7. + +### 1.7-integration +- First end-to-end integration of ioctl, sysctl, debug. +- Introduced MYFIRSTIOC_{GETVER,RESET,GETMSG,SETMSG}. + +### 1.6-debug +- Added DPRINTF framework and SDT probes. diff --git a/examples/part-05/ch25-advanced/Makefile b/examples/part-05/ch25-advanced/Makefile new file mode 100644 index 0000000..fc61710 --- /dev/null +++ b/examples/part-05/ch25-advanced/Makefile @@ -0,0 +1,16 @@ +# Makefile for the myfirst driver - Chapter 25 (1.8-maintenance). +# +# Chapter 25 splits the driver into subject-matter files. Each file +# answers a single question; the Makefile lists them in alphabetical +# order after myfirst.c (which carries the module glue) so the +# reader sees the main file first. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_debug.c myfirst_ioctl.c \ + myfirst_log.c myfirst_sysctl.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-05/ch25-advanced/devd.conf b/examples/part-05/ch25-advanced/devd.conf new file mode 100644 index 0000000..4557fb4 --- /dev/null +++ b/examples/part-05/ch25-advanced/devd.conf @@ -0,0 +1,13 @@ +# /etc/devd/myfirst.conf +# +# devd rules for the myfirst driver. Drop this file into +# /etc/devd/ and restart devd(8) for the rules to take effect. + +notify 0 { + match "system" "myfirst"; + match "type" "MSG_CHANGED"; + action "logger -t myfirst 'message changed on $subsystem'"; +}; + +# Future: match attach/detach events once Chapter 26's USB variant +# starts emitting them. diff --git a/examples/part-05/ch25-advanced/lab01-log-flood/Makefile b/examples/part-05/ch25-advanced/lab01-log-flood/Makefile new file mode 100644 index 0000000..74c65d1 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab01-log-flood/Makefile @@ -0,0 +1,11 @@ +# Lab 1: Reproducing a Log Flood +# +# Builds the user-space flood driver. The two kernel-module variants +# live in the `unlimited/` and `limited/` subdirectories. + +PROG= flood +SRCS= flood.c +NO_MAN= yes +MK_WERROR= no + +.include diff --git a/examples/part-05/ch25-advanced/lab01-log-flood/flood.c b/examples/part-05/ch25-advanced/lab01-log-flood/flood.c new file mode 100644 index 0000000..a3a85c9 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab01-log-flood/flood.c @@ -0,0 +1,48 @@ +/* + * flood.c - user-space log-flood driver for Lab 1. + * + * Calls read() on /dev/myfirst0 as fast as the kernel will let us. + * With MYF_DBG_IO enabled on the read path, each call produces one + * log message. Run once against the "unlimited" driver variant and + * once against the "limited" (DLOG_RL) variant to see the difference. + */ + +#include +#include +#include +#include +#include +#include + +#define DEVNODE "/dev/myfirst0" + +int +main(int argc, char **argv) +{ + int fd; + long i, n; + char buf[64]; + + if (argc != 2) { + fprintf(stderr, "usage: flood \n"); + return (2); + } + n = strtol(argv[1], NULL, 10); + if (n <= 0) + errx(2, "count must be positive"); + + fd = open(DEVNODE, O_RDONLY); + if (fd < 0) + err(1, "open %s", DEVNODE); + + for (i = 0; i < n; i++) { + if (lseek(fd, 0, SEEK_SET) < 0) + err(1, "lseek"); + if (read(fd, buf, sizeof(buf)) < 0) + err(1, "read"); + } + + close(fd); + printf("flood: %ld reads completed\n", n); + return (0); +} diff --git a/examples/part-05/ch25-advanced/lab01-log-flood/limited/Makefile b/examples/part-05/ch25-advanced/lab01-log-flood/limited/Makefile new file mode 100644 index 0000000..c929f24 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab01-log-flood/limited/Makefile @@ -0,0 +1,15 @@ +# Lab 1: Rate-limited log variant of myfirst. +# +# Rebuilds myfirst.ko as shipped at the top of ch25-advanced/ (no +# additional defines). The cdev read path uses DLOG_RL with the +# default 10 pps cap. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab01-log-flood/unlimited/Makefile b/examples/part-05/ch25-advanced/lab01-log-flood/unlimited/Makefile new file mode 100644 index 0000000..eb56f63 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab01-log-flood/unlimited/Makefile @@ -0,0 +1,17 @@ +# Lab 1: Unlimited (naive) log variant of myfirst. +# +# Rebuilds myfirst.ko with MYFIRST_UNLIMITED_LOG defined. The cdev +# read path prints every call through a bare device_printf instead +# of DLOG_RL. Use this to reproduce a log flood and compare against +# the rate-limited build under ../limited/. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_UNLIMITED_LOG + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab02-errno-audit/Makefile b/examples/part-05/ch25-advanced/lab02-errno-audit/Makefile new file mode 100644 index 0000000..caf8ed4 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab02-errno-audit/Makefile @@ -0,0 +1,14 @@ +# Lab 2: errno Audit with truss +# +# Builds the audit driver. Run under truss(1) to watch each errno: +# +# # make +# # truss -f -o /tmp/audit.truss ./audit +# # less /tmp/audit.truss + +PROG= audit +SRCS= audit.c +NO_MAN= yes +MK_WERROR= no + +.include diff --git a/examples/part-05/ch25-advanced/lab02-errno-audit/audit.c b/examples/part-05/ch25-advanced/lab02-errno-audit/audit.c new file mode 100644 index 0000000..e244a10 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab02-errno-audit/audit.c @@ -0,0 +1,80 @@ +/* + * audit.c - errno audit driver for Lab 2. + * + * Performs a series of deliberately invalid calls against the myfirst + * driver. Run under truss(1) to see the errno each one returns and + * calibrate your intuition about the driver's error reporting. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../myfirst_ioctl.h" + +#define DEVNODE "/dev/myfirst0" + +/* Cook up an ioctl number the driver will not recognise. */ +#define MYFIRSTIOC_UNKNOWN _IO('M', 99) + +int +main(void) +{ + int fd, rc; + char bigbuf[512]; + u_int v; + size_t vlen = sizeof(v); + + fd = open(DEVNODE, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVNODE); + + /* 1. Unknown ioctl command number. */ + errno = 0; + rc = ioctl(fd, MYFIRSTIOC_UNKNOWN); + printf("step 1: ioctl(unknown) = %d, errno = %d (%s)\n", + rc, errno, strerror(errno)); + + /* 2. MYFIRSTIOC_SETMSG with NULL argument. */ + errno = 0; + rc = ioctl(fd, MYFIRSTIOC_SETMSG, (char *)NULL); + printf("step 2: ioctl(SETMSG, NULL) = %d, errno = %d (%s)\n", + rc, errno, strerror(errno)); + + /* 3. Zero-length write. */ + errno = 0; + rc = write(fd, "", 0); + printf("step 3: write(0 bytes) = %d, errno = %d (%s)\n", + rc, errno, strerror(errno)); + + /* 4. Oversize write. */ + memset(bigbuf, 'x', sizeof(bigbuf)); + errno = 0; + rc = write(fd, bigbuf, sizeof(bigbuf)); + printf("step 4: write(oversize) = %d, errno = %d (%s)\n", + rc, errno, strerror(errno)); + + /* 5. Sysctl out-of-range. */ + v = 9999; + errno = 0; + rc = sysctlbyname("dev.myfirst.0.timeout_sec", NULL, NULL, + &v, sizeof(v)); + printf("step 5: sysctl(timeout_sec=9999) = %d, errno = %d (%s)\n", + rc, errno, strerror(errno)); + + /* Read the value back to confirm it was not corrupted. */ + if (sysctlbyname("dev.myfirst.0.timeout_sec", &v, &vlen, + NULL, 0) == 0) + printf(" sysctl timeout_sec = %u\n", v); + + close(fd); + return (0); +} diff --git a/examples/part-05/ch25-advanced/lab03-tunable-reboot/apply_tunable.sh b/examples/part-05/ch25-advanced/lab03-tunable-reboot/apply_tunable.sh new file mode 100755 index 0000000..272d700 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab03-tunable-reboot/apply_tunable.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# +# apply_tunable.sh - helper for Lab 3. +# +# Unloads myfirst, sets the tunable via kenv(1), reloads, and prints +# the resulting initial sysctl value. Compare with and without the +# tunable set to see that TUNABLE_INT_FETCH actually overrides the +# attach-time default. + +set -e + +TUNABLE="${1:-hw.myfirst.timeout_sec}" +VALUE="${2:-12}" +KMOD="${3:-../myfirst.ko}" +SYSCTL="dev.myfirst.0.${TUNABLE#hw.myfirst.}" + +echo "== Step 1: unload any existing myfirst instance" +kldunload myfirst 2>/dev/null || true + +echo "== Step 2: set ${TUNABLE} = ${VALUE} via kenv(1)" +kenv "${TUNABLE}=${VALUE}" + +echo "== Step 3: load ${KMOD}" +kldload "${KMOD}" + +echo "== Step 4: observe the initial sysctl value" +sysctl "${SYSCTL}" + +echo +echo "To reset, run:" +echo " kldunload myfirst" +echo " kenv -u ${TUNABLE}" +echo " kldload ${KMOD}" diff --git a/examples/part-05/ch25-advanced/lab04-failure-injection/inject-cdev/Makefile b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-cdev/Makefile new file mode 100644 index 0000000..ffbdb02 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-cdev/Makefile @@ -0,0 +1,15 @@ +# Lab 4: failure injection after make_dev_s. +# +# attach() returns ENOMEM after the cdev is created. The +# fail_cdev -> fail_mtx chain has to destroy the cdev and the lock. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_DEBUG_INJECT_FAIL_CDEV + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab04-failure-injection/inject-log/Makefile b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-log/Makefile new file mode 100644 index 0000000..f564af8 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-log/Makefile @@ -0,0 +1,16 @@ +# Lab 4: failure injection after myfirst_log_attach. +# +# attach() returns ENOMEM just after the rate-limit state is +# initialised. fail_log -> fail_cdev -> fail_mtx must release every +# resource acquired to that point. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_DEBUG_INJECT_FAIL_LOG + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab04-failure-injection/inject-mtx/Makefile b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-mtx/Makefile new file mode 100644 index 0000000..347904e --- /dev/null +++ b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-mtx/Makefile @@ -0,0 +1,17 @@ +# Lab 4: failure injection after mtx_init. +# +# Compiles myfirst.ko with MYFIRST_DEBUG_INJECT_FAIL_MTX defined. +# attach() returns ENOMEM at the first injection label; only the +# lock should need releasing. A clean load/fail cycle confirms +# that fail_mtx: releases everything it should. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_DEBUG_INJECT_FAIL_MTX + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab04-failure-injection/inject-sysctl/Makefile b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-sysctl/Makefile new file mode 100644 index 0000000..2373937 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab04-failure-injection/inject-sysctl/Makefile @@ -0,0 +1,16 @@ +# Lab 4: failure injection after sysctl tree built. +# +# attach() returns ENOMEM just after myfirst_sysctl_attach() returns. +# The cdev and lock must both be released; sysctl OIDs are owned by +# Newbus, so they unwind automatically when the device is torn down. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_DEBUG_INJECT_FAIL_SYSCTL + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab04-failure-injection/run.sh b/examples/part-05/ch25-advanced/lab04-failure-injection/run.sh new file mode 100755 index 0000000..07b876a --- /dev/null +++ b/examples/part-05/ch25-advanced/lab04-failure-injection/run.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# +# run.sh - combined regression for Lab 4 failure injection. +# +# Builds each of the four injection variants, attempts to load it, +# verifies that the load fails, and verifies that the kernel is in a +# clean state (no sysctl, no cdev, no witness complaints). One-line +# pass/fail report per variant. + +set -u + +SCRIPT_DIR=$(dirname "$0") +cd "$SCRIPT_DIR" + +VARIANTS="inject-mtx inject-cdev inject-sysctl inject-log" + +fail=0 +for v in $VARIANTS; do + echo "== Variant: $v" + + make -C "$v" clean >/dev/null 2>&1 || true + if ! make -C "$v" >/dev/null 2>"$v/build.log"; then + echo " FAIL: build error; see $v/build.log" + fail=$((fail + 1)) + continue + fi + + # The load is expected to fail. + if kldload "$v/myfirst.ko" >/dev/null 2>&1; then + echo " FAIL: load succeeded; should have failed" + kldunload myfirst >/dev/null 2>&1 || true + fail=$((fail + 1)) + continue + fi + + # Confirm clean state. + if sysctl dev.myfirst >/dev/null 2>&1; then + echo " FAIL: dev.myfirst sysctl still exists" + fail=$((fail + 1)) + continue + fi + if ls /dev/myfirst0 >/dev/null 2>&1; then + echo " FAIL: /dev/myfirst0 still exists" + fail=$((fail + 1)) + continue + fi + if dmesg | tail -20 | grep -iq "witness\|leak"; then + echo " FAIL: witness/leak warning in dmesg" + fail=$((fail + 1)) + continue + fi + + echo " PASS" +done + +echo +if [ $fail -eq 0 ]; then + echo "All $(echo $VARIANTS | wc -w) variants passed." + exit 0 +else + echo "$fail variant(s) failed." + exit 1 +fi diff --git a/examples/part-05/ch25-advanced/lab05-shutdown-handler/Makefile b/examples/part-05/ch25-advanced/lab05-shutdown-handler/Makefile new file mode 100644 index 0000000..d48227a --- /dev/null +++ b/examples/part-05/ch25-advanced/lab05-shutdown-handler/Makefile @@ -0,0 +1,17 @@ +# Lab 5: shutdown_pre_sync handler demonstration. +# +# Rebuilds myfirst.ko with MYFIRST_SHUTDOWN_NOISY defined so the +# shutdown handler writes an unconditional device_printf instead of +# the debug-mask-gated DPRINTF. Use this build on a test machine +# to watch the message appear on the console before filesystems sync. + +KMOD= myfirst +SRCS= myfirst.c myfirst_cdev.c myfirst_ioctl.c \ + myfirst_sysctl.c myfirst_debug.c myfirst_log.c + +CFLAGS+= -I${.CURDIR}/../.. +CFLAGS+= -DMYFIRST_SHUTDOWN_NOISY + +.PATH: ${.CURDIR}/../.. + +.include diff --git a/examples/part-05/ch25-advanced/lab06-100-cycles/run.sh b/examples/part-05/ch25-advanced/lab06-100-cycles/run.sh new file mode 100755 index 0000000..4d9f63e --- /dev/null +++ b/examples/part-05/ch25-advanced/lab06-100-cycles/run.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# +# run.sh - 100-cycle load/unload regression for Lab 6. +# +# Loads, sleeps, and unloads the myfirst module 100 times in a row. +# Records pass/fail per cycle and reports any leaks visible through +# vmstat -m. Log lives at /tmp/myfirst-cycles.log. + +set -u + +CYCLES="${1:-100}" +KMOD="${2:-../myfirst.ko}" +LOGFILE="${LOGFILE:-/tmp/myfirst-cycles.log}" + +: >"$LOGFILE" + +# Sanity check: the module must start unloaded. +if kldstat -n myfirst >/dev/null 2>&1; then + echo "myfirst is already loaded. Unload it first." >&2 + exit 2 +fi + +echo "== Recording baseline vmstat -m" +vmstat -m >/tmp/myfirst-before.txt + +failures=0 +for i in $(seq 1 "$CYCLES"); do + if ! kldload "$KMOD" >>"$LOGFILE" 2>&1; then + echo "cycle $i/$CYCLES: load FAILED" + failures=$((failures + 1)) + continue + fi + sleep 0.1 + if ! kldunload myfirst >>"$LOGFILE" 2>&1; then + echo "cycle $i/$CYCLES: unload FAILED" + failures=$((failures + 1)) + continue + fi + echo "cycle $i/$CYCLES: ok" +done + +echo "== Recording final vmstat -m" +vmstat -m >/tmp/myfirst-after.txt + +leaks=0 +if ! diff -q /tmp/myfirst-before.txt /tmp/myfirst-after.txt \ + >/dev/null 2>&1; then + # Some churn is normal (kernel bookkeeping). The lab reports + # the diff for human inspection rather than flagging every + # delta as a leak. + leaks=$(diff /tmp/myfirst-before.txt /tmp/myfirst-after.txt | \ + grep -c '^[<>]' || true) +fi + +echo +echo "done: $CYCLES cycles, $failures failures, " \ + "$leaks lines changed in vmstat -m." +if [ "$failures" -ne 0 ]; then + echo "See $LOGFILE for the first failing cycle." + exit 1 +fi +if [ "$leaks" -gt 4 ]; then + echo "Significant vmstat -m drift. Compare:" + echo " /tmp/myfirst-before.txt" + echo " /tmp/myfirst-after.txt" + exit 1 +fi +exit 0 diff --git a/examples/part-05/ch25-advanced/lab07-getcaps/Makefile b/examples/part-05/ch25-advanced/lab07-getcaps/Makefile new file mode 100644 index 0000000..3760ce7 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab07-getcaps/Makefile @@ -0,0 +1,13 @@ +# Lab 7: Capability Discovery in User Space +# +# Builds mfctl25, a user-space control program that discovers the +# driver's capabilities via MYFIRSTIOC_GETCAPS before issuing each +# operation. Falls back to a documented default set if GETCAPS is +# not supported (older driver). + +PROG= mfctl25 +SRCS= mfctl25.c +NO_MAN= yes +MK_WERROR= no + +.include diff --git a/examples/part-05/ch25-advanced/lab07-getcaps/mfctl25.c b/examples/part-05/ch25-advanced/lab07-getcaps/mfctl25.c new file mode 100644 index 0000000..70d2cc1 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab07-getcaps/mfctl25.c @@ -0,0 +1,165 @@ +/* + * mfctl25.c - capability-aware control program for the myfirst driver. + * + * Chapter 25, Lab 7. This program issues MYFIRSTIOC_GETCAPS before + * each operation and skips operations the driver does not advertise. + * When GETCAPS itself is not supported (older driver), it falls back + * to a documented default capability set derived from Chapter 24. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../myfirst_ioctl.h" + +#define DEVNODE "/dev/myfirst0" + +static const uint32_t FALLBACK_CAPS = + MYF_CAP_RESET | MYF_CAP_GETMSG | MYF_CAP_SETMSG; + +static uint32_t +driver_caps(int fd) +{ + uint32_t caps; + + if (ioctl(fd, MYFIRSTIOC_GETCAPS, &caps) == 0) + return (caps); + if (errno != ENOTTY) + err(1, "MYFIRSTIOC_GETCAPS"); + + fprintf(stderr, + "GETCAPS ioctl not supported. " + "Falling back to default feature set:\n"); + return (FALLBACK_CAPS); +} + +static void +print_caps(uint32_t caps) +{ + if (caps & MYF_CAP_RESET) + printf(" MYF_CAP_RESET\n"); + if (caps & MYF_CAP_GETMSG) + printf(" MYF_CAP_GETMSG\n"); + if (caps & MYF_CAP_SETMSG) + printf(" MYF_CAP_SETMSG\n"); + if (caps & MYF_CAP_TIMEOUT) + printf(" MYF_CAP_TIMEOUT\n"); + if (caps & MYF_CAP_STATS) + printf(" MYF_CAP_STATS\n"); +} + +static void +cmd_caps(int fd) +{ + uint32_t caps = driver_caps(fd); + + printf("Driver reports capabilities:\n"); + print_caps(caps); +} + +static void +cmd_reset(int fd) +{ + uint32_t caps = driver_caps(fd); + + if (!(caps & MYF_CAP_RESET)) { + printf("reset: not supported on this driver version.\n"); + return; + } + if (ioctl(fd, MYFIRSTIOC_RESET) != 0) + err(1, "MYFIRSTIOC_RESET"); +} + +static void +cmd_getmsg(int fd) +{ + uint32_t caps = driver_caps(fd); + char buf[MYFIRST_MSG_MAX]; + + if (!(caps & MYF_CAP_GETMSG)) { + printf("getmsg: not supported on this driver version.\n"); + return; + } + if (ioctl(fd, MYFIRSTIOC_GETMSG, buf) != 0) + err(1, "MYFIRSTIOC_GETMSG"); + printf("Current message: %s\n", buf); +} + +static void +cmd_setmsg(int fd, const char *msg) +{ + uint32_t caps = driver_caps(fd); + char buf[MYFIRST_MSG_MAX]; + + if (!(caps & MYF_CAP_SETMSG)) { + printf("setmsg: not supported on this driver version.\n"); + return; + } + strlcpy(buf, msg, sizeof(buf)); + if (ioctl(fd, MYFIRSTIOC_SETMSG, buf) != 0) + err(1, "MYFIRSTIOC_SETMSG"); +} + +static void +cmd_timeout(int fd) +{ + uint32_t caps = driver_caps(fd); + + if (!(caps & MYF_CAP_TIMEOUT)) { + printf("Timeout ioctl not supported; use sysctl " + "dev.myfirst.0.timeout_sec instead.\n"); + return; + } + printf("Timeout ioctl supported; would issue the ioctl here.\n"); +} + +static void +usage(void) +{ + fprintf(stderr, + "usage: mfctl25 [arg]\n" + "commands: caps | reset | getmsg | setmsg | timeout\n"); + exit(2); +} + +int +main(int argc, char **argv) +{ + int fd; + + if (argc < 2) + usage(); + + fd = open(DEVNODE, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVNODE); + + if (strcmp(argv[1], "caps") == 0) + cmd_caps(fd); + else if (strcmp(argv[1], "reset") == 0) + cmd_reset(fd); + else if (strcmp(argv[1], "getmsg") == 0) + cmd_getmsg(fd); + else if (strcmp(argv[1], "setmsg") == 0) { + if (argc != 3) + usage(); + cmd_setmsg(fd, argv[2]); + } else if (strcmp(argv[1], "timeout") == 0) + cmd_timeout(fd); + else + usage(); + + close(fd); + return (0); +} diff --git a/examples/part-05/ch25-advanced/lab08-sysctl-validation/run.sh b/examples/part-05/ch25-advanced/lab08-sysctl-validation/run.sh new file mode 100755 index 0000000..2503c7a --- /dev/null +++ b/examples/part-05/ch25-advanced/lab08-sysctl-validation/run.sh @@ -0,0 +1,60 @@ +#!/bin/sh +# +# run.sh - sysctl range-validation regression for Lab 8. +# +# Drives every writable sysctl to zero, to its maximum, and to one +# above its maximum. Reports pass/fail per sysctl. + +set -u + +check() { + oid="$1" + value="$2" + expected="$3" # "ok" if the assignment should succeed + # "reject" if it should be rejected + + out=$(sysctl "$oid=$value" 2>&1 || true) + if printf '%s' "$out" | grep -qi "Invalid argument"; then + got="reject" + else + got="ok" + fi + + if [ "$got" = "$expected" ]; then + printf "PASS %-32s = %-8s (%s)\n" "$oid" "$value" "$got" + else + printf "FAIL %-32s = %-8s (expected %s, got %s)\n" \ + "$oid" "$value" "$expected" "$got" + fi +} + +echo "== timeout_sec (valid range 1-60)" +check dev.myfirst.0.timeout_sec 0 reject +check dev.myfirst.0.timeout_sec 1 ok +check dev.myfirst.0.timeout_sec 60 ok +check dev.myfirst.0.timeout_sec 61 reject + +echo +echo "== max_retries (valid range 1-100)" +check dev.myfirst.0.max_retries 0 reject +check dev.myfirst.0.max_retries 1 ok +check dev.myfirst.0.max_retries 100 ok +check dev.myfirst.0.max_retries 101 reject + +echo +echo "== log_ratelimit_pps (valid range 1-10000)" +check dev.myfirst.0.log_ratelimit_pps 0 reject +check dev.myfirst.0.log_ratelimit_pps 1 ok +check dev.myfirst.0.log_ratelimit_pps 10000 ok +check dev.myfirst.0.log_ratelimit_pps 10001 reject + +echo +echo "== debug.mask (accepts any int; check that read-back matches)" +check dev.myfirst.0.debug.mask 0 ok +check dev.myfirst.0.debug.mask 255 ok + +# Restore sane defaults for subsequent labs. +sysctl dev.myfirst.0.timeout_sec=5 >/dev/null 2>&1 || true +sysctl dev.myfirst.0.max_retries=3 >/dev/null 2>&1 || true +sysctl dev.myfirst.0.log_ratelimit_pps=10 >/dev/null 2>&1 || true +sysctl dev.myfirst.0.debug.mask=0 >/dev/null 2>&1 || true diff --git a/examples/part-05/ch25-advanced/lab09-log-audit/audit.sh b/examples/part-05/ch25-advanced/lab09-log-audit/audit.sh new file mode 100755 index 0000000..503a0b4 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab09-log-audit/audit.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# +# audit.sh - mechanical audit of every log site in the driver. +# +# Categorises each printf/device_printf/log/DPRINTF/DLOG_RL call as +# one of: +# PASS - device_printf/DPRINTF/DLOG_RL (device-named or debug-gated) +# WARN - bare printf (legitimate only at MOD_LOAD, usually) +# FAIL - device_printf on a hot path without rate limiting +# +# The "hot path" detection is based on file names: myfirst_cdev.c and +# myfirst_ioctl.c are hot; everything else is cold. + +set -u + +SRCDIR="$(cd "$(dirname "$0")/.." && pwd)" +FILES="myfirst.c myfirst_cdev.c myfirst_ioctl.c myfirst_sysctl.c \ + myfirst_debug.c myfirst_log.c" + +hot_path() { + case "$1" in + myfirst_cdev.c|myfirst_ioctl.c) return 0 ;; + *) return 1 ;; + esac +} + +total_pass=0 +total_warn=0 +total_fail=0 + +for f in $FILES; do + file="$SRCDIR/$f" + [ -f "$file" ] || continue + + pass=0 + warn=0 + fail=0 + + while IFS= read -r line; do + case "$line" in + *"device_printf"*|*"DPRINTF"*|*"DLOG_RL"*) + if hot_path "$f" && \ + printf '%s' "$line" | grep -q "device_printf" && \ + ! printf '%s' "$line" | grep -q "DPRINTF\|DLOG_RL\|MYF_CDEV_HOT_LOG" + then + fail=$((fail + 1)) + else + pass=$((pass + 1)) + fi + ;; + *"printf("*|*" log("*) + warn=$((warn + 1)) + ;; + esac + done <"$file" + + total=$((pass + warn + fail)) + total_pass=$((total_pass + pass)) + total_warn=$((total_warn + warn)) + total_fail=$((total_fail + fail)) + + if [ "$total" -eq 0 ]; then + printf "%-20s %d log messages\n" "$f:" "$total" + else + printf "%-20s %d log messages - %d PASS, %d WARN, %d FAIL\n" \ + "$f:" "$total" "$pass" "$warn" "$fail" + fi +done + +total=$((total_pass + total_warn + total_fail)) +echo +echo "Total: $total log messages -" \ + "$total_warn WARN, $total_fail FAIL" + +if [ "$total_fail" -gt 0 ]; then + exit 1 +fi diff --git a/examples/part-05/ch25-advanced/lab10-compat-matrix/Makefile b/examples/part-05/ch25-advanced/lab10-compat-matrix/Makefile new file mode 100644 index 0000000..ca0fc70 --- /dev/null +++ b/examples/part-05/ch25-advanced/lab10-compat-matrix/Makefile @@ -0,0 +1,12 @@ +# Lab 10: Multi-Version Compatibility Matrix +# +# Builds mfctl-universal, a single user-space control program that +# works against three driver versions (1.6, 1.7, 1.8) via the +# three-tier capability fallback. + +PROG= mfctl-universal +SRCS= mfctl-universal.c +NO_MAN= yes +MK_WERROR= no + +.include diff --git a/examples/part-05/ch25-advanced/lab10-compat-matrix/mfctl-universal.c b/examples/part-05/ch25-advanced/lab10-compat-matrix/mfctl-universal.c new file mode 100644 index 0000000..f076b5c --- /dev/null +++ b/examples/part-05/ch25-advanced/lab10-compat-matrix/mfctl-universal.c @@ -0,0 +1,210 @@ +/* + * mfctl-universal.c - single user-space tool that spans three + * driver versions. + * + * Chapter 25, Lab 10. This program is the practical payoff of the + * capability-discovery pattern: one binary works against the 1.6, + * 1.7, and 1.8 drivers without modification. The three-tier + * fallback is: + * + * 1. Ask the driver directly via MYFIRSTIOC_GETCAPS. + * 2. If that fails with ENOTTY, match known version strings + * from dev.myfirst.0.version. + * 3. If the version string is unknown, use a minimal safe set. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../myfirst_ioctl.h" + +#define DEVNODE "/dev/myfirst0" + +static void +read_version(char *buf, size_t buflen) +{ + size_t len = buflen; + + if (sysctlbyname("dev.myfirst.0.version", buf, &len, + NULL, 0) != 0) { + strlcpy(buf, "unknown", buflen); + return; + } + if (len > 0 && buf[len - 1] == '\0') + len--; + if (len < buflen) + buf[len] = '\0'; +} + +static uint32_t +driver_caps(int fd, const char *version, bool *getcaps_supported) +{ + uint32_t caps; + + if (ioctl(fd, MYFIRSTIOC_GETCAPS, &caps) == 0) { + *getcaps_supported = true; + return (caps); + } + if (errno != ENOTTY) + err(1, "GETCAPS ioctl"); + *getcaps_supported = false; + + /* Fallback by version string. */ + if (strstr(version, "1.8-") != NULL) + return (MYF_CAP_RESET | MYF_CAP_GETMSG | + MYF_CAP_SETMSG); + if (strstr(version, "1.7-") != NULL) + return (MYF_CAP_RESET | MYF_CAP_GETMSG | + MYF_CAP_SETMSG); + if (strstr(version, "1.6-") != NULL) + return (MYF_CAP_GETMSG | MYF_CAP_SETMSG); + + /* Unknown version: use the minimal safe set. */ + return (MYF_CAP_GETMSG); +} + +static void +print_caps(uint32_t caps) +{ + if (caps & MYF_CAP_RESET) + printf(" MYF_CAP_RESET\n"); + if (caps & MYF_CAP_GETMSG) + printf(" MYF_CAP_GETMSG\n"); + if (caps & MYF_CAP_SETMSG) + printf(" MYF_CAP_SETMSG\n"); + if (caps & MYF_CAP_TIMEOUT) + printf(" MYF_CAP_TIMEOUT\n"); + if (caps & MYF_CAP_STATS) + printf(" MYF_CAP_STATS\n"); +} + +static void +cmd_caps(int fd) +{ + char version[64]; + bool getcaps_supported; + uint32_t caps; + + read_version(version, sizeof(version)); + caps = driver_caps(fd, version, &getcaps_supported); + + printf("Driver: version %s\n", version); + printf("GETCAPS ioctl: %s\n", + getcaps_supported ? "supported" : "not supported"); + if (getcaps_supported) + printf("Driver reports capabilities:\n"); + else + printf("Using fallback capability set:\n"); + print_caps(caps); +} + +static void +cmd_reset(int fd) +{ + char version[64]; + bool getcaps_supported; + uint32_t caps; + + read_version(version, sizeof(version)); + caps = driver_caps(fd, version, &getcaps_supported); + + if (!(caps & MYF_CAP_RESET)) { + printf("reset: not supported on this driver " + "version (%s)\n", version); + return; + } + if (ioctl(fd, MYFIRSTIOC_RESET) != 0) + err(1, "MYFIRSTIOC_RESET"); +} + +static void +cmd_getmsg(int fd) +{ + char version[64]; + bool getcaps_supported; + uint32_t caps; + char buf[MYFIRST_MSG_MAX]; + + read_version(version, sizeof(version)); + caps = driver_caps(fd, version, &getcaps_supported); + + if (!(caps & MYF_CAP_GETMSG)) { + printf("getmsg: not supported on this driver " + "version (%s)\n", version); + return; + } + if (ioctl(fd, MYFIRSTIOC_GETMSG, buf) != 0) + err(1, "MYFIRSTIOC_GETMSG"); + printf("Current message: %s\n", buf); +} + +static void +cmd_setmsg(int fd, const char *msg) +{ + char version[64]; + bool getcaps_supported; + uint32_t caps; + char buf[MYFIRST_MSG_MAX]; + + read_version(version, sizeof(version)); + caps = driver_caps(fd, version, &getcaps_supported); + + if (!(caps & MYF_CAP_SETMSG)) { + printf("setmsg: not supported on this driver " + "version (%s)\n", version); + return; + } + strlcpy(buf, msg, sizeof(buf)); + if (ioctl(fd, MYFIRSTIOC_SETMSG, buf) != 0) + err(1, "MYFIRSTIOC_SETMSG"); +} + +static void +usage(void) +{ + fprintf(stderr, + "usage: mfctl-universal --caps\n" + " mfctl-universal reset | getmsg | setmsg \n"); + exit(2); +} + +int +main(int argc, char **argv) +{ + int fd; + + if (argc < 2) + usage(); + + fd = open(DEVNODE, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVNODE); + + if (strcmp(argv[1], "--caps") == 0 || + strcmp(argv[1], "caps") == 0) + cmd_caps(fd); + else if (strcmp(argv[1], "reset") == 0) + cmd_reset(fd); + else if (strcmp(argv[1], "getmsg") == 0) + cmd_getmsg(fd); + else if (strcmp(argv[1], "setmsg") == 0) { + if (argc != 3) + usage(); + cmd_setmsg(fd, argv[2]); + } else + usage(); + + close(fd); + return (0); +} diff --git a/examples/part-05/ch25-advanced/myfirst.c b/examples/part-05/ch25-advanced/myfirst.c new file mode 100644 index 0000000..affce5f --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst.c @@ -0,0 +1,194 @@ +/* + * myfirst.c - module glue and attach/detach for the myfirst driver. + * + * Chapter 25 (version 1.8-maintenance). This file owns the cdevsw + * table, the MODULE_VERSION declaration, the attach routine (with a + * full labelled-cleanup chain), and the detach routine (mirror of + * attach). Every other responsibility lives in a focused sibling + * file: myfirst_cdev.c, myfirst_ioctl.c, myfirst_sysctl.c, + * myfirst_log.c, myfirst_debug.c. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" +#include "myfirst_ioctl.h" + +MODULE_VERSION(myfirst, 18); + +struct cdevsw myfirst_cdevsw = { + .d_version = D_VERSION, + .d_name = "myfirst", + .d_open = myfirst_open, + .d_close = myfirst_close, + .d_read = myfirst_read, + .d_write = myfirst_write, + .d_ioctl = myfirst_ioctl, +}; + +static void +myfirst_shutdown(void *arg, int howto) +{ + struct myfirst_softc *sc = arg; + +#ifdef MYFIRST_SHUTDOWN_NOISY + device_printf(sc->sc_dev, "shutdown: howto=0x%x\n", howto); +#else + DPRINTF(sc, MYF_DBG_INIT, "shutdown: howto=0x%x\n", howto); +#endif +} + +static int +myfirst_probe(device_t dev) +{ + + device_set_desc(dev, "myfirst pseudo-device (Chapter 25)"); + return (BUS_PROBE_NOWILDCARD); +} + +static int +myfirst_attach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + struct make_dev_args args; + int error; + + /* Stage 1: softc basics. Cannot fail. */ + sc->sc_dev = dev; + + /* Stage 2: lock. Cannot fail on MTX_DEF. */ + mtx_init(&sc->sc_mtx, "myfirst", NULL, MTX_DEF); + +#ifdef MYFIRST_DEBUG_INJECT_FAIL_MTX + device_printf(dev, "attach: stage 1 complete\n"); + device_printf(dev, "attach: injected failure after mtx_init\n"); + error = ENOMEM; + goto fail_mtx; +#endif + + /* Stage 3: defaults and tunable fetches. Cannot fail. */ + strlcpy(sc->sc_msg, "Hello from myfirst", sizeof(sc->sc_msg)); + sc->sc_msglen = strlen(sc->sc_msg); + sc->sc_open_count = 0; + sc->sc_total_reads = 0; + sc->sc_total_writes = 0; + sc->sc_debug = 0; + sc->sc_timeout_sec = 5; + sc->sc_max_retries = 3; + sc->sc_log_pps = MYF_RL_DEFAULT_PPS; + + TUNABLE_INT_FETCH("hw.myfirst.debug_mask_default", + &sc->sc_debug); + TUNABLE_INT_FETCH("hw.myfirst.timeout_sec", + &sc->sc_timeout_sec); + TUNABLE_INT_FETCH("hw.myfirst.max_retries", + &sc->sc_max_retries); + TUNABLE_INT_FETCH("hw.myfirst.log_ratelimit_pps", + &sc->sc_log_pps); + + /* Stage 4: cdev. Can fail. */ + make_dev_args_init(&args); + args.mda_devsw = &myfirst_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0660; + args.mda_si_drv1 = sc; + args.mda_unit = device_get_unit(dev); + + error = make_dev_s(&args, &sc->sc_cdev, "myfirst%d", + device_get_unit(dev)); + if (error != 0) + goto fail_mtx; + +#ifdef MYFIRST_DEBUG_INJECT_FAIL_CDEV + device_printf(dev, "attach: injected failure after make_dev_s\n"); + error = ENOMEM; + goto fail_cdev; +#endif + + /* Stage 5: sysctl tree. Cannot fail (Newbus owns the context). */ + myfirst_sysctl_attach(sc); + +#ifdef MYFIRST_DEBUG_INJECT_FAIL_SYSCTL + device_printf(dev, "attach: injected failure after sysctl\n"); + error = ENOMEM; + goto fail_cdev; +#endif + + /* Stage 6: rate-limit state. Can fail. */ + error = myfirst_log_attach(sc); + if (error != 0) + goto fail_cdev; + +#ifdef MYFIRST_DEBUG_INJECT_FAIL_LOG + device_printf(dev, "attach: injected failure after log_attach\n"); + error = ENOMEM; + goto fail_log; +#endif + + /* Stage 7: shutdown handler. Can fail. */ + sc->sc_shutdown_tag = EVENTHANDLER_REGISTER(shutdown_pre_sync, + myfirst_shutdown, sc, SHUTDOWN_PRI_DEFAULT); + if (sc->sc_shutdown_tag == NULL) { + error = ENOMEM; + goto fail_log; + } + + DPRINTF(sc, MYF_DBG_INIT, + "attach: version 1.8-maintenance complete\n"); + return (0); + +fail_log: + myfirst_log_detach(sc); +fail_cdev: + destroy_dev(sc->sc_cdev); +fail_mtx: + mtx_destroy(&sc->sc_mtx); + return (error); +} + +static int +myfirst_detach(device_t dev) +{ + struct myfirst_softc *sc = device_get_softc(dev); + + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count > 0) { + mtx_unlock(&sc->sc_mtx); + return (EBUSY); + } + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_INIT, "detach: tearing down\n"); + + EVENTHANDLER_DEREGISTER(shutdown_pre_sync, sc->sc_shutdown_tag); + myfirst_log_detach(sc); + destroy_dev(sc->sc_cdev); + mtx_destroy(&sc->sc_mtx); + + return (0); +} + +static device_method_t myfirst_methods[] = { + DEVMETHOD(device_probe, myfirst_probe), + DEVMETHOD(device_attach, myfirst_attach), + DEVMETHOD(device_detach, myfirst_detach), + DEVMETHOD_END +}; + +static driver_t myfirst_driver = { + "myfirst", + myfirst_methods, + sizeof(struct myfirst_softc), +}; + +DRIVER_MODULE(myfirst, nexus, myfirst_driver, 0, 0); diff --git a/examples/part-05/ch25-advanced/myfirst.h b/examples/part-05/ch25-advanced/myfirst.h new file mode 100644 index 0000000..7495588 --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst.h @@ -0,0 +1,66 @@ +/* + * myfirst.h - public types and constants for the myfirst driver. + * + * Types and prototypes declared here are visible to every .c file in + * the driver. Keep this header small. Wire-format declarations live + * in myfirst_ioctl.h. Debug macros live in myfirst_debug.h. Rate- + * limit state lives in myfirst_log.h. + * + * Driver version at Chapter 25: 1.8-maintenance. + */ + +#ifndef _MYFIRST_H_ +#define _MYFIRST_H_ + +#include +#include +#include +#include +#include + +#include "myfirst_log.h" + +#define MYFIRST_MSG_MAX 256 + +struct myfirst_softc { + device_t sc_dev; + struct mtx sc_mtx; + struct cdev *sc_cdev; + + char sc_msg[MYFIRST_MSG_MAX]; + size_t sc_msglen; + + u_int sc_open_count; + u_int sc_total_reads; + u_int sc_total_writes; + + u_int sc_debug; + u_int sc_timeout_sec; + u_int sc_max_retries; + u_int sc_log_pps; + + struct myfirst_ratelimit sc_rl_generic; + struct myfirst_ratelimit sc_rl_io; + struct myfirst_ratelimit sc_rl_intr; + + eventhandler_tag sc_shutdown_tag; +}; + +/* Sysctl tree. */ +void myfirst_sysctl_attach(struct myfirst_softc *); + +/* Rate-limit state. */ +int myfirst_log_attach(struct myfirst_softc *); +void myfirst_log_detach(struct myfirst_softc *); + +/* Ioctl dispatch. */ +struct thread; +int myfirst_ioctl(struct cdev *, u_long, caddr_t, int, struct thread *); + +/* cdev callbacks. */ +d_open_t myfirst_open; +d_close_t myfirst_close; +d_read_t myfirst_read; +d_write_t myfirst_write; + +#endif /* _MYFIRST_H_ */ diff --git a/examples/part-05/ch25-advanced/myfirst_cdev.c b/examples/part-05/ch25-advanced/myfirst_cdev.c new file mode 100644 index 0000000..80c0dbd --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_cdev.c @@ -0,0 +1,107 @@ +/* + * myfirst_cdev.c - character-device callbacks for the myfirst driver. + * + * open/close/read/write all operate on the softc that make_dev_s + * installed as si_drv1. ioctl dispatch is in myfirst_ioctl.c; + * this file intentionally does not handle ioctls. + */ + +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" + +/* + * Lab 1 rebuilds the module with MYFIRST_UNLIMITED_LOG defined so the + * hot-path read/write messages go straight to device_printf instead of + * through DLOG_RL. The production build leaves the macro undefined, + * which is the rate-limited path. + */ +#ifdef MYFIRST_UNLIMITED_LOG +#define MYF_CDEV_HOT_LOG(sc, rlp, pps, fmt, ...) \ + device_printf((sc)->sc_dev, fmt, ##__VA_ARGS__) +#else +#define MYF_CDEV_HOT_LOG(sc, rlp, pps, fmt, ...) \ + DLOG_RL(sc, rlp, pps, fmt, ##__VA_ARGS__) +#endif + +int +myfirst_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + + mtx_lock(&sc->sc_mtx); + sc->sc_open_count++; + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_OPEN, "open: count now %u\n", + sc->sc_open_count); + return (0); +} + +int +myfirst_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + + mtx_lock(&sc->sc_mtx); + if (sc->sc_open_count > 0) + sc->sc_open_count--; + mtx_unlock(&sc->sc_mtx); + + DPRINTF(sc, MYF_DBG_OPEN, "close: count now %u\n", + sc->sc_open_count); + return (0); +} + +int +myfirst_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + size_t amt; + int error; + + mtx_lock(&sc->sc_mtx); + if (uio->uio_offset >= (off_t)sc->sc_msglen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + amt = MIN(sc->sc_msglen - uio->uio_offset, uio->uio_resid); + error = uiomove(sc->sc_msg + uio->uio_offset, amt, uio); + sc->sc_total_reads++; + mtx_unlock(&sc->sc_mtx); + + MYF_CDEV_HOT_LOG(sc, &sc->sc_rl_io, sc->sc_log_pps, + "read: %zu bytes served\n", amt); + return (error); +} + +int +myfirst_write(struct cdev *dev, struct uio *uio, int ioflag) +{ + struct myfirst_softc *sc = dev->si_drv1; + size_t amt; + int error; + + if (uio->uio_resid > sizeof(sc->sc_msg) - 1) + return (EINVAL); + + mtx_lock(&sc->sc_mtx); + amt = uio->uio_resid; + error = uiomove(sc->sc_msg, amt, uio); + if (error == 0) { + sc->sc_msg[amt] = '\0'; + sc->sc_msglen = amt; + sc->sc_total_writes++; + } + mtx_unlock(&sc->sc_mtx); + + MYF_CDEV_HOT_LOG(sc, &sc->sc_rl_io, sc->sc_log_pps, + "write: %zu bytes accepted\n", amt); + return (error); +} diff --git a/examples/part-05/ch25-advanced/myfirst_debug.c b/examples/part-05/ch25-advanced/myfirst_debug.c new file mode 100644 index 0000000..c4d2f96 --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_debug.c @@ -0,0 +1,12 @@ +/* + * myfirst_debug.c - debug-class enumeration. + * + * Today the debug macros are all inline in myfirst_debug.h. This + * .c file exists to keep the build graph stable if future versions + * need an out-of-line helper for a complex class filter. + */ + +#include +#include + +#include "myfirst.h" diff --git a/examples/part-05/ch25-advanced/myfirst_debug.h b/examples/part-05/ch25-advanced/myfirst_debug.h new file mode 100644 index 0000000..bf5fabc --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_debug.h @@ -0,0 +1,55 @@ +/* + * myfirst_debug.h - DPRINTF macros, debug class bits, DLOG_RL. + * + * The debug framework was introduced in Chapter 23. Chapter 25 adds + * the DLOG_RL macro that wraps ppsratecheck(9) for hot-path logging. + */ + +#ifndef _MYFIRST_DEBUG_H_ +#define _MYFIRST_DEBUG_H_ + +#include +#include + +#include "myfirst.h" + +/* + * Debug class bits. The chapter's class list is: + * INIT - attach/detach lifecycle. + * OPEN - open/close events. + * IO - read/write hot path. + * IOCTL - ioctl dispatch. + * INTR - interrupt paths (placeholder for a future hardware port). + * DMA - DMA operations (placeholder). + * PWR - power management (placeholder). + * MEM - memory allocation (placeholder). + */ +#define MYF_DBG_INIT 0x01 +#define MYF_DBG_OPEN 0x02 +#define MYF_DBG_IO 0x04 +#define MYF_DBG_IOCTL 0x08 +#define MYF_DBG_INTR 0x10 +#define MYF_DBG_DMA 0x20 +#define MYF_DBG_PWR 0x40 +#define MYF_DBG_MEM 0x80 + +/* + * DPRINTF: emit a device_printf only when the matching class bit is + * set in sc->sc_debug. Disabled classes add only a branch. + */ +#define DPRINTF(sc, class, fmt, ...) do { \ + if (((sc)->sc_debug & (class)) != 0) \ + device_printf((sc)->sc_dev, fmt, ##__VA_ARGS__);\ +} while (0) + +/* + * DLOG_RL: rate-limited device_printf. pps is the cap on how often + * the call actually fires. rlp is a struct myfirst_ratelimit pointer + * stored in the softc. + */ +#define DLOG_RL(sc, rlp, pps, fmt, ...) do { \ + if (ppsratecheck(&(rlp)->rl_lasttime, &(rlp)->rl_curpps, pps)) \ + device_printf((sc)->sc_dev, fmt, ##__VA_ARGS__); \ +} while (0) + +#endif /* _MYFIRST_DEBUG_H_ */ diff --git a/examples/part-05/ch25-advanced/myfirst_ioctl.c b/examples/part-05/ch25-advanced/myfirst_ioctl.c new file mode 100644 index 0000000..502e34c --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_ioctl.c @@ -0,0 +1,68 @@ +/* + * myfirst_ioctl.c - ioctl dispatch for the myfirst driver. + * + * The switch is the driver's entire public ioctl surface. Adding a + * command means adding a case here and the matching declaration in + * myfirst_ioctl.h. Retiring a command means removing its case here + * and marking the number retired in the header. + */ + +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" +#include "myfirst_ioctl.h" + +int +myfirst_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, + struct thread *td) +{ + struct myfirst_softc *sc = dev->si_drv1; + int error = 0; + + DPRINTF(sc, MYF_DBG_IOCTL, "ioctl: cmd=0x%lx\n", cmd); + + switch (cmd) { + case MYFIRSTIOC_GETVER: + *(int *)data = MYFIRST_IOCTL_VERSION; + break; + + case MYFIRSTIOC_RESET: + mtx_lock(&sc->sc_mtx); + sc->sc_total_reads = 0; + sc->sc_total_writes = 0; + mtx_unlock(&sc->sc_mtx); + break; + + case MYFIRSTIOC_GETMSG: + mtx_lock(&sc->sc_mtx); + strlcpy((char *)data, sc->sc_msg, MYFIRST_MSG_MAX); + mtx_unlock(&sc->sc_mtx); + break; + + case MYFIRSTIOC_SETMSG: + mtx_lock(&sc->sc_mtx); + strlcpy(sc->sc_msg, (const char *)data, + sizeof(sc->sc_msg)); + sc->sc_msglen = strlen(sc->sc_msg); + mtx_unlock(&sc->sc_mtx); + devctl_notify("myfirst", device_get_nameunit(sc->sc_dev), + "MSG_CHANGED", NULL); + break; + + case MYFIRSTIOC_GETCAPS: + *(uint32_t *)data = MYF_CAP_RESET | MYF_CAP_GETMSG | + MYF_CAP_SETMSG; + break; + + default: + error = ENOIOCTL; + break; + } + return (error); +} diff --git a/examples/part-05/ch25-advanced/myfirst_ioctl.h b/examples/part-05/ch25-advanced/myfirst_ioctl.h new file mode 100644 index 0000000..e011508 --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_ioctl.h @@ -0,0 +1,39 @@ +/* + * myfirst_ioctl.h - ioctl command numbers and payload structures. + * + * Chapter 25 adds MYFIRSTIOC_GETCAPS (command 5) to the set inherited + * from Chapter 22. Command 4 was reserved during draft work and + * retired before release; do not reuse the number. + * + * Wire format version is 1. Increment MYFIRST_IOCTL_VERSION only for + * genuine breaking changes (removed command, changed payload size or + * layout, changed semantics). Pure additions leave it alone. + */ + +#ifndef _MYFIRST_IOCTL_H_ +#define _MYFIRST_IOCTL_H_ + +#include +#include + +#define MYFIRST_IOCTL_VERSION 1 + +#define MYFIRST_MSG_MAX 256 + +#define MYFIRSTIOC_GETVER _IOR('M', 0, int) +#define MYFIRSTIOC_RESET _IO ('M', 1) +#define MYFIRSTIOC_GETMSG _IOR('M', 2, char[MYFIRST_MSG_MAX]) +#define MYFIRSTIOC_SETMSG _IOW('M', 3, char[MYFIRST_MSG_MAX]) +/* + * Command 4 retired; do not reuse. + */ +#define MYFIRSTIOC_GETCAPS _IOR('M', 5, uint32_t) + +/* Capability bits returned by MYFIRSTIOC_GETCAPS. */ +#define MYF_CAP_RESET (1U << 0) +#define MYF_CAP_GETMSG (1U << 1) +#define MYF_CAP_SETMSG (1U << 2) +#define MYF_CAP_TIMEOUT (1U << 3) /* reserved; not set by 1.8 */ +#define MYF_CAP_STATS (1U << 4) /* reserved for Challenge 8 */ + +#endif /* _MYFIRST_IOCTL_H_ */ diff --git a/examples/part-05/ch25-advanced/myfirst_log.c b/examples/part-05/ch25-advanced/myfirst_log.c new file mode 100644 index 0000000..be80cfa --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_log.c @@ -0,0 +1,34 @@ +/* + * myfirst_log.c - attach/detach helpers for the rate-limit state. + * + * Today myfirst_log_attach does not allocate anything; the rate-limit + * state is embedded by value in the softc, so the helper just zeroes + * the fields. The helper exists as a named label for the attach + * chain and as a seam for future growth: if a later version of the + * driver grows a per-class counter array, the allocation fits here + * without changing the attach function's shape. + */ + +#include +#include +#include +#include + +#include "myfirst.h" + +int +myfirst_log_attach(struct myfirst_softc *sc) +{ + + bzero(&sc->sc_rl_generic, sizeof(sc->sc_rl_generic)); + bzero(&sc->sc_rl_io, sizeof(sc->sc_rl_io)); + bzero(&sc->sc_rl_intr, sizeof(sc->sc_rl_intr)); + return (0); +} + +void +myfirst_log_detach(struct myfirst_softc *sc) +{ + + (void)sc; +} diff --git a/examples/part-05/ch25-advanced/myfirst_log.h b/examples/part-05/ch25-advanced/myfirst_log.h new file mode 100644 index 0000000..d2113ca --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_log.h @@ -0,0 +1,21 @@ +/* + * myfirst_log.h - rate-limit state for Chapter 25's logging discipline. + * + * The struct is embedded by value in the softc. myfirst_log.c does + * the attach and detach bookkeeping. DLOG_RL (defined in + * myfirst_debug.h) is the macro that consumes the state. + */ + +#ifndef _MYFIRST_LOG_H_ +#define _MYFIRST_LOG_H_ + +#include + +struct myfirst_ratelimit { + struct timeval rl_lasttime; + int rl_curpps; +}; + +#define MYF_RL_DEFAULT_PPS 10 + +#endif /* _MYFIRST_LOG_H_ */ diff --git a/examples/part-05/ch25-advanced/myfirst_sysctl.c b/examples/part-05/ch25-advanced/myfirst_sysctl.c new file mode 100644 index 0000000..559b66f --- /dev/null +++ b/examples/part-05/ch25-advanced/myfirst_sysctl.c @@ -0,0 +1,179 @@ +/* + * myfirst_sysctl.c - sysctl tree for the myfirst driver. + * + * Chapter 25 extends the Chapter 24 tree with three new runtime + * knobs: timeout_sec, max_retries, log_ratelimit_pps. Each has a + * matching hw.myfirst.* tunable and a range-validating handler. + * + * The per-device sysctl context is owned by Newbus; the driver does + * not track or destroy it explicitly. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "myfirst.h" +#include "myfirst_debug.h" + +#define MYFIRST_VERSION "1.8-maintenance" + +static int +myfirst_sysctl_message_len(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + u_int len; + + mtx_lock(&sc->sc_mtx); + len = (u_int)sc->sc_msglen; + mtx_unlock(&sc->sc_mtx); + + return (sysctl_handle_int(oidp, &len, 0, req)); +} + +static int +myfirst_sysctl_timeout_sec(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + u_int new_val; + int error; + + mtx_lock(&sc->sc_mtx); + new_val = sc->sc_timeout_sec; + mtx_unlock(&sc->sc_mtx); + + error = sysctl_handle_int(oidp, &new_val, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + if (new_val < 1 || new_val > 60) + return (EINVAL); + + mtx_lock(&sc->sc_mtx); + sc->sc_timeout_sec = new_val; + mtx_unlock(&sc->sc_mtx); + return (0); +} + +static int +myfirst_sysctl_max_retries(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + u_int new_val; + int error; + + mtx_lock(&sc->sc_mtx); + new_val = sc->sc_max_retries; + mtx_unlock(&sc->sc_mtx); + + error = sysctl_handle_int(oidp, &new_val, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + if (new_val < 1 || new_val > 100) + return (EINVAL); + + mtx_lock(&sc->sc_mtx); + sc->sc_max_retries = new_val; + mtx_unlock(&sc->sc_mtx); + return (0); +} + +static int +myfirst_sysctl_log_pps(SYSCTL_HANDLER_ARGS) +{ + struct myfirst_softc *sc = arg1; + u_int new_val; + int error; + + mtx_lock(&sc->sc_mtx); + new_val = sc->sc_log_pps; + mtx_unlock(&sc->sc_mtx); + + error = sysctl_handle_int(oidp, &new_val, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + if (new_val < 1 || new_val > 10000) + return (EINVAL); + + mtx_lock(&sc->sc_mtx); + sc->sc_log_pps = new_val; + mtx_unlock(&sc->sc_mtx); + return (0); +} + +void +myfirst_sysctl_attach(struct myfirst_softc *sc) +{ + device_t dev = sc->sc_dev; + struct sysctl_ctx_list *ctx; + struct sysctl_oid *tree; + struct sysctl_oid_list *child; + struct sysctl_oid *debug_node; + struct sysctl_oid_list *debug_child; + + ctx = device_get_sysctl_ctx(dev); + tree = device_get_sysctl_tree(dev); + child = SYSCTL_CHILDREN(tree); + + SYSCTL_ADD_STRING(ctx, child, OID_AUTO, "version", + CTLFLAG_RD, MYFIRST_VERSION, 0, + "Driver version string"); + + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "open_count", + CTLFLAG_RD, &sc->sc_open_count, 0, + "Number of currently open file descriptors"); + + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "total_reads", + CTLFLAG_RD, &sc->sc_total_reads, 0, + "Total read() calls since attach"); + + SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "total_writes", + CTLFLAG_RD, &sc->sc_total_writes, 0, + "Total write() calls since attach"); + + SYSCTL_ADD_STRING(ctx, child, OID_AUTO, "message", + CTLFLAG_RD, sc->sc_msg, sizeof(sc->sc_msg), + "Current in-driver message"); + + SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "message_len", + CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_message_len, "IU", + "Current length of the in-driver message in bytes"); + + SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "timeout_sec", + CTLTYPE_UINT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_timeout_sec, "IU", + "Operation timeout in seconds (range 1-60)"); + + SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "max_retries", + CTLTYPE_UINT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_max_retries, "IU", + "Maximum retry count (range 1-100)"); + + SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "log_ratelimit_pps", + CTLTYPE_UINT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, + sc, 0, myfirst_sysctl_log_pps, "IU", + "Rate-limit ceiling in messages per second (range 1-10000)"); + + debug_node = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "debug", + CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, + "Debug controls and class enumeration"); + debug_child = SYSCTL_CHILDREN(debug_node); + + SYSCTL_ADD_UINT(ctx, debug_child, OID_AUTO, "mask", + CTLFLAG_RWTUN, &sc->sc_debug, 0, + "Bitmask of enabled debug classes"); + + SYSCTL_ADD_STRING(ctx, debug_child, OID_AUTO, "classes", + CTLFLAG_RD, + "INIT(0x1) OPEN(0x2) IO(0x4) IOCTL(0x8) " + "INTR(0x10) DMA(0x20) PWR(0x40) MEM(0x80)", + 0, "Names and bit values of debug classes"); +} diff --git a/examples/part-06/ch26-usb-serial/Makefile b/examples/part-06/ch26-usb-serial/Makefile new file mode 100644 index 0000000..454dd37 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/Makefile @@ -0,0 +1,23 @@ +# Makefile for myfirst_usb - Chapter 26 (USB and Serial Drivers). +# +# Builds the chapter's reference USB driver module, myfirst_usb.ko, +# which demonstrates the USB transfer framework, the probe/attach +# lifecycle, and the labelled-goto cleanup chain applied to USB. +# +# The companion file myfirst_usb.h declares the softc and transfer +# indices; myfirst_usb.c implements the Newbus methods and the +# three-state callback state machine for bulk and interrupt transfers. + +KMOD= myfirst_usb +SRCS= myfirst_usb.c + +CFLAGS+= -I${.CURDIR} + +# Needed for usb_if.h, usbdi.h, and related headers. +SRCS+= usb_if.h +SRCS+= device_if.h +SRCS+= bus_if.h + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-06/ch26-usb-serial/lab01-explore-usb/explore.sh b/examples/part-06/ch26-usb-serial/lab01-explore-usb/explore.sh new file mode 100755 index 0000000..a57159c --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab01-explore-usb/explore.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# +# explore.sh - Dump descriptors for all attached USB devices. +# +# For each ugenN.M device listed by usbconfig(8), print the device +# descriptor, configuration descriptor, and string descriptors. + +set -eu + +for dev in $(usbconfig list | awk '/^ugen/ {print $1}' | tr -d ':'); do + echo "==================== ${dev} ====================" + usbconfig -d "${dev}" dump_device_desc || true + echo "------ current config ------" + usbconfig -d "${dev}" dump_curr_config_desc || true + echo "------ strings ------" + usbconfig -d "${dev}" dump_string 0x00 || true + usbconfig -d "${dev}" dump_string 0x01 || true + usbconfig -d "${dev}" dump_string 0x02 || true + usbconfig -d "${dev}" dump_string 0x03 || true + echo +done diff --git a/examples/part-06/ch26-usb-serial/lab03-bulk-loopback/test_echo.sh b/examples/part-06/ch26-usb-serial/lab03-bulk-loopback/test_echo.sh new file mode 100755 index 0000000..3251c4f --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab03-bulk-loopback/test_echo.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# +# test_echo.sh - Minimal test for the bulk-loopback driver. +# +# Writes a short string to /dev/myfirst_usb0 and reads the result +# back. Exits 0 on match, 1 on mismatch. + +set -eu + +DEV=${DEV:-/dev/myfirst_usb0} +MSG=${MSG:-"hello usb"} + +if [ ! -c "${DEV}" ]; then + echo "Device ${DEV} not present. Is the driver loaded and the" + echo "test hardware plugged in?" + exit 2 +fi + +echo "${MSG}" > "${DEV}" + +# Read back up to len(MSG)+1 bytes. Allow short read. +got=$(dd if="${DEV}" bs=1 count=$((${#MSG}+1)) 2>/dev/null | tr -d '\n') + +if [ "${got}" = "${MSG}" ]; then + echo "OK: echo loopback returned '${got}'" + exit 0 +else + echo "FAIL: sent '${MSG}' got '${got}'" + exit 1 +fi diff --git a/examples/part-06/ch26-usb-serial/lab04-simulated-serial/test_nmdm.sh b/examples/part-06/ch26-usb-serial/lab04-simulated-serial/test_nmdm.sh new file mode 100755 index 0000000..57b0aa4 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab04-simulated-serial/test_nmdm.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# +# test_nmdm.sh - Exercise an nmdm(4) virtual serial pair. + +set -eu + +if ! kldstat -qm nmdm >/dev/null 2>&1; then + echo "Loading nmdm module" + kldload nmdm +fi + +A=/dev/nmdm0.A +B=/dev/nmdm0.B + +# Open the B end in a background reader. +( cat "${B}" > /tmp/nmdm0.B.out ) & +READER=$! + +sleep 1 + +echo "hello from A" > "${A}" +echo "another line" > "${A}" + +sleep 1 +kill "${READER}" 2>/dev/null || true + +echo "B end received:" +cat /tmp/nmdm0.B.out diff --git a/examples/part-06/ch26-usb-serial/lab05-cu-test/loopback.sh b/examples/part-06/ch26-usb-serial/lab05-cu-test/loopback.sh new file mode 100755 index 0000000..2dbb4c8 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab05-cu-test/loopback.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# +# loopback.sh - Exercise a USB-to-serial loopback. +# +# Assumes a loopback cable (TX->RX) on /dev/cuaU0. + +set -eu + +DEV=${DEV:-/dev/cuaU0} +SPEED=${SPEED:-9600} +MSG=${MSG:-"loopback test"} + +if [ ! -c "${DEV}" ]; then + echo "Device ${DEV} not present" + exit 2 +fi + +stty -f "${DEV}" "${SPEED}" cs8 -parenb -cstopb + +# Reader first. +( dd if="${DEV}" bs=1 count=${#MSG} 2>/dev/null > /tmp/loopback.out ) & +READER=$! + +sleep 1 + +echo "${MSG}" > "${DEV}" + +sleep 1 +wait "${READER}" 2>/dev/null || true + +got=$(cat /tmp/loopback.out) +if [ "${got}" = "${MSG}" ]; then + echo "OK: loopback returned '${got}'" + exit 0 +else + echo "FAIL: sent '${MSG}' got '${got}'" + exit 1 +fi diff --git a/examples/part-06/ch26-usb-serial/lab06-hotplug/watch.sh b/examples/part-06/ch26-usb-serial/lab06-hotplug/watch.sh new file mode 100755 index 0000000..be59150 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab06-hotplug/watch.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# +# watch.sh - Tail /var/log/messages filtered to USB events. + +DUR=${DUR:-60} + +echo "Watching /var/log/messages for USB events for ${DUR} seconds." +echo "Plug/unplug USB devices to generate events." + +timeout "${DUR}" tail -F /var/log/messages | grep -iE 'usb|ugen|uftdi|uplcom|uslcom|myfirst_usb|uhub' diff --git a/examples/part-06/ch26-usb-serial/lab07-ucom-skeleton/ucom_outline.c b/examples/part-06/ch26-usb-serial/lab07-ucom-skeleton/ucom_outline.c new file mode 100644 index 0000000..942eccb --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab07-ucom-skeleton/ucom_outline.c @@ -0,0 +1,125 @@ +/* + * ucom_outline.c - Skeleton structure for a ucom(4)-based USB driver. + * + * This file is illustrative only. It is not complete, does not + * compile as-is, and is intended to be studied alongside uftdi.c. + * + * The purpose is to show where each ucom_callback entry goes in + * relation to the rest of the driver, and to make clear the + * separation between USB transfer callbacks (the three-state + * state machine) and ucom configuration callbacks (one-shot + * calls issued by the framework). + * + * The real struct ucom_callback is defined in + * /usr/src/sys/dev/usb/serial/usb_serial.h and contains more + * methods than are shown here (for example ucom_cfg_get_status, + * ucom_cfg_set_ring, ucom_ioctl, ucom_tty_name, ucom_poll, + * and ucom_free). This skeleton implements only the commonly + * required subset to keep the outline readable. + */ + +#include +#include +#include +#include +#include +#include +/* #include -- provides ucom API */ + +#if 0 /* outline only */ + +struct my_softc { + device_t sc_dev; + struct usb_device *sc_udev; + struct mtx sc_mtx; + struct ucom_softc sc_ucom; + struct usb_xfer *sc_xfer[N_CHANNELS]; + /* chip-specific fields */ +}; + +static void +my_ucom_cfg_open(struct ucom_softc *ucom) +{ + /* Issue chip-specific init via control transfer. */ +} + +static void +my_ucom_cfg_close(struct ucom_softc *ucom) +{ + /* Issue chip-specific teardown. */ +} + +static int +my_ucom_pre_param(struct ucom_softc *ucom, struct termios *t) +{ + /* Validate termios. Reject unsupported baud rates with EINVAL. */ + return (0); +} + +static void +my_ucom_cfg_param(struct ucom_softc *ucom, struct termios *t) +{ + /* + * Translate the termios settings into a vendor-specific USB + * control transfer and issue it through the ucom framework. + * + * This is the heart of a ucom driver. Every chip has its own + * command set, but the ingest point for userland 'stty' calls + * is uniformly this function. + */ +} + +static void +my_ucom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) +{ + /* Issue a control transfer that asserts/clears DTR. */ +} + +static void +my_ucom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) +{ + /* Issue a control transfer that asserts/clears RTS. */ +} + +static void +my_ucom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) +{ + /* Issue a control transfer that starts/stops a break condition. */ +} + +static const struct ucom_callback my_callback = { + .ucom_cfg_open = &my_ucom_cfg_open, + .ucom_cfg_close = &my_ucom_cfg_close, + .ucom_pre_param = &my_ucom_pre_param, + .ucom_cfg_param = &my_ucom_cfg_param, + .ucom_cfg_set_dtr = &my_ucom_cfg_set_dtr, + .ucom_cfg_set_rts = &my_ucom_cfg_set_rts, + .ucom_cfg_set_break = &my_ucom_cfg_set_break, + .ucom_start_read = &my_start_read, + .ucom_stop_read = &my_stop_read, + .ucom_start_write = &my_start_write, + .ucom_stop_write = &my_stop_write, +}; + +static int +my_attach(device_t dev) +{ + /* + * Standard attach: init mutex, call usbd_transfer_setup, then + * ucom_attach with sc, callback, and method count. Last step is + * ucom_set_pnpinfo_usb to register for matching. + */ + return (0); +} + +static int +my_detach(device_t dev) +{ + /* + * Detach order: ucom_detach first (stops new opens and the TTY + * side), then usbd_transfer_unsetup, then mtx_destroy. + */ + return (0); +} + +#endif /* outline only */ diff --git a/examples/part-06/ch26-usb-serial/lab08-tty-troubleshoot/diagnose.sh b/examples/part-06/ch26-usb-serial/lab08-tty-troubleshoot/diagnose.sh new file mode 100755 index 0000000..f75d934 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab08-tty-troubleshoot/diagnose.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# +# diagnose.sh - Compare termios settings on both ends of a TTY pair. + +set -eu + +A=${A:-/dev/nmdm0.A} +B=${B:-/dev/nmdm0.B} + +if [ ! -c "${A}" ] || [ ! -c "${B}" ]; then + echo "One of ${A}, ${B} is missing. Load nmdm and open the pair." + exit 2 +fi + +echo "=== A: ${A} ===" +stty -a -f "${A}" +echo +echo "=== B: ${B} ===" +stty -a -f "${B}" +echo +echo "=== Diff ===" +diff -u \ + <(stty -a -f "${A}" | tr ';' '\n' | sort) \ + <(stty -a -f "${B}" | tr ';' '\n' | sort) || true diff --git a/examples/part-06/ch26-usb-serial/lab09-usb-stats/watch_usb.sh b/examples/part-06/ch26-usb-serial/lab09-usb-stats/watch_usb.sh new file mode 100755 index 0000000..5759620 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/lab09-usb-stats/watch_usb.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# +# watch_usb.sh - Sample USB transfer stats periodically. + +set -eu + +DEV=${DEV:-ugen0.2} +PERIOD=${PERIOD:-5} + +while :; do + echo "=== $(date) ===" + usbconfig -d "${DEV}" dump_stats 2>/dev/null || true + sleep "${PERIOD}" +done diff --git a/examples/part-06/ch26-usb-serial/myfirst_usb.c b/examples/part-06/ch26-usb-serial/myfirst_usb.c new file mode 100644 index 0000000..3a7f3a2 --- /dev/null +++ b/examples/part-06/ch26-usb-serial/myfirst_usb.c @@ -0,0 +1,279 @@ +/* + * myfirst_usb.c - Chapter 26 reference USB driver. + * + * This driver is the companion to the USB walkthrough in Section 2 + * of Chapter 26. It declares bulk IN, bulk OUT, and interrupt IN + * channels, and implements the three-state callback state machine + * for each one. It is intentionally minimal: no /dev node, no + * user-facing configuration. The goal is to give readers a working + * skeleton they can extend. + * + * To bind this driver to a specific device, edit myfirst_usb_devs[] + * below and replace the placeholder VID/PID with the values from + * your test hardware. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "myfirst_usb.h" + +/* Debug printouts. Toggle via hw.usb.myfirst_usb.debug sysctl if you + * extend the driver with a sysctl tree; for now this is a compile-time + * flag. */ +#ifndef MYFIRST_USB_DEBUG +#define MYFIRST_USB_DEBUG 0 +#endif + +#define DPRINTFN(n, ...) do { \ + if (MYFIRST_USB_DEBUG >= (n)) \ + printf("myfirst_usb: " __VA_ARGS__); \ +} while (0) + +/* + * Match table. + * + * Replace the vendor and product values with those of the USB device + * you intend to bind this driver to. As shipped, the entry uses a + * nonexistent VID/PID so the driver does not accidentally bind to + * a real device during testing. + */ +static const STRUCT_USB_HOST_ID myfirst_usb_devs[] = { + {USB_VPI(0xffff, 0xffff, 0)}, /* placeholder */ +}; + +/* Forward declarations. */ +static device_probe_t myfirst_usb_probe; +static device_attach_t myfirst_usb_attach; +static device_detach_t myfirst_usb_detach; + +static usb_callback_t myfirst_usb_bulk_read_callback; +static usb_callback_t myfirst_usb_bulk_write_callback; +static usb_callback_t myfirst_usb_intr_read_callback; + +/* + * Transfer configuration. + * + * The framework uses this array to allocate and manage the driver's + * USB channels. Buffer sizes are sized for typical experiments. + */ +static const struct usb_config myfirst_usb_config[MYFIRST_USB_N_TRANSFER] = { + [MYFIRST_USB_BULK_DT_RD] = { + .type = UE_BULK, + .endpoint = UE_ADDR_ANY, + .direction = UE_DIR_IN, + .bufsize = MYFIRST_USB_BULK_BUFSZ, + .flags = {.pipe_bof = 1, .short_xfer_ok = 1}, + .callback = &myfirst_usb_bulk_read_callback, + }, + [MYFIRST_USB_BULK_DT_WR] = { + .type = UE_BULK, + .endpoint = UE_ADDR_ANY, + .direction = UE_DIR_OUT, + .bufsize = MYFIRST_USB_BULK_BUFSZ, + .flags = {.pipe_bof = 1, .force_short_xfer = 1}, + .callback = &myfirst_usb_bulk_write_callback, + }, + [MYFIRST_USB_INTR_DT_RD] = { + .type = UE_INTERRUPT, + .endpoint = UE_ADDR_ANY, + .direction = UE_DIR_IN, + .bufsize = MYFIRST_USB_INTR_BUFSZ, + .flags = {.pipe_bof = 1, .short_xfer_ok = 1}, + .callback = &myfirst_usb_intr_read_callback, + }, +}; + +static int +myfirst_usb_probe(device_t dev) +{ + struct usb_attach_arg *uaa = device_get_ivars(dev); + + if (uaa->usb_mode != USB_MODE_HOST) + return (ENXIO); + if (uaa->info.bConfigIndex != 0) + return (ENXIO); + if (uaa->info.bIfaceIndex != 0) + return (ENXIO); + + return (usbd_lookup_id_by_uaa(myfirst_usb_devs, + sizeof(myfirst_usb_devs), uaa)); +} + +static int +myfirst_usb_attach(device_t dev) +{ + struct myfirst_usb_softc *sc = device_get_softc(dev); + struct usb_attach_arg *uaa = device_get_ivars(dev); + int error; + + sc->sc_dev = dev; + sc->sc_udev = uaa->device; + sc->sc_iface_index = uaa->info.bIfaceIndex; + + mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); + + error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, + sc->sc_xfer, myfirst_usb_config, MYFIRST_USB_N_TRANSFER, + sc, &sc->sc_mtx); + if (error != 0) { + device_printf(dev, "usbd_transfer_setup failed: %d\n", error); + goto fail_mtx; + } + + device_set_desc(dev, "myfirst USB skeleton"); + return (0); + +fail_mtx: + mtx_destroy(&sc->sc_mtx); + return (ENXIO); +} + +static int +myfirst_usb_detach(device_t dev) +{ + struct myfirst_usb_softc *sc = device_get_softc(dev); + + MYFIRST_USB_LOCK(sc); + sc->sc_flags |= MYFIRST_USB_FLAG_DETACHING; + MYFIRST_USB_UNLOCK(sc); + + usbd_transfer_unsetup(sc->sc_xfer, MYFIRST_USB_N_TRANSFER); + mtx_destroy(&sc->sc_mtx); + + return (0); +} + +/* + * Bulk IN callback. + * + * On transfer completion, this example discards the received bytes. + * Extend by copying them out with usbd_copy_out and forwarding them + * to a consumer (for example, a character device's read queue). + */ +static void +myfirst_usb_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) +{ + struct myfirst_usb_softc *sc = usbd_xfer_softc(xfer); + int actlen; + + usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); + + switch (USB_GET_STATE(xfer)) { + case USB_ST_TRANSFERRED: + DPRINTFN(2, "bulk in completed: %d bytes\n", actlen); + /* FALLTHROUGH */ + case USB_ST_SETUP: +tr_setup: + if (sc->sc_flags & MYFIRST_USB_FLAG_READ_STALL) { + /* Would clear the stall here in a full driver. */ + } + usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); + usbd_transfer_submit(xfer); + break; + + default: /* USB_ST_ERROR */ + if (error == USB_ERR_CANCELLED) + return; + sc->sc_flags |= MYFIRST_USB_FLAG_READ_STALL; + goto tr_setup; + } +} + +/* + * Bulk OUT callback. + * + * On USB_ST_SETUP this example submits a short zero-filled buffer + * just so the callback is observable during testing. Extend by + * pulling a buffer from a producer (for example, a character + * device's write queue). + */ +static void +myfirst_usb_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) +{ + struct myfirst_usb_softc *sc = usbd_xfer_softc(xfer); + struct usb_page_cache *pc; + + switch (USB_GET_STATE(xfer)) { + case USB_ST_TRANSFERRED: + DPRINTFN(2, "bulk out completed\n"); + /* FALLTHROUGH */ + case USB_ST_SETUP: +tr_setup: + if (sc->sc_flags & MYFIRST_USB_FLAG_WRITE_STALL) { + /* Would clear the stall here in a full driver. */ + } + pc = usbd_xfer_get_frame(xfer, 0); + usbd_frame_zero(pc, 0, 16); + usbd_xfer_set_frame_len(xfer, 0, 16); + usbd_transfer_submit(xfer); + break; + + default: /* USB_ST_ERROR */ + if (error == USB_ERR_CANCELLED) + return; + sc->sc_flags |= MYFIRST_USB_FLAG_WRITE_STALL; + goto tr_setup; + } +} + +/* + * Interrupt IN callback. + * + * Runs continuously once started. On completion, the received bytes + * would typically be handed to a status consumer. + */ +static void +myfirst_usb_intr_read_callback(struct usb_xfer *xfer, usb_error_t error) +{ + int actlen; + + usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); + + switch (USB_GET_STATE(xfer)) { + case USB_ST_TRANSFERRED: + DPRINTFN(2, "intr in: %d bytes\n", actlen); + /* FALLTHROUGH */ + case USB_ST_SETUP: + usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); + usbd_transfer_submit(xfer); + break; + + default: /* USB_ST_ERROR */ + if (error == USB_ERR_CANCELLED) + return; + /* Rearm on non-cancellation errors. */ + usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); + usbd_transfer_submit(xfer); + break; + } +} + +static device_method_t myfirst_usb_methods[] = { + DEVMETHOD(device_probe, myfirst_usb_probe), + DEVMETHOD(device_attach, myfirst_usb_attach), + DEVMETHOD(device_detach, myfirst_usb_detach), + + DEVMETHOD_END +}; + +static driver_t myfirst_usb_driver = { + "myfirst_usb", + myfirst_usb_methods, + sizeof(struct myfirst_usb_softc), +}; + +DRIVER_MODULE(myfirst_usb, uhub, myfirst_usb_driver, NULL, NULL); +MODULE_DEPEND(myfirst_usb, usb, 1, 1, 1); +MODULE_VERSION(myfirst_usb, 1); +USB_PNP_HOST_INFO(myfirst_usb_devs); diff --git a/examples/part-06/ch26-usb-serial/myfirst_usb.h b/examples/part-06/ch26-usb-serial/myfirst_usb.h new file mode 100644 index 0000000..eddb59a --- /dev/null +++ b/examples/part-06/ch26-usb-serial/myfirst_usb.h @@ -0,0 +1,48 @@ +/* + * myfirst_usb.h - Chapter 26 reference USB driver header. + * + * Declares the softc structure, transfer indices, and public + * prototypes for the myfirst_usb driver. The driver is a thin + * skeleton with bulk IN, bulk OUT, and interrupt IN channels + * suitable for experiments with a USB gadget-mode peer or with + * a programmable USB device running matching firmware. + */ + +#ifndef _MYFIRST_USB_H_ +#define _MYFIRST_USB_H_ + +/* Transfer indices. Keep in sync with myfirst_usb_config[] in myfirst_usb.c. */ +enum { + MYFIRST_USB_BULK_DT_RD = 0, + MYFIRST_USB_BULK_DT_WR, + MYFIRST_USB_INTR_DT_RD, + MYFIRST_USB_N_TRANSFER, +}; + +/* + * Per-device software context. + * + * Every field below is protected by sc_mtx except for sc_udev and + * sc_dev, which are set once during attach and never changed. + */ +struct myfirst_usb_softc { + device_t sc_dev; + struct usb_device *sc_udev; + struct mtx sc_mtx; + struct usb_xfer *sc_xfer[MYFIRST_USB_N_TRANSFER]; + uint8_t sc_iface_index; + uint8_t sc_flags; +#define MYFIRST_USB_FLAG_DETACHING 0x01 +#define MYFIRST_USB_FLAG_READ_STALL 0x02 +#define MYFIRST_USB_FLAG_WRITE_STALL 0x04 +}; + +#define MYFIRST_USB_LOCK(sc) mtx_lock(&(sc)->sc_mtx) +#define MYFIRST_USB_UNLOCK(sc) mtx_unlock(&(sc)->sc_mtx) +#define MYFIRST_USB_LOCK_ASSERT(sc) mtx_assert(&(sc)->sc_mtx, MA_OWNED) + +/* Buffer sizes. Large enough for typical bulk activity without excess. */ +#define MYFIRST_USB_BULK_BUFSZ 4096 +#define MYFIRST_USB_INTR_BUFSZ 64 + +#endif /* _MYFIRST_USB_H_ */ diff --git a/examples/part-06/ch26-usb-serial/shared/check_env.sh b/examples/part-06/ch26-usb-serial/shared/check_env.sh new file mode 100755 index 0000000..d27030e --- /dev/null +++ b/examples/part-06/ch26-usb-serial/shared/check_env.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# +# check_env.sh - Verify the lab environment has what Chapter 26 needs. + +set -eu + +ok=1 + +echo "Checking userland utilities..." +for cmd in usbconfig stty cu tip dtrace kldstat kldload; do + if command -v "${cmd}" >/dev/null 2>&1; then + echo " OK: ${cmd}" + else + echo " MISSING: ${cmd}" + ok=0 + fi +done + +echo +echo "Checking kernel modules (loadable on demand)..." +for mod in usb uhci ohci ehci xhci uhub nmdm ucom; do + if kldstat -qm "${mod}" >/dev/null 2>&1; then + echo " OK: ${mod} (loaded)" + else + if kldload -n "${mod}" 2>/dev/null; then + echo " OK: ${mod} (available)" + else + echo " NOT AVAILABLE: ${mod}" + fi + fi +done + +echo +echo "Checking kernel sources..." +if [ -d /usr/src/sys/dev/usb ]; then + echo " OK: /usr/src/sys/dev/usb exists" +else + echo " MISSING: /usr/src/sys/dev/usb. Install via git or svnlite." + ok=0 +fi +if [ -d /usr/src/sys/dev/uart ]; then + echo " OK: /usr/src/sys/dev/uart exists" +else + echo " MISSING: /usr/src/sys/dev/uart. Install via git or svnlite." + ok=0 +fi + +echo +if [ "${ok}" = "1" ]; then + echo "Environment looks good for Chapter 26 labs." + exit 0 +else + echo "Environment is missing one or more required pieces." + exit 1 +fi diff --git a/examples/part-06/ch27-storage-vfs/Makefile b/examples/part-06/ch27-storage-vfs/Makefile new file mode 100644 index 0000000..f4dd362 --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/Makefile @@ -0,0 +1,15 @@ +# Makefile for myfirst_blk - Chapter 27 (Storage Devices and VFS). +# +# Builds the chapter's reference pseudo block device driver, +# myblk.ko, which demonstrates the g_disk registration path, a +# complete BIO handler, a flat-buffer backing store, and safe +# load/unload lifecycle. + +KMOD= myblk +SRCS= myfirst_blk.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-06/ch27-storage-vfs/lab01-explore-geom/explore.sh b/examples/part-06/ch27-storage-vfs/lab01-explore-geom/explore.sh new file mode 100755 index 0000000..4d84937 --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/lab01-explore-geom/explore.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# +# explore.sh - Dump the current GEOM topology to a text file. +# +# Produces a human-readable inventory suitable for later comparison +# before and after loading new GEOM classes. + +set -eu + +echo "==================== geom -t ====================" +geom -t || true +echo + +echo "==================== geom disk list ====================" +geom disk list || true +echo + +echo "==================== geom provider list ====================" +geom provider list || true +echo + +echo "==================== gstat snapshot (1s) ====================" +gstat -b -d -I 1s || true +echo + +echo "==================== kldstat ====================" +kldstat || true diff --git a/examples/part-06/ch27-storage-vfs/lab11-measure-blocksize/measure.sh b/examples/part-06/ch27-storage-vfs/lab11-measure-blocksize/measure.sh new file mode 100755 index 0000000..5c578e3 --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/lab11-measure-blocksize/measure.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# +# measure.sh - Sweep transfer sizes and record rough throughput. +# +# Outputs CSV lines of the form: +# ,,, +# +# Requires /dev/myblk0 to exist and not be mounted. + +set -eu + +DEVICE=${DEVICE:-/dev/myblk0} +TOTAL=${TOTAL:-$((32 * 1024 * 1024))} + +if [ ! -c "${DEVICE}" ]; then + echo "${DEVICE} not found" >&2 + exit 1 +fi + +echo "op,bs,count,duration_s,bytes" + +for bs in 512 4096 16384 65536 262144 1048576; do + count=$((TOTAL / bs)) + start=$(date +%s.%N) + dd if=/dev/zero of="${DEVICE}" bs=${bs} count=${count} \ + conv=fsync 2>/dev/null + end=$(date +%s.%N) + duration=$(echo "${end} - ${start}" | bc) + echo "WRITE,${bs},${count},${duration},${TOTAL}" + + start=$(date +%s.%N) + dd if="${DEVICE}" of=/dev/null bs=${bs} count=${count} \ + 2>/dev/null + end=$(date +%s.%N) + duration=$(echo "${end} - ${start}" | bc) + echo "READ,${bs},${count},${duration},${TOTAL}" +done diff --git a/examples/part-06/ch27-storage-vfs/lab12-race-test/race.sh b/examples/part-06/ch27-storage-vfs/lab12-race-test/race.sh new file mode 100755 index 0000000..54947cd --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/lab12-race-test/race.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# +# race.sh - Stress test with concurrent readers and writers. +# +# Spawns background dd processes and lets them run for a fixed +# duration. Useful for exercising lock discipline. + +set -eu + +DEVICE=${DEVICE:-/dev/myblk0} +DURATION=${DURATION:-10} + +if [ ! -c "${DEVICE}" ]; then + echo "${DEVICE} not found" >&2 + exit 1 +fi + +echo "Launching 4 writers and 4 readers against ${DEVICE}..." +pids="" +for i in 1 2 3 4; do + dd if=/dev/urandom of="${DEVICE}" bs=4096 count=999999 \ + >/dev/null 2>&1 & + pids="${pids} $!" + dd if="${DEVICE}" of=/dev/null bs=4096 count=999999 \ + >/dev/null 2>&1 & + pids="${pids} $!" +done + +echo "Running for ${DURATION} seconds..." +sleep "${DURATION}" + +echo "Stopping..." +for p in ${pids}; do + kill -TERM "${p}" 2>/dev/null || true +done +wait 2>/dev/null || true + +echo "Done. Check gstat and geom disk list for anomalies." diff --git a/examples/part-06/ch27-storage-vfs/myfirst_blk.c b/examples/part-06/ch27-storage-vfs/myfirst_blk.c new file mode 100644 index 0000000..56fd473 --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/myfirst_blk.c @@ -0,0 +1,204 @@ +/* + * myfirst_blk.c - a pseudo block device driver. + * + * Companion source for Chapter 27 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery". + * + * This driver registers a single pseudo disk called myblk0 with + * the g_disk subsystem. It serves BIO requests out of a flat + * kernel memory buffer whose size is set by MYBLK_MEDIASIZE. + * Compare with /usr/src/sys/dev/md/md.c for a production-grade + * pseudo block device driver. + * + * The chapter develops this driver in three steps: + * + * Section 3: registration skeleton (no I/O yet). + * Section 4: GEOM-backed provider integration. + * Section 5: strategy function with a flat backing store. + * + * The file below is the Section 5 version. Earlier sections of + * the chapter use intermediate forms kept inside the chapter + * prose; this file is the ready-to-compile final form. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define MYBLK_NAME "myblk" +#define MYBLK_SECTOR 512 +#define MYBLK_MEDIASIZE (32ULL * 1024 * 1024) /* 32 MiB */ + +struct myblk_softc { + struct disk *disk; + struct mtx lock; + u_int unit; + uint8_t *backing; + size_t backing_size; +}; + +static MALLOC_DEFINE(M_MYBLK, "myblk", "myfirst_blk driver state"); + +static struct myblk_softc *myblk_unit0; + +static void +myblk_strategy(struct bio *bp) +{ + struct myblk_softc *sc; + off_t offset; + size_t len; + + sc = bp->bio_disk->d_drv1; + offset = bp->bio_offset; + len = bp->bio_bcount; + + /* Defensive range check. GEOM will not normally send us */ + /* out-of-range requests, but a cheap guard prevents any */ + /* upstream bug from corrupting kernel memory. */ + if (offset < 0 || + (size_t)offset > sc->backing_size || + len > sc->backing_size - (size_t)offset) { + bp->bio_error = EIO; + bp->bio_flags |= BIO_ERROR; + bp->bio_resid = len; + biodone(bp); + return; + } + + switch (bp->bio_cmd) { + case BIO_READ: + mtx_lock(&sc->lock); + memcpy(bp->bio_data, sc->backing + offset, len); + mtx_unlock(&sc->lock); + bp->bio_resid = 0; + break; + + case BIO_WRITE: + mtx_lock(&sc->lock); + memcpy(sc->backing + offset, bp->bio_data, len); + mtx_unlock(&sc->lock); + bp->bio_resid = 0; + break; + + case BIO_DELETE: + mtx_lock(&sc->lock); + memset(sc->backing + offset, 0, len); + mtx_unlock(&sc->lock); + bp->bio_resid = 0; + break; + + case BIO_FLUSH: + /* + * Backing store is RAM. No ordering work is needed. + */ + bp->bio_resid = 0; + break; + + default: + bp->bio_error = EOPNOTSUPP; + bp->bio_flags |= BIO_ERROR; + bp->bio_resid = len; + break; + } + + biodone(bp); +} + +static int +myblk_attach_unit(struct myblk_softc *sc) +{ + + sc->backing_size = MYBLK_MEDIASIZE; + sc->backing = malloc(sc->backing_size, M_MYBLK, + M_WAITOK | M_ZERO); + + sc->disk = disk_alloc(); + sc->disk->d_name = MYBLK_NAME; + sc->disk->d_unit = sc->unit; + sc->disk->d_strategy = myblk_strategy; + sc->disk->d_sectorsize = MYBLK_SECTOR; + sc->disk->d_mediasize = MYBLK_MEDIASIZE; + sc->disk->d_maxsize = MAXPHYS; + sc->disk->d_flags = DISKFLAG_CANDELETE | + DISKFLAG_CANFLUSHCACHE; + sc->disk->d_drv1 = sc; + + disk_create(sc->disk, DISK_VERSION); + return (0); +} + +static void +myblk_detach_unit(struct myblk_softc *sc) +{ + + /* + * Order matters. Destroy the disk first to guarantee no + * BIO is in flight, then free the backing store. + */ + if (sc->disk != NULL) { + disk_destroy(sc->disk); + sc->disk = NULL; + } + if (sc->backing != NULL) { + free(sc->backing, M_MYBLK); + sc->backing = NULL; + sc->backing_size = 0; + } +} + +static int +myblk_loader(struct module *m, int what, void *arg) +{ + struct myblk_softc *sc; + int error; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_MYBLK, M_WAITOK | M_ZERO); + mtx_init(&sc->lock, "myblk lock", NULL, MTX_DEF); + sc->unit = 0; + error = myblk_attach_unit(sc); + if (error != 0) { + mtx_destroy(&sc->lock); + free(sc, M_MYBLK); + return (error); + } + myblk_unit0 = sc; + printf("myblk: loaded, /dev/%s%u size=%jd bytes\n", + MYBLK_NAME, sc->unit, + (intmax_t)sc->disk->d_mediasize); + return (0); + + case MOD_UNLOAD: + sc = myblk_unit0; + if (sc == NULL) + return (0); + myblk_detach_unit(sc); + mtx_destroy(&sc->lock); + free(sc, M_MYBLK); + myblk_unit0 = NULL; + printf("myblk: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t myblk_mod = { + "myblk", + myblk_loader, + NULL +}; + +DECLARE_MODULE(myblk, myblk_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(myblk, 1); +MODULE_DEPEND(myblk, g_disk, 0, 0, 0); diff --git a/examples/part-06/ch27-storage-vfs/shared/check_env.sh b/examples/part-06/ch27-storage-vfs/shared/check_env.sh new file mode 100755 index 0000000..b9606fe --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/shared/check_env.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# +# check_env.sh - Verify the lab environment has what Chapter 27 needs. + +set -eu + +ok=1 + +echo "Checking userland utilities..." +for cmd in newfs_ufs mount umount fsck kldstat kldload diskinfo gstat dtrace; do + if command -v "${cmd}" >/dev/null 2>&1; then + echo " OK: ${cmd}" + else + echo " MISSING: ${cmd}" + ok=0 + fi +done + +echo +echo "Checking kernel modules (loadable on demand)..." +for mod in g_disk geom ufs; do + if kldstat -qm "${mod}" >/dev/null 2>&1; then + echo " OK: ${mod} (loaded)" + else + if kldload -n "${mod}" 2>/dev/null; then + echo " OK: ${mod} (available)" + else + echo " NOT AVAILABLE: ${mod}" + fi + fi +done + +echo +echo "Checking kernel sources..." +if [ -d /usr/src/sys/geom ]; then + echo " OK: /usr/src/sys/geom exists" +else + echo " MISSING: /usr/src/sys/geom. Install via git or fetch." + ok=0 +fi +if [ -d /usr/src/sys/dev/md ]; then + echo " OK: /usr/src/sys/dev/md exists" +else + echo " MISSING: /usr/src/sys/dev/md. Install via git or fetch." + ok=0 +fi +if [ -d /usr/src/sys/ufs ]; then + echo " OK: /usr/src/sys/ufs exists" +else + echo " MISSING: /usr/src/sys/ufs. Install via git or fetch." + ok=0 +fi + +echo +echo "Checking /mnt directory..." +if [ -d /mnt ]; then + echo " OK: /mnt exists" +else + echo " MISSING: /mnt. Create it with: mkdir /mnt" + ok=0 +fi + +echo +if [ "${ok}" = "1" ]; then + echo "Environment looks good for Chapter 27 labs." + exit 0 +else + echo "Environment is missing one or more required pieces." + exit 1 +fi diff --git a/examples/part-06/ch27-storage-vfs/shared/reload.sh b/examples/part-06/ch27-storage-vfs/shared/reload.sh new file mode 100755 index 0000000..7ab978f --- /dev/null +++ b/examples/part-06/ch27-storage-vfs/shared/reload.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# +# reload.sh - Rebuild and reload the chapter driver. +# +# Run from the chapter root (one directory above shared/). + +set -eu + +cd "$(dirname "$0")/.." + +if kldstat -qm myblk >/dev/null 2>&1; then + echo "Unloading existing myblk..." + umount /mnt/myblk 2>/dev/null || true + kldunload myblk +fi + +echo "Building..." +make clean +make + +echo "Loading..." +kldload ./myblk.ko + +echo "Loaded. /dev/myblk0 should now exist." +ls -l /dev/myblk0 || true diff --git a/examples/part-06/ch28-network-driver/Makefile b/examples/part-06/ch28-network-driver/Makefile new file mode 100644 index 0000000..68269f9 --- /dev/null +++ b/examples/part-06/ch28-network-driver/Makefile @@ -0,0 +1,16 @@ +# Makefile for mynet - Chapter 28 (Writing a Network Driver). +# +# Builds the chapter's reference pseudo Ethernet driver, mynet.ko, +# which demonstrates the ifnet registration path, a synchronous +# transmit callback, a synthesised receive path, an ioctl handler +# that cooperates with ether_ioctl, and a full clone-create and +# clone-destroy lifecycle. + +KMOD= mynet +SRCS= mynet.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-06/ch28-network-driver/lab05-bpf/run.sh b/examples/part-06/ch28-network-driver/lab05-bpf/run.sh new file mode 100755 index 0000000..4e6e4bd --- /dev/null +++ b/examples/part-06/ch28-network-driver/lab05-bpf/run.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# +# run.sh - lifecycle baseline for Chapter 28 Lab 5. +# +# Loads the mynet module, creates an interface, configures an IPv4 +# address, captures traffic, and tears everything down. Use it as a +# regression check after edits to mynet.c. +# +# Run this script from the chapter directory: +# examples/part-06/ch28-network-driver/ +# after building mynet.ko with "make". +# +# Requires root and FreeBSD 14.3 or later. + +set -e + +echo "== load ==" +kldload ./mynet.ko + +echo "== create ==" +ifconfig mynet create + +echo "== configure ==" +ifconfig mynet0 inet 192.0.2.1/24 up + +echo "== traffic ==" +(tcpdump -i mynet0 -nn -c 5 > /tmp/mynet-tcpdump.txt 2>&1) & +sleep 3 +ping -c 2 192.0.2.99 || true +wait +cat /tmp/mynet-tcpdump.txt + +echo "== counters ==" +netstat -in -I mynet0 + +echo "== teardown ==" +ifconfig mynet0 destroy +kldunload mynet diff --git a/examples/part-06/ch28-network-driver/mynet.c b/examples/part-06/ch28-network-driver/mynet.c new file mode 100644 index 0000000..7b36c41 --- /dev/null +++ b/examples/part-06/ch28-network-driver/mynet.c @@ -0,0 +1,481 @@ +/* + * mynet.c - a pseudo Ethernet driver. + * + * Companion source for Chapter 28 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery". + * + * This driver registers a clonable pseudo Ethernet interface called + * mynet0 (or mynet1, mynet2, ...) with the ifnet framework. It accepts + * outbound frames, taps BPF, updates counters, and frees them; it also + * synthesises one ARP request per second on the inbound path so the + * reader can observe a receive flow without needing real hardware. + * + * Compare with /usr/src/sys/net/if_disc.c for a minimal pseudo driver, + * /usr/src/sys/net/if_epair.c for a clonable pair driver, and + * /usr/src/sys/net/if_ethersubr.c for the Ethernet helpers this driver + * relies on (ether_ifattach, ether_ifdetach, ether_input, ether_ioctl). + * + * The chapter develops this driver in layers: + * + * Section 3: registration skeleton (clone, softc, ifnet, media). + * Section 4: transmit callback. + * Section 5: receive callout and if_input. + * Section 6: flags, link state, and media. + * Section 7: testing with standard tools. + * Section 8: clean detach and cloner teardown. + * + * The file below is the final unified form, ready to compile. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static const char mynet_name[] = "mynet"; +static MALLOC_DEFINE(M_MYNET, "mynet", "mynet pseudo Ethernet driver"); + +VNET_DEFINE_STATIC(struct if_clone *, mynet_cloner); +#define V_mynet_cloner VNET(mynet_cloner) + +struct mynet_softc { + struct ifnet *ifp; + struct mtx mtx; + uint8_t hwaddr[ETHER_ADDR_LEN]; + struct ifmedia media; + struct callout rx_callout; + int rx_interval_hz; + bool running; +}; + +#define MYNET_LOCK(sc) mtx_lock(&(sc)->mtx) +#define MYNET_UNLOCK(sc) mtx_unlock(&(sc)->mtx) +#define MYNET_ASSERT(sc) mtx_assert(&(sc)->mtx, MA_OWNED) + +/* Forward declarations. */ +static int mynet_clone_create(struct if_clone *, int, caddr_t); +static void mynet_clone_destroy(struct ifnet *); +static int mynet_create_unit(int unit); +static void mynet_destroy(struct mynet_softc *); +static void mynet_init(void *); +static void mynet_stop(struct mynet_softc *); +static int mynet_transmit(struct ifnet *, struct mbuf *); +static void mynet_qflush(struct ifnet *); +static int mynet_ioctl(struct ifnet *, u_long, caddr_t); +static int mynet_media_change(struct ifnet *); +static void mynet_media_status(struct ifnet *, struct ifmediareq *); +static void mynet_rx_timer(void *); +static void mynet_rx_fake_arp(struct mynet_softc *); +static int mynet_modevent(module_t, int, void *); +static void vnet_mynet_init(const void *); +static void vnet_mynet_uninit(const void *); + +/* + * Cloner dispatch. These two functions are thin wrappers that + * delegate the real work. Keeping the cloner callbacks small is a + * convention worth following because it makes the interesting code + * in mynet_create_unit and mynet_destroy easy to isolate. + */ +static int +mynet_clone_create(struct if_clone *ifc __unused, int unit, + caddr_t params __unused) +{ + + return (mynet_create_unit(unit)); +} + +static void +mynet_clone_destroy(struct ifnet *ifp) +{ + + mynet_destroy((struct mynet_softc *)ifp->if_softc); +} + +/* + * Per-unit creation. This is where the softc is allocated, the ifnet + * is filled in, the media table is constructed, and the interface is + * handed to ether_ifattach for registration with the stack. + */ +static int +mynet_create_unit(int unit) +{ + struct mynet_softc *sc; + struct ifnet *ifp; + + sc = malloc(sizeof(*sc), M_MYNET, M_WAITOK | M_ZERO); + ifp = if_alloc(IFT_ETHER); + if (ifp == NULL) { + free(sc, M_MYNET); + return (ENOSPC); + } + sc->ifp = ifp; + mtx_init(&sc->mtx, "mynet", NULL, MTX_DEF); + + arc4rand(sc->hwaddr, ETHER_ADDR_LEN, 0); + sc->hwaddr[0] = 0x02; /* locally administered, unicast */ + + if_initname(ifp, mynet_name, unit); + ifp->if_softc = sc; + ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; + ifp->if_capabilities = IFCAP_VLAN_MTU; + ifp->if_capenable = IFCAP_VLAN_MTU; + ifp->if_transmit = mynet_transmit; + ifp->if_qflush = mynet_qflush; + ifp->if_ioctl = mynet_ioctl; + ifp->if_init = mynet_init; + ifp->if_baudrate = IF_Gbps(1); + + ifmedia_init(&sc->media, 0, mynet_media_change, mynet_media_status); + ifmedia_add(&sc->media, IFM_ETHER | IFM_1000_T | IFM_FDX, 0, NULL); + ifmedia_add(&sc->media, IFM_ETHER | IFM_AUTO, 0, NULL); + ifmedia_set(&sc->media, IFM_ETHER | IFM_AUTO); + + callout_init_mtx(&sc->rx_callout, &sc->mtx, 0); + sc->rx_interval_hz = hz; + + ether_ifattach(ifp, sc->hwaddr); + return (0); +} + +/* + * Destruction mirrors creation in reverse: stop the activity, drain + * the callout, detach from the stack, free the ifnet, tear down the + * media list, destroy the mutex, and release the softc. + */ +static void +mynet_destroy(struct mynet_softc *sc) +{ + struct ifnet *ifp = sc->ifp; + + MYNET_LOCK(sc); + sc->running = false; + ifp->if_drv_flags &= ~IFF_DRV_RUNNING; + MYNET_UNLOCK(sc); + + callout_drain(&sc->rx_callout); + + ether_ifdetach(ifp); + if_free(ifp); + + ifmedia_removeall(&sc->media); + mtx_destroy(&sc->mtx); + free(sc, M_MYNET); +} + +/* + * Init and stop handle the transition between "not running" and + * "running". Link state changes are notified with the mutex dropped + * to avoid lock order inversions with the routing subsystem. + */ +static void +mynet_init(void *arg) +{ + struct mynet_softc *sc = arg; + + MYNET_LOCK(sc); + sc->running = true; + sc->ifp->if_drv_flags |= IFF_DRV_RUNNING; + sc->ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; + callout_reset(&sc->rx_callout, sc->rx_interval_hz, + mynet_rx_timer, sc); + MYNET_UNLOCK(sc); + + if_link_state_change(sc->ifp, LINK_STATE_UP); +} + +static void +mynet_stop(struct mynet_softc *sc) +{ + + MYNET_LOCK(sc); + sc->running = false; + sc->ifp->if_drv_flags &= ~IFF_DRV_RUNNING; + callout_stop(&sc->rx_callout); + MYNET_UNLOCK(sc); + + if_link_state_change(sc->ifp, LINK_STATE_DOWN); +} + +/* + * Transmit callback. Receives an mbuf, taps BPF, updates counters, + * and frees the mbuf. A real driver would queue the mbuf for hardware + * DMA; a pseudo driver just drops the frame on the floor after + * accounting for it. + */ +static int +mynet_transmit(struct ifnet *ifp, struct mbuf *m) +{ + struct mynet_softc *sc = ifp->if_softc; + int len; + + if (m == NULL) + return (0); + M_ASSERTPKTHDR(m); + + if (m->m_pkthdr.len > + (ifp->if_mtu + sizeof(struct ether_vlan_header))) { + m_freem(m); + if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); + return (E2BIG); + } + + if ((ifp->if_flags & IFF_UP) == 0 || + (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || + !sc->running) { + m_freem(m); + if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); + return (ENETDOWN); + } + + BPF_MTAP(ifp, m); + + len = m->m_pkthdr.len; + if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); + if_inc_counter(ifp, IFCOUNTER_OBYTES, len); + if (m->m_flags & (M_BCAST | M_MCAST)) + if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1); + + m_freem(m); + return (0); +} + +static void +mynet_qflush(struct ifnet *ifp __unused) +{ + + /* + * No internal queue to flush. A real driver would drain any + * pending mbufs that had not yet reached hardware. + */ +} + +/* + * Receive timer. Fires once per second by default, reschedules itself, + * and synthesises an ARP request to demonstrate the receive path. + */ +static void +mynet_rx_timer(void *arg) +{ + struct mynet_softc *sc = arg; + + MYNET_ASSERT(sc); + if (!sc->running) + return; + callout_reset(&sc->rx_callout, sc->rx_interval_hz, + mynet_rx_timer, sc); + MYNET_UNLOCK(sc); + + mynet_rx_fake_arp(sc); + + MYNET_LOCK(sc); +} + +/* + * Build a broadcast ARP request that looks as if it had arrived on the + * wire, tap BPF, update counters, and hand it to the stack. + */ +static void +mynet_rx_fake_arp(struct mynet_softc *sc) +{ + struct ifnet *ifp = sc->ifp; + struct mbuf *m; + struct ether_header *eh; + struct arphdr *ah; + uint8_t *payload; + size_t frame_len; + + frame_len = sizeof(*eh) + sizeof(*ah) + 2 * (ETHER_ADDR_LEN + 4); + MGETHDR(m, M_NOWAIT, MT_DATA); + if (m == NULL) { + if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); + return; + } + m->m_pkthdr.len = m->m_len = frame_len; + m->m_pkthdr.rcvif = ifp; + + eh = mtod(m, struct ether_header *); + memset(eh->ether_dhost, 0xff, ETHER_ADDR_LEN); + memcpy(eh->ether_shost, sc->hwaddr, ETHER_ADDR_LEN); + eh->ether_type = htons(ETHERTYPE_ARP); + + ah = (struct arphdr *)(eh + 1); + ah->ar_hrd = htons(ARPHRD_ETHER); + ah->ar_pro = htons(ETHERTYPE_IP); + ah->ar_hln = ETHER_ADDR_LEN; + ah->ar_pln = 4; + ah->ar_op = htons(ARPOP_REQUEST); + + payload = (uint8_t *)(ah + 1); + memcpy(payload, sc->hwaddr, ETHER_ADDR_LEN); + payload += ETHER_ADDR_LEN; + memset(payload, 0, 4); + payload += 4; + memset(payload, 0, ETHER_ADDR_LEN); + payload += ETHER_ADDR_LEN; + memcpy(payload, "\xc0\x00\x02\x63", 4); + + BPF_MTAP(ifp, m); + if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); + if_inc_counter(ifp, IFCOUNTER_IBYTES, frame_len); + if_inc_counter(ifp, IFCOUNTER_IMCASTS, 1); + + if_input(ifp, m); +} + +/* + * Ioctl handler. Translates administrative requests (SIOCSIFFLAGS, + * SIOCSIFMTU, SIOCGIFMEDIA, ...) into driver actions. Unknown ioctls + * are delegated to ether_ioctl, which handles most of the common ones + * for Ethernet interfaces. + */ +static int +mynet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) +{ + struct mynet_softc *sc = ifp->if_softc; + struct ifreq *ifr = (struct ifreq *)data; + int error = 0; + + switch (cmd) { + case SIOCSIFFLAGS: + MYNET_LOCK(sc); + if (ifp->if_flags & IFF_UP) { + if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { + MYNET_UNLOCK(sc); + mynet_init(sc); + MYNET_LOCK(sc); + } + } else { + if (ifp->if_drv_flags & IFF_DRV_RUNNING) { + MYNET_UNLOCK(sc); + mynet_stop(sc); + MYNET_LOCK(sc); + } + } + MYNET_UNLOCK(sc); + break; + + case SIOCSIFMTU: + if (ifr->ifr_mtu < 68 || ifr->ifr_mtu > 9216) { + error = EINVAL; + break; + } + ifp->if_mtu = ifr->ifr_mtu; + break; + + case SIOCADDMULTI: + case SIOCDELMULTI: + /* + * Real hardware would program a multicast filter here. + * Our pseudo driver accepts the request silently. + */ + break; + + case SIOCGIFMEDIA: + case SIOCSIFMEDIA: + error = ifmedia_ioctl(ifp, ifr, &sc->media, cmd); + break; + + default: + error = ether_ioctl(ifp, cmd, data); + break; + } + + return (error); +} + +/* + * Media callbacks. We always report the maximum advertised media type + * because a pseudo interface has no real link rate to negotiate. + */ +static int +mynet_media_change(struct ifnet *ifp __unused) +{ + + return (0); +} + +static void +mynet_media_status(struct ifnet *ifp, struct ifmediareq *imr) +{ + struct mynet_softc *sc = ifp->if_softc; + + imr->ifm_status = IFM_AVALID; + if (sc->running) + imr->ifm_status |= IFM_ACTIVE; + imr->ifm_active = IFM_ETHER | IFM_1000_T | IFM_FDX; +} + +/* + * Cloner registration per VNET. Each VNET receives its own cloner, so + * jails with private network stacks can create their own mynet + * interfaces independently of the host. + */ +static void +vnet_mynet_init(const void *unused __unused) +{ + + V_mynet_cloner = if_clone_simple(mynet_name, mynet_clone_create, + mynet_clone_destroy, 0); +} +VNET_SYSINIT(vnet_mynet_init, SI_SUB_PSEUDO, SI_ORDER_ANY, + vnet_mynet_init, NULL); + +static void +vnet_mynet_uninit(const void *unused __unused) +{ + + if_clone_detach(V_mynet_cloner); +} +VNET_SYSUNINIT(vnet_mynet_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY, + vnet_mynet_uninit, NULL); + +/* + * Module lifecycle. All the per-VNET work happens in the SYSINIT and + * SYSUNINIT pair above; the module handler itself only needs to + * acknowledge MOD_LOAD and MOD_UNLOAD. + */ +static int +mynet_modevent(module_t mod __unused, int type, void *data __unused) +{ + + switch (type) { + case MOD_LOAD: + case MOD_UNLOAD: + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t mynet_mod = { + "mynet", + mynet_modevent, + NULL +}; + +DECLARE_MODULE(mynet, mynet_mod, SI_SUB_PSEUDO, SI_ORDER_ANY); +MODULE_DEPEND(mynet, ether, 1, 1, 1); +MODULE_VERSION(mynet, 1); diff --git a/examples/part-06/ch28-network-driver/shared/smoke.sh b/examples/part-06/ch28-network-driver/shared/smoke.sh new file mode 100755 index 0000000..def78de --- /dev/null +++ b/examples/part-06/ch28-network-driver/shared/smoke.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# +# smoke.sh - minimum viable lifecycle check for mynet. +# +# Loads the module, creates an instance, configures an address, prints +# the observable state, and tears everything down. Intended for use +# after any change to mynet.c as a quick regression check. +# +# Run this from the chapter directory: +# examples/part-06/ch28-network-driver/ +# after building with "make". +# +# Requires root and FreeBSD 14.3 or later. + +set -e + +echo "== load ==" +kldload ./mynet.ko + +echo "== create ==" +ifconfig mynet create + +echo "== configure ==" +ifconfig mynet0 inet 192.0.2.1/24 up + +echo "== observe ==" +ifconfig mynet0 +netstat -in -I mynet0 + +echo "== teardown ==" +ifconfig mynet0 destroy +kldunload mynet + +echo "OK" diff --git a/examples/part-07/ch29-portability/README.portability.md b/examples/part-07/ch29-portability/README.portability.md new file mode 100644 index 0000000..bf74a67 --- /dev/null +++ b/examples/part-07/ch29-portability/README.portability.md @@ -0,0 +1,78 @@ +# portdrv - Portability Notes + +This document records the portability surface of the `portdrv` +reference driver that accompanies Chapter 29. + +## Supported Platforms + +| Architecture | Status | Notes | +|--------------|-------------|----------------------------------------------------| +| amd64 | tested | Primary development platform. | +| i386 | tested | Builds cleanly; runtime tested under bhyve. | +| arm64 | builds | Cross-compile tested; runtime should work. | +| riscv64 | builds | Cross-compile tested; runtime not validated. | +| powerpc64 | builds | Cross-compile tested; validates endian paths. | + +## Supported FreeBSD Versions + +| Version | Status | Notes | +|-----------|-----------------|--------------------------------------------------| +| 14.3 | primary target | All labs assume this release. | +| 14.2 | tested | Builds and loads; API surface identical. | +| 13.x | not supported | Pre-`bus_barrier` work; would need backporting. | + +## Supported Buses + +| Bus | Backend file | Status | +|--------|-------------------|---------| +| PCI | `portdrv_pci.c` | tested | +| SIM | `portdrv_sim.c` | tested | +| FDT | (challenge) | planned | +| USB | (challenge) | planned | + +## Supported Build Configurations + +| Configuration | Status | +|--------------------------------------------------|---------| +| `make` (defaults to SIM only) | tested | +| `make PORTDRV_WITH_PCI=yes` | tested | +| `make PORTDRV_WITH_SIM=yes` | tested | +| `make PORTDRV_WITH_PCI=yes PORTDRV_WITH_SIM=yes` | tested | + +## Known Limitations + +1. The driver assumes little-endian hardware registers. Big-endian + hardware would require swapping the `htole`/`letoh` calls in the + data path to `htobe`/`betoh`. +2. The simulation backend does not model DMA. A production driver + with DMA would need a richer simulation. +3. The driver does not currently support hotplug. `detach` is only + exercised on `kldunload`. + +## How to Report a Portability Bug + +Include the output of: + +```sh +uname -a +make -V CFLAGS +sysctl dev.portdrv +dmesg | grep portdrv +``` + +Along with the exact build command used and the platform on which the +failure occurred. Bug reports that include these four items are much +easier to triage. + +## Version History + +| Version | Change | +|---------|----------------------------------------------------------------| +| 1 | Initial monolithic driver (Lab 1). | +| 2 | Added backend interface (Lab 3). | +| 3 | Split into multiple files (Lab 4). | +| 4 | Added simulation backend (Lab 5). | +| 5 | Added conditional compilation (Lab 6). | +| 6 | Added endian helpers (Lab 7). | +| 7 | Added sysctl tree (Lab 10). | +| 8 | Added runtime backend selection (Lab 11). | diff --git a/examples/part-07/ch29-portability/final/Makefile b/examples/part-07/ch29-portability/final/Makefile new file mode 100644 index 0000000..8e6dc6e --- /dev/null +++ b/examples/part-07/ch29-portability/final/Makefile @@ -0,0 +1,38 @@ +# Makefile for portdrv - Chapter 29 final reference driver. +# +# Builds portdrv.ko with one or more backends selected at build time. +# If no backend is selected, the Makefile falls back to SIM so that a +# plain `make` always produces a loadable module. +# +# Usage: +# make # SIM backend only (default). +# make PORTDRV_WITH_PCI=yes # PCI backend only. +# make PORTDRV_WITH_SIM=yes # SIM backend only (explicit). +# make PORTDRV_WITH_PCI=yes PORTDRV_WITH_SIM=yes +# # Both backends. + +KMOD= portdrv +SRCS= portdrv_core.c + +.if defined(PORTDRV_WITH_PCI) && ${PORTDRV_WITH_PCI} == "yes" +SRCS+= portdrv_pci.c +CFLAGS+= -DPORTDRV_WITH_PCI +.endif + +.if defined(PORTDRV_WITH_SIM) && ${PORTDRV_WITH_SIM} == "yes" +SRCS+= portdrv_sim.c +CFLAGS+= -DPORTDRV_WITH_SIM +.endif + +.if !defined(PORTDRV_WITH_PCI) && !defined(PORTDRV_WITH_SIM) +SRCS+= portdrv_sim.c +CFLAGS+= -DPORTDRV_WITH_SIM +.endif + +SRCS+= device_if.h bus_if.h pci_if.h + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch29-portability/final/portdrv.h b/examples/part-07/ch29-portability/final/portdrv.h new file mode 100644 index 0000000..ff944f2 --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv.h @@ -0,0 +1,55 @@ +/* + * portdrv.h - public header for the Chapter 29 reference driver. + * + * Included by every file in the driver. Declares the softc, the core + * entry points used across files, and the shared constants the core + * and its backends need to agree on. + */ + +#ifndef _PORTDRV_H_ +#define _PORTDRV_H_ + +#include +#include + +/* Driver version. Bump when externally observable behaviour changes. */ +#define PORTDRV_VERSION 8 + +/* Shared register offsets. */ +#define REG_ID 0x00 +#define REG_STATUS 0x04 +#define REG_DATA 0x08 +#define REG_CONTROL 0x0c + +#define PORTDRV_EXPECTED_ID 0x504f5254 + +/* Backend interface version. Bumped on every incompatible change. */ +#define PORTDRV_BACKEND_VERSION 2 + +/* Malloc type for driver allocations. */ +MALLOC_DECLARE(M_PORTDRV); + +/* Forward declarations. */ +struct portdrv_softc; + +/* + * Per-instance statistics exposed through sysctl. Update counters + * atomically; they are read without holding the softc lock. + */ +struct portdrv_stats { + uint64_t transfers_ok; + uint64_t transfers_fail; + uint64_t bytes_in; + uint64_t bytes_out; +}; + +/* + * Core entry points called from module-load hooks in each backend's + * compilation unit. The core owns the softc; each backend fills in the + * fields it needs and then hands the softc back to the core to finish + * attach or start detach. + */ +int portdrv_core_attach(struct portdrv_softc *sc); +void portdrv_core_detach(struct portdrv_softc *sc); + +#endif /* !_PORTDRV_H_ */ diff --git a/examples/part-07/ch29-portability/final/portdrv_backend.h b/examples/part-07/ch29-portability/final/portdrv_backend.h new file mode 100644 index 0000000..0406c5f --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv_backend.h @@ -0,0 +1,36 @@ +/* + * portdrv_backend.h - backend interface for portdrv. + * + * The core calls through this interface. Each backend provides an + * instance. No file in the driver should describe how a specific bus + * works; that is the backend's concern. This header is the contract + * the core holds every backend to. + */ + +#ifndef _PORTDRV_BACKEND_H_ +#define _PORTDRV_BACKEND_H_ + +#include "portdrv.h" + +struct portdrv_softc; + +struct portdrv_backend { + uint32_t version; /* must match PORTDRV_BACKEND_VERSION. */ + const char *name; /* "pci", "sim", "usb", ... */ + + int (*attach)(struct portdrv_softc *sc); + void (*detach)(struct portdrv_softc *sc); + uint32_t (*read_reg)(struct portdrv_softc *sc, bus_size_t off); + void (*write_reg)(struct portdrv_softc *sc, bus_size_t off, + uint32_t val); +}; + +#ifdef PORTDRV_WITH_PCI +extern const struct portdrv_backend portdrv_pci_backend; +#endif + +#ifdef PORTDRV_WITH_SIM +extern const struct portdrv_backend portdrv_sim_backend; +#endif + +#endif /* !_PORTDRV_BACKEND_H_ */ diff --git a/examples/part-07/ch29-portability/final/portdrv_common.h b/examples/part-07/ch29-portability/final/portdrv_common.h new file mode 100644 index 0000000..525c79b --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv_common.h @@ -0,0 +1,29 @@ +/* + * portdrv_common.h - types shared between the core and its backends. + * + * The core owns this header. Backends include it so they can access + * the softc's public fields. Keeping this split from portdrv.h keeps + * the backend files small: they only see what they need to see. + */ + +#ifndef _PORTDRV_COMMON_H_ +#define _PORTDRV_COMMON_H_ + +#include "portdrv.h" + +struct portdrv_backend; + +struct portdrv_softc { + device_t sc_dev; /* Newbus identity. */ + struct resource *sc_bar; /* memory-mapped BAR. */ + int sc_bar_rid; /* resource id. */ + const struct portdrv_backend *sc_be; /* backend dispatch. */ + void *sc_backend_priv; /* backend-owned state. */ + struct cdev *sc_cdev; /* character device. */ + struct mtx sc_mtx; /* protects softc state. */ + struct portdrv_stats sc_stats; /* counters. */ + uint32_t sc_last_data; /* last REG_DATA value. */ + int sc_unit; /* unit number. */ +}; + +#endif /* !_PORTDRV_COMMON_H_ */ diff --git a/examples/part-07/ch29-portability/final/portdrv_core.c b/examples/part-07/ch29-portability/final/portdrv_core.c new file mode 100644 index 0000000..c06b09b --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv_core.c @@ -0,0 +1,254 @@ +/* + * portdrv_core.c - hardware-independent core for portdrv. + * + * This file knows about the softc, the character device, the sysctl + * tree, and the read/write path through accessors. It does not include + * any bus-specific header. If you find yourself reaching for + * dev/pci/pcivar.h here, you are in the wrong file. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "portdrv.h" +#include "portdrv_common.h" +#include "portdrv_backend.h" + +MALLOC_DEFINE(M_PORTDRV, "portdrv", "portdrv driver buffers"); + +static d_open_t portdrv_open; +static d_close_t portdrv_close; +static d_read_t portdrv_read; +static d_write_t portdrv_write; + +static struct cdevsw portdrv_cdevsw = { + .d_version = D_VERSION, + .d_open = portdrv_open, + .d_close = portdrv_close, + .d_read = portdrv_read, + .d_write = portdrv_write, + .d_name = "portdrv", +}; + +/* + * Register accessors. Every path that needs a register value goes + * through these. The actual read/write primitive lives in the backend. + */ +static inline uint32_t +portdrv_read_reg(struct portdrv_softc *sc, bus_size_t off) +{ + return (sc->sc_be->read_reg(sc, off)); +} + +static inline void +portdrv_write_reg(struct portdrv_softc *sc, bus_size_t off, uint32_t val) +{ + sc->sc_be->write_reg(sc, off, val); +} + +/* + * Higher-level accessors that know the byte order of a specific + * register. These are the functions core logic calls when it wants the + * decoded value. The plain accessors above move raw bits; these apply + * the documented semantics. + */ +static uint32_t +portdrv_read_data_le(struct portdrv_softc *sc) +{ + return (le32toh(portdrv_read_reg(sc, REG_DATA))); +} + +static void +portdrv_write_data_le(struct portdrv_softc *sc, uint32_t val) +{ + portdrv_write_reg(sc, REG_DATA, htole32(val)); +} + +/* + * sysctl tree. Called once per instance at attach time. Adds leaf + * nodes under dev.portdrv.. The stats leaves are read-only. + */ +static void +portdrv_sysctl_init(struct portdrv_softc *sc) +{ + struct sysctl_ctx_list *ctx; + struct sysctl_oid *tree; + + if (sc->sc_dev == NULL) + return; + + ctx = device_get_sysctl_ctx(sc->sc_dev); + tree = device_get_sysctl_tree(sc->sc_dev); + + SYSCTL_ADD_STRING(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "backend", + CTLFLAG_RD, __DECONST(char *, sc->sc_be->name), 0, + "Backend name"); + + SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "version", + CTLFLAG_RD, NULL, PORTDRV_VERSION, "Driver version"); + + SYSCTL_ADD_UQUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "transfers_ok", + CTLFLAG_RD, &sc->sc_stats.transfers_ok, "Successful transfers"); + + SYSCTL_ADD_UQUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "transfers_fail", + CTLFLAG_RD, &sc->sc_stats.transfers_fail, "Failed transfers"); + + SYSCTL_ADD_UQUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "bytes_in", + CTLFLAG_RD, &sc->sc_stats.bytes_in, "Bytes written to device"); + + SYSCTL_ADD_UQUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "bytes_out", + CTLFLAG_RD, &sc->sc_stats.bytes_out, "Bytes read from device"); +} + +int +portdrv_core_attach(struct portdrv_softc *sc) +{ + int error; + + if (sc->sc_be == NULL) { + printf("portdrv: no backend bound before core_attach\n"); + return (EINVAL); + } + + if (sc->sc_be->version != PORTDRV_BACKEND_VERSION) { + printf("portdrv: backend %s version %u, core expects %u\n", + sc->sc_be->name, sc->sc_be->version, + PORTDRV_BACKEND_VERSION); + return (EPROTONOSUPPORT); + } + + mtx_init(&sc->sc_mtx, "portdrv_sc", NULL, MTX_DEF); + + if (sc->sc_be->attach != NULL) { + error = sc->sc_be->attach(sc); + if (error != 0) { + mtx_destroy(&sc->sc_mtx); + return (error); + } + } + + sc->sc_cdev = make_dev(&portdrv_cdevsw, sc->sc_unit, + UID_ROOT, GID_WHEEL, 0600, "portdrv%d", sc->sc_unit); + if (sc->sc_cdev == NULL) { + if (sc->sc_be->detach != NULL) + sc->sc_be->detach(sc); + mtx_destroy(&sc->sc_mtx); + return (ENXIO); + } + sc->sc_cdev->si_drv1 = sc; + + portdrv_sysctl_init(sc); + + if (sc->sc_dev != NULL) + device_printf(sc->sc_dev, + "portdrv version %d attached (backend %s)\n", + PORTDRV_VERSION, sc->sc_be->name); + else + printf("portdrv%d: version %d attached (backend %s)\n", + sc->sc_unit, PORTDRV_VERSION, sc->sc_be->name); + + return (0); +} + +void +portdrv_core_detach(struct portdrv_softc *sc) +{ + if (sc->sc_cdev != NULL) { + destroy_dev(sc->sc_cdev); + sc->sc_cdev = NULL; + } + if (sc->sc_be != NULL && sc->sc_be->detach != NULL) + sc->sc_be->detach(sc); + mtx_destroy(&sc->sc_mtx); +} + +static int +portdrv_open(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_close(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_read(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val; + int error; + + val = portdrv_read_data_le(sc); + error = uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio); + if (error == 0) { + atomic_add_64(&sc->sc_stats.transfers_ok, 1); + atomic_add_64(&sc->sc_stats.bytes_out, sizeof(val)); + } else { + atomic_add_64(&sc->sc_stats.transfers_fail, 1); + } + return (error); +} + +static int +portdrv_write(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = 0; + int error; + + error = uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio); + if (error != 0) { + atomic_add_64(&sc->sc_stats.transfers_fail, 1); + return (error); + } + portdrv_write_data_le(sc, val); + sc->sc_last_data = val; + atomic_add_64(&sc->sc_stats.transfers_ok, 1); + atomic_add_64(&sc->sc_stats.bytes_in, sizeof(val)); + return (0); +} + +static int +portdrv_core_modevent(module_t mod, int type, void *arg) +{ + switch (type) { + case MOD_LOAD: + printf("portdrv: version %d loaded, backends:" +#ifdef PORTDRV_WITH_PCI + " pci" +#endif +#ifdef PORTDRV_WITH_SIM + " sim" +#endif + "\n", PORTDRV_VERSION); + return (0); + case MOD_UNLOAD: + return (0); + } + return (0); +} + +static moduledata_t portdrv_core_mod = { + "portdrv_core", + portdrv_core_modevent, + NULL +}; + +DECLARE_MODULE(portdrv_core, portdrv_core_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); +MODULE_VERSION(portdrv_core, PORTDRV_VERSION); diff --git a/examples/part-07/ch29-portability/final/portdrv_pci.c b/examples/part-07/ch29-portability/final/portdrv_pci.c new file mode 100644 index 0000000..4e3ed54 --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv_pci.c @@ -0,0 +1,141 @@ +/* + * portdrv_pci.c - PCI backend for portdrv. + * + * Everything that knows about PCI lives here. Probe, attach, resource + * allocation, and the actual bus_read_* and bus_write_* calls. The + * core does not include any PCI header; this file is where the PCI + * dependency is isolated. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "portdrv.h" +#include "portdrv_common.h" +#include "portdrv_backend.h" + +static const struct portdrv_pci_id { + uint16_t vendor; + uint16_t device; + const char *desc; +} portdrv_pci_ids[] = { + { 0x1af4, 0x1005, "portdrv virtio-rnd (demo target)" }, + { 0, 0, NULL } +}; + +static uint32_t +portdrv_pci_read_reg(struct portdrv_softc *sc, bus_size_t off) +{ + return (bus_read_4(sc->sc_bar, off)); +} + +static void +portdrv_pci_write_reg(struct portdrv_softc *sc, bus_size_t off, uint32_t val) +{ + bus_write_4(sc->sc_bar, off, val); +} + +static int +portdrv_pci_backend_attach(struct portdrv_softc *sc) +{ + device_t dev = sc->sc_dev; + + sc->sc_bar_rid = PCIR_BAR(0); + sc->sc_bar = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->sc_bar_rid, RF_ACTIVE); + if (sc->sc_bar == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + return (ENXIO); + } + return (0); +} + +static void +portdrv_pci_backend_detach(struct portdrv_softc *sc) +{ + if (sc->sc_bar != NULL) { + bus_release_resource(sc->sc_dev, SYS_RES_MEMORY, + sc->sc_bar_rid, sc->sc_bar); + sc->sc_bar = NULL; + } +} + +const struct portdrv_backend portdrv_pci_backend = { + .version = PORTDRV_BACKEND_VERSION, + .name = "pci", + .attach = portdrv_pci_backend_attach, + .detach = portdrv_pci_backend_detach, + .read_reg = portdrv_pci_read_reg, + .write_reg = portdrv_pci_write_reg, +}; + +static int +portdrv_pci_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct portdrv_pci_id *id; + + for (id = portdrv_pci_ids; id->desc != NULL; id++) { + if (vendor == id->vendor && device == id->device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +portdrv_pci_attach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + sc->sc_dev = dev; + sc->sc_unit = device_get_unit(dev); + sc->sc_be = &portdrv_pci_backend; + + return (portdrv_core_attach(sc)); +} + +static int +portdrv_pci_detach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + portdrv_core_detach(sc); + return (0); +} + +static device_method_t portdrv_pci_methods[] = { + DEVMETHOD(device_probe, portdrv_pci_probe), + DEVMETHOD(device_attach, portdrv_pci_attach), + DEVMETHOD(device_detach, portdrv_pci_detach), + DEVMETHOD_END +}; + +static driver_t portdrv_pci_driver = { + "portdrv", + portdrv_pci_methods, + sizeof(struct portdrv_softc) +}; + +DRIVER_MODULE(portdrv_pci, pci, portdrv_pci_driver, NULL, NULL); +MODULE_VERSION(portdrv_pci, PORTDRV_VERSION); +MODULE_DEPEND(portdrv_pci, pci, 1, 1, 1); +MODULE_DEPEND(portdrv_pci, portdrv_core, PORTDRV_VERSION, PORTDRV_VERSION, + PORTDRV_VERSION); + +MODULE_PNP_INFO("U16:vendor;U16:device", pci, portdrv, + portdrv_pci_ids, nitems(portdrv_pci_ids) - 1); diff --git a/examples/part-07/ch29-portability/final/portdrv_sim.c b/examples/part-07/ch29-portability/final/portdrv_sim.c new file mode 100644 index 0000000..76776c7 --- /dev/null +++ b/examples/part-07/ch29-portability/final/portdrv_sim.c @@ -0,0 +1,176 @@ +/* + * portdrv_sim.c - simulation backend for portdrv. + * + * A software-only backend. Keeps a flat array of register values and + * serves reads and writes from it. The core is unaware that no real + * hardware is present. This backend is what makes the driver testable + * without a physical device. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "portdrv.h" +#include "portdrv_common.h" +#include "portdrv_backend.h" + +#define PORTDRV_SIM_NREGS 256 + +struct portdrv_sim_priv { + uint32_t regs[PORTDRV_SIM_NREGS]; +}; + +static int portdrv_sim_instances = 1; +static struct portdrv_softc **portdrv_sim_softcs; +static struct portdrv_sim_priv **portdrv_sim_privs; + +SYSCTL_NODE(_debug, OID_AUTO, portdrv, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, + "portdrv debug"); + +SYSCTL_INT(_debug_portdrv, OID_AUTO, sim_instances, + CTLFLAG_RDTUN, &portdrv_sim_instances, 0, + "Number of simulation backend instances to create at load time"); + +static uint32_t +portdrv_sim_read_reg(struct portdrv_softc *sc, bus_size_t off) +{ + struct portdrv_sim_priv *psp = sc->sc_backend_priv; + + if (off / 4 >= PORTDRV_SIM_NREGS) + return (0); + return (psp->regs[off / 4]); +} + +static void +portdrv_sim_write_reg(struct portdrv_softc *sc, bus_size_t off, uint32_t val) +{ + struct portdrv_sim_priv *psp = sc->sc_backend_priv; + + if (off / 4 < PORTDRV_SIM_NREGS) + psp->regs[off / 4] = val; +} + +static int +portdrv_sim_attach_be(struct portdrv_softc *sc) +{ + struct portdrv_sim_priv *psp = sc->sc_backend_priv; + + psp->regs[REG_ID / 4] = PORTDRV_EXPECTED_ID; + psp->regs[REG_STATUS / 4] = 0; + return (0); +} + +static void +portdrv_sim_detach_be(struct portdrv_softc *sc) +{ + (void)sc; +} + +const struct portdrv_backend portdrv_sim_backend = { + .version = PORTDRV_BACKEND_VERSION, + .name = "sim", + .attach = portdrv_sim_attach_be, + .detach = portdrv_sim_detach_be, + .read_reg = portdrv_sim_read_reg, + .write_reg = portdrv_sim_write_reg, +}; + +static int +portdrv_sim_create_instance(int unit) +{ + struct portdrv_softc *sc; + struct portdrv_sim_priv *psp; + int error; + + sc = malloc(sizeof(*sc), M_PORTDRV, M_WAITOK | M_ZERO); + psp = malloc(sizeof(*psp), M_PORTDRV, M_WAITOK | M_ZERO); + sc->sc_unit = unit; + sc->sc_be = &portdrv_sim_backend; + sc->sc_backend_priv = psp; + + error = portdrv_core_attach(sc); + if (error != 0) { + free(psp, M_PORTDRV); + free(sc, M_PORTDRV); + return (error); + } + + portdrv_sim_softcs[unit] = sc; + portdrv_sim_privs[unit] = psp; + return (0); +} + +static void +portdrv_sim_destroy_instance(int unit) +{ + struct portdrv_softc *sc = portdrv_sim_softcs[unit]; + struct portdrv_sim_priv *psp = portdrv_sim_privs[unit]; + + if (sc == NULL) + return; + portdrv_core_detach(sc); + free(psp, M_PORTDRV); + free(sc, M_PORTDRV); + portdrv_sim_softcs[unit] = NULL; + portdrv_sim_privs[unit] = NULL; +} + +static int +portdrv_sim_modevent(module_t mod, int type, void *arg) +{ + int i, error; + + switch (type) { + case MOD_LOAD: + if (portdrv_sim_instances <= 0) + return (0); + portdrv_sim_softcs = malloc( + portdrv_sim_instances * sizeof(*portdrv_sim_softcs), + M_PORTDRV, M_WAITOK | M_ZERO); + portdrv_sim_privs = malloc( + portdrv_sim_instances * sizeof(*portdrv_sim_privs), + M_PORTDRV, M_WAITOK | M_ZERO); + for (i = 0; i < portdrv_sim_instances; i++) { + error = portdrv_sim_create_instance(i); + if (error != 0) { + while (i-- > 0) + portdrv_sim_destroy_instance(i); + free(portdrv_sim_softcs, M_PORTDRV); + free(portdrv_sim_privs, M_PORTDRV); + portdrv_sim_softcs = NULL; + portdrv_sim_privs = NULL; + return (error); + } + } + return (0); + case MOD_UNLOAD: + if (portdrv_sim_softcs != NULL) { + for (i = 0; i < portdrv_sim_instances; i++) + portdrv_sim_destroy_instance(i); + free(portdrv_sim_softcs, M_PORTDRV); + free(portdrv_sim_privs, M_PORTDRV); + portdrv_sim_softcs = NULL; + portdrv_sim_privs = NULL; + } + return (0); + } + return (0); +} + +static moduledata_t portdrv_sim_mod = { + "portdrv_sim", + portdrv_sim_modevent, + NULL +}; + +DECLARE_MODULE(portdrv_sim, portdrv_sim_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(portdrv_sim, PORTDRV_VERSION); +MODULE_DEPEND(portdrv_sim, portdrv_core, PORTDRV_VERSION, PORTDRV_VERSION, + PORTDRV_VERSION); diff --git a/examples/part-07/ch29-portability/lab01-monolithic/Makefile b/examples/part-07/ch29-portability/lab01-monolithic/Makefile new file mode 100644 index 0000000..1ab515e --- /dev/null +++ b/examples/part-07/ch29-portability/lab01-monolithic/Makefile @@ -0,0 +1,13 @@ +# Makefile for portdrv - Chapter 29 Lab 1 (Monolithic Starting Point). +# +# A single source file. No conditional compilation. No backend split. +# This is the baseline against which every later lab measures progress. + +KMOD= portdrv +SRCS= portdrv.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch29-portability/lab01-monolithic/portdrv.c b/examples/part-07/ch29-portability/lab01-monolithic/portdrv.c new file mode 100644 index 0000000..0f9a908 --- /dev/null +++ b/examples/part-07/ch29-portability/lab01-monolithic/portdrv.c @@ -0,0 +1,183 @@ +/* + * portdrv.c - Chapter 29 reference driver, Lab 1 starting point. + * + * A single-file driver that exercises a small, fictitious device + * attached to a PCI bus. It compiles and loads, but it mixes core + * logic, bus-specific code, and register access without any of the + * portability structure the chapter will introduce in later labs. + * + * The point of keeping every concern in one file is not that this is + * good code. It is that it is the baseline. Every lab after this one + * improves on a specific axis of portability. Having the starting + * point in front of you makes the improvements easier to see. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#define PORTDRV_VERSION 1 + +#define REG_ID 0x00 +#define REG_STATUS 0x04 +#define REG_DATA 0x08 +#define REG_CONTROL 0x0c + +#define PORTDRV_EXPECTED_ID 0x504f5254 + +MALLOC_DECLARE(M_PORTDRV); +MALLOC_DEFINE(M_PORTDRV, "portdrv", "portdrv driver buffers"); + +struct portdrv_softc { + device_t sc_dev; + struct resource *sc_bar; + int sc_bar_rid; + struct cdev *sc_cdev; + uint32_t sc_last_data; +}; + +static const struct portdrv_ids { + uint16_t vendor; + uint16_t device; + const char *desc; +} portdrv_ids[] = { + { 0x1af4, 0x1005, "portdrv virtio-rnd (demo target)" }, + { 0, 0, NULL } +}; + +static d_open_t portdrv_open; +static d_close_t portdrv_close; +static d_read_t portdrv_read; +static d_write_t portdrv_write; + +static struct cdevsw portdrv_cdevsw = { + .d_version = D_VERSION, + .d_open = portdrv_open, + .d_close = portdrv_close, + .d_read = portdrv_read, + .d_write = portdrv_write, + .d_name = "portdrv", +}; + +static int +portdrv_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct portdrv_ids *id; + + for (id = portdrv_ids; id->desc != NULL; id++) { + if (vendor == id->vendor && device == id->device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +portdrv_attach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + sc->sc_dev = dev; + sc->sc_bar_rid = PCIR_BAR(0); + sc->sc_bar = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->sc_bar_rid, RF_ACTIVE); + if (sc->sc_bar == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + return (ENXIO); + } + + sc->sc_last_data = bus_read_4(sc->sc_bar, REG_DATA); + device_printf(dev, "portdrv version %d attached\n", PORTDRV_VERSION); + + sc->sc_cdev = make_dev(&portdrv_cdevsw, device_get_unit(dev), + UID_ROOT, GID_WHEEL, 0600, "portdrv%d", device_get_unit(dev)); + if (sc->sc_cdev == NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (ENXIO); + } + sc->sc_cdev->si_drv1 = sc; + + return (0); +} + +static int +portdrv_detach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + if (sc->sc_cdev != NULL) + destroy_dev(sc->sc_cdev); + if (sc->sc_bar != NULL) + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (0); +} + +static int +portdrv_open(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_close(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_read(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = bus_read_4(sc->sc_bar, REG_DATA); + + return (uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio)); +} + +static int +portdrv_write(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = 0; + int error; + + error = uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio); + if (error != 0) + return (error); + bus_write_4(sc->sc_bar, REG_DATA, val); + sc->sc_last_data = val; + return (0); +} + +static device_method_t portdrv_methods[] = { + DEVMETHOD(device_probe, portdrv_probe), + DEVMETHOD(device_attach, portdrv_attach), + DEVMETHOD(device_detach, portdrv_detach), + DEVMETHOD_END +}; + +static driver_t portdrv_driver = { + "portdrv", + portdrv_methods, + sizeof(struct portdrv_softc) +}; + +DRIVER_MODULE(portdrv, pci, portdrv_driver, NULL, NULL); +MODULE_VERSION(portdrv, 1); +MODULE_DEPEND(portdrv, pci, 1, 1, 1); diff --git a/examples/part-07/ch29-portability/lab02-accessors/Makefile b/examples/part-07/ch29-portability/lab02-accessors/Makefile new file mode 100644 index 0000000..1ab515e --- /dev/null +++ b/examples/part-07/ch29-portability/lab02-accessors/Makefile @@ -0,0 +1,13 @@ +# Makefile for portdrv - Chapter 29 Lab 1 (Monolithic Starting Point). +# +# A single source file. No conditional compilation. No backend split. +# This is the baseline against which every later lab measures progress. + +KMOD= portdrv +SRCS= portdrv.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch29-portability/lab02-accessors/portdrv.c b/examples/part-07/ch29-portability/lab02-accessors/portdrv.c new file mode 100644 index 0000000..da71efa --- /dev/null +++ b/examples/part-07/ch29-portability/lab02-accessors/portdrv.c @@ -0,0 +1,194 @@ +/* + * portdrv.c - Chapter 29 Lab 2 (accessors introduced). + * + * Same driver as Lab 1, but every register access now flows through a + * pair of inline accessors. The accessors are the first step toward a + * backend split; see Lab 3 for the next step. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#define PORTDRV_VERSION 1 + +#define REG_ID 0x00 +#define REG_STATUS 0x04 +#define REG_DATA 0x08 +#define REG_CONTROL 0x0c + +#define PORTDRV_EXPECTED_ID 0x504f5254 + +MALLOC_DECLARE(M_PORTDRV); +MALLOC_DEFINE(M_PORTDRV, "portdrv", "portdrv driver buffers"); + +struct portdrv_softc { + device_t sc_dev; + struct resource *sc_bar; + int sc_bar_rid; + struct cdev *sc_cdev; + uint32_t sc_last_data; +}; + +/* + * Accessors. Every register access below goes through these two + * functions. Introducing the layer does not change behaviour; it + * gives us a single point of change for Lab 3. + */ +static inline uint32_t +portdrv_read_reg(struct portdrv_softc *sc, bus_size_t off) +{ + return (bus_read_4(sc->sc_bar, off)); +} + +static inline void +portdrv_write_reg(struct portdrv_softc *sc, bus_size_t off, uint32_t val) +{ + bus_write_4(sc->sc_bar, off, val); +} + +static const struct portdrv_ids { + uint16_t vendor; + uint16_t device; + const char *desc; +} portdrv_ids[] = { + { 0x1af4, 0x1005, "portdrv virtio-rnd (demo target)" }, + { 0, 0, NULL } +}; + +static d_open_t portdrv_open; +static d_close_t portdrv_close; +static d_read_t portdrv_read; +static d_write_t portdrv_write; + +static struct cdevsw portdrv_cdevsw = { + .d_version = D_VERSION, + .d_open = portdrv_open, + .d_close = portdrv_close, + .d_read = portdrv_read, + .d_write = portdrv_write, + .d_name = "portdrv", +}; + +static int +portdrv_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct portdrv_ids *id; + + for (id = portdrv_ids; id->desc != NULL; id++) { + if (vendor == id->vendor && device == id->device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +portdrv_attach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + sc->sc_dev = dev; + sc->sc_bar_rid = PCIR_BAR(0); + sc->sc_bar = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->sc_bar_rid, RF_ACTIVE); + if (sc->sc_bar == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + return (ENXIO); + } + + sc->sc_last_data = portdrv_read_reg(sc, REG_DATA); + device_printf(dev, "portdrv version %d attached\n", PORTDRV_VERSION); + + sc->sc_cdev = make_dev(&portdrv_cdevsw, device_get_unit(dev), + UID_ROOT, GID_WHEEL, 0600, "portdrv%d", device_get_unit(dev)); + if (sc->sc_cdev == NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (ENXIO); + } + sc->sc_cdev->si_drv1 = sc; + + return (0); +} + +static int +portdrv_detach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + if (sc->sc_cdev != NULL) + destroy_dev(sc->sc_cdev); + if (sc->sc_bar != NULL) + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (0); +} + +static int +portdrv_open(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_close(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_read(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = portdrv_read_reg(sc, REG_DATA); + + return (uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio)); +} + +static int +portdrv_write(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = 0; + int error; + + error = uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio); + if (error != 0) + return (error); + portdrv_write_reg(sc, REG_DATA, val); + sc->sc_last_data = val; + return (0); +} + +static device_method_t portdrv_methods[] = { + DEVMETHOD(device_probe, portdrv_probe), + DEVMETHOD(device_attach, portdrv_attach), + DEVMETHOD(device_detach, portdrv_detach), + DEVMETHOD_END +}; + +static driver_t portdrv_driver = { + "portdrv", + portdrv_methods, + sizeof(struct portdrv_softc) +}; + +DRIVER_MODULE(portdrv, pci, portdrv_driver, NULL, NULL); +MODULE_VERSION(portdrv, 2); +MODULE_DEPEND(portdrv, pci, 1, 1, 1); diff --git a/examples/part-07/ch29-portability/lab03-backend/Makefile b/examples/part-07/ch29-portability/lab03-backend/Makefile new file mode 100644 index 0000000..277fad2 --- /dev/null +++ b/examples/part-07/ch29-portability/lab03-backend/Makefile @@ -0,0 +1,15 @@ +# Makefile for portdrv - Chapter 29 Lab 3 (Backend Interface Extracted). +# +# The driver is still a single source file. The backend header is not +# listed here because bsd.kmod.mk picks it up automatically through +# the include in portdrv.c. Lab 4 will add a second source file and +# the Makefile will grow accordingly. + +KMOD= portdrv +SRCS= portdrv.c + +CFLAGS+= -I${.CURDIR} + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch29-portability/lab03-backend/portdrv.c b/examples/part-07/ch29-portability/lab03-backend/portdrv.c new file mode 100644 index 0000000..0464c77 --- /dev/null +++ b/examples/part-07/ch29-portability/lab03-backend/portdrv.c @@ -0,0 +1,233 @@ +/* + * portdrv.c - Chapter 29 Lab 3 (Backend Interface Extracted). + * + * Same functionality as Lab 2, but the accessors now dispatch through + * a backend structure declared in portdrv_backend.h. The driver still + * lives in a single source file; Lab 4 will break it into a PCI + * backend file and a core file. The point of this intermediate step + * is to get the interface right while there is still only one place + * that has to be kept consistent. + * + * After this lab, no function in the core path calls bus_read_* or + * bus_write_* directly. Every register access goes through the + * backend pointer on the softc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "portdrv_backend.h" + +#define PORTDRV_VERSION 1 + +#define REG_ID 0x00 +#define REG_STATUS 0x04 +#define REG_DATA 0x08 +#define REG_CONTROL 0x0c + +#define PORTDRV_EXPECTED_ID 0x504f5254 + +MALLOC_DECLARE(M_PORTDRV); +MALLOC_DEFINE(M_PORTDRV, "portdrv", "portdrv driver buffers"); + +struct portdrv_softc { + device_t sc_dev; + struct resource *sc_bar; + int sc_bar_rid; + const struct portdrv_backend *sc_be; + struct cdev *sc_cdev; + uint32_t sc_last_data; +}; + +/* + * Accessors. These no longer call bus_read_4/bus_write_4 themselves. + * They dispatch through the backend pointer, so the same code runs + * unchanged when a different backend is installed. + */ +static inline uint32_t +portdrv_read_reg(struct portdrv_softc *sc, bus_size_t off) +{ + return (sc->sc_be->read_reg(sc, off)); +} + +static inline void +portdrv_write_reg(struct portdrv_softc *sc, bus_size_t off, uint32_t val) +{ + sc->sc_be->write_reg(sc, off, val); +} + +/* + * PCI backend implementation. This is where the real bus_read_* and + * bus_write_* calls live in Lab 3. In Lab 4 these functions and the + * backend instance move into a separate portdrv_pci.c file. + */ +static uint32_t +portdrv_pci_read_reg_impl(struct portdrv_softc *sc, bus_size_t off) +{ + return (bus_read_4(sc->sc_bar, off)); +} + +static void +portdrv_pci_write_reg_impl(struct portdrv_softc *sc, bus_size_t off, + uint32_t val) +{ + bus_write_4(sc->sc_bar, off, val); +} + +const struct portdrv_backend portdrv_pci_backend = { + .name = "pci", + .attach = NULL, + .detach = NULL, + .read_reg = portdrv_pci_read_reg_impl, + .write_reg = portdrv_pci_write_reg_impl, +}; + +static const struct portdrv_ids { + uint16_t vendor; + uint16_t device; + const char *desc; +} portdrv_ids[] = { + { 0x1af4, 0x1005, "portdrv virtio-rnd (demo target)" }, + { 0, 0, NULL } +}; + +static d_open_t portdrv_open; +static d_close_t portdrv_close; +static d_read_t portdrv_read; +static d_write_t portdrv_write; + +static struct cdevsw portdrv_cdevsw = { + .d_version = D_VERSION, + .d_open = portdrv_open, + .d_close = portdrv_close, + .d_read = portdrv_read, + .d_write = portdrv_write, + .d_name = "portdrv", +}; + +static int +portdrv_probe(device_t dev) +{ + uint16_t vendor = pci_get_vendor(dev); + uint16_t device = pci_get_device(dev); + const struct portdrv_ids *id; + + for (id = portdrv_ids; id->desc != NULL; id++) { + if (vendor == id->vendor && device == id->device) { + device_set_desc(dev, id->desc); + return (BUS_PROBE_DEFAULT); + } + } + return (ENXIO); +} + +static int +portdrv_attach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + sc->sc_dev = dev; + sc->sc_be = &portdrv_pci_backend; + + sc->sc_bar_rid = PCIR_BAR(0); + sc->sc_bar = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->sc_bar_rid, RF_ACTIVE); + if (sc->sc_bar == NULL) { + device_printf(dev, "cannot allocate BAR0\n"); + return (ENXIO); + } + + sc->sc_last_data = portdrv_read_reg(sc, REG_DATA); + device_printf(dev, "portdrv version %d attached via %s backend\n", + PORTDRV_VERSION, sc->sc_be->name); + + sc->sc_cdev = make_dev(&portdrv_cdevsw, device_get_unit(dev), + UID_ROOT, GID_WHEEL, 0600, "portdrv%d", device_get_unit(dev)); + if (sc->sc_cdev == NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (ENXIO); + } + sc->sc_cdev->si_drv1 = sc; + + return (0); +} + +static int +portdrv_detach(device_t dev) +{ + struct portdrv_softc *sc = device_get_softc(dev); + + if (sc->sc_cdev != NULL) + destroy_dev(sc->sc_cdev); + if (sc->sc_bar != NULL) + bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_bar_rid, + sc->sc_bar); + return (0); +} + +static int +portdrv_open(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_close(struct cdev *cdev, int flags, int devtype, struct thread *td) +{ + return (0); +} + +static int +portdrv_read(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = portdrv_read_reg(sc, REG_DATA); + + return (uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio)); +} + +static int +portdrv_write(struct cdev *cdev, struct uio *uio, int flag) +{ + struct portdrv_softc *sc = cdev->si_drv1; + uint32_t val = 0; + int error; + + error = uiomove(&val, MIN(uio->uio_resid, sizeof(val)), uio); + if (error != 0) + return (error); + portdrv_write_reg(sc, REG_DATA, val); + sc->sc_last_data = val; + return (0); +} + +static device_method_t portdrv_methods[] = { + DEVMETHOD(device_probe, portdrv_probe), + DEVMETHOD(device_attach, portdrv_attach), + DEVMETHOD(device_detach, portdrv_detach), + DEVMETHOD_END +}; + +static driver_t portdrv_driver = { + "portdrv", + portdrv_methods, + sizeof(struct portdrv_softc) +}; + +DRIVER_MODULE(portdrv, pci, portdrv_driver, NULL, NULL); +MODULE_VERSION(portdrv, 3); +MODULE_DEPEND(portdrv, pci, 1, 1, 1); diff --git a/examples/part-07/ch29-portability/lab03-backend/portdrv_backend.h b/examples/part-07/ch29-portability/lab03-backend/portdrv_backend.h new file mode 100644 index 0000000..ed40d3d --- /dev/null +++ b/examples/part-07/ch29-portability/lab03-backend/portdrv_backend.h @@ -0,0 +1,26 @@ +/* + * portdrv_backend.h - backend interface for portdrv (Lab 3). + * + * The core dispatches every register access through this interface. + * The Lab 3 driver still lives in a single portdrv.c, so the backend + * instance is defined in that same file. Lab 4 will move each backend + * into its own source file without changing this header. + */ + +#ifndef _PORTDRV_BACKEND_H_ +#define _PORTDRV_BACKEND_H_ + +struct portdrv_softc; + +struct portdrv_backend { + const char *name; /* "pci", "sim", ... */ + int (*attach)(struct portdrv_softc *sc); + void (*detach)(struct portdrv_softc *sc); + uint32_t (*read_reg)(struct portdrv_softc *sc, bus_size_t off); + void (*write_reg)(struct portdrv_softc *sc, bus_size_t off, + uint32_t val); +}; + +extern const struct portdrv_backend portdrv_pci_backend; + +#endif /* !_PORTDRV_BACKEND_H_ */ diff --git a/examples/part-07/ch29-portability/lab08-matrix/validate-build.sh b/examples/part-07/ch29-portability/lab08-matrix/validate-build.sh new file mode 100755 index 0000000..ffbac97 --- /dev/null +++ b/examples/part-07/ch29-portability/lab08-matrix/validate-build.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# validate-build.sh - build portdrv in every supported configuration. +# +# Usage: run from the directory that contains the driver's Makefile. +# Exit status 0 means every listed configuration built; non-zero means +# the first failing configuration. Build logs land in build.log. + +set -e + +configs=" +PORTDRV_WITH_SIM=yes +PORTDRV_WITH_PCI=yes +PORTDRV_WITH_PCI=yes PORTDRV_WITH_SIM=yes +" + +echo "$configs" | while read cfg; do + [ -z "$cfg" ] && continue + printf "==> %s ... " "$cfg" + make clean > /dev/null 2>&1 + if env $cfg make > build.log 2>&1; then + echo "OK" + else + echo "FAIL" + tail -n 20 build.log + exit 1 + fi +done +echo "All configurations built successfully." diff --git a/examples/part-07/ch29-portability/lab09-userland-test/Makefile b/examples/part-07/ch29-portability/lab09-userland-test/Makefile new file mode 100644 index 0000000..f7c49fa --- /dev/null +++ b/examples/part-07/ch29-portability/lab09-userland-test/Makefile @@ -0,0 +1,8 @@ +# Makefile for portdrv_test - Chapter 29 Lab 9 userland test program. + +PROG= portdrv_test +SRCS= portdrv_test.c + +CFLAGS+= -Wall -Wextra -Wno-unused-parameter + +.include diff --git a/examples/part-07/ch29-portability/lab09-userland-test/portdrv_test.c b/examples/part-07/ch29-portability/lab09-userland-test/portdrv_test.c new file mode 100644 index 0000000..2c61519 --- /dev/null +++ b/examples/part-07/ch29-portability/lab09-userland-test/portdrv_test.c @@ -0,0 +1,76 @@ +/* + * portdrv_test.c - Chapter 29 Lab 9 userland harness for portdrv. + * + * Opens a portdrv character device, writes a known value, reads it + * back, and prints the result. The test is meant to exercise the + * simulation backend end-to-end without needing hardware. + * + * Build: cc -o portdrv_test portdrv_test.c + * Run: ./portdrv_test /dev/portdrv0 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int +round_trip(const char *dev, uint32_t value) +{ + int fd; + uint32_t readback = 0; + + fd = open(dev, O_RDWR); + if (fd < 0) { + perror(dev); + return (-1); + } + + if (write(fd, &value, sizeof(value)) != (ssize_t)sizeof(value)) { + perror("write"); + close(fd); + return (-1); + } + + if (lseek(fd, 0, SEEK_SET) < 0) { + /* Ignore: some drivers do not support seeking. */ + } + + if (read(fd, &readback, sizeof(readback)) != (ssize_t)sizeof(readback)) { + perror("read"); + close(fd); + return (-1); + } + + close(fd); + + printf("%s: wrote 0x%08" PRIx32 ", read 0x%08" PRIx32 "\n", + dev, value, readback); + + return (value == readback) ? 0 : 1; +} + +int +main(int argc, char *argv[]) +{ + const char *dev = (argc > 1) ? argv[1] : "/dev/portdrv0"; + int failures = 0; + + failures += (round_trip(dev, 0x12345678) != 0); + failures += (round_trip(dev, 0xcafebabe) != 0); + failures += (round_trip(dev, 0x00000000) != 0); + failures += (round_trip(dev, 0xffffffff) != 0); + + if (failures == 0) { + printf("All round-trip tests passed for %s\n", dev); + return (0); + } + + fprintf(stderr, "%d round-trip tests failed for %s\n", failures, dev); + return (1); +} diff --git a/examples/part-07/ch29-portability/lab12-ci/ci-check.sh b/examples/part-07/ch29-portability/lab12-ci/ci-check.sh new file mode 100755 index 0000000..6c3d1b5 --- /dev/null +++ b/examples/part-07/ch29-portability/lab12-ci/ci-check.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# ci-check.sh - validate portdrv in every supported configuration. +# +# Combines the build matrix from Lab 8 with a load test. Runs from the +# driver's build directory. Requires sudo to load and unload kernel +# modules; if run without sudo, the load step is skipped. + +set -e + +configs=" +PORTDRV_WITH_SIM=yes +PORTDRV_WITH_PCI=yes +PORTDRV_WITH_PCI=yes PORTDRV_WITH_SIM=yes +" + +HAVE_SUDO=0 +if command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then + HAVE_SUDO=1 +fi + +echo "$configs" | while read cfg; do + [ -z "$cfg" ] && continue + printf "==> Build: %s ... " "$cfg" + make clean > /dev/null 2>&1 + if env $cfg make > build.log 2>&1; then + echo "OK" + else + echo "FAIL" + tail -n 20 build.log + exit 1 + fi + + if [ $HAVE_SUDO -eq 1 ]; then + printf "==> Load : %s ... " "$cfg" + if sudo kldload ./portdrv.ko > load.log 2>&1; then + sudo kldunload portdrv > /dev/null 2>&1 || true + echo "OK" + else + echo "FAIL" + cat load.log + exit 1 + fi + else + printf "==> Load : %s ... SKIPPED (no sudo)\n" "$cfg" + fi +done +echo "All configurations passed." diff --git a/examples/part-07/ch30-virtualisation/lab02-detect/Makefile b/examples/part-07/ch30-virtualisation/lab02-detect/Makefile new file mode 100644 index 0000000..5305810 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab02-detect/Makefile @@ -0,0 +1,11 @@ +# Makefile for detectmod - Chapter 30 Lab 2 (Hypervisor Detection). +# +# A single source file kernel module that reads vm_guest and logs the +# detected environment at load time. + +KMOD= detectmod +SRCS= detectmod.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch30-virtualisation/lab02-detect/detectmod.c b/examples/part-07/ch30-virtualisation/lab02-detect/detectmod.c new file mode 100644 index 0000000..4811346 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab02-detect/detectmod.c @@ -0,0 +1,62 @@ +/* + * detectmod.c - Hypervisor detection kernel module + * + * Chapter 30, Lab 2. Reads the global vm_guest variable on module load + * and prints a descriptive message naming the hypervisor environment. + * Demonstrates the simplest form of environment-aware driver behaviour. + * + * Build: + * make clean && make + * Load: + * sudo kldload ./detectmod.ko + * Unload: + * sudo kldunload detectmod + */ + +#include +#include +#include +#include + +static const char * +vm_guest_name(int guest) +{ + switch (guest) { + case VM_GUEST_NO: return ("bare metal"); + case VM_GUEST_VM: return ("generic VM"); + case VM_GUEST_XEN: return ("Xen"); + case VM_GUEST_HV: return ("Microsoft Hyper-V"); + case VM_GUEST_VMWARE: return ("VMware"); + case VM_GUEST_KVM: return ("KVM"); + case VM_GUEST_BHYVE: return ("bhyve"); + case VM_GUEST_VBOX: return ("VirtualBox"); + case VM_GUEST_PARALLELS: return ("Parallels"); + case VM_GUEST_NVMM: return ("NVMM"); + default: return ("unknown"); + } +} + +static int +detectmod_modevent(module_t mod, int event, void *arg) +{ + switch (event) { + case MOD_LOAD: + printf("detectmod: running on %s (vm_guest=%d)\n", + vm_guest_name(vm_guest), vm_guest); + return (0); + case MOD_UNLOAD: + printf("detectmod: goodbye\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t detectmod_mod = { + "detectmod", + detectmod_modevent, + NULL +}; + +DECLARE_MODULE(detectmod, detectmod_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(detectmod, 1); diff --git a/examples/part-07/ch30-virtualisation/lab03-jaildev/Makefile b/examples/part-07/ch30-virtualisation/lab03-jaildev/Makefile new file mode 100644 index 0000000..cb3bb7e --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab03-jaildev/Makefile @@ -0,0 +1,8 @@ +# Makefile for jaildev - Chapter 30 Lab 3 (Character Device in a Jail). + +KMOD= jaildev +SRCS= jaildev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch30-virtualisation/lab03-jaildev/jaildev.c b/examples/part-07/ch30-virtualisation/lab03-jaildev/jaildev.c new file mode 100644 index 0000000..1b7e63e --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab03-jaildev/jaildev.c @@ -0,0 +1,117 @@ +/* + * jaildev.c - A minimal character-device driver for jail visibility testing. + * + * Chapter 30, Lab 3. Creates /dev/jaildev that returns a fixed greeting on + * read. Exposes an ioctl that requires PRIV_DRIVER, so the same operation + * succeeds on the host's root and fails inside a jail (where PRIV_DRIVER + * is not granted by default). + * + * The driver illustrates three ideas: + * 1. make_dev(9) with a well-known name for devfs ruleset control. + * 2. d_read handling that is safe for any caller. + * 3. priv_check(9) as the correct primitive for gated ioctls. + * + * Build: + * make clean && make + * Load: + * sudo kldload ./jaildev.ko + * Test: + * cat /dev/jaildev + * Unload: + * sudo kldunload jaildev + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define JAILDEV_GREETING "hello from jaildev\n" + +#define JAILDEV_IOC_PRIVOP _IO('J', 1) + +static d_read_t jaildev_read; +static d_ioctl_t jaildev_ioctl; + +static struct cdevsw jaildev_cdevsw = { + .d_version = D_VERSION, + .d_read = jaildev_read, + .d_ioctl = jaildev_ioctl, + .d_name = "jaildev", +}; + +static struct cdev *jaildev_dev; + +static int +jaildev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + const char *msg = JAILDEV_GREETING; + size_t len = sizeof(JAILDEV_GREETING) - 1; + size_t toread; + + if (uio->uio_offset >= (off_t)len) + return (0); + + toread = len - uio->uio_offset; + if (toread > uio->uio_resid) + toread = uio->uio_resid; + + return (uiomove(__DECONST(void *, msg + uio->uio_offset), toread, uio)); +} + +static int +jaildev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data __unused, + int fflag __unused, struct thread *td) +{ + int error; + + switch (cmd) { + case JAILDEV_IOC_PRIVOP: + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + printf("jaildev: privileged ioctl executed by pid %d\n", + td->td_proc->p_pid); + return (0); + default: + return (ENOTTY); + } +} + +static int +jaildev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + int error = 0; + + switch (event) { + case MOD_LOAD: + jaildev_dev = make_dev(&jaildev_cdevsw, 0, UID_ROOT, + GID_WHEEL, 0644, "jaildev"); + if (jaildev_dev == NULL) + return (ENOMEM); + printf("jaildev: created /dev/jaildev\n"); + break; + case MOD_UNLOAD: + if (jaildev_dev != NULL) + destroy_dev(jaildev_dev); + printf("jaildev: goodbye\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t jaildev_mod = { + "jaildev", + jaildev_modevent, + NULL +}; + +DECLARE_MODULE(jaildev, jaildev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(jaildev, 1); diff --git a/examples/part-07/ch30-virtualisation/lab03-jaildev/testclient.c b/examples/part-07/ch30-virtualisation/lab03-jaildev/testclient.c new file mode 100644 index 0000000..4f8bb0e --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab03-jaildev/testclient.c @@ -0,0 +1,44 @@ +/* + * testclient.c - A small user-space test for jaildev. + * + * Compile: + * cc -Wall -o testclient testclient.c + * Run (as root on the host, and as root inside a jail): + * ./testclient + */ + +#include +#include +#include +#include +#include + +#define JAILDEV_IOC_PRIVOP _IO('J', 1) + +int +main(void) +{ + char buf[64]; + ssize_t n; + int fd; + + fd = open("/dev/jaildev", O_RDONLY); + if (fd < 0) + err(1, "open /dev/jaildev"); + + n = read(fd, buf, sizeof(buf) - 1); + if (n < 0) { + warn("read"); + } else { + buf[n] = '\0'; + printf("read: %s", buf); + } + + if (ioctl(fd, JAILDEV_IOC_PRIVOP) < 0) + warn("ioctl PRIVOP"); + else + printf("privileged ioctl succeeded\n"); + + close(fd); + return (0); +} diff --git a/examples/part-07/ch30-virtualisation/lab04-vnet/setup.sh b/examples/part-07/ch30-virtualisation/lab04-vnet/setup.sh new file mode 100755 index 0000000..01e2a90 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab04-vnet/setup.sh @@ -0,0 +1,72 @@ +#!/bin/sh +# +# setup.sh - Create a VNET jail with an epair interface. +# Chapter 30, Lab 4. +# +# Run as root on the FreeBSD host. Creates /jails/vnet-test, mounts +# a minimal filesystem, and starts a VNET jail with one end of an +# epair moved into it. +# +# Companion to chapter-30.md. + +set -eu + +JAIL_NAME="vnet-test" +JAIL_ROOT="/jails/${JAIL_NAME}" +HOST_IP="10.100.0.1" +JAIL_IP="10.100.0.2" +PREFIX="24" + +if [ "$(id -u)" -ne 0 ]; then + echo "$0: must be run as root" >&2 + exit 1 +fi + +# Ensure required modules are available. +kldload -n if_epair +kldload -n vmm 2>/dev/null || true + +# Create jail root directory if missing. +if [ ! -d "${JAIL_ROOT}" ]; then + mkdir -p "${JAIL_ROOT}" + # Minimal filesystem: copy a statically-linked shell in /rescue. + cp /rescue/sh "${JAIL_ROOT}/sh" + cp /rescue/ifconfig "${JAIL_ROOT}/ifconfig" + cp /rescue/ping "${JAIL_ROOT}/ping" + echo "created minimal jail root at ${JAIL_ROOT}" +fi + +# Create the epair if it does not already exist. +if ! ifconfig epair0a >/dev/null 2>&1; then + EPAIR=$(ifconfig epair create) + # epair create returns epairNa; the partner is the matching b. + HOST_END="${EPAIR}" + JAIL_END="${EPAIR%a}b" +else + HOST_END="epair0a" + JAIL_END="epair0b" +fi + +echo "host end: ${HOST_END} jail end: ${JAIL_END}" + +ifconfig "${HOST_END}" inet "${HOST_IP}/${PREFIX}" up + +# Start the VNET jail. +jail -c \ + name="${JAIL_NAME}" \ + path="${JAIL_ROOT}" \ + host.hostname="${JAIL_NAME}" \ + vnet \ + vnet.interface="${JAIL_END}" \ + persist \ + command=/sh + +# Configure the jail's end of the epair. +jexec "${JAIL_NAME}" /ifconfig "${JAIL_END}" inet "${JAIL_IP}/${PREFIX}" up + +echo +echo "jail ${JAIL_NAME} is running. Try:" +echo " jexec ${JAIL_NAME} /ping -c 2 ${HOST_IP}" +echo " ping -c 2 ${JAIL_IP}" +echo "To tear down:" +echo " ./teardown.sh" diff --git a/examples/part-07/ch30-virtualisation/lab04-vnet/teardown.sh b/examples/part-07/ch30-virtualisation/lab04-vnet/teardown.sh new file mode 100755 index 0000000..896ca77 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/lab04-vnet/teardown.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# +# teardown.sh - Clean up the VNET jail set up by setup.sh. +# Chapter 30, Lab 4. + +set -eu + +JAIL_NAME="vnet-test" + +if [ "$(id -u)" -ne 0 ]; then + echo "$0: must be run as root" >&2 + exit 1 +fi + +if jls | awk '{ print $3 }' | grep -q "^${JAIL_NAME}$"; then + jail -r "${JAIL_NAME}" + echo "jail ${JAIL_NAME} removed" +else + echo "no jail named ${JAIL_NAME}" +fi + +# Remove the epair (will succeed whichever end is left on the host). +if ifconfig epair0a >/dev/null 2>&1; then + ifconfig epair0a destroy + echo "epair destroyed" +fi diff --git a/examples/part-07/ch30-virtualisation/shared/devfs.rules.example b/examples/part-07/ch30-virtualisation/shared/devfs.rules.example new file mode 100644 index 0000000..13507cd --- /dev/null +++ b/examples/part-07/ch30-virtualisation/shared/devfs.rules.example @@ -0,0 +1,33 @@ +# Example devfs rulesets for Chapter 30 labs. +# +# Copy the relevant rules into /etc/devfs.rules (creating the file if it +# does not exist), then reload with: +# +# sudo service devfs restart +# +# These rulesets use numbers in the 100 range to avoid conflict with the +# kernel's defaults (1, 2, 3, 4, 5). + +[devfsrules_jaildev=100] +add include $devfsrules_hide_all +add include $devfsrules_unhide_basic +add path 'jaildev' unhide + +[devfsrules_myservice=101] +add include $devfsrules_hide_all +add include $devfsrules_unhide_basic +add include $devfsrules_unhide_login +add path 'myservice*' unhide +add path 'log' unhide + +# Example: a jail that should be able to use tun0 specifically but not +# any other tunnel device. Useful for VPN or network-service jails. +[devfsrules_tun0jail=102] +add include $devfsrules_jail +add path 'tun0' unhide + +# Example: a jail that runs packet-capture tools (tcpdump, dhclient). +# Starts from the VNET jail ruleset and ensures bpf is visible. +[devfsrules_capturejail=103] +add include $devfsrules_jail_vnet +add path 'bpf*' unhide diff --git a/examples/part-07/ch30-virtualisation/shared/jail.conf.example b/examples/part-07/ch30-virtualisation/shared/jail.conf.example new file mode 100644 index 0000000..ba62c4b --- /dev/null +++ b/examples/part-07/ch30-virtualisation/shared/jail.conf.example @@ -0,0 +1,37 @@ +# Example jail.conf(5) snippets for Chapter 30 labs. +# +# Copy relevant blocks into /etc/jail.conf (or into a per-jail include), +# edit paths and names, and manage the jails with service jail. + +# A simple non-VNET jail that uses the custom jaildev ruleset from Lab 3. +testjail { + path = "/jails/test"; + host.hostname = "testjail"; + ip4 = inherit; + devfs_ruleset = 100; + exec.start = "/bin/sh /etc/rc"; + exec.stop = "/bin/sh /etc/rc.shutdown"; + persist; +} + +# A VNET jail with an epair interface moved in. Complements Lab 4. +vnet-test { + path = "/jails/vnet-test"; + host.hostname = "vnet-test"; + vnet; + vnet.interface = "epair0b"; + devfs_ruleset = 5; # devfsrules_jail_vnet + persist; +} + +# A "services" jail that sees only a custom service device. +myservice { + path = "/jails/myservice"; + host.hostname = "myservice"; + devfs_ruleset = 101; + allow.raw_sockets = 0; + allow.mount = 0; + exec.start = "/bin/sh /etc/rc"; + exec.stop = "/bin/sh /etc/rc.shutdown"; + persist; +} diff --git a/examples/part-07/ch30-virtualisation/vtedu/Makefile b/examples/part-07/ch30-virtualisation/vtedu/Makefile new file mode 100644 index 0000000..aa1b807 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/vtedu/Makefile @@ -0,0 +1,13 @@ +# Makefile for vtedu - Chapter 30 Case Study. +# +# A pedagogical VirtIO character device driver. Depends on the virtio +# framework. Requires a matching backend in bhyve(8) or QEMU; without +# one, probe will not match anything and the driver will not attach. + +KMOD= virtio_edu +SRCS= vtedu.c +SRCS+= device_if.h bus_if.h virtio_if.h + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch30-virtualisation/vtedu/vtedu.c b/examples/part-07/ch30-virtualisation/vtedu/vtedu.c new file mode 100644 index 0000000..2aeec78 --- /dev/null +++ b/examples/part-07/ch30-virtualisation/vtedu/vtedu.c @@ -0,0 +1,268 @@ +/* + * vtedu.c - A pedagogical VirtIO character device driver. + * + * Chapter 30 Case Study. Designed for teaching, not for production. + * The driver: + * + * - Advertises a reserved VirtIO device ID (VIRTIO_ID_EDU). + * - Negotiates one feature bit (VTEDU_F_UPPERCASE). + * - Allocates a single virtqueue. + * - Exposes /dev/vteduN through make_dev(9). + * - On write, submits the user-space bytes to the virtqueue. + * - On read, returns whatever the backend put back. + * + * This is the driver described in Chapter 30's closing case study. + * A matching backend in bhyve(8) is required for it to do anything + * useful; without one, probe will not match any device. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define VIRTIO_ID_EDU 0xfff0 /* hypothetical reserved ID */ + +#define VTEDU_F_UPPERCASE (1ULL << 0) +#define VTEDU_FEATURES (VIRTIO_F_VERSION_1 | VTEDU_F_UPPERCASE) + +#define VTEDU_BUF_SIZE 256 + +struct vtedu_softc { + device_t dev; + struct virtqueue *vq; + uint64_t features; + struct mtx lock; + struct cdev *cdev; + struct sglist *sg; + char buf[VTEDU_BUF_SIZE]; + size_t buf_len; + bool response_ready; +}; + +static int vtedu_probe(device_t); +static int vtedu_attach(device_t); +static int vtedu_detach(device_t); + +static int vtedu_negotiate_features(struct vtedu_softc *); +static int vtedu_alloc_virtqueue(struct vtedu_softc *); +static int vtedu_submit_locked(struct vtedu_softc *); +static void vtedu_vq_intr(void *); + +static d_open_t vtedu_open; +static d_read_t vtedu_read; +static d_write_t vtedu_write; + +static struct virtio_feature_desc vtedu_feature_descs[] = { + { VTEDU_F_UPPERCASE, "Uppercase" }, + { 0, NULL } +}; + +static struct cdevsw vtedu_cdevsw = { + .d_version = D_VERSION, + .d_open = vtedu_open, + .d_read = vtedu_read, + .d_write = vtedu_write, + .d_name = "vtedu", +}; + +static device_method_t vtedu_methods[] = { + DEVMETHOD(device_probe, vtedu_probe), + DEVMETHOD(device_attach, vtedu_attach), + DEVMETHOD(device_detach, vtedu_detach), + DEVMETHOD_END +}; + +static driver_t vtedu_driver = { + "vtedu", + vtedu_methods, + sizeof(struct vtedu_softc) +}; + +VIRTIO_SIMPLE_PNPINFO(virtio_edu, VIRTIO_ID_EDU, + "VirtIO Educational Device"); +VIRTIO_DRIVER_MODULE(virtio_edu, vtedu_driver, NULL, NULL); +MODULE_VERSION(virtio_edu, 1); +MODULE_DEPEND(virtio_edu, virtio, 1, 1, 1); + +static int +vtedu_probe(device_t dev) +{ + return (VIRTIO_SIMPLE_PROBE(dev, virtio_edu)); +} + +static int +vtedu_attach(device_t dev) +{ + struct vtedu_softc *sc = device_get_softc(dev); + int error; + + sc->dev = dev; + mtx_init(&sc->lock, device_get_nameunit(dev), NULL, MTX_DEF); + + virtio_set_feature_desc(dev, vtedu_feature_descs); + + error = vtedu_negotiate_features(sc); + if (error != 0) + goto fail; + + error = vtedu_alloc_virtqueue(sc); + if (error != 0) + goto fail; + + error = virtio_setup_intr(dev, INTR_TYPE_MISC); + if (error != 0) + goto fail; + + sc->sg = sglist_alloc(2, M_WAITOK); + sc->cdev = make_dev(&vtedu_cdevsw, device_get_unit(dev), + UID_ROOT, GID_WHEEL, 0600, "vtedu%d", device_get_unit(dev)); + if (sc->cdev == NULL) { + error = ENXIO; + goto fail; + } + sc->cdev->si_drv1 = sc; + + device_printf(dev, "attached (features=0x%lx)\n", + (unsigned long)sc->features); + return (0); + +fail: + vtedu_detach(dev); + return (error); +} + +static int +vtedu_detach(device_t dev) +{ + struct vtedu_softc *sc = device_get_softc(dev); + + if (sc->cdev != NULL) { + destroy_dev(sc->cdev); + sc->cdev = NULL; + } + if (sc->sg != NULL) { + sglist_free(sc->sg); + sc->sg = NULL; + } + virtio_stop(dev); + if (mtx_initialized(&sc->lock)) + mtx_destroy(&sc->lock); + return (0); +} + +static int +vtedu_negotiate_features(struct vtedu_softc *sc) +{ + uint64_t features = VTEDU_FEATURES; + + sc->features = virtio_negotiate_features(sc->dev, features); + return (virtio_finalize_features(sc->dev)); +} + +static int +vtedu_alloc_virtqueue(struct vtedu_softc *sc) +{ + struct vq_alloc_info vq_info; + + VQ_ALLOC_INFO_INIT(&vq_info, 0, vtedu_vq_intr, sc, &sc->vq, + "%s request", device_get_nameunit(sc->dev)); + + return (virtio_alloc_virtqueues(sc->dev, 0, 1, &vq_info)); +} + +static int +vtedu_open(struct cdev *dev __unused, int oflags __unused, int devtype __unused, + struct thread *td __unused) +{ + return (0); +} + +static int +vtedu_write(struct cdev *dev, struct uio *uio, int flags __unused) +{ + struct vtedu_softc *sc = dev->si_drv1; + size_t n; + int error; + + n = uio->uio_resid; + if (n == 0 || n > VTEDU_BUF_SIZE) + return (EINVAL); + + mtx_lock(&sc->lock); + error = uiomove(sc->buf, n, uio); + if (error == 0) { + sc->buf_len = n; + sc->response_ready = false; + error = vtedu_submit_locked(sc); + } + mtx_unlock(&sc->lock); + return (error); +} + +static int +vtedu_read(struct cdev *dev, struct uio *uio, int flags __unused) +{ + struct vtedu_softc *sc = dev->si_drv1; + int error; + + mtx_lock(&sc->lock); + while (!sc->response_ready) { + error = mtx_sleep(sc, &sc->lock, PCATCH, "vteduR", 0); + if (error != 0) { + mtx_unlock(&sc->lock); + return (error); + } + } + error = uiomove(sc->buf, + MIN(sc->buf_len, (size_t)uio->uio_resid), uio); + sc->buf_len = 0; + sc->response_ready = false; + mtx_unlock(&sc->lock); + return (error); +} + +static int +vtedu_submit_locked(struct vtedu_softc *sc) +{ + int error; + + mtx_assert(&sc->lock, MA_OWNED); + + sglist_reset(sc->sg); + error = sglist_append(sc->sg, sc->buf, sc->buf_len); + if (error != 0) + return (error); + + error = virtqueue_enqueue(sc->vq, sc, sc->sg, 1, 1); + if (error != 0) + return (error); + + virtqueue_notify(sc->vq); + return (0); +} + +static void +vtedu_vq_intr(void *arg) +{ + struct vtedu_softc *sc = arg; + void *cookie; + uint32_t len; + + mtx_lock(&sc->lock); + while ((cookie = virtqueue_dequeue(sc->vq, &len)) != NULL) { + sc->buf_len = len; + sc->response_ready = true; + wakeup(sc); + } + mtx_unlock(&sc->lock); +} diff --git a/examples/part-07/ch31-security/lab01-unsafe/Makefile b/examples/part-07/ch31-security/lab01-unsafe/Makefile new file mode 100644 index 0000000..a03db4b --- /dev/null +++ b/examples/part-07/ch31-security/lab01-unsafe/Makefile @@ -0,0 +1,11 @@ +# Makefile for secdev - Chapter 31 Lab 1 (intentionally unsafe). +# +# This module is deliberately insecure and exists only as a teaching +# artefact. Later labs in this chapter show how to correct each bug. + +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab01-unsafe/secdev.c b/examples/part-07/ch31-security/lab01-unsafe/secdev.c new file mode 100644 index 0000000..a4fb262 --- /dev/null +++ b/examples/part-07/ch31-security/lab01-unsafe/secdev.c @@ -0,0 +1,205 @@ +/* + * secdev.c - Lab 1 of Chapter 31 (Security Best Practices). + * + * This module is intentionally INSECURE. It exists only as a teaching + * artefact. Do NOT use this code as a starting point for any real + * driver. Every "TODO: security issue" comment marks a specific bug + * that later labs will fix. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + /* 4 bytes of implicit padding on 64-bit builds. */ + uint64_t flags; + uint16_t id; + /* 6 bytes of implicit padding. */ + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_close_t secdev_close; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_close = secdev_close, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + /* + * TODO: security issue (missing privilege check). + * A real driver that exposes privileged functionality should call + * priv_check(td, PRIV_DRIVER) here and refuse non-privileged opens. + */ + return (0); +} + +static int +secdev_close(struct cdev *dev __unused, int fflag __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO: security issue (unchecked read length). + * This copies sc_buflen bytes regardless of caller buffer size and + * regardless of whether sc_buflen reflects valid data. + */ + error = uiomove(sc->sc_buf, sc->sc_buflen, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO: security issue (buffer overflow). + * uiomove is asked to move uio_resid bytes into a buffer of only + * SECDEV_BUFSIZE bytes. A write larger than SECDEV_BUFSIZE + * overflows kernel memory. + */ + error = uiomove(sc->sc_buf, uio->uio_resid, uio); + sc->sc_buflen = SECDEV_BUFSIZE - uio->uio_resid; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + /* + * TODO: security issue (information leak). + * info is not zeroed before fields are filled, so the padding + * bytes between fields carry whatever was on the kernel stack + * back to user space. + */ + info->version = 1; + info->flags = 0; + info->id = 42; + strncpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + /* + * TODO: security issue (unbounded log on bad input). + * Without rate limiting, a user loop of malformed ioctls can + * flood the kernel log. + */ + printf("secdev: unknown ioctl 0x%lx\n", cmd); + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + /* + * TODO: security issue (world-writable device node). + * 0666 lets every user on the system read and write the + * device. For a driver with any privileged surface this + * should be 0600 or 0660 with a trusted group. + */ + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (intentionally unsafe, Lab 1)\n"); + return (0); + + case MOD_UNLOAD: + /* + * TODO: security issue (unsafe detach order). + * Freeing the buffer before destroying the cdev races with + * in-flight reads and writes. + */ + free(sc->sc_buf, M_TEMP); + destroy_dev(sc->sc_cdev); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab02-bounds/Makefile b/examples/part-07/ch31-security/lab02-bounds/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab02-bounds/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab02-bounds/secdev.c b/examples/part-07/ch31-security/lab02-bounds/secdev.c new file mode 100644 index 0000000..35516bb --- /dev/null +++ b/examples/part-07/ch31-security/lab02-bounds/secdev.c @@ -0,0 +1,185 @@ +/* + * secdev.c - Lab 2 of Chapter 31 (starter file). + * + * This file is a copy of Lab 1 with "TODO(lab2)" markers added at the + * two places where you need to add bounds checks. Your task is to make + * sc_buf-sized reads and writes safe regardless of what the caller asks + * for. + * + * The buffer overflow and the unchecked read length are the only two + * issues you are asked to fix in this lab. Do not worry about the + * information leak, the privilege check, the logging rate, or the + * detach order here; they are covered in later labs. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_close_t secdev_close; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_close = secdev_close, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_close(struct cdev *dev __unused, int fflag __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO(lab2): replace the unbounded read with a bounded one. The + * caller may request more or fewer bytes than sc_buflen; copy out + * only min(sc_buflen - uio_offset, uio_resid) bytes. If + * uio_offset is already past the valid data, return 0 bytes. + */ + error = uiomove(sc->sc_buf, sc->sc_buflen, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO(lab2): clamp the copy length to SECDEV_BUFSIZE. A common + * pattern is: + * + * size_t amount = MIN(uio->uio_resid, SECDEV_BUFSIZE); + * error = uiomove(sc->sc_buf, amount, uio); + * + * Remember to update sc_buflen to reflect how many bytes were + * actually copied. + */ + error = uiomove(sc->sc_buf, uio->uio_resid, uio); + sc->sc_buflen = SECDEV_BUFSIZE - uio->uio_resid; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + info->version = 1; + info->flags = 0; + info->id = 42; + strncpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 2 starter)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab02-fixed/Makefile b/examples/part-07/ch31-security/lab02-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab02-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab02-fixed/secdev.c b/examples/part-07/ch31-security/lab02-fixed/secdev.c new file mode 100644 index 0000000..2928abe --- /dev/null +++ b/examples/part-07/ch31-security/lab02-fixed/secdev.c @@ -0,0 +1,171 @@ +/* + * secdev.c - Lab 2 of Chapter 31 (fixed). + * + * Adds bounds checks to the read and write paths. Every other bug + * from Lab 1 is preserved for later labs to fix. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_close_t secdev_close; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_close = secdev_close, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_close(struct cdev *dev __unused, int fflag __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + info->version = 1; + info->flags = 0; + info->id = 42; + strncpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 2 fixed)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab03-fixed/Makefile b/examples/part-07/ch31-security/lab03-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab03-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab03-fixed/secdev.c b/examples/part-07/ch31-security/lab03-fixed/secdev.c new file mode 100644 index 0000000..93d4ee2 --- /dev/null +++ b/examples/part-07/ch31-security/lab03-fixed/secdev.c @@ -0,0 +1,164 @@ +/* + * secdev.c - Lab 3 of Chapter 31 (fixed). + * + * Information-leak fix: the SECDEV_GET_INFO ioctl zeros its output + * structure before populating it and uses strlcpy for the name. + * Padding bytes are always zero, so the ioctl no longer carries + * kernel memory contents to user space. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 3 fixed)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab03-info-leak/Makefile b/examples/part-07/ch31-security/lab03-info-leak/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab03-info-leak/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab03-info-leak/secdev.c b/examples/part-07/ch31-security/lab03-info-leak/secdev.c new file mode 100644 index 0000000..909c934 --- /dev/null +++ b/examples/part-07/ch31-security/lab03-info-leak/secdev.c @@ -0,0 +1,182 @@ +/* + * secdev.c - Lab 3 of Chapter 31 (starter file). + * + * Information-leak focus. The SECDEV_GET_INFO ioctl returns a + * structure that contains implicit padding on 64-bit builds. Because + * the structure is never zeroed before being populated, the padding + * bytes carry whatever was on the kernel stack back to user space. + * + * A companion test program lives in test/leak_check.c. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + /* 4 bytes of implicit padding on 64-bit builds. */ + uint64_t flags; + uint16_t id; + /* 6 bytes of implicit padding before name. */ + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + /* + * TODO(lab3): zero the structure before filling it. + * A single bzero(info, sizeof(*info)) closes the leak. An + * alternative is to declare a local stack copy initialised + * with "= { 0 }" and to memcpy it into *info at the end, + * but the in-place bzero is simplest. + */ + info->version = 1; + info->flags = 0; + info->id = 42; + /* + * TODO(lab3): use strlcpy (or snprintf) so name is always + * NUL-terminated and we do not copy past the end of the + * source string. strncpy does not guarantee NUL + * termination and will pad the tail with zeroes, which + * happens to be safe here only because sizeof(name) is + * larger than the source. + */ + strncpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 3 starter, leaks padding)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab03-info-leak/test/leak_check.c b/examples/part-07/ch31-security/lab03-info-leak/test/leak_check.c new file mode 100644 index 0000000..b8b6e66 --- /dev/null +++ b/examples/part-07/ch31-security/lab03-info-leak/test/leak_check.c @@ -0,0 +1,89 @@ +/* + * leak_check.c - companion test program for Chapter 31 Lab 3. + * + * Issues SECDEV_GET_INFO multiple times and dumps the returned + * structure as a hex dump. With the unfixed driver you should see + * non-zero bytes in the padding slots that differ between invocations. + * Those bytes are whatever happened to be on the kernel stack when the + * structure was populated. + * + * Build on the host: + * cc -Wall -O2 -o leak_check leak_check.c + * + * Run (with the module loaded and /dev/secdev accessible): + * ./leak_check 5 + */ + +#include +#include +#include +#include +#include +#include +#include + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +static void +hex_dump(const void *buf, size_t len) +{ + const unsigned char *p = buf; + + for (size_t i = 0; i < len; i++) { + printf("%02x", p[i]); + if ((i + 1) % 8 == 0) + printf(" "); + if ((i + 1) % 16 == 0) + printf("\n"); + } + if (len % 16 != 0) + printf("\n"); +} + +int +main(int argc, char *argv[]) +{ + int fd, n = 5; + + if (argc >= 2) + n = atoi(argv[1]); + + fd = open("/dev/secdev", O_RDWR); + if (fd < 0) { + perror("open /dev/secdev"); + return (1); + } + + printf("sizeof(struct secdev_info) = %zu bytes\n", + sizeof(struct secdev_info)); + for (int i = 0; i < n; i++) { + struct secdev_info info; + + /* + * Pre-fill with a recognisable pattern so we can tell + * which bytes the driver overwrites and which it leaves + * untouched. The ioctl is _IOR (kernel -> user) so the + * kernel will overwrite the whole buffer in the copyout + * path, but zeroing here before the call still helps us + * reason about the driver's own fill behaviour in the + * INOUT case. + */ + memset(&info, 0xaa, sizeof(info)); + if (ioctl(fd, SECDEV_GET_INFO, &info) < 0) { + perror("ioctl"); + close(fd); + return (1); + } + printf("--- invocation %d ---\n", i + 1); + hex_dump(&info, sizeof(info)); + } + close(fd); + return (0); +} diff --git a/examples/part-07/ch31-security/lab04-fixed/Makefile b/examples/part-07/ch31-security/lab04-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab04-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab04-fixed/secdev.c b/examples/part-07/ch31-security/lab04-fixed/secdev.c new file mode 100644 index 0000000..116c7eb --- /dev/null +++ b/examples/part-07/ch31-security/lab04-fixed/secdev.c @@ -0,0 +1,174 @@ +/* + * secdev.c - Lab 4 of Chapter 31 (fixed). + * + * Adds two layers of access control: + * - filesystem-level: device-node mode 0600, root owner + * - in-kernel: priv_check(td, PRIV_DRIVER) in d_open plus a + * jailed(td->td_ucred) refusal + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 4 fixed, root only)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab04-privilege/Makefile b/examples/part-07/ch31-security/lab04-privilege/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab04-privilege/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab04-privilege/secdev.c b/examples/part-07/ch31-security/lab04-privilege/secdev.c new file mode 100644 index 0000000..1c5f80d --- /dev/null +++ b/examples/part-07/ch31-security/lab04-privilege/secdev.c @@ -0,0 +1,181 @@ +/* + * secdev.c - Lab 4 of Chapter 31 (starter file). + * + * Privilege-check focus. The starter still creates the device node + * world-writable and allows any caller to open it. Your task is to + * restrict access to privileged users and to close the jail escape + * path. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + + /* + * TODO(lab4): add a priv_check(td, PRIV_DRIVER) call here and + * return the error it produces if the caller lacks privilege. + * + * TODO(lab4): additionally refuse opens from jailed credentials + * with jailed(td->td_ucred). Device nodes can be exposed inside + * a jail, so the in-kernel check is the last defence. + */ + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + /* + * TODO(lab4): change the default device-node mode to 0600 + * so that the filesystem layer alone blocks unprivileged + * access. This is the outer layer of the defence. + */ + args.mda_mode = 0666; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 4 starter)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab05-fixed/Makefile b/examples/part-07/ch31-security/lab05-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab05-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab05-fixed/secdev.c b/examples/part-07/ch31-security/lab05-fixed/secdev.c new file mode 100644 index 0000000..dc9155c --- /dev/null +++ b/examples/part-07/ch31-security/lab05-fixed/secdev.c @@ -0,0 +1,181 @@ +/* + * secdev.c - Lab 5 of Chapter 31 (fixed). + * + * Adds a ppsratecheck-gated log line to the default branch of the + * ioctl dispatcher. A process that issues malformed ioctls in a + * tight loop can no longer flood dmesg. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +static struct timeval secdev_log_last; +static int secdev_log_pps; + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td) +{ + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + if (ppsratecheck(&secdev_log_last, &secdev_log_pps, 5)) { + printf("secdev: unknown ioctl 0x%lx from uid %u\n", + cmd, td->td_ucred->cr_uid); + } + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 5 fixed)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab05-ratelimit/Makefile b/examples/part-07/ch31-security/lab05-ratelimit/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab05-ratelimit/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab05-ratelimit/secdev.c b/examples/part-07/ch31-security/lab05-ratelimit/secdev.c new file mode 100644 index 0000000..7132629 --- /dev/null +++ b/examples/part-07/ch31-security/lab05-ratelimit/secdev.c @@ -0,0 +1,194 @@ +/* + * secdev.c - Lab 5 of Chapter 31 (starter file). + * + * Rate-limited logging. Without a rate limiter, a user process that + * issues malformed ioctls in a tight loop can overwhelm dmesg and the + * console. Your task is to add a ppsratecheck-gated log message in + * the default branch of secdev_ioctl. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; +}; + +static struct secdev_softc secdev_sc; + +/* + * TODO(lab5): declare the rate-limit state for ppsratecheck. You need + * a "struct timeval" (for the last-seen timestamp) and an "int" (for + * the current per-second count). Give them file-scope storage so the + * counters persist across calls. + */ + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) + sc->sc_buflen = amount; + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td) +{ + struct secdev_softc *sc = &secdev_sc; + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + default: + /* + * TODO(lab5): gate the message with ppsratecheck so that a + * flood of malformed ioctls cannot flood dmesg. Aim for at + * most 5 messages per second. A good template is: + * + * if (ppsratecheck(&secdev_log_last, &secdev_log_pps, 5)) + * device_printf(sc->sc_cdev->si_drv1, ...); + * + * For this Lab we use device_printf indirectly; the book's + * later labs move to a proper newbus device_t. + */ + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 5 starter)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab05-ratelimit/test/flood.c b/examples/part-07/ch31-security/lab05-ratelimit/test/flood.c new file mode 100644 index 0000000..c82c466 --- /dev/null +++ b/examples/part-07/ch31-security/lab05-ratelimit/test/flood.c @@ -0,0 +1,40 @@ +/* + * flood.c - companion test program for Chapter 31 Lab 5. + * + * Opens /dev/secdev and issues a million unknown ioctls as fast as + * possible. Without rate limiting this floods dmesg; with the fix + * applied, the kernel should log at most about five messages per + * second regardless of how fast the calls arrive. + * + * Must be run as root because the driver refuses unprivileged opens. + * + * Build: cc -Wall -O2 -o flood flood.c + * Usage: ./flood [iterations] + */ + +#include +#include +#include +#include +#include + +int +main(int argc, char *argv[]) +{ + int fd; + long iters = 1000000L; + + if (argc >= 2) + iters = atol(argv[1]); + + fd = open("/dev/secdev", O_RDWR); + if (fd < 0) { + perror("open /dev/secdev"); + return (1); + } + for (long i = 0; i < iters; i++) + (void)ioctl(fd, 0xdeadbeefUL, NULL); + close(fd); + printf("issued %ld unknown ioctls\n", iters); + return (0); +} diff --git a/examples/part-07/ch31-security/lab06-detach/Makefile b/examples/part-07/ch31-security/lab06-detach/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab06-detach/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab06-detach/secdev.c b/examples/part-07/ch31-security/lab06-detach/secdev.c new file mode 100644 index 0000000..b98d74e --- /dev/null +++ b/examples/part-07/ch31-security/lab06-detach/secdev.c @@ -0,0 +1,164 @@ +/* + * secdev.c - Lab 6 of Chapter 31 (starter file). + * + * Detach-race focus. This version adds a periodic callout (to + * simulate asynchronous work) and a slow ioctl (SECDEV_SLEEP) that + * spends a little time in the d_ioctl handler. The detach function + * is intentionally flawed: it frees resources without draining the + * callout and without stopping new ioctls from entering the driver. + * Your task is to reorder cleanup so that concurrent activity cannot + * reach freed memory. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +#define SECDEV_SLEEP _IO('S', 2) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; + struct callout sc_callout; + uint64_t sc_ticks; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static void +secdev_timer(void *arg) +{ + struct secdev_softc *sc = arg; + + mtx_lock(&sc->sc_mtx); + sc->sc_ticks++; + mtx_unlock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); +} + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + return (0); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data __unused, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_softc *sc = &secdev_sc; + + switch (cmd) { + case SECDEV_SLEEP: + /* Simulate slow work by sleeping briefly. */ + pause("secdev", hz / 10); + mtx_lock(&sc->sc_mtx); + sc->sc_ticks++; + mtx_unlock(&sc->sc_mtx); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + mtx_lock(&sc->sc_mtx); + callout_stop(&sc->sc_callout); + mtx_unlock(&sc->sc_mtx); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 6 starter, unsafe detach)\n"); + return (0); + + case MOD_UNLOAD: + /* + * TODO(lab6): reorder this cleanup so that it is safe + * under concurrent activity. The correct sequence is: + * + * 1. destroy_dev(sc->sc_cdev) // no new d_* enters + * 2. callout_drain(&sc->sc_callout) // no pending callout + * 3. free(sc->sc_buf, M_TEMP) + * 4. mtx_destroy(&sc->sc_mtx) + * + * Each step closes a door; the next step may safely release + * memory nothing can reach. + */ + free(sc->sc_buf, M_TEMP); + callout_stop(&sc->sc_callout); + destroy_dev(sc->sc_cdev); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab06-detach/test/spin.c b/examples/part-07/ch31-security/lab06-detach/test/spin.c new file mode 100644 index 0000000..24c0450 --- /dev/null +++ b/examples/part-07/ch31-security/lab06-detach/test/spin.c @@ -0,0 +1,37 @@ +/* + * spin.c - companion test program for Chapter 31 Lab 6. + * + * Opens /dev/secdev and hammers the SECDEV_SLEEP ioctl in a loop. + * Running this while another terminal issues `kldunload secdev` + * exercises the detach race. + * + * Build: cc -Wall -O2 -o spin spin.c + * Usage: sudo ./spin + */ + +#include +#include +#include +#include + +#define SECDEV_SLEEP _IO('S', 2) + +int +main(void) +{ + int fd; + + fd = open("/dev/secdev", O_RDWR); + if (fd < 0) { + perror("open /dev/secdev"); + return (1); + } + for (;;) { + if (ioctl(fd, SECDEV_SLEEP, NULL) < 0) { + perror("ioctl SECDEV_SLEEP"); + break; + } + } + close(fd); + return (0); +} diff --git a/examples/part-07/ch31-security/lab06-fixed/Makefile b/examples/part-07/ch31-security/lab06-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab06-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab06-fixed/secdev.c b/examples/part-07/ch31-security/lab06-fixed/secdev.c new file mode 100644 index 0000000..dba9ff6 --- /dev/null +++ b/examples/part-07/ch31-security/lab06-fixed/secdev.c @@ -0,0 +1,149 @@ +/* + * secdev.c - Lab 6 of Chapter 31 (fixed). + * + * Safe detach. The MOD_UNLOAD case closes doors in the right order: + * + * 1. destroy_dev (no new d_* entries; in-flight d_* drain) + * 2. callout_drain (no pending or running callback) + * 3. free (memory can now be released safely) + * 4. mtx_destroy (lock is no longer held or waited on) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +#define SECDEV_SLEEP _IO('S', 2) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; + struct callout sc_callout; + uint64_t sc_ticks; +}; + +static struct secdev_softc secdev_sc; + +static d_open_t secdev_open; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static void +secdev_timer(void *arg) +{ + struct secdev_softc *sc = arg; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + sc->sc_ticks++; + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); +} + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + return (0); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data __unused, + int fflag __unused, struct thread *td __unused) +{ + struct secdev_softc *sc = &secdev_sc; + + switch (cmd) { + case SECDEV_SLEEP: + pause("secdev", hz / 10); + mtx_lock(&sc->sc_mtx); + sc->sc_ticks++; + mtx_unlock(&sc->sc_mtx); + return (0); + default: + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); + mtx_unlock(&sc->sc_mtx); + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + callout_drain(&sc->sc_callout); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 6 fixed)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + callout_drain(&sc->sc_callout); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab07-fixed/Makefile b/examples/part-07/ch31-security/lab07-fixed/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab07-fixed/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab07-fixed/secdev.c b/examples/part-07/ch31-security/lab07-fixed/secdev.c new file mode 100644 index 0000000..72f9497 --- /dev/null +++ b/examples/part-07/ch31-security/lab07-fixed/secdev.c @@ -0,0 +1,263 @@ +/* + * secdev.c - Lab 7 of Chapter 31 (fully secure reference). + * + * Consolidation of every defence introduced in Labs 1 through 6 plus + * a handful of additional measures that round out the driver's + * defensive posture: + * + * - Driver-private MALLOC_DEFINE tag so allocations appear in + * vmstat -m under a recognisable name. + * - make_dev_s with mode 0600, UID_ROOT, GID_WHEEL. + * - priv_check(PRIV_DRIVER) and jailed() refusal in d_open. + * - Bounds checks on every read, write, and ioctl path. + * - bzero before every copyout; strlcpy for strings. + * - M_ZERO on every allocation. + * - explicit_bzero on sensitive buffer before free. + * - ppsratecheck-gated log message on the unknown-ioctl path. + * - destroy_dev -> callout_drain -> free -> mtx_destroy on unload. + * - sysctl-controlled debug flag (secdev_debug). + * - KASSERT statements documenting internal invariants. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +static MALLOC_DEFINE(M_SECDEV, "secdev", "Chapter 31 secdev driver"); + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) +#define SECDEV_SLEEP _IO('S', 2) +#define SECDEV_WIPE _IO('S', 3) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; + struct callout sc_callout; + uint64_t sc_ticks; +}; + +static struct secdev_softc secdev_sc; + +static struct timeval secdev_log_last; +static int secdev_log_pps; +static int secdev_debug = 0; + +static SYSCTL_NODE(_debug, OID_AUTO, secdev, + CTLFLAG_RW | CTLFLAG_MPSAFE, 0, + "secdev teaching driver"); +SYSCTL_INT(_debug_secdev, OID_AUTO, debug, + CTLFLAG_RWTUN, &secdev_debug, 0, + "Enable verbose diagnostic logging (0 = off, 1 = on)"); + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static void +secdev_timer(void *arg) +{ + struct secdev_softc *sc = arg; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + sc->sc_ticks++; + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); +} + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + int error; + + if (jailed(td->td_ucred)) + return (EPERM); + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + if (secdev_debug) { + printf("secdev: open from uid %u\n", + td->td_ucred->cr_uid); + } + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + KASSERT(sc->sc_buf != NULL, ("secdev_read: sc_buf is NULL")); + + mtx_lock(&sc->sc_mtx); + KASSERT(sc->sc_buflen <= SECDEV_BUFSIZE, + ("secdev_read: sc_buflen %zu exceeds SECDEV_BUFSIZE", + sc->sc_buflen)); + if ((size_t)uio->uio_offset >= sc->sc_buflen) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + available = sc->sc_buflen - (size_t)uio->uio_offset; + error = uiomove(sc->sc_buf + uio->uio_offset, available, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t amount; + int error; + + mtx_lock(&sc->sc_mtx); + amount = MIN((size_t)uio->uio_resid, SECDEV_BUFSIZE); + error = uiomove(sc->sc_buf, amount, uio); + if (error == 0) { + sc->sc_buflen = amount; + KASSERT(sc->sc_buflen <= SECDEV_BUFSIZE, + ("secdev_write: sc_buflen %zu exceeds SECDEV_BUFSIZE", + sc->sc_buflen)); + } + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td) +{ + struct secdev_softc *sc = &secdev_sc; + struct secdev_info *info; + int error; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + bzero(info, sizeof(*info)); + info->version = 1; + info->flags = 0; + info->id = 42; + strlcpy(info->name, "secdev", sizeof(info->name)); + return (0); + + case SECDEV_SLEEP: + pause("secdev", hz / 10); + mtx_lock(&sc->sc_mtx); + sc->sc_ticks++; + mtx_unlock(&sc->sc_mtx); + return (0); + + case SECDEV_WIPE: + error = priv_check(td, PRIV_DRIVER); + if (error != 0) + return (error); + mtx_lock(&sc->sc_mtx); + explicit_bzero(sc->sc_buf, SECDEV_BUFSIZE); + sc->sc_buflen = 0; + mtx_unlock(&sc->sc_mtx); + return (0); + + default: + if (ppsratecheck(&secdev_log_last, &secdev_log_pps, 5)) { + printf("secdev: unknown ioctl 0x%lx from uid %u\n", + cmd, td->td_ucred->cr_uid); + } + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_SECDEV, + M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, secdev_timer, sc); + mtx_unlock(&sc->sc_mtx); + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + callout_drain(&sc->sc_callout); + explicit_bzero(sc->sc_buf, SECDEV_BUFSIZE); + free(sc->sc_buf, M_SECDEV); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 7 fixed)\n"); + return (0); + + case MOD_UNLOAD: + destroy_dev(sc->sc_cdev); + callout_drain(&sc->sc_callout); + explicit_bzero(sc->sc_buf, SECDEV_BUFSIZE); + free(sc->sc_buf, M_SECDEV); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch31-security/lab07-secure/Makefile b/examples/part-07/ch31-security/lab07-secure/Makefile new file mode 100644 index 0000000..4154637 --- /dev/null +++ b/examples/part-07/ch31-security/lab07-secure/Makefile @@ -0,0 +1,6 @@ +KMOD= secdev +SRCS= secdev.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch31-security/lab07-secure/secdev.c b/examples/part-07/ch31-security/lab07-secure/secdev.c new file mode 100644 index 0000000..f4bfb17 --- /dev/null +++ b/examples/part-07/ch31-security/lab07-secure/secdev.c @@ -0,0 +1,244 @@ +/* + * secdev.c - Lab 7 of Chapter 31 (skeleton). + * + * This is the consolidation lab. Fill in each TODO(lab7) marker, + * applying every lesson from Labs 1 through 6 plus any additional + * defensive measures you think the driver warrants. When you are + * finished the driver should satisfy every item on the Security + * Checklist at the end of the chapter. + * + * The reference solution is in ../lab07-fixed/. Try to complete this + * skeleton without peeking; your version may diverge from the + * reference in details, and that is fine as long as it is secure. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECDEV_BUFSIZE 4096 + +/* + * TODO(lab7): define a MALLOC_DECLARE / MALLOC_DEFINE for this + * driver's own memory tag so that vmstat -m makes the allocations + * visible to the operator. Free it in MOD_UNLOAD if you use + * MALLOC_DEFINE. + */ + +struct secdev_info { + uint32_t version; + uint64_t flags; + uint16_t id; + char name[32]; +}; + +#define SECDEV_GET_INFO _IOR('S', 1, struct secdev_info) +#define SECDEV_SLEEP _IO('S', 2) +#define SECDEV_WIPE _IO('S', 3) + +struct secdev_softc { + struct mtx sc_mtx; + struct cdev *sc_cdev; + char *sc_buf; + size_t sc_buflen; + struct callout sc_callout; +}; + +static struct secdev_softc secdev_sc; + +/* + * TODO(lab7): declare rate-limit state for the unknown-ioctl log and + * a sysctl-controlled debug flag that gates verbose diagnostic + * messages. An OID per driver is common; see CTLFLAG_RWTUN. + */ + +static d_open_t secdev_open; +static d_read_t secdev_read; +static d_write_t secdev_write; +static d_ioctl_t secdev_ioctl; + +static struct cdevsw secdev_cdevsw = { + .d_version = D_VERSION, + .d_open = secdev_open, + .d_read = secdev_read, + .d_write = secdev_write, + .d_ioctl = secdev_ioctl, + .d_name = "secdev", +}; + +static int +secdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td) +{ + + /* + * TODO(lab7): refuse opens from jailed credentials, refuse at + * elevated securelevel where appropriate, and call priv_check + * (or priv_check_cred) to enforce the in-kernel privilege + * requirement. + */ + (void)td; + return (0); +} + +static int +secdev_read(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + size_t available; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO(lab7): honour uio_offset so partial reads work. Copy + * out only as many bytes as are valid in sc_buf. + */ + (void)available; + error = uiomove(sc->sc_buf, sc->sc_buflen, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_write(struct cdev *dev __unused, struct uio *uio, int ioflag __unused) +{ + struct secdev_softc *sc = &secdev_sc; + int error; + + mtx_lock(&sc->sc_mtx); + /* + * TODO(lab7): clamp the copy length to SECDEV_BUFSIZE and + * update sc_buflen accordingly. Consider returning EFBIG if + * the caller asked for more than the driver can hold; the + * silent-truncate behaviour is not always what you want. + */ + error = uiomove(sc->sc_buf, uio->uio_resid, uio); + mtx_unlock(&sc->sc_mtx); + return (error); +} + +static int +secdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td) +{ + struct secdev_softc *sc = &secdev_sc; + struct secdev_info *info; + + switch (cmd) { + case SECDEV_GET_INFO: + info = (struct secdev_info *)data; + /* + * TODO(lab7): zero the structure before filling it, then + * use strlcpy for any string field. Re-check sign of id + * if the field type changes. + */ + info->version = 1; + info->flags = 0; + info->id = 42; + strncpy(info->name, "secdev", sizeof(info->name)); + return (0); + case SECDEV_SLEEP: + pause("secdev", hz / 10); + return (0); + case SECDEV_WIPE: + /* + * TODO(lab7): require PRIV_DRIVER (or a more specific + * privilege) with priv_check. Zero the buffer with + * explicit_bzero so the optimiser cannot elide the clear. + */ + mtx_lock(&sc->sc_mtx); + bzero(sc->sc_buf, SECDEV_BUFSIZE); + sc->sc_buflen = 0; + mtx_unlock(&sc->sc_mtx); + return (0); + default: + /* + * TODO(lab7): log the unknown-ioctl event through a + * ppsratecheck gate so that a flood of malformed ioctls + * cannot flood dmesg. Include the uid from + * td->td_ucred->cr_uid in the message. + */ + (void)td; + return (ENOTTY); + } +} + +static int +secdev_modevent(module_t mod __unused, int event, void *arg __unused) +{ + struct secdev_softc *sc = &secdev_sc; + struct make_dev_args args; + int error; + + switch (event) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "secdev", NULL, MTX_DEF); + /* + * TODO(lab7): replace M_TEMP with your private + * MALLOC_DEFINE tag and always include M_ZERO when the + * buffer may be copied to user space. + */ + sc->sc_buf = malloc(SECDEV_BUFSIZE, M_TEMP, M_WAITOK | M_ZERO); + sc->sc_buflen = 0; + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + make_dev_args_init(&args); + args.mda_devsw = &secdev_cdevsw; + args.mda_uid = UID_ROOT; + args.mda_gid = GID_WHEEL; + /* + * TODO(lab7): use 0600 by default; think carefully before + * picking anything looser. If the device should be + * accessible to a specific group, set that group here and + * document the trust model in the README. + */ + args.mda_mode = 0600; + + error = make_dev_s(&args, &sc->sc_cdev, "secdev"); + if (error != 0) { + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + return (error); + } + printf("secdev: loaded (Lab 7 skeleton)\n"); + return (0); + + case MOD_UNLOAD: + /* + * TODO(lab7): close doors in the right order: + * destroy_dev -> callout_drain -> explicit_bzero of the + * sensitive buffer -> free -> mtx_destroy. + */ + destroy_dev(sc->sc_cdev); + free(sc->sc_buf, M_TEMP); + mtx_destroy(&sc->sc_mtx); + printf("secdev: unloaded\n"); + return (0); + + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t secdev_mod = { + "secdev", + secdev_modevent, + NULL +}; + +DECLARE_MODULE(secdev, secdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(secdev, 1); diff --git a/examples/part-07/ch32-fdt-embedded/lab01-fdthello/Makefile b/examples/part-07/ch32-fdt-embedded/lab01-fdthello/Makefile new file mode 100644 index 0000000..5bb7882 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab01-fdthello/Makefile @@ -0,0 +1,6 @@ +KMOD= fdthello +SRCS= fdthello.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch32-fdt-embedded/lab01-fdthello/fdthello.c b/examples/part-07/ch32-fdt-embedded/lab01-fdthello/fdthello.c new file mode 100644 index 0000000..d88d411 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab01-fdthello/fdthello.c @@ -0,0 +1,82 @@ +/* + * fdthello.c - Minimal FDT-aware driver skeleton + * + * Companion source file for Chapter 32, Section 4 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * This driver matches a Device Tree node with + * compatible = "freebsd,fdthello"; + * and logs its attach and detach. It does nothing useful on its own; + * it is a starting skeleton for any further FDT driver you write. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +struct fdthello_softc { + device_t sc_dev; +}; + +static const struct ofw_compat_data compat_data[] = { + {"freebsd,fdthello", 1}, + {NULL, 0} +}; + +static int +fdthello_probe(device_t dev) +{ + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + + if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) + return (ENXIO); + + device_set_desc(dev, "FDT Hello Example"); + return (BUS_PROBE_DEFAULT); +} + +static int +fdthello_attach(device_t dev) +{ + struct fdthello_softc *sc = device_get_softc(dev); + phandle_t node = ofw_bus_get_node(dev); + + sc->sc_dev = dev; + device_printf(dev, "attached, node phandle 0x%lx\n", + (unsigned long)node); + return (0); +} + +static int +fdthello_detach(device_t dev) +{ + device_printf(dev, "detached\n"); + return (0); +} + +static device_method_t fdthello_methods[] = { + DEVMETHOD(device_probe, fdthello_probe), + DEVMETHOD(device_attach, fdthello_attach), + DEVMETHOD(device_detach, fdthello_detach), + DEVMETHOD_END +}; + +static driver_t fdthello_driver = { + "fdthello", + fdthello_methods, + sizeof(struct fdthello_softc) +}; + +DRIVER_MODULE(fdthello, simplebus, fdthello_driver, 0, 0); +DRIVER_MODULE(fdthello, ofwbus, fdthello_driver, 0, 0); +MODULE_VERSION(fdthello, 1); diff --git a/examples/part-07/ch32-fdt-embedded/lab02-overlay/fdthello-overlay.dts b/examples/part-07/ch32-fdt-embedded/lab02-overlay/fdthello-overlay.dts new file mode 100644 index 0000000..f718fc3 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab02-overlay/fdthello-overlay.dts @@ -0,0 +1,27 @@ +/* + * fdthello-overlay.dts - Overlay that adds an fdthello DT node + * + * Companion overlay for Chapter 32, Section 5 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * Targets the /soc node of a Raspberry Pi 4 base tree and adds a + * fdthello@20000 child that matches the driver from Lab 1. + */ + +/dts-v1/; +/plugin/; + +/ { + compatible = "brcm,bcm2711"; + + fragment@0 { + target-path = "/soc"; + __overlay__ { + hello@20000 { + compatible = "freebsd,fdthello"; + reg = <0x20000 0x100>; + status = "okay"; + }; + }; + }; +}; diff --git a/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-broken.dts b/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-broken.dts new file mode 100644 index 0000000..d410cd5 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-broken.dts @@ -0,0 +1,48 @@ +/* + * lab03-broken.dts - Deliberately broken overlay for debugging practice + * + * Companion source for Chapter 32, Section 6 and Lab 3 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * This overlay contains three distinct bugs that prevent the + * fdthello driver from attaching. Identify and fix each one. + * + * Bug 1: fragment@0 has a typo in the compatible string. + * "free-bsd,fdthello" (extra hyphen) + * Bug 2: fragment@0 node is disabled via status = "disabled". + * Bug 3: fragment@1 has a malformed reg property with only one cell + * when the parent declares #address-cells = <1> and + * #size-cells = <1>. + * + * Each bug produces a distinct symptom. Work through the debugging + * checklist in Chapter 32, Section 6 and the lab writeup to find them. + */ + +/dts-v1/; +/plugin/; + +/ { + compatible = "brcm,bcm2711"; + + fragment@0 { + target-path = "/soc"; + __overlay__ { + hello@20000 { + compatible = "free-bsd,fdthello"; + reg = <0x20000 0x100>; + status = "disabled"; + }; + }; + }; + + fragment@1 { + target-path = "/soc"; + __overlay__ { + hello@30000 { + compatible = "freebsd,fdthello"; + reg = <0x30000>; + status = "okay"; + }; + }; + }; +}; diff --git a/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-fixed.dts b/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-fixed.dts new file mode 100644 index 0000000..9a19e30 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab03-debug-broken/lab03-fixed.dts @@ -0,0 +1,37 @@ +/* + * lab03-fixed.dts - Reference corrected overlay for Lab 3 + * + * Fixes applied: + * - fragment@0 compatible corrected to "freebsd,fdthello" + * - fragment@0 status set to "okay" + * - fragment@1 reg corrected to include size cell + */ + +/dts-v1/; +/plugin/; + +/ { + compatible = "brcm,bcm2711"; + + fragment@0 { + target-path = "/soc"; + __overlay__ { + hello@20000 { + compatible = "freebsd,fdthello"; + reg = <0x20000 0x100>; + status = "okay"; + }; + }; + }; + + fragment@1 { + target-path = "/soc"; + __overlay__ { + hello@30000 { + compatible = "freebsd,fdthello"; + reg = <0x30000 0x100>; + status = "okay"; + }; + }; + }; +}; diff --git a/examples/part-07/ch32-fdt-embedded/lab04-edled/Makefile b/examples/part-07/ch32-fdt-embedded/lab04-edled/Makefile new file mode 100644 index 0000000..b66937d --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab04-edled/Makefile @@ -0,0 +1,6 @@ +KMOD= edled +SRCS= edled.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.c b/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.c new file mode 100644 index 0000000..e541020 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.c @@ -0,0 +1,152 @@ +/* + * edled.c - Example Embedded LED Driver + * + * Companion source for Chapter 32, Section 7 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * Demonstrates a minimal FDT-driven GPIO consumer on FreeBSD 14.3: + * - matches a DT node with compatible = "example,edled" + * - acquires a GPIO pin listed in the "leds-gpios" property + * - exposes dev.edled..state as a read/write sysctl + * - releases the pin cleanly on detach + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +struct edled_softc { + device_t sc_dev; + gpio_pin_t sc_pin; + int sc_on; + struct sysctl_oid *sc_oid; +}; + +static const struct ofw_compat_data compat_data[] = { + {"example,edled", 1}, + {NULL, 0} +}; + +static int edled_sysctl_state(SYSCTL_HANDLER_ARGS); + +static int +edled_probe(device_t dev) +{ + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) + return (ENXIO); + device_set_desc(dev, "Example embedded LED"); + return (BUS_PROBE_DEFAULT); +} + +static int +edled_attach(device_t dev) +{ + struct edled_softc *sc = device_get_softc(dev); + phandle_t node = ofw_bus_get_node(dev); + int error; + + sc->sc_dev = dev; + sc->sc_on = 0; + + error = gpio_pin_get_by_ofw_property(dev, node, + "leds-gpios", &sc->sc_pin); + if (error != 0) { + device_printf(dev, "cannot get GPIO pin: %d\n", error); + goto fail; + } + + error = gpio_pin_setflags(sc->sc_pin, GPIO_PIN_OUTPUT); + if (error != 0) { + device_printf(dev, "cannot set pin flags: %d\n", error); + goto fail; + } + + error = gpio_pin_set_active(sc->sc_pin, 0); + if (error != 0) { + device_printf(dev, "cannot set pin state: %d\n", error); + goto fail; + } + + sc->sc_oid = SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev), + SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), + OID_AUTO, "state", + CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, + sc, 0, edled_sysctl_state, "I", "LED state (0=off, 1=on)"); + + device_printf(dev, "attached, GPIO pin acquired, state=0\n"); + return (0); + +fail: + if (sc->sc_pin != NULL) { + gpio_pin_release(sc->sc_pin); + sc->sc_pin = NULL; + } + return (error); +} + +static int +edled_detach(device_t dev) +{ + struct edled_softc *sc = device_get_softc(dev); + + if (sc->sc_pin != NULL) { + (void)gpio_pin_set_active(sc->sc_pin, 0); + gpio_pin_release(sc->sc_pin); + sc->sc_pin = NULL; + } + device_printf(dev, "detached\n"); + return (0); +} + +static int +edled_sysctl_state(SYSCTL_HANDLER_ARGS) +{ + struct edled_softc *sc = arg1; + int val = sc->sc_on; + int error; + + error = sysctl_handle_int(oidp, &val, 0, req); + if (error != 0 || req->newptr == NULL) + return (error); + + if (val != 0 && val != 1) + return (EINVAL); + + error = gpio_pin_set_active(sc->sc_pin, val); + if (error == 0) + sc->sc_on = val; + return (error); +} + +static device_method_t edled_methods[] = { + DEVMETHOD(device_probe, edled_probe), + DEVMETHOD(device_attach, edled_attach), + DEVMETHOD(device_detach, edled_detach), + DEVMETHOD_END +}; + +static driver_t edled_driver = { + "edled", + edled_methods, + sizeof(struct edled_softc) +}; + +DRIVER_MODULE(edled, simplebus, edled_driver, 0, 0); +DRIVER_MODULE(edled, ofwbus, edled_driver, 0, 0); +MODULE_DEPEND(edled, gpiobus, 1, 1, 1); +MODULE_VERSION(edled, 1); diff --git a/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.dts b/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.dts new file mode 100644 index 0000000..88c2d0b --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab04-edled/edled.dts @@ -0,0 +1,33 @@ +/* + * edled.dts - Overlay for the edled driver on Raspberry Pi 4 + * + * Companion overlay for Chapter 32, Section 7 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * Adds an edled@0 node under /soc that references GPIO 18 as its + * LED output. Wire an LED with a current-limiting resistor between + * GPIO 18 (pin 12 on the header) and ground. + * + * The third cell of leds-gpios is the flag word: + * 0 = active high (pin drives 3.3V when active) + * 1 = active low (pin drives 0V when active) + */ + +/dts-v1/; +/plugin/; + +/ { + compatible = "brcm,bcm2711"; + + fragment@0 { + target-path = "/soc"; + __overlay__ { + edled0: edled@0 { + compatible = "example,edled"; + status = "okay"; + leds-gpios = <&gpio 18 0>; + label = "lab-indicator"; + }; + }; + }; +}; diff --git a/examples/part-07/ch32-fdt-embedded/lab05-edledi/Makefile b/examples/part-07/ch32-fdt-embedded/lab05-edledi/Makefile new file mode 100644 index 0000000..3885408 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab05-edledi/Makefile @@ -0,0 +1,6 @@ +KMOD= edledi +SRCS= edledi.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.c b/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.c new file mode 100644 index 0000000..2cd953d --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.c @@ -0,0 +1,195 @@ +/* + * edledi.c - edled with a GPIO interrupt input + * + * Companion source for Chapter 32, Lab 5 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * Extends the Lab 4 edled driver with a second GPIO that is + * configured as an input with a pull-up and as an interrupt source. + * Pressing a button wired to that pin toggles the LED. + * + * DT binding: + * compatible = "example,edledi"; + * leds-gpios = <&gpio LED_PIN 0>; + * button-gpios = <&gpio BTN_PIN 1>; + * interrupt-parent = <&gpio>; + * interrupts = ; // either edge + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include + +struct edledi_softc { + device_t sc_dev; + gpio_pin_t sc_led; + gpio_pin_t sc_button; + struct resource *sc_irq; + void *sc_irq_cookie; + int sc_irq_rid; + struct mtx sc_mtx; + int sc_on; +}; + +static const struct ofw_compat_data compat_data[] = { + {"example,edledi", 1}, + {NULL, 0} +}; + +static void +edledi_intr(void *arg) +{ + struct edledi_softc *sc = arg; + + mtx_lock(&sc->sc_mtx); + sc->sc_on = !sc->sc_on; + (void)gpio_pin_set_active(sc->sc_led, sc->sc_on); + mtx_unlock(&sc->sc_mtx); +} + +static int +edledi_probe(device_t dev) +{ + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) + return (ENXIO); + device_set_desc(dev, "Example embedded LED with button"); + return (BUS_PROBE_DEFAULT); +} + +static int +edledi_attach(device_t dev) +{ + struct edledi_softc *sc = device_get_softc(dev); + phandle_t node = ofw_bus_get_node(dev); + int error; + + sc->sc_dev = dev; + mtx_init(&sc->sc_mtx, device_get_nameunit(dev), "edledi", MTX_DEF); + + error = gpio_pin_get_by_ofw_property(dev, node, + "leds-gpios", &sc->sc_led); + if (error != 0) { + device_printf(dev, "cannot get LED pin: %d\n", error); + goto fail; + } + + error = gpio_pin_setflags(sc->sc_led, GPIO_PIN_OUTPUT); + if (error != 0) { + device_printf(dev, "cannot set LED flags: %d\n", error); + goto fail; + } + (void)gpio_pin_set_active(sc->sc_led, 0); + + error = gpio_pin_get_by_ofw_property(dev, node, + "button-gpios", &sc->sc_button); + if (error != 0) { + device_printf(dev, "cannot get button pin: %d\n", error); + goto fail; + } + + error = gpio_pin_setflags(sc->sc_button, + GPIO_PIN_INPUT | GPIO_PIN_PULLUP); + if (error != 0) { + device_printf(dev, "cannot configure button: %d\n", error); + goto fail; + } + + sc->sc_irq_rid = 0; + sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, + &sc->sc_irq_rid, RF_ACTIVE); + if (sc->sc_irq == NULL) { + device_printf(dev, "cannot allocate IRQ\n"); + error = ENXIO; + goto fail; + } + + error = bus_setup_intr(dev, sc->sc_irq, + INTR_TYPE_MISC | INTR_MPSAFE, + NULL, edledi_intr, sc, &sc->sc_irq_cookie); + if (error != 0) { + device_printf(dev, "cannot setup interrupt: %d\n", error); + goto fail; + } + + device_printf(dev, "attached, press button to toggle LED\n"); + return (0); + +fail: + if (sc->sc_irq != NULL) { + bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irq_rid, + sc->sc_irq); + sc->sc_irq = NULL; + } + if (sc->sc_button != NULL) { + gpio_pin_release(sc->sc_button); + sc->sc_button = NULL; + } + if (sc->sc_led != NULL) { + gpio_pin_release(sc->sc_led); + sc->sc_led = NULL; + } + mtx_destroy(&sc->sc_mtx); + return (error); +} + +static int +edledi_detach(device_t dev) +{ + struct edledi_softc *sc = device_get_softc(dev); + + if (sc->sc_irq_cookie != NULL) { + bus_teardown_intr(dev, sc->sc_irq, sc->sc_irq_cookie); + sc->sc_irq_cookie = NULL; + } + if (sc->sc_irq != NULL) { + bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irq_rid, + sc->sc_irq); + sc->sc_irq = NULL; + } + if (sc->sc_button != NULL) { + gpio_pin_release(sc->sc_button); + sc->sc_button = NULL; + } + if (sc->sc_led != NULL) { + (void)gpio_pin_set_active(sc->sc_led, 0); + gpio_pin_release(sc->sc_led); + sc->sc_led = NULL; + } + mtx_destroy(&sc->sc_mtx); + device_printf(dev, "detached\n"); + return (0); +} + +static device_method_t edledi_methods[] = { + DEVMETHOD(device_probe, edledi_probe), + DEVMETHOD(device_attach, edledi_attach), + DEVMETHOD(device_detach, edledi_detach), + DEVMETHOD_END +}; + +static driver_t edledi_driver = { + "edledi", + edledi_methods, + sizeof(struct edledi_softc) +}; + +DRIVER_MODULE(edledi, simplebus, edledi_driver, 0, 0); +DRIVER_MODULE(edledi, ofwbus, edledi_driver, 0, 0); +MODULE_DEPEND(edledi, gpiobus, 1, 1, 1); +MODULE_VERSION(edledi, 1); diff --git a/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.dts b/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.dts new file mode 100644 index 0000000..855d480 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/lab05-edledi/edledi.dts @@ -0,0 +1,36 @@ +/* + * edledi.dts - Overlay for the edledi driver on Raspberry Pi 4 + * + * Companion overlay for Chapter 32, Lab 5 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + * + * Adds an edledi@0 node that uses: + * - GPIO 18 as the LED output (header pin 12) + * - GPIO 23 as the button input (header pin 16), with a pull-up + * and an interrupt on either edge. + * + * Wire the button between GPIO 23 and ground. The internal pull-up + * keeps the line high when the button is released; pressing shorts + * it to ground and triggers the interrupt. + */ + +/dts-v1/; +/plugin/; + +/ { + compatible = "brcm,bcm2711"; + + fragment@0 { + target-path = "/soc"; + __overlay__ { + edledi0: edledi@0 { + compatible = "example,edledi"; + status = "okay"; + leds-gpios = <&gpio 18 0>; + button-gpios = <&gpio 23 1>; + interrupt-parent = <&gpio>; + interrupts = <23 3>; + }; + }; + }; +}; diff --git a/examples/part-07/ch32-fdt-embedded/shared/build-notes.md b/examples/part-07/ch32-fdt-embedded/shared/build-notes.md new file mode 100644 index 0000000..d15cff7 --- /dev/null +++ b/examples/part-07/ch32-fdt-embedded/shared/build-notes.md @@ -0,0 +1,98 @@ +# Shared Build and Development Notes + +## Prerequisites + +- FreeBSD 14.3 or later. +- Kernel sources under `/usr/src`. +- `devel/dtc` (install with `pkg install dtc`). +- For cross-building from amd64 to arm64, a full FreeBSD build tree. + +## Standard Makefile pattern + +Every kernel module in this chapter uses the same Makefile shape: + +```make +KMOD= +SRCS= .c + +SYSDIR?= /usr/src/sys + +.include +``` + +`bsd.kmod.mk` handles compilation, linking, symbol tables, and debug +output. Typing `make` produces `.ko` and +`.ko.debug`. + +## Compiling DT overlays + +Overlay sources have the extension `.dts` (some projects use +`.dtso`; the content is the same). Compile with: + +```sh +dtc -I dts -O dtb -@ -o out.dtbo input.dts +``` + +- `-I dts` declares the input is text. +- `-O dtb` requests binary output. +- `-@` includes symbol information for label resolution. + +Install the output under `/boot/dtb/overlays/` and list the +basename (without `.dtbo`) in `fdt_overlays` in `/boot/loader.conf`. + +## Loading modules manually + +```sh +sudo kldload ./module.ko +kldstat -m module +sudo kldunload module +``` + +Use `./` before the filename to load from the current directory +rather than the default kernel module path. + +## Boot-time loading + +In `/boot/loader.conf`: + +``` +module_load="YES" +fdt_overlays="overlay1,overlay2" +``` + +Ensure the module `.ko` lives in `/boot/modules/` and the overlays +live in `/boot/dtb/overlays/`. + +## Common debugging commands + +```sh +# Show the current DT as the kernel sees it +ofwdump -a | less + +# Show one node +ofwdump -p /soc/your-node + +# Show one property +ofwdump -P compatible /soc/your-node + +# Show attached devices +devinfo -r + +# Show sysctls for a driver +sysctl dev.your-driver + +# Show interrupt counts +vmstat -i +``` + +## Tearing down state between iterations + +When iterating on a driver, unload before reloading: + +```sh +sudo kldunload your-driver +sudo kldload ./your-driver.ko +``` + +If `kldunload` returns `EBUSY`, detach did not release all resources. +Check the source and try again. diff --git a/examples/part-07/ch33-performance/lab01-perfcounters/Makefile b/examples/part-07/ch33-performance/lab01-perfcounters/Makefile new file mode 100644 index 0000000..72cc5d4 --- /dev/null +++ b/examples/part-07/ch33-performance/lab01-perfcounters/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo +SRCS= perfdemo.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab01-perfcounters/perfdemo.c b/examples/part-07/ch33-performance/lab01-perfcounters/perfdemo.c new file mode 100644 index 0000000..fe86b6f --- /dev/null +++ b/examples/part-07/ch33-performance/lab01-perfcounters/perfdemo.c @@ -0,0 +1,136 @@ +/* + * perfdemo - pseudo-device used to illustrate performance measurement + * and tuning techniques in FreeBSD device drivers. + * + * Lab 1: baseline. Implements a trivial read that returns zero bytes and + * counts reads and bytes with counter(9). Exposes totals via sysctl. + * + * This is a companion example for Chapter 33 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static d_read_t perfdemo_read; +static d_open_t perfdemo_open; +static d_close_t perfdemo_close; + +static struct cdevsw perfdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "perfdemo", + .d_open = perfdemo_open, + .d_close = perfdemo_close, + .d_read = perfdemo_read, +}; + +static struct cdev *perfdemo_dev; + +static counter_u64_t perfdemo_reads; +static counter_u64_t perfdemo_bytes; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo driver"); + +static int +perfdemo_sysctl_reads(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_reads); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +static int +perfdemo_sysctl_bytes(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_bytes); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo, OID_AUTO, reads, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_sysctl_reads, "QU", + "Total number of reads served since load"); + +SYSCTL_PROC(_hw_perfdemo, OID_AUTO, bytes, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_sysctl_bytes, "QU", + "Total bytes returned to readers since load"); + +static int +perfdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +perfdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +perfdemo_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + size_t amt; + static const char zero_buf[4096] = { 0 }; + int error; + + amt = MIN(uio->uio_resid, sizeof(zero_buf)); + if (amt == 0) + return (0); + + error = uiomove(__DECONST(void *, zero_buf), amt, uio); + if (error == 0) { + counter_u64_add(perfdemo_reads, 1); + counter_u64_add(perfdemo_bytes, amt); + } + return (error); +} + +static int +perfdemo_modevent(module_t mod, int what, void *arg) +{ + int error = 0; + + switch (what) { + case MOD_LOAD: + perfdemo_reads = counter_u64_alloc(M_WAITOK); + perfdemo_bytes = counter_u64_alloc(M_WAITOK); + perfdemo_dev = make_dev(&perfdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "perfdemo"); + if (perfdemo_dev == NULL) { + counter_u64_free(perfdemo_reads); + counter_u64_free(perfdemo_bytes); + error = ENOMEM; + } else { + printf("perfdemo: loaded, device node created\n"); + } + break; + case MOD_UNLOAD: + if (perfdemo_dev != NULL) + destroy_dev(perfdemo_dev); + counter_u64_free(perfdemo_reads); + counter_u64_free(perfdemo_bytes); + printf("perfdemo: unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t perfdemo_mod = { + "perfdemo", + perfdemo_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo, perfdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo, 1); diff --git a/examples/part-07/ch33-performance/lab01-perfcounters/run-workload.sh b/examples/part-07/ch33-performance/lab01-perfcounters/run-workload.sh new file mode 100755 index 0000000..93c7d5b --- /dev/null +++ b/examples/part-07/ch33-performance/lab01-perfcounters/run-workload.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# +# run-workload.sh - run a simple read workload against /dev/perfdemo. +# +# Usage: ./run-workload.sh [count] +# +# Default count is 10000 blocks of 4096 bytes (40 MB total). + +COUNT=${1:-10000} +DEV=${DEV:-/dev/perfdemo} +BS=${BS:-4096} + +if [ ! -c "$DEV" ]; then + echo "Error: $DEV does not exist. Load the driver first:" + echo " sudo kldload ./perfdemo.ko" + exit 1 +fi + +echo "Reading $COUNT blocks of $BS bytes from $DEV..." +time dd if=$DEV of=/dev/null bs=$BS count=$COUNT 2>&1 + +echo +echo "Counter values after workload:" +sysctl hw.perfdemo diff --git a/examples/part-07/ch33-performance/lab02-dtrace-scripts/lockstat-simple.d b/examples/part-07/ch33-performance/lab02-dtrace-scripts/lockstat-simple.d new file mode 100644 index 0000000..371b565 --- /dev/null +++ b/examples/part-07/ch33-performance/lab02-dtrace-scripts/lockstat-simple.d @@ -0,0 +1,40 @@ +#!/usr/sbin/dtrace -s +/* + * lockstat-simple.d - count lock acquisitions in and around perfdemo_read. + * + * Usage: sudo dtrace -s lockstat-simple.d + * + * Prints, per lock, the number of times the lock was held while + * perfdemo_read was on-CPU. A lock that appears here many times is + * touched by the read path. + * + * Note: on a perfdemo built without its own mutex, the output will + * show only the locks touched by common kernel code (sleepq locks, + * sched_lock, etc.). A driver with its own mutex under load will + * show that mutex prominently. + */ + +#pragma D option quiet + +fbt:perfdemo:perfdemo_read:entry +{ + self->in_read = 1; +} + +fbt:perfdemo:perfdemo_read:return +{ + self->in_read = 0; +} + +lockstat:::adaptive-acquire +/self->in_read/ +{ + @[probefunc, stringof(args[0]->lock_object.lo_name)] = + count(); +} + +END +{ + printf("%-30s %-30s %s\n", "caller", "lock", "count"); + printa("%-30s %-30s %@d\n", @); +} diff --git a/examples/part-07/ch33-performance/lab02-dtrace-scripts/profile-sample.d b/examples/part-07/ch33-performance/lab02-dtrace-scripts/profile-sample.d new file mode 100644 index 0000000..9478010 --- /dev/null +++ b/examples/part-07/ch33-performance/lab02-dtrace-scripts/profile-sample.d @@ -0,0 +1,27 @@ +#!/usr/sbin/dtrace -s +/* + * profile-sample.d - kernel-wide profile sample at 997 Hz. + * + * Usage: sudo dtrace -s profile-sample.d + * + * Run a workload in another terminal. Let this script run for + * 30 to 60 seconds, then Ctrl-C. The output is a list of stack + * traces ordered by sample count. + * + * 997 Hz is deliberately not 1000 Hz. Using a prime number avoids + * interference with any 1 Hz, 10 Hz, 100 Hz, or 1000 Hz periodic + * activity that might create systematic bias. + */ + +#pragma D option quiet + +profile-997 +{ + @[stack()] = count(); +} + +END +{ + trunc(@, 20); + printa(@); +} diff --git a/examples/part-07/ch33-performance/lab02-dtrace-scripts/read-latency.d b/examples/part-07/ch33-performance/lab02-dtrace-scripts/read-latency.d new file mode 100644 index 0000000..fe95e82 --- /dev/null +++ b/examples/part-07/ch33-performance/lab02-dtrace-scripts/read-latency.d @@ -0,0 +1,30 @@ +#!/usr/sbin/dtrace -s +/* + * read-latency.d - histogram the latency of perfdemo_read in nanoseconds. + * + * Usage: sudo dtrace -s read-latency.d + * + * Run a workload against /dev/perfdemo in another terminal. Let this + * script run for 30 seconds, then Ctrl-C. The output is a quantize() + * histogram of latencies in ns, bucketed by power of two. + */ + +#pragma D option quiet +#pragma D option dynvarsize=16m + +fbt:perfdemo:perfdemo_read:entry +{ + self->ts = timestamp; +} + +fbt:perfdemo:perfdemo_read:return +/self->ts/ +{ + @ = quantize(timestamp - self->ts); + self->ts = 0; +} + +END +{ + printa(@); +} diff --git a/examples/part-07/ch33-performance/lab03-pmcstat/callgraph.sh b/examples/part-07/ch33-performance/lab03-pmcstat/callgraph.sh new file mode 100755 index 0000000..6f30d94 --- /dev/null +++ b/examples/part-07/ch33-performance/lab03-pmcstat/callgraph.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# +# callgraph.sh - collect callgraph samples while a workload runs. +# +# Usage: ./callgraph.sh [duration_seconds] +# +# Produces pmc.cg, which can be converted to a flame graph with: +# pmcstat -R pmc.cg -G - | stackcollapse-pmc.pl | flamegraph.pl > out.svg +# (stackcollapse-pmc.pl and flamegraph.pl are from Brendan Gregg's +# FlameGraph repository.) + +DURATION=${1:-30} + +if ! kldstat | grep -q hwpmc; then + echo "Loading hwpmc..." + sudo kldload hwpmc +fi + +echo "Collecting callgraph samples for $DURATION seconds..." +sudo pmcstat -S cycles -O pmc.cg -n 1 sleep $DURATION + +echo +echo "Samples written to pmc.cg. Top functions by call count:" +sudo pmcstat -R pmc.cg -G - | head -30 diff --git a/examples/part-07/ch33-performance/lab03-pmcstat/count-events.sh b/examples/part-07/ch33-performance/lab03-pmcstat/count-events.sh new file mode 100755 index 0000000..f07517d --- /dev/null +++ b/examples/part-07/ch33-performance/lab03-pmcstat/count-events.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# +# count-events.sh - count instructions retired and LLC misses during +# a fixed-duration workload window. +# +# Usage: ./count-events.sh [duration_seconds] + +DURATION=${1:-10} + +if ! kldstat | grep -q hwpmc; then + echo "Loading hwpmc..." + sudo kldload hwpmc +fi + +echo "Counting cycles and instructions for $DURATION seconds..." +echo "Run a workload in another terminal now." +echo + +sudo pmcstat -c 0 -w $DURATION -s instructions -s cycles + +echo +echo "LLC_MISSES count for $DURATION seconds..." +sudo pmcstat -c 0 -w $DURATION -s LLC_MISSES diff --git a/examples/part-07/ch33-performance/lab03-pmcstat/sample-cycles.sh b/examples/part-07/ch33-performance/lab03-pmcstat/sample-cycles.sh new file mode 100755 index 0000000..6e6c7a7 --- /dev/null +++ b/examples/part-07/ch33-performance/lab03-pmcstat/sample-cycles.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# +# sample-cycles.sh - sample system-wide CPU cycles while a workload runs. +# +# Usage: ./sample-cycles.sh [duration_seconds] + +DURATION=${1:-30} + +if ! kldstat | grep -q hwpmc; then + echo "Loading hwpmc..." + sudo kldload hwpmc +fi + +echo "Sampling CPU cycles for $DURATION seconds..." +echo "Run a workload (for example, dd if=/dev/perfdemo of=/dev/null \\" +echo " bs=4096 count=100000) in another terminal now." +echo + +sudo pmcstat -S cycles -O pmc.out sleep $DURATION +echo +echo "Samples written to pmc.out. Producing top-N report..." +sudo pmcstat -R pmc.out -T | head -30 diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/compare-variants.sh b/examples/part-07/ch33-performance/lab04-cache-aligned/compare-variants.sh new file mode 100755 index 0000000..d5f24e3 --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/compare-variants.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# +# compare-variants.sh - compare throughput of the three variants. +# +# Loads each variant in turn, runs a concurrent read workload, and +# reports the throughput. To see the cache-line contention effect, +# run on a multi-core machine with NCPU >= 4. +# +# Usage: ./compare-variants.sh + +NCPU=${NCPU:-4} +COUNT=${COUNT:-25000} + +load_and_test() +{ + local variant=$1 + local dev=$2 + + (cd $variant && make) || return 1 + sudo kldload ./$variant/${variant%.ko}.ko || return 1 + + echo "=== Testing $variant with $NCPU concurrent readers ===" + start=$(date +%s.%N) + for i in $(seq 1 $NCPU); do + dd if=$dev of=/dev/null bs=4096 count=$COUNT \ + 2>/dev/null & + done + wait + end=$(date +%s.%N) + elapsed=$(echo "$end - $start" | bc) + total_reads=$(echo "$NCPU * $COUNT" | bc) + rate=$(echo "scale=0; $total_reads / $elapsed" | bc) + echo " Elapsed: ${elapsed}s" + echo " Total reads: $total_reads" + echo " Throughput: ${rate} reads/sec" + echo + + sudo kldunload ${variant%.ko} +} + +load_and_test v1-atomic /dev/perfdemo_v1 +load_and_test v2-aligned /dev/perfdemo_v2 +load_and_test v3-counter9 /dev/perfdemo_v3 + +echo "Summary:" +echo " v1 shows contention because a shared atomic is hammered" +echo " by NCPU cores." +echo " v2 uses a manually-aligned per-CPU array to eliminate the" +echo " contention. It should be significantly faster." +echo " v3 uses counter(9), which is the recommended approach. Its" +echo " throughput should match v2 closely." diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/Makefile b/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/Makefile new file mode 100644 index 0000000..067f499 --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo_v1 +SRCS= perfdemo_v1.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/perfdemo_v1.c b/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/perfdemo_v1.c new file mode 100644 index 0000000..7bae48c --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v1-atomic/perfdemo_v1.c @@ -0,0 +1,84 @@ +/* + * perfdemo_v1 - variant using a shared atomic counter. + * + * This is the intentionally-bad baseline for Lab 4. A single + * atomic_add_64 is updated on every read from every CPU, producing + * cache-line ping-pong under concurrent load. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static d_read_t perfdemo_v1_read; + +static struct cdevsw perfdemo_v1_cdevsw = { + .d_version = D_VERSION, + .d_name = "perfdemo_v1", + .d_read = perfdemo_v1_read, +}; + +static struct cdev *perfdemo_v1_dev; + +static volatile uint64_t perfdemo_v1_reads; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo_v1, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo_v1 driver"); + +SYSCTL_U64(_hw_perfdemo_v1, OID_AUTO, reads, + CTLFLAG_RD, __DEVOLATILE(uint64_t *, &perfdemo_v1_reads), 0, + "Total number of reads (shared atomic)"); + +static int +perfdemo_v1_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + static const char zero_buf[4096] = { 0 }; + size_t amt; + int error; + + amt = MIN(uio->uio_resid, sizeof(zero_buf)); + if (amt == 0) + return (0); + + error = uiomove(__DECONST(void *, zero_buf), amt, uio); + if (error == 0) + atomic_add_64(&perfdemo_v1_reads, 1); + return (error); +} + +static int +perfdemo_v1_modevent(module_t mod, int what, void *arg) +{ + switch (what) { + case MOD_LOAD: + perfdemo_v1_dev = make_dev(&perfdemo_v1_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "perfdemo_v1"); + if (perfdemo_v1_dev == NULL) + return (ENOMEM); + printf("perfdemo_v1: loaded (shared atomic variant)\n"); + return (0); + case MOD_UNLOAD: + if (perfdemo_v1_dev != NULL) + destroy_dev(perfdemo_v1_dev); + printf("perfdemo_v1: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_v1_mod = { + "perfdemo_v1", + perfdemo_v1_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo_v1, perfdemo_v1_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo_v1, 1); diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/Makefile b/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/Makefile new file mode 100644 index 0000000..de75d81 --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo_v2 +SRCS= perfdemo_v2.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/perfdemo_v2.c b/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/perfdemo_v2.c new file mode 100644 index 0000000..19e23e6 --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v2-aligned/perfdemo_v2.c @@ -0,0 +1,109 @@ +/* + * perfdemo_v2 - variant using a manually-aligned per-CPU array. + * + * This variant uses an explicit per-CPU counter array with each + * element aligned to a cache line to prevent false sharing between + * counters on adjacent CPUs. + * + * The summing happens only on read (not on every update), so the + * hot path has no cross-CPU coordination. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static d_read_t perfdemo_v2_read; + +static struct cdevsw perfdemo_v2_cdevsw = { + .d_version = D_VERSION, + .d_name = "perfdemo_v2", + .d_read = perfdemo_v2_read, +}; + +static struct cdev *perfdemo_v2_dev; + +struct perfdemo_v2_pc { + uint64_t reads; +} __aligned(CACHE_LINE_SIZE); + +static struct perfdemo_v2_pc perfdemo_v2_pc[MAXCPU]; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo_v2, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo_v2 driver"); + +static int +perfdemo_v2_sysctl_reads(SYSCTL_HANDLER_ARGS) +{ + uint64_t sum = 0; + int i; + + CPU_FOREACH(i) { + sum += perfdemo_v2_pc[i].reads; + } + return (sysctl_handle_64(oidp, &sum, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo_v2, OID_AUTO, reads, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_v2_sysctl_reads, "QU", + "Total number of reads (manually-aligned per-CPU)"); + +static int +perfdemo_v2_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + static const char zero_buf[4096] = { 0 }; + size_t amt; + int error, cpu; + + amt = MIN(uio->uio_resid, sizeof(zero_buf)); + if (amt == 0) + return (0); + + error = uiomove(__DECONST(void *, zero_buf), amt, uio); + if (error == 0) { + cpu = PCPU_GET(cpuid); + perfdemo_v2_pc[cpu].reads++; + } + return (error); +} + +static int +perfdemo_v2_modevent(module_t mod, int what, void *arg) +{ + switch (what) { + case MOD_LOAD: + memset(perfdemo_v2_pc, 0, sizeof(perfdemo_v2_pc)); + perfdemo_v2_dev = make_dev(&perfdemo_v2_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "perfdemo_v2"); + if (perfdemo_v2_dev == NULL) + return (ENOMEM); + printf("perfdemo_v2: loaded (aligned per-CPU variant)\n"); + return (0); + case MOD_UNLOAD: + if (perfdemo_v2_dev != NULL) + destroy_dev(perfdemo_v2_dev); + printf("perfdemo_v2: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_v2_mod = { + "perfdemo_v2", + perfdemo_v2_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo_v2, perfdemo_v2_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo_v2, 1); diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/Makefile b/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/Makefile new file mode 100644 index 0000000..d094ae4 --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo_v3 +SRCS= perfdemo_v3.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/perfdemo_v3.c b/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/perfdemo_v3.c new file mode 100644 index 0000000..1bd7daf --- /dev/null +++ b/examples/part-07/ch33-performance/lab04-cache-aligned/v3-counter9/perfdemo_v3.c @@ -0,0 +1,97 @@ +/* + * perfdemo_v3 - variant using the counter(9) API. + * + * This is the recommended shape. counter(9) handles per-CPU storage, + * alignment, and the read-time sum; the driver simply calls + * counter_u64_add() on the hot path. The API is also type-safe and + * well-tested. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static d_read_t perfdemo_v3_read; + +static struct cdevsw perfdemo_v3_cdevsw = { + .d_version = D_VERSION, + .d_name = "perfdemo_v3", + .d_read = perfdemo_v3_read, +}; + +static struct cdev *perfdemo_v3_dev; + +static counter_u64_t perfdemo_v3_reads; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo_v3, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo_v3 driver"); + +static int +perfdemo_v3_sysctl_reads(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_v3_reads); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo_v3, OID_AUTO, reads, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_v3_sysctl_reads, "QU", + "Total number of reads (counter(9))"); + +static int +perfdemo_v3_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + static const char zero_buf[4096] = { 0 }; + size_t amt; + int error; + + amt = MIN(uio->uio_resid, sizeof(zero_buf)); + if (amt == 0) + return (0); + + error = uiomove(__DECONST(void *, zero_buf), amt, uio); + if (error == 0) + counter_u64_add(perfdemo_v3_reads, 1); + return (error); +} + +static int +perfdemo_v3_modevent(module_t mod, int what, void *arg) +{ + switch (what) { + case MOD_LOAD: + perfdemo_v3_reads = counter_u64_alloc(M_WAITOK); + perfdemo_v3_dev = make_dev(&perfdemo_v3_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "perfdemo_v3"); + if (perfdemo_v3_dev == NULL) { + counter_u64_free(perfdemo_v3_reads); + return (ENOMEM); + } + printf("perfdemo_v3: loaded (counter(9) variant)\n"); + return (0); + case MOD_UNLOAD: + if (perfdemo_v3_dev != NULL) + destroy_dev(perfdemo_v3_dev); + counter_u64_free(perfdemo_v3_reads); + printf("perfdemo_v3: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_v3_mod = { + "perfdemo_v3", + perfdemo_v3_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo_v3, perfdemo_v3_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo_v3, 1); diff --git a/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/Makefile b/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/Makefile new file mode 100644 index 0000000..95dfe09 --- /dev/null +++ b/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo_tq1 +SRCS= perfdemo_tq1.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/perfdemo_tq1.c b/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/perfdemo_tq1.c new file mode 100644 index 0000000..729d7d7 --- /dev/null +++ b/examples/part-07/ch33-performance/lab05-interrupt-tq/v1-in-callout/perfdemo_tq1.c @@ -0,0 +1,96 @@ +/* + * perfdemo_tq1 - variant that does heavy work inside a callout. + * + * The callout fires at 1 ms intervals and, for demonstration, + * spends some cycles "processing" before returning. The problem: + * the callout runs at a high scheduling priority and can delay + * other callouts if its work expands. + * + * This is the anti-pattern variant for Lab 5. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include + +static struct callout perfdemo_tq1_co; +static counter_u64_t perfdemo_tq1_ticks; +static counter_u64_t perfdemo_tq1_cycles; +static volatile uint64_t perfdemo_tq1_running; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo_tq1, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo_tq1 driver"); + +static int +perfdemo_tq1_sysctl_ticks(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_tq1_ticks); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo_tq1, OID_AUTO, ticks, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_tq1_sysctl_ticks, "QU", + "Callout ticks fired since load"); + +static void +perfdemo_tq1_fake_work(void) +{ + volatile uint64_t x; + int i; + + /* Pretend to do work. */ + for (i = 0; i < 20000; i++) + x += i; + counter_u64_add(perfdemo_tq1_cycles, i); +} + +static void +perfdemo_tq1_callout(void *arg) +{ + counter_u64_add(perfdemo_tq1_ticks, 1); + perfdemo_tq1_fake_work(); + if (perfdemo_tq1_running) + callout_schedule(&perfdemo_tq1_co, 1); +} + +static int +perfdemo_tq1_modevent(module_t mod, int what, void *arg) +{ + switch (what) { + case MOD_LOAD: + perfdemo_tq1_ticks = counter_u64_alloc(M_WAITOK); + perfdemo_tq1_cycles = counter_u64_alloc(M_WAITOK); + callout_init(&perfdemo_tq1_co, 1); + perfdemo_tq1_running = 1; + callout_reset(&perfdemo_tq1_co, 1, + perfdemo_tq1_callout, NULL); + printf("perfdemo_tq1: loaded (work-in-callout variant)\n"); + return (0); + case MOD_UNLOAD: + perfdemo_tq1_running = 0; + callout_drain(&perfdemo_tq1_co); + counter_u64_free(perfdemo_tq1_ticks); + counter_u64_free(perfdemo_tq1_cycles); + printf("perfdemo_tq1: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_tq1_mod = { + "perfdemo_tq1", + perfdemo_tq1_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo_tq1, perfdemo_tq1_mod, SI_SUB_DRIVERS, + SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo_tq1, 1); diff --git a/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/Makefile b/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/Makefile new file mode 100644 index 0000000..bab68fd --- /dev/null +++ b/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo_tq2 +SRCS= perfdemo_tq2.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/perfdemo_tq2.c b/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/perfdemo_tq2.c new file mode 100644 index 0000000..ea7b93b --- /dev/null +++ b/examples/part-07/ch33-performance/lab05-interrupt-tq/v2-taskqueue/perfdemo_tq2.c @@ -0,0 +1,123 @@ +/* + * perfdemo_tq2 - variant that defers heavy work to a taskqueue. + * + * The callout fires at 1 ms intervals and enqueues a task on a + * dedicated taskqueue. The task performs the work in a kernel + * thread context, which does not block the callout wheel. + * + * This is the recommended pattern for Lab 5: keep the callout or + * interrupt handler light, move heavy work to a taskqueue. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static struct callout perfdemo_tq2_co; +static struct taskqueue *perfdemo_tq2_tq; +static struct task perfdemo_tq2_task; +static counter_u64_t perfdemo_tq2_ticks; +static counter_u64_t perfdemo_tq2_runs; +static counter_u64_t perfdemo_tq2_cycles; +static volatile uint64_t perfdemo_tq2_running; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo_tq2, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo_tq2 driver"); + +static int +perfdemo_tq2_sysctl_ticks(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_tq2_ticks); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo_tq2, OID_AUTO, ticks, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_tq2_sysctl_ticks, "QU", + "Callout ticks fired since load"); + +static int +perfdemo_tq2_sysctl_runs(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_tq2_runs); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo_tq2, OID_AUTO, runs, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_tq2_sysctl_runs, "QU", + "Taskqueue runs since load"); + +static void +perfdemo_tq2_fake_work(void *arg, int pending) +{ + volatile uint64_t x; + int i; + + counter_u64_add(perfdemo_tq2_runs, 1); + for (i = 0; i < 20000; i++) + x += i; + counter_u64_add(perfdemo_tq2_cycles, i); +} + +static void +perfdemo_tq2_callout(void *arg) +{ + counter_u64_add(perfdemo_tq2_ticks, 1); + taskqueue_enqueue(perfdemo_tq2_tq, &perfdemo_tq2_task); + if (perfdemo_tq2_running) + callout_schedule(&perfdemo_tq2_co, 1); +} + +static int +perfdemo_tq2_modevent(module_t mod, int what, void *arg) +{ + switch (what) { + case MOD_LOAD: + perfdemo_tq2_ticks = counter_u64_alloc(M_WAITOK); + perfdemo_tq2_runs = counter_u64_alloc(M_WAITOK); + perfdemo_tq2_cycles = counter_u64_alloc(M_WAITOK); + perfdemo_tq2_tq = taskqueue_create("perfdemo_tq2", + M_WAITOK, taskqueue_thread_enqueue, + &perfdemo_tq2_tq); + taskqueue_start_threads(&perfdemo_tq2_tq, 1, + PI_SOFT, "perfdemo_tq2"); + TASK_INIT(&perfdemo_tq2_task, 0, + perfdemo_tq2_fake_work, NULL); + callout_init(&perfdemo_tq2_co, 1); + perfdemo_tq2_running = 1; + callout_reset(&perfdemo_tq2_co, 1, + perfdemo_tq2_callout, NULL); + printf("perfdemo_tq2: loaded (taskqueue variant)\n"); + return (0); + case MOD_UNLOAD: + perfdemo_tq2_running = 0; + callout_drain(&perfdemo_tq2_co); + taskqueue_drain(perfdemo_tq2_tq, &perfdemo_tq2_task); + taskqueue_free(perfdemo_tq2_tq); + counter_u64_free(perfdemo_tq2_ticks); + counter_u64_free(perfdemo_tq2_runs); + counter_u64_free(perfdemo_tq2_cycles); + printf("perfdemo_tq2: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_tq2_mod = { + "perfdemo_tq2", + perfdemo_tq2_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo_tq2, perfdemo_tq2_mod, SI_SUB_DRIVERS, + SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo_tq2, 1); diff --git a/examples/part-07/ch33-performance/lab06-v23-final/Makefile b/examples/part-07/ch33-performance/lab06-v23-final/Makefile new file mode 100644 index 0000000..72cc5d4 --- /dev/null +++ b/examples/part-07/ch33-performance/lab06-v23-final/Makefile @@ -0,0 +1,6 @@ +KMOD= perfdemo +SRCS= perfdemo.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch33-performance/lab06-v23-final/perfdemo.c b/examples/part-07/ch33-performance/lab06-v23-final/perfdemo.c new file mode 100644 index 0000000..6484767 --- /dev/null +++ b/examples/part-07/ch33-performance/lab06-v23-final/perfdemo.c @@ -0,0 +1,211 @@ +/* + * perfdemo v2.3 - the shipped, optimised pseudo-device. + * + * This is the lab-6 final that combines the best techniques from + * the earlier labs: + * - counter(9) for per-CPU counters (reads, bytes). + * - Latency histogram exposed via sysctl. + * - Minimum instrumentation on the hot path. + * - Versioned (MODULE_VERSION == 23). + * - Stable sysctl interface under hw.perfdemo. + * - Debug mode controllable at runtime. + * + * Companion example for Chapter 33. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PD_HIST_BUCKETS 8 + +static d_read_t perfdemo_read; +static d_open_t perfdemo_open; +static d_close_t perfdemo_close; + +static struct cdevsw perfdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "perfdemo", + .d_open = perfdemo_open, + .d_close = perfdemo_close, + .d_read = perfdemo_read, +}; + +static struct cdev *perfdemo_dev; + +/* Latency-bucket upper bounds, in nanoseconds. */ +static const uint64_t perfdemo_hist_bounds_ns[PD_HIST_BUCKETS] = { + 1000ULL, /* <= 1us */ + 10000ULL, /* <= 10us */ + 100000ULL, /* <= 100us */ + 1000000ULL, /* <= 1ms */ + 10000000ULL, /* <= 10ms */ + 100000000ULL, /* <= 100ms */ + 1000000000ULL, /* <= 1s */ + UINT64_MAX, /* > 1s */ +}; + +static counter_u64_t perfdemo_reads; +static counter_u64_t perfdemo_bytes; +static counter_u64_t perfdemo_hist[PD_HIST_BUCKETS]; + +static int perfdemo_debug = 0; + +static SYSCTL_NODE(_hw, OID_AUTO, perfdemo, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "perfdemo driver"); + +SYSCTL_INT(_hw_perfdemo, OID_AUTO, debug, + CTLFLAG_RWTUN, &perfdemo_debug, 0, + "Enable debug printf from read path (0 = off)"); + +static int +perfdemo_sysctl_reads(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_reads); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +static int +perfdemo_sysctl_bytes(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(perfdemo_bytes); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_perfdemo, OID_AUTO, reads, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_sysctl_reads, "QU", + "Total number of reads served"); + +SYSCTL_PROC(_hw_perfdemo, OID_AUTO, bytes, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_sysctl_bytes, "QU", + "Total bytes returned"); + +static int +perfdemo_sysctl_hist(SYSCTL_HANDLER_ARGS) +{ + uint64_t snap[PD_HIST_BUCKETS]; + int i; + + for (i = 0; i < PD_HIST_BUCKETS; i++) + snap[i] = counter_u64_fetch(perfdemo_hist[i]); + return (SYSCTL_OUT(req, snap, sizeof(snap))); +} + +SYSCTL_PROC(_hw_perfdemo, OID_AUTO, latency_histogram, + CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, perfdemo_sysctl_hist, "", + "Read latency histogram (8 x uint64 ns buckets)"); + +static int +perfdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +perfdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static inline int +perfdemo_bucket(uint64_t ns) +{ + int i; + + for (i = 0; i < PD_HIST_BUCKETS - 1; i++) { + if (ns <= perfdemo_hist_bounds_ns[i]) + return (i); + } + return (PD_HIST_BUCKETS - 1); +} + +static int +perfdemo_read(struct cdev *dev, struct uio *uio, int ioflag) +{ + static const char zero_buf[4096] = { 0 }; + size_t amt; + int error, bucket; + struct bintime start, end; + uint64_t elapsed_ns; + + amt = MIN(uio->uio_resid, sizeof(zero_buf)); + if (amt == 0) + return (0); + + binuptime(&start); + error = uiomove(__DECONST(void *, zero_buf), amt, uio); + binuptime(&end); + + if (error == 0) { + counter_u64_add(perfdemo_reads, 1); + counter_u64_add(perfdemo_bytes, amt); + + bintime_sub(&end, &start); + elapsed_ns = (uint64_t)end.sec * 1000000000ULL + + ((uint64_t)(end.frac >> 32) * 1000000000ULL) / + ((uint64_t)1 << 32); + bucket = perfdemo_bucket(elapsed_ns); + counter_u64_add(perfdemo_hist[bucket], 1); + + if (perfdemo_debug > 0) { + log(LOG_DEBUG, "perfdemo: read %zu bytes in %llu ns\n", + amt, (unsigned long long)elapsed_ns); + } + } + return (error); +} + +static int +perfdemo_modevent(module_t mod, int what, void *arg) +{ + int i; + + switch (what) { + case MOD_LOAD: + perfdemo_reads = counter_u64_alloc(M_WAITOK); + perfdemo_bytes = counter_u64_alloc(M_WAITOK); + for (i = 0; i < PD_HIST_BUCKETS; i++) + perfdemo_hist[i] = counter_u64_alloc(M_WAITOK); + perfdemo_dev = make_dev(&perfdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "perfdemo"); + if (perfdemo_dev == NULL) { + counter_u64_free(perfdemo_reads); + counter_u64_free(perfdemo_bytes); + for (i = 0; i < PD_HIST_BUCKETS; i++) + counter_u64_free(perfdemo_hist[i]); + return (ENOMEM); + } + printf("perfdemo v2.3: loaded\n"); + return (0); + case MOD_UNLOAD: + if (perfdemo_dev != NULL) + destroy_dev(perfdemo_dev); + counter_u64_free(perfdemo_reads); + counter_u64_free(perfdemo_bytes); + for (i = 0; i < PD_HIST_BUCKETS; i++) + counter_u64_free(perfdemo_hist[i]); + printf("perfdemo v2.3: unloaded\n"); + return (0); + default: + return (EOPNOTSUPP); + } +} + +static moduledata_t perfdemo_mod = { + "perfdemo", + perfdemo_modevent, + NULL +}; + +DECLARE_MODULE(perfdemo, perfdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(perfdemo, 23); diff --git a/examples/part-07/ch33-performance/lab06-v23-final/read-histogram.sh b/examples/part-07/ch33-performance/lab06-v23-final/read-histogram.sh new file mode 100755 index 0000000..4fc830c --- /dev/null +++ b/examples/part-07/ch33-performance/lab06-v23-final/read-histogram.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# +# read-histogram.sh - poll the v2.3 latency histogram every second +# and print a simple textual display. +# +# Usage: ./read-histogram.sh [iterations] + +ITER=${1:-10} +BOUNDS="<=1us <=10us <=100us <=1ms <=10ms <=100ms <=1s >1s" + +if [ ! -c /dev/perfdemo ]; then + echo "perfdemo is not loaded." + exit 1 +fi + +for i in $(seq 1 $ITER); do + echo "=== $(date) ===" + # sysctl -x prints raw hex; we need to turn it into 8 uint64. + sysctl -b hw.perfdemo.latency_histogram | \ + od -An -tu8 -v -w64 | \ + tr -s ' ' '\n' | grep -v '^$' | head -8 > /tmp/perfdemo_hist + + total=0 + while read n; do + total=$((total + n)) + done < /tmp/perfdemo_hist + + echo "Total samples: $total" + idx=1 + for b in $BOUNDS; do + n=$(sed -n "${idx}p" /tmp/perfdemo_hist) + if [ "$total" -gt 0 ]; then + pct=$(echo "scale=1; $n * 100 / $total" | bc) + else + pct=0 + fi + printf " %-10s %8d (%.1f%%)\n" "$b" "$n" "$pct" + idx=$((idx + 1)) + done + sleep 1 +done + +rm -f /tmp/perfdemo_hist diff --git a/examples/part-07/ch33-performance/shared/build-notes.md b/examples/part-07/ch33-performance/shared/build-notes.md new file mode 100644 index 0000000..b842a8f --- /dev/null +++ b/examples/part-07/ch33-performance/shared/build-notes.md @@ -0,0 +1,83 @@ +# Shared Build Notes + +These notes apply to every lab in this chapter. + +## Prerequisites + +Each lab assumes: + +- FreeBSD 14.3 or later. +- `/usr/src/` is populated (run `svnlite co` or use `pkg install + src-quarterly` or a release tarball). +- Standard build tools available (`make(1)`, `cc(1)`). These are in + the base system on FreeBSD. + +## Building a Kernel Module + +The labs use the standard FreeBSD kernel module build system. + +``` +$ make clean +$ make +``` + +This produces a `.ko` file in the current directory. The file name +matches the `KMOD` variable in the `Makefile`. + +## Loading and Unloading + +``` +$ sudo kldload ./perfdemo.ko # load +$ sudo kldunload perfdemo # unload (no .ko suffix on unload) +$ kldstat | grep perfdemo # verify +``` + +Always unload a test module before rebuilding. A stale module in the +kernel confuses the next build. + +## Running the Workload + +Most labs use `dd(1)` as a simple read workload: + +``` +$ dd if=/dev/perfdemo of=/dev/null bs=4096 count=100000 +``` + +For concurrent loads, run multiple `dd` processes in parallel: + +``` +$ for i in 1 2 3 4; do dd if=/dev/perfdemo of=/dev/null bs=4096 \ + count=25000 & done; wait +``` + +## Reading Counters + +``` +$ sysctl hw.perfdemo +``` + +The exact names depend on the lab; each lab's README lists them. + +## Measuring Latency With `time(1)` + +``` +$ time dd if=/dev/perfdemo of=/dev/null bs=4096 count=100000 +``` + +## Measuring Elapsed Time Inside a Script + +``` +#!/bin/sh +start=$(date +%s.%N) +dd if=/dev/perfdemo of=/dev/null bs=4096 count=100000 2>/dev/null +end=$(date +%s.%N) +echo "elapsed: $(echo $end - $start | bc)s" +``` + +## Cleaning Up + +Always unload test modules when you are finished: + +``` +$ sudo kldunload perfdemo +``` diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/Makefile b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.c new file mode 100644 index 0000000..bfe5658 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.c @@ -0,0 +1,166 @@ +/* + * bugdemo - Challenge 3 (deadlock) variant. + * + * Two mutexes, two ioctl paths, opposite acquisition orders. + * Classic AB-BA deadlock. The lab03-debug-kernel variant is + * deterministic (sleeps between acquisitions to force the + * ordering); this challenge variant adds timing jitter so the + * hang looks intermittent. Your job is to find it anyway. + * + * Run with a kernel that has WITNESS enabled. WITNESS will + * report the lock-order violation the first time it is seen, + * even if the deadlock itself does not trigger that run. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx lock1; + struct mtx lock2; + uint64_t ncalls; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_do_path_a(struct bugdemo_softc *sc) +{ + mtx_lock(&sc->lock1); + /* Simulate some work under lock1. */ + pause("path_a", 1); + mtx_lock(&sc->lock2); + sc->ncalls++; + mtx_unlock(&sc->lock2); + mtx_unlock(&sc->lock1); +} + +static void +bugdemo_do_path_b(struct bugdemo_softc *sc) +{ + /* + * Deliberate bug: path B acquires lock2 first, then lock1. + * If thread 1 runs path A and holds lock1 while thread 2 + * runs path B and holds lock2, both will block forever. + */ + mtx_lock(&sc->lock2); + pause("path_b", 1); + mtx_lock(&sc->lock1); + sc->ncalls++; + mtx_unlock(&sc->lock1); + mtx_unlock(&sc->lock2); +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + switch (bcmd->op) { + case BUGDEMO_OP_PATH_A: + bugdemo_do_path_a(sc); + return (0); + case BUGDEMO_OP_PATH_B: + bugdemo_do_path_b(sc); + return (0); + default: + return (EINVAL); + } + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->lock1, "bugdemo_l1", NULL, MTX_DEF); + mtx_init(&sc->lock2, "bugdemo_l2", NULL, MTX_DEF); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->lock1); + mtx_destroy(&sc->lock2); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: deadlock variant loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + mtx_destroy(&sc->lock1); + mtx_destroy(&sc->lock2); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: deadlock variant unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.h new file mode 100644 index 0000000..32f5aa0 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo.h @@ -0,0 +1,23 @@ +/* + * bugdemo.h - Challenge 3 (deadlock) shared header. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_PATH_A 0 +#define BUGDEMO_OP_PATH_B 1 +#define BUGDEMO_OP_MAX 2 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo_test.c new file mode 100644 index 0000000..5f2b36d --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/deadlock/bugdemo_test.c @@ -0,0 +1,97 @@ +/* + * bugdemo_test - Challenge 3 (deadlock) companion. + * + * Usage: + * ./bugdemo_test path-a + * ./bugdemo_test path-b + * ./bugdemo_test race N - spawn N children alternating + * path-a and path-b + * + * To observe the deadlock, run "race" with a few tens of + * iterations on an SMP system. On a single-CPU VM the race is + * much harder to hit but WITNESS will still flag the + * lock-order violation. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +#define DEVPATH "/dev/bugdemo" + +static void +usage(const char *prog) +{ + fprintf(stderr, + "usage: %s path-a\n" + " %s path-b\n" + " %s race N\n", + prog, prog, prog); + exit(2); +} + +static int +issue_one(int fd, uint32_t op) +{ + struct bugdemo_command cmd; + + memset(&cmd, 0, sizeof(cmd)); + cmd.op = op; + return (ioctl(fd, BUGDEMO_TRIGGER, &cmd)); +} + +int +main(int argc, char **argv) +{ + int fd; + + if (argc < 2) + usage(argv[0]); + + fd = open(DEVPATH, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVPATH); + + if (strcmp(argv[1], "path-a") == 0) { + if (issue_one(fd, BUGDEMO_OP_PATH_A) != 0) + err(1, "ioctl path-a"); + } else if (strcmp(argv[1], "path-b") == 0) { + if (issue_one(fd, BUGDEMO_OP_PATH_B) != 0) + err(1, "ioctl path-b"); + } else if (strcmp(argv[1], "race") == 0) { + int n, children = 0; + + if (argc != 3) + usage(argv[0]); + n = atoi(argv[2]); + for (int i = 0; i < n; i++) { + pid_t pid = fork(); + if (pid < 0) + err(1, "fork"); + if (pid == 0) { + uint32_t op = (i & 1) ? + BUGDEMO_OP_PATH_A : BUGDEMO_OP_PATH_B; + for (int j = 0; j < 50; j++) + (void)issue_one(fd, op); + _exit(0); + } + children++; + } + for (int i = 0; i < children; i++) + (void)wait(NULL); + } else { + usage(argv[0]); + } + + close(fd); + return (0); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/Makefile b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.c new file mode 100644 index 0000000..766996c --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.c @@ -0,0 +1,204 @@ +/* + * bugdemo - Challenge 2 (leaky-driver) variant. + * + * Each ALLOC ioctl allocates a small object. Each FREE ioctl is + * supposed to free the most recently allocated object. The bug + * is that one code path inside ALLOC returns without adding the + * new object to the list, so FREE cannot find it. Over time the + * orphaned objects accumulate. + * + * Your job in the challenge is to find the leak path. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_obj { + TAILQ_ENTRY(bugdemo_obj) link; + uint64_t id; + char pad[56]; +}; + +TAILQ_HEAD(bugdemo_objlist, bugdemo_obj); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; + struct bugdemo_objlist objs; + uint64_t next_id; + uint64_t nallocs; + uint64_t nfrees; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_do_alloc(struct bugdemo_softc *sc, struct bugdemo_command *bcmd) +{ + struct bugdemo_obj *obj; + + obj = malloc(sizeof(*obj), M_BUGDEMO, M_WAITOK | M_ZERO); + + mtx_lock(&sc->sc_mutex); + obj->id = ++sc->next_id; + sc->nallocs++; + + /* + * Deliberate bug: when RETURN_EARLY is set, the driver + * increments the statistics counter and returns without + * linking the object into sc->objs. The caller gets + * success, but the object is unreachable from FREE. + */ + if (bcmd->flags & BUGDEMO_FLAG_RETURN_EARLY) { + mtx_unlock(&sc->sc_mutex); + return (0); + } + + TAILQ_INSERT_HEAD(&sc->objs, obj, link); + mtx_unlock(&sc->sc_mutex); + return (0); +} + +static int +bugdemo_do_free(struct bugdemo_softc *sc) +{ + struct bugdemo_obj *obj; + + mtx_lock(&sc->sc_mutex); + obj = TAILQ_FIRST(&sc->objs); + if (obj == NULL) { + mtx_unlock(&sc->sc_mutex); + return (ENOENT); + } + TAILQ_REMOVE(&sc->objs, obj, link); + sc->nfrees++; + mtx_unlock(&sc->sc_mutex); + free(obj, M_BUGDEMO); + return (0); +} + +static int +bugdemo_do_stats(struct bugdemo_softc *sc, struct bugdemo_command *bcmd) +{ + mtx_lock(&sc->sc_mutex); + bcmd->arg = sc->nallocs - sc->nfrees; + mtx_unlock(&sc->sc_mutex); + return (0); +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + switch (bcmd->op) { + case BUGDEMO_OP_ALLOC: + return (bugdemo_do_alloc(sc, bcmd)); + case BUGDEMO_OP_FREE: + return (bugdemo_do_free(sc)); + case BUGDEMO_OP_STATS: + return (bugdemo_do_stats(sc, bcmd)); + default: + return (EINVAL); + } + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + struct bugdemo_obj *obj, *tobj; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + TAILQ_INIT(&sc->objs); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: leaky-driver variant loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + TAILQ_FOREACH_SAFE(obj, &sc->objs, link, tobj) { + TAILQ_REMOVE(&sc->objs, obj, link); + free(obj, M_BUGDEMO); + } + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: leaky-driver variant unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.h new file mode 100644 index 0000000..a818172 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo.h @@ -0,0 +1,26 @@ +/* + * bugdemo.h - Challenge 2 (leaky-driver) shared header. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_ALLOC 0 +#define BUGDEMO_OP_FREE 1 +#define BUGDEMO_OP_STATS 2 +#define BUGDEMO_OP_MAX 3 + +#define BUGDEMO_FLAG_RETURN_EARLY 0x0001 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo_test.c new file mode 100644 index 0000000..0640fec --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/leaky-driver/bugdemo_test.c @@ -0,0 +1,91 @@ +/* + * bugdemo_test - Challenge 2 (leaky-driver) companion. + * + * Usage: + * ./bugdemo_test alloc [N] - N allocations, normal path + * ./bugdemo_test alloc-leaky [N] - N allocations, leaky path + * ./bugdemo_test free [N] - free the top N objects + * ./bugdemo_test stats - inflight allocations + * + * Exercise: drive enough leaky allocations to make vmstat -m + * show the leak, then use DTrace to capture the stack trace of + * the leaking path. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +#define DEVPATH "/dev/bugdemo" + +static void +usage(const char *prog) +{ + fprintf(stderr, + "usage: %s alloc [N]\n" + " %s alloc-leaky [N]\n" + " %s free [N]\n" + " %s stats\n", + prog, prog, prog, prog); + exit(2); +} + +int +main(int argc, char **argv) +{ + struct bugdemo_command cmd; + int fd, n = 1; + + if (argc < 2) + usage(argv[0]); + + fd = open(DEVPATH, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVPATH); + + memset(&cmd, 0, sizeof(cmd)); + + if (strcmp(argv[1], "alloc") == 0 || + strcmp(argv[1], "alloc-leaky") == 0) { + if (argc == 3) + n = atoi(argv[2]); + cmd.op = BUGDEMO_OP_ALLOC; + if (strcmp(argv[1], "alloc-leaky") == 0) + cmd.flags = BUGDEMO_FLAG_RETURN_EARLY; + for (int i = 0; i < n; i++) { + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) + err(1, "ioctl alloc"); + } + printf("issued %d allocations (flags=0x%x)\n", + n, cmd.flags); + } else if (strcmp(argv[1], "free") == 0) { + if (argc == 3) + n = atoi(argv[2]); + cmd.op = BUGDEMO_OP_FREE; + for (int i = 0; i < n; i++) { + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) { + warn("ioctl free (after %d)", i); + break; + } + } + } else if (strcmp(argv[1], "stats") == 0) { + cmd.op = BUGDEMO_OP_STATS; + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) + err(1, "ioctl stats"); + printf("inflight = %llu\n", + (unsigned long long)cmd.arg); + } else { + usage(argv[0]); + } + + close(fd); + return (0); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/Makefile b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.c new file mode 100644 index 0000000..9a8edaa --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.c @@ -0,0 +1,169 @@ +/* + * bugdemo - Challenge 1 (silent-bug) variant. + * + * Contains a subtle bug: an atomic counter is incremented without + * the memory barrier that callers implicitly expect. Under enough + * concurrency the READ path can observe stale values. There is no + * panic, no error, no log message. The only symptom is a wrong + * number. + * + * Your job in the challenge is to reproduce the bug, locate it + * with tracing, and fix it. + * + * Hint: look at the choice of atomic operation. FreeBSD's + * atomic(9) distinguishes between plain atomics and atomics with + * acquire/release semantics for a reason. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; + volatile u_int counter; + volatile u_int ready; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_do_increment(struct bugdemo_softc *sc) +{ + /* + * Deliberate bug: plain add. The READ path depends on + * ready=1 implying the counter is visible, but without a + * release barrier on the writer side (and an acquire + * barrier on the reader side), the ready store can become + * visible before the counter store on weakly ordered + * architectures. The correct primitive here is + * atomic_store_rel_int() (or equivalent). + */ + atomic_add_int(&sc->counter, 1); + atomic_store_int(&sc->ready, 1); +} + +static u_int +bugdemo_do_read(struct bugdemo_softc *sc) +{ + /* + * Deliberate bug: plain load. Without acquire semantics on + * ready, the compiler or hardware can reorder the counter + * load above the ready check, yielding a stale value. + */ + if (atomic_load_int(&sc->ready) == 0) + return (0); + return (atomic_load_int(&sc->counter)); +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + switch (bcmd->op) { + case BUGDEMO_OP_INCREMENT: + bugdemo_do_increment(sc); + return (0); + case BUGDEMO_OP_READ: + bcmd->arg = bugdemo_do_read(sc); + return (0); + default: + return (EINVAL); + } + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: silent-bug variant loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: silent-bug variant unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.h new file mode 100644 index 0000000..044dfbf --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo.h @@ -0,0 +1,23 @@ +/* + * bugdemo.h - Challenge 1 (silent-bug) shared header. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_INCREMENT 0 +#define BUGDEMO_OP_READ 1 +#define BUGDEMO_OP_MAX 2 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo_test.c new file mode 100644 index 0000000..ae61389 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab-challenges/silent-bug/bugdemo_test.c @@ -0,0 +1,71 @@ +/* + * bugdemo_test - Challenge 1 (silent-bug) companion. + * + * Drives the driver through INCREMENT and READ ioctls. On a + * single thread the bug is hard to observe; it shows up under + * concurrency. Try running several copies of this program in + * parallel and compare the reported totals against the number + * of increments. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +#define DEVPATH "/dev/bugdemo" + +static void +usage(const char *prog) +{ + fprintf(stderr, + "usage: %s increment [N]\n" + " %s read\n", + prog, prog); + exit(2); +} + +int +main(int argc, char **argv) +{ + struct bugdemo_command cmd; + int fd, n = 1; + + if (argc < 2) + usage(argv[0]); + + fd = open(DEVPATH, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVPATH); + + memset(&cmd, 0, sizeof(cmd)); + + if (strcmp(argv[1], "increment") == 0) { + if (argc == 3) + n = atoi(argv[2]); + cmd.op = BUGDEMO_OP_INCREMENT; + for (int i = 0; i < n; i++) { + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) + err(1, "ioctl increment"); + } + printf("issued %d increments\n", n); + } else if (strcmp(argv[1], "read") == 0) { + cmd.op = BUGDEMO_OP_READ; + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) + err(1, "ioctl read"); + printf("counter = %llu\n", + (unsigned long long)cmd.arg); + } else { + usage(argv[0]); + } + + close(fd); + return (0); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab01-kassert/Makefile b/examples/part-07/ch34-advanced-debugging/lab01-kassert/Makefile new file mode 100644 index 0000000..e202b54 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab01-kassert/Makefile @@ -0,0 +1,16 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +testclean: + rm -f bugdemo_test + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.c new file mode 100644 index 0000000..683c4fc --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.c @@ -0,0 +1,220 @@ +/* + * bugdemo - pseudo-device used to illustrate advanced debugging + * techniques in FreeBSD device drivers. + * + * Lab 1: baseline. Implements a minimal ioctl(2) interface guarded by + * KASSERT, MPASS, and CTASSERT checks. The driver exposes a + * few ops through sysctl; one op deliberately generates an + * out-of-range value to demonstrate a KASSERT firing. + * + * This is a companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +CTASSERT(sizeof(struct bugdemo_command) == 16); +CTASSERT(BUGDEMO_OP_MAX <= 16); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; + int state; +#define BUGDEMO_STATE_INIT 0 +#define BUGDEMO_STATE_READY 1 +#define BUGDEMO_STATE_DEAD 2 + counter_u64_t ioctls; + counter_u64_t errors; +}; + +#define BUGDEMO_LOCK(sc) mtx_lock(&(sc)->sc_mutex) +#define BUGDEMO_UNLOCK(sc) mtx_unlock(&(sc)->sc_mutex) +#define BUGDEMO_LOCK_ASSERT(sc) mtx_assert(&(sc)->sc_mutex, MA_OWNED) + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static SYSCTL_NODE(_hw, OID_AUTO, bugdemo, + CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "bugdemo driver"); + +static int +bugdemo_sysctl_ioctls(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(bugdemo_sc->ioctls); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +static int +bugdemo_sysctl_errors(SYSCTL_HANDLER_ARGS) +{ + uint64_t v = counter_u64_fetch(bugdemo_sc->errors); + return (sysctl_handle_64(oidp, &v, 0, req)); +} + +SYSCTL_PROC(_hw_bugdemo, OID_AUTO, ioctls, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, bugdemo_sysctl_ioctls, "QU", + "Total number of ioctls served since load"); + +SYSCTL_PROC(_hw_bugdemo, OID_AUTO, errors, + CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, + NULL, 0, bugdemo_sysctl_errors, "QU", + "Total number of errors since load"); + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) +{ + + KASSERT(sc != NULL, ("bugdemo: softc missing")); + KASSERT(cmd != NULL, ("bugdemo: cmd missing")); + KASSERT(cmd->op < BUGDEMO_OP_MAX, + ("bugdemo: op %u out of range", cmd->op)); + MPASS(sc->state == BUGDEMO_STATE_READY); + BUGDEMO_LOCK_ASSERT(sc); + + switch (cmd->op) { + case BUGDEMO_OP_NOOP: + break; + case BUGDEMO_OP_HELLO: + cmd->arg = 0x48454c4c4f; /* "HELLO" */ + break; + case BUGDEMO_OP_COUNT: + cmd->arg = counter_u64_fetch(sc->ioctls); + break; + default: + /* + * Unreachable because of the KASSERT above, but kept + * as an explicit fail-safe for release kernels. + */ + cmd->arg = 0; + break; + } +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + KASSERT(sc != NULL, ("bugdemo_ioctl: no softc")); + + counter_u64_add(sc->ioctls, 1); + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + /* + * FORCE_BAD_OP deliberately produces an out-of-range + * op to demonstrate KASSERT firing. In a release build + * (no INVARIANTS) the KASSERT in bugdemo_process is + * compiled out and the default switch branch handles + * the bad op safely. + */ + if (bcmd->flags & BUGDEMO_FLAG_FORCE_BAD_OP) + bcmd->op = 0xff; + BUGDEMO_LOCK(sc); + bugdemo_process(sc, bcmd); + BUGDEMO_UNLOCK(sc); + return (0); + default: + counter_u64_add(sc->errors, 1); + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + sc->state = BUGDEMO_STATE_READY; + sc->ioctls = counter_u64_alloc(M_WAITOK); + sc->errors = counter_u64_alloc(M_WAITOK); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + counter_u64_free(sc->ioctls); + counter_u64_free(sc->errors); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: lab01 loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + BUGDEMO_LOCK(sc); + sc->state = BUGDEMO_STATE_DEAD; + BUGDEMO_UNLOCK(sc); + if (sc->dev != NULL) + destroy_dev(sc->dev); + counter_u64_free(sc->ioctls); + counter_u64_free(sc->errors); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: lab01 unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.h new file mode 100644 index 0000000..ef56f15 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo.h @@ -0,0 +1,40 @@ +/* + * bugdemo.h - shared user-kernel definitions for the bugdemo driver. + * + * This header defines the ioctl interface used by the bugdemo + * pseudo-device and its companion user-space test program. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +/* + * bugdemo_command - the argument struct for BUGDEMO_TRIGGER. + * + * The layout is fixed-width so user-space and kernel-space see the + * same bytes regardless of compiler options. CTASSERT in the driver + * verifies the size. + */ +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +/* Operation codes. Add new ones at the end and update BUGDEMO_OP_MAX. */ +#define BUGDEMO_OP_NOOP 0 +#define BUGDEMO_OP_HELLO 1 +#define BUGDEMO_OP_COUNT 2 +#define BUGDEMO_OP_MAX 3 + +/* Flags passed with BUGDEMO_TRIGGER. */ +#define BUGDEMO_FLAG_FORCE_BAD_OP 0x0001 +#define BUGDEMO_FLAG_NULL_SOFTC 0x0002 + +/* ioctl commands */ +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo_test.c new file mode 100644 index 0000000..de83eb7 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab01-kassert/bugdemo_test.c @@ -0,0 +1,79 @@ +/* + * bugdemo_test - user-space test program for the bugdemo driver. + * + * Exercises the ioctl(2) interface with one subcommand per argument: + * + * noop - triggers BUGDEMO_OP_NOOP + * hello - triggers BUGDEMO_OP_HELLO + * count - triggers BUGDEMO_OP_COUNT + * force-bad-op - sets BUGDEMO_FLAG_FORCE_BAD_OP, which panics on + * a kernel with INVARIANTS + * + * On a debug kernel, force-bad-op triggers a KASSERT panic. + * On a release kernel, the KASSERT is compiled out and the call + * returns without any error. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static int +do_op(int fd, uint32_t op, uint32_t flags) +{ + struct bugdemo_command cmd; + + memset(&cmd, 0, sizeof(cmd)); + cmd.op = op; + cmd.flags = flags; + + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) < 0) { + warn("ioctl BUGDEMO_TRIGGER"); + return (1); + } + + printf("op=%u flags=0x%x arg=0x%llx\n", + cmd.op, cmd.flags, (unsigned long long)cmd.arg); + return (0); +} + +int +main(int argc, char *argv[]) +{ + int fd; + int rv; + + if (argc < 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + fprintf(stderr, "subcommands:\n"); + fprintf(stderr, " noop, hello, count, force-bad-op\n"); + return (2); + } + + fd = open("/dev/bugdemo", O_RDWR); + if (fd < 0) + err(1, "open /dev/bugdemo"); + + if (strcmp(argv[1], "noop") == 0) + rv = do_op(fd, BUGDEMO_OP_NOOP, 0); + else if (strcmp(argv[1], "hello") == 0) + rv = do_op(fd, BUGDEMO_OP_HELLO, 0); + else if (strcmp(argv[1], "count") == 0) + rv = do_op(fd, BUGDEMO_OP_COUNT, 0); + else if (strcmp(argv[1], "force-bad-op") == 0) + rv = do_op(fd, BUGDEMO_OP_NOOP, BUGDEMO_FLAG_FORCE_BAD_OP); + else { + fprintf(stderr, "unknown subcommand: %s\n", argv[1]); + rv = 2; + } + + close(fd); + return (rv); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab02-kgdb/Makefile b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.c new file mode 100644 index 0000000..6833eac --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.c @@ -0,0 +1,171 @@ +/* + * bugdemo - Lab 2 variant. + * + * Adds support for a subcommand that clears the softc pointer to + * produce a predictable null-pointer panic whose dump can be walked + * with kgdb. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; + int state; +#define BUGDEMO_STATE_READY 1 + counter_u64_t ioctls; +}; + +#define BUGDEMO_LOCK(sc) mtx_lock(&(sc)->sc_mutex) +#define BUGDEMO_UNLOCK(sc) mtx_unlock(&(sc)->sc_mutex) + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) +{ + + /* + * The KASSERT fires on a debug kernel when sc is NULL, which + * is what the null-softc test path produces. + */ + KASSERT(sc != NULL, ("bugdemo: softc missing")); + + counter_u64_add(sc->ioctls, 1); + + switch (cmd->op) { + case BUGDEMO_OP_NOOP: + break; + case BUGDEMO_OP_HELLO: + cmd->arg = 0x48454c4c4f; + break; + case BUGDEMO_OP_COUNT: + cmd->arg = counter_u64_fetch(sc->ioctls); + break; + default: + cmd->arg = 0; + break; + } +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + /* + * NULL_SOFTC sets the si_drv1 pointer to NULL before + * dereferencing it in bugdemo_process. This is a + * deliberate bug for demonstration. + */ + if (bcmd->flags & BUGDEMO_FLAG_NULL_SOFTC) { + dev->si_drv1 = NULL; + sc = NULL; + } else { + sc = dev->si_drv1; + } + BUGDEMO_LOCK(bugdemo_sc); + bugdemo_process(sc, bcmd); + BUGDEMO_UNLOCK(bugdemo_sc); + return (0); + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + sc->state = BUGDEMO_STATE_READY; + sc->ioctls = counter_u64_alloc(M_WAITOK); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + counter_u64_free(sc->ioctls); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: lab02 loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + counter_u64_free(sc->ioctls); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: lab02 unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.h new file mode 100644 index 0000000..c43f94c --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo.h @@ -0,0 +1,31 @@ +/* + * bugdemo.h - shared user/kernel header for the Lab 2 variant. + * + * Adds a subcommand that clears the driver's softc pointer and + * triggers an immediate panic, so the reader can walk the resulting + * crash dump with kgdb. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_NOOP 0 +#define BUGDEMO_OP_HELLO 1 +#define BUGDEMO_OP_COUNT 2 +#define BUGDEMO_OP_MAX 3 + +#define BUGDEMO_FLAG_FORCE_BAD_OP 0x0001 +#define BUGDEMO_FLAG_NULL_SOFTC 0x0002 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo_test.c new file mode 100644 index 0000000..b39b30e --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/bugdemo_test.c @@ -0,0 +1,69 @@ +/* + * bugdemo_test - Lab 2 test program. + * + * Adds a null-softc subcommand that deliberately triggers a panic + * suitable for walking with kgdb after a reboot. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static int +do_op(int fd, uint32_t op, uint32_t flags) +{ + struct bugdemo_command cmd; + + memset(&cmd, 0, sizeof(cmd)); + cmd.op = op; + cmd.flags = flags; + + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) < 0) { + warn("ioctl BUGDEMO_TRIGGER"); + return (1); + } + + printf("op=%u flags=0x%x arg=0x%llx\n", + cmd.op, cmd.flags, (unsigned long long)cmd.arg); + return (0); +} + +int +main(int argc, char *argv[]) +{ + int fd; + int rv; + + if (argc < 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + fprintf(stderr, "subcommands: noop hello count null-softc\n"); + return (2); + } + + fd = open("/dev/bugdemo", O_RDWR); + if (fd < 0) + err(1, "open /dev/bugdemo"); + + if (strcmp(argv[1], "noop") == 0) + rv = do_op(fd, BUGDEMO_OP_NOOP, 0); + else if (strcmp(argv[1], "hello") == 0) + rv = do_op(fd, BUGDEMO_OP_HELLO, 0); + else if (strcmp(argv[1], "count") == 0) + rv = do_op(fd, BUGDEMO_OP_COUNT, 0); + else if (strcmp(argv[1], "null-softc") == 0) + rv = do_op(fd, BUGDEMO_OP_NOOP, BUGDEMO_FLAG_NULL_SOFTC); + else { + fprintf(stderr, "unknown subcommand: %s\n", argv[1]); + rv = 2; + } + + close(fd); + return (rv); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab02-kgdb/dump-setup.sh b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/dump-setup.sh new file mode 100644 index 0000000..66eb47c --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab02-kgdb/dump-setup.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# +# dump-setup.sh - verify that a dump device is configured. +# +# This script does not change the system. It reports the current dump +# configuration and, if no dump device is set, prints the commands the +# reader should run to configure one. + +echo "current dump configuration:" +dumpon -l + +if ! dumpon -l | grep -q '^/dev/'; then + cat <<'EOF' + +No dump device is currently configured. To set one, identify your +swap partition and run: + + # dumpon /dev/DEVICE + +and persist across reboots by adding to /etc/rc.conf: + + dumpdev="/dev/DEVICE" + savecore_enable="YES" + +Replace DEVICE with your actual swap partition name. You can find it +with: + + # swapinfo + +EOF + exit 1 +fi + +echo "dump device is configured. ready to capture panics." +exit 0 diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/GENERIC-DEBUG.sample b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/GENERIC-DEBUG.sample new file mode 100644 index 0000000..ae7cbc9 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/GENERIC-DEBUG.sample @@ -0,0 +1,32 @@ +# GENERIC-DEBUG.sample +# +# A sample debug kernel config. On FreeBSD 14.3, the stock +# GENERIC-DEBUG is equivalent to this; you can use it directly +# by specifying KERNCONF=GENERIC-DEBUG when building. +# +# For memguard work in Lab 5, you can add: +# options DEBUG_MEMGUARD +# to this file and build with KERNCONF pointing to this copy. + +include GENERIC +include "std.debug" + +# Uncomment for Lab 5: +# options DEBUG_MEMGUARD + +# Uncomment if you want to see even more verbose boot output: +# options VERBOSE_SYSINIT + +# Notes: +# +# std.debug already enables: +# INVARIANTS, INVARIANT_SUPPORT, WITNESS, WITNESS_SKIPSPIN, +# MALLOC_DEBUG_MAXZONES=8, ALT_BREAK_TO_DEBUGGER, DEADLKRES, +# BUF_TRACKING, and makeoptions DEBUG=-g. +# +# GENERIC already enables: +# KDB, KDB_TRACE, DDB, GDB, EKCD, KDTRACE_FRAME, KDTRACE_HOOKS, +# DDB_CTF. +# +# With the two combined you have the standard debug kernel used +# throughout Chapter 34. diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/Makefile b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.c new file mode 100644 index 0000000..08ed7a6 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.c @@ -0,0 +1,147 @@ +/* + * bugdemo - Lab 3 variant. + * + * Two mutexes, acquired in opposite orders on different ioctl paths. + * WITNESS detects the second acquisition order and warns. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx lock1; + struct mtx lock2; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_path_a(struct bugdemo_softc *sc) +{ + /* order: lock1 -> lock2 */ + mtx_lock(&sc->lock1); + mtx_lock(&sc->lock2); + mtx_unlock(&sc->lock2); + mtx_unlock(&sc->lock1); +} + +static void +bugdemo_path_b(struct bugdemo_softc *sc) +{ + /* order: lock2 -> lock1 (reverses the order seen in path A) */ + mtx_lock(&sc->lock2); + mtx_lock(&sc->lock1); + mtx_unlock(&sc->lock1); + mtx_unlock(&sc->lock2); +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + if (bcmd->op == BUGDEMO_OP_LOCK_A) + bugdemo_path_a(sc); + else if (bcmd->op == BUGDEMO_OP_LOCK_B) + bugdemo_path_b(sc); + else + return (EINVAL); + return (0); + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->lock1, "bugdemo_lock1", NULL, MTX_DEF); + mtx_init(&sc->lock2, "bugdemo_lock2", NULL, MTX_DEF); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->lock1); + mtx_destroy(&sc->lock2); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: lab03 loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + mtx_destroy(&sc->lock1); + mtx_destroy(&sc->lock2); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: lab03 unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.h new file mode 100644 index 0000000..c781df9 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo.h @@ -0,0 +1,27 @@ +/* + * bugdemo.h - Lab 3 shared header. + * + * Exposes two ioctl paths with deliberate lock ordering disagreement + * to trigger WITNESS warnings on a debug kernel. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +/* Lock order paths. */ +#define BUGDEMO_OP_LOCK_A 0 /* lock1 -> lock2 */ +#define BUGDEMO_OP_LOCK_B 1 /* lock2 -> lock1 */ +#define BUGDEMO_OP_MAX 2 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo_test.c new file mode 100644 index 0000000..8ced7a9 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/bugdemo_test.c @@ -0,0 +1,60 @@ +/* + * bugdemo_test - Lab 3 test program. + * + * Two subcommands exercise the two lock acquisition orders in the + * driver. Running both (in either order) triggers a WITNESS warning. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static int +do_op(int fd, uint32_t op) +{ + struct bugdemo_command cmd; + + memset(&cmd, 0, sizeof(cmd)); + cmd.op = op; + + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) < 0) { + warn("ioctl BUGDEMO_TRIGGER"); + return (1); + } + return (0); +} + +int +main(int argc, char *argv[]) +{ + int fd; + int rv; + + if (argc < 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + return (2); + } + + fd = open("/dev/bugdemo", O_RDWR); + if (fd < 0) + err(1, "open /dev/bugdemo"); + + if (strcmp(argv[1], "path-a") == 0) + rv = do_op(fd, BUGDEMO_OP_LOCK_A); + else if (strcmp(argv[1], "path-b") == 0) + rv = do_op(fd, BUGDEMO_OP_LOCK_B); + else { + fprintf(stderr, "unknown subcommand: %s\n", argv[1]); + rv = 2; + } + + close(fd); + return (rv); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/build-kernel.sh b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/build-kernel.sh new file mode 100644 index 0000000..2e317be --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab03-debug-kernel/build-kernel.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# +# build-kernel.sh - walk through building a debug kernel. +# +# This script is not run automatically; it prints the commands the +# reader should run, with brief commentary. It does not change the +# system. + +cat <<'EOF' +Debug kernel build procedure +============================ + +1. Ensure /usr/src/ is populated. If it is not: + + # git clone --depth 1 -b releng/14.3 \ + https://git.freebsd.org/src.git /usr/src + +2. Review the existing GENERIC-DEBUG config: + + $ cat /usr/src/sys/amd64/conf/GENERIC-DEBUG + +3. Build the kernel: + + # cd /usr/src + # make buildkernel KERNCONF=GENERIC-DEBUG + + This takes twenty to forty minutes on a modest VM. + +4. Install the new kernel (the previous one is kept as kernel.old): + + # make installkernel KERNCONF=GENERIC-DEBUG + +5. Reboot: + + # shutdown -r now + +6. After reboot, confirm: + + $ uname -v + $ sysctl debug.kdb.supported_backends + $ sysctl debug.debugger_on_panic + +7. If the new kernel fails to boot, pick "Boot kernel.old" from the + loader menu to return to the previous working kernel. + +EOF diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/Makefile b/examples/part-07/ch34-advanced-debugging/lab04-tracing/Makefile new file mode 100644 index 0000000..87c40ee --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/Makefile @@ -0,0 +1,16 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +# Build with WITH_CTF=1 to let DTrace resolve struct fields by name: +# $ WITH_CTF=1 make + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.c new file mode 100644 index 0000000..34f3540 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.c @@ -0,0 +1,165 @@ +/* + * bugdemo - Lab 4 variant. + * + * Adds SDT probes at command start and completion so DTrace can + * watch the driver in action. Also exposes an explicit error path + * (BUGDEMO_OP_BAD) that returns EIO, useful for demonstrating how + * DTrace can walk stacks on errors. + * + * Build with WITH_CTF=1 for DTrace to resolve struct fields by name: + * $ WITH_CTF=1 make + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +SDT_PROVIDER_DEFINE(bugdemo); + +SDT_PROBE_DEFINE2(bugdemo, , , cmd__start, + "struct bugdemo_softc *", "int"); +SDT_PROBE_DEFINE3(bugdemo, , , cmd__done, + "struct bugdemo_softc *", "int", "int"); +SDT_PROBE_DEFINE2(bugdemo, , , cmd__error, + "struct bugdemo_softc *", "int"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_process(struct bugdemo_softc *sc, struct bugdemo_command *cmd) +{ + int error = 0; + + SDT_PROBE2(bugdemo, , , cmd__start, sc, cmd->op); + + switch (cmd->op) { + case BUGDEMO_OP_NOOP: + break; + case BUGDEMO_OP_HELLO: + cmd->arg = 0x48454c4c4f; + break; + case BUGDEMO_OP_COUNT: + cmd->arg = 1; + break; + case BUGDEMO_OP_BAD: + SDT_PROBE2(bugdemo, , , cmd__error, sc, cmd->op); + error = EIO; + break; + default: + error = EINVAL; + break; + } + + SDT_PROBE3(bugdemo, , , cmd__done, sc, cmd->op, error); + return (error); +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + int error; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + mtx_lock(&sc->sc_mutex); + error = bugdemo_process(sc, bcmd); + mtx_unlock(&sc->sc_mutex); + return (error); + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: lab04 loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + if (sc->dev != NULL) + destroy_dev(sc->dev); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: lab04 unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.h new file mode 100644 index 0000000..9043a26 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo.h @@ -0,0 +1,25 @@ +/* + * bugdemo.h - Lab 4 shared header. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_NOOP 0 +#define BUGDEMO_OP_HELLO 1 +#define BUGDEMO_OP_COUNT 2 +#define BUGDEMO_OP_BAD 3 /* deliberately returns EIO */ +#define BUGDEMO_OP_MAX 4 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo_test.c new file mode 100644 index 0000000..b3ee90f --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/bugdemo_test.c @@ -0,0 +1,63 @@ +/* + * bugdemo_test - Lab 4 test program. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static int +do_op(int fd, uint32_t op) +{ + struct bugdemo_command cmd; + + memset(&cmd, 0, sizeof(cmd)); + cmd.op = op; + + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) < 0) { + warn("ioctl BUGDEMO_TRIGGER"); + return (1); + } + printf("op=%u arg=0x%llx\n", cmd.op, (unsigned long long)cmd.arg); + return (0); +} + +int +main(int argc, char *argv[]) +{ + int fd; + int rv; + + if (argc < 2) { + fprintf(stderr, "usage: %s \n", + argv[0]); + return (2); + } + + fd = open("/dev/bugdemo", O_RDWR); + if (fd < 0) + err(1, "open /dev/bugdemo"); + + if (strcmp(argv[1], "noop") == 0) + rv = do_op(fd, BUGDEMO_OP_NOOP); + else if (strcmp(argv[1], "hello") == 0) + rv = do_op(fd, BUGDEMO_OP_HELLO); + else if (strcmp(argv[1], "count") == 0) + rv = do_op(fd, BUGDEMO_OP_COUNT); + else if (strcmp(argv[1], "bad-op") == 0) + rv = do_op(fd, BUGDEMO_OP_BAD); + else { + fprintf(stderr, "unknown subcommand: %s\n", argv[1]); + rv = 2; + } + + close(fd); + return (rv); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/latency.d b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/latency.d new file mode 100644 index 0000000..b1edfe5 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/latency.d @@ -0,0 +1,30 @@ +#!/usr/sbin/dtrace -s +/* + * latency.d - measure ioctl latency per op. + * + * Usage: + * # dtrace -s latency.d + * + * Ctrl-C to print the aggregation. + */ + +#pragma D option quiet + +sdt:bugdemo::cmd-start +{ + self->start = timestamp; + self->op = arg1; +} + +sdt:bugdemo::cmd-done +/self->start != 0/ +{ + @lat[self->op] = quantize(timestamp - self->start); + self->start = 0; + self->op = 0; +} + +END +{ + printa("op=%d latency(ns):%@d\n", @lat); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/run-ktrace.sh b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/run-ktrace.sh new file mode 100644 index 0000000..76a5efa --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/run-ktrace.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# +# run-ktrace.sh - run bugdemo_test under ktrace and print the +# resulting trace with kdump. +# +# Usage: ./run-ktrace.sh +# +# The subcommand is passed directly to bugdemo_test. + +if [ $# -lt 1 ]; then + echo "usage: $0 " + exit 2 +fi + +rm -f ktrace.out +ktrace -t ci ../bugdemo_test "$@" +kdump | grep -E 'ioctl|bugdemo' || kdump +rm -f ktrace.out diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/trace-ioctls.d b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/trace-ioctls.d new file mode 100644 index 0000000..22563e5 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/trace-ioctls.d @@ -0,0 +1,20 @@ +#!/usr/sbin/dtrace -s +/* + * trace-ioctls.d - print each bugdemo command as it starts and ends. + * + * Usage: + * # dtrace -s trace-ioctls.d + */ + +#pragma D option quiet + +sdt:bugdemo::cmd-start +{ + printf("%Y %s:%d start op=%d\n", walltimestamp, execname, pid, arg1); +} + +sdt:bugdemo::cmd-done +{ + printf("%Y %s:%d done op=%d rv=%d\n", + walltimestamp, execname, pid, arg1, arg2); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/walk-errors.d b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/walk-errors.d new file mode 100644 index 0000000..e761aab --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab04-tracing/scripts/walk-errors.d @@ -0,0 +1,18 @@ +#!/usr/sbin/dtrace -s +/* + * walk-errors.d - print a stack trace each time bugdemo returns an + * error. + * + * Usage: + * # dtrace -s walk-errors.d + */ + +#pragma D option quiet + +sdt:bugdemo::cmd-error +{ + printf("error op=%d at %Y by %s:%d\n", + arg1, walltimestamp, execname, pid); + stack(); + printf("\n"); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab05-memguard/Makefile b/examples/part-07/ch34-advanced-debugging/lab05-memguard/Makefile new file mode 100644 index 0000000..5a8232b --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab05-memguard/Makefile @@ -0,0 +1,13 @@ +KMOD= bugdemo +SRCS= bugdemo.c + +SYSDIR?= /usr/src/sys + +test: bugdemo_test + +bugdemo_test: bugdemo_test.c bugdemo.h + cc -o bugdemo_test bugdemo_test.c + +CLEANFILES+= bugdemo_test + +.include diff --git a/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.c b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.c new file mode 100644 index 0000000..fa7526e --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.c @@ -0,0 +1,170 @@ +/* + * bugdemo - Lab 5 variant. + * + * Contains a deliberate use-after-free: the ioctl allocates a + * buffer, schedules a callout to read from it, then frees the + * buffer. When the callout fires, it dereferences freed memory. On + * a kernel with DEBUG_MEMGUARD and the driver's malloc type guarded, + * this produces an immediate page fault. + * + * Usage: + * # kldload ./bugdemo.ko + * # sysctl vm.memguard.desc=bugdemo + * # ./bugdemo_test use-after-free + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +static MALLOC_DEFINE(M_BUGDEMO, "bugdemo", "bugdemo driver buffers"); + +struct bugdemo_softc { + struct cdev *dev; + struct mtx sc_mutex; + char *buffer; + size_t buflen; + struct callout cb; +}; + +static d_open_t bugdemo_open; +static d_close_t bugdemo_close; +static d_ioctl_t bugdemo_ioctl; + +static struct cdevsw bugdemo_cdevsw = { + .d_version = D_VERSION, + .d_name = "bugdemo", + .d_open = bugdemo_open, + .d_close = bugdemo_close, + .d_ioctl = bugdemo_ioctl, +}; + +static struct bugdemo_softc *bugdemo_sc; + +static int +bugdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +bugdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static void +bugdemo_callout(void *arg) +{ + struct bugdemo_softc *sc = arg; + volatile char c; + + /* + * Read from sc->buffer. In the use-after-free path, this + * buffer has already been freed by the ioctl. With memguard + * enabled for the bugdemo type, the page is unmapped and this + * access produces a page fault. + */ + c = sc->buffer[0]; + (void)c; +} + +static void +bugdemo_trigger_use_after_free(struct bugdemo_softc *sc) +{ + sc->buflen = 128; + sc->buffer = malloc(sc->buflen, M_BUGDEMO, M_WAITOK | M_ZERO); + memcpy(sc->buffer, "bugdemo", 7); + + /* schedule the callout for 100ms out. */ + callout_init_mtx(&sc->cb, &sc->sc_mutex, 0); + callout_reset(&sc->cb, hz / 10, bugdemo_callout, sc); + + /* + * Deliberate bug: free the buffer without cancelling the + * callout. The callout will fire with sc->buffer still pointing + * at the freed memory. + */ + free(sc->buffer, M_BUGDEMO); + /* note: we do not set sc->buffer to NULL, also deliberately */ +} + +static int +bugdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, + struct thread *td) +{ + struct bugdemo_softc *sc = dev->si_drv1; + struct bugdemo_command *bcmd; + + switch (cmd) { + case BUGDEMO_TRIGGER: + bcmd = (struct bugdemo_command *)data; + mtx_lock(&sc->sc_mutex); + if (bcmd->op == BUGDEMO_OP_USE_AFTER_FREE) + bugdemo_trigger_use_after_free(sc); + mtx_unlock(&sc->sc_mutex); + return (0); + default: + return (ENOTTY); + } +} + +static int +bugdemo_modevent(module_t mod, int what, void *arg) +{ + struct bugdemo_softc *sc; + int error = 0; + + switch (what) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_BUGDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mutex, "bugdemo_sc", NULL, MTX_DEF); + sc->dev = make_dev(&bugdemo_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0666, "bugdemo"); + if (sc->dev == NULL) { + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + return (ENOMEM); + } + sc->dev->si_drv1 = sc; + bugdemo_sc = sc; + printf("bugdemo: lab05 loaded\n"); + break; + case MOD_UNLOAD: + if (bugdemo_sc != NULL) { + sc = bugdemo_sc; + callout_drain(&sc->cb); + if (sc->dev != NULL) + destroy_dev(sc->dev); + mtx_destroy(&sc->sc_mutex); + free(sc, M_BUGDEMO); + bugdemo_sc = NULL; + } + printf("bugdemo: lab05 unloaded\n"); + break; + default: + error = EOPNOTSUPP; + } + return (error); +} + +static moduledata_t bugdemo_mod = { + "bugdemo", + bugdemo_modevent, + NULL +}; + +DECLARE_MODULE(bugdemo, bugdemo_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(bugdemo, 1); diff --git a/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.h b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.h new file mode 100644 index 0000000..8845ade --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo.h @@ -0,0 +1,23 @@ +/* + * bugdemo.h - Lab 5 shared header. + */ + +#ifndef _BUGDEMO_H_ +#define _BUGDEMO_H_ + +#include +#include + +struct bugdemo_command { + uint32_t op; + uint32_t flags; + uint64_t arg; +}; + +#define BUGDEMO_OP_ALLOC 0 +#define BUGDEMO_OP_USE_AFTER_FREE 1 +#define BUGDEMO_OP_MAX 2 + +#define BUGDEMO_TRIGGER _IOWR('B', 1, struct bugdemo_command) + +#endif /* _BUGDEMO_H_ */ diff --git a/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo_test.c b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo_test.c new file mode 100644 index 0000000..59f23b0 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab05-memguard/bugdemo_test.c @@ -0,0 +1,67 @@ +/* + * bugdemo_test - Lab 5 variant. + * + * Sends a use-after-free ioctl to the bugdemo driver. With memguard + * enabled for the bugdemo malloc type, this is expected to panic the + * kernel. Run only on a throwaway debug VM. + * + * Companion example for Chapter 34 of + * "FreeBSD Device Drivers: From First Steps to Kernel Mastery." + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "bugdemo.h" + +#define DEVPATH "/dev/bugdemo" + +static void +usage(const char *prog) +{ + fprintf(stderr, + "usage: %s use-after-free\n", prog); + exit(2); +} + +int +main(int argc, char **argv) +{ + struct bugdemo_command cmd; + int fd; + + if (argc != 2) + usage(argv[0]); + + memset(&cmd, 0, sizeof(cmd)); + + if (strcmp(argv[1], "use-after-free") == 0) + cmd.op = BUGDEMO_OP_USE_AFTER_FREE; + else + usage(argv[0]); + + fd = open(DEVPATH, O_RDWR); + if (fd < 0) + err(1, "open %s", DEVPATH); + + if (ioctl(fd, BUGDEMO_TRIGGER, &cmd) != 0) + warn("ioctl BUGDEMO_TRIGGER"); + else + printf("ioctl issued: op=%u\n", cmd.op); + + /* + * The callout fires 100ms after the ioctl returns. Sleep for + * half a second so we do not exit before the bug manifests. + */ + usleep(500 * 1000); + + close(fd); + return (0); +} diff --git a/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/bhyve-launch.sh.sample b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/bhyve-launch.sh.sample new file mode 100644 index 0000000..039672e --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/bhyve-launch.sh.sample @@ -0,0 +1,37 @@ +#!/bin/sh +# +# bhyve-launch.sh.sample - sample bhyve launch script for Chapter 34 +# Lab 6 (remote GDB stub debugging). +# +# Adjust the VM name, disk image, and network settings for your +# environment. The important piece is the serial line: -l +# com1,/dev/nmdmXA gives the host a matching /dev/nmdmXB that you +# can open from kgdb. +# +# This is a sample. Do not copy it blindly. + +VMNAME=bugdemo-debug +DISK=/vms/bugdemo-debug.img +MEM=2G +CPUS=2 + +# The null-modem pair. XA is the guest side; XB is what the host +# reads from. +NMDM_GUEST=/dev/nmdm34A +NMDM_HOST=/dev/nmdm34B + +bhyve \ + -c ${CPUS} \ + -m ${MEM} \ + -H -w \ + -s 0,hostbridge \ + -s 1,lpc \ + -s 2,virtio-blk,${DISK} \ + -s 3,virtio-net,tap0 \ + -l com1,${NMDM_GUEST} \ + -l bootrom,/usr/local/share/uefi-firmware/BHYVE_UEFI.fd \ + ${VMNAME} + +echo "Serial device on the host: ${NMDM_HOST}" +echo "Attach with: kgdb /boot/kernel/kernel" +echo "Then in kgdb: target remote ${NMDM_HOST}" diff --git a/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/gdb-stub-notes.md b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/gdb-stub-notes.md new file mode 100644 index 0000000..f6356a9 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/gdb-stub-notes.md @@ -0,0 +1,73 @@ +# Annotated Notes on the GDB Stub Workflow + +## The Moving Parts + +- **KDB**: the in-kernel debugger framework. It selects a + backend and invokes it. +- **DDB**: the local, in-kernel debugger backend. Uses the + system console directly. +- **GDB (stub)**: a remote backend. Speaks the GDB remote + serial protocol over a serial line. +- **kgdb**: the host-side debugger. On a dump, it reads + `/var/crash/vmcore.last`. On a live remote session, it + connects to the stub. + +## Key Sysctls + +- `debug.kdb.supported_backends` - read-only list of backends + compiled in. +- `debug.kdb.current_backend` - writable; selects which backend + handles the next debugger entry. +- `debug.kdb.enter` - write `1` to force entry. +- `debug.kdb.panic_str` - triggers a test panic (when the + kernel has `INVARIANTS`). + +## Serial Transport + +The GDB stub requires a serial line the host can open. Options: + +- bhyve: `-l com1,stdio` or `-l com1,/dev/nmdmXA` with + `/dev/nmdmXB` on the host. +- QEMU: `-serial stdio`, `-serial pty`, or + `-serial unix:/tmp/serial.sock,server,nowait`. +- Real hardware: a dedicated serial port. + +## Attach Sequence + +1. VM enters KDB via `debug.kdb.enter=1` or panic. +2. KDB switches to the GDB backend (if selected). +3. Stub waits for the `$` GDB packet. +4. Host `kgdb` opens the serial device, sends the handshake. +5. Stub responds with register values; `kgdb` takes control. + +## Detach Sequence + +1. In `kgdb`: `detach`, then `quit`. +2. Stub sees the detach, returns control to the kernel. +3. Kernel resumes at the instruction after the entry point. + +A hard close (killing `kgdb` without `detach`) leaves the stub +expecting more packets. The kernel stays blocked. Usually only +a reboot recovers. + +## When to Use the Stub vs. DDB + +| Situation | Prefer | +|-----------------------------------:|:-------| +| Quick look on a local console | DDB | +| Deep debugging with source-level view | GDB stub | +| No serial port, dev box only | DDB | +| Intermittent bug, need live inspection | GDB stub | +| Post-mortem only | kgdb on vmcore | +| Watchpoints on specific addresses | GDB stub | + +## When the Stub Is the Wrong Tool + +- Production servers: halts all work. +- Time-sensitive code under test: the halt itself is an + observation effect. +- Hypervisor-managed migrations: a long halt can look like a + dead node and be fenced. +- SMP hangs: only the CPU that entered the debugger is + stopped; other CPUs may still be running, which can confuse + the picture. diff --git a/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/kgdb-commands.txt b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/kgdb-commands.txt new file mode 100644 index 0000000..c6800f6 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/kgdb-commands.txt @@ -0,0 +1,42 @@ +kgdb remote-session command reference +===================================== + +Connect / disconnect +-------------------- +target remote /dev/ttyXX attach to a running kernel's GDB stub +detach let the kernel resume +quit exit kgdb + +Inspect state +------------- +bt backtrace of the current thread +info threads list all kernel threads +thread N switch to thread N +frame N switch to frame N in the current thread +up / down move up or down one frame +print expr evaluate expr in the current frame +print *sc dereference a struct pointer named sc +print /x expr print in hex +list show source at the current frame + +Breakpoints and watchpoints +--------------------------- +break function break on entry to function +break file.c:42 break at file.c line 42 +watch expr break when expr changes value +rwatch expr break when expr is read +info breakpoints list all breakpoints +delete N delete breakpoint number N +continue resume execution + +Stepping +-------- +next step one source line, skipping calls +step step one source line, into calls +nexti / stepi step one machine instruction +finish run to the end of the current function + +Modules +------- +add-kld /path/to/module.ko load a module's symbols +info sharedlibrary list modules known to kgdb diff --git a/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/qemu-launch.sh.sample b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/qemu-launch.sh.sample new file mode 100644 index 0000000..c3097b5 --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/lab06-remote-gdb/qemu-launch.sh.sample @@ -0,0 +1,26 @@ +#!/bin/sh +# +# qemu-launch.sh.sample - sample QEMU launch script for Chapter 34 +# Lab 6 (remote GDB stub debugging). +# +# The key flag is -serial pty, which makes QEMU allocate a +# pseudo-terminal on the host and print its path on startup. Open +# that path from kgdb with "target remote ". +# +# This is a sample. Adjust for your environment. + +VMNAME=bugdemo-debug +DISK=/vms/bugdemo-debug.qcow2 +MEM=2G +CPUS=2 + +qemu-system-x86_64 \ + -name ${VMNAME} \ + -m ${MEM} \ + -smp ${CPUS} \ + -enable-kvm \ + -drive file=${DISK},if=virtio \ + -netdev user,id=net0 \ + -device virtio-net-pci,netdev=net0 \ + -serial pty \ + -display none diff --git a/examples/part-07/ch34-advanced-debugging/shared/build-notes.md b/examples/part-07/ch34-advanced-debugging/shared/build-notes.md new file mode 100644 index 0000000..73a218f --- /dev/null +++ b/examples/part-07/ch34-advanced-debugging/shared/build-notes.md @@ -0,0 +1,137 @@ +# Shared Build Notes + +These notes apply to every lab in this chapter. + +## Prerequisites + +Each lab assumes: + +- FreeBSD 14.3 or later. +- `/usr/src/` is populated (clone from git, or use + `pkg install src-quarterly`, or extract the release source tarball). +- Standard build tools available (`make(1)`, `cc(1)`). These are in + the base system on FreeBSD. +- A dump device configured (use `dumpon -l` to check). +- For Lab 3, Lab 5, and some challenges: a kernel built from + `GENERIC-DEBUG` with appropriate options. + +## Building a Debug Kernel + +Several labs assume you are running a debug kernel. The minimum +configuration is `GENERIC-DEBUG`, which lives at +`/usr/src/sys/amd64/conf/GENERIC-DEBUG` (or the equivalent path for +your architecture). + +``` +# cd /usr/src +# make buildkernel KERNCONF=GENERIC-DEBUG +# make installkernel KERNCONF=GENERIC-DEBUG +# shutdown -r now +``` + +For Lab 5, add `options DEBUG_MEMGUARD` to your kernel config before +building. + +## Building a Kernel Module + +The labs use the standard FreeBSD kernel module build system. + +``` +$ make clean +$ make +``` + +This produces `bugdemo.ko` in the current directory. + +## Loading and Unloading + +``` +$ sudo kldload ./bugdemo.ko # load +$ sudo kldunload bugdemo # unload (no .ko suffix on unload) +$ kldstat | grep bugdemo # verify +``` + +Always unload a test module before rebuilding. A stale module in the +kernel confuses the next build. + +## Running the Test Program + +Each lab includes a small user-space program, `bugdemo_test`, that +exercises the driver. Build and run: + +``` +$ make test +$ ./bugdemo_test +``` + +The available subcommands vary by lab and are documented in each +lab's README. + +## Configuring Dumps + +Before running a lab that deliberately panics, confirm a dump device +is configured: + +``` +# dumpon -l +``` + +If nothing is listed, configure your swap partition: + +``` +# dumpon /dev/ada0p3 +``` + +Persist in `/etc/rc.conf`: + +``` +dumpdev="/dev/ada0p3" +savecore_enable="YES" +``` + +## Reading a Dump + +After a panic and reboot, dumps appear in `/var/crash/`: + +``` +# ls -l /var/crash/ +# cat /var/crash/info.0 +# kgdb /boot/kernel/kernel /var/crash/vmcore.0 +``` + +## Cleaning Up + +Always unload test modules when you are finished: + +``` +$ sudo kldunload bugdemo +``` + +If a deliberate panic has rebooted your VM, the module is of course +gone. Kernel dumps remain in `/var/crash/` until you remove them. + +## Enabling INVARIANTS for a Single Module + +If you are running a release kernel but want to test a module built +with `INVARIANTS`, make sure the kernel has `INVARIANT_SUPPORT` at +minimum, then build the module with: + +``` +$ CFLAGS="-DINVARIANTS -DINVARIANT_SUPPORT -DWITNESS" make +``` + +The module will use INVARIANTS-mode macros while the kernel itself +stays in release mode. This is a reasonable compromise for testing +assertions without a full debug kernel rebuild. + +## Enabling DTrace on a Module + +To let DTrace see structure fields by name in your module, build with +CTF information: + +``` +$ WITH_CTF=1 make +``` + +This adds CTF data to `bugdemo.ko`, which DTrace uses to decode +structures. diff --git a/examples/part-07/ch35-async-io/lab01-sync-baseline/Makefile b/examples/part-07/ch35-async-io/lab01-sync-baseline/Makefile new file mode 100644 index 0000000..9652c79 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab01-sync-baseline/Makefile @@ -0,0 +1,16 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +test: evdemo_test + +evdemo_test: evdemo_test.c evdemo.h + cc -o evdemo_test evdemo_test.c + +testclean: + rm -f evdemo_test + +CLEANFILES+= evdemo_test + +.include diff --git a/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.c b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.c new file mode 100644 index 0000000..412a1a9 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.c @@ -0,0 +1,275 @@ +/* + * evdemo.c - Lab 1: synchronous baseline for the evdemo driver. + * + * This first version supports: + * - open(), close(), and blocking read() on /dev/evdemo. + * - An internal ring-buffer event queue. + * - A callout that posts a synthetic "tick" event once per second. + * - A sysctl (dev.evdemo.trigger) that posts a synthetic event on + * demand. + * + * No asynchronous I/O mechanisms yet: no poll(), no kqueue(), no + * SIGIO. Reads block in a condition variable until an event is + * available. Later labs layer the asynchronous mechanisms on top of + * this baseline. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + cv_broadcast(&sc->sc_cv); + mtx_unlock(&sc->sc_mtx); +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab01-sync-baseline)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + mtx_unlock(&sc->sc_mtx); + + callout_drain(&sc->sc_callout); + destroy_dev(sc->sc_dev); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 10); diff --git a/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.h b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.h new file mode 100644 index 0000000..5eaf5da --- /dev/null +++ b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo.h @@ -0,0 +1,31 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + * + * The evdemo pseudo-device exposes a queue of synthetic events. This + * header defines the event record that userland reads from the + * /dev/evdemo device node. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +/* + * A single event record. The layout mirrors the evdev(4) event + * convention: a timestamp plus a (type, code, value) triple. + */ +struct evdemo_event { + struct timespec ev_time; /* kernel time at event */ + uint32_t ev_type; /* event type */ + uint32_t ev_code; /* event code */ + int64_t ev_value; /* event value */ +}; + +/* Event types. Extend as needed. */ +#define EVDEMO_EV_TYPE_TICK 1 /* periodic tick from callout */ +#define EVDEMO_EV_TYPE_TRIGGER 2 /* synthetic trigger from sysctl */ +#define EVDEMO_EV_TYPE_BURST 3 /* event from a burst */ + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo_test.c b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo_test.c new file mode 100644 index 0000000..050a303 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab01-sync-baseline/evdemo_test.c @@ -0,0 +1,69 @@ +/* + * evdemo_test.c - Lab 1 companion user-space program. + * + * Opens /dev/evdemo and calls read() in a loop. Each read blocks + * until the driver posts an event. The program prints each event + * and exits after receiving five events, or on Ctrl+C. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct evdemo_event ev; + ssize_t n; + int fd; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 5; + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY); + if (fd < 0) + err(1, "open /dev/evdemo"); + + printf("evdemo_test: reading up to %d events (Ctrl+C to stop)\n", + limit); + + while (!stop && count < limit) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (stop) + break; + err(1, "read"); + } + if (n == 0) { + printf("evdemo_test: end of file\n"); + break; + } + if (n != sizeof(ev)) { + warnx("short read: %zd bytes", n); + continue; + } + printf("event: time=%jd.%09ld type=%u code=%u value=%lld\n", + (intmax_t)ev.ev_time.tv_sec, ev.ev_time.tv_nsec, + ev.ev_type, ev.ev_code, (long long)ev.ev_value); + count++; + } + + close(fd); + printf("evdemo_test: read %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab02-poll/Makefile b/examples/part-07/ch35-async-io/lab02-poll/Makefile new file mode 100644 index 0000000..f0991ae --- /dev/null +++ b/examples/part-07/ch35-async-io/lab02-poll/Makefile @@ -0,0 +1,16 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +test: evdemo_test_poll + +evdemo_test_poll: evdemo_test_poll.c evdemo.h + cc -o evdemo_test_poll evdemo_test_poll.c + +testclean: + rm -f evdemo_test_poll + +CLEANFILES+= evdemo_test_poll + +.include diff --git a/examples/part-07/ch35-async-io/lab02-poll/evdemo.c b/examples/part-07/ch35-async-io/lab02-poll/evdemo.c new file mode 100644 index 0000000..1a8da6f --- /dev/null +++ b/examples/part-07/ch35-async-io/lab02-poll/evdemo.c @@ -0,0 +1,308 @@ +/* + * evdemo.c - Lab 2: adds poll() support to the evdemo driver. + * + * Changes from Lab 1: + * - Adds struct selinfo sc_rsel to the softc. + * - Initializes the selinfo's knlist in attach (cheap, and makes + * it compatible with the kqueue support added in Lab 3). + * - Adds d_poll callback that registers the caller on the + * selinfo if the queue is empty, reports POLLIN if non-empty. + * - Calls selwakeup() in the producer path after the lock is + * dropped. + * - Adds seldrain() and knlist_destroy() to the detach path. + * - Tracks a selwakeup counter for observability. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + struct selinfo sc_rsel; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + u_int sc_selwakeups; + + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; +static d_poll_t evdemo_poll; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_poll = evdemo_poll, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +evdemo_poll(struct cdev *dev, int events, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int revents = 0; + + mtx_lock(&sc->sc_mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (!evdemo_queue_empty(sc)) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->sc_rsel); + } + if (events & (POLLOUT | POLLWRNORM)) + revents |= events & (POLLOUT | POLLWRNORM); + mtx_unlock(&sc->sc_mtx); + + return (revents); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + cv_broadcast(&sc->sc_cv); + sc->sc_selwakeups++; + mtx_unlock(&sc->sc_mtx); + + selwakeup(&sc->sc_rsel); +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + knlist_init_mtx(&sc->sc_rsel.si_note, &sc->sc_mtx); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab02-poll)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + mtx_unlock(&sc->sc_mtx); + selwakeup(&sc->sc_rsel); + + callout_drain(&sc->sc_callout); + destroy_dev(sc->sc_dev); + + seldrain(&sc->sc_rsel); + knlist_destroy(&sc->sc_rsel.si_note); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 20); diff --git a/examples/part-07/ch35-async-io/lab02-poll/evdemo.h b/examples/part-07/ch35-async-io/lab02-poll/evdemo.h new file mode 100644 index 0000000..2630917 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab02-poll/evdemo.h @@ -0,0 +1,26 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + * + * The evdemo pseudo-device exposes a queue of synthetic events. This + * header defines the event record that userland reads from the + * /dev/evdemo device node. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +struct evdemo_event { + struct timespec ev_time; + uint32_t ev_type; + uint32_t ev_code; + int64_t ev_value; +}; + +#define EVDEMO_EV_TYPE_TICK 1 +#define EVDEMO_EV_TYPE_TRIGGER 2 +#define EVDEMO_EV_TYPE_BURST 3 + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab02-poll/evdemo_test_poll.c b/examples/part-07/ch35-async-io/lab02-poll/evdemo_test_poll.c new file mode 100644 index 0000000..9a451b6 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab02-poll/evdemo_test_poll.c @@ -0,0 +1,99 @@ +/* + * evdemo_test_poll.c - Lab 2 companion user-space program. + * + * Opens /dev/evdemo and calls poll() with a timeout. When poll() + * reports POLLIN, reads one event and prints it. Loops until it has + * seen a fixed number of events or until the user presses Ctrl+C. + * + * This is the poll-based analogue of Lab 1's blocking read loop. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct pollfd pfd; + struct evdemo_event ev; + ssize_t n; + int fd; + int ret; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 5; + int timeout_ms = 5000; + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + printf("evdemo_test_poll: waiting for %d events (timeout %d ms)\n", + limit, timeout_ms); + + while (!stop && count < limit) { + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + + ret = poll(&pfd, 1, timeout_ms); + if (ret < 0) { + if (stop || errno == EINTR) + break; + err(1, "poll"); + } + if (ret == 0) { + printf("evdemo_test_poll: poll timeout\n"); + continue; + } + if (pfd.revents & POLLIN) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + err(1, "read"); + } + if (n == 0) { + printf("evdemo_test_poll: end of file\n"); + break; + } + if (n != sizeof(ev)) { + warnx("short read: %zd", n); + continue; + } + printf("event: time=%jd.%09ld type=%u code=%u " + "value=%lld\n", + (intmax_t)ev.ev_time.tv_sec, + ev.ev_time.tv_nsec, + ev.ev_type, ev.ev_code, + (long long)ev.ev_value); + count++; + } + if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) { + warnx("poll flagged error/hangup: 0x%x", pfd.revents); + break; + } + } + + close(fd); + printf("evdemo_test_poll: read %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab03-kqueue/Makefile b/examples/part-07/ch35-async-io/lab03-kqueue/Makefile new file mode 100644 index 0000000..2649f28 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab03-kqueue/Makefile @@ -0,0 +1,16 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +test: evdemo_test_kqueue + +evdemo_test_kqueue: evdemo_test_kqueue.c evdemo.h + cc -o evdemo_test_kqueue evdemo_test_kqueue.c + +testclean: + rm -f evdemo_test_kqueue + +CLEANFILES+= evdemo_test_kqueue + +.include diff --git a/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.c b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.c new file mode 100644 index 0000000..03f6751 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.c @@ -0,0 +1,358 @@ +/* + * evdemo.c - Lab 3: adds kqueue() support to the evdemo driver. + * + * Changes from Lab 2: + * - Adds a filterops structure for EVFILT_READ. + * - Adds d_kqfilter callback that attaches the caller's knote to + * sc->sc_rsel.si_note. + * - Adds KNOTE_LOCKED(&sc->sc_rsel.si_note, 0) in the producer + * path, inside the softc mutex. + * - Adds knlist_clear() to the detach path before seldrain(). + * - Reports EV_EOF to kqueue waiters during detach. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + struct selinfo sc_rsel; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; +static d_poll_t evdemo_poll; +static d_kqfilter_t evdemo_kqfilter; + +static int evdemo_kqread(struct knote *kn, long hint); +static void evdemo_kqdetach(struct knote *kn); + +static const struct filterops evdemo_read_filterops = { + .f_isfd = 1, + .f_attach = NULL, + .f_detach = evdemo_kqdetach, + .f_event = evdemo_kqread, +}; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_poll = evdemo_poll, + .d_kqfilter = evdemo_kqfilter, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +evdemo_poll(struct cdev *dev, int events, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int revents = 0; + + mtx_lock(&sc->sc_mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (!evdemo_queue_empty(sc)) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->sc_rsel); + } + if (events & (POLLOUT | POLLWRNORM)) + revents |= events & (POLLOUT | POLLWRNORM); + mtx_unlock(&sc->sc_mtx); + + return (revents); +} + +static int +evdemo_kqfilter(struct cdev *dev, struct knote *kn) +{ + struct evdemo_softc *sc = dev->si_drv1; + + switch (kn->kn_filter) { + case EVFILT_READ: + kn->kn_fop = &evdemo_read_filterops; + kn->kn_hook = sc; + knlist_add(&sc->sc_rsel.si_note, kn, 0); + return (0); + default: + return (EINVAL); + } +} + +static int +evdemo_kqread(struct knote *kn, long hint __unused) +{ + struct evdemo_softc *sc = kn->kn_hook; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + + kn->kn_data = sc->sc_nevents; + if (sc->sc_detaching) { + kn->kn_flags |= EV_EOF; + return (1); + } + return (!evdemo_queue_empty(sc)); +} + +static void +evdemo_kqdetach(struct knote *kn) +{ + struct evdemo_softc *sc = kn->kn_hook; + + knlist_remove(&sc->sc_rsel.si_note, kn, 0); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + + selwakeup(&sc->sc_rsel); +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + knlist_init_mtx(&sc->sc_rsel.si_note, &sc->sc_mtx); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab03-kqueue)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + selwakeup(&sc->sc_rsel); + + callout_drain(&sc->sc_callout); + destroy_dev(sc->sc_dev); + + knlist_clear(&sc->sc_rsel.si_note, 0); + seldrain(&sc->sc_rsel); + knlist_destroy(&sc->sc_rsel.si_note); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 23); diff --git a/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.h b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.h new file mode 100644 index 0000000..bc31052 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo.h @@ -0,0 +1,22 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +struct evdemo_event { + struct timespec ev_time; + uint32_t ev_type; + uint32_t ev_code; + int64_t ev_value; +}; + +#define EVDEMO_EV_TYPE_TICK 1 +#define EVDEMO_EV_TYPE_TRIGGER 2 +#define EVDEMO_EV_TYPE_BURST 3 + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab03-kqueue/evdemo_test_kqueue.c b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo_test_kqueue.c new file mode 100644 index 0000000..f2b1826 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab03-kqueue/evdemo_test_kqueue.c @@ -0,0 +1,111 @@ +/* + * evdemo_test_kqueue.c - Lab 3 companion user-space program. + * + * Opens /dev/evdemo, creates a kqueue, registers an EVFILT_READ + * filter on the device descriptor, and loops calling kevent(2) to + * receive events. Prints each event and exits after seeing a fixed + * number of them or on Ctrl+C. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct kevent ev_set, ev_got; + struct evdemo_event event; + struct timespec timeout; + ssize_t n; + int fd, kq, ret; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 5; + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + kq = kqueue(); + if (kq < 0) + err(1, "kqueue"); + + EV_SET(&ev_set, fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, NULL); + if (kevent(kq, &ev_set, 1, NULL, 0, NULL) < 0) + err(1, "kevent add"); + + printf("evdemo_test_kqueue: waiting for %d events\n", limit); + + while (!stop && count < limit) { + timeout.tv_sec = 5; + timeout.tv_nsec = 0; + ret = kevent(kq, NULL, 0, &ev_got, 1, &timeout); + if (ret < 0) { + if (stop || errno == EINTR) + break; + err(1, "kevent wait"); + } + if (ret == 0) { + printf("evdemo_test_kqueue: kevent timeout\n"); + continue; + } + + if (ev_got.flags & EV_EOF) { + printf("evdemo_test_kqueue: device closed (EV_EOF)\n"); + break; + } + + printf("kqueue: %lld events queued in driver\n", + (long long)ev_got.data); + + while (count < limit) { + n = read(fd, &event, sizeof(event)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + break; + err(1, "read"); + } + if (n == 0) { + printf("evdemo_test_kqueue: end of file\n"); + goto done; + } + if (n != sizeof(event)) { + warnx("short read: %zd", n); + break; + } + printf("event: time=%jd.%09ld type=%u code=%u " + "value=%lld\n", + (intmax_t)event.ev_time.tv_sec, + event.ev_time.tv_nsec, + event.ev_type, event.ev_code, + (long long)event.ev_value); + count++; + } + } + +done: + close(kq); + close(fd); + printf("evdemo_test_kqueue: read %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab04-sigio/Makefile b/examples/part-07/ch35-async-io/lab04-sigio/Makefile new file mode 100644 index 0000000..17f800f --- /dev/null +++ b/examples/part-07/ch35-async-io/lab04-sigio/Makefile @@ -0,0 +1,16 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +test: evdemo_test_sigio + +evdemo_test_sigio: evdemo_test_sigio.c evdemo.h + cc -o evdemo_test_sigio evdemo_test_sigio.c + +testclean: + rm -f evdemo_test_sigio + +CLEANFILES+= evdemo_test_sigio + +.include diff --git a/examples/part-07/ch35-async-io/lab04-sigio/evdemo.c b/examples/part-07/ch35-async-io/lab04-sigio/evdemo.c new file mode 100644 index 0000000..6d8e62d --- /dev/null +++ b/examples/part-07/ch35-async-io/lab04-sigio/evdemo.c @@ -0,0 +1,404 @@ +/* + * evdemo.c - Lab 4: adds SIGIO support to the evdemo driver. + * + * Changes from Lab 3: + * - Adds sc_async (bool) and sc_sigio (struct sigio *) to the softc. + * - Adds d_ioctl callback with FIOASYNC, FIOSETOWN, FIOGETOWN. + * - Adds pgsigio() delivery in the producer path, outside the + * softc mutex. + * - Adds funsetown() to the detach path. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + struct selinfo sc_rsel; + struct sigio *sc_sigio; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + + bool sc_async; + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; +static d_ioctl_t evdemo_ioctl; +static d_poll_t evdemo_poll; +static d_kqfilter_t evdemo_kqfilter; + +static int evdemo_kqread(struct knote *kn, long hint); +static void evdemo_kqdetach(struct knote *kn); + +static const struct filterops evdemo_read_filterops = { + .f_isfd = 1, + .f_attach = NULL, + .f_detach = evdemo_kqdetach, + .f_event = evdemo_kqread, +}; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_ioctl = evdemo_ioctl, + .d_poll = evdemo_poll, + .d_kqfilter = evdemo_kqfilter, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + + mtx_lock(&sc->sc_mtx); + sc->sc_async = false; + mtx_unlock(&sc->sc_mtx); + funsetown(&sc->sc_sigio); + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +evdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, + int fflag, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int error = 0; + + switch (cmd) { + case FIOASYNC: + mtx_lock(&sc->sc_mtx); + sc->sc_async = (*(int *)data != 0); + mtx_unlock(&sc->sc_mtx); + break; + case FIOSETOWN: + error = fsetown(*(int *)data, &sc->sc_sigio); + break; + case FIOGETOWN: + *(int *)data = fgetown(&sc->sc_sigio); + break; + case FIONBIO: + /* Handled by the generic layer; accept and ignore. */ + break; + default: + error = ENOTTY; + break; + } + return (error); +} + +static int +evdemo_poll(struct cdev *dev, int events, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int revents = 0; + + mtx_lock(&sc->sc_mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (!evdemo_queue_empty(sc)) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->sc_rsel); + } + if (events & (POLLOUT | POLLWRNORM)) + revents |= events & (POLLOUT | POLLWRNORM); + mtx_unlock(&sc->sc_mtx); + + return (revents); +} + +static int +evdemo_kqfilter(struct cdev *dev, struct knote *kn) +{ + struct evdemo_softc *sc = dev->si_drv1; + + switch (kn->kn_filter) { + case EVFILT_READ: + kn->kn_fop = &evdemo_read_filterops; + kn->kn_hook = sc; + knlist_add(&sc->sc_rsel.si_note, kn, 0); + return (0); + default: + return (EINVAL); + } +} + +static int +evdemo_kqread(struct knote *kn, long hint __unused) +{ + struct evdemo_softc *sc = kn->kn_hook; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + + kn->kn_data = sc->sc_nevents; + if (sc->sc_detaching) { + kn->kn_flags |= EV_EOF; + return (1); + } + return (!evdemo_queue_empty(sc)); +} + +static void +evdemo_kqdetach(struct knote *kn) +{ + struct evdemo_softc *sc = kn->kn_hook; + + knlist_remove(&sc->sc_rsel.si_note, kn, 0); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + bool async; + + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + async = sc->sc_async; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + + selwakeup(&sc->sc_rsel); + if (async) + pgsigio(&sc->sc_sigio, SIGIO, 0); +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + knlist_init_mtx(&sc->sc_rsel.si_note, &sc->sc_mtx); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab04-sigio)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + selwakeup(&sc->sc_rsel); + + callout_drain(&sc->sc_callout); + destroy_dev(sc->sc_dev); + + knlist_clear(&sc->sc_rsel.si_note, 0); + seldrain(&sc->sc_rsel); + knlist_destroy(&sc->sc_rsel.si_note); + funsetown(&sc->sc_sigio); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 24); diff --git a/examples/part-07/ch35-async-io/lab04-sigio/evdemo.h b/examples/part-07/ch35-async-io/lab04-sigio/evdemo.h new file mode 100644 index 0000000..bc31052 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab04-sigio/evdemo.h @@ -0,0 +1,22 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +struct evdemo_event { + struct timespec ev_time; + uint32_t ev_type; + uint32_t ev_code; + int64_t ev_value; +}; + +#define EVDEMO_EV_TYPE_TICK 1 +#define EVDEMO_EV_TYPE_TRIGGER 2 +#define EVDEMO_EV_TYPE_BURST 3 + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab04-sigio/evdemo_test_sigio.c b/examples/part-07/ch35-async-io/lab04-sigio/evdemo_test_sigio.c new file mode 100644 index 0000000..e668afa --- /dev/null +++ b/examples/part-07/ch35-async-io/lab04-sigio/evdemo_test_sigio.c @@ -0,0 +1,115 @@ +/* + * evdemo_test_sigio.c - Lab 4 companion user-space program. + * + * Opens /dev/evdemo, declares the process as the signal owner via + * FIOSETOWN, enables SIGIO delivery with FIOASYNC, and then loops + * in pause() waiting for SIGIO. The SIGIO handler sets a flag; the + * main loop reads events when the flag is set. + * + * This is the classical pattern for SIGIO-driven userland programs. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t pending; +static volatile sig_atomic_t stop; + +static void +on_sigio(int sig __attribute__((unused))) +{ + pending = 1; +} + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct evdemo_event ev; + struct sigaction sa; + ssize_t n; + pid_t pid; + int fd; + int flag; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 5; + + sa.sa_handler = on_sigio; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + if (sigaction(SIGIO, &sa, NULL) < 0) + err(1, "sigaction SIGIO"); + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + pid = getpid(); + if (ioctl(fd, FIOSETOWN, &pid) < 0) + err(1, "FIOSETOWN"); + + flag = 1; + if (ioctl(fd, FIOASYNC, &flag) < 0) + err(1, "FIOASYNC"); + + printf("evdemo_test_sigio: waiting for %d events (pid=%d)\n", + limit, (int)pid); + + while (!stop && count < limit) { + if (!pending) { + pause(); + continue; + } + pending = 0; + + for (;;) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + break; + err(1, "read"); + } + if (n == 0) { + printf("evdemo_test_sigio: end of file\n"); + goto done; + } + if (n != sizeof(ev)) { + warnx("short read: %zd", n); + break; + } + printf("event: time=%jd.%09ld type=%u code=%u " + "value=%lld\n", + (intmax_t)ev.ev_time.tv_sec, + ev.ev_time.tv_nsec, + ev.ev_type, ev.ev_code, + (long long)ev.ev_value); + count++; + if (count >= limit) + break; + } + } + +done: + flag = 0; + (void)ioctl(fd, FIOASYNC, &flag); + close(fd); + printf("evdemo_test_sigio: read %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab05-event-queue/Makefile b/examples/part-07/ch35-async-io/lab05-event-queue/Makefile new file mode 100644 index 0000000..a0b560b --- /dev/null +++ b/examples/part-07/ch35-async-io/lab05-event-queue/Makefile @@ -0,0 +1,16 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +test: evdemo_watch + +evdemo_watch: evdemo_watch.c evdemo.h + cc -o evdemo_watch evdemo_watch.c + +testclean: + rm -f evdemo_watch + +CLEANFILES+= evdemo_watch + +.include diff --git a/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.c b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.c new file mode 100644 index 0000000..e6d3df3 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.c @@ -0,0 +1,495 @@ +/* + * evdemo.c - Lab 5: polished event queue with sysctl observability. + * + * Changes from Lab 4: + * - Adds a dev.evdemo.stats sysctl subtree with qlen, posted, + * consumed, dropped, selwakeups, knotes_delivered, sigio_sent. + * - Adds dev.evdemo.burst that posts a batch of events. + * - Leaves the three async mechanisms unchanged but exposes their + * counters. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + struct selinfo sc_rsel; + struct sigio *sc_sigio; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + u_int sc_selwakeups; + u_int sc_knotes_delivered; + u_int sc_sigio_sent; + + bool sc_async; + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; +static d_ioctl_t evdemo_ioctl; +static d_poll_t evdemo_poll; +static d_kqfilter_t evdemo_kqfilter; + +static int evdemo_kqread(struct knote *kn, long hint); +static void evdemo_kqdetach(struct knote *kn); + +static const struct filterops evdemo_read_filterops = { + .f_isfd = 1, + .f_attach = NULL, + .f_detach = evdemo_kqdetach, + .f_event = evdemo_kqread, +}; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_ioctl = evdemo_ioctl, + .d_poll = evdemo_poll, + .d_kqfilter = evdemo_kqfilter, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); +static int evdemo_burst_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +static SYSCTL_NODE(_dev_evdemo, OID_AUTO, stats, CTLFLAG_RW, 0, + "evdemo runtime statistics"); + +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, burst, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_burst_sysctl, "I", "Post a batch of events"); + +static u_int evdemo_qsize = EVDEMO_QUEUE_SIZE; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, qsize, CTLFLAG_RD, + &evdemo_qsize, 0, "queue capacity"); + +static u_int evdemo_qlen; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, qlen, CTLFLAG_RD, + &evdemo_qlen, 0, "current queue length"); + +static u_int evdemo_dropped; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, dropped, CTLFLAG_RD, + &evdemo_dropped, 0, "events dropped due to overflow"); + +static u_int evdemo_posted; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, posted, CTLFLAG_RD, + &evdemo_posted, 0, "events posted since attach"); + +static u_int evdemo_consumed; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, consumed, CTLFLAG_RD, + &evdemo_consumed, 0, "events consumed by read(2)"); + +static u_int evdemo_selwakeups; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, selwakeups, CTLFLAG_RD, + &evdemo_selwakeups, 0, "selwakeup calls"); + +static u_int evdemo_knotes_delivered; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, knotes_delivered, CTLFLAG_RD, + &evdemo_knotes_delivered, 0, "knote deliveries"); + +static u_int evdemo_sigio_sent; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, sigio_sent, CTLFLAG_RD, + &evdemo_sigio_sent, 0, "SIGIO signals sent"); + +static void +evdemo_publish_stats(struct evdemo_softc *sc) +{ + evdemo_qlen = sc->sc_nevents; + evdemo_dropped = sc->sc_dropped; + evdemo_posted = sc->sc_posted; + evdemo_consumed = sc->sc_consumed; + evdemo_selwakeups = sc->sc_selwakeups; + evdemo_knotes_delivered = sc->sc_knotes_delivered; + evdemo_sigio_sent = sc->sc_sigio_sent; +} + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + + mtx_lock(&sc->sc_mtx); + sc->sc_async = false; + mtx_unlock(&sc->sc_mtx); + funsetown(&sc->sc_sigio); + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +evdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, + int fflag, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int error = 0; + + switch (cmd) { + case FIOASYNC: + mtx_lock(&sc->sc_mtx); + sc->sc_async = (*(int *)data != 0); + mtx_unlock(&sc->sc_mtx); + break; + case FIOSETOWN: + error = fsetown(*(int *)data, &sc->sc_sigio); + break; + case FIOGETOWN: + *(int *)data = fgetown(&sc->sc_sigio); + break; + case FIONBIO: + break; + default: + error = ENOTTY; + break; + } + return (error); +} + +static int +evdemo_poll(struct cdev *dev, int events, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int revents = 0; + + mtx_lock(&sc->sc_mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (!evdemo_queue_empty(sc)) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->sc_rsel); + } + if (events & (POLLOUT | POLLWRNORM)) + revents |= events & (POLLOUT | POLLWRNORM); + mtx_unlock(&sc->sc_mtx); + + return (revents); +} + +static int +evdemo_kqfilter(struct cdev *dev, struct knote *kn) +{ + struct evdemo_softc *sc = dev->si_drv1; + + switch (kn->kn_filter) { + case EVFILT_READ: + kn->kn_fop = &evdemo_read_filterops; + kn->kn_hook = sc; + knlist_add(&sc->sc_rsel.si_note, kn, 0); + return (0); + default: + return (EINVAL); + } +} + +static int +evdemo_kqread(struct knote *kn, long hint __unused) +{ + struct evdemo_softc *sc = kn->kn_hook; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + + kn->kn_data = sc->sc_nevents; + if (sc->sc_detaching) { + kn->kn_flags |= EV_EOF; + return (1); + } + return (!evdemo_queue_empty(sc)); +} + +static void +evdemo_kqdetach(struct knote *kn) +{ + struct evdemo_softc *sc = kn->kn_hook; + + knlist_remove(&sc->sc_rsel.si_note, kn, 0); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + bool async; + + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + async = sc->sc_async; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + sc->sc_knotes_delivered++; + sc->sc_selwakeups++; + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + selwakeup(&sc->sc_rsel); + if (async) { + pgsigio(&sc->sc_sigio, SIGIO, 0); + mtx_lock(&sc->sc_mtx); + sc->sc_sigio_sent++; + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + } +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_burst_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int count = 0; + int error, i; + + error = sysctl_handle_int(oidp, &count, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + if (count < 1 || count > 10000) + return (EINVAL); + + for (i = 0; i < count; i++) { + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_BURST; + ev.ev_code = (uint32_t)i; + ev.ev_value = count; + evdemo_post_event(sc, &ev); + } + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + knlist_init_mtx(&sc->sc_rsel.si_note, &sc->sc_mtx); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab05-event-queue)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + selwakeup(&sc->sc_rsel); + + callout_drain(&sc->sc_callout); + destroy_dev(sc->sc_dev); + + knlist_clear(&sc->sc_rsel.si_note, 0); + seldrain(&sc->sc_rsel); + knlist_destroy(&sc->sc_rsel.si_note); + funsetown(&sc->sc_sigio); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + + evdemo_qlen = 0; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 24); diff --git a/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.h b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.h new file mode 100644 index 0000000..bc31052 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo.h @@ -0,0 +1,22 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +struct evdemo_event { + struct timespec ev_time; + uint32_t ev_type; + uint32_t ev_code; + int64_t ev_value; +}; + +#define EVDEMO_EV_TYPE_TICK 1 +#define EVDEMO_EV_TYPE_TRIGGER 2 +#define EVDEMO_EV_TYPE_BURST 3 + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab05-event-queue/evdemo_watch.c b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo_watch.c new file mode 100644 index 0000000..97a9bd6 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab05-event-queue/evdemo_watch.c @@ -0,0 +1,67 @@ +/* + * evdemo_watch.c - Lab 5 companion diagnostic tool. + * + * Polls the dev.evdemo.stats.* sysctl counters once per second and + * prints them in a compact table. Useful for watching the queue's + * behaviour while triggering events or bursts in another terminal. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +static u_int +get_uint(const char *name) +{ + u_int value = 0; + size_t len = sizeof(value); + + if (sysctlbyname(name, &value, &len, NULL, 0) < 0) + return (0); + return (value); +} + +int +main(int argc, char **argv) +{ + int interval = (argc > 1) ? atoi(argv[1]) : 1; + int i = 0; + + if (interval < 1) + interval = 1; + + signal(SIGINT, on_int); + + while (!stop) { + if ((i % 20) == 0) { + printf("%8s %8s %8s %8s %8s %8s %8s\n", + "qlen", "posted", "consumed", "dropped", + "selwake", "knotes", "sigio"); + } + printf("%8u %8u %8u %8u %8u %8u %8u\n", + get_uint("dev.evdemo.stats.qlen"), + get_uint("dev.evdemo.stats.posted"), + get_uint("dev.evdemo.stats.consumed"), + get_uint("dev.evdemo.stats.dropped"), + get_uint("dev.evdemo.stats.selwakeups"), + get_uint("dev.evdemo.stats.knotes_delivered"), + get_uint("dev.evdemo.stats.sigio_sent")); + fflush(stdout); + sleep((unsigned)interval); + i++; + } + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/Makefile b/examples/part-07/ch35-async-io/lab06-v25-async/Makefile new file mode 100644 index 0000000..49d2658 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/Makefile @@ -0,0 +1,28 @@ +KMOD= evdemo +SRCS= evdemo.c + +SYSDIR?= /usr/src/sys + +TEST_PROGS= evdemo_test_poll evdemo_test_kqueue evdemo_test_sigio \ + evdemo_test_combined + +test: ${TEST_PROGS} + +evdemo_test_poll: evdemo_test_poll.c evdemo.h + cc -o evdemo_test_poll evdemo_test_poll.c + +evdemo_test_kqueue: evdemo_test_kqueue.c evdemo.h + cc -o evdemo_test_kqueue evdemo_test_kqueue.c + +evdemo_test_sigio: evdemo_test_sigio.c evdemo.h + cc -o evdemo_test_sigio evdemo_test_sigio.c + +evdemo_test_combined: evdemo_test_combined.c evdemo.h + cc -o evdemo_test_combined evdemo_test_combined.c + +testclean: + rm -f ${TEST_PROGS} + +CLEANFILES+= ${TEST_PROGS} + +.include diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.c b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.c new file mode 100644 index 0000000..2c68200 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.c @@ -0,0 +1,494 @@ +/* + * evdemo.c - v2.5-async reference driver. + * + * This is the final combined driver: poll, kqueue, and SIGIO support + * all layered on a bounded event queue, with an audited detach path + * and sysctl-based observability. Future drivers that need + * asynchronous I/O can use this file as a template. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +#define EVDEMO_QUEUE_SIZE 64 + +MALLOC_DEFINE(M_EVDEMO, "evdemo", "evdemo driver softc"); + +struct evdemo_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct cv sc_cv; + struct callout sc_callout; + struct selinfo sc_rsel; + struct sigio *sc_sigio; + + struct evdemo_event sc_queue[EVDEMO_QUEUE_SIZE]; + u_int sc_qhead; + u_int sc_qtail; + u_int sc_nevents; + + u_int sc_dropped; + u_int sc_posted; + u_int sc_consumed; + u_int sc_selwakeups; + u_int sc_knotes_delivered; + u_int sc_sigio_sent; + + bool sc_async; + bool sc_detaching; +}; + +static struct evdemo_softc *evdemo_sc_global; + +static d_open_t evdemo_open; +static d_close_t evdemo_close; +static d_read_t evdemo_read; +static d_ioctl_t evdemo_ioctl; +static d_poll_t evdemo_poll; +static d_kqfilter_t evdemo_kqfilter; + +static int evdemo_kqread(struct knote *kn, long hint); +static void evdemo_kqdetach(struct knote *kn); + +static const struct filterops evdemo_read_filterops = { + .f_isfd = 1, + .f_attach = NULL, + .f_detach = evdemo_kqdetach, + .f_event = evdemo_kqread, +}; + +static struct cdevsw evdemo_cdevsw = { + .d_version = D_VERSION, + .d_open = evdemo_open, + .d_close = evdemo_close, + .d_read = evdemo_read, + .d_ioctl = evdemo_ioctl, + .d_poll = evdemo_poll, + .d_kqfilter = evdemo_kqfilter, + .d_name = "evdemo", +}; + +static void evdemo_callout(void *arg); +static void evdemo_post_event(struct evdemo_softc *sc, + struct evdemo_event *ev); +static int evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS); +static int evdemo_burst_sysctl(SYSCTL_HANDLER_ARGS); + +static SYSCTL_NODE(_dev, OID_AUTO, evdemo, CTLFLAG_RW, 0, + "evdemo driver"); +static SYSCTL_NODE(_dev_evdemo, OID_AUTO, stats, CTLFLAG_RW, 0, + "evdemo runtime statistics"); + +SYSCTL_PROC(_dev_evdemo, OID_AUTO, trigger, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_trigger_sysctl, "I", "Post a synthetic event"); +SYSCTL_PROC(_dev_evdemo, OID_AUTO, burst, + CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE, NULL, 0, + evdemo_burst_sysctl, "I", "Post a batch of events"); + +static u_int evdemo_qsize = EVDEMO_QUEUE_SIZE; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, qsize, CTLFLAG_RD, + &evdemo_qsize, 0, "queue capacity"); + +static u_int evdemo_qlen; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, qlen, CTLFLAG_RD, + &evdemo_qlen, 0, "current queue length"); + +static u_int evdemo_dropped; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, dropped, CTLFLAG_RD, + &evdemo_dropped, 0, "events dropped due to overflow"); + +static u_int evdemo_posted; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, posted, CTLFLAG_RD, + &evdemo_posted, 0, "events posted since attach"); + +static u_int evdemo_consumed; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, consumed, CTLFLAG_RD, + &evdemo_consumed, 0, "events consumed by read(2)"); + +static u_int evdemo_selwakeups; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, selwakeups, CTLFLAG_RD, + &evdemo_selwakeups, 0, "selwakeup calls"); + +static u_int evdemo_knotes_delivered; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, knotes_delivered, CTLFLAG_RD, + &evdemo_knotes_delivered, 0, "knote deliveries"); + +static u_int evdemo_sigio_sent; +SYSCTL_UINT(_dev_evdemo_stats, OID_AUTO, sigio_sent, CTLFLAG_RD, + &evdemo_sigio_sent, 0, "SIGIO signals sent"); + +static void +evdemo_publish_stats(struct evdemo_softc *sc) +{ + evdemo_qlen = sc->sc_nevents; + evdemo_dropped = sc->sc_dropped; + evdemo_posted = sc->sc_posted; + evdemo_consumed = sc->sc_consumed; + evdemo_selwakeups = sc->sc_selwakeups; + evdemo_knotes_delivered = sc->sc_knotes_delivered; + evdemo_sigio_sent = sc->sc_sigio_sent; +} + +static inline bool +evdemo_queue_empty(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == 0); +} + +static inline bool +evdemo_queue_full(const struct evdemo_softc *sc) +{ + return (sc->sc_nevents == EVDEMO_QUEUE_SIZE); +} + +static void +evdemo_enqueue(struct evdemo_softc *sc, const struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_full(sc)) { + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_dropped++; + } + sc->sc_queue[sc->sc_qtail] = *ev; + sc->sc_qtail = (sc->sc_qtail + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents++; + sc->sc_posted++; +} + +static int +evdemo_dequeue(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + if (evdemo_queue_empty(sc)) + return (-1); + *ev = sc->sc_queue[sc->sc_qhead]; + sc->sc_qhead = (sc->sc_qhead + 1) % EVDEMO_QUEUE_SIZE; + sc->sc_nevents--; + sc->sc_consumed++; + return (0); +} + +static int +evdemo_open(struct cdev *dev, int oflags, int devtype, struct thread *td) +{ + return (0); +} + +static int +evdemo_close(struct cdev *dev, int fflag, int devtype, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + + mtx_lock(&sc->sc_mtx); + sc->sc_async = false; + mtx_unlock(&sc->sc_mtx); + funsetown(&sc->sc_sigio); + return (0); +} + +static int +evdemo_read(struct cdev *dev, struct uio *uio, int flag) +{ + struct evdemo_softc *sc = dev->si_drv1; + struct evdemo_event ev; + ssize_t start_resid = uio->uio_resid; + int error = 0; + + while (uio->uio_resid >= (ssize_t)sizeof(ev)) { + mtx_lock(&sc->sc_mtx); + while (evdemo_queue_empty(sc) && !sc->sc_detaching) { + if (flag & O_NONBLOCK) { + mtx_unlock(&sc->sc_mtx); + if (uio->uio_resid == start_resid) + return (EAGAIN); + return (0); + } + error = cv_wait_sig(&sc->sc_cv, &sc->sc_mtx); + if (error != 0) { + mtx_unlock(&sc->sc_mtx); + return (error); + } + } + if (sc->sc_detaching) { + mtx_unlock(&sc->sc_mtx); + return (0); + } + evdemo_dequeue(sc, &ev); + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + error = uiomove(&ev, sizeof(ev), uio); + if (error != 0) + return (error); + } + return (0); +} + +static int +evdemo_ioctl(struct cdev *dev, u_long cmd, caddr_t data, + int fflag, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int error = 0; + + switch (cmd) { + case FIOASYNC: + mtx_lock(&sc->sc_mtx); + sc->sc_async = (*(int *)data != 0); + mtx_unlock(&sc->sc_mtx); + break; + case FIOSETOWN: + error = fsetown(*(int *)data, &sc->sc_sigio); + break; + case FIOGETOWN: + *(int *)data = fgetown(&sc->sc_sigio); + break; + case FIONBIO: + break; + default: + error = ENOTTY; + break; + } + return (error); +} + +static int +evdemo_poll(struct cdev *dev, int events, struct thread *td) +{ + struct evdemo_softc *sc = dev->si_drv1; + int revents = 0; + + mtx_lock(&sc->sc_mtx); + if (events & (POLLIN | POLLRDNORM)) { + if (!evdemo_queue_empty(sc)) + revents |= events & (POLLIN | POLLRDNORM); + else + selrecord(td, &sc->sc_rsel); + } + if (events & (POLLOUT | POLLWRNORM)) + revents |= events & (POLLOUT | POLLWRNORM); + if (sc->sc_detaching) + revents |= POLLHUP; + mtx_unlock(&sc->sc_mtx); + + return (revents); +} + +static int +evdemo_kqfilter(struct cdev *dev, struct knote *kn) +{ + struct evdemo_softc *sc = dev->si_drv1; + + switch (kn->kn_filter) { + case EVFILT_READ: + kn->kn_fop = &evdemo_read_filterops; + kn->kn_hook = sc; + knlist_add(&sc->sc_rsel.si_note, kn, 0); + return (0); + default: + return (EINVAL); + } +} + +static int +evdemo_kqread(struct knote *kn, long hint __unused) +{ + struct evdemo_softc *sc = kn->kn_hook; + + mtx_assert(&sc->sc_mtx, MA_OWNED); + + kn->kn_data = sc->sc_nevents; + if (sc->sc_detaching) { + kn->kn_flags |= EV_EOF; + return (1); + } + return (!evdemo_queue_empty(sc)); +} + +static void +evdemo_kqdetach(struct knote *kn) +{ + struct evdemo_softc *sc = kn->kn_hook; + + knlist_remove(&sc->sc_rsel.si_note, kn, 0); +} + +static void +evdemo_post_event(struct evdemo_softc *sc, struct evdemo_event *ev) +{ + bool async; + + mtx_lock(&sc->sc_mtx); + evdemo_enqueue(sc, ev); + async = sc->sc_async; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + sc->sc_knotes_delivered++; + sc->sc_selwakeups++; + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + selwakeup(&sc->sc_rsel); + if (async) { + pgsigio(&sc->sc_sigio, SIGIO, 0); + mtx_lock(&sc->sc_mtx); + sc->sc_sigio_sent++; + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + } +} + +static void +evdemo_callout(void *arg) +{ + struct evdemo_softc *sc = arg; + struct evdemo_event ev; + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TICK; + ev.ev_code = 0; + ev.ev_value = 0; + evdemo_post_event(sc, &ev); + + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); +} + +static int +evdemo_trigger_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int value = 0; + int error; + + error = sysctl_handle_int(oidp, &value, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_TRIGGER; + ev.ev_code = 0; + ev.ev_value = value; + evdemo_post_event(sc, &ev); + return (0); +} + +static int +evdemo_burst_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct evdemo_softc *sc = evdemo_sc_global; + struct evdemo_event ev; + int count = 0; + int error, i; + + error = sysctl_handle_int(oidp, &count, 0, req); + if (error != 0 || req->newptr == NULL || sc == NULL) + return (error); + + if (count < 1 || count > 10000) + return (EINVAL); + + for (i = 0; i < count; i++) { + nanotime(&ev.ev_time); + ev.ev_type = EVDEMO_EV_TYPE_BURST; + ev.ev_code = (uint32_t)i; + ev.ev_value = count; + evdemo_post_event(sc, &ev); + } + return (0); +} + +static int +evdemo_modevent(module_t mod, int event, void *arg) +{ + struct evdemo_softc *sc; + int error = 0; + + switch (event) { + case MOD_LOAD: + sc = malloc(sizeof(*sc), M_EVDEMO, M_WAITOK | M_ZERO); + mtx_init(&sc->sc_mtx, "evdemo", NULL, MTX_DEF); + cv_init(&sc->sc_cv, "evdemo"); + knlist_init_mtx(&sc->sc_rsel.si_note, &sc->sc_mtx); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + + sc->sc_dev = make_dev(&evdemo_cdevsw, 0, UID_ROOT, GID_WHEEL, + 0600, "evdemo"); + sc->sc_dev->si_drv1 = sc; + evdemo_sc_global = sc; + + mtx_lock(&sc->sc_mtx); + callout_reset(&sc->sc_callout, hz, evdemo_callout, sc); + evdemo_publish_stats(sc); + mtx_unlock(&sc->sc_mtx); + + printf("evdemo: loaded (lab06-v25-async)\n"); + break; + + case MOD_UNLOAD: + sc = evdemo_sc_global; + if (sc == NULL) + break; + + mtx_lock(&sc->sc_mtx); + sc->sc_detaching = true; + cv_broadcast(&sc->sc_cv); + KNOTE_LOCKED(&sc->sc_rsel.si_note, 0); + mtx_unlock(&sc->sc_mtx); + selwakeup(&sc->sc_rsel); + + callout_drain(&sc->sc_callout); + destroy_dev_drain(sc->sc_dev); + + knlist_clear(&sc->sc_rsel.si_note, 0); + seldrain(&sc->sc_rsel); + knlist_destroy(&sc->sc_rsel.si_note); + funsetown(&sc->sc_sigio); + + cv_destroy(&sc->sc_cv); + mtx_destroy(&sc->sc_mtx); + + free(sc, M_EVDEMO); + evdemo_sc_global = NULL; + evdemo_qlen = 0; + printf("evdemo: unloaded\n"); + break; + + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t evdemo_mod = { + "evdemo", + evdemo_modevent, + NULL +}; + +DECLARE_MODULE(evdemo, evdemo_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); +MODULE_VERSION(evdemo, 25); diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.h b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.h new file mode 100644 index 0000000..c959a97 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo.h @@ -0,0 +1,24 @@ +/* + * evdemo.h - shared user/kernel definitions for the evdemo driver. + * + * Version 2.5-async reference implementation. + */ + +#ifndef _EVDEMO_H_ +#define _EVDEMO_H_ + +#include +#include + +struct evdemo_event { + struct timespec ev_time; + uint32_t ev_type; + uint32_t ev_code; + int64_t ev_value; +}; + +#define EVDEMO_EV_TYPE_TICK 1 +#define EVDEMO_EV_TYPE_TRIGGER 2 +#define EVDEMO_EV_TYPE_BURST 3 + +#endif /* _EVDEMO_H_ */ diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_combined.c b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_combined.c new file mode 100644 index 0000000..749fc68 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_combined.c @@ -0,0 +1,262 @@ +/* + * evdemo_test_combined.c - combined three-mechanism tester. + * + * Forks three children. Each child opens its own fd to /dev/evdemo + * and watches events through a different mechanism: poll, kqueue, + * or SIGIO. After a fixed duration, each child reports the number + * of events it saw. The parent triggers events at a known rate and + * prints a summary. + * + * The goal is to verify that all three mechanisms see the same + * number of events, which demonstrates that the producer's + * notifications are complete and that the locking discipline is + * correct. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t pending_sigio; + +static void +on_sigio(int sig __attribute__((unused))) +{ + pending_sigio = 1; +} + +static int +drain_all(int fd, int *count, int limit) +{ + struct evdemo_event ev; + ssize_t n; + + for (;;) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + return (0); + return (-1); + } + if (n == 0) + return (1); + if (n != sizeof(ev)) + return (0); + (*count)++; + if (*count >= limit) + return (1); + } +} + +static int +poll_child(int duration_s) +{ + struct pollfd pfd; + struct evdemo_event ev; + int fd, ret, count = 0; + time_t deadline = time(NULL) + duration_s; + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) { + warn("poll_child: open"); + return (-1); + } + + while (time(NULL) < deadline) { + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + ret = poll(&pfd, 1, 500); + if (ret < 0 && errno != EINTR) + break; + if (ret > 0 && (pfd.revents & POLLIN)) { + while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) + count++; + } + } + close(fd); + return (count); +} + +static int +kqueue_child(int duration_s) +{ + struct kevent ev_set, ev_got; + struct evdemo_event ev; + struct timespec timeout; + int fd, kq, ret, count = 0; + time_t deadline = time(NULL) + duration_s; + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) { + warn("kqueue_child: open"); + return (-1); + } + + kq = kqueue(); + if (kq < 0) { + warn("kqueue_child: kqueue"); + close(fd); + return (-1); + } + + EV_SET(&ev_set, fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, NULL); + (void)kevent(kq, &ev_set, 1, NULL, 0, NULL); + + while (time(NULL) < deadline) { + timeout.tv_sec = 0; + timeout.tv_nsec = 500 * 1000 * 1000; + ret = kevent(kq, NULL, 0, &ev_got, 1, &timeout); + if (ret < 0 && errno != EINTR) + break; + if (ret > 0) { + if (ev_got.flags & EV_EOF) + break; + while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) + count++; + } + } + + close(kq); + close(fd); + return (count); +} + +static int +sigio_child(int duration_s) +{ + struct evdemo_event ev; + struct sigaction sa; + pid_t pid; + int fd, flag, count = 0; + time_t deadline = time(NULL) + duration_s; + + sa.sa_handler = on_sigio; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + if (sigaction(SIGIO, &sa, NULL) < 0) { + warn("sigio_child: sigaction"); + return (-1); + } + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) { + warn("sigio_child: open"); + return (-1); + } + + pid = getpid(); + if (ioctl(fd, FIOSETOWN, &pid) < 0) { + warn("sigio_child: FIOSETOWN"); + close(fd); + return (-1); + } + + flag = 1; + if (ioctl(fd, FIOASYNC, &flag) < 0) { + warn("sigio_child: FIOASYNC"); + close(fd); + return (-1); + } + + while (time(NULL) < deadline) { + if (pending_sigio) { + pending_sigio = 0; + while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) + count++; + } else { + struct timespec ts = { 0, 100 * 1000 * 1000 }; + nanosleep(&ts, NULL); + } + } + + flag = 0; + (void)ioctl(fd, FIOASYNC, &flag); + close(fd); + return (count); +} + +int +main(int argc, char **argv) +{ + pid_t poll_pid, kq_pid, sig_pid; + int status; + int duration = (argc > 1) ? atoi(argv[1]) : 5; + int burst = (argc > 2) ? atoi(argv[2]) : 100; + int rounds = (argc > 3) ? atoi(argv[3]) : 5; + + if (duration < 1) + duration = 1; + if (burst < 1) + burst = 10; + + printf("combined: duration=%ds burst=%d rounds=%d\n", + duration, burst, rounds); + + poll_pid = fork(); + if (poll_pid == 0) { + int n = poll_child(duration); + printf("poll child: %d events\n", n); + exit(0); + } + if (poll_pid < 0) + err(1, "fork poll_child"); + + kq_pid = fork(); + if (kq_pid == 0) { + int n = kqueue_child(duration); + printf("kqueue child: %d events\n", n); + exit(0); + } + if (kq_pid < 0) + err(1, "fork kqueue_child"); + + sig_pid = fork(); + if (sig_pid == 0) { + int n = sigio_child(duration); + printf("sigio child: %d events\n", n); + exit(0); + } + if (sig_pid < 0) + err(1, "fork sigio_child"); + + /* + * Parent triggers bursts. Give children a moment to open and + * register before posting events. + */ + struct timespec ts = { 0, 500 * 1000 * 1000 }; + nanosleep(&ts, NULL); + + int i; + char cmd[128]; + for (i = 0; i < rounds; i++) { + snprintf(cmd, sizeof(cmd), + "sysctl dev.evdemo.burst=%d >/dev/null", burst); + (void)system(cmd); + nanosleep(&ts, NULL); + } + + waitpid(poll_pid, &status, 0); + waitpid(kq_pid, &status, 0); + waitpid(sig_pid, &status, 0); + + printf("combined: done. Compare the three counts: they should " + "all match roughly the total of %d burst events plus %d " + "tick events.\n", rounds * burst, duration); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_kqueue.c b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_kqueue.c new file mode 100644 index 0000000..55ae732 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_kqueue.c @@ -0,0 +1,94 @@ +/* + * evdemo_test_kqueue.c - kqueue-based reader for the v2.5-async + * driver. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct kevent ev_set, ev_got; + struct evdemo_event event; + struct timespec timeout; + ssize_t n; + int fd, kq, ret; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 10; + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + kq = kqueue(); + if (kq < 0) + err(1, "kqueue"); + + EV_SET(&ev_set, fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, NULL); + if (kevent(kq, &ev_set, 1, NULL, 0, NULL) < 0) + err(1, "kevent add"); + + printf("kqueue: waiting for %d events\n", limit); + + while (!stop && count < limit) { + timeout.tv_sec = 5; + timeout.tv_nsec = 0; + ret = kevent(kq, NULL, 0, &ev_got, 1, &timeout); + if (ret < 0) { + if (stop || errno == EINTR) + break; + err(1, "kevent wait"); + } + if (ret == 0) + continue; + if (ev_got.flags & EV_EOF) { + printf("kqueue: device closed\n"); + break; + } + + while (count < limit) { + n = read(fd, &event, sizeof(event)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + break; + err(1, "read"); + } + if (n == 0) + goto done; + if (n != sizeof(event)) + break; + printf("kqueue event %d: type=%u value=%lld\n", + count + 1, event.ev_type, + (long long)event.ev_value); + count++; + } + } + +done: + close(kq); + close(fd); + printf("kqueue: received %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_poll.c b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_poll.c new file mode 100644 index 0000000..39598a3 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_poll.c @@ -0,0 +1,80 @@ +/* + * evdemo_test_poll.c - poll-based reader for the v2.5-async driver. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t stop; + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct pollfd pfd; + struct evdemo_event ev; + ssize_t n; + int fd, ret; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 10; + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + printf("poll: waiting for %d events\n", limit); + + while (!stop && count < limit) { + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + + ret = poll(&pfd, 1, 5000); + if (ret < 0) { + if (stop || errno == EINTR) + break; + err(1, "poll"); + } + if (ret == 0) + continue; + if (pfd.revents & (POLLHUP | POLLNVAL)) { + printf("poll: device closed\n"); + break; + } + if (pfd.revents & POLLIN) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + continue; + err(1, "read"); + } + if (n == 0) + break; + if (n != sizeof(ev)) + continue; + printf("poll event %d: type=%u value=%lld\n", + count + 1, ev.ev_type, + (long long)ev.ev_value); + count++; + } + } + close(fd); + printf("poll: received %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_sigio.c b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_sigio.c new file mode 100644 index 0000000..83ec08b --- /dev/null +++ b/examples/part-07/ch35-async-io/lab06-v25-async/evdemo_test_sigio.c @@ -0,0 +1,100 @@ +/* + * evdemo_test_sigio.c - SIGIO-based reader for the v2.5-async + * driver. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "evdemo.h" + +static volatile sig_atomic_t pending; +static volatile sig_atomic_t stop; + +static void +on_sigio(int sig __attribute__((unused))) +{ + pending = 1; +} + +static void +on_int(int sig __attribute__((unused))) +{ + stop = 1; +} + +int +main(int argc, char **argv) +{ + struct evdemo_event ev; + struct sigaction sa; + ssize_t n; + pid_t pid; + int fd, flag; + int count = 0; + int limit = (argc > 1) ? atoi(argv[1]) : 10; + + sa.sa_handler = on_sigio; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + if (sigaction(SIGIO, &sa, NULL) < 0) + err(1, "sigaction SIGIO"); + + signal(SIGINT, on_int); + + fd = open("/dev/evdemo", O_RDONLY | O_NONBLOCK); + if (fd < 0) + err(1, "open /dev/evdemo"); + + pid = getpid(); + if (ioctl(fd, FIOSETOWN, &pid) < 0) + err(1, "FIOSETOWN"); + + flag = 1; + if (ioctl(fd, FIOASYNC, &flag) < 0) + err(1, "FIOASYNC"); + + printf("sigio: waiting for %d events\n", limit); + + while (!stop && count < limit) { + if (!pending) { + pause(); + continue; + } + pending = 0; + + for (;;) { + n = read(fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EAGAIN || errno == EINTR) + break; + err(1, "read"); + } + if (n == 0) + goto done; + if (n != sizeof(ev)) + break; + printf("sigio event %d: type=%u value=%lld\n", + count + 1, ev.ev_type, + (long long)ev.ev_value); + count++; + if (count >= limit) + break; + } + } + +done: + flag = 0; + (void)ioctl(fd, FIOASYNC, &flag); + close(fd); + printf("sigio: received %d events\n", count); + return (0); +} diff --git a/examples/part-07/ch35-async-io/lab07-stress/evdemo_stress.sh b/examples/part-07/ch35-async-io/lab07-stress/evdemo_stress.sh new file mode 100755 index 0000000..b4caf04 --- /dev/null +++ b/examples/part-07/ch35-async-io/lab07-stress/evdemo_stress.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# +# evdemo_stress.sh - load/unload stress for the v2.5-async driver. +# +# Usage: sudo ./evdemo_stress.sh [cycles] [lab06_path] +# +# Defaults: 100 cycles, module taken from ../lab06-v25-async/. +# +# Each cycle: +# 1. kldload the module. +# 2. trigger a burst of events. +# 3. open a reader in the background. +# 4. trigger more events. +# 5. kldunload the module. +# If any step fails, the script exits non-zero. A driver with a +# correct detach path survives many hundreds of cycles without +# panicking, leaking memory, or leaving stale /dev/evdemo nodes. + +set -e + +CYCLES=${1:-100} +LAB=${2:-"../lab06-v25-async"} + +if [ ! -f "${LAB}/evdemo.ko" ]; then + echo "error: ${LAB}/evdemo.ko not found. Run 'make' there first." >&2 + exit 1 +fi + +MODULE="${LAB}/evdemo.ko" + +# Clean up any leftover module from a previous run. +kldstat | grep -q evdemo && kldunload evdemo || true + +i=0 +while [ "$i" -lt "${CYCLES}" ]; do + i=$((i + 1)) + printf "cycle %4d/%d ... " "$i" "${CYCLES}" + + kldload "${MODULE}" + + sysctl dev.evdemo.burst=50 >/dev/null + + # A short-lived reader that consumes a few events and exits. + (cat /dev/evdemo >/dev/null) & + READER_PID=$! + sleep 0.1 + + sysctl dev.evdemo.burst=50 >/dev/null + sleep 0.1 + + kill "${READER_PID}" 2>/dev/null || true + wait "${READER_PID}" 2>/dev/null || true + + kldunload evdemo + + echo "ok" +done + +echo "stress test completed ${CYCLES} cycles without panic" diff --git a/examples/part-07/ch35-async-io/shared/build-notes.md b/examples/part-07/ch35-async-io/shared/build-notes.md new file mode 100644 index 0000000..b2466ba --- /dev/null +++ b/examples/part-07/ch35-async-io/shared/build-notes.md @@ -0,0 +1,127 @@ +# Shared Build Notes + +These notes apply to every lab in this chapter. + +## Prerequisites + +Each lab assumes: + +- FreeBSD 14.3 or later. +- `/usr/src/` is populated (clone from git, or use + `pkg install src-quarterly`, or extract the release source tarball). +- Standard build tools available (`make(1)`, `cc(1)`). These are in + the base system on FreeBSD. +- Root privileges for `kldload` and `kldunload` (or membership in the + `operator` group with appropriate `devfs(8)` rules). + +## Building a Kernel Module + +The labs use the standard FreeBSD kernel module build system. + +``` +$ make clean +$ make +``` + +This produces `evdemo.ko` in the current directory. + +## Loading and Unloading + +``` +$ sudo kldload ./evdemo.ko # load +$ sudo kldunload evdemo # unload (no .ko suffix on unload) +$ kldstat | grep evdemo # verify loaded +``` + +Always unload a previous build before reloading. A stale module in +the kernel will make the next `kldload` fail with "file exists." + +## Running the Test Programs + +Each lab includes one or more user-space programs that exercise the +driver. Build them with: + +``` +$ make test +``` + +Then run them as root so they can open `/dev/evdemo`: + +``` +$ sudo ./evdemo_test +$ sudo ./evdemo_test_poll +$ sudo ./evdemo_test_kqueue +$ sudo ./evdemo_test_sigio +``` + +The device node is created with mode 0600 and owner root:wheel, so +the test programs need elevated privileges to open it. + +## Triggering Synthetic Events + +Every `evdemo` variant exposes a `trigger` sysctl that posts a +synthetic event into the queue: + +``` +$ sudo sysctl dev.evdemo.trigger=1 +``` + +Starting with Lab 5, a `burst` sysctl posts a batch of events at +once: + +``` +$ sudo sysctl dev.evdemo.burst=100 +``` + +Use these sysctls to exercise the driver without having to write +custom test programs. + +## Observing Queue State + +Labs 5, 6, and 7 expose queue metrics through sysctl: + +``` +$ sysctl dev.evdemo.stats +``` + +Watch these counters in a loop to see the queue behaviour at +runtime: + +``` +$ while :; do sysctl dev.evdemo.stats; sleep 1; done +``` + +## Enabling INVARIANTS for a Single Module + +If you are running a release kernel but want to test a module built +with `INVARIANTS`, make sure the kernel has `INVARIANT_SUPPORT` at +minimum, then build the module with: + +``` +$ CFLAGS="-DINVARIANTS -DINVARIANT_SUPPORT -DWITNESS" make +``` + +This enables the `mtx_assert()` calls inside the driver so that any +missing locks show up immediately rather than as silent races. + +## Enabling DTrace on a Module + +To let DTrace see structure fields by name in your module, build with +CTF information: + +``` +$ WITH_CTF=1 make +``` + +This adds CTF data to `evdemo.ko`, which DTrace uses to decode +structures. + +## Troubleshooting the Build + +If `make` fails with "bsd.kmod.mk: not found", the source tree is +either missing or incomplete. Install `src-quarterly` or clone +`/usr/src/` from the FreeBSD git tree. + +If the build succeeds but `kldload` fails with "symbol not found," +the kernel is older than the module expects. Rebuild the module +against the running kernel's source. diff --git a/examples/part-07/ch36-reverse-engineering/exercise-your-own/skeleton-template.c b/examples/part-07/ch36-reverse-engineering/exercise-your-own/skeleton-template.c new file mode 100644 index 0000000..c482891 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/exercise-your-own/skeleton-template.c @@ -0,0 +1,131 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * skeleton-template.c + * + * Companion to Chapter 36 of "FreeBSD Device Drivers: From First + * Steps to Kernel Mastery", "Hands-On Exercise: Your Own + * Observation". + * + * This file is a minimal Newbus-style USB driver skeleton. It is + * not a complete driver. It shows the scaffolding every USB + * driver needs, with TODO: markers at the points the exercise + * asks you to fill in using your own observations: + * + * - the vendor and product IDs from Step 1 + * - the endpoint types, directions, and transfer setup that + * match what you catalogued in Step 3 + * - the attach and detach bodies that allocate and release the + * endpoints and transfers + * + * The goal at this stage is a module that compiles, loads, + * attaches to your device, prints a short message on attach, and + * prints another on detach. Do not attempt to implement data + * handling until the attach and detach paths are clean. + * + * See /usr/src/sys/dev/usb/serial/umcs.c and + * /usr/src/sys/dev/usb/serial/uftdi.c for complete, in-tree + * examples of the same pattern at full scale. + */ + +#include +#include +#include +#include +#include + +#include +#include + +/* + * Device identification table. + * + * TODO: replace the placeholder vendor and product IDs with the + * idVendor and idProduct values you observed in + * device-descriptors.txt. + */ +static const STRUCT_USB_HOST_ID myusb_devs[] = { + { USB_VP(0x0000 /* TODO: VID */, 0x0000 /* TODO: PID */) }, +}; + +static device_probe_t myusb_probe; +static device_attach_t myusb_attach; +static device_detach_t myusb_detach; + +/* + * Probe: called by the USB subsystem for each candidate device. + * Returns 0 on match, ENXIO on mismatch. + */ +static int +myusb_probe(device_t dev) +{ + struct usb_attach_arg *uaa = device_get_ivars(dev); + + if (uaa->usb_mode != USB_MODE_HOST) + return (ENXIO); + + return (usbd_lookup_id_by_uaa(myusb_devs, + sizeof(myusb_devs), uaa)); +} + +/* + * Attach: called after a successful probe. + * + * TODO: build a struct usb_config array that describes the + * endpoints you catalogued in Step 3, using fields of the form: + * + * { + * .type = UE_BULK, (or UE_INTERRUPT, UE_CONTROL) + * .endpoint = UE_ADDR_ANY, (or a specific address) + * .direction = UE_DIR_IN, (or UE_DIR_OUT) + * .bufsize = , + * .callback = &myusb__callback, + * } + * + * Then call usbd_transfer_setup() to allocate the transfers. + * Keep the skeleton empty until those pieces are in place; the + * attach path should still print a message and return 0 so you + * can confirm Newbus binding independently of transfer setup. + */ +static int +myusb_attach(device_t dev) +{ + /* TODO: allocate endpoints and set up transfers here. */ + device_printf(dev, "attached\n"); + return (0); +} + +/* + * Detach: called when the module is unloaded or the device is + * removed. + * + * TODO: unwind whatever attach allocated, in reverse order. + * Typical sequence: + * + * - usbd_transfer_unsetup() on each transfer group + * - release any mutexes and memory the driver allocated + */ +static int +myusb_detach(device_t dev) +{ + /* TODO: release endpoints and transfers here. */ + device_printf(dev, "detached\n"); + return (0); +} + +static device_method_t myusb_methods[] = { + DEVMETHOD(device_probe, myusb_probe), + DEVMETHOD(device_attach, myusb_attach), + DEVMETHOD(device_detach, myusb_detach), + DEVMETHOD_END +}; + +static driver_t myusb_driver = { + .name = "myusb", + .methods = myusb_methods, + .size = 0, /* TODO: replace with sizeof(struct myusb_softc). */ +}; + +DRIVER_MODULE(myusb, uhub, myusb_driver, NULL, NULL); +MODULE_DEPEND(myusb, usb, 1, 1, 1); +MODULE_VERSION(myusb, 1); diff --git a/examples/part-07/ch36-reverse-engineering/exercise-your-own/walkthrough.sh b/examples/part-07/ch36-reverse-engineering/exercise-your-own/walkthrough.sh new file mode 100755 index 0000000..27730eb --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/exercise-your-own/walkthrough.sh @@ -0,0 +1,183 @@ +#!/bin/sh +# +# walkthrough.sh - Companion script for Chapter 36's +# "Hands-On Exercise: Your Own Observation". +# +# This script runs the suggested usbconfig(8) and usbdump(8) +# commands in order against one USB device of your choice. It is +# a template: edit the three variables below to match your device +# and your capture layout before you run it. +# +# The script performs passive observation only. It does not write +# to the device and it does not change device state. Read the +# exercise's README.md and the safety notes in Chapter 36 before +# running it. +# +# Usage: +# sudo sh walkthrough.sh +# + +set -eu + +############################################################ +# Edit these three variables before running. +############################################################ + +# The ugenB.D coordinate of your target device. +# Run "usbconfig list" first to find the right value. +UGEN="ugen0.2" + +# The USB bus the device is attached to. +# On a single-controller system this is typically usbus0. +USBUS="usbus0" + +# Directory in which to store the captures and dumps. +# A dedicated per-device folder is the cleanest option. +OUTDIR="./capture" + +############################################################ +# End of configuration. +############################################################ + +if [ "$(id -u)" -ne 0 ]; then + echo "This script must be run as root." >&2 + exit 1 +fi + +if ! command -v usbconfig >/dev/null 2>&1; then + echo "usbconfig(8) not found in PATH." >&2 + exit 1 +fi + +if ! command -v usbdump >/dev/null 2>&1; then + echo "usbdump(8) not found in PATH." >&2 + exit 1 +fi + +mkdir -p "$OUTDIR" + +############################################################ +# Safety reminder. +############################################################ + +cat < $OUTDIR/usbconfig-list.txt" +usbconfig list > "$OUTDIR/usbconfig-list.txt" + +echo " -> $OUTDIR/show-ifdrv.txt" +usbconfig -d "$UGEN" show_ifdrv > "$OUTDIR/show-ifdrv.txt" + +echo " -> $OUTDIR/device-descriptors.txt" +usbconfig -d "$UGEN" dump_all_desc > "$OUTDIR/device-descriptors.txt" + +cat <" before running your own code + against the device. You do not need to detach it for the + capture step below; the capture is passive. + - Make a note of the bInterfaceClass, bInterfaceSubClass, and + bInterfaceProtocol fields from $OUTDIR/device-descriptors.txt. + You will map them to driver structures in Step 3. + +EOF + +############################################################ +# Step 2: packet-level observation with usbdump(8). +############################################################ + +echo "Step 2: preparing to capture packet-level traffic." + +cat < $OUTDIR/trace.pcap" +# Run usbdump to pcap. The operator stops this with Control-C. +usbdump -i "$USBUS" -s 2048 -w "$OUTDIR/trace.pcap" || true + +cat < $OUTDIR/trace.txt" +usbdump -i "$USBUS" -s 2048 > "$OUTDIR/trace.txt" || true + +cat <&2 + exit 1 +fi + +OUTDIR="${1:-identify-$(date '+%Y%m%d-%H%M%S')}" +mkdir -p "$OUTDIR" + +echo "Writing captures to $OUTDIR" + +# Static system identity. Useful for correlating captures from +# different machines. +{ + echo "# uname -a" + uname -a + echo + echo "# date" + date + echo + echo "# sysctl hw.machine hw.model hw.ncpu" + sysctl hw.machine hw.model hw.ncpu +} >"$OUTDIR/system.txt" + +# PCI devices. The -lvc flags ask pciconf for a long listing with +# verbose output and capability dumps, which is the most informative +# form available for static identification. +echo "Capturing PCI device list..." +pciconf -lvc >"$OUTDIR/pciconf.txt" 2>&1 + +# Devices that have no in-tree driver attached appear as "noneN@..." +# in the pciconf output. Those are the candidate targets for any +# reverse-engineering investigation. +grep '^none' "$OUTDIR/pciconf.txt" >"$OUTDIR/pciconf-none.txt" || true + +# USB devices. usbconfig with no arguments lists every USB device +# the kernel has enumerated. +echo "Capturing USB device list..." +usbconfig >"$OUTDIR/usbconfig.txt" 2>&1 + +# For each USB device, dump the device, configuration, and string +# descriptors. The descriptors are the static identity of the device +# at the USB level. +echo "Capturing USB descriptors..." +mkdir -p "$OUTDIR/usb-descriptors" +usbconfig list 2>/dev/null | awk '{print $1}' | sed 's/:$//' | + while read -r dev; do + if [ -z "$dev" ]; then + continue + fi + safedev=$(echo "$dev" | tr '/.' '__') + { + echo "# usbconfig -d $dev dump_device_desc" + usbconfig -d "$dev" dump_device_desc 2>&1 || true + echo + echo "# usbconfig -d $dev dump_curr_config_desc" + usbconfig -d "$dev" dump_curr_config_desc 2>&1 || true + echo + echo "# usbconfig -d $dev dump_string_desc" + usbconfig -d "$dev" dump_string_desc 2>&1 || true + } >"$OUTDIR/usb-descriptors/$safedev.txt" + done + +# Newbus devices. devinfo gives a tree view of every device the +# kernel knows about, with parent-child relationships visible. +echo "Capturing devinfo tree..." +devinfo -v >"$OUTDIR/devinfo.txt" 2>&1 +devinfo -r >"$OUTDIR/devinfo-resources.txt" 2>&1 + +# Boot-time device messages. dmesg records the attach messages of +# every driver that successfully probed a device, which often +# includes useful identifying information. +echo "Capturing boot-time device messages..." +dmesg | grep -E 'pci|usb|attached|detached|on usbus|<' \ + >"$OUTDIR/dmesg-devices.txt" 2>&1 || true + +# Optional: kernel module list. Knowing which modules are loaded can +# explain why some devices have drivers and others do not. +echo "Capturing loaded kernel modules..." +kldstat -v >"$OUTDIR/kldstat.txt" 2>&1 + +echo +echo "Capture complete." +echo "Output directory: $OUTDIR" +echo +echo "Suggested next steps:" +echo " 1. Open $OUTDIR/pciconf-none.txt and look for unknown devices." +echo " 2. Open $OUTDIR/usbconfig.txt and pick a USB device of interest." +echo " 3. Compare $OUTDIR/usb-descriptors/.txt with the public" +echo " USB.org class definitions for the corresponding device class." diff --git a/examples/part-07/ch36-reverse-engineering/lab02-capture/capture.sh b/examples/part-07/ch36-reverse-engineering/lab02-capture/capture.sh new file mode 100755 index 0000000..5ee32ec --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab02-capture/capture.sh @@ -0,0 +1,114 @@ +#!/bin/sh +# +# capture.sh - Capture USB traffic with usbdump(8) for offline +# analysis in Wireshark or another pcap-aware tool. +# +# Companion to Chapter 36, Lab 2. +# +# This script is a thin wrapper around usbdump(8) that handles +# the common-case bookkeeping: picking a sensible output filename, +# requesting the right bus, and giving the operator clear instructions +# for how to start, stop, and read the capture. +# +# Usage: +# sudo sh capture.sh [-i usbus_interface] [-o output_file] +# [-c count] [-s snaplen] +# +# Defaults: +# interface: usbus0 +# output_file: capture-YYYYMMDD-HHMMSS.pcap +# count: 0 (no limit, capture until interrupted) +# snaplen: 65535 (full packets) + +set -eu + +INTERFACE="usbus0" +OUTPUT="" +COUNT="0" +SNAPLEN="65535" + +usage() { + cat <&2 + exit 1 +fi + +# Verify the interface exists. +if ! ifconfig "$INTERFACE" >/dev/null 2>&1; then + echo "Interface $INTERFACE does not exist." >&2 + echo "Available USB buses:" >&2 + ifconfig -l | tr ' ' '\n' | grep '^usbus' >&2 || true + exit 1 +fi + +# Default output filename if none supplied. +if [ -z "$OUTPUT" ]; then + OUTPUT="capture-$(date '+%Y%m%d-%H%M%S').pcap" +fi + +cat < + 3. Use the endpoint filter to focus on a specific transfer type: + usb.endpoint_address == 0x81 + 4. Compare the device descriptor in the capture against + dump_device_desc output from Lab 1. + +If your version of Wireshark does not understand FreeBSD usbdump +captures directly, install the wireshark port from the FreeBSD +Ports Collection or pkg, both of which include the necessary +dissector. +EOF diff --git a/examples/part-07/ch36-reverse-engineering/lab03-register-map/Makefile b/examples/part-07/ch36-reverse-engineering/lab03-register-map/Makefile new file mode 100644 index 0000000..4308e36 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab03-register-map/Makefile @@ -0,0 +1,6 @@ +KMOD= regprobe +SRCS= regprobe.c device_if.h bus_if.h pci_if.h + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch36-reverse-engineering/lab03-register-map/regprobe.c b/examples/part-07/ch36-reverse-engineering/lab03-register-map/regprobe.c new file mode 100644 index 0000000..b64617c --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab03-register-map/regprobe.c @@ -0,0 +1,217 @@ +/* + * regprobe.c - A read-only register probing kernel module. + * + * Companion to Chapter 36, Lab 3, of "FreeBSD Device Drivers: + * From First Steps to Kernel Mastery." + * + * This module attaches as a child of the PCI bus when the operator + * tells it to (the probe method returns BUS_PROBE_NOWILDCARD, so + * the module never claims a device automatically). When attached, + * it allocates the first SYS_RES_MEMORY resource of the device and + * exposes a sysctl that, when read, dumps every word of that + * resource as hexadecimal. + * + * The module performs no writes. It is purely an observation tool, + * intended for the early stages of a reverse-engineering project + * when you want to see the contents of a device's memory-mapped + * register region without changing anything. + * + * Suggested use: + * + * # Detach the in-tree driver from the device first. + * sudo devctl detach pci0:1:0:0 + * + * # Load this module. + * sudo kldload ./regprobe.ko + * + * # Attach this module to the device. + * sudo devctl set driver pci0:1:0:0 regprobe + * + * # Read the dump sysctl. + * sysctl dev.regprobe.0.dump + * + * # Compare two dumps separated by some time. + * sysctl dev.regprobe.0.dump > dump1.txt + * sleep 10 + * sysctl dev.regprobe.0.dump > dump2.txt + * diff dump1.txt dump2.txt + * + * # Detach when done. + * sudo devctl detach pci0:1:0:0 + * sudo kldunload regprobe + * sudo devctl attach pci0:1:0:0 + * + * Do not attach this module to a device that is currently in use. + * Do not attach it to the device that backs your console or your + * storage. The act of detaching the in-tree driver and attaching + * this one will, at minimum, stop the original driver from working + * until you reverse the operation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#define REGPROBE_MAX_DUMP (64 * 1024) + +struct regprobe_softc { + device_t sc_dev; + struct mtx sc_mtx; + struct resource *sc_mem; + int sc_rid; + bus_size_t sc_size; +}; + +static int regprobe_probe(device_t dev); +static int regprobe_attach(device_t dev); +static int regprobe_detach(device_t dev); +static int regprobe_dump_sysctl(SYSCTL_HANDLER_ARGS); + +static int +regprobe_probe(device_t dev) +{ + /* + * BUS_PROBE_NOWILDCARD is the protective return value. It + * means: do not attach to any device unless the operator + * explicitly tells me to with devctl(8). Without this, the + * module would attempt to attach to every PCI device in the + * system, which would be both useless and dangerous. + */ + device_set_desc(dev, "Register probing tool (read-only)"); + return (BUS_PROBE_NOWILDCARD); +} + +static int +regprobe_attach(device_t dev) +{ + struct regprobe_softc *sc = device_get_softc(dev); + struct sysctl_ctx_list *ctx; + struct sysctl_oid *tree; + + sc->sc_dev = dev; + sc->sc_rid = PCIR_BAR(0); + mtx_init(&sc->sc_mtx, "regprobe", NULL, MTX_DEF); + + /* + * Allocate the device's first memory BAR. We accept whatever + * the bus gives us; the size of the resource determines how + * much we will dump in the sysctl handler. + */ + sc->sc_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, + &sc->sc_rid, RF_ACTIVE); + if (sc->sc_mem == NULL) { + device_printf(dev, + "could not allocate memory resource\n"); + mtx_destroy(&sc->sc_mtx); + return (ENXIO); + } + sc->sc_size = rman_get_size(sc->sc_mem); + device_printf(dev, "mapped %ju bytes at BAR0\n", + (uintmax_t)sc->sc_size); + + /* Sanity check the size. We refuse to map regions larger than + * REGPROBE_MAX_DUMP because the sysctl-dump output would not + * fit in any sensible buffer. */ + if (sc->sc_size > REGPROBE_MAX_DUMP) { + device_printf(dev, + "BAR0 is %ju bytes, larger than the limit of %u\n", + (uintmax_t)sc->sc_size, REGPROBE_MAX_DUMP); + bus_release_resource(dev, SYS_RES_MEMORY, + sc->sc_rid, sc->sc_mem); + mtx_destroy(&sc->sc_mtx); + return (E2BIG); + } + + ctx = device_get_sysctl_ctx(dev); + tree = device_get_sysctl_tree(dev); + + SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "dump", + CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, + sc, 0, regprobe_dump_sysctl, "A", + "Hexadecimal dump of the device's memory region"); + + SYSCTL_ADD_UQUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "size", + CTLFLAG_RD, &sc->sc_size, + "Size in bytes of the mapped region"); + + return (0); +} + +static int +regprobe_detach(device_t dev) +{ + struct regprobe_softc *sc = device_get_softc(dev); + + if (sc->sc_mem != NULL) { + bus_release_resource(dev, SYS_RES_MEMORY, + sc->sc_rid, sc->sc_mem); + sc->sc_mem = NULL; + } + mtx_destroy(&sc->sc_mtx); + return (0); +} + +static int +regprobe_dump_sysctl(SYSCTL_HANDLER_ARGS) +{ + struct regprobe_softc *sc = arg1; + char *buf, *p; + bus_size_t off, size; + uint32_t val; + int error, n; + size_t bufsize; + + size = sc->sc_size; + /* Each 4-byte word produces about 24 bytes of output text + * ("ffff: 0xdeadbeef\n" is 18 bytes; round up). Allocate + * generously. */ + bufsize = (size_t)(size / 4 + 1) * 32 + 64; + if (bufsize > REGPROBE_MAX_DUMP * 32) + return (E2BIG); + buf = malloc(bufsize, M_TEMP, M_WAITOK | M_ZERO); + p = buf; + + mtx_lock(&sc->sc_mtx); + for (off = 0; off + 4 <= size; off += 4) { + val = bus_read_4(sc->sc_mem, off); + n = snprintf(p, bufsize - (p - buf), + "%04jx: 0x%08x\n", (uintmax_t)off, val); + if (n < 0 || (size_t)n >= bufsize - (p - buf)) + break; + p += n; + } + mtx_unlock(&sc->sc_mtx); + + error = sysctl_handle_string(oidp, buf, p - buf, req); + free(buf, M_TEMP); + return (error); +} + +static device_method_t regprobe_methods[] = { + DEVMETHOD(device_probe, regprobe_probe), + DEVMETHOD(device_attach, regprobe_attach), + DEVMETHOD(device_detach, regprobe_detach), + DEVMETHOD_END +}; + +static driver_t regprobe_driver = { + "regprobe", + regprobe_methods, + sizeof(struct regprobe_softc) +}; + +DRIVER_MODULE(regprobe, pci, regprobe_driver, NULL, NULL); +MODULE_VERSION(regprobe, 1); diff --git a/examples/part-07/ch36-reverse-engineering/lab04-mock-device/Makefile b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/Makefile new file mode 100644 index 0000000..f4b62f1 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/Makefile @@ -0,0 +1,18 @@ +KMOD= mockdev +SRCS= mockdev.c + +SYSDIR?= /usr/src/sys + +CFLAGS+= -I${.CURDIR} + +# User-space test program is built with `make test`. +test: mockdev_test + +mockdev_test: mockdev_test.c mockdev.h + cc -Wall -Wextra -O2 -o mockdev_test mockdev_test.c + +clean: cleantest +cleantest: + rm -f mockdev_test + +.include diff --git a/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.c b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.c new file mode 100644 index 0000000..ce0915c --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.c @@ -0,0 +1,231 @@ +/* + * mockdev.c - A software-only mock device. + * + * Companion to Chapter 36, Lab 4, of "FreeBSD Device Drivers: + * From First Steps to Kernel Mastery." + * + * This module simulates a tiny "command and status" device entirely + * in software. There is no hardware involved, no bus_alloc_resource + * call, no real memory-mapped I/O. The point of the mock is to give + * a driver author a target for testing driver code without needing + * the real device, and to give a learner a safe environment to + * practice the simulation pattern that real reverse-engineering + * projects rely on. + * + * The mock exposes a character device at /dev/mockdev. Operations + * happen through ioctl, with the operation codes defined in + * mockdev.h. Commands take a simulated time to complete (modeled + * with a callout), during which the BUSY status bit is set. When + * the simulated processing time elapses, the BUSY bit is cleared, + * the DONE bit is set, and the result of the command is placed in + * the data register. + * + * The simulated commands are: + * + * MOCKDEV_CMD_NOP - succeeds immediately, returns zero + * MOCKDEV_CMD_RESET - resets the internal counter + * MOCKDEV_CMD_READ_ID - returns the constant chip identifier + * MOCKDEV_CMD_INCREMENT - increments and returns the counter + * MOCKDEV_CMD_FAIL - always reports the ERROR status bit + * + * Any other command code is treated as unknown and produces an + * ERROR status, which is the same behaviour a real device would + * exhibit if the driver sent a command code outside its valid + * range. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mockdev.h" + +#define MOCKDEV_PROC_TICKS (hz / 10) /* 100 ms */ + +struct mockdev_softc { + struct cdev *sc_dev; + struct mtx sc_mtx; + struct callout sc_callout; + uint32_t sc_cmd; + uint32_t sc_status; + uint32_t sc_data; + uint32_t sc_counter; +}; + +static struct mockdev_softc mockdev_sc; + +static d_open_t mockdev_open; +static d_close_t mockdev_close; +static d_ioctl_t mockdev_ioctl; + +static struct cdevsw mockdev_cdevsw = { + .d_version = D_VERSION, + .d_open = mockdev_open, + .d_close = mockdev_close, + .d_ioctl = mockdev_ioctl, + .d_name = MOCKDEV_DEVICE_NAME, +}; + +static void mockdev_complete(void *arg); +static void mockdev_dispatch(struct mockdev_softc *sc, uint32_t cmd); + +static int +mockdev_open(struct cdev *dev __unused, int oflags __unused, + int devtype __unused, struct thread *td __unused) +{ + return (0); +} + +static int +mockdev_close(struct cdev *dev __unused, int fflag __unused, + int devtype __unused, struct thread *td __unused) +{ + return (0); +} + +static void +mockdev_dispatch(struct mockdev_softc *sc, uint32_t cmd) +{ + mtx_assert(&sc->sc_mtx, MA_OWNED); + + sc->sc_cmd = cmd; + sc->sc_status = MOCKDEV_STATUS_BUSY; + sc->sc_data = 0; + callout_reset(&sc->sc_callout, MOCKDEV_PROC_TICKS, + mockdev_complete, sc); +} + +static void +mockdev_complete(void *arg) +{ + struct mockdev_softc *sc = arg; + + mtx_lock(&sc->sc_mtx); + switch (sc->sc_cmd) { + case MOCKDEV_CMD_NOP: + sc->sc_data = 0; + sc->sc_status = MOCKDEV_STATUS_DONE; + break; + case MOCKDEV_CMD_RESET: + sc->sc_counter = 0; + sc->sc_data = 0; + sc->sc_status = MOCKDEV_STATUS_DONE; + break; + case MOCKDEV_CMD_READ_ID: + sc->sc_data = MOCKDEV_CHIP_ID; + sc->sc_status = MOCKDEV_STATUS_DONE; + break; + case MOCKDEV_CMD_INCREMENT: + sc->sc_counter++; + sc->sc_data = sc->sc_counter; + sc->sc_status = MOCKDEV_STATUS_DONE; + break; + case MOCKDEV_CMD_FAIL: + sc->sc_data = 0; + sc->sc_status = MOCKDEV_STATUS_ERROR; + break; + default: + sc->sc_data = 0; + sc->sc_status = MOCKDEV_STATUS_ERROR; + break; + } + mtx_unlock(&sc->sc_mtx); +} + +static int +mockdev_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data, + int fflag __unused, struct thread *td __unused) +{ + struct mockdev_softc *sc = &mockdev_sc; + struct mockdev_op *op; + + switch (cmd) { + case MOCKDEV_IOC_SUBMIT: + op = (struct mockdev_op *)data; + mtx_lock(&sc->sc_mtx); + if (sc->sc_status & MOCKDEV_STATUS_BUSY) { + mtx_unlock(&sc->sc_mtx); + return (EBUSY); + } + mockdev_dispatch(sc, op->mo_cmd); + op->mo_status = sc->sc_status; + op->mo_data = sc->sc_data; + mtx_unlock(&sc->sc_mtx); + return (0); + + case MOCKDEV_IOC_READ_STATUS: + op = (struct mockdev_op *)data; + mtx_lock(&sc->sc_mtx); + op->mo_cmd = sc->sc_cmd; + op->mo_status = sc->sc_status; + op->mo_data = sc->sc_data; + mtx_unlock(&sc->sc_mtx); + return (0); + + case MOCKDEV_IOC_RESET: + mtx_lock(&sc->sc_mtx); + callout_stop(&sc->sc_callout); + sc->sc_cmd = 0; + sc->sc_status = 0; + sc->sc_data = 0; + sc->sc_counter = 0; + mtx_unlock(&sc->sc_mtx); + return (0); + + default: + return (ENOTTY); + } +} + +static int +mockdev_modevent(module_t mod __unused, int type, void *data __unused) +{ + struct mockdev_softc *sc = &mockdev_sc; + int error = 0; + + switch (type) { + case MOD_LOAD: + mtx_init(&sc->sc_mtx, "mockdev", NULL, MTX_DEF); + callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); + sc->sc_dev = make_dev(&mockdev_cdevsw, 0, + UID_ROOT, GID_WHEEL, 0600, MOCKDEV_DEVICE_NAME); + if (sc->sc_dev == NULL) { + callout_drain(&sc->sc_callout); + mtx_destroy(&sc->sc_mtx); + return (ENOMEM); + } + printf("mockdev: loaded, /dev/%s ready\n", + MOCKDEV_DEVICE_NAME); + break; + case MOD_UNLOAD: + if (sc->sc_dev != NULL) { + destroy_dev(sc->sc_dev); + sc->sc_dev = NULL; + } + callout_drain(&sc->sc_callout); + mtx_destroy(&sc->sc_mtx); + printf("mockdev: unloaded\n"); + break; + default: + error = EOPNOTSUPP; + break; + } + return (error); +} + +static moduledata_t mockdev_mod = { + "mockdev", + mockdev_modevent, + NULL +}; + +DECLARE_MODULE(mockdev, mockdev_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE); +MODULE_VERSION(mockdev, 1); diff --git a/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.h b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.h new file mode 100644 index 0000000..cb4f0f4 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev.h @@ -0,0 +1,62 @@ +/* + * mockdev.h - Public interface of the mock device. + * + * Companion to Chapter 36, Lab 4. + * + * The mock device exposes a small "command and status" interface + * via a character device at /dev/mockdev. The interface uses ioctl + * to send commands and to read back status and result data. + * + * The simulated register layout, were the mock backed by real + * hardware, would be: + * + * offset 0x00 (CMD) - write a command code; reads as 0 + * offset 0x04 (STATUS) - status bits (BUSY, DONE, ERROR) + * offset 0x08 (DATA) - result data after a successful command + * offset 0x0c (ID) - constant chip identifier + * + * In this lab the registers are not memory-mapped onto a bus; the + * mock implements them as fields in its softc and exposes them + * through ioctl. The structure of the interface is the same as the + * real device's would be, however, so that the test program can be + * adapted to drive a real device with minimal changes. + */ + +#ifndef _MOCKDEV_H_ +#define _MOCKDEV_H_ + +#include + +#define MOCKDEV_DEVICE_NAME "mockdev" + +/* Command codes. The mock recognises only a few specific codes; + * everything else is treated as an unknown command and reported as + * an error in the status register. */ +#define MOCKDEV_CMD_NOP 0x00 /* no operation */ +#define MOCKDEV_CMD_RESET 0x01 /* reset internal state */ +#define MOCKDEV_CMD_READ_ID 0x02 /* read chip identifier */ +#define MOCKDEV_CMD_INCREMENT 0x03 /* increment internal counter */ +#define MOCKDEV_CMD_FAIL 0xfe /* always reports failure */ + +/* Status register bits. */ +#define MOCKDEV_STATUS_BUSY 0x01 +#define MOCKDEV_STATUS_DONE 0x02 +#define MOCKDEV_STATUS_ERROR 0x04 + +/* Constant chip identifier returned by MOCKDEV_CMD_READ_ID. The + * value is a magic number that tests can verify against. */ +#define MOCKDEV_CHIP_ID 0x4d4f434bU /* "MOCK" */ + +/* ioctl interface. Each ioctl operates on a small command/status + * structure that mirrors what a real driver would expose. */ +struct mockdev_op { + uint32_t mo_cmd; /* command code, input */ + uint32_t mo_status; /* status, output */ + uint32_t mo_data; /* result data, output */ +}; + +#define MOCKDEV_IOC_SUBMIT _IOWR('M', 1, struct mockdev_op) +#define MOCKDEV_IOC_READ_STATUS _IOR('M', 2, struct mockdev_op) +#define MOCKDEV_IOC_RESET _IO('M', 3) + +#endif /* _MOCKDEV_H_ */ diff --git a/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev_test.c b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev_test.c new file mode 100644 index 0000000..0cd3449 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab04-mock-device/mockdev_test.c @@ -0,0 +1,174 @@ +/* + * mockdev_test.c - User-space test program for the mock device. + * + * Companion to Chapter 36, Lab 4. + * + * The test program opens /dev/mockdev, sends each of the documented + * command codes, polls for completion, and reports the result. It + * also demonstrates the watchdog pattern: each command is given a + * deadline, and if the device does not complete by the deadline, + * the test reports a failure rather than hanging. + * + * Build with `make test` in this directory. + * + * Usage: + * ./mockdev_test [-d device] + * + * The default device is /dev/mockdev. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mockdev.h" + +#define WATCHDOG_TIMEOUT_MS 1000 +#define POLL_INTERVAL_US 1000 + +static int +poll_completion(int fd, struct mockdev_op *op, int timeout_ms) +{ + struct timespec start, now; + long elapsed_ms; + + if (clock_gettime(CLOCK_MONOTONIC, &start) != 0) + return (-1); + for (;;) { + if (ioctl(fd, MOCKDEV_IOC_READ_STATUS, op) != 0) + return (-1); + if ((op->mo_status & MOCKDEV_STATUS_BUSY) == 0) + return (0); + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) + return (-1); + elapsed_ms = (now.tv_sec - start.tv_sec) * 1000 + + (now.tv_nsec - start.tv_nsec) / 1000000; + if (elapsed_ms >= timeout_ms) { + errno = ETIMEDOUT; + return (-1); + } + usleep(POLL_INTERVAL_US); + } +} + +static int +run_command(int fd, uint32_t cmd, const char *label, + uint32_t *result_data, uint32_t *result_status) +{ + struct mockdev_op op; + int err; + + memset(&op, 0, sizeof(op)); + op.mo_cmd = cmd; + if (ioctl(fd, MOCKDEV_IOC_SUBMIT, &op) != 0) { + warn("submit %s", label); + return (-1); + } + if (poll_completion(fd, &op, WATCHDOG_TIMEOUT_MS) != 0) { + err = errno; + fprintf(stderr, + "%s: poll failed: %s\n", label, strerror(err)); + return (-1); + } + if (result_data != NULL) + *result_data = op.mo_data; + if (result_status != NULL) + *result_status = op.mo_status; + printf("%-12s status=0x%02x data=0x%08x\n", + label, op.mo_status, op.mo_data); + return (0); +} + +int +main(int argc, char **argv) +{ + const char *path = "/dev/mockdev"; + uint32_t data, status; + int fd, ch, failures = 0; + + while ((ch = getopt(argc, argv, "d:h")) != -1) { + switch (ch) { + case 'd': + path = optarg; + break; + case 'h': + default: + fprintf(stderr, + "usage: %s [-d device]\n", argv[0]); + return (ch == 'h' ? 0 : 1); + } + } + + fd = open(path, O_RDWR); + if (fd < 0) + err(1, "open %s", path); + + if (ioctl(fd, MOCKDEV_IOC_RESET, NULL) != 0) + warn("reset"); + + if (run_command(fd, MOCKDEV_CMD_NOP, "NOP", + &data, &status) != 0) + failures++; + + if (run_command(fd, MOCKDEV_CMD_READ_ID, "READ_ID", + &data, &status) != 0) + failures++; + else if (data != MOCKDEV_CHIP_ID) { + fprintf(stderr, + "READ_ID returned 0x%08x, expected 0x%08x\n", + data, MOCKDEV_CHIP_ID); + failures++; + } + + if (run_command(fd, MOCKDEV_CMD_INCREMENT, "INCREMENT", + &data, &status) != 0) + failures++; + else if (data != 1) { + fprintf(stderr, + "INCREMENT returned 0x%08x, expected 1\n", data); + failures++; + } + + if (run_command(fd, MOCKDEV_CMD_INCREMENT, "INCREMENT", + &data, &status) != 0) + failures++; + else if (data != 2) { + fprintf(stderr, + "INCREMENT returned 0x%08x, expected 2\n", data); + failures++; + } + + if (run_command(fd, MOCKDEV_CMD_RESET, "RESET", + &data, &status) != 0) + failures++; + + if (run_command(fd, MOCKDEV_CMD_FAIL, "FAIL", + &data, &status) != 0) { + failures++; + } else if ((status & MOCKDEV_STATUS_ERROR) == 0) { + fprintf(stderr, + "FAIL did not set ERROR status (got 0x%02x)\n", + status); + failures++; + } else { + printf("FAIL correctly reported the ERROR bit.\n"); + } + + close(fd); + + if (failures != 0) { + fprintf(stderr, "\n%d test(s) failed.\n", failures); + return (1); + } + printf("\nAll tests passed.\n"); + return (0); +} diff --git a/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/Makefile b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/Makefile new file mode 100644 index 0000000..de6c4b4 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/Makefile @@ -0,0 +1,6 @@ +KMOD= safeprobe +SRCS= safeprobe.c + +SYSDIR?= /usr/src/sys + +.include diff --git a/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.c b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.c new file mode 100644 index 0000000..cd3f61b --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.c @@ -0,0 +1,160 @@ +/* + * safeprobe.c - Implementation of the safe register-access + * wrappers. + * + * Companion to Chapter 36, Lab 5. + * + * See safeprobe.h for the rationale and the public interface. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "safeprobe.h" + +void +safeprobe_init(struct safeprobe_ctx *ctx, device_t dev, + struct resource *res) +{ + ctx->sp_dev = dev; + ctx->sp_mem = res; + mtx_init(&ctx->sp_mtx, "safeprobe", NULL, MTX_DEF); + ctx->sp_log_reads = 0; + ctx->sp_log_writes = 1; + ctx->sp_read_only = 0; + ctx->sp_n_reads = 0; + ctx->sp_n_writes = 0; + ctx->sp_n_failures = 0; +} + +void +safeprobe_destroy(struct safeprobe_ctx *ctx) +{ + mtx_destroy(&ctx->sp_mtx); + ctx->sp_mem = NULL; +} + +uint32_t +safeprobe_read(struct safeprobe_ctx *ctx, bus_size_t off) +{ + uint32_t val; + + mtx_lock(&ctx->sp_mtx); + val = bus_read_4(ctx->sp_mem, off); + ctx->sp_n_reads++; + if (ctx->sp_log_reads) { + device_printf(ctx->sp_dev, + "safeprobe READ off=0x%04jx val=0x%08x\n", + (uintmax_t)off, val); + } + mtx_unlock(&ctx->sp_mtx); + return (val); +} + +int +safeprobe_write(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t value) +{ + mtx_lock(&ctx->sp_mtx); + if (ctx->sp_read_only) { + if (ctx->sp_log_writes) { + device_printf(ctx->sp_dev, + "safeprobe WRITE-SUPPRESSED off=0x%04jx " + "val=0x%08x (read-only mode)\n", + (uintmax_t)off, value); + } + mtx_unlock(&ctx->sp_mtx); + return (EROFS); + } + if (ctx->sp_log_writes) { + device_printf(ctx->sp_dev, + "safeprobe WRITE off=0x%04jx val=0x%08x\n", + (uintmax_t)off, value); + } + bus_write_4(ctx->sp_mem, off, value); + ctx->sp_n_writes++; + mtx_unlock(&ctx->sp_mtx); + return (0); +} + +int +safeprobe_set_field(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t mask, uint32_t value) +{ + uint32_t old, new, readback; + + mtx_lock(&ctx->sp_mtx); + old = bus_read_4(ctx->sp_mem, off); + new = (old & ~mask) | (value & mask); + + if (ctx->sp_read_only) { + if (ctx->sp_log_writes) { + device_printf(ctx->sp_dev, + "safeprobe SETFIELD-SUPPRESSED off=0x%04jx " + "mask=0x%08x value=0x%08x\n", + (uintmax_t)off, mask, value); + } + mtx_unlock(&ctx->sp_mtx); + return (EROFS); + } + + if (ctx->sp_log_writes) { + device_printf(ctx->sp_dev, + "safeprobe SETFIELD off=0x%04jx mask=0x%08x " + "old=0x%08x new=0x%08x\n", + (uintmax_t)off, mask, old, new); + } + bus_write_4(ctx->sp_mem, off, new); + ctx->sp_n_writes++; + + readback = bus_read_4(ctx->sp_mem, off); + if ((readback & mask) != (value & mask)) { + ctx->sp_n_failures++; + device_printf(ctx->sp_dev, + "safeprobe SETFIELD off=0x%04jx mask=0x%08x " + "value=0x%08x readback=0x%08x mismatch\n", + (uintmax_t)off, mask, value, readback); + mtx_unlock(&ctx->sp_mtx); + return (EIO); + } + mtx_unlock(&ctx->sp_mtx); + return (0); +} + +int +safeprobe_wait(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t mask, uint32_t value, int timeout_us) +{ + uint32_t observed; + int waited_us = 0; + const int step_us = 10; + + for (;;) { + mtx_lock(&ctx->sp_mtx); + observed = bus_read_4(ctx->sp_mem, off); + ctx->sp_n_reads++; + mtx_unlock(&ctx->sp_mtx); + + if ((observed & mask) == (value & mask)) + return (0); + + if (waited_us >= timeout_us) { + ctx->sp_n_failures++; + device_printf(ctx->sp_dev, + "safeprobe WAIT timeout off=0x%04jx " + "mask=0x%08x expected=0x%08x last=0x%08x\n", + (uintmax_t)off, mask, value, observed); + return (ETIMEDOUT); + } + DELAY(step_us); + waited_us += step_us; + } +} diff --git a/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.h b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.h new file mode 100644 index 0000000..de3e728 --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab05-safe-wrapper/safeprobe.h @@ -0,0 +1,70 @@ +/* + * safeprobe.h - Safe register-access wrappers for use during + * reverse-engineering work. + * + * Companion to Chapter 36, Lab 5. + * + * The wrappers in this header combine four safety techniques that + * the chapter recommends: + * + * 1. Logging of every access, so that the kernel log records + * what the driver did against the device. The log can be + * compared against captures of the vendor driver's behaviour. + * + * 2. Read-modify-write-verify for set-field operations. After + * every write that should change a value, the wrapper reads + * the value back and confirms that the change took effect. + * + * 3. Timeout-protected polling. Loops that wait for the device + * to reach a state include a hard deadline; the loop returns + * an error if the deadline expires. + * + * 4. Read-only mode. A flag in the safeprobe context can suppress + * all writes, turning the wrappers into pure-observation tools + * for use early in an investigation. + * + * The wrappers are not specific to any particular device. They are + * meant to be used by any driver-style code that needs disciplined + * access to a memory-mapped resource. + */ + +#ifndef _SAFEPROBE_H_ +#define _SAFEPROBE_H_ + +#ifdef _KERNEL + +#include +#include +#include +#include +#include + +#include + +struct safeprobe_ctx { + device_t sp_dev; + struct resource *sp_mem; + struct mtx sp_mtx; + int sp_log_reads; + int sp_log_writes; + int sp_read_only; + uint64_t sp_n_reads; + uint64_t sp_n_writes; + uint64_t sp_n_failures; +}; + +void safeprobe_init(struct safeprobe_ctx *ctx, device_t dev, + struct resource *res); +void safeprobe_destroy(struct safeprobe_ctx *ctx); + +uint32_t safeprobe_read(struct safeprobe_ctx *ctx, bus_size_t off); +int safeprobe_write(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t value); +int safeprobe_set_field(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t mask, uint32_t value); +int safeprobe_wait(struct safeprobe_ctx *ctx, bus_size_t off, + uint32_t mask, uint32_t value, int timeout_us); + +#endif /* _KERNEL */ + +#endif /* _SAFEPROBE_H_ */ diff --git a/examples/part-07/ch36-reverse-engineering/lab06-pseudo-datasheet/DATASHEET-TEMPLATE.md b/examples/part-07/ch36-reverse-engineering/lab06-pseudo-datasheet/DATASHEET-TEMPLATE.md new file mode 100644 index 0000000..7ba639e --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/lab06-pseudo-datasheet/DATASHEET-TEMPLATE.md @@ -0,0 +1,248 @@ +# Pseudo-Datasheet: + +> Replace `` with the device's marketed name, internal +> codename, or model number. If the device has multiple names +> (manufacturer, distributor, OEM rebrand), list them all in the +> Identity section below. + +**Version:** 0.1-rev +**Last updated:** YYYY-MM-DD +**Status:** Draft / In progress / Stable + +This document is a pseudo-datasheet: a structured account of what +has been learned about the device through reverse engineering. It +is not an official datasheet from the device's manufacturer. Every +fact in this document is tagged with its provenance, so that +readers can judge how much confidence to place in any given claim. + +## 1. Identity + +| Field | Value | Provenance | +|-------|-------|------------| +| Marketed name | | | +| Internal codename | | | +| Vendor | | | +| Vendor ID (USB or PCI) | | | +| Product ID | | | +| Subsystem vendor ID | | | +| Subsystem ID | | | +| Revision | | | +| Form factor | | | +| Bus interface | | | + +**Provenance tag legend.** Each fact in this datasheet is tagged +with one of four levels of confidence: + +- **HIGH**: directly observed by the author; reproducible. +- **MEDIUM**: inferred from observation, with strong supporting + evidence; reproducible but indirect. +- **LOW**: hypothesised from limited observation; not yet + conclusively verified. +- **UNKNOWN**: not yet investigated, or investigated without + conclusive results. + +Any claim in the datasheet may be re-tagged as new evidence +appears. The Git history records the changes. + +## 2. Provenance + +This section describes the methodology used to gather the facts in +the rest of the document. It exists so that any reader can +understand the basis of the work and reproduce it if they wish. + +- **Captures used.** List the captures (pcap files, register + dumps, log files) that informed this datasheet. Reference them + by filename and a one-line description. + +- **Tools used.** List the tools used to gather and analyse the + evidence: `pciconf`, `usbconfig`, `usbdump`, Wireshark, + Ghidra, IDA, radare2, custom scripts, custom kernel modules. + +- **Sources of prior art.** List any public sources consulted: + driver code in other operating systems, vendor patents, leaked + documentation, hobbyist write-ups. Include URLs and access + dates. + +- **Dates of work.** When the investigation began, when it has + been actively worked on, when this version of the document was + last updated. + +- **Cleanroom discipline.** If the work was performed under a + cleanroom procedure to keep it free of derivation from + copyrighted material, describe the procedure briefly. + +## 3. Resources + +This section describes the bus-level resources the device exposes: +memory regions, I/O ports, interrupt lines, DMA channels. + +- **Memory BARs.** For each memory BAR, list the BAR number, size, + alignment, and known purpose. Include the provenance of the + size (read from PCI configuration space) and of the purpose + (inferred from access patterns). + +- **I/O port ranges.** For each I/O range, list the range and + known purpose. + +- **Interrupts.** Describe the interrupt mechanism (legacy INTx, + MSI, MSI-X), the number of vectors used, and the purpose of + each vector if known. + +- **DMA channels.** Describe any DMA channels the device uses, + their direction, addressing capabilities, and known buffer + formats. + +## 4. Register Map + +This is the central section of the datasheet. List every register +that has been identified, with its offset, size, access mode, and +purpose. + +| Offset | Name | Width | Access | Purpose | Provenance | +|--------|------|-------|--------|---------|------------| +| 0x00 | | 32 | RO | | | +| 0x04 | | 32 | RW | | | +| 0x08 | | 32 | W1C | | | +| ... | | | | | | + +Access modes: + +- **RO**: read-only. +- **WO**: write-only (reads return undefined or zero). +- **RW**: read-write. +- **W1C**: write-1-to-clear (writing 1 to a bit clears it). +- **W1S**: write-1-to-set (writing 1 to a bit sets it). +- **RWO**: read-write-once (writable once, then becomes read-only). +- **VOL**: read-volatile (value can change between reads). + +For each register, include a sub-section with the bit-field +breakdown. + +### Register: `` (offset `0xNN`) + +| Bits | Name | Access | Description | Provenance | +|------|------|--------|-------------|------------| +| 31:24 | | | | | +| 23:16 | | | | | +| 15:8 | | | | | +| 7:0 | | | | | + +### Reserved Bits and Offsets + +List any bits or offsets that are known to be reserved (writes +must preserve their current values; reads return undefined data). +Reserved means "do not touch", not "ignore". + +## 5. Buffer Layouts + +If the device uses ring buffers, descriptor rings, or other +in-memory data structures, document them here. + +For each buffer: + +- The C structure that describes one entry. +- The number of entries in the ring (or the size of the ring in + bytes). +- The producer and consumer pointers (which side updates each). +- The synchronisation mechanism (memory barriers, doorbell + registers, interrupts). +- Endianness, if it differs from the host's. +- Provenance for each of these claims. + +## 6. Command Interface + +If the device uses a command/status mailbox or a similar +high-level interface, document it here. + +- The command opcodes, with their parameters and return values. +- The completion mechanism (status register, interrupt, + descriptor completion). +- Error codes and their meanings. +- Any sequencing requirements (commands that must be issued in a + specific order, or that depend on the device's state). + +## 7. Initialisation Sequence + +The exact sequence of operations the driver must perform to bring +the device from reset to operational. Each step should include the +register accesses, the values, and the verification that confirms +the step succeeded. + +``` +1. Soft reset: + - Write 0x80000000 to CTRL (offset 0x00). + - Wait for bit 31 of STATUS (offset 0x04) to clear. + - Timeout: 100 ms. + - Provenance: HIGH (observed in vendor capture, reproducible). + +2. Verify identifier: + - Read CHIP_ID (offset 0xfc). + - Expect 0x4d4f434b. + - On mismatch: abort attach. + - Provenance: HIGH (observed in vendor capture). + +3. ... +``` + +## 8. Operating Patterns + +Common operations performed during normal use, with the register +sequences they generate. This section is the bridge between the +register map and the high-level driver behaviour. + +For each operating pattern: + +- The user-facing operation (e.g., "transmit a packet"). +- The register-access sequence the driver performs. +- The expected device behaviour (counters that change, + interrupts that fire, status bits that toggle). +- Any common pitfalls (race conditions, ordering requirements, + values that must not be written). + +## 9. Quirks and Errata + +A list of unexpected behaviours that the driver must work around. +Each quirk is a fact about the device that no one would have +guessed from a normal reading of the register map. + +For each quirk: + +- A short description. +- The conditions under which it manifests. +- The work-around that the driver applies. +- Whether the quirk is known to be revision-specific. +- Provenance for each claim. + +## 10. Open Questions + +Things you do not yet know about the device. Recording open +questions explicitly is as valuable as recording known facts: it +tells future readers where to focus further investigation. + +For each open question: + +- A clear statement of the question. +- What you have already tried. +- What you would want to try next. +- Why the question matters. + +## 11. References + +External material that informed this datasheet. URLs, documents, +source code, conversations. + +- [ ] Vendor patent: ... +- [ ] Linux driver: ... +- [ ] OpenBSD driver: ... +- [ ] Mailing list discussion: ... +- [ ] Personal correspondence: ... + +## 12. Changelog + +A record of significant updates to this document. Distinct from +the Git history because it summarises the substantive changes +rather than every textual change. + +| Date | Author | Summary | +|------|--------|---------| +| YYYY-MM-DD | | Initial draft. | diff --git a/examples/part-07/ch36-reverse-engineering/shared/build-notes.md b/examples/part-07/ch36-reverse-engineering/shared/build-notes.md new file mode 100644 index 0000000..8b187ff --- /dev/null +++ b/examples/part-07/ch36-reverse-engineering/shared/build-notes.md @@ -0,0 +1,119 @@ +# Build Notes for Chapter 36 Examples + +This file collects the build-related notes that apply across the +chapter's labs. Read it before working through the labs. + +## FreeBSD Version + +The labs are written and tested against FreeBSD 14.3. They use only +public, stable interfaces from `bus_space(9)`, the device driver +framework, and the kernel module Makefile system. They should also +build on FreeBSD 14.x stable branches and on -CURRENT, but minor +adjustments may be required. + +## Source Tree + +You need a copy of the FreeBSD kernel source under `/usr/src/`. The +Makefiles use `SYSDIR?= /usr/src/sys` to locate the kernel headers +and the build infrastructure. If your source tree is in a different +location, override `SYSDIR` on the `make` command line. + +## The `bsd.kmod.mk` Pattern + +Every kernel module in this chapter uses the same minimal Makefile +pattern. The pattern is: + +``` +KMOD= +SRCS= + +SYSDIR?= /usr/src/sys + +.include +``` + +`KMOD` is the module's name. The build will produce a file named +`KMOD.ko` in the build directory. + +`SRCS` lists the source files that make up the module. For modules +that are children of the PCI bus, include the generated header files +`device_if.h`, `bus_if.h`, and `pci_if.h` so that `make` knows to +build them on demand. + +`SYSDIR` points at the kernel source tree. The `?=` form lets the +operator override it without editing the Makefile. + +`bsd.kmod.mk` is the include file that does all the actual work. It +sets up the compiler flags, the linker flags, the dependencies, and +the install rules for kernel modules. + +## Common Build Targets + +After a Makefile of the form above, the standard make targets are: + +- `make` - build the module. +- `make clean` - remove build artifacts. +- `make load` - load the module with `kldload(8)`. +- `make unload` - unload the module with `kldunload(8)`. +- `make install` - install the module to `/boot/modules/`. Most labs + do not need this; load and unload from the build directory + instead. + +If a lab also has user-space test programs, the lab's own README +will document the additional targets used to build them. + +## Loading and Unloading + +Every kernel module in this chapter is designed to be loadable and +unloadable cleanly. The expected workflow is: + +1. Build the module with `make`. +2. Load it with `sudo kldload ./.ko`. +3. Exercise it through whatever interface the lab provides (sysctls, + device files, test programs). +4. Unload it with `sudo kldunload `. + +The leading `./` on `kldload` is important. It tells `kldload(8)` +to load the module from the current directory rather than from the +system module path. + +## Permissions + +Loading and unloading kernel modules requires root. Use `sudo` (or +`doas`, if you prefer) to execute the commands. + +The sysctls exposed by the modules are readable by anyone by +default. The lab READMEs document which sysctls are read-only and +which take values, where applicable. + +## Development VM + +All of the labs in this chapter are designed to run safely on a +development virtual machine. None of them deliberately panics the +kernel, but a bug in your variants of the code can. Using a VM means +that a panic costs you a few seconds of reboot time, not a +disrupted host system. + +A 4 GB VM with 20 GB of disk and a recent FreeBSD 14.3 install is +more than enough for everything in this chapter. + +## Cleaning Up + +Each lab includes `make clean` in its Makefile. Running it after you +are done with a lab removes build artifacts and keeps the working +directory tidy. + +If you load a module and forget to unload it, `kldstat -v` will show +it in the loaded list. You can unload it from there with +`kldunload `. If a module refuses to unload (the kernel reports +that it is in use), check whether you have a process with an open +file descriptor on a device node the module created. + +## Safety Reminder + +Read Section 10 of the chapter before attaching any of these +modules to real hardware. The `regprobe` module is read-only by +construction, but the act of attaching any kernel module to an +unknown device is itself an action that should be performed +deliberately, not casually. The chapter's safety advice applies to +the lab work as much as to real reverse engineering. diff --git a/examples/part-07/ch37-upstream/cover-letter.txt b/examples/part-07/ch37-upstream/cover-letter.txt new file mode 100644 index 0000000..94711a1 --- /dev/null +++ b/examples/part-07/ch37-upstream/cover-letter.txt @@ -0,0 +1,88 @@ +To: freebsd-hackers@FreeBSD.org +Subject: New driver: FooCorp FC100 sensor boards + +Hello, + +I am proposing a new driver, mydev(4), for FooCorp FC100 +PCI-attached environmental sensor boards. The boards are +documented in the FC100 Programmer's Reference Manual v1.4 from +FooCorp, which is publicly available. I have two hardware units +to test against (one rev 1.0 and one rev 1.1) and I have +additionally verified FC200 compatibility mode against a third +unit. + +What the driver provides +------------------------ + +The driver implements probe/attach/detach through the standard +Newbus framework and exposes a character device at /dev/mydevN +for userland interaction. Userland programs can read sampled +sensor data by open(2)/read(2) on the device node. The sampling +interval is tunable via sysctl. + +The driver is organised as: + + * sys/dev/mydev/mydev.c - main driver source + * sys/dev/mydev/mydev.h - internal header + * sys/dev/mydev/mydevreg.h - hardware register definitions + * sys/modules/mydev/Makefile - loadable module Makefile + * share/man/man4/mydev.4 - manual page + +The total diff is approximately 620 lines of C and 95 lines of +mdoc. + +Hardware supported +------------------ + + * FooCorp FC100 rev 1.0 + * FooCorp FC100 rev 1.1 + * FooCorp FC200 in FC100-compatibility mode + +Testing performed +----------------- + + * Runs cleanly on amd64 and arm64. + * mandoc -Tlint share/man/man4/mydev.4 is silent. + * /usr/src/tools/build/checkstyle9.pl is clean against every + .c and .h file. + * make universe completed without warnings against this driver + on the last full run. + * kldload/kldunload cycle repeated 50 times on amd64 without + leaks (confirmed with vmstat -m) or panics. + * A small userland test program that opens /dev/mydev0, reads + 1000 samples, and exits has been run under witness(4) and + produces no warnings. + +Design questions I would welcome feedback on +-------------------------------------------- + + * Is a character device the right primary interface for a + sensor driver of this shape, or would a sysctl tree be more + idiomatic? I chose the character-device interface because + the board also supports streaming mode, but I have not yet + implemented streaming and am open to reconsidering. + * The sysctl hierarchy uses hw.mydev.unit.interval_ms for the + sampling interval. I would welcome naming feedback. + * The driver uses a single BAR and a single IRQ. MSI-X is not + supported by the hardware. If that constraint affects the + review, please flag it. + +Review routing +-------------- + +I intend to open a Phabricator review once any early feedback +from this list has been incorporated. The working branch lives +at https://github.com//freebsd-src/tree/mydev-driver for +anyone who would like to read the code before it appears in +Phabricator. + +I am new to the FreeBSD contribution process. I have read +CONTRIBUTING.md and the relevant sections of Chapter 37 of +"FreeBSD Device Drivers: From First Steps to Kernel Mastery," +and I have done my best to follow the project's conventions. +If I have missed anything obvious, I would rather hear about it +now than in review. + +Thanks for reading. I look forward to the feedback. + +Your Name diff --git a/examples/part-07/ch37-upstream/sample-driver/Makefile b/examples/part-07/ch37-upstream/sample-driver/Makefile new file mode 100644 index 0000000..4619368 --- /dev/null +++ b/examples/part-07/ch37-upstream/sample-driver/Makefile @@ -0,0 +1,7 @@ +.PATH: ${SRCTOP}/sys/dev/mydev + +KMOD= mydev +SRCS= mydev.c +SRCS+= bus_if.h device_if.h pci_if.h + +.include diff --git a/examples/part-07/ch37-upstream/sample-driver/mydev.c b/examples/part-07/ch37-upstream/sample-driver/mydev.c new file mode 100644 index 0000000..98c6ec3 --- /dev/null +++ b/examples/part-07/ch37-upstream/sample-driver/mydev.c @@ -0,0 +1,102 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include + +static int mydev_probe(device_t dev); +static int mydev_attach(device_t dev); +static int mydev_detach(device_t dev); + +static int +mydev_probe(device_t dev) +{ + /* + * Match your PCI vendor/device ID here. Returning ENXIO + * from the skeleton means the driver will never attach + * to any real hardware; that is intentional for a + * template. Replace the body with a vendor/device ID + * check and device_set_desc() once you have real + * hardware to match. + */ + return (ENXIO); +} + +static int +mydev_attach(device_t dev) +{ + /* + * Allocate resources, initialise the device, set up + * interrupts, and create any device nodes here. The + * skeleton returns 0 without doing anything because the + * probe routine above never matches. + */ + return (0); +} + +static int +mydev_detach(device_t dev) +{ + /* + * Release resources and quiesce the device here. Undo + * everything attach() did, in reverse order. + */ + return (0); +} + +static device_method_t mydev_methods[] = { + DEVMETHOD(device_probe, mydev_probe), + DEVMETHOD(device_attach, mydev_attach), + DEVMETHOD(device_detach, mydev_detach), + DEVMETHOD_END +}; + +static driver_t mydev_driver = { + "mydev", + mydev_methods, + sizeof(struct mydev_softc), +}; + +DRIVER_MODULE(mydev, pci, mydev_driver, 0, 0); +MODULE_VERSION(mydev, 1); +MODULE_DEPEND(mydev, pci, 1, 1, 1); diff --git a/examples/part-07/ch37-upstream/sample-driver/mydev.h b/examples/part-07/ch37-upstream/sample-driver/mydev.h new file mode 100644 index 0000000..70a984a --- /dev/null +++ b/examples/part-07/ch37-upstream/sample-driver/mydev.h @@ -0,0 +1,50 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _DEV_MYDEV_MYDEV_H_ +#define _DEV_MYDEV_MYDEV_H_ + +/* + * Per-instance driver state. The softc is the private scratch + * space that FreeBSD's Newbus framework hands back to the driver + * on every call. Store your device_t, bus-resource pointers, + * and any per-instance state that needs to survive across + * invocations of the driver's method table. + */ +struct mydev_softc { + device_t sc_dev; + struct resource *sc_mem_res; + int sc_mem_rid; + struct resource *sc_irq_res; + int sc_irq_rid; + void *sc_irq_cookie; +}; + +#endif /* _DEV_MYDEV_MYDEV_H_ */ diff --git a/examples/part-07/ch37-upstream/sample-driver/mydevreg.h b/examples/part-07/ch37-upstream/sample-driver/mydevreg.h new file mode 100644 index 0000000..d64fdb0 --- /dev/null +++ b/examples/part-07/ch37-upstream/sample-driver/mydevreg.h @@ -0,0 +1,71 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _DEV_MYDEV_MYDEVREG_H_ +#define _DEV_MYDEV_MYDEVREG_H_ + +/* + * Hardware register definitions for the FooCorp FC100 sensor + * board. Register offsets are relative to the BAR0 base + * address. Values are from the FC100 Programmer's Reference + * Manual v1.4. + * + * This file intentionally contains only register-layout + * information, not driver logic. Keeping the layout in a + * separate header makes it easy to share with test harnesses, + * userland tools, and reverse-engineering scripts. + */ + +/* PCI identifiers. */ +#define MYDEV_VENDOR_ID 0xFEED +#define MYDEV_DEVICE_ID_FC100 0x0100 +#define MYDEV_DEVICE_ID_FC200 0x0200 + +/* BAR0 register offsets. */ +#define MYDEV_REG_ID 0x00 /* RO: device and revision */ +#define MYDEV_REG_CTRL 0x04 /* RW: control */ +#define MYDEV_REG_STATUS 0x08 /* RO: status */ +#define MYDEV_REG_DATA 0x0C /* RW: data sample */ + +/* CTRL register bits. */ +#define MYDEV_CTRL_ENABLE (1u << 0) +#define MYDEV_CTRL_IRQ_ENABLE (1u << 1) +#define MYDEV_CTRL_RESET (1u << 7) + +/* STATUS register bits. */ +#define MYDEV_STATUS_READY (1u << 0) +#define MYDEV_STATUS_BUSY (1u << 1) +#define MYDEV_STATUS_ERROR (1u << 2) + +/* Revision field decoded from MYDEV_REG_ID. */ +#define MYDEV_ID_REV_MASK 0x000000FFu +#define MYDEV_ID_REV_SHIFT 0 + +#endif /* _DEV_MYDEV_MYDEVREG_H_ */ diff --git a/examples/part-07/ch37-upstream/sample-manpage/mydev.4 b/examples/part-07/ch37-upstream/sample-manpage/mydev.4 new file mode 100644 index 0000000..f6248b4 --- /dev/null +++ b/examples/part-07/ch37-upstream/sample-manpage/mydev.4 @@ -0,0 +1,94 @@ +.\"- +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2026 Your Name +.\" +.\" Redistribution and use in source and binary forms, with or +.\" without modification, are permitted provided that the +.\" following conditions are met: +.\" 1. Redistributions of source code must retain the above +.\" copyright notice, this list of conditions and the following +.\" disclaimer. +.\" 2. Redistributions in binary form must reproduce the above +.\" copyright notice, this list of conditions and the following +.\" disclaimer in the documentation and/or other materials +.\" provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY +.\" EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +.\" THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +.\" PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +.\" AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +.\" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +.\" LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +.\" EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +.\" +.Dd April 20, 2026 +.Dt MYDEV 4 +.Os +.Sh NAME +.Nm mydev +.Nd driver for FooCorp FC100 sensor boards +.Sh SYNOPSIS +To compile this driver into the kernel, +place the following line in your +kernel configuration file: +.Bd -ragged -offset indent +.Cd "device mydev" +.Ed +.Pp +Alternatively, to load the driver as a +module at boot time, place the following line in +.Xr loader.conf 5 : +.Bd -literal -offset indent +mydev_load="YES" +.Ed +.Sh DESCRIPTION +The +.Nm +driver provides support for FooCorp FC100 series PCI-attached +environmental sensor boards. +It exposes a character device at +.Pa /dev/mydev0 +that userland programs can open, read, and write using standard +system calls. +.Pp +Each attached board is enumerated with an integer unit number +beginning at 0. +The driver supports probe, attach, and detach through the +standard Newbus framework. +.Sh HARDWARE +The +.Nm +driver supports the following hardware: +.Pp +.Bl -bullet -compact +.It +FooCorp FC100 rev 1.0 +.It +FooCorp FC100 rev 1.1 +.It +FooCorp FC200 (compatibility mode) +.El +.Sh FILES +.Bl -tag -width ".Pa /dev/mydev0" +.It Pa /dev/mydev0 +First unit of the driver. +.El +.Sh SEE ALSO +.Xr pci 4 +.Sh HISTORY +The +.Nm +driver first appeared in +.Fx 15.0 . +.Sh AUTHORS +.An -nosplit +The +.Nm +driver and this manual page were written by +.An Your Name Aq Mt you@example.com . diff --git a/examples/part-07/ch37-upstream/scripts/make-patch.sh b/examples/part-07/ch37-upstream/scripts/make-patch.sh new file mode 100755 index 0000000..c11f609 --- /dev/null +++ b/examples/part-07/ch37-upstream/scripts/make-patch.sh @@ -0,0 +1,157 @@ +#!/bin/sh +# +# make-patch.sh +# +# Generate a single-commit patch file for a driver topic branch, +# with sanity checks for the things reviewers most commonly +# reject. Companion to Chapter 37 of "FreeBSD Device Drivers: +# From First Steps to Kernel Mastery." +# +# The script assumes you have committed your driver as a single +# commit on a topic branch that was created off of origin/main. +# +# Usage: +# cd /usr/src +# /path/to/make-patch.sh [output-directory] +# +# The default output directory is the current directory. The +# generated patch file will be named something like +# 0001-mydev-Add-driver-for-FooCorp-FC100-sensor-boards.patch +# +# Exit code 0 means the patch was generated and passed the +# sanity checks. Non-zero means a check failed. + +set -e + +OUTDIR=${1:-.} + +# ----- helpers ----- + +stage() { + printf '\n=== %s ===\n' "$1" +} + +fail() { + printf '\n*** FAIL: %s ***\n' "$1" >&2 + exit 1 +} + +# ----- sanity checks ----- + +stage "sanity checks" + +command -v git >/dev/null 2>&1 || fail "git is not installed" + +[ -d .git ] || fail "not a git repository (run from the top of the tree)" + +BRANCH=$(git rev-parse --abbrev-ref HEAD) +if [ "$BRANCH" = "main" ] || [ "$BRANCH" = "master" ]; then + fail "on $BRANCH branch; patches must be generated from a topic branch" +fi + +echo "branch: $BRANCH" + +# Verify the branch diverges from origin/main by exactly one commit. +BASE=$(git merge-base HEAD origin/main 2>/dev/null) \ + || fail "cannot find merge base with origin/main" + +AHEAD=$(git rev-list --count "${BASE}..HEAD") +if [ "$AHEAD" -eq 0 ]; then + fail "branch has no commits ahead of origin/main" +fi +if [ "$AHEAD" -gt 1 ]; then + printf 'branch has %s commits ahead of origin/main.\n' "$AHEAD" >&2 + printf 'a driver submission should be a single commit.\n' >&2 + printf 'consider: git rebase -i origin/main\n' >&2 + fail "multiple commits; squash before submitting" +fi + +echo "branch is exactly 1 commit ahead of origin/main." + +# ----- commit-message checks ----- + +stage "commit-message checks" + +SUBJECT=$(git log -1 --pretty=%s HEAD) +BODY=$(git log -1 --pretty=%b HEAD) + +echo "subject: $SUBJECT" + +# Subject should be under 72 characters. +if [ "$(printf '%s' "$SUBJECT" | wc -c)" -gt 72 ]; then + fail "subject line exceeds 72 characters" +fi + +# Subject should follow subsystem: description form. +case "$SUBJECT" in + *:\ *) ;; + *) fail "subject does not follow 'subsystem: description' form" ;; +esac + +# Body should wrap at 72 columns. +if printf '%s' "$BODY" | awk '{ if (length($0) > 72) exit 1 }'; then + : +else + fail "commit-message body has a line longer than 72 columns" +fi + +# Look for Signed-off-by. +if ! printf '%s' "$BODY" | grep -q '^Signed-off-by: '; then + printf 'warning: no Signed-off-by line in commit body.\n' >&2 + printf 'consider: git commit --amend -s\n' >&2 +fi + +echo "commit message looks well-formed." + +# ----- working-tree checks ----- + +stage "working-tree checks" + +if [ -n "$(git status --porcelain)" ]; then + fail "working tree is dirty; commit or stash before generating patch" +fi + +# Trailing whitespace in the diff. +if git show HEAD | grep -nE '\^I$|[ ]+$' >/dev/null; then + git show HEAD | grep -nE '^\+.*[ ]+$' || true + fail "diff contains trailing whitespace" +fi + +echo "working tree is clean and diff has no trailing whitespace." + +# ----- generate the patch ----- + +stage "generating patch" + +mkdir -p "$OUTDIR" +PATCH_FILE=$(git format-patch -1 HEAD -o "$OUTDIR" | tail -n 1) + +if [ -z "$PATCH_FILE" ] || [ ! -f "$PATCH_FILE" ]; then + fail "git format-patch did not produce a file" +fi + +echo "patch file: $PATCH_FILE" + +# ----- verify the patch applies cleanly ----- + +stage "verifying the patch applies cleanly" + +# Use a scratch worktree rooted at origin/main to test application. +WORKDIR=$(mktemp -d) +trap 'rm -rf "$WORKDIR"' EXIT + +git worktree add --detach "$WORKDIR" origin/main >/dev/null +( + cd "$WORKDIR" || fail "cannot cd to scratch worktree" + git am --abort >/dev/null 2>&1 || true + git am "$PATCH_FILE" >/dev/null +) +git worktree remove --force "$WORKDIR" + +echo "patch applies cleanly to a fresh origin/main tree." + +# ----- done ----- + +stage "patch is ready for submission" +echo "file: $PATCH_FILE" +echo "next: open a Phabricator review or a GitHub PR." diff --git a/examples/part-07/ch37-upstream/scripts/pre-submission-test.sh b/examples/part-07/ch37-upstream/scripts/pre-submission-test.sh new file mode 100755 index 0000000..7933a0a --- /dev/null +++ b/examples/part-07/ch37-upstream/scripts/pre-submission-test.sh @@ -0,0 +1,134 @@ +#!/bin/sh +# +# pre-submission-test.sh +# +# Run the standard pre-submission pipeline for a FreeBSD driver +# before opening a review. This script is a companion to +# Chapter 37 of "FreeBSD Device Drivers: From First Steps to +# Kernel Mastery." +# +# It assumes a conventional file layout: +# +# $SRC: /usr/src/sys/dev// +# $MOD: /usr/src/sys/modules// +# $MAN: /usr/src/share/man/man4/.4 +# +# Edit the NAME and ARCH variables to match your driver and the +# architecture you want to cross-build for. +# +# Usage: +# ./pre-submission-test.sh +# +# Exit code 0 means every stage passed. Non-zero means a stage +# failed; the script's -e flag stops the pipeline at the first +# failing command. + +set -e + +# ----- configuration ----- + +NAME=${NAME:-mydev} +ARCH=${ARCH:-arm64} +SRC=${SRC:-/usr/src/sys/dev/${NAME}} +MOD=${MOD:-/usr/src/sys/modules/${NAME}} +MAN=${MAN:-/usr/src/share/man/man4/${NAME}.4} + +CHECKSTYLE=${CHECKSTYLE:-/usr/src/tools/build/checkstyle9.pl} + +# ----- helpers ----- + +stage() { + printf '\n=== %s ===\n' "$1" +} + +fail() { + printf '\n*** FAIL: %s ***\n' "$1" >&2 + exit 1 +} + +require_file() { + [ -e "$1" ] || fail "missing: $1" +} + +require_dir() { + [ -d "$1" ] || fail "missing directory: $1" +} + +# ----- sanity checks ----- + +stage "sanity checks" +require_dir "$SRC" +require_dir "$MOD" +require_file "$MAN" +require_file "$CHECKSTYLE" +echo "source directory: $SRC" +echo "module directory: $MOD" +echo "manual page: $MAN" +echo "style checker: $CHECKSTYLE" + +# ----- style check ----- + +stage "style check (checkstyle9.pl)" +# shellcheck disable=SC2086 +perl "$CHECKSTYLE" "$SRC"/*.c "$SRC"/*.h + +# ----- mandoc lint ----- + +stage "manual-page lint (mandoc -Tlint)" +mandoc -Tlint "$MAN" + +# ----- optional igor pass ----- + +if command -v igor >/dev/null 2>&1; then + stage "manual-page prose check (igor)" + igor "$MAN" || fail "igor reported issues" +else + stage "igor not installed; skipping prose check" +fi + +# ----- local build ----- + +stage "local build (make clean && make obj && make depend && make)" +( + cd "$MOD" || fail "cannot cd to $MOD" + make clean + make obj + make depend + make +) + +# ----- load and unload ----- + +KO_PATH="$MOD/${NAME}.ko" + +if [ ! -f "$KO_PATH" ]; then + # Some module builds place the .ko under an obj tree. + KO_PATH=$(find "$MOD" -name "${NAME}.ko" -print -quit) +fi + +if [ -z "$KO_PATH" ] || [ ! -f "$KO_PATH" ]; then + fail "built module not found for $NAME" +fi + +stage "load/unload cycle (kldload / kldunload)" +echo "loading: $KO_PATH" +sudo kldload "$KO_PATH" + +echo "verifying: kldstat" +kldstat | grep -F "$NAME" || fail "module $NAME not listed by kldstat" + +echo "unloading: $NAME" +sudo kldunload "$NAME" + +# ----- cross-architecture build ----- + +stage "cross-architecture build (TARGET=${ARCH} buildkernel)" +( + cd /usr/src || fail "cannot cd to /usr/src" + make TARGET="${ARCH}" buildkernel KERNCONF=GENERIC +) + +# ----- done ----- + +stage "all pre-submission tests passed" +echo "driver ${NAME} is ready for review." diff --git a/examples/part-07/ch37-upstream/submission-checklist.md b/examples/part-07/ch37-upstream/submission-checklist.md new file mode 100644 index 0000000..44554f1 --- /dev/null +++ b/examples/part-07/ch37-upstream/submission-checklist.md @@ -0,0 +1,151 @@ +# Pre-Submission Checklist + +This checklist mirrors the gates a FreeBSD reviewer will apply to +a new driver submission. Use it as a starting point and adapt it +to your own driver. Type your own version in your own words. +A checklist you have typed yourself will be more useful than one +you copied verbatim: the act of typing forces you to think about +each item. + +Treat every item as a blocker. Do not submit until you can tick +every box with full confidence. + +## File Layout + +- [ ] Driver sources live under `sys/dev//`. +- [ ] The main source file is named `.c`. +- [ ] The internal header, if any, is named `.h`. +- [ ] Hardware register definitions, if any, live in + `reg.h`. +- [ ] The module Makefile lives at `sys/modules//Makefile`. +- [ ] The manual page lives at `share/man/man4/.4`. +- [ ] No files live in ad-hoc locations outside these paths. + +## Copyright Headers + +- [ ] Every `.c` and `.h` file starts in column 1 with `/*-`. +- [ ] Every file has an `SPDX-License-Identifier:` line + immediately after the opening marker. +- [ ] The SPDX code matches the licence text that follows. +- [ ] Every file has at least one `Copyright (c) YEAR Name` line. +- [ ] The licence text matches one of the approved templates + documented in Section 3 of Chapter 37. +- [ ] The manual page uses `.\"-` (with a dash) as its opening + marker, not `.\"`. + +## Code Style + +- [ ] `/usr/src/tools/build/checkstyle9.pl` runs clean against + every `.c` and `.h` file. +- [ ] Indentation uses real tabs, not spaces. +- [ ] Tab stops are set to 8 columns; continuation indents use + 4 spaces. +- [ ] Lines are no longer than 80 columns except where an + exception is warranted (panic strings, grep anchors). +- [ ] Every function that is not declared in a header is + `static`. +- [ ] Return expressions are parenthesised: `return (0);` not + `return 0;`. +- [ ] Variable declarations are grouped at the top of each + function with a blank line separating them from the first + statement. +- [ ] Function definitions have the return type on the line + above the function name, with the name starting in column 1. +- [ ] Identifier names follow the `snake_case` convention, not + `camelCase` or `PascalCase`. + +## Build Integration + +- [ ] The module Makefile includes `bsd.kmod.mk`. +- [ ] `SRCS` lists every `.c` file in the driver, plus any + auto-generated `*_if.h` files that the driver uses. +- [ ] `.PATH` uses `${SRCTOP}/sys/dev/`, not a + hardcoded path. +- [ ] `make` in the module directory succeeds from a clean + tree. +- [ ] `make clean && make obj && make depend && make` produces + a single `.ko` file and no warnings. + +## Runtime + +- [ ] `kldload ` succeeds with no warnings or + error messages. +- [ ] `kldstat` shows the module loaded. +- [ ] The driver detaches cleanly under `kldunload `. +- [ ] A load/unload cycle repeated 50 times produces no kernel + panics, no memory leaks (confirmed with `vmstat -m`), and no + unexpected messages in `dmesg`. +- [ ] If the driver exposes a device node, it is created on + attach and removed on detach. +- [ ] If the driver creates sysctl variables, they appear on + attach and disappear on detach. + +## Cross-Architecture Build + +- [ ] `make universe` completes without errors for the + architectures the driver is expected to support. +- [ ] At a minimum, `amd64` and `arm64` build cleanly. +- [ ] If the driver uses architecture-specific code, every + supported architecture has been tested. + +## Manual Page + +- [ ] `mandoc -Tlint share/man/man4/.4` is silent. +- [ ] The manual page has `NAME`, `SYNOPSIS`, `DESCRIPTION`, + `HARDWARE`, `FILES`, `SEE ALSO`, `HISTORY`, and `AUTHORS` + sections. +- [ ] The `HARDWARE` section uses the `.Bl -bullet -compact` + list style required by `style.mdoc(5)`. +- [ ] Every sentence starts on its own line. +- [ ] `igor(1)` runs clean (optional but recommended). +- [ ] The page renders clearly when viewed with + `mandoc .4 | less -R`. + +## Commit Message + +- [ ] The subject line is in the form + `: `. +- [ ] The subject line is no longer than 72 characters. +- [ ] The body wraps at 72 columns. +- [ ] The body explains what the driver does and why it is + being added. +- [ ] The commit message ends with a `Signed-off-by:` line. +- [ ] The commit message does not reference internal company + URLs, internal ticket IDs, or internal review tools that + external contributors cannot reach. + +## Review Preparation + +- [ ] The submission description is written as a one-paragraph + summary, a design discussion, and a testing summary. +- [ ] The description names the hardware supported and the + versions tested. +- [ ] The description invites feedback on specific design + questions. +- [ ] The branch on which the commit lives is up to date with + `origin/main`. +- [ ] `git show HEAD` reads cleanly end to end. +- [ ] No unrelated files are included in the commit. +- [ ] No trailing whitespace is present. + +## Post-Submission Readiness + +- [ ] You have subscribed to the Bugzilla product for the + driver's subsystem. +- [ ] You have a plan for responding to review feedback within + a reasonable time. +- [ ] You have noted the UPDATING file so you can watch for + tree-wide changes that will affect the driver. +- [ ] You understand that the driver is your long-term + responsibility, not just a one-time submission. + +## Final Gate + +- [ ] Someone other than you has read the patch and the manual + page and thinks both are clear. +- [ ] You can explain, in one paragraph, why this driver + belongs in the tree. +- [ ] You are prepared to iterate on feedback and not be + defensive about the code. + +If every box is ticked, you are ready to submit. diff --git a/examples/part-07/ch38-final-thoughts/scripts/regression-test.sh b/examples/part-07/ch38-final-thoughts/scripts/regression-test.sh new file mode 100755 index 0000000..4d34aac --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/scripts/regression-test.sh @@ -0,0 +1,142 @@ +#!/bin/sh +# +# regression-test.sh +# +# Skeleton regression-test script for a FreeBSD driver. This +# script is a companion to Chapter 38 of "FreeBSD Device +# Drivers: From First Steps to Kernel Mastery." +# +# The intent is to give you a starting point you can adapt to +# the specific behaviours your driver exposes. The skeleton +# exercises the generic lifecycle (build, load, attach, basic +# interaction, detach, unload) and fails loudly at the first +# step that misbehaves. +# +# Edit the NAME and ITERATIONS variables, and then add your +# own driver-specific test functions below the section marked +# "driver-specific tests". +# +# Usage: +# ./regression-test.sh +# +# Exit code 0 means every check passed. Non-zero means a +# check failed; the script's -e flag stops at the first +# failing command. + +set -e + +# ----- configuration ----- + +NAME=${NAME:-mydrv} +MOD=${MOD:-/usr/src/sys/modules/${NAME}} +ITERATIONS=${ITERATIONS:-50} + +# ----- helpers ----- + +stage() { + printf '\n=== %s ===\n' "$1" +} + +fail() { + printf '\n*** FAIL: %s ***\n' "$1" >&2 + exit 1 +} + +# ----- sanity checks ----- + +stage "sanity checks" +[ -d "$MOD" ] || fail "module directory not found: $MOD" +command -v kldstat >/dev/null 2>&1 || fail "kldstat not in PATH" +command -v kldload >/dev/null 2>&1 || fail "kldload not in PATH" +command -v kldunload >/dev/null 2>&1 || fail "kldunload not in PATH" + +# ----- build ----- + +stage "build" +( + cd "$MOD" || fail "cannot cd to $MOD" + make clean + make obj + make depend + make +) + +# ----- locate the .ko ----- + +KO_PATH="$MOD/${NAME}.ko" +if [ ! -f "$KO_PATH" ]; then + KO_PATH=$(find "$MOD" -name "${NAME}.ko" -print -quit) +fi +[ -f "$KO_PATH" ] || fail "built module not found for $NAME" + +# ----- first load and unload ----- + +stage "initial load" +sudo kldload "$KO_PATH" + +stage "verify kldstat" +kldstat | grep -F "$NAME" || fail "module not listed by kldstat" + +# ----- driver-specific tests ----- +# +# Add your own tests here. Examples of the kinds of checks you +# might include: +# - confirm that the expected /dev node exists +# - open /dev/${NAME}0, issue a test ioctl, and read the +# returned value +# - read a sysctl and confirm it has the expected value +# - write a sysctl and confirm the driver reacts +# - push data through a character device and verify round +# trip +# +# Wrap each test in a stage() call so the log is easy to read. +# +# Example: +# stage "verify /dev node" +# [ -c /dev/${NAME}0 ] || fail "missing /dev/${NAME}0" +# +# stage "read sysctl dev.${NAME}.0.status" +# sysctl -n dev.${NAME}.0.status | grep -q ready || \ +# fail "driver not in 'ready' state" +# + +stage "driver-specific tests" +echo "(no driver-specific tests defined yet)" + +# ----- unload ----- + +stage "initial unload" +sudo kldunload "$NAME" + +# ----- load / unload stress loop ----- + +stage "load/unload stress loop (${ITERATIONS} iterations)" +i=1 +while [ "$i" -le "$ITERATIONS" ]; do + printf 'iteration %d of %d\n' "$i" "$ITERATIONS" + sudo kldload "$KO_PATH" + kldstat | grep -F "$NAME" >/dev/null || \ + fail "module not present on iteration $i" + sudo kldunload "$NAME" + i=$((i + 1)) +done + +# ----- memory leak sanity check ----- + +stage "memory leak sanity check (vmstat -m)" +vmstat -m | grep -F "$NAME" || \ + echo "(no entries for $NAME; this is normal for drivers " \ + "that do not name their mallocs)" + +# ----- dmesg scan ----- + +stage "dmesg scan for unexpected messages" +DMESG_OUT=$(dmesg | tail -n 200) +echo "$DMESG_OUT" | grep -Ei "panic|warn|err|fail" | \ + grep -F "$NAME" && \ + fail "unexpected messages in dmesg; review above" + +# ----- done ----- + +stage "all regression checks passed" +echo "driver ${NAME} survived ${ITERATIONS} load/unload cycles." diff --git a/examples/part-07/ch38-final-thoughts/template-driver/share/man/man4/mydrv.4 b/examples/part-07/ch38-final-thoughts/template-driver/share/man/man4/mydrv.4 new file mode 100644 index 0000000..c4997fc --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/template-driver/share/man/man4/mydrv.4 @@ -0,0 +1,68 @@ +.\"- +.\" SPDX-License-Identifier: BSD-2-Clause +.\" +.\" Copyright (c) 2026 Your Name +.\" +.\" Redistribution and use in source and binary forms, with or +.\" without modification, are permitted provided that the +.\" following conditions are met: +.\" 1. Redistributions of source code must retain the above +.\" copyright notice, this list of conditions and the +.\" following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above +.\" copyright notice, this list of conditions and the +.\" following disclaimer in the documentation and/or other +.\" materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY +.\" EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +.\" THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +.\" PARTICULAR PURPOSE ARE DISCLAIMED. +.\" +.Dd April 20, 2026 +.Dt MYDRV 4 +.Os +.Sh NAME +.Nm mydrv +.Nd short description of the driver +.Sh SYNOPSIS +To compile the driver into the kernel, place the following line +in your kernel configuration file: +.Bd -ragged -offset indent +.Cd "device mydrv" +.Ed +.Pp +Alternatively, to load the driver as a module at boot, place +the following line in +.Xr loader.conf 5 : +.Bd -literal -offset indent +mydrv_load="YES" +.Ed +.Sh DESCRIPTION +Describe what the driver does and what sort of device it +supports. +Keep each sentence on its own line as required by +.Xr style.mdoc 5 . +.Sh HARDWARE +The +.Nm +driver supports the following hardware: +.Bl -bullet -compact +.It +Vendor Product, model number +.El +.Sh FILES +.Bl -tag -width ".Pa /dev/mydrv0" -compact +.It Pa /dev/mydrv0 +character-device node for the first attached instance +.El +.Sh SEE ALSO +.Xr pci 4 , +.Xr style 9 +.Sh HISTORY +The +.Nm +driver first appeared in +.Fx 14.3 . +.Sh AUTHORS +.An Your Name Aq Mt you@example.com diff --git a/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.c b/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.c new file mode 100644 index 0000000..8396231 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.c @@ -0,0 +1,110 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include + +static int mydrv_probe(device_t dev); +static int mydrv_attach(device_t dev); +static int mydrv_detach(device_t dev); + +static int +mydrv_probe(device_t dev) +{ + /* + * Replace the ENXIO return with a real vendor/device ID + * check and a call to device_set_desc() once you have + * hardware to match against. + */ + return (ENXIO); +} + +static int +mydrv_attach(device_t dev) +{ + struct mydrv_softc *sc; + + sc = device_get_softc(dev); + sc->dev = dev; + mtx_init(&sc->mtx, device_get_nameunit(dev), NULL, MTX_DEF); + + /* + * Allocate bus resources, map registers, set up interrupts, + * and create any device nodes here. Undo each step on error + * before returning, in reverse order. + */ + return (0); +} + +static int +mydrv_detach(device_t dev) +{ + struct mydrv_softc *sc; + + sc = device_get_softc(dev); + + /* + * Release resources in reverse order of attach(). + */ + mtx_destroy(&sc->mtx); + return (0); +} + +static device_method_t mydrv_methods[] = { + DEVMETHOD(device_probe, mydrv_probe), + DEVMETHOD(device_attach, mydrv_attach), + DEVMETHOD(device_detach, mydrv_detach), + DEVMETHOD_END +}; + +static driver_t mydrv_driver = { + "mydrv", + mydrv_methods, + sizeof(struct mydrv_softc), +}; + +DRIVER_MODULE(mydrv, pci, mydrv_driver, 0, 0); +MODULE_VERSION(mydrv, 1); +MODULE_DEPEND(mydrv, pci, 1, 1, 1); diff --git a/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.h b/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.h new file mode 100644 index 0000000..083b3e2 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/template-driver/sys/dev/mydrv/mydrv.h @@ -0,0 +1,39 @@ +/*- + * SPDX-License-Identifier: BSD-2-Clause + * + * Copyright (c) 2026 Your Name + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. + */ + +#ifndef _DEV_MYDRV_MYDRV_H_ +#define _DEV_MYDRV_MYDRV_H_ + +#include +#include + +struct mydrv_softc { + device_t dev; + struct mtx mtx; + + /* + * Add resource handles, bus_space tags, interrupt + * cookies, and any per-device state below. + */ +}; + +#endif /* _DEV_MYDRV_MYDRV_H_ */ diff --git a/examples/part-07/ch38-final-thoughts/template-driver/sys/modules/mydrv/Makefile b/examples/part-07/ch38-final-thoughts/template-driver/sys/modules/mydrv/Makefile new file mode 100644 index 0000000..83d977c --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/template-driver/sys/modules/mydrv/Makefile @@ -0,0 +1,7 @@ +.PATH: ${SRCTOP}/sys/dev/mydrv + +KMOD= mydrv +SRCS= mydrv.c +SRCS+= bus_if.h device_if.h pci_if.h + +.include diff --git a/examples/part-07/ch38-final-thoughts/templates/code-review-checklist.md b/examples/part-07/ch38-final-thoughts/templates/code-review-checklist.md new file mode 100644 index 0000000..4516ea3 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/code-review-checklist.md @@ -0,0 +1,110 @@ +# Code Review Checklist + +Use this checklist whenever you sit down to review a change, +whether the change is your own before submitting or someone +else's before approving. A consistent pass over the same set of +concerns catches more problems than a free-form read. + +**Change under review:** _________ + +**Reviewer:** _________ + +**Date:** _________ + +--- + +## Understanding + +- [ ] I understand what the change is trying to accomplish + and can restate its purpose in one sentence. +- [ ] The commit message explains the "why" clearly. +- [ ] The commit message will still make sense to someone + reading it five years from now. + +## Scope + +- [ ] The change is scoped appropriately: not so large that + it cannot be reviewed carefully, not so small that the + context is missing. +- [ ] The change does not mix unrelated concerns (cleanup + plus feature, refactor plus bug fix). +- [ ] Any incidental cleanup that did sneak in is small + enough to be worth keeping in the same commit. + +## Correctness + +- [ ] Every function added or modified has a clear + responsibility and a clear contract. +- [ ] Error paths are handled rather than silently + swallowed. +- [ ] Resources allocated in attach() are released in + detach() in reverse order. +- [ ] Any new locks are named clearly and their scope is + explicit. +- [ ] The lock order is consistent with existing code. +- [ ] There is no potential for use-after-free, leaked + references, or double-free. +- [ ] Integer arithmetic is checked for overflow where + appropriate. +- [ ] String operations use safe variants. + +## Style + +- [ ] The change passes `checkstyle9.pl`. +- [ ] Identifier names follow the project conventions. +- [ ] Comments explain only what is not obvious from the + code itself. +- [ ] No commented-out code is present. + +## Build and Test + +- [ ] The change compiles on at least two architectures with + no new warnings. +- [ ] The change does not break any in-tree test. +- [ ] The change has a test case or a clear reason why no + test is possible. +- [ ] The change passes the author's regression test suite. + +## Documentation + +- [ ] Any manual pages affected by the change have been + updated. +- [ ] Any `sysctl` or `dev.` names introduced are named + consistently with existing conventions. +- [ ] Any user-visible behaviour change has a + release-notes-worthy summary. + +## Operational + +- [ ] The change behaves correctly under load and unload + cycles. +- [ ] The change does not introduce a regression in boot + time, attach time, or power consumption. +- [ ] The change does not log excessively at default + verbosity. + +--- + +## Tone (When Reviewing Others) + +- [ ] My comments are respectful. +- [ ] My comments are specific (pointing to a line, an + assumption, or a source) rather than abrupt dismissals. +- [ ] When I propose a different approach, I explain why. +- [ ] I have separated "must change" from "nice to have" + in my feedback. +- [ ] I have acknowledged at least one thing the author + did well. + +--- + +## Notes + +Use the space below for specific comments, open questions, or +things you want to come back to after the first pass. + +_________ + +_________ + +_________ diff --git a/examples/part-07/ch38-final-thoughts/templates/contribution-checklist.md b/examples/part-07/ch38-final-thoughts/templates/contribution-checklist.md new file mode 100644 index 0000000..90ba8ee --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/contribution-checklist.md @@ -0,0 +1,105 @@ +# Contribution Checklist + +Use this checklist the first time you send a patch to the +FreeBSD Project, and every time after that. It mirrors the +gates a reviewer will apply and helps you catch avoidable +issues before the reviewer has to point them out. + +Treat every box as a blocker. Do not submit until each item is +ticked with confidence. + +## Scope and Purpose + +- [ ] My patch addresses a specific, well-defined issue or + adds a specific, well-defined feature. +- [ ] The patch does not mix unrelated concerns. +- [ ] I can state the "why" of the change in one sentence. +- [ ] The change is the right size for reviewers to read + carefully in a single sitting. + +## Build Integrity + +- [ ] The patch applies cleanly to the current tip of the + relevant branch. +- [ ] The patch builds on amd64 without warnings. +- [ ] The patch builds on at least one other architecture + (typically arm64) without warnings. +- [ ] The patch does not introduce new `make universe` + failures. + +## Style and Conventions + +- [ ] `checkstyle9.pl` runs clean against every `.c` and `.h` + file. +- [ ] Every sentence in the manual page starts on its own + line. +- [ ] Identifier names follow the project's `snake_case` + conventions. +- [ ] Return statements are parenthesised: `return (0);` not + `return 0;`. +- [ ] No trailing whitespace is present. + +## Testing + +- [ ] I have run my pre-submission test pipeline end to end + and every stage passes. +- [ ] I have performed at least 50 load/unload cycles with no + panics, no leaks, and no unexpected messages in `dmesg`. +- [ ] I have run any relevant in-tree tests (for example + Kyua suites) and they pass. +- [ ] If the change is subtle, I have written at least one + test case that catches the specific behaviour. + +## Documentation + +- [ ] I have written or updated the relevant manual page. +- [ ] `mandoc -Tlint` is silent on the updated manual page. +- [ ] I have updated any README, UPDATING notice, or release + note that the change implies. +- [ ] I have added or updated comments only where they + genuinely clarify intent. + +## Commit Message + +- [ ] The subject line is in the form + `: `. +- [ ] The subject line is no longer than 72 characters. +- [ ] The body wraps at 72 columns. +- [ ] The body explains what the change does and why. +- [ ] The commit message ends with a `Signed-off-by:` line. +- [ ] The commit message does not reference internal company + URLs, internal ticket IDs, or internal review tools. + +## Privacy and Sensitivity + +- [ ] The patch contains no proprietary information. +- [ ] The patch does not include private correspondence or + mailing-list content. +- [ ] The patch does not embed credentials, API keys, or + other secrets. +- [ ] The patch does not include debugging output or + personal scratch files. + +## Review Preparation + +- [ ] I have identified the reviewer(s) I will request. +- [ ] I have chosen the appropriate submission channel: + Phabricator for structured review, GitHub pull request or + mailing list otherwise. +- [ ] I have written the review description as a + one-paragraph summary, a design discussion, and a testing + summary. +- [ ] I have named the hardware supported and the versions + tested. +- [ ] I have invited feedback on the specific design + questions that worry me. + +## Long-Term Readiness + +- [ ] I have a plan for responding to review feedback within + a reasonable time. +- [ ] I have subscribed to notifications for the review. +- [ ] I understand that merging the patch is a beginning, + not an end, and I am prepared to maintain the code. +- [ ] I have noted the UPDATING file so I can watch for + tree-wide changes that will affect this code. diff --git a/examples/part-07/ch38-final-thoughts/templates/debugging-journal.md b/examples/part-07/ch38-final-thoughts/templates/debugging-journal.md new file mode 100644 index 0000000..68828ce --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/debugging-journal.md @@ -0,0 +1,127 @@ +# Debugging Journal Entry + +Use one entry of this template for each bug that takes more +than a single short session to diagnose. Keep entries together +in a single file or folder, so that over time they become a +personal reference you can search. + +The most valuable fields are the last two (what you learned and +what you would look at sooner next time). Fill them in even +when you feel the bug is self-explanatory. + +--- + +**Date:** _________ + +**Module or driver:** _________ + +**Kernel version:** _________ + +**Hardware involved:** _________ + +--- + +## One-Line Description of the Symptom + +_________ + +## What I Observed First + +Describe the exact behaviour that made you realise something +was wrong. Include dmesg fragments, console output, or stack +traces when available. + +_________ + +## First Hypothesis + +What did you think the bug was, before investigating? + +_________ + +## How I Tested the First Hypothesis + +Describe the specific actions you took to test the hypothesis. + +_________ + +## What Happened Instead + +What did the test reveal? If the first hypothesis held, say +so. If it did not, describe the surprising observation. + +_________ + +## Subsequent Hypotheses + +If the first hypothesis was wrong, list each subsequent one, +with a short note on how you tested it and what you found. + +- Hypothesis 2: _________ + + Test: _________ + + Result: _________ + +- Hypothesis 3: _________ + + Test: _________ + + Result: _________ + +## Root Cause + +When you finally understood the real cause, what was it? + +_________ + +## Fix + +What change, exactly, made the bug go away? Include the commit +hash or the diff if you have it. + +_________ + +## What I Learned + +What do I know now that I did not know before this bug? This +field is the single most valuable one in the journal. + +_________ + +## What I Would Look At Sooner Next Time + +If I saw a similar symptom again, what is the first thing I +would check, knowing what I know now? + +_________ + +--- + +## References + +- **Relevant source paths and line numbers:** + + _________ + +- **Relevant mailing-list threads or commits:** + + _________ + +- **Relevant bug IDs:** + + _________ + +- **Documentation I wish had existed:** + + _________ + +--- + +## Follow-Ups + +- [ ] Write a regression test that would have caught this. +- [ ] Update any manual page affected by the fix. +- [ ] Share the finding with anyone who might hit the same + bug. +- [ ] Close the bug report if one was filed. diff --git a/examples/part-07/ch38-final-thoughts/templates/driver-handoff.md b/examples/part-07/ch38-final-thoughts/templates/driver-handoff.md new file mode 100644 index 0000000..980c979 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/driver-handoff.md @@ -0,0 +1,114 @@ +# Driver Handoff Checklist + +A driver is rarely owned by the same person forever. Whether +you are handing a driver off to a new maintainer, leaving a +company, or simply transferring stewardship to a colleague, +the items below help ensure the transition is clean. + +Use the checklist both as a handoff document and as a +self-review. Running through it regularly will surface the +gaps in your own maintenance practice long before you actually +need to hand the driver off. + +**Driver:** _________ + +**Current maintainer:** _________ + +**Proposed new maintainer:** _________ + +**Expected handoff date:** _________ + +--- + +## Source and Build + +- [ ] The driver builds from a clean tree with no local + modifications required. +- [ ] The build succeeds on every architecture the driver is + expected to support. +- [ ] The build produces no new warnings at any warning level + that the project uses by default. +- [ ] The driver integrates cleanly with `make buildkernel` + and `make buildworld`. + +## Documentation + +- [ ] The manual page is current and reflects real behaviour. +- [ ] The manual page passes `mandoc -Tlint`. +- [ ] A short design document explains the non-obvious + decisions and the hardware-specific quirks. +- [ ] The `sysctl` variables and `dev.` names are documented + with their meaning and their expected range of values. +- [ ] The module's `MODULE_DEPEND` relationships are + explained or obviously correct. + +## Testing + +- [ ] The driver has a regression test suite that the new + maintainer can run on their own hardware. +- [ ] The regression tests have been run successfully within + the last month. +- [ ] The driver has been tested against at least two FreeBSD + releases. +- [ ] The compatibility range is documented. +- [ ] Known failure modes are documented, including any + hardware configurations that are known not to work. + +## Hardware + +- [ ] The hardware required to test the driver is described + in enough detail that the new maintainer can acquire or + borrow it. +- [ ] Any vendor-specific documentation, datasheets, or NDAs + that affect the driver are recorded, either with the + driver or in a known location. +- [ ] Any hardware in the maintainer's possession that should + travel with the driver is packaged and ready for + shipment. + +## Open Work + +- [ ] All TODOs, known bugs, and planned work are recorded in + an issue tracker or a text file in the repository. +- [ ] Any outstanding patches or reviews have been surfaced + to the new maintainer. +- [ ] Any pending conversations with the community, vendors, + or users have been summarised. +- [ ] Any scheduled deprecations or upstream changes that + will affect the driver soon are flagged. + +## Community Context + +- [ ] The new maintainer has been introduced to the relevant + mailing-list discussions. +- [ ] The new maintainer has been introduced to any + community members who have contributed to the driver. +- [ ] The new maintainer has been added to any access + controls (Phabricator, Bugzilla, GitHub) the role + requires. +- [ ] The change in maintainership has been announced on the + appropriate mailing list. + +## Privacy + +- [ ] The commit history contains no proprietary information + that would prevent further public development. +- [ ] Any internal tooling, internal URLs, or internal ticket + references have been scrubbed from the public repository. +- [ ] Credentials, API keys, and secrets are not present in + the repository history. + +--- + +## Free-Form Handoff Notes + +Use the space below to capture anything that does not fit in +the boxes above: personal context the new maintainer might +want, the history of major decisions, expected future direction, +or any final words. + +_________ + +_________ + +_________ diff --git a/examples/part-07/ch38-final-thoughts/templates/learning-roadmap.md b/examples/part-07/ch38-final-thoughts/templates/learning-roadmap.md new file mode 100644 index 0000000..be95313 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/learning-roadmap.md @@ -0,0 +1,116 @@ +# Personal Learning Roadmap + +Use this template to plan each three-to-six-month learning +cycle. Copy the template, fill it in, and keep the filled copy +in your `freebsd-learning` repository so you can trace your +trajectory over time. + +A roadmap is not a contract with yourself. It is a working +plan that you will revise as circumstances change. The value is +in the planning and the revising, not in the strict adherence. + +--- + +**Period:** _________ to _________ + +**Primary focus area:** _________ + +**Why this area, now:** + +_________ + +--- + +## Monthly Milestones + +- **Month 1:** _________ + +- **Month 2:** _________ + +- **Month 3:** _________ + +- **Month 4** (if applicable): _________ + +- **Month 5** (if applicable): _________ + +- **Month 6** (if applicable): _________ + +--- + +## Resources + +- **Manual pages to read or re-read:** + + _________ + +- **Source files to study:** + + _________ + +- **Conference talks to watch:** + + _________ + +- **Books and papers:** + + _________ + +- **People I will learn from:** + + _________ + +--- + +## Practice Cadence + +- **Frequency:** _________ + +- **Duration per session:** _________ + +- **Default time of week:** _________ + +--- + +## Secondary Goals + +- **Toolkit improvement:** + + _________ + +- **Community engagement:** + + _________ + +- **Currency with FreeBSD development:** + + _________ + +--- + +## Progress Markers + +I will know I am on track when: + +_________ + +I will know I am off track when: + +_________ + +--- + +## Review Cadence + +- **First check-in:** _________ + +- **Mid-cycle review:** _________ + +- **Final review and write-up:** _________ + +--- + +## Notes + +Leave room for free-form notes as the cycle progresses. Capture +things that surprised you, directions you want to explore +next, and any distractions that you decided to defer. diff --git a/examples/part-07/ch38-final-thoughts/templates/quarterly-review.md b/examples/part-07/ch38-final-thoughts/templates/quarterly-review.md new file mode 100644 index 0000000..3c70414 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/quarterly-review.md @@ -0,0 +1,124 @@ +# Quarterly Review + +Every three months, take an hour or two to review your broader +trajectory, not just your immediate projects. The quarterly +review is different from the monthly stay-current rhythm. The +monthly rhythm keeps you in touch with the kernel as a living +system. The quarterly review keeps you in touch with your own +growth as a developer. + +Keep filled copies in your `freebsd-learning` repository so you +can read them in sequence over time. + +--- + +**Quarter:** Q___ of ____ + +**Start date:** _________ + +**End date:** _________ + +**Review written on:** _________ + +--- + +## At a Glance + +What I worked on this quarter: + +_________ + +## Learning Highlights + +**The most significant thing I learned:** + +_________ + +**A specific moment I am proud of:** + +_________ + +**A specific moment that was harder than I expected:** + +_________ + +## Roadmap Review + +**Milestones I completed:** + +_________ + +**Milestones I missed, and why:** + +_________ + +**Milestones I changed or abandoned, and why:** + +_________ + +## Community Engagement + +- **Patches submitted:** _________ + +- **Reviews performed:** _________ + +- **Mailing-list replies:** _________ + +- **Conference talks watched:** _________ + +- **Bug reports filed or triaged:** _________ + +- **Mentoring or teaching moments:** _________ + +## Toolkit Evolution + +- **New scripts or templates I added:** + + _________ + +- **Existing scripts I improved:** + + _________ + +- **Scripts I retired:** + + _________ + +- **Tools I tried but did not adopt, and why:** + + _________ + +## Forward Priorities + +**What I want to prioritise next quarter:** + +1. _________ +2. _________ +3. _________ + +**What I want to stop doing, or do less of:** + +_________ + +**Who I would like to learn from next quarter:** + +_________ + +**One small, concrete commitment for the coming month:** + +_________ + +--- + +## Honest Self-Observation + +Use the space below to write without structure. Are you +motivated? Are you drifting? Is your practice sustainable? Is +there something you are avoiding? Write what is true, not what +sounds good. + +_________ + +_________ + +_________ diff --git a/examples/part-07/ch38-final-thoughts/templates/self-assessment.md b/examples/part-07/ch38-final-thoughts/templates/self-assessment.md new file mode 100644 index 0000000..445bf54 --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/self-assessment.md @@ -0,0 +1,192 @@ +# Self-Assessment Worksheet + +Fill this worksheet in at the end of Chapter 38, and again every +three to six months. Keep the filled copies together so you can +see how your ratings evolve over time. The worksheet is not a +test. It is a calibration tool to help you know, clearly, where +your practice stands. + +--- + +**Date:** _________ + +**FreeBSD version last built:** _________ + +**How long since I finished this book:** _________ + +--- + +## Confidence Ratings + +Rate each item from 1 (I have heard of it and could explain the +idea roughly) to 5 (I could teach a beginner this topic from +first principles and debug a problem in it unaided). Add a +one-sentence rationale to each. + +**C for kernel programming:** _________ + +_Rationale:_ _________ + +**Kernel debugging (ddb, kgdb, dtrace):** _________ + +_Rationale:_ _________ + +**Kernel profiling (hwpmc, dtrace, pmcstat):** _________ + +_Rationale:_ _________ + +**Newbus (`device_t`, `DEVMETHOD`, `DRIVER_MODULE`):** _________ + +_Rationale:_ _________ + +**Softc and private state management:** _________ + +_Rationale:_ _________ + +**Resource allocation (`bus_alloc_resource()`):** _________ + +_Rationale:_ _________ + +**Register access (`bus_space(9)`):** _________ + +_Rationale:_ _________ + +**Interrupt handling:** _________ + +_Rationale:_ _________ + +**DMA and busdma(9):** _________ + +_Rationale:_ _________ + +**Concurrency and synchronisation (mtx, sx, rm, cv):** _________ + +_Rationale:_ _________ + +**Character-device and cdevsw interfaces:** _________ + +_Rationale:_ _________ + +**sysctl(9):** _________ + +_Rationale:_ _________ + +**ioctl(9) and handler design:** _________ + +_Rationale:_ _________ + +**devfs(5):** _________ + +_Rationale:_ _________ + +**Kernel build and `bsd.kmod.mk`:** _________ + +_Rationale:_ _________ + +**Device Tree integration (FDT):** _________ + +_Rationale:_ _________ + +**Embedded FreeBSD bring-up:** _________ + +_Rationale:_ _________ + +**Reverse engineering and hardware interrogation:** _________ + +_Rationale:_ _________ + +**Performance analysis and tuning:** _________ + +_Rationale:_ _________ + +**Upstream submission and review readiness:** _________ + +_Rationale:_ _________ + +**Manual-page authoring (mdoc, style.mdoc):** _________ + +_Rationale:_ _________ + +--- + +## What I Can Do Without Help + +List the specific things you are confident you can do without +consulting notes or a book. Be concrete. "I can write a probe +and attach routine for a PCI device" is better than "I +understand Newbus." + +1. _________ +2. _________ +3. _________ +4. _________ +5. _________ + +## What I Still Need Help With + +List the things that still feel shaky or that would send you +back to a reference before you acted. + +1. _________ +2. _________ +3. _________ +4. _________ +5. _________ + +--- + +## Growth Since the Last Review + +- What my ratings look like compared to last time: + + _________ + +- Areas where I grew the most: + + _________ + +- Areas where I did not grow as much as I hoped: + + _________ + +- A specific example of new capability I have now that I did + not have then: + + _________ + +--- + +## Next Six Months + +**Three topics I most want to deepen:** + +1. _________ +2. _________ +3. _________ + +**One concrete project I will start this month:** + +_________ + +**One community action I will take this month:** + +_________ + +**One reading I will complete:** + +_________ + +--- + +## Free-Form Reflection + +Leave room for whatever else is on your mind about your practice +right now. Celebration, worry, curiosity, ambition, confusion. +All of it is useful data for the next version of you who reads +these pages. + +_________ + +_________ + +_________ diff --git a/examples/part-07/ch38-final-thoughts/templates/stay-current-checklist.md b/examples/part-07/ch38-final-thoughts/templates/stay-current-checklist.md new file mode 100644 index 0000000..d536ade --- /dev/null +++ b/examples/part-07/ch38-final-thoughts/templates/stay-current-checklist.md @@ -0,0 +1,70 @@ +# Stay-Current Checklist + +Use this checklist on a monthly cadence to keep yourself in +step with FreeBSD development. It is deliberately short; a +checklist that takes an hour is more likely to get done than +one that takes a full day. + +**Month:** _________ + +**Date completed:** _________ + +--- + +## Source Currency + +- [ ] I have pulled the latest FreeBSD source tree. +- [ ] I have rebuilt the kernel on my main development + machine against the latest sources. +- [ ] I have built my personal drivers against the latest + source and investigated any new warnings or errors. +- [ ] I have run my regression tests against the latest + source and investigated any failures. + +## Release-Notes and UPDATING + +- [ ] I have read the UPDATING file for any new notices since + my last check. +- [ ] If a recent release branched, I have skimmed the + release notes. +- [ ] I have noted any items that affect my ongoing work. + +## Commit and Subsystem Awareness + +- [ ] I have read the commit log for the subsystems I care + about since the last time I looked. +- [ ] I have identified at least one commit worth reading in + detail and read it. +- [ ] I have traced any API changes that intersect with my + drivers. + +## Community + +- [ ] I have read at least one thread on `freebsd-hackers@` + or `freebsd-drivers@`. +- [ ] I have watched at least one conference talk or read at + least one blog post about FreeBSD. +- [ ] I have replied on a mailing list or a review at least + once this month. + +## Reflection + +- [ ] I have thought about whether any of the changes I saw + affect my ongoing work. +- [ ] I have noted any TODO items for next month's review. +- [ ] I have saved this filled-in checklist in my + `freebsd-learning` repository. + +--- + +## Notes From This Month + +Use the space below to capture interesting threads, commits, +bug reports, or conversations that you want to remember for +later. + +_________ + +_________ + +_________