mirror of
https://github.com/ebrandi/FDD-book.git
synced 2026-12-06 00:23:30 +00:00
Add book companion files under examples/
Organize companion code and materials by book part: part-01/ Foundations part-02/ Kernel & driver fundamentals part-03/ Character & block devices part-04/ Networking & storage part-05/ Buses & advanced topics part-06/ Debugging & performance part-07/ Real-world drivers appendices/ Supplementary material README.md Overview and build instructions
This commit is contained in:
parent
0de35c86b5
commit
6e6dac94fe
692 changed files with 70664 additions and 109 deletions
|
|
@ -1,167 +1,233 @@
|
||||||
# Examples Directory
|
# 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
|
## 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/
|
examples/
|
||||||
├── README.md # This file
|
├── README.md # This file
|
||||||
├── chapters/ # Examples from main chapters
|
├── part-01/ # Part 1: Foundations: FreeBSD, C, and the Kernel
|
||||||
│ ├── part1/ # Part 1: Fundamentals
|
│ ├── ch02-setting-up-your-lab/
|
||||||
│ ├── part2/ # Part 2: Basic Drivers
|
│ ├── ch03-a-gentle-introduction-to-unix/
|
||||||
│ ├── part3/ # Part 3: Advanced Topics
|
│ ├── ch04-a-first-look-at-the-c-programming-language/
|
||||||
│ ├── part4/ # Part 4: Specialized Drivers
|
│ ├── ch05-understanding-c-for-freebsd-kernel-programming/
|
||||||
│ ├── part5/ # Part 5: Performance & Optimization
|
│ └── ch06-the-anatomy-of-a-freebsd-driver/
|
||||||
│ ├── part6/ # Part 6: Debugging & Testing
|
├── part-02/ # Part 2: Building Your First Driver
|
||||||
│ └── part7/ # Part 7: Real-world Applications
|
│ ├── ch07-writing-your-first-driver/
|
||||||
└── appendices/ # Examples from appendices
|
│ ├── ch08-working-with-device-files/
|
||||||
├── appendix-a/ # Appendix A examples
|
│ ├── ch09-reading-and-writing/
|
||||||
├── appendix-b/ # Appendix B examples
|
│ └── ch10-handling-io-efficiently/
|
||||||
├── appendix-c/ # Appendix C examples
|
├── part-03/ # Part 3: Concurrency and Synchronization
|
||||||
├── appendix-d/ # Appendix D examples
|
│ ├── ch11-concurrency/
|
||||||
└── appendix-e/ # Appendix E examples
|
│ ├── 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.)
|
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:
|
||||||
- **Makefile** for building the example
|
|
||||||
- **README** with specific instructions for that example
|
|
||||||
- **Documentation** explaining the example's purpose and usage
|
|
||||||
|
|
||||||
## 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
|
* **Source files** (`.c`, `.h`) for the driver, helper code, or user-space program.
|
||||||
2. **Kernel source code** available
|
* **A Makefile** that includes `bsd.kmod.mk` for kernel modules, or `bsd.prog.mk` for user-space programs.
|
||||||
3. **Required tools** installed:
|
* **Scripts** (`.sh`, DTrace `.d`, `awk`, and similar) used during the lab or its measurement steps.
|
||||||
- `gcc` or `clang`
|
* **Configuration fragments** (loader.conf snippets, sysctl files, FDT overlays) when the lab needs them.
|
||||||
- `make`
|
* **Test artifacts** such as fixed input data, expected output, or trace files used for comparison.
|
||||||
- `kldload`/`kldunload` (for kernel modules)
|
|
||||||
|
|
||||||
### Building a Specific Example
|
## Building and Loading an Example
|
||||||
|
|
||||||
```bash
|
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`:
|
||||||
# Navigate to the example directory
|
|
||||||
cd examples/chapters/part1/example-01
|
|
||||||
|
|
||||||
# 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
|
make
|
||||||
|
|
||||||
# Load the kernel module (if applicable)
|
# Load it
|
||||||
sudo kldload ./example_module.ko
|
sudo kldload ./myfirst.ko
|
||||||
|
|
||||||
# Unload the kernel module (if applicable)
|
# Inspect it
|
||||||
sudo kldunload example_module
|
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
|
## Prerequisites
|
||||||
# From the examples directory
|
|
||||||
make all
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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
|
### 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
|
* Chapter 1, *Introduction: From Curiosity to Contribution*, has no companion files.
|
||||||
- **Writing Your First Driver** - Creating a simple kernel module
|
* `part-01/ch02-setting-up-your-lab/` — preparing the FreeBSD lab system, with starter configuration files and the first hello-world module.
|
||||||
- **Working with Device Files** - Device file creation and management
|
* `part-01/ch03-a-gentle-introduction-to-unix/` — UNIX fundamentals, shell scripting, automation, and portability examples used throughout the book.
|
||||||
- **Reading and Writing to Devices** - Implementing read/write operations
|
* `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.
|
||||||
- **Handling Input and Output Efficiently** - Optimizing I/O operations
|
* `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
|
### Part 3: Concurrency and Synchronization
|
||||||
- **Concurrency in Drivers** - Managing concurrent operations
|
|
||||||
- **Synchronization Mechanisms** - Implementing proper synchronization
|
* `part-03/ch11-concurrency/` — race demonstrations, concurrent-safe versions, and `KASSERT`-instrumented variants, with a userland exerciser.
|
||||||
- **Timers and Delayed Work** - Time-based operations and delayed execution
|
* `part-03/ch12-synchronization-mechanisms/` — condition variables, bounded reads, `sx` lock based configuration, and a final converged module.
|
||||||
- **Taskqueues and Deferred Work** - Using taskqueues for deferred processing
|
* `part-03/ch13-timers-and-delayed-work/` — heartbeat, watchdog, tick-source, and final variants of a timer-driven driver.
|
||||||
- **More Synchronization — Conditions, Semaphores, and Coordination** - Advanced synchronization techniques
|
* `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
|
### Part 4: Hardware and Platform-Level Integration
|
||||||
- **Accessing Hardware** - Direct hardware access techniques
|
|
||||||
- **Simulating Hardware** - Creating virtual hardware for testing
|
* `part-04/ch16-accessing-hardware/` — register-map, `bus_space(9)`, synchronized, and final stages, plus a standalone hardware simulator (`hwsim-standalone/`) and labs.
|
||||||
- **Writing a PCI Driver** - Developing drivers for PCI and PCIe devices
|
* `part-04/ch17-simulating-hardware/` — backend, integration, timing, faults, and final stages of a richer simulator (`hwsim2-standalone/`) and labs.
|
||||||
- **Handling Interrupts** - Basic interrupt handling implementation
|
* `part-04/ch18-writing-pci-driver/` — probe, BAR mapping, integrated, and final stages for a PCI driver, with labs.
|
||||||
- **Advanced Interrupt Handling** - Sophisticated interrupt techniques
|
* `part-04/ch19-handling-interrupts/` — registration, handler, simulation, and final stages of an interrupt-driven driver.
|
||||||
- **DMA and High-Speed Data Transfer** - Direct Memory Access implementation
|
* `part-04/ch20-advanced-interrupts/` — single MSI, multi-vector MSI, MSI-X, and final stages.
|
||||||
- **Power Management** - Power management features in drivers
|
* `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
|
### 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
|
* `part-05/ch23-debug/` — logging, SDT probes, and refactor stages, plus debugging labs.
|
||||||
- **Advanced Topics and Practical Tips** - Advanced techniques and practical advice
|
* `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
|
### 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
|
* `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.
|
||||||
- **Writing a Network Driver** - Network interface driver development
|
* `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
|
### 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
|
* `appendices/appendix-a-freebsd-kernel-api-reference/` — kernel API reference material with `cheatsheets/` and `scripts/`.
|
||||||
2. **Document any issues** you encounter
|
* `appendices/appendix-b-algorithms-and-logic-for-systems-programming/` — algorithm and data-structure cheatsheets relevant to driver work.
|
||||||
3. **Submit improvements** via pull request
|
* `appendices/appendix-c-hardware-concepts-for-driver-developers/` — hardware-side cheatsheets used when reading datasheets and reasoning about buses, registers, and timing.
|
||||||
4. **Follow the coding standards** used in the book
|
* `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
|
## Version Compatibility
|
||||||
|
|
||||||
These examples are designed for:
|
The companion files target:
|
||||||
- **FreeBSD 14.x** and later
|
|
||||||
- **x86_64** and **ARM64** architectures
|
* **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.
|
||||||
- **GCC** and **Clang** compilers
|
* **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
|
## Troubleshooting
|
||||||
|
|
||||||
### Common Issues
|
The most common issues, and where to look first:
|
||||||
|
|
||||||
1. **Build errors**: Ensure you have the correct kernel headers installed
|
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 loading failures**: Check kernel messages with `dmesg`
|
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**: Use `sudo` for kernel module operations
|
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**: Verify you're building for the correct architecture
|
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
|
## Contributing
|
||||||
- Review the book chapter for theoretical background
|
|
||||||
- Consult FreeBSD documentation and man pages
|
If you spot a problem with an example, or you would like to suggest an improvement:
|
||||||
- Check kernel messages: `dmesg | tail`
|
|
||||||
|
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
|
## 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.
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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 <name>` 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.
|
||||||
|
|
@ -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 <api-name>
|
||||||
|
#
|
||||||
|
# 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 <api-name>\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
|
||||||
106
examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-manpage
Executable file
106
examples/appendices/appendix-a-freebsd-kernel-api-reference/scripts/fdd-manpage
Executable file
|
|
@ -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 <api-name>
|
||||||
|
#
|
||||||
|
# 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 <api-name>\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"
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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_` | `<sys/queue.h>` | Yes | No | O(n) | Only with prev ptr | 1 next |
|
||||||
|
| `LIST_` | `<sys/queue.h>` | Yes | No | O(n) | O(1) | 1 next, 1 prev ptr |
|
||||||
|
| `STAILQ_` | `<sys/queue.h>` | Yes | No (FIFO) | O(n) | Hard in middle | 1 next + tail |
|
||||||
|
| `TAILQ_` | `<sys/queue.h>` | Yes | No | O(n) | O(1) from node | 2 ptrs + tail |
|
||||||
|
| `RB_` tree | `<sys/tree.h>` | Yes | By key | O(log n) | O(log n) | Left, right, parent, colour |
|
||||||
|
| Bit string | `<sys/bitstring.h>` | 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 | `<net/radix.h>` | 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 `<sys/queue.h>`. 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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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`
|
||||||
|
|
@ -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/`).
|
||||||
|
|
@ -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.<driver>.<unit>`)
|
||||||
|
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.
|
||||||
|
|
@ -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`.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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/<name>` node | `if_<name>` (e.g., `em0`) | `/dev/<disk>` node (GEOM) | `/dev/<name>` or `if_<name>` |
|
||||||
|
| 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, <parent-bus>, 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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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.
|
||||||
28
examples/appendices/appendix-f-benchmarks/dtrace/Makefile
Normal file
28
examples/appendices/appendix-f-benchmarks/dtrace/Makefile
Normal file
|
|
@ -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
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
42
examples/appendices/appendix-f-benchmarks/dtrace/run_overhead_suite.sh
Executable file
42
examples/appendices/appendix-f-benchmarks/dtrace/run_overhead_suite.sh
Executable file
|
|
@ -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"
|
||||||
|
|
@ -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 <sys/types.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
|
||||||
|
#include <err.h>
|
||||||
|
#include <inttypes.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -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 <sys/types.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
|
||||||
|
#include <err.h>
|
||||||
|
#include <inttypes.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#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);
|
||||||
|
}
|
||||||
99
examples/appendices/appendix-f-benchmarks/iflib/compare_iflib_corpus.sh
Executable file
99
examples/appendices/appendix-f-benchmarks/iflib/compare_iflib_corpus.sh
Executable file
|
|
@ -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
|
||||||
60
examples/appendices/appendix-f-benchmarks/iflib/count_driver_lines.sh
Executable file
60
examples/appendices/appendix-f-benchmarks/iflib/count_driver_lines.sh
Executable file
|
|
@ -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 <source-file>" >&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}"
|
||||||
108
examples/appendices/appendix-f-benchmarks/iflib/git_conversion_delta.sh
Executable file
108
examples/appendices/appendix-f-benchmarks/iflib/git_conversion_delta.sh
Executable file
|
|
@ -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 <repo-path> <driver-basename>
|
||||||
|
# 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 <repo-path> <driver-basename>" >&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}"
|
||||||
16
examples/appendices/appendix-f-benchmarks/sync/Makefile
Normal file
16
examples/appendices/appendix-f-benchmarks/sync/Makefile
Normal file
|
|
@ -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 <bsd.kmod.mk>
|
||||||
44
examples/appendices/appendix-f-benchmarks/sync/run_sync_bench.sh
Executable file
44
examples/appendices/appendix-f-benchmarks/sync/run_sync_bench.sh
Executable file
|
|
@ -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"
|
||||||
299
examples/appendices/appendix-f-benchmarks/sync/sync_bench.c
Normal file
299
examples/appendices/appendix-f-benchmarks/sync/sync_bench.c
Normal file
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
#include <sys/sysctl.h>
|
||||||
|
#include <sys/lock.h>
|
||||||
|
#include <sys/mutex.h>
|
||||||
|
#include <sys/sx.h>
|
||||||
|
#include <sys/condvar.h>
|
||||||
|
#include <sys/sema.h>
|
||||||
|
#include <sys/kthread.h>
|
||||||
|
#include <sys/proc.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
|
||||||
|
#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);
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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 <sys/types.h>
|
||||||
|
|
||||||
|
#include <err.h>
|
||||||
|
#include <inttypes.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#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);
|
||||||
|
}
|
||||||
57
examples/appendices/appendix-f-benchmarks/timecounter/run_tc_bench.sh
Executable file
57
examples/appendices/appendix-f-benchmarks/timecounter/run_tc_bench.sh
Executable file
|
|
@ -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}"
|
||||||
|
|
@ -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 <sys/types.h>
|
||||||
|
#include <sys/sysctl.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
|
||||||
|
#include <err.h>
|
||||||
|
#include <inttypes.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#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);
|
||||||
|
}
|
||||||
13
examples/part-01/ch02-setting-up-your-lab/configs/dot-vimrc
Normal file
13
examples/part-01/ch02-setting-up-your-lab/configs/dot-vimrc
Normal file
|
|
@ -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
|
||||||
17
examples/part-01/ch02-setting-up-your-lab/configs/pf.conf
Normal file
17
examples/part-01/ch02-setting-up-your-lab/configs/pf.conf
Normal file
|
|
@ -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
|
||||||
|
|
@ -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:
|
||||||
|
```
|
||||||
|
|
@ -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 <bsd.kmod.mk>
|
||||||
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 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);
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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.
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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 {} +
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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)"
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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 $?"
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -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")"
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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");
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
#ifndef DEV_FLAGS_H
|
||||||
|
#define DEV_FLAGS_H
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
#ifndef EB_LOG_H
|
||||||
|
#define EB_LOG_H
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
#ifndef DEVNAME_H
|
||||||
|
#define DEVNAME_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#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 : "<invalid>");
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("valid? 'ttyu0'=%d, 'u0tty'=%d\n",
|
||||||
|
is_valid_devname("ttyu0"),
|
||||||
|
is_valid_devname("u0tty"));
|
||||||
|
|
||||||
|
return (0);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,43 @@
|
||||||
|
#include <string.h>
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
#ifndef OPS_H
|
||||||
|
#define OPS_H
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
|
@ -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
|
||||||
|
};
|
||||||
|
|
@ -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
|
||||||
|
};
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
#ifndef CBUF_H
|
||||||
|
#define CBUF_H
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
/* 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
|
||||||
|
|
@ -0,0 +1,41 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#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);}
|
||||||
|
|
@ -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 <bsd.kmod.mk>
|
||||||
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/malloc.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
#include <stdlib.h> /* 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);
|
||||||
|
}
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include "greetings.h"
|
||||||
|
|
||||||
|
void
|
||||||
|
say_hello(void)
|
||||||
|
{
|
||||||
|
printf("Hello from greetings.c!\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void
|
||||||
|
say_goodbye(void)
|
||||||
|
{
|
||||||
|
printf("Goodbye from greetings.c!\n");
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
#ifndef GREETINGS_H
|
||||||
|
#define GREETINGS_H
|
||||||
|
|
||||||
|
void say_hello(void);
|
||||||
|
void say_goodbye(void);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
#include "greetings.h"
|
||||||
|
|
||||||
|
int
|
||||||
|
main(void)
|
||||||
|
{
|
||||||
|
say_hello();
|
||||||
|
say_goodbye();
|
||||||
|
return (0);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#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);
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
#ifndef MATHUTILS_H
|
||||||
|
#define MATHUTILS_H
|
||||||
|
|
||||||
|
int add(int a, int b);
|
||||||
|
int subtract(int a, int b);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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 <stdio.h>
|
||||||
|
|
||||||
|
int
|
||||||
|
main(void)
|
||||||
|
{
|
||||||
|
|
||||||
|
printf("Hello, World!\n");
|
||||||
|
return (0);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
KMOD= atomic_demo
|
||||||
|
SRCS= atomic_demo.c
|
||||||
|
|
||||||
|
.include <bsd.kmod.mk>
|
||||||
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
#include <machine/atomic.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
KMOD= defensive_demo
|
||||||
|
SRCS= defensive_demo.c
|
||||||
|
|
||||||
|
.include <bsd.kmod.mk>
|
||||||
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/malloc.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
#include <machine/atomic.h>
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
KMOD= error_demo
|
||||||
|
SRCS= error_demo.c
|
||||||
|
|
||||||
|
.include <bsd.kmod.mk>
|
||||||
|
|
@ -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 <sys/param.h>
|
||||||
|
#include <sys/kernel.h>
|
||||||
|
#include <sys/malloc.h>
|
||||||
|
#include <sys/module.h>
|
||||||
|
#include <sys/systm.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <machine/atomic.h>
|
||||||
|
|
||||||
|
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);
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue