Try Embedded

The device tree

Nodes, compatible strings, overlays and how drivers find hardware.

Describing hardware that cannot describe itself

A PC discovers most of its hardware: PCI and USB devices announce themselves. On an embedded SoC, peripherals sit at fixed addresses on internal buses and external chips hang off I2C or SPI with no way to enumerate them. Hard-coding each board's hardware into the kernel (as Arm Linux once did) does not scale. The device tree is a data structure, passed to the kernel by the bootloader, that describes the hardware: which devices exist, at what addresses, using which interrupts, clocks, pins and GPIOs.

The same kernel binary can then boot many boards, each with its own device tree.

Source, blob and overlays

FileWhat
.dtsDevice tree source for a board
.dtsiInclude file: shared descriptions, usually the SoC (imx8mm.dtsi)
.dtbCompiled binary blob, passed to the kernel
.dtboOverlay: a fragment applied on top of a base tree

The compiler is dtc; kernel builds run it (make dtbs).

Syntax

/dts-v1/;
#include "soc.dtsi"
#include <dt-bindings/gpio/gpio.h>
#include <dt-bindings/interrupt-controller/irq.h>

/ {
    model = "Acme Sensor Gateway rev B";
    compatible = "acme,sensor-gw-b", "vendor,soc-family";

    chosen {
        stdout-path = &uart1;
    };

    leds {
        compatible = "gpio-leds";
        status_led: led-0 {
            label = "status";
            gpios = <&gpio1 5 GPIO_ACTIVE_HIGH>;
            linux,default-trigger = "heartbeat";
        };
    };
};

&i2c2 {                                   /* modify a node defined in soc.dtsi */
    status = "okay";
    clock-frequency = <400000>;

    temp-sensor@48 {
        compatible = "ti,tmp117";
        reg = <0x48>;                     /* I2C address */
        interrupt-parent = <&gpio3>;
        interrupts = <12 IRQ_TYPE_EDGE_FALLING>;
    };
};

Elements:

  • Nodes (name@unit-address { ... }) represent devices or buses; the unit address matches the first reg value.
  • Properties (name = value;): strings, cell lists <...> of 32-bit values, byte arrays [...], or empty (boolean, presence is true).
  • Labels and phandles: status_led: labels a node; &gpio1 refers to another node by label; &i2c2 { ... } extends a node defined elsewhere.
  • #address-cells and #size-cells in a parent say how many cells its children's reg uses.

The important properties

PropertyMeaning
compatibleWhich driver handles this node; most specific first: "ti,tmp117"
regAddress and size on the parent bus (memory-mapped) or address (I2C, SPI chip select)
status"okay" to enable, "disabled" to ignore; SoC files usually disable everything and boards enable what they use
interrupts, interrupt-parentWhich interrupt line, in the parent controller's format
clocks, clock-namesClock inputs
gpios, *-gpiosGPIO references: controller, pin, flags
pinctrl-0, pinctrl-namesPin multiplexing configuration
*-supplyRegulators powering the device

How a driver finds its node

Each driver declares the compatible strings it supports:

static const struct of_device_id tmp117_of_match[] = {
    { .compatible = "ti,tmp117" },
    { }
};
MODULE_DEVICE_TABLE(of, tmp117_of_match);

When the kernel creates a device from a node whose compatible matches, it calls the driver's probe() function, which reads the node's properties (of_property_read_u32, devm_gpiod_get, platform_get_irq) to configure itself. The bindings documentation (Documentation/devicetree/bindings/, YAML schemas) defines which properties each compatible requires; make dtbs_check validates trees against them.

Overlays

An overlay modifies a base tree at boot, without rebuilding it: enabling an add-on board's devices, a display variant, or HAT/cape configurations. U-Boot or the kernel's configfs applies them.

/dts-v1/;
/plugin/;

&spi1 {
    status = "okay";
    display@0 {
        compatible = "sitronix,st7789v";
        reg = <0>;
        spi-max-frequency = <32000000>;
        dc-gpios = <&gpio2 7 GPIO_ACTIVE_HIGH>;
    };
};

Checking what the kernel actually received

On a running system the live tree is at /proc/device-tree (or /sys/firmware/devicetree/base):

ls /proc/device-tree/soc/
cat /proc/device-tree/model
dtc -I fs -O dts /proc/device-tree > live.dts      # decompile the running tree

Comparing the live tree with what you expected solves most "my driver does not probe" problems.

Device trees outside Linux

U-Boot uses device trees for its own drivers, and Zephyr RTOS uses device tree source at build time (generated into C macros) to describe microcontroller boards, so the same skills apply to MCU work there.

The program below shows how the <controller pin flags> triplet in a gpios property is just a list of 32-bit cells that a driver decodes:

#include <stdio.h>
#include <stdint.h>

#define GPIO_ACTIVE_HIGH 0
#define GPIO_ACTIVE_LOW  1

int main(void) {
  /* gpios = <&gpio1 5 GPIO_ACTIVE_LOW>; after compilation the phandle is a number, say 0x1c */
  uint32_t cells[3] = { 0x1c, 5, GPIO_ACTIVE_LOW };
  printf("controller phandle 0x%x, pin %u, %s\n", cells[0], cells[1],
         cells[2] & GPIO_ACTIVE_LOW ? "active low" : "active high");
  return 0;
}

Pitfall: Editing the board .dts but booting an old .dtb (copied to the boot partition earlier, or embedded in a FIT image) is the most common reason a device-tree change "has no effect". Check /proc/device-tree on the running board.

Interview question: What is a device tree and why does embedded Linux use one?

Answer: A hardware description, written as a tree of nodes and properties (.dts, compiled to .dtb), that tells the kernel which non-discoverable devices exist, their addresses, interrupts, clocks, GPIOs, pin multiplexing and power supplies. The bootloader passes it to the kernel, which creates devices from the nodes and binds drivers by matching compatible strings. It lets one kernel binary support many boards, keeps board details out of driver code, and overlays allow variants and add-on boards without rebuilding.

Interview question: How does a Linux driver get its configuration from the device tree?

Answer: The driver lists compatible strings in an of_device_id table. When the kernel creates a device from a node whose compatible matches, it calls the driver's probe function with that device. In probe, the driver reads resources and properties: memory regions via platform_get_resource and devm_ioremap_resource, interrupts with platform_get_irq, GPIOs with devm_gpiod_get, clocks with devm_clk_get, regulators with devm_regulator_get, and custom properties with of_property_read_u32 or device_property_read_*. The binding documentation defines which properties are required.

Build it: find the Zigbee radio in the device tree

This is step 3 of the module project, the smart-home gateway. The gateway's second board revision has a newer Zigbee radio, and the same firmware image has to run on both, so the radio's driver finds its hardware from the device tree, as the kernel does: by its compatible strings and its reg property. The gateway's small first-stage loader has to do the same before Linux is running, so you write it by hand.

Lab: Match compatible strings, and decode reg

  • dt_match(compat, len, table, n) picks the driver entry for a node. compat is the raw property: len bytes holding one or more zero-terminated strings, the most specific first. Return the index in table of an entry equal to the earliest string that has any match (so "acme,zb-radio-v2" wins over the generic "acme,zb-radio" when the driver knows both, and the generic one is used when it does not know the specific one), or -1 if none match. Strings must match exactly, not as prefixes.
  • dt_reg(prop, len, addr_cells, size_cells, out, max) decodes a reg property: a list of (address, size) pairs, each number made of addr_cells or size_cells 32-bit big-endian cells (1 or 2 for addresses; 0, 1 or 2 for sizes, 0 meaning there is no size, as for a device on an I2C bus). Return the number of pairs, or -1 if len is not a whole number of pairs or there are more than max.

Going deeper

Interview question: How would you support three board revisions of a home gateway with one Linux image?

Answer: Describe each revision's hardware in its own device tree (or overlays on a common one), identify the board at boot from an ID resistor or EEPROM, and have the bootloader pass the matching tree to the kernel. Drivers bind from the tree, so the same kernel and root file system run on all three.

Interview question: How does a driver find a GPIO it needs from the device tree?

Answer: The node includes a property such as reset-gpios = <&gpio2 7 GPIO_ACTIVE_LOW>;. In probe, the driver calls devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH), which looks up the reset-gpios property, resolves the controller phandle, pin number and flags, and returns a descriptor with polarity already handled, so the driver writes logical values without knowing the board wiring.

Interview question: What does #address-cells and #size-cells control?

Answer: They tell how many 32-bit cells a child node's reg property uses for the address and for the size on that parent's bus. A 32-bit memory bus typically has 1 and 1; a 64-bit one 2 and 2; an I2C bus has #address-cells = 1 and #size-cells = 0 because devices have an address but no size. Getting them wrong makes reg values parse incorrectly.

Explain it: In your own words, explain how the device tree connects a board's hardware to its Linux drivers.

Answer: The device tree is a description of the hardware written as nodes and properties: which devices exist, at what addresses and on which buses, and which interrupts, clocks, pins and supplies they use. The bootloader passes the compiled tree to the kernel, which creates a device for each enabled node. Each driver lists the compatible strings it supports, and when a node's compatible string matches, the kernel calls that driver's probe function, which reads the node's properties to configure itself. The same kernel can therefore run on many boards, each with its own tree.