--- title: "Device Tree and Embedded Development" description: "Driver development for embedded systems using device tree" partNumber: 7 partName: "Mastery Topics: Special Scenarios and Edge Cases" chapter: 32 lastUpdated: "2026-04-20" status: "complete" author: "Edson Brandi" reviewer: "TBD" translator: "TBD" estimatedReadTime: 195 --- # Device Tree and Embedded Development ## Introduction Chapter 31 trained you to look at your driver from the outside, through the eyes of whoever might try to misuse it. The boundaries you learned to watch were invisible to the compiler but very real to the kernel: user space on one side, kernel memory on the other; one thread with privilege, another without; a length field the caller claimed, a length the driver must verify. That chapter was about who is allowed to ask the driver to do something, and what the driver should check before it agrees. Chapter 32 shifts the perspective entirely. The question stops being *who wants this driver to run* and becomes *how does this driver find its hardware at all*. On the machines we have leaned on so far, the answer was easy enough that you could ignore it. A PCI device announced itself through standard configuration registers. An ACPI-described peripheral appeared in a table the firmware handed to the kernel. The bus did the looking, the kernel probed each candidate, and your driver's `probe()` function only had to look at an identifier and say yes or no. Discovery was mostly someone else's problem. On embedded platforms that assumption breaks. A small ARM board does not speak PCI, does not carry an ACPI BIOS, and does not have a firmware layer that will hand the kernel a neat table of devices. The SoC has an I2C controller at a fixed physical address, three UARTs at three other fixed addresses, a GPIO bank at a fourth, a timer, a watchdog, a clock tree, a pin multiplexer, and a dozen other peripherals that the hardware designer soldered onto the board in a particular arrangement. Nothing in the silicon announces itself. If the kernel is going to attach drivers to these peripherals, something has to tell the kernel where they are, what they are, and how they relate. That something is the **Device Tree**, and learning to work with it is what Chapter 32 is about. Device Tree is not a driver. It is not a subsystem in the sense that `vfs` or `devfs` is a subsystem. It is a *data structure*, a textual hardware description that the bootloader hands to the kernel at boot time, and that the kernel then walks to decide which drivers to run and where to point them. The structure has its own file format, its own compiler, its own conventions, and its own quiet conventions that embedded developers learn over time. A driver written for a Device Tree platform looks almost like the drivers you already know, with a handful of important differences in how it finds its resources. Those differences are the subject of this chapter. We are also going to widen the map. Until now most of your drivers have run on amd64, the flavour of 64-bit x86 that powers laptops, workstations, and servers. That architecture will not be going anywhere, and your understanding of it will continue to serve you. But FreeBSD runs on more than amd64. It runs on arm64, the 64-bit ARM architecture that powers the Raspberry Pi 4, the Pine64, the HoneyComb LX2, countless industrial boards, and a growing fraction of the cloud. It runs on 32-bit ARM for older Pis, BeagleBones, and embedded appliances. It runs on RISC-V, a newer, open architecture whose first serious FreeBSD support matured over the FreeBSD 13 and 14 cycles. On every one of those architectures outside the PC-like world, Device Tree is how drivers find their hardware. If you want to write drivers that run on anything other than a laptop, you need to know how it works. The good news is that the shape of a driver does not change much when you cross over. Your probe and attach routines still look like probe and attach routines. Your softc still lives in the same kind of structure. Your lifecycle is still the same lifecycle, with load and unload, detach and cleanup. What changes is the set of helpers you call to discover your hardware's address, to read its interrupt specification, to turn on its clock, to pull its reset line, to request a GPIO pin. Those helpers have a family resemblance once you see a few of them. The FreeBSD source tree uses them in hundreds of places, and by the end of this chapter you will recognise them on sight and know where to look when you need one you have not used before. The chapter proceeds in eight sections. Section 1 introduces the embedded FreeBSD world and the hardware platforms on which it runs. Section 2 explains what the Device Tree is, how its files are organised, how `.dts` source turns into `.dtb` binary blobs, and what the nodes and properties inside actually mean. Section 3 walks through FreeBSD's support for Device Tree: the `fdt(4)` framework, the `ofw_bus` interfaces, the `simplebus` enumerator, and the Open Firmware helpers that drivers use to read properties. Section 4 is the first concrete driver-writing section. You will see the shape of an FDT-aware driver from probe to attach to detach, with its `ofw_compat_data` table and its calls to `ofw_bus_search_compatible`, `ofw_bus_get_node`, and the property-reading helpers. Section 5 turns to the DTB itself: how to compile a `.dts` with `dtc`, how overlays work, how to add a custom node to an existing board description, and how FreeBSD's build tooling fits together. Section 6 is about debugging, both at boot and at runtime, using `ofwdump(8)`, `dmesg`, and the kernel log to find out why a node did not match. Section 7 brings the pieces together in a practical GPIO driver that takes its pin assignments from Device Tree and toggles an LED. Section 8 is the refactoring section: we will take the driver you built in Section 7, tighten its error handling, expose a sysctl for observability, and talk through what packaging an embedded image looks like. Along the way we will touch on the peripheral frameworks that every serious embedded driver eventually leans on. The clock framework, regulator framework, and hardware-reset framework under `/usr/src/sys/dev/extres/` are the three big ones; the pin-control framework under `/usr/src/sys/dev/fdt/` is the fourth. The GPIO framework under `/usr/src/sys/dev/gpio/` is your first stop for reading and writing pins. `interrupt-parent` chaining routes IRQs up the interrupt tree to the controller that can actually handle them. Device Tree *overlays*, files with the extension `.dtbo`, let you add or modify nodes at boot without rebuilding the base blob. And at the highest level, on arm64 in particular, a single kernel binary can run on either FDT or ACPI; the mechanism that picks between the two is worth looking at briefly, because it shows how drivers written for both are factored. One last framing note before we begin. Embedded work can feel intimidating from a distance. The lexicon is unfamiliar, the boards are small and fiddly, the documentation is thinner than on desktop platforms, and the first time a DTB mismatch sends you into a silent boot hang it is easy to lose your nerve. None of that is a reason to stay away. The core skill you are going to build in this chapter, reading a `.dts` file and recognising what is being described, is learnable in a long afternoon. The second skill, writing a driver that matches on a compatible string and walks the properties it needs, is the same kind of driver writing you already know with three or four new helper calls. The third skill, building and loading a DTB and seeing your driver attach, is exactly the kind of feedback loop that makes kernel work enjoyable. By the end of the chapter you will have written, compiled, loaded, and observed an FDT-aware driver on either a real ARM board or an emulated one, and you will have the mental model that lets you read any FreeBSD embedded driver and understand how it finds its hardware. The rest of the book will continue to treat drivers as drivers, but your toolkit will have grown. Let us begin. ## Reader Guidance: How to Use This Chapter Chapter 32 sits in a particular place in the book's arc. Earlier chapters assumed a PC-like machine where buses discovered themselves and drivers bound to devices the kernel already knew about. This chapter steps sideways into a world where discovery is a problem the driver has to participate in. That step is easier than it sounds, but it does require a small shift in how you think about hardware, and a willingness to read some new kinds of files. There are two reading paths, and one optional third path for readers who have embedded hardware at home. If you choose the **reading-only path**, plan for three to four focused hours. You will finish the chapter with a clear mental model of what Device Tree is, how the kernel uses it, what an FDT-aware driver looks like, and where the important FreeBSD source files live. You will not have typed a driver, but you will be able to read one and understand every helper call you see. For many readers, this is the right stopping point on a first pass. If you choose the **reading-plus-labs path**, plan for seven to ten hours spread across two or three sessions. The labs are built around a small pedagogical driver called `edled`, short for *embedded LED*. Over the chapter you will write a minimal FDT driver that matches a custom compatible string, grow it into a driver that reads its pin number and timer interval from Device Tree, and finally wrap it in a tidy detach path with a sysctl for runtime observability. You will compile a tiny `.dts` fragment into a `.dtb` overlay, load it with FreeBSD's loader, and watch the driver attach in `dmesg`. None of these steps are long; none require more than a basic familiarity with `make`, `sudo`, and a shell. If you have access to a Raspberry Pi 3 or 4, a BeagleBone, a Pine64, a Rock64, or a compatible ARM board, you can follow the **reading-plus-labs-plus-hardware path**. In that case the `edled` driver blinks a real LED attached to a real pin, and you get the satisfying experience of writing kernel code that makes a physical thing happen. If you do not have hardware, do not worry. The entire chapter can be followed with a QEMU virtual machine emulating a generic ARM platform, or even with printed simulation on a regular FreeBSD machine. You will not miss any of the conceptual material. ### Prerequisites You should be comfortable with the FreeBSD driver skeleton from earlier chapters: module init and exit, `probe()` and `attach()`, softc allocation and destruction, `DRIVER_MODULE()` registration, and the basics of `bus_alloc_resource_any()` and `bus_setup_intr()`. If any of those is fuzzy, a short revisit of Chapters 6 through 14 before this chapter will pay off. The helpers in this chapter sit *alongside* the familiar `bus_*` helpers; they do not replace them. You should also be comfortable with simple FreeBSD system administration: loading and unloading kernel modules with `kldload(8)` and `kldunload(8)`, reading `dmesg(8)`, editing `/boot/loader.conf`, and running a command as root. You will use all of them, but none at any deeper level than earlier chapters have already asked. No prior experience with embedded hardware is required. If you have never touched an ARM board, the chapter will teach you what you need. If you have used a Raspberry Pi but only as a small Linux machine, the chapter will give you a new perspective on what is going on under its covers. ### Structure and Pacing Section 1 sets the stage: what embedded FreeBSD looks like in practice, which architectures FreeBSD supports, what kinds of boards you are likely to encounter, and why Device Tree is the answer embedded platforms have settled on. Section 2 is the longest conceptual section: it introduces Device Tree files, their source and binary forms, their node-and-property structure, and the handful of conventions you need to read them fluently. Section 3 brings the conversation back to FreeBSD specifically, introducing the `fdt(4)` framework, the `ofw_bus` interfaces, and the simplebus enumerator. Section 4 is the first driver-writing section; it walks through the canonical shape of an FDT driver from probe to attach to detach. Section 5 teaches you how to build and modify `.dtb` files and how FreeBSD's overlays system works. Section 6 is the debugging section. Section 7 is the substantive worked example: the `edled` GPIO driver. Section 8 is the refactoring and finalising section. After Section 8 you will find hands-on labs, challenge exercises, a troubleshooting reference, the Wrapping Up review, and the bridge into Chapter 33. Read the sections in order. They build on each other, and the later sections assume the vocabulary the earlier ones establish. If you are short on time and want the smallest conceptual tour, read Sections 1, 2, and 3, then skim Section 4 for its driver skeleton; that gives you the map of the territory. ### Work Section by Section Each section covers one coherent piece of the subject. Read one, let it settle, then start the next. If a section ends and a point still feels blurry, pause, re-read the closing paragraphs, and open the cited FreeBSD source file. A quick look at real code often clarifies in thirty seconds what prose can only dance around. ### Keep the Lab Driver Close The `edled` driver used in the chapter lives under `examples/part-07/ch32-fdt-embedded/` in the book's repository. Each lab directory contains the state of the driver at that step, with its `Makefile`, a brief `README.md`, a matching DTS overlay where relevant, and any supporting scripts. Clone the directory, work in place, and load each version after every change. A kernel module that attaches in `dmesg` and toggles a pin you can observe is the single most concrete feedback loop in embedded work; use it. ### Open the FreeBSD Source Tree Several sections point to real FreeBSD files. The most useful ones to keep open for this chapter are `/usr/src/sys/dev/fdt/simplebus.c` and `/usr/src/sys/dev/fdt/simplebus.h`, which define the simple FDT bus enumerator every child driver binds to; `/usr/src/sys/dev/ofw/ofw_bus.h`, `/usr/src/sys/dev/ofw/ofw_bus_subr.h`, and `/usr/src/sys/dev/ofw/ofw_bus_subr.c`, which give you the compatibility helpers and property readers; `/usr/src/sys/dev/ofw/openfirm.h`, which declares the lower-level `OF_*` primitives; `/usr/src/sys/dev/gpio/gpioled_fdt.c`, a small real driver you will imitate; `/usr/src/sys/dev/gpio/gpiobusvar.h`, which defines `gpio_pin_get_by_ofw_idx()` and its siblings; and `/usr/src/sys/dev/fdt/fdt_pinctrl.h`, which defines the pinctrl API. Open them when the chapter points you at them. The source is the authority; the book is a guide into it. ### Keep a Lab Logbook Continue the lab logbook from earlier chapters. For this chapter, log a short note for each lab: which commands you ran, which DTB loaded, what `dmesg` said, which pin you used, and any surprises. Embedded debugging benefits more than most from a paper trail, because the variables that cause a driver not to attach (a missed overlay, a wrong phandle, a swapped pin number) are easy to forget and expensive to re-discover. ### Pace Yourself The concepts in this chapter are often easier the second time you meet them than the first. The words *phandle*, *ranges*, and *interrupt-parent* can sit uneasily for a while before clicking. If a subsection blurs, mark it, move on, and come back to it. Most readers find Section 2 (the Device Tree format itself) is the hardest of the chapter; after it, Sections 3 and 4 feel easy because they are mostly *driver code* and the shape of driver code is already familiar. ## How to Get the Most Out of This Chapter A few habits will help you turn the chapter's prose into durable intuition. They are the same habits that help with any new subsystem, tuned for the particulars of embedded work. ### Read Real Source The single best way to learn to read Device Tree files and FDT-aware drivers is to read real ones. The FreeBSD tree ships several hundred. Pick a peripheral you find interesting, find its driver under `/usr/src/sys/dev/`, open it, and read it. If it has an `ofw_compat_data` table near the top and a `probe()` that calls `ofw_bus_search_compatible`, you are looking at an FDT-aware driver. Notice which properties it reads. Notice how it acquires its resources. Notice what it does and does not do on detach. The DTS side rewards the same treatment. The FreeBSD tree keeps custom board descriptions under `/usr/src/sys/dts/`, the upstream Linux-derived device trees under `/usr/src/sys/contrib/device-tree/`, and overlays under `/usr/src/sys/dts/arm/overlays/` and `/usr/src/sys/dts/arm64/overlays/`. Open a `.dts` file that describes a board you have heard of, and read it the way you would read code: top down, noticing the hierarchy, the property names, and the commentary. ### Run What You Build The point of the labs is that they end in something you can observe. When you load a module and nothing happens, that too is information; it usually means the driver did not match, and the chapter will teach you how to find out why. The feedback cycle is the whole point. Do not skip the loading step just because the code compiled. ### Type the Labs The `edled` driver is small on purpose. Typing it yourself slows you down enough to notice what each line does. The finger-memory of writing FDT boilerplate is worth having. Copy-pasting deprives you of that; resist the temptation even when you are sure you could reproduce the file from memory. ### Follow the Nodes When you read a Device Tree file or a `dmesg` boot log and you do not recognise a property, follow it. Look at the node's binding documentation in `/usr/src/sys/contrib/device-tree/Bindings/` if one exists. Search the FreeBSD source for the property name to see which drivers care about it. Embedded work is full of small conventions, and each one becomes obvious once you have seen it used in real code. ### Treat `dmesg` as Part of the Manuscript Almost everything interesting about FDT discovery shows up in `dmesg`, not in the shell. When a driver attaches, when a node is skipped because its status is disabled, when simplebus reports a child with no matching driver, you find those messages in the kernel log and nowhere else. Keep `dmesg -a` or `tail -f /var/log/messages` in a second terminal during labs. Copy relevant lines into your logbook when they teach something non-obvious. ### Break Things on Purpose Some of the most useful lessons in this chapter come from watching a driver *fail* to attach. A typo in a compatible string, a wrong pin number, a disabled status, a missing overlay will each produce a different flavour of silence in `dmesg`. Working through those failures in a lab environment teaches the recognition you will need when the same failure surprises you in real work. Do not only build drivers that work; break a few on purpose and look at what the kernel says. ### Work in Pairs When You Can Embedded debugging, like security work, benefits from a second pair of eyes. If you have a study partner, one of you can read the `.dts` while the other reads the driver; you can trade perspectives and compare what you each thought the setup was doing. The conversation tends to catch the small mistakes (a swapped cell count, a misread phandle, an interrupt cell in the wrong position) that slip past a single reader. ### Trust the Iteration You are not going to memorise every property, every flag, every helper on the first pass. That is fine. What you need on the first pass is the *shape* of the subject: the names of the primitives, the structure of a driver that uses them, the places to look when a concrete question comes up. The identifiers become reflex after you have written one or two FDT drivers; they are not a memorisation exercise. ### Take Breaks Embedded work, like security work, is cognitively dense. It asks you to hold a description of physical hardware in your head while you read software that tries to describe and control it. Two focused hours, a proper break, and another focused hour is almost always more productive than four hours of grinding through in one sitting. With those habits in place, let us begin with the broad question: what is embedded FreeBSD, and what does it ask of a driver author that desktop FreeBSD does not? ## Section 1: Introduction to Embedded FreeBSD Systems The word *embedded* has been used so loosely over the years that it is worth pausing to say what we mean by it inside this book. For our purposes, an embedded system is a computer designed to do a specific job rather than to be a general-purpose machine. A Raspberry Pi running a thermostat control loop is embedded. A BeagleBone running a CNC controller is embedded. A small ARM box running a firewall appliance, a RISC-V development board running a dedicated sensor gateway, a router built around a MIPS SoC in the old days, all of these are embedded. A laptop is not embedded even when it is small. A server is not embedded even when it is stripped down. The word is about purpose and constraint, not size. From a driver author's perspective, embedded systems share a handful of practical traits that shape the work. The hardware is usually an SoC with many on-chip peripherals rather than a motherboard with plug-in cards. The peripherals are fixed: they cannot be added or removed, because they are literally part of the silicon. There is usually no discoverable bus in the PCI sense; the peripherals sit at known physical addresses and the kernel must be told where they are. Power is constrained, sometimes severely. RAM is limited. Storage is limited. The boot flow is simple, often relying on a bootloader like U-Boot or a small EFI implementation. The user interface, if any, is minimal. The kernel boots, the drivers attach, the one application the machine exists to run comes up, and that is the life of the system. FreeBSD runs on a growing family of embedded-friendly architectures. Most of this chapter assumes arm64 because it is the most widely used embedded target for FreeBSD today, but most of what you learn applies directly to 32-bit ARM, RISC-V, and, to a lesser extent, older MIPS and PowerPC platforms. The differences between these architectures matter for the compiler and the kernel's lowest-level code, but for driver writing the differences are mostly absent. The same FDT framework, the same `ofw_bus` helpers, the same simplebus enumerator, and the same GPIO and clock APIs work across all of them. A driver you write for a Raspberry Pi today will, with very little modification, build and run on a RISC-V SiFive HiFive Unmatched tomorrow. ### What Embedded FreeBSD Looks Like Picture a Raspberry Pi 4 running FreeBSD 14.3. The board has a quad-core ARM Cortex-A72 CPU, 4 GB of RAM, a PCIe root complex with a gigabit Ethernet controller and a USB host controller hanging off it, an SD card slot for storage, a Broadcom VideoCore VI GPU, an HDMI output, four USB ports, a 40-pin GPIO header, and on-chip UARTs, SPI buses, I2C buses, pulse-width modulators, and timers. Most of those peripherals sit inside the BCM2711 SoC at fixed memory-mapped addresses. A few, like the USB and the Ethernet, hang off the SoC's internal PCIe controller. The SD card is driven by a host controller inside the SoC that speaks the SD protocol. When you power the board on, a tiny firmware on the GPU core reads the SD card, finds the FreeBSD EFI bootloader, and hands control to it. The EFI loader reads `/boot/loader.conf`, loads the FreeBSD kernel, loads the Device Tree blob that describes the hardware, loads any overlay blobs that tweak the description, and jumps to the kernel. The kernel boots, attaches a simplebus to the root node of the tree, walks the tree's children, matches drivers to nodes, attaches drivers to their hardware, and the system comes up. By the time you see a login prompt, your filesystem has been mounted from the SD card by the SD host driver, your network interface has been brought up by the Ethernet driver, your USB devices are probed and available, and the ordinary userland tools (`ps`, `dmesg`, `sysctl`, `kldload`) behave exactly as they do on a laptop. None of that last paragraph would have been true for a PC. On a PC, the firmware is BIOS or UEFI, the peripherals are on PCI, and the kernel does not need a separate blob that describes the hardware because the PCI bus itself describes its children. The arm64 world has none of those luxuries. It has Device Tree instead. ### Why Embedded Platforms Rely on Device Trees The embedded world chose Device Trees because of the problem space. A small SoC has dozens of on-chip peripherals. Every SoC variant, every board revision, every integration choice the hardware engineer made shapes which peripherals are enabled, which pins they use, how their clocks are wired, and what their interrupt priorities are. There are thousands of distinct SoCs in the wild, and tens of thousands of distinct boards. A single kernel binary cannot afford to have every one of those variations compiled into it. Nor is there a magical bus protocol it could use to *ask* the hardware what is on the board; the hardware does not know, and most of it cannot answer. The old solution, the one the embedded Linux world used before Device Trees, was called *board files*. Each board had a C source file compiled into the kernel, full of static structures that described the peripherals, their addresses, their interrupts, and their clocks. A kernel intended for five boards had five board files. A kernel intended for fifty boards had fifty, each with its own static description, each requiring the kernel to be rebuilt every time a board's hardware changed. The approach did not scale. Every board revision was a kernel release. Device Trees are the approach that replaced board files. The core idea is elegant: rather than encode the hardware description in C inside the kernel, encode it in a separate textual file that lives outside the kernel, compile that file into a compact binary blob, and let the bootloader hand the blob to the kernel at boot. The kernel then reads the blob, decides which drivers to attach, and hands each driver the part of the blob that describes its hardware. A single kernel binary can now run on any board whose DTB it is given. A board revision that changes pin assignments or adds a peripheral needs a new DTB, not a new kernel. The approach originated in the IBM and Apple PowerPC world of the 1990s, where the concept was called *Open Firmware* and the tree was part of the firmware itself. The modern Flattened Device Tree (FDT) format is a descendant, streamlined and reworked to suit bootloaders and kernels that do not carry a whole Forth interpreter the way Open Firmware did. In FreeBSD you will see both names. The framework is called `fdt(4)`, the helpers still live under `sys/dev/ofw/` because of that OpenFirmware lineage, and the functions that read properties are named `OF_getprop`, `OF_child`, `OF_hasprop` for the same reason. When you read *Open Firmware*, *OFW*, and *FDT* in FreeBSD source, they all refer to pieces of the same tradition. ### Architecture Overview: FreeBSD on ARM, RISC-V, and MIPS FreeBSD supports several embedded-friendly architectures in FreeBSD 14.3. The two most actively used are arm64 (the 64-bit ARM architecture called AArch64 in the ARM documentation) and armv7 (32-bit ARM with hardware floating point, sometimes written `armv7` or `armhf`). RISC-V support has matured over FreeBSD 13 and 14 and now runs on real boards like the SiFive HiFive Unmatched and the VisionFive 2. MIPS support existed for a long time and powered many older routers and embedded appliances; it has been removed from the base system in recent releases, so this chapter will not dwell on it, but the skills you learn for ARM and RISC-V would transfer directly if you ever dropped back to a legacy MIPS platform. All of those architectures use Device Tree to describe non-discoverable hardware. The boot flows differ in detail, but the shape is the same: some stage-zero firmware starts the CPU, some stage-one bootloader (U-Boot is common; on arm64 an EFI loader is increasingly standard) loads the kernel and the DTB, and the kernel takes over with the tree in hand. On arm64 the FreeBSD EFI loader handles this cleanly, and the tree can come from either a file on disk (`/boot/dtb/*.dtb`) or, on server-class hardware, from the firmware itself. On armv7 boards, U-Boot usually supplies the DTB. On RISC-V the picture is a mix of OpenSBI, U-Boot, and EFI, depending on the board. None of these differences matter much to a driver author. The tree the kernel sees by the time your driver runs is a Device Tree, the helpers it gives you are `OF_*` and `ofw_bus_*`, and the drivers you write to run against it are portable across architectures that use the same framework. ### Typical Limitations: No ACPI, Limited Buses, Power Constraints It is worth enumerating the limitations of embedded platforms that shape driver work, so that they do not take you by surprise. **No ACPI, usually.** ACPI is the firmware-to-OS interface that most PCs use to describe their non-discoverable hardware. It contains tables, a bytecode language called AML, and a long specification. ARM servers sometimes use ACPI, and FreeBSD supports that path on arm64 with the ACPI subsystem, but small and mid-range embedded boards almost always use FDT. A few high-end arm64 systems may ship with *both* ACPI and FDT descriptions and let the firmware pick between them; FreeBSD can handle either, and on arm64 there is a runtime switch that decides which bus to attach. The practical consequence for most embedded drivers is that you write for FDT and not worry about ACPI. We will return to the dual-support case in Section 3. **No PCI-style discovery for on-SoC peripherals.** A PCI or PCIe device announces itself through vendor and device IDs in a standardised configuration space. The kernel scans the bus, finds the device, and dispatches to a driver that claims the IDs. On-SoC peripherals on an ARM chip do not have that announcement mechanism. The only way the kernel knows a UART is at address `0x7E201000` on a Raspberry Pi 4 is because the DTB says so. This shifts the driver-author's mental model: you do not wait for the bus to hand you a probed device; you wait for simplebus (or the equivalent) to find your node in the tree and dispatch your probe with that node's context. **Power constraints matter.** An embedded board may run on a battery, or from a small USB adapter, or from a power-over-Ethernet feed. A driver that leaves a clock running when the device is idle, or that keeps a regulator enabled past the peripheral's needs, hurts the entire system. FreeBSD provides clock and regulator frameworks precisely so drivers can turn things off when appropriate. We will touch on them in Sections 3, 4, and 7. **Limited RAM and storage.** Embedded boards commonly have between 256 MB and 8 GB of RAM, and between a few hundred megabytes and a few tens of gigabytes of storage. A driver that allocates lavishly or prints a screenful of debug output to the console on every event will consume resources the system may not have. Write for the constraints you expect to face. **A simpler boot flow, for better or worse.** The boot process on an embedded board is usually shorter and less forgiving than on a PC. If the kernel fails to find the root filesystem, you may not have a handy rescue environment. If the DTB is wrong and the right interrupt controller does not attach, the system will hang silently. This is the main reason embedded work benefits from a working debug cable, a serial console, and the habit of making small, testable changes rather than heroic ones. ### Boot Flow: From Firmware to Driver Attachment To make the moving parts concrete, let us walk through what happens from power-on to the first driver attachment on a representative arm64 board. The details vary by board, but the shape is consistent. 1. Power-on: the first CPU core starts executing code from a boot ROM burned into the SoC. This ROM is beyond your control; its job is to load the next stage. 2. The boot ROM reads a stage-one loader from a fixed location (usually the SD card, eMMC, or SPI flash). On Raspberry Pi boards this is the VideoCore firmware; on generic arm64 boards it is usually U-Boot. 3. The stage-one loader does platform bring-up: it configures DRAM, sets up early clocks, initialises a UART for debug output, and loads the next stage. On boards with FreeBSD installed, that next stage is usually the FreeBSD EFI loader (`loader.efi`). 4. The FreeBSD EFI loader reads its configuration from the ESP partition of the boot medium, consults `/boot/loader.conf`, and loads three things: the kernel itself, a DTB from `/boot/dtb/`, and any overlays listed in the `fdt_overlays` tunable from `/boot/dtb/overlays/`. 5. The loader hands control to the kernel along with pointers to the loaded DTB. 6. The kernel starts. Its machine-dependent startup code parses the DTB to find the memory map, the CPU topology, and the root node of the tree. Based on the top-level `compatible` string of the root node, arm64 decides whether to run the FDT path or the ACPI path. 7. On the FDT path, the kernel attaches an `ofwbus` to the tree root and a `simplebus` to the `/soc` node (or the equivalent on that board). Simplebus walks its children and creates a `device_t` for each node with a valid compatible string. 8. For each of those `device_t`s, the kernel runs the usual newbus probe loop. Every driver that has registered with `DRIVER_MODULE(mydrv, simplebus, ...)` gets a chance to probe. The driver whose `probe()` returns the best match wins and has its `attach()` called. The driver then reads properties, allocates resources, and comes up. 9. The attachment process recurses for nested buses (a `simple-bus` child of `/soc`, an I2C controller with its own child devices, a GPIO bank with its own pin consumers), producing the full device tree visible in `dmesg` and `devinfo -r`. 10. By the time init runs, the devices the system needs to boot (UART, SD host, Ethernet, USB, GPIO) have all attached, and userland comes up. That sequence is the backdrop against which every driver in this chapter operates. When you write an FDT-aware driver, you are writing the code that runs at step 8 for your particular node. The surrounding machinery runs with or without you; the part you control is the reading of your node and the allocation of your resources. ### Where to See It for Yourself The fastest way to see a real FDT-based boot is to run FreeBSD 14.3 on a Raspberry Pi 3 or 4. Images are available from the FreeBSD project in the standard arm64 download area, and the setup is well documented. If you do not have the hardware, the second fastest way is to use QEMU's `virt` platform, which emulates a generic arm64 machine with a small set of FDT-described peripherals. The kernel and loader from a normal FreeBSD arm64 release run inside it. A sample QEMU invocation lives in the lab notes later in this chapter. A third option, useful even on an amd64 workstation, is to read `.dts` files and the FreeBSD drivers that consume them. Open `/usr/src/sys/contrib/device-tree/src/arm/bcm2835-rpi-b.dts` or `/usr/src/sys/contrib/device-tree/src/arm64/broadcom/bcm2711-rpi-4-b.dts`. Follow the node structure top-down. Notice how the top-level node has a `compatible` property that names the board. Notice how children describe CPUs, memory, the clock controller, the interrupt controller, the peripheral bus. Then open `/usr/src/sys/arm/broadcom/bcm2835/` in the FreeBSD tree and look at the drivers that consume those nodes. You will start to see how the descriptions and the code meet. ### Wrapping Up This Section Section 1 set the scene. Embedded FreeBSD is not an exotic niche inside the project; it is the project on platforms that do not look like PCs. The architecture the embedded work pushes you toward, thinking of hardware as a set of fixed peripherals on a SoC rather than discoverable devices on a bus, is exactly the architecture Device Tree supports. Device Tree is the bridge between the hardware description that the board designer knows and the driver code that the kernel runs. The rest of this chapter is about learning that bridge well enough to walk across it confidently. In the next section we will slow down and read Device Tree files themselves. Before we can write a driver that consumes them, we need to know how they are structured, what their properties mean, and how a `.dts` source becomes the `.dtb` binary the kernel actually sees. ## Section 2: What Is the Device Tree? A Device Tree is a textual description of hardware organised as a tree of nodes, with each node representing a device or a bus, and each node carrying named properties that describe its addresses, its interrupts, its clocks, its relationships to other nodes, and anything else a driver might need to know. That description is what the embedded world uses in place of PCI enumeration or ACPI tables. In the embedded FreeBSD world you will spend your life reading, writing, and reasoning about these files. The sooner they become friendly, the easier every subsequent chapter will feel. The best way to start is to look at one. ### A Minimal Device Tree Here is the smallest interesting Device Tree source file, in `.dts` form: ```dts /dts-v1/; / { compatible = "acme,trivial-board"; #address-cells = <1>; #size-cells = <1>; chosen { bootargs = "console=ttyS0,115200"; }; memory@80000000 { device_type = "memory"; reg = <0x80000000 0x10000000>; }; uart0: serial@10000000 { compatible = "ns16550a"; reg = <0x10000000 0x100>; interrupts = <5>; clock-frequency = <24000000>; status = "okay"; }; }; ``` That is a complete, valid, if tiny Device Tree. It describes a fictional board called `acme,trivial-board` that has 256 MB of RAM at physical address `0x80000000`, and a 16550-compatible UART at `0x10000000` that delivers interrupt number 5 and runs at 24 MHz. Even if none of the syntax is familiar yet, the intent is legible: the file is a hardware description, written in a compact domain-specific format. Let us unpack it piece by piece. ### The Tree Structure The first line, `/dts-v1/;`, is a mandatory directive declaring the DTS syntax version. Every FreeBSD DTS file you will ever write or read begins with it. Anything before it is not a valid DTS file; treat it like `#!/bin/sh` at the top of a shell script. The rest of the file is enclosed in a single block that starts with `/ {` and ends with `};`. That outer block is the **root node** of the tree. Every Device Tree has exactly one root. Its children are peripherals and sub-buses; their children are further peripherals and sub-buses; and so on. Nodes are identified by **names**. A name like `serial@10000000` consists of a base name (`serial`) and a **unit address** (`10000000`, which is the starting address of the node's first register region written in hexadecimal without the `0x` prefix). The unit address is a convention, not a hard requirement; it exists so that nodes with the same base name can be distinguished (you can have multiple `serial` nodes at different addresses), and it doubles as a readable hint for what the node describes. A **label**, like `uart0:` in `uart0: serial@10000000`, is a handle that lets other parts of the tree refer to this node. Labels let you write `&uart0` elsewhere in the file to mean *the node labelled `uart0`*. We will use labels in the overlay section. Nodes contain **properties**. A property is a name followed by an equals sign, followed by a value, followed by a semicolon: ```dts compatible = "ns16550a"; ``` Some properties have no value; they exist only as flags: ```dts interrupt-controller; ``` The value of a property can be a string (`"ns16550a"`), a list of strings (`"brcm,bcm2711", "brcm,bcm2838"`), a list of integers inside angle brackets (`<0x10000000 0x100>`), a list of references to other nodes (`<&gpio0>`), or a binary byte string (`[01 02 03]`). Most everyday properties are strings, string lists, or integer lists. The tree uses 32-bit *cells* as its fundamental integer unit; the integers inside `<...>` are cells, and 64-bit values are expressed as two consecutive cells (high, low). Let us go back to the minimal example and read each property with fresh eyes. ### Reading the Minimal Example The root node has three properties: ```dts compatible = "acme,trivial-board"; #address-cells = <1>; #size-cells = <1>; ``` The **`compatible`** property is how the root (and any node) tells the world what it is. It is the single most important property in Device Tree. A driver matches on it. The value is a vendor-prefixed string (`"acme,trivial-board"`) or, more commonly, a list of them in decreasing order of specificity. A Raspberry Pi 4 root node, for example, might be `compatible = "raspberrypi,4-model-b", "brcm,bcm2711";` The first string says "exactly this board"; the second says "in the general family of boards using the BCM2711 chip". Drivers that know about the specific board can match the first; drivers that only know about the chip can match the second. The DTS spec calls this a *compatibility list*, and both FreeBSD and Linux respect it. The **`#address-cells`** and **`#size-cells`** properties at the root describe how many 32-bit cells a child node uses for its address and size in `reg` properties. At the root of a 32-bit board, both are typically 1. On a 64-bit board with more than 4 GB of addressable memory, they would both be 2. When you see `reg = <0x80000000 0x10000000>;` under the memory node, you know from the parent's cell counts that this is one address cell and one size cell, which means the region is at `0x80000000` with size `0x10000000`. If `#address-cells` were 2, the region would instead be written `reg = <0x0 0x80000000 0x0 0x10000000>;`. The **`chosen`** node is a special sibling of the root's hardware children. It carries parameters the bootloader wants to pass to the kernel: the boot arguments, the console device, sometimes the initrd location. FreeBSD reads `/chosen/bootargs` and uses it to populate the kernel environment. The **`memory@80000000`** node describes a region of physical memory. Memory nodes carry `device_type = "memory"` and a `reg` property giving their range. FreeBSD's early boot reads these to build its physical memory map. The **`serial@10000000`** node is the interesting one. Its `compatible = "ns16550a"` tells the kernel *this is an ns16550a UART*, which is a very common PC-style serial port chip. Its `reg = <0x10000000 0x100>` says *my registers live at physical address `0x10000000` and occupy `0x100` bytes*. Its `interrupts = <5>` says *I deliver interrupt number 5 to my interrupt parent*. Its `clock-frequency = <24000000>` says *my reference clock runs at 24 MHz, so divisors should be computed from this*. Its `status = "okay"` says *I am enabled*; had it said `"disabled"`, the driver would skip this node. That is essentially what a Device Tree does: it describes each peripheral in a few properties whose meanings are defined by conventions called **bindings**. A binding for a UART tells you what properties a UART node should carry. A binding for an I2C controller tells you what properties an I2C controller node should carry. And so on. The bindings are documented separately, and the FreeBSD tree ships a large library of them under `/usr/src/sys/contrib/device-tree/Bindings/`. ### Source vs Binary: .dts, .dtsi, and .dtb Device Tree files come in three file types that are easy to confuse at first. **`.dts`** is the main source form. A `.dts` file describes a whole board or platform and is what you feed to the compiler. **`.dtsi`** is an include fragment, the `i` standing for *include*. A typical SoC family has a large `.dtsi` describing the SoC itself (its interrupt controller, its clock tree, its on-chip peripherals), and each board that uses that SoC has a small `.dts` that `#include`s the `.dtsi` and then describes the board-specific additions (external devices soldered to the board, pin configuration, chosen node). You will see many `.dtsi` files under `/usr/src/sys/contrib/device-tree/src/arm/` and `/usr/src/sys/contrib/device-tree/src/arm64/`. **`.dtb`** is the compiled binary form. The kernel and bootloader deal with `.dtb` files, not `.dts` files. A `.dtb` is the output of the `dtc` compiler fed a `.dts` source. It is compact, has no whitespace or comments, and is designed to be parsed by a bootloader in a few kilobytes of code. A `.dtb` file for a Raspberry Pi 4 is typically around 30 KB. And a fourth, less common type: **`.dtbo`** is a compiled *overlay*. Overlays are fragments that modify an existing base `.dtb` at load time: they can enable or disable nodes, add new nodes, or change properties. They are the mechanism FreeBSD and many Linux distributions use to let users customise a stock DTB without rebuilding it. `.dtbo` files are compiled from `.dtso` (device-tree-source-overlay) files, and loaded by the bootloader via the `fdt_overlays` tunable. We will meet them in Section 5. When you work with DTS you are almost always writing either a `.dts` or a `.dtso`. You compile either with the device tree compiler, `dtc`, which in FreeBSD lives in the `devel/dtc` port and is installed as `/usr/local/bin/dtc`. The FreeBSD kernel build system invokes `dtc` through the scripts under `/usr/src/sys/tools/fdt/`, specifically `make_dtb.sh` and `make_dtbo.sh`. ### Nodes, Properties, Addresses, and the Phandle A few additional concepts recur so often that it is worth naming them once and for all. **Nodes** are the hierarchical units. Every node has a name, optionally a label, possibly a unit address, and zero or more properties. Nodes nest; a node's children are described inside its enclosing braces. **Properties** are key-value pairs. The keys are strings. The values are typed by convention: `compatible` is a string list, `reg` is an integer list, `status` is a string, `interrupts` is an integer list whose length depends on the interrupt parent, and so on. **Unit addresses** in node names (`serial@10000000`) mirror the first cell of the `reg` property. The DTC compiler warns if they disagree. You should write both consistently. The **`reg`** property describes the memory-mapped register regions of the device. Its format is `
`, with each address-size pair being a contiguous region. Most simple peripherals have exactly one region. Some have several (a peripheral with a main register area and a separate interrupt register block, for example). **Address cells and size cells** are the property pair `#address-cells` and `#size-cells` that live on a parent node and describe how `reg` is formatted in its children. A SoC bus with `#address-cells = <1>; #size-cells = <1>;` lets its children use one cell each for address and size. An I2C bus usually has `#address-cells = <1>; #size-cells = <0>;` because an I2C child has an address but no size. **Interrupts** are described by one or more properties depending on the style used. The older style is `interrupts = <...>;` with the cells interpreted by the interrupt parent's convention. On ARM GIC-based platforms this is a three-cell form: interrupt type, interrupt number, interrupt flags. The newer style, mixed with the old throughout the kernel, is `interrupts-extended = <&gic 0 15 4>;` which explicitly names the interrupt parent. Either way, the cells tell the kernel which hardware interrupt the device raises and under what conditions. A **phandle** is a unique integer assigned by the compiler to each node. Phandles let other nodes refer to this one. When you write `<&gpio0>`, the compiler substitutes the phandle of the node labelled `gpio0`. When you write `<&gpio0 17 0>`, you are passing three cells: the phandle of `gpio0`, the pin number `17`, and a flags cell `0`. The meaning of the cells after the phandle is defined by the *provider*'s binding. This is the pattern by which GPIO consumers, clock consumers, reset consumers, and interrupt consumers talk to their providers: the first cell names the provider, the following cells say which resource and how. The **`status`** property is a small but critical one. A node with `status = "okay";` is enabled, and drivers will probe it. A node with `status = "disabled";` is skipped. Overlays often toggle this property to turn a peripheral on or off without removing the node. FreeBSD's `ofw_bus_status_okay()` is the helper that returns true when a node's status is okay. The **`label`** and **`alias`** mechanisms let you refer to a node by a short name rather than a path. A label like `uart0:` is a file-local handle; an alias defined under the special `/aliases` node (`serial0 = &uart0;`) is a kernel-visible name. FreeBSD makes use of aliases for some devices like the console. That is most of what you need to read a typical Device Tree. A few more exotic pieces appear in specific bindings (for example, `clock-names` and `clocks` for consumers of the clock framework, `reset-names` and `resets` for hwreset consumers, `dma-names` and `dmas` for DMA engine consumers, `pinctrl-0`, `pinctrl-names` for pin control), but they all follow the same *named index list* pattern. ### A More Realistic Example To give you a feel for a real SoC-level fragment, here is an abbreviated node from a BCM2711 (Raspberry Pi 4) description. The full file lives under `/usr/src/sys/contrib/device-tree/src/arm/bcm2711.dtsi`. ```dts soc { compatible = "simple-bus"; #address-cells = <1>; #size-cells = <1>; ranges = <0x7e000000 0x0 0xfe000000 0x01800000>, <0x7c000000 0x0 0xfc000000 0x02000000>, <0x40000000 0x0 0xff800000 0x00800000>; dma-ranges = <0xc0000000 0x0 0x00000000 0x40000000>; gpio: gpio@7e200000 { compatible = "brcm,bcm2711-gpio", "brcm,bcm2835-gpio"; reg = <0x7e200000 0xb4>; interrupts = , ; gpio-controller; #gpio-cells = <2>; interrupt-controller; #interrupt-cells = <2>; }; spi0: spi@7e204000 { compatible = "brcm,bcm2835-spi"; reg = <0x7e204000 0x200>; interrupts = ; clocks = <&clocks BCM2835_CLOCK_VPU>; #address-cells = <1>; #size-cells = <0>; status = "disabled"; }; }; ``` Reading this top-down: - The `soc` node is the on-chip-peripherals bus. Its `compatible = "simple-bus"` is the magic token that tells FreeBSD to attach the simplebus driver here. - Its `ranges` property defines the address translation from bus addresses (the "local" addresses the CPU's peripheral interconnect uses internally, starting at `0x7E000000`) to CPU physical addresses (starting at `0xFE000000`). FreeBSD reads this and applies it when mapping child `reg` properties. - The `gpio` node is the GPIO controller. It claims two interrupts, declares itself a gpio-controller (so other nodes can reference it), and uses two cells per GPIO reference (the first cell is the pin number, the second is a flag word). - The `spi0` node is the SPI controller at bus address `0x7E204000`. It is `status = "disabled"` in the base description, meaning it does not attach until an overlay enables it. Every embedded board description looks roughly like this: a tree of on-chip peripherals, each with a compatible string identifying what driver to bind, a `reg` for its memory-mapped registers, an `interrupts` for its IRQ line, and possibly references to clocks, resets, regulators, and pins. ### How the DTB Is Loaded For completeness, it helps to know how the DTB goes from disk to kernel at boot. On an arm64 board running FreeBSD 14.3, the typical flow is: 1. The EFI firmware or bootloader reads the FreeBSD EFI loader from the ESP. 2. The FreeBSD loader loads the kernel from `/boot/kernel/kernel` and the DTB from `/boot/dtb/.dtb`. The DTB's filename is selected based on the SoC family. 3. If `/boot/loader.conf` sets `fdt_overlays="overlay1,overlay2"`, the loader reads `/boot/dtb/overlays/overlay1.dtbo` and `/boot/dtb/overlays/overlay2.dtbo`, applies them to the base DTB in memory, and hands the merged result to the kernel. 4. The kernel takes the merged DTB as its authoritative hardware description. On U-Boot-driven boards (common for armv7) the flow is similar but the loader is U-Boot itself. U-Boot's environment variables `fdt_file` and `fdt_addr` tell it which DTB to load and where to place it. When U-Boot finally does `bootefi` or `booti`, it passes the DTB to the FreeBSD loader or directly to the kernel. On EFI systems that ship FDT in their firmware (rare for small boards, common for ARM servers that use the Server Base System Architecture), the firmware stores the DTB as an EFI configuration table and the kernel reads it from there. For a driver author, the details of boot do not matter most of the time. What matters is that by the time your driver's probe is called, the tree has been loaded, parsed, and presented to the kernel; you read it with the same `OF_*` helpers no matter how it got there. ### Wrapping Up This Section Section 2 introduced Device Tree as a hardware-description language. You have seen a minimal example, you have met the core concepts of nodes and properties, you know the difference between `.dts`, `.dtsi`, `.dtb`, and `.dtbo` files, and you have walked through a realistic fragment of a SoC description. You also know how a DTB reaches the kernel at boot. What you do *not* yet know is how FreeBSD's kernel consumes the tree once it is loaded: which subsystem attaches to it, which helpers drivers call to read properties, and how a driver's `probe()` and `attach()` find their node. That is Section 3. ## Section 3: FreeBSD's Device Tree Support FreeBSD handles Device Tree through a framework whose design predates FDT itself. The framework is named after Open Firmware, abbreviated **OFW** throughout the source tree, because the API it grew out of originally served PowerPC Macs and IBM systems that used the real Open Firmware specification. When the ARM world standardised on Flattened Device Tree in the late 2000s, FreeBSD mapped FDT onto the same internal API. A driver in FreeBSD 14.3 therefore calls the same `OF_getprop()` whether it is running on a PowerPC Mac, an ARM board with an FDT blob, or a RISC-V board with an FDT blob. The implementation beneath differs; the interface above is uniform. This section introduces the pieces of that framework you need to know: the `fdt(4)` interface as it is used in practice, the `ofw_bus` helpers that drivers call on top of the raw `OF_*` primitives, the `simplebus(4)` bus driver that enumerates children, and the property-reading idioms you will use constantly. By the end of the section you will know what code already exists on the FreeBSD side and where it lives; Section 4 will then build a driver on top of it. ### The fdt(4) Framework Overview `fdt(4)` is the kernel's Flattened Device Tree support. It provides the code that parses the binary `.dtb`, walks it to find nodes, extracts properties, applies overlays, and presents the result through the `OF_*` API. You can think of `fdt(4)` as the lower half and `ofw_bus` as the upper half, with `OF_*` functions spanning both. The code that implements the FDT side of the OFW interface lives in `/usr/src/sys/dev/ofw/ofw_fdt.c`. It is a specific instance of the `ofw_if.m` kobj interface. When the kernel calls `OF_getprop()`, the call goes through the interface and ends up in the FDT implementation, which walks the flattened blob. On a PowerPC Mac it would end up in the real Open Firmware implementation instead; the drivers above do not need to know or care. For your purposes as a driver author, you almost never touch `ofw_fdt.c` directly. You use the helpers one layer up. ### OF_*: The Raw Property Readers The lowest-level API that drivers call is the `OF_*` family of functions declared in `/usr/src/sys/dev/ofw/openfirm.h`. The ones you will use most are a small set. `OF_getprop(phandle_t node, const char *prop, void *buf, size_t len)` reads a property's raw bytes into a caller-supplied buffer. It returns the number of bytes read on success, or `-1` on failure. The buffer must be large enough for the expected length. `OF_getencprop(phandle_t node, const char *prop, pcell_t *buf, size_t len)` reads a property whose cells are big-endian and converts them to host byte order as it copies. Almost any property that contains integers should be read with this variant rather than `OF_getprop()`. `OF_getprop_alloc(phandle_t node, const char *prop, void **buf)` reads a property of unknown length. The kernel allocates a buffer and returns the pointer through the third argument. When you are done, call `OF_prop_free(buf)` to release it. `OF_hasprop(phandle_t node, const char *prop)` returns non-zero if the named property exists, zero otherwise. Useful for optional properties where the mere presence is meaningful. `OF_child(phandle_t node)` returns the first child of a node. `OF_peer(phandle_t node)` returns the next sibling. `OF_parent(phandle_t node)` returns the parent. Combined, they let you walk the tree. `OF_finddevice(const char *path)` returns a phandle for the node at a given path, such as `"/chosen"` or `"/soc/gpio@7e200000"`. Most drivers do not need this because the framework hands them their node already. `OF_decode_addr(phandle_t dev, int regno, bus_space_tag_t *tag, bus_space_handle_t *hp, bus_size_t *sz)` is a convenience routine used by very early code (serial console drivers, mostly) to set up a bus-space mapping for register `regno` of a given node without going through newbus. Normal drivers use `bus_alloc_resource_any()` instead, which reads the `reg` property via the resource list set up during probe. These primitives are the foundation. In practice you will call them indirectly through the slightly more convenient `ofw_bus_*` helpers, but the ones above are what those helpers use internally, and it is worth recognising them when you read real driver code. ### ofw_bus: The Compatibility Helpers The most common thing an FDT-aware driver does is ask: *is this device compatible with something I know how to drive?* FreeBSD provides a small layer of helpers on top of `OF_getprop` to make those checks idiomatic. They live in `/usr/src/sys/dev/ofw/ofw_bus.h` and `/usr/src/sys/dev/ofw/ofw_bus_subr.h`, with their implementations in `/usr/src/sys/dev/ofw/ofw_bus_subr.c`. The helpers worth knowing, in the order you will meet them: `ofw_bus_get_node(device_t dev)` returns the phandle associated with a `device_t`. It is implemented as an inline that calls the parent bus's `OFW_BUS_GET_NODE` method. For a child of simplebus, this returns the phandle of the DTS node that gave rise to this device. `ofw_bus_status_okay(device_t dev)` returns 1 if the node's `status` property is absent, empty, or `"okay"`; 0 otherwise. Every FDT-aware probe should call it at the top to skip disabled nodes. `ofw_bus_is_compatible(device_t dev, const char *string)` returns 1 if any entry of the node's `compatible` property exactly equals `string`. Short, precise, and the usual tool when a driver only wants one compatible string. `ofw_bus_search_compatible(device_t dev, const struct ofw_compat_data *table)` walks a driver-provided table and returns the matching entry if any of its compatible strings is in the node's `compatible` list. This is the standard way a driver that supports multiple chips registers its compatibility. The table is an array of entries, each containing a string and a `uintptr_t` cookie the driver can use to remember which chip matched; the table ends with a sentinel entry whose string is `NULL`. We will see the full pattern in Section 4. `ofw_bus_has_prop(device_t dev, const char *prop)` is a convenience wrapper over `OF_hasprop(ofw_bus_get_node(dev), prop)`. `ofw_bus_get_name(device_t dev)`, `ofw_bus_get_compat(device_t dev)`, `ofw_bus_get_type(device_t dev)`, and `ofw_bus_get_model(device_t dev)` return the corresponding strings from the node, or `NULL` if absent. Those are the bread-and-butter helpers. You will see them at the top of almost every FDT-aware driver's probe and attach routines. ### simplebus: The Default Enumerator The simplebus driver is the piece that makes all of this work in practice. It lives in `/usr/src/sys/dev/fdt/simplebus.c` and its header is at `/usr/src/sys/dev/fdt/simplebus.h`. Simplebus has two jobs. Its first job is to enumerate children. When the kernel attaches simplebus to a node whose `compatible` includes `"simple-bus"` (or whose `device_type` is `"soc"`, for historical reasons), simplebus walks the node's children, creates a `device_t` for each child that has a `compatible` property, and feeds them into newbus. This is what makes your driver's probe get called at all; simplebus is the bus your driver registers with via `DRIVER_MODULE(mydrv, simplebus, ...)`. Its second job is to translate child addresses into CPU physical addresses. The parent node's `ranges` property encodes how the bus-local addresses that appear in children's `reg` properties map to CPU physical addresses. Simplebus reads `ranges` in `simplebus_fill_ranges()` and applies it when setting up each child's resource list, so by the time your driver asks for its memory resource, the region is already in CPU physical space. The central probe code that decides whether simplebus should attach to a given node sits near the top of `/usr/src/sys/dev/fdt/simplebus.c`. Here it is, stripped of comments for brevity: ```c if (!ofw_bus_status_okay(dev)) return (ENXIO); if (ofw_bus_is_compatible(dev, "syscon") || ofw_bus_is_compatible(dev, "simple-mfd")) return (ENXIO); if (!(ofw_bus_is_compatible(dev, "simple-bus") && ofw_bus_has_prop(dev, "ranges")) && (ofw_bus_get_type(dev) == NULL || strcmp(ofw_bus_get_type(dev), "soc") != 0)) return (ENXIO); device_set_desc(dev, "Flattened device tree simple bus"); return (BUS_PROBE_GENERIC); ``` That snippet is a compact exemplar of the entire probe style. Test `status`, reject the known exceptions, confirm the node looks like a simple bus, describe the device, and return a probe confidence. Every FDT-aware probe in the tree follows some variation of this shape. Simplebus registers itself with two parent buses. On the primary ofw root, it registers via `EARLY_DRIVER_MODULE(simplebus, ofwbus, ...)`; and recursively, on itself, via `EARLY_DRIVER_MODULE(simplebus, simplebus, ...)`. The recursion is how nested simple-bus nodes get enumerated: a simplebus parent that encounters a child whose compatible is `"simple-bus"` attaches another simplebus instance to it, which then enumerates *its* children. For most driver work you do not need to know more about simplebus than that it exists and that you register with it. Your driver's module registration will read `DRIVER_MODULE(mydrv, simplebus, mydrv_driver, 0, 0);` and everything downstream will happen automatically. ### Mapping the Pieces to a Probe Call To put the moving parts together, let us trace what happens from the DTB being loaded to your driver's probe being called. 1. The loader hands the kernel a DTB. 2. The kernel's early arm64 code parses the DTB to find memory and CPU information. 3. The `ofwbus0` pseudo-device attaches to the tree root. 4. `ofwbus0` creates a `device_t` for the `/soc` node (or whichever node has `compatible = "simple-bus"`) and dispatches the usual newbus probe loop. 5. The simplebus driver's probe runs, returns `BUS_PROBE_GENERIC`, and is picked. 6. Simplebus's attach walks the children of the `/soc` node and creates a `device_t` for each child. Each child's resource list is populated from its `reg` and `interrupts` properties, translated through the parent's `ranges`. 7. For each child, the newbus probe loop runs. Every driver registered to simplebus gets a chance to probe. 8. Your driver's probe is called. It calls `ofw_bus_status_okay()`, `ofw_bus_search_compatible()`, and (if it matches) returns `BUS_PROBE_DEFAULT`. 9. If your driver wins the probe contest for this node, its attach is called. At that point the `device_t` has a resource list already populated with the node's memory and interrupt information. 10. Your driver calls `bus_alloc_resource_any()` for its memory region and for its interrupt, sets up an interrupt handler if it has one, maps the memory, initialises the hardware, and returns 0 to indicate success. From the driver author's perspective the first six steps are machinery; steps 7 through 10 are the code you write. The chapter will now zoom in on those four steps. ### Registering a Driver with ofw_bus When your driver registers with simplebus, it is implicitly opting into the OFW dispatch. The module registration line is: ```c DRIVER_MODULE(mydrv, simplebus, mydrv_driver, 0, 0); ``` That tells newbus: *attach the driver described by `mydrv_driver` as a child of simplebus*. Your `device_method_t` array must supply at minimum a `device_probe` and a `device_attach` method. If you have a detach, add `device_detach`. If your driver also implements OFW interface methods (rarely needed at the leaf level), add those too. On some platforms, and for drivers that want to attach both to simplebus and to the `ofwbus` root (in case there is no simplebus between them and the root), it is common to add a second registration: ```c DRIVER_MODULE(mydrv, ofwbus, mydrv_driver, 0, 0); ``` This is what `gpioled_fdt.c` does, for example. It covers platforms where the `gpio-leds` node sits directly under the root rather than under a `simple-bus`. ### Writing a Compatibility Table A driver that supports more than one variant of a chip typically declares a table of compatible strings: ```c static const struct ofw_compat_data compat_data[] = { { "brcm,bcm2711-gpio", 1 }, { "brcm,bcm2835-gpio", 2 }, { NULL, 0 } }; ``` Then in probe: ```c static int mydrv_probe(device_t dev) { if (!ofw_bus_status_okay(dev)) return (ENXIO); if (ofw_bus_search_compatible(dev, compat_data)->ocd_str == NULL) return (ENXIO); device_set_desc(dev, "My FDT-Aware Driver"); return (BUS_PROBE_DEFAULT); } ``` And in attach, the matched entry is available for re-lookup: ```c static int mydrv_attach(device_t dev) { const struct ofw_compat_data *match; ... match = ofw_bus_search_compatible(dev, compat_data); if (match == NULL || match->ocd_str == NULL) return (ENXIO); sc->variant = match->ocd_data; /* 1 for BCM2711, 2 for BCM2835 */ ... } ``` The `ocd_data` field is the cookie you defined in the table. It is a plain `uintptr_t`, so you can use it as an integer discriminator, a pointer to a per-variant structure, or whatever fits your driver's needs. ### Reading Properties Once you have a `device_t`, reading its node's properties is straightforward. A typical pattern: ```c phandle_t node = ofw_bus_get_node(dev); uint32_t val; if (OF_getencprop(node, "clock-frequency", &val, sizeof(val)) <= 0) { device_printf(dev, "missing clock-frequency\n"); return (ENXIO); } ``` The helpers are `OF_getencprop` for integer properties (with endianness handled), `OF_getprop` for raw buffers, `OF_getprop_alloc` for strings of unknown length. For boolean properties (ones whose presence is the signal and whose value is empty), `OF_hasprop` is the idiom: ```c bool want_rts = OF_hasprop(node, "uart-has-rtscts"); ``` For list properties, `OF_getprop_alloc` or the fixed-buffer variants let you pull the full list and iterate over it. ### Acquiring Resources Memory and interrupt resources come through the standard `bus_alloc_resource_any()` calls you already know: ```c sc->mem_rid = 0; sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid, RF_ACTIVE); if (sc->mem_res == NULL) { device_printf(dev, "cannot allocate memory\n"); return (ENXIO); } sc->irq_rid = 0; sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid, RF_ACTIVE | RF_SHAREABLE); ``` This is possible because simplebus has already read your node's `reg` and `interrupts` properties, translated them through the parent's `ranges`, and stored them in the resource list. The indices `0`, `1`, `2` refer to the first, second, and third entries of the respective list. A device with multiple `reg` regions will have multiple memory resources at rids `0`, `1`, `2`, and so on. For anything beyond plain memory and interrupts, you reach into the peripheral frameworks. ### Peripheral Frameworks: Clock, Regulator, Reset, Pinctrl, GPIO Embedded peripherals usually need more than just a memory region. They need a clock turned on, a regulator enabled, a reset line de-asserted, perhaps pins multiplexed, and sometimes a GPIO to drive a chip-select or an enable. FreeBSD provides a coherent set of frameworks for each. **Clock framework.** Declared in `/usr/src/sys/dev/extres/clk/clk.h`. A consumer calls `clk_get_by_ofw_index(dev, node, idx, &clk)` to acquire a handle to the N-th clock listed in the node's `clocks` property, or `clk_get_by_ofw_name(dev, node, "fck", &clk)` to acquire the clock whose `clock-names` entry is `"fck"`. With a handle in hand, the consumer calls `clk_enable(clk)` to turn it on, `clk_get_freq(clk, &freq)` to ask its rate, and `clk_disable(clk)` to turn it off on shutdown. **Regulator framework.** Declared in `/usr/src/sys/dev/extres/regulator/regulator.h`. `regulator_get_by_ofw_property(dev, node, "vdd-supply", ®)` fetches a regulator by the named property; `regulator_enable(reg)` enables it; `regulator_disable(reg)` disables it. **Hardware-reset framework.** Declared in `/usr/src/sys/dev/extres/hwreset/hwreset.h`. `hwreset_get_by_ofw_name(dev, node, "main", &rst)` fetches a reset line; `hwreset_deassert(rst)` brings the peripheral out of reset; `hwreset_assert(rst)` puts it back. **Pin control framework.** Declared in `/usr/src/sys/dev/fdt/fdt_pinctrl.h`. `fdt_pinctrl_configure_by_name(dev, "default")` applies the pin configuration associated with the `pinctrl-names = "default"` slot of the node. Most drivers that need pin control simply call this once from attach. **GPIO framework.** The consumer side is declared in `/usr/src/sys/dev/gpio/gpiobusvar.h`. `gpio_pin_get_by_ofw_idx(dev, node, idx, &pin)` fetches the N-th GPIO listed in the node's `gpios` property. `gpio_pin_setflags(pin, GPIO_PIN_OUTPUT)` sets its direction. `gpio_pin_set_active(pin, value)` drives its level. `gpio_pin_release(pin)` gives it back. These frameworks are the reason embedded drivers in FreeBSD are often shorter than their Linux counterparts. You do not have to write the clock tree, the regulator logic, or the GPIO controller: you consume them through a uniform consumer API, and the provider drivers are someone else's problem. The worked example in Section 7 uses the GPIO consumer API end to end. ### Interrupt Routing: A Quick Look at interrupt-parent Interrupts on FDT platforms use a chained lookup scheme. A node's `interrupts` property gives the raw interrupt specifier, and the node's `interrupt-parent` property (or the nearest ancestor's) names the controller that should interpret it. That controller, in turn, may be a child of another controller (a secondary GIC redistributor, a nested PLIC, an I/O APIC-like bridge on some SoCs), which further routes the interrupt upward until it reaches a top-level controller bound to a real CPU vector. For a driver author, you do not usually have to think about this chain. The kernel's interrupt resource already lives in your resource list as a cookie that the interrupt controller knows how to interpret, and `bus_setup_intr()` hands the cookie back to the controller when you ask for an IRQ. What matters is that your node has the right `interrupts = <...>;` for its immediate interrupt parent, and that the tree's `interrupt-parent` or `interrupts-extended` chain reaches a real controller. When it does not, your interrupt will be silently dropped at boot. The internals live in `/usr/src/sys/dev/ofw/ofw_bus_subr.c`, with `ofw_bus_lookup_imap()`, `ofw_bus_setup_iinfo()`, and related helpers. You will probably never call them directly unless you are writing a bus driver. ### A Brief Look at Overlays We have mentioned overlays several times. The short version is that an overlay is a small DTB fragment that references nodes in the base tree by label (for example, `&i2c0` or `&gpio0`) and adds or modifies properties or children. The loader merges overlays into the base blob before the kernel sees it. We will return to overlays in Section 5 and use them in the worked example in Section 7; for now just note that FreeBSD supports them through the `fdt_overlays` loader tunable and the files under `/boot/dtb/overlays/`. ### ACPI vs FDT on arm64 The arm64 port of FreeBSD supports both FDT and ACPI as discovery mechanisms. Which path the kernel takes is decided during early boot by looking at what the firmware provided. If a DTB was supplied and the top-level `compatible` does not suggest an ACPI path, the kernel attaches the FDT bus. If an ACPI RSDP was supplied and the firmware indicates SBSA compliance, the kernel attaches the ACPI bus. The relevant code is in `/usr/src/sys/arm64/arm64/nexus.c`, which handles both paths; the variable `arm64_bus_method` records which one was chosen. The practical consequence for driver authors is that a driver written for both mechanisms has to attach to both buses. Drivers that only care about FDT (the majority of small embedded drivers) register with simplebus only. Drivers that serve generic hardware that can show up on either ARM servers (ACPI) or ARM embedded boards (FDT) register with both. The `ahci_generic` driver at `/usr/src/sys/dev/ahci/ahci_generic.c` is one such dual-supporting driver; its source is worth reading when you eventually need to write one. For most of this chapter we will stay on the pure FDT side. ### Wrapping Up This Section Section 3 gave you the map of FreeBSD's FDT support. You now know where the core code lives, which helpers to use for which job, and how the pieces connect: `fdt(4)` parses the tree, `OF_*` primitives read properties, `ofw_bus_*` helpers wrap the primitives into idiomatic checks, simplebus enumerates the children, and the peripheral frameworks hand you clocks, resets, regulators, pins, and GPIOs. In the next section we will take those pieces and write a real driver with them. Section 4 walks through the full skeleton of an FDT-aware driver from top to bottom, in enough detail that you could copy the structure into your own project and start filling in the hardware-specific logic. ## Section 4: Writing a Driver for an FDT-Based System This section walks through the complete shape of an FDT-aware FreeBSD driver. The shape is simple; the reason to lay it out in full is that once you have seen it, every FDT driver in the tree becomes legible. You will start noticing the same patterns in hundreds of files under `/usr/src/sys/dev/` and `/usr/src/sys/arm/`, and each of those drivers becomes one more template you can adapt. We will build the skeleton in six passes. First the header includes. Then the softc. Then the compatibility table. Then `probe()`. Then `attach()`. Then `detach()` and the module registration. Each pass is short; by the end you will have a complete, compilable minimal driver that prints a message when the kernel matches it to a Device Tree node. ### The Header Includes FDT drivers lean on a handful of headers from the `ofw` and `fdt` directories on top of the usual kernel and bus headers. A typical set: ```c #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ``` Nothing exotic. The three `ofw` headers bring in the property readers and the compatibility helpers. If your driver is a consumer of GPIOs, clocks, regulators, or hwreset, add their headers as well: ```c #include #include #include #include ``` Pinctrl: ```c #include ``` And `simplebus.h` if your driver actually extends simplebus rather than just binding to it as a leaf: ```c #include ``` Most leaf drivers do not need the simplebus header. Bring it in only when you are implementing a bus-like driver that enumerates children. ### The Softc A softc for an FDT-aware driver is a plain softc with a few additional fields to track resources and references you acquired through the OFW helpers: ```c struct mydrv_softc { device_t dev; struct resource *mem_res; /* memory region (bus_alloc_resource) */ int mem_rid; struct resource *irq_res; /* interrupt resource, if any */ int irq_rid; void *irq_cookie; /* FDT-specific state. */ phandle_t node; uintptr_t variant; /* matched ocd_data */ /* Example: acquired GPIO pin for driving a chip-select. */ gpio_pin_t cs_pin; /* Example: acquired clock handle. */ clk_t clk; /* Usual driver state: mutex, buffers, etc. */ struct mtx sc_mtx; }; ``` The fields that differ from a PCI or ISA driver are `node`, `variant`, and the consumer handles (`cs_pin`, `clk`, and others). Everything else is standard. ### The Compatibility Table The compatibility table is the driver's claim on a set of Device Tree nodes. It is conventionally declared file-scope and immutable: ```c static const struct ofw_compat_data mydrv_compat_data[] = { { "acme,trivial-timer", 1 }, { "acme,fancy-timer", 2 }, { NULL, 0 } }; ``` The second field, `ocd_data`, is a `uintptr_t` cookie. I like to use it as an integer discriminator (1 for the basic variant, 2 for the fancy variant); you can also use it as a pointer to a per-variant configuration structure. The table ends with a sentinel entry whose first field is `NULL`. ### The Probe Routine A canonical probe for an FDT-aware driver: ```c static int mydrv_probe(device_t dev) { if (!ofw_bus_status_okay(dev)) return (ENXIO); if (ofw_bus_search_compatible(dev, mydrv_compat_data)->ocd_str == NULL) return (ENXIO); device_set_desc(dev, "ACME Trivial Timer"); return (BUS_PROBE_DEFAULT); } ``` Three lines of logic. First, bail out if the node is disabled. Second, bail out if none of our compatible strings match. Third, set a descriptive name and return `BUS_PROBE_DEFAULT`. The exact return value matters when more than one driver might claim the same node; a more specialised driver can return `BUS_PROBE_SPECIFIC` to outrank a generic one, and a generic fallback can return `BUS_PROBE_GENERIC` to let anything better win. For most drivers, `BUS_PROBE_DEFAULT` is correct. The `ofw_bus_search_compatible(dev, compat_data)` call returns a pointer to the matching entry, or to the sentinel entry if no match was found. The sentinel's `ocd_str` is `NULL`, so testing for `NULL` is the idiomatic way to say *we did not match anything*. Some drivers alternatively save the returned pointer into a local variable and re-use it; we will do that in attach. ### The Attach Routine Attach is where the real work happens. A canonical FDT attach: ```c static int mydrv_attach(device_t dev) { struct mydrv_softc *sc; const struct ofw_compat_data *match; phandle_t node; uint32_t freq; int err; sc = device_get_softc(dev); sc->dev = dev; sc->node = ofw_bus_get_node(dev); node = sc->node; /* Remember which variant we matched. */ match = ofw_bus_search_compatible(dev, mydrv_compat_data); if (match == NULL || match->ocd_str == NULL) return (ENXIO); sc->variant = match->ocd_data; /* Pull any required properties. */ if (OF_getencprop(node, "clock-frequency", &freq, sizeof(freq)) <= 0) { device_printf(dev, "missing clock-frequency property\n"); return (ENXIO); } /* Allocate memory and interrupt resources. */ sc->mem_rid = 0; sc->mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->mem_rid, RF_ACTIVE); if (sc->mem_res == NULL) { device_printf(dev, "cannot allocate memory resource\n"); err = ENXIO; goto fail; } sc->irq_rid = 0; sc->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irq_rid, RF_ACTIVE | RF_SHAREABLE); if (sc->irq_res == NULL) { device_printf(dev, "cannot allocate IRQ resource\n"); err = ENXIO; goto fail; } /* Enable clock, if one is described. */ if (clk_get_by_ofw_index(dev, node, 0, &sc->clk) == 0) { err = clk_enable(sc->clk); if (err != 0) { device_printf(dev, "could not enable clock: %d\n", err); goto fail; } } /* Apply pinctrl default, if any. */ (void)fdt_pinctrl_configure_by_name(dev, "default"); /* Initialise locks and driver state. */ mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); /* Hook up the interrupt handler. */ err = bus_setup_intr(dev, sc->irq_res, INTR_TYPE_MISC | INTR_MPSAFE, NULL, mydrv_intr, sc, &sc->irq_cookie); if (err != 0) { device_printf(dev, "could not setup interrupt: %d\n", err); goto fail; } device_printf(dev, "variant %lu at %s, clock %u Hz\n", (unsigned long)sc->variant, device_get_nameunit(dev), freq); return (0); fail: mydrv_detach(dev); return (err); } ``` That is a lot to unpack. Let us walk it. 1. `device_get_softc(dev)` returns the driver's softc, which FreeBSD allocated on your behalf when the driver attached. 2. `ofw_bus_get_node(dev)` returns the phandle for our DT node. We save it on the softc because detach will also want it. 3. We re-run the compat search and record which variant matched. 4. We read a scalar integer property with `OF_getencprop`. The call returns the number of bytes read, `-1` on absence, or some smaller number if the property is too short. We treat anything non-positive as failure. 5. We allocate our memory and IRQ resources. Simplebus has already populated the resource list from the node's `reg` and `interrupts`, so indices 0 and 0 are correct. 6. We try to acquire a clock. This driver treats the clock as optional, so a missing `clocks` property is not fatal. If one is present, we enable it. 7. We apply default pin control. 8. We initialise a driver mutex. 9. We set up the interrupt handler, which will dispatch to `mydrv_intr`. 10. We log a message. 11. On any error, we goto a single cleanup path that calls detach. The single cleanup path deserves its own discussion. It is an embedded-friendly pattern because embedded drivers acquire many resources from many different frameworks, and attempting to write out cleanup code at every failure point rapidly becomes unreadable. Instead, write a detach that handles partially-initialised softc state, and call it from the failure path. This is the pattern the FreeBSD tree uses consistently; your driver will be easier to read if you follow it. ### The Detach Routine A compliant detach tears down everything attach might have set up, and does so in the reverse order: ```c static int mydrv_detach(device_t dev) { struct mydrv_softc *sc; sc = device_get_softc(dev); if (sc->irq_cookie != NULL) { bus_teardown_intr(dev, sc->irq_res, sc->irq_cookie); sc->irq_cookie = NULL; } if (sc->irq_res != NULL) { bus_release_resource(dev, SYS_RES_IRQ, sc->irq_rid, sc->irq_res); sc->irq_res = NULL; } if (sc->mem_res != NULL) { bus_release_resource(dev, SYS_RES_MEMORY, sc->mem_rid, sc->mem_res); sc->mem_res = NULL; } if (sc->clk != NULL) { clk_disable(sc->clk); clk_release(sc->clk); sc->clk = NULL; } if (mtx_initialized(&sc->sc_mtx)) mtx_destroy(&sc->sc_mtx); return (0); } ``` Two things to notice. First, every teardown step is guarded by a check on whether the resource was actually acquired. The check lets detach run correctly from either a normal unload path (all resources were acquired) or a failed-attach path (only some were). Second, the order is the reverse of acquisition. Interrupt handler off before interrupt resource released. Clock disabled before released. Mutex destroyed last. ### Interrupt Handler The interrupt handler is a normal FreeBSD interrupt routine. Nothing is FDT-specific about it: ```c static void mydrv_intr(void *arg) { struct mydrv_softc *sc = arg; mtx_lock(&sc->sc_mtx); /* Handle the hardware event. */ mtx_unlock(&sc->sc_mtx); } ``` What *is* FDT-specific is the way the interrupt resource was set up in attach. The resource came from the node's `interrupts` property via simplebus, which translated it through the interrupt-parent chain so that by the time your driver called `bus_alloc_resource_any(SYS_RES_IRQ, ...)`, the resource already represented a real hardware interrupt at a real controller. ### Module Registration The driver's module registration ties the device methods to the driver and registers the driver with a parent bus: ```c static device_method_t mydrv_methods[] = { DEVMETHOD(device_probe, mydrv_probe), DEVMETHOD(device_attach, mydrv_attach), DEVMETHOD(device_detach, mydrv_detach), DEVMETHOD_END }; static driver_t mydrv_driver = { "mydrv", mydrv_methods, sizeof(struct mydrv_softc) }; DRIVER_MODULE(mydrv, simplebus, mydrv_driver, 0, 0); DRIVER_MODULE(mydrv, ofwbus, mydrv_driver, 0, 0); MODULE_VERSION(mydrv, 1); SIMPLEBUS_PNP_INFO(mydrv_compat_data); ``` The two `DRIVER_MODULE` calls register the driver with both simplebus and the ofwbus root. The latter covers platforms or boards whose node sits directly under the root rather than under an explicit simple-bus. `MODULE_VERSION` declares the driver's version for `kldstat` and dependency tracking. `SIMPLEBUS_PNP_INFO` emits a pnpinfo descriptor that `kldstat -v` can print; it is a small courtesy to the operator but the driver will work without it. ### The Full Skeleton Assembled Here is the skeleton assembled into a single minimal file that compiles as a kernel module. It does nothing useful; it only demonstrates attachment and logs a message when matched: ```c #include #include #include #include #include #include #include #include #include #include #include struct fdthello_softc { device_t dev; phandle_t node; }; static const struct ofw_compat_data compat_data[] = { { "freebsd,fdthello", 1 }, { NULL, 0 } }; static int fdthello_probe(device_t dev) { if (!ofw_bus_status_okay(dev)) return (ENXIO); if (ofw_bus_search_compatible(dev, compat_data)->ocd_str == NULL) return (ENXIO); device_set_desc(dev, "FDT Hello Example"); return (BUS_PROBE_DEFAULT); } static int fdthello_attach(device_t dev) { struct fdthello_softc *sc; sc = device_get_softc(dev); sc->dev = dev; sc->node = ofw_bus_get_node(dev); device_printf(dev, "attached, node phandle 0x%x\n", sc->node); return (0); } static int fdthello_detach(device_t dev) { device_printf(dev, "detached\n"); return (0); } static device_method_t fdthello_methods[] = { DEVMETHOD(device_probe, fdthello_probe), DEVMETHOD(device_attach, fdthello_attach), DEVMETHOD(device_detach, fdthello_detach), DEVMETHOD_END }; static driver_t fdthello_driver = { "fdthello", fdthello_methods, sizeof(struct fdthello_softc) }; DRIVER_MODULE(fdthello, simplebus, fdthello_driver, 0, 0); DRIVER_MODULE(fdthello, ofwbus, fdthello_driver, 0, 0); MODULE_VERSION(fdthello, 1); ``` And its matching `Makefile`: ```make KMOD= fdthello SRCS= fdthello.c SYSDIR?= /usr/src/sys .include ``` You will find both under `examples/part-07/ch32-fdt-embedded/lab01-fdthello/`. Build them on any FreeBSD system that has the kernel sources installed. The module will only *attach* on a platform that has a Device Tree containing a node with `compatible = "freebsd,fdthello"`, but it will at least compile and load cleanly even on amd64. ### What the Kernel Does Next When you load that module on an arm64 system whose DTB contains a matching node, the sequence is: 1. The module registers `fdthello_driver` with simplebus and ofwbus. 2. Newbus iterates over every existing device that has `simplebus` or `ofwbus` as a parent and calls the newly registered driver's probe. 3. For each device whose node has `compatible = "freebsd,fdthello"`, the probe returns `BUS_PROBE_DEFAULT`. If no other driver is already attached (or if we outrank it), our attach is called. 4. Attach logs a message; the device is now attached. When you unload the module, detach runs for each attached instance, then the module is unloaded. In the simple case, `kldunload fdthello` cleans up fully. ### Checking Your Work Three quick ways to tell whether your driver matched: 1. **`dmesg`** should show a line like: ``` fdthello0: on simplebus0 fdthello0: attached, node phandle 0x8f ``` 2. **`devinfo -r`** should show your device attached somewhere under `simplebus`. 3. **`sysctl dev.fdthello.0.%parent`** should confirm the parent bus. If your module loads but no devices attach, the probe did not match. The most common causes are a typo in the compatible string, a missing or disabled node, or a node that sits somewhere the simplebus/ofwbus drivers did not reach. Section 6 goes into the debugging in detail. ### A Note on Naming and Vendor Prefixes Real FreeBSD drivers match on compatibility strings like `"brcm,bcm2711-gpio"`, `"allwinner,sun50i-a64-mmc"`, or `"st,stm32-uart"`. The prefix before the comma is the vendor or community name; the rest is the specific chip or family. The convention is widely respected both in upstream Linux and in FreeBSD. When inventing a new compatible for an experiment (as we did above with `"freebsd,fdthello"`), follow the same vendor-slash-identifier form. Do not invent one-word compatibles; they collide with existing ones and confuse future readers. ### Wrapping Up This Section Section 4 walked through the shape of an FDT driver. You have seen the headers to include, the softc to define, the compatibility table to declare, the probe and attach and detach routines to write, and the module registration that ties it all together. You have a minimal, complete driver that you could compile and load right now. It does not do much, but its structure is the same structure every FDT-aware driver in FreeBSD uses. In the next section we turn to the other half of the story. A driver is no use without a Device Tree node to match. Section 5 teaches you how to build and modify `.dtb` files, how FreeBSD's overlay system works, and how to add your own node to an existing board description so that your driver has something to attach to. ## 5. Creating and Modifying Device Tree Blobs You now have a driver that waits patiently for a Device Tree node with `compatible = "freebsd,fdthello"`. Nothing in the running system provides such a node, so nothing probes. In this section we learn how to change that. We will look at the source-to-binary pipeline, at the overlay mechanism that lets us add nodes without rebuilding the whole `.dtb`, and at the loader tunables that decide which blob the kernel actually sees at boot time. Creating Device Tree blobs is not a rite of passage for experienced kernel hackers. It is an ordinary editing task. The file is text, the compiler is standard, and the output is a small binary that lives in `/boot`. What makes it feel unfamiliar is only that very few hobbyist projects encounter it. On embedded FreeBSD it is routine. ### The Source-to-Binary Pipeline Every `.dtb` that boots a FreeBSD system started life as one or more source files. The pipeline is simple: ```text .dtsi .dtsi .dtsi \ | / \ | / .dts (top-level source) | | cpp (C preprocessor) v .dts (preprocessed) | | dtc (device tree compiler) v .dtb (binary blob) ``` The C preprocessor runs first. It expands `#include` directives, macro definitions from header files like `dt-bindings/gpio/gpio.h`, and arithmetic in property expressions. The `dtc` compiler then turns the preprocessed source into the compact flattened format the kernel can parse. Overlay files go through the same pipeline, except their source file carries the extension `.dtso` and their output carries `.dtbo`. The only real syntactic difference is the magic incantation at the top of overlay source files, which we look at shortly. FreeBSD's build system wraps this pipeline in two small shell scripts you can study at `/usr/src/sys/tools/fdt/make_dtb.sh` and `/usr/src/sys/tools/fdt/make_dtbo.sh`. They chain `cpp` and `dtc` together, add the right include paths for the kernel's own `dt-bindings` headers, and write the resulting blobs into the build tree. When you `make buildkernel` for an embedded platform, these scripts are what produce the `.dtb` files that end up in `/boot/dtb/` on the installed system. ### Installing the Tools On FreeBSD, `dtc` is available as a port: ```console # pkg install dtc ``` The package installs the `dtc` binary together with its companion `fdtdump`, which prints the decoded structure of an existing blob. If you plan to do any overlay work, install both. The FreeBSD base tree also ships a copy of `dtc` under `/usr/src/sys/contrib/device-tree/`, but the port version is easier to reach from userspace. To check the version: ```console $ dtc --version Version: DTC 1.7.0 ``` Any version from 1.6 onwards supports overlays. Earlier versions lack the `/plugin/;` directive, so if you inherit an old build environment, upgrade before going further. ### Writing a Standalone .dts File We will start with a complete, standalone Device Tree source file so the syntax has time to settle before we add overlay complications. Create a file called `tiny.dts` somewhere outside the kernel tree: ```dts /dts-v1/; / { compatible = "example,tiny-board"; model = "Tiny Example Board"; #address-cells = <1>; #size-cells = <1>; chosen { bootargs = "-v"; }; cpus { #address-cells = <1>; #size-cells = <0>; cpu0: cpu@0 { device_type = "cpu"; reg = <0>; compatible = "arm,cortex-a53"; }; }; memory@0 { device_type = "memory"; reg = <0x00000000 0x10000000>; }; soc { compatible = "simple-bus"; #address-cells = <1>; #size-cells = <1>; ranges; hello0: hello@10000 { compatible = "freebsd,fdthello"; reg = <0x10000 0x100>; status = "okay"; }; }; }; ``` The first line, `/dts-v1/;`, tells `dtc` which version of the source format we are using. Version 1 is the only version in current use, but the directive is still required. After that, we have the root node, containing a handful of expected children. The `cpus` node describes the processor topology, the `memory@0` node declares a 256 MB region of DRAM at physical address zero, and the `soc` node groups on-chip peripherals under a `simple-bus`. Inside `soc`, our `hello@10000` node provides the Device Tree match for the `fdthello` driver we wrote in Section 4. A few things are worth noticing here even in this small file. First, `#address-cells` and `#size-cells` reappear inside the `soc` node. The values a parent sets apply only to that parent's direct children, so every level of the tree that cares about addresses has to declare them. Here the `soc` is using one cell for addresses and one for sizes, which is why `reg = <0x10000 0x100>;` inside `hello@10000` lists exactly two `u32` values. Second, the `ranges;` property on the `soc` node is empty. An empty `ranges` means "addresses inside this bus match addresses outside it one to one." If the `soc` were, say, mapped at a different base address than its children claim, you would use a longer `ranges` list to express the translation. Third, `status = "okay"` is explicit here. Without it, every tree implicitly defaults to okay, but many board files set `status = "disabled"` on optional peripherals and expect overlays or board-specific files to flip them on. Get into the habit of checking this property whenever a driver mysteriously fails to probe. ### Compiling a .dts File Compile the tiny example: ```console $ dtc -I dts -O dtb -o tiny.dtb tiny.dts ``` The `-I dts` flag tells `dtc` the input is textual source, and `-O dtb` requests a binary blob output. A successful compile prints nothing. A syntax error tells you the file and line. You can verify the result with `fdtdump`: ```console $ fdtdump tiny.dtb | head -30 **** fdtdump is a low-level debugging tool, not meant for general use. **** Use the fdtput/fdtget/dtc tools to manipulate .dtb files. /dts-v1/; // magic: 0xd00dfeed // totalsize: 0x214 (532) // off_dt_struct: 0x38 // off_dt_strings: 0x184 // off_mem_rsvmap: 0x28 // version: 17 // last_comp_version: 16 // boot_cpuid_phys: 0x0 // boot_cpuid_phys: 0x0 // size_dt_strings: 0x90 // size_dt_strings: 0x90 // size_dt_structs: 0x14c // size_dt_structs: 0x14c / { compatible = "example,tiny-board"; model = "Tiny Example Board"; ... ``` That round-trip confirms the blob is valid and parseable. You could now drop it into a QEMU run with `-dtb tiny.dtb` and the kernel would attempt to boot against it. In practice you rarely hand-write a complete `.dts` for a real board. You start with the vendor's own source file (for instance `/usr/src/sys/contrib/device-tree/src/arm64/broadcom/bcm2711-rpi-4-b.dts` for the Raspberry Pi 4) and modify a subset of nodes with an overlay. ### The Role of .dtsi Include Files The `.dtsi` extension is used for Device Tree *includes*. These files contain tree fragments that are meant to be pulled into another `.dts` or `.dtsi`. The compiler treats them identically to `.dts` files, but the filename suffix tells other humans (and the build system) that the file is not standalone. A common pattern in modern SoC descriptions is: ```text arm/bcm283x.dtsi <- SoC definition arm/bcm2710.dtsi <- Family refinement (Pi 3 lineage) arm/bcm2710-rpi-3-b.dts <- Specific board top-level file, includes both ``` Each `.dtsi` adds and refines nodes. Labels declared in a lower file can be referenced from a higher file with the `&label` syntax to override properties without rewriting the node. This is the mechanism that makes it possible to support dozens of related boards from a handful of shared SoC descriptions. ### Understanding Overlays A full `.dts` for a real SBC like the Raspberry Pi 4 is dozens of kilobytes long. If you only want to enable SPI, or add a single GPIO-controlled peripheral, rebuilding the whole blob is wasteful and error-prone. The overlay mechanism exists exactly for this situation. An overlay is a small, special `.dtb` that targets an existing tree. At load time, the FreeBSD loader merges the overlay into the base tree in memory, producing a combined view that the kernel sees as a single Device Tree. The base `.dtb` on disk is never modified. That means the same overlay can enable a feature across several systems with one copy on each. The syntax of an overlay source file uses two magic directives at the top: ```dts /dts-v1/; /plugin/; ``` After those, the source refers to nodes in the base tree by label. The compiler records the references symbolically, and the loader resolves them at merge time against whatever labels the base tree actually exports. That is why the overlay can be written and compiled independently of the exact base tree it will later be merged with. Here is a minimal overlay that attaches an `fdthello` node to an existing `soc` bus: ```dts /dts-v1/; /plugin/; / { compatible = "brcm,bcm2711"; fragment@0 { target = <&soc>; __overlay__ { hello0: hello@20000 { compatible = "freebsd,fdthello"; reg = <0x20000 0x100>; status = "okay"; }; }; }; }; ``` The outer `compatible` says this overlay is intended for a BCM2711 tree. The loader uses that string to refuse overlays that do not match the current board. Inside we see a single `fragment@0` node. Each fragment targets one existing node in the base tree through the `target` property. The content under `__overlay__` is the set of properties and children that get merged into that target. In this example, we are adding a `hello@20000` child under whatever node `&soc` resolves to at merge time. The base tree on a Raspberry Pi 4 declares the `soc` label on the top-level SoC bus node, so after the merge the base `soc` will gain a new `hello@20000` child, and our driver's probe will fire. You can also use overlays to *modify* existing nodes. If you set a property with the same name as an existing one, the overlay value replaces the original. If you add a new property, it simply appears. If you add a new child, it is grafted on. The mechanism is additive except for property value replacement. ### Compiling and Deploying Overlays Build the overlay with: ```console $ dtc -I dts -O dtb -@ -o fdthello.dtbo fdthello-overlay.dts ``` The `-@` flag tells the compiler to emit the symbolic label information needed at merge time. Without it, overlays that reference labels fail silently or produce unhelpful errors. On a running FreeBSD system, overlays live under `/boot/dtb/overlays/`. The filename needs to end in `.dtbo` by convention. The loader looks in `/boot/dtb/overlays` by default; the path can be overridden through loader tunables if you want to stage overlays elsewhere. To tell the loader which overlays to apply, add a line to `/boot/loader.conf`: ```ini fdt_overlays="fdthello,sunxi-i2c1,spigen-rpi4" ``` The value is a comma-separated list of overlay basenames without the `.dtbo` extension. Order matters only when overlays interact with each other. On boot, the loader reads the list, loads each overlay, merges them into the base tree in sequence, and hands the combined blob to the kernel. A good sanity check is to watch the loader output on a serial console or HDMI screen. When `fdt_overlays` is set, the loader prints a line like: ```text Loading DTB overlay 'fdthello' (0x1200 bytes) ``` If the file is missing or the target does not match, the loader prints a warning and continues. Your driver then fails to probe because the overlay never applied. Checking the loader's console output is the fastest way to catch this kind of failure. ### A Walkthrough: Adding a Node to a Raspberry Pi 4 Tree Let us put the machinery together in a realistic scenario. Imagine you are bringing up a custom daughterboard for the Raspberry Pi 4. It contains a single GPIO-controlled indicator LED on GPIO18 of the Pi's header. You want FreeBSD to drive the LED through your own `edled` driver (which we build in Section 7). You need a Device Tree node. First, you look up what the Pi 4's base `.dtb` already declares. On a running Pi with FreeBSD installed, `ofwdump -ap | less` or `fdtdump /boot/dtb/broadcom/bcm2711-rpi-4-b.dtb | less` gives you the full tree. Your main interest is the `soc` and `gpio` nodes, where you see a label `gpio = <&gpio>;` exported from the GPIO controller. Next, you write the overlay source: ```dts /dts-v1/; /plugin/; / { compatible = "brcm,bcm2711"; fragment@0 { target-path = "/soc"; __overlay__ { edled0: edled@0 { compatible = "example,edled"; status = "okay"; leds-gpios = <&gpio 18 0>; label = "daughter-indicator"; }; }; }; }; ``` We use `target-path` instead of `target` here because the target is an existing path rather than a label. Both forms are valid; `target` takes a phandle reference, `target-path` takes a string. The `leds-gpios` property is the conventional way to describe a GPIO reference in Device Tree. It is a phandle to the GPIO controller, followed by the GPIO number on that controller, followed by a flag word. Value `0` for the flag means active-high; `1` means active-low. Pinmux usually needs no explicit mention on the Pi because the Broadcom GPIO controller handles both direction and function through the same register set. Compile and install the overlay: ```console $ dtc -I dts -O dtb -@ -o edled.dtbo edled-overlay.dts $ sudo cp edled.dtbo /boot/dtb/overlays/ ``` Add the overlay to the loader configuration: ```console # echo 'fdt_overlays="edled"' >> /boot/loader.conf ``` Reboot. On the way up, the loader prints its overlay-load line, the base DT gains the new `edled@0` node under `/soc`, the `edled` driver's probe fires, and the daughterboard LED comes up under software control. ### Inspecting the Result Once the kernel is running, three tools verify that everything landed where it should: ```console # ofwdump -p /soc/edled@0 ``` prints the properties of the newly added node. ```console # sysctl dev.edled.0.%parent ``` confirms the driver attached and shows its parent bus. ```console # devinfo -r | less ``` displays the full device tree as FreeBSD sees it, with your driver in place. If any of these disagree with the overlay content, Section 6 helps you diagnose the cause. ### Troubleshooting Build Failures Most DT build errors fall into a small number of categories. **Unresolved references.** If the overlay refers to a label like `&gpio` that is not exported by the base tree, the loader prints `no symbol for