A sensor works for 30 seconds after boot, then dies. No driver fix helps; one line in the device tree does. Match a node to a driver, feed it resources, and watch Linux decide.
Pick the node’s compatible strings and press the switches. First make the driver fail to match. Then match it. Then take away its clock. Then we build, piece by piece, the whole path from a line of text to a running driver.
You need a rough idea of what a driver is (code that talks to one chip) and a little C. We build the rest from zero. Part of the Physical AI Systems Linux track; it follows The Boot Chain.
Built from primary sources we opened: the Linux 6.12 kernel source and documentation, the Devicetree specification v0.4, and the pages listed in the Field Guide. The instrument is a model of the kernel’s rules, not the kernel itself.
A model of three real kernel rules: the match against the driver’s table (drivers/of/base.c), the retry on -EPROBE_DEFER (drivers/base/dd.c) and the status check, read in Linux 6.12. The driver, the strings and the probe order (pinctrl, clock, regulator) are illustrative.
Chapter 0
Follow one dead sensor to a rule in the kernel, and see why the cure is a line of text and not a line of code
You wire a small pressure sensor to a Linux board. You boot, you read a value, and it works. You show a friend. You walk away to get coffee. When you come back, every read fails. The board did not crash. The sensor just stopped answering.
You reboot and read again at once. It works. You wait half a minute. It dies again. The time is the same on every boot, so this is not a loose wire. Something in the system switches the sensor off on a timer.
A sensor chip needs power. On a board, power comes from a regulator: a circuit that turns the supply into one steady voltage, such as 3.3 volts. Many regulators have an enable pin that a processor can switch. The wire that carries the voltage is the rail.
Linux has a regulator framework that owns these switches. Think of a shared room with one light. Each person who needs the room tells the framework. The framework keeps a count of people inside. When the last person leaves, it turns the light off. The count is called the use count, and a person who tells the framework is a consumer.
Now the trap. The bootloader (the first program, covered in The Boot Chain) often switches the rail on before Linux starts. So at the moment Linux begins, the light is on and the count is zero. Nobody has told the framework that the sensor needs the room.
The framework cannot leave every unclaimed light on forever. That would waste power on every board. So it runs a cleanup. In the Linux 6.12 source, the function regulator_init_complete() is registered with late_initcall_sync. That means it runs after the kernel has finished its normal start-up calls. It does not clean up at once. It schedules the cleanup 30 seconds later, with msecs_to_jiffies(30000).
The comment in the source gives the reason. Systems load many drivers from user space, so consumers might not be ready yet. The authors wrote that they "wait a bit and hope we waited long enough." The 30 seconds is a guess, written down as a number.
When the timer fires, the cleanup function checks each regulator. It skips one if it is marked always_on. It skips one if its use count is above zero. Otherwise, if the system has full constraints, it prints disabling and switches the rail off. A system that boots from a device tree counts as having full constraints: the same function sets that flag when of_have_populated_dt() is true.
rail off at = time of late_initcall_sync + 30 s
Work one case. Say the kernel reaches late_initcall_sync at 6.4 seconds after power on. The cleanup runs at 6.4 + 30 = 36.4 seconds. If your sensor samples every 5 seconds, the first failed read is the sample at 40 seconds. Your coffee break was long enough. Drag the boot time below and see the failure move. Then claim the rail, and watch it stay.
The warm bar is the kernel starting up. The yellow bar is the 30 second grace period. The green line is the rail. Dots are sensor reads every 5 seconds. Drag the slider, then press the two switches.
The 30 000 ms delay, the late_initcall_sync registration, the always_on skip and the use count test are read from drivers/regulator/core.c in Linux 6.12. The boot time slider and the 5 second sample period are illustrative; real boot times vary by board and by kernel configuration.
The symptom is a sensor that works for about half a minute and then fails, the same way on each boot. The measurement has three parts. First, search the kernel log with dmesg | grep disabling. A line such as vdd_sens: disabling names the rail. Second, read the files under /sys/class/regulator/. Each regulator has a state file and a num_users file, both listed in the kernel ABI documents. A rail with num_users at 0 is a rail the janitor will take. Third, put a multimeter on the sensor’s supply pin and watch it fall at the time you predicted.
The fix is a fact about the board. The sensor takes its power from vdd_sens. Only the board designer knows that. So we write it down in the device tree, as a property on the sensor node: vdd-supply = <&vdd_sens>;. The driver asks for its supply by that name, the framework adds one to the use count, and the janitor leaves the rail alone. The quick patch is regulator-always-on; on the regulator node. That works, but it also keeps the rail on when no driver needs it. For debugging only, the boot option regulator_ignore_unused stops the cleanup.
Notice what no driver fix can do. The driver code is the same on every board. It cannot know which rail feeds which chip on this board. That knowledge must live outside the driver, in a data file the kernel reads at boot. That file is the device tree, and the rest of this lesson builds it from zero: where it sits, how it picks a driver, how drivers wait for each other, and how you debug it.
dmesg -w, and note the second when a disabling line appears. Compare it with your prediction. Then add the supply property and measure again. A BME280 binding in the Linux 6.12 tree lists vddd-supply and vdda-supply as its power properties.Chapter 1
Separate what the kernel can discover from what someone must tell it, and see which file holds the second kind
Your team makes two revisions of one board. Revision A and revision B carry the same sensor and the same Linux driver. On revision B, the designer moved the sensor’s reset wire from one processor pin to another, to make routing easier. You flash the same software. The sensor on revision B never wakes up.
Nothing is wrong with the sensor, the driver or the wire. The software still pulses the old pin. The pin number was a fact about the board, and it lived in the wrong place.
Some buses are friendly. When you plug a USB stick into a laptop, the stick answers a question: “who are you?” It sends back an identity number. Linux reads the number and loads the right driver. PCI cards work the same way. This is called enumeration: the bus can list what is on it.
Many chips on an embedded board are not friendly. A sensor on an I2C bus sits silent until someone sends its address. A memory-mapped block inside the processor, such as a UART, is just a range of addresses. Neither one announces itself. The kernel documentation says it plainly: a platform device is used for "memory or I/O mapped devices which cannot be detected by hardware."
So somebody must write down the list. Which chip is where? Which address? Which interrupt line? Which pin resets it? Which rail powers it? In the past, that list was C code inside the kernel, written once for each board. The modern answer is a data file that describes the board, kept apart from the drivers.
The device tree is that data file. The kernel documentation calls it "simply a data structure that describes the hardware." It is a tree because hardware nests: a board holds a processor, the processor holds an I2C controller, the controller holds a sensor. Each box in the tree is a node. Each fact inside a node is a property, a name with a value.
You write it as text, in a .dts file (device tree source). A compiler called dtc turns it into a compact binary, a .dtb (device tree blob). The bootloader loads the blob into memory and hands the kernel its address, as the boot-chain lesson showed. The kernel unpacks the blob and builds a device for every node that has a compatible property. A special node, /chosen, carries data from the bootloader, such as the kernel command line.
The Devicetree specification is the written standard for the file format. The version we read is v0.4, published on 28 June 2023. The specification says what a property named reg or status must mean, so that a bootloader and a kernel from different teams agree.
// i2c1 is the controller; the sensor is its child. Values are illustrative. &i2c1 { status = "okay"; sensor@76 { compatible = "bosch,bme280"; reg = <0x76>; // I2C address vddd-supply = <&vdd_sens>; // the rail from Chapter 0 vdda-supply = <&vdd_sens>; reset-gpios = <&gpio1 14 GPIO_ACTIVE_LOW>; }; };
Read it line by line. sensor@76 is the node name, then an @, then its address on the bus. compatible names the chip family so the kernel can find a driver. reg gives the I2C address, 0x76. The two -supply lines name the rail. The last line names the reset pin: pin 14 of the controller labelled gpio1, active when low. The names vddd-supply, vdda-supply and reset-gpios come from the BME280 binding in the Linux 6.12 tree.
A BSP (board support package) is the full recipe that makes Linux run on one particular board. It has five parts. First, the bootloader and its settings. Second, the kernel configuration, which lists the drivers to build. Third, the device tree. Fourth, any drivers the board needs that the main kernel lacks. Fifth, the root filesystem, the programs and files that Linux starts with.
Look at the five parts and ask which ones are about this board and which are about the world. Drivers are about the world: one BME280 driver serves a million boards. The device tree is about this board. That split is the point. If you keep board facts in the tree and chip knowledge in the driver, then a new board means a new tree, and no new driver.
Choose where the reset pin number lives. Then press the switch to build revision B, where the wire moves from GPIO 12 to GPIO 14. Warm boxes are the parts you must edit and rebuild.
Illustrative: GPIO 12 and GPIO 14 and the five layer names are a toy, not a real board. The split between what the hardware can enumerate and what the device tree must declare is from the Linux kernel devicetree usage-model document.
The device above shows the cost. With the pin in the driver, revision B needs an edited driver, a rebuilt kernel and a retest of every board that shares that driver. With the pin in the tree, one number changes in one text file, and only the blob is rebuilt. The driver binary does not change at all.
The symptom is a driver that works on one board and fails on the next, though the chip is the same. The measurement compares the live tree with the schematic. Linux exposes the running tree as files under /proc/device-tree, and the tool dtc -I fs -O dts /proc/device-tree turns it back into readable source. Check each number against the schematic. The fix is to move the fact out of the driver. Read the pin through a property, with the kernel’s GPIO functions, and put the number in the tree.
dtc -I fs -O dts /proc/device-tree > live.dts. Find the node of one device you know. Compare its reg value with the board’s documentation. Then find the matching source file in the kernel tree and see that the two agree.Chapter 2
Trace how one string in the tree picks one driver, and learn why a mismatch is silent
A new chip revision arrives. Its vendor calls it vendor,sensor-v2. You add a node to the tree with that string, rebuild the blob, and boot. You expect a line in the kernel log. You get nothing. No error, no warning. The node is there, and no driver is attached.
The silence is the first thing to understand. A mismatch is not a failure in the kernel’s eyes. It only means that no driver has claimed this device yet.
The Linux device model has three kinds of object. A device is one piece of hardware as the kernel sees it. A driver is code that can run a kind of device. A bus is the place where the two meet. Picture a dating service. Devices register on one side. Drivers register on the other. The bus is the matchmaker. It owns a rule for the question “do these two fit?”
The matchmaker asks that question every time something new registers. A device appears: the bus asks each known driver. A driver loads: the bus asks each device that has no driver yet. When a pair fits, the kernel calls the driver’s probe function with the device. Probe is where the driver checks the chip, sets it up and takes ownership. The kernel documentation describes it as the callback that "holds the driver-specific logic to bind the driver to a given device." If probe returns zero, the driver is bound.
For a platform device, the bus’s rule is the function platform_match() in Linux 6.12. It tries four tests in order and stops at the first that says yes. One: if a driver_override is set, use only that driver. Two: the device tree match. Three: the ACPI match. Four: the driver’s ID table, and last of all a plain name match. I2C devices, such as our sensor, use the I2C bus’s own matchmaker, but it asks the same device tree question.
The device tree question works on two lists of strings. The node has a compatible property: a list, ordered from the most specific name to the most general. The specification says so directly: "from most specific to most general." The driver has an of_match_table: an array of entries, each with one compatible string and some private data, ended by an empty entry.
Here is the real table in the Linux 6.12 BME280 driver, shortened to two entries.
static const struct of_device_id bmp280_of_i2c_match[] = { { .compatible = "bosch,bmp280", .data = &bmp280_chip_info }, { .compatible = "bosch,bme280", .data = &bme280_chip_info }, { }, /* empty entry ends the table */ }; MODULE_DEVICE_TABLE(of, bmp280_of_i2c_match);
The .data pointer matters. When the kernel finds the entry that matched, the driver can read its data and learn which chip variant it has. One driver then serves six compatible strings with five small tables of facts, because two old names share one table.
Why is the node’s list ordered? Because the kernel scores every driver entry by where it appears in the list. In drivers/of/base.c, the function walks the node’s strings with a counter index. For the first string that equals the entry, it sets the score to INT_MAX/2 - (index << 2). A match at index 0 scores higher than a match at index 1. The kernel then returns the entry with the best score.
score = INT_MAX / 2 − 4 × index = 1 073 741 823 − 4 × index
Work an example. The node lists "vendor,sensor-v2" at index 0 and "vendor,sensor" at index 1. A new driver has entries for both. Entry vendor,sensor-v2 matches at index 0 and scores 1 073 741 823. Entry vendor,sensor matches at index 1 and scores 1 073 741 823 − 4 = 1 073 741 819. The first wins, so the driver applies its v2 settings. An old driver with only the generic entry still matches, at index 1, and runs its generic code. That is the point of the fallback compatible: a new node works with an old kernel.
Test it yourself. Pick a node and a driver, and read the scores.
Left: the node’s compatible list with index numbers. Right: the driver’s table. A line joins a string that matches. The best line turns green.
The score formula and the case-insensitive string compare (strcasecmp) are read from drivers/of/base.c and include/linux/of.h in Linux 6.12. The vendor,sensor strings are illustrative.
Switch on the capital letter and watch what happens. The match still succeeds. In Linux 6.12 the compare for compatible strings is strcasecmp, which ignores case. So a wrong-case string is not the usual cause of a silent failure. The checker in Chapter 6 still rejects it, because the binding lists only the lowercase form. Do not rely on the kernel to forgive you.
A node can have a status property. If it is missing, or equals "okay", the node is available. The specification also defines "disabled", "reserved" and "fail". The kernel checks availability before it makes a device, in of_device_is_available(). A node marked "disabled" never becomes a device, so no driver is even asked. A common pattern is that the chip’s shared tree leaves optional blocks disabled, and each board file switches on the ones it wires up.
The symptom is a node with no driver and no log line. The measurement starts in sysfs. Look at /sys/bus/i2c/devices/ for a directory named after the bus and the address, such as 1-0076. If it exists but has no driver symlink inside, the device was created and nothing matched. Read its modalias file: it carries the compatible string the kernel used. Then check the driver’s table in the source. If the device directory does not exist at all, suspect status or a node in the wrong place. The fix is to add the string the driver knows, usually as a fallback after the new name.
ls -l /sys/bus/i2c/devices/2-0076/. Note that the directory exists with no driver link and that dmesg says nothing. Fix the string and see the link appear."vendor,sensor-v2" then "vendor,sensor". The driver’s table has only "vendor,sensor". What happens?Chapter 3
Watch drivers that cannot start yet wait their turn, and learn to name the one provider that never arrived
The sensor from Chapter 2 matched its driver. The kernel calls probe. The driver asks for its clock, and the clock does not exist yet. The clock chip’s own driver has not run. What should the sensor driver do?
It cannot fail for good: the clock will appear in a few milliseconds. It cannot wait inside probe: the clock driver might be waiting for the same CPU. So it does the polite thing. It says “not yet” and leaves.
The way to say it is to return a special error from probe: -EPROBE_DEFER, which is error number 517. The kernel documentation says the driver core then "will put the device onto the deferred probe list and will try to call it again later." The source comment in drivers/base/dd.c gives a real example: an SD card controller first needs a GPIO line from an I2C GPIO chip.
Think of cooking a meal with one pair of hands. You cannot bake before the oven is hot. So you put the dough to one side, do the next task, and each time something finishes you look at the side pile again. The kernel does the same. It keeps two lists, pending and active. A deferred device goes on the pending list. Whenever any driver probes successfully, the kernel moves all pending devices to the active list, and a worker retries them. When a retry round binds nothing new, the process stops.
What are drivers usually waiting for? Things that other drivers supply. A provider is a driver that offers a resource. A consumer is a driver that needs it. The common providers are clocks, regulators, GPIO lines, pin controllers and reset lines. Chapter 4 explains each one. A consumer names its provider in the tree with a phandle, a reference to another node, written <&vdd_sens>.
static int sensor_probe(struct i2c_client *client) { struct clk *clk = devm_clk_get(&client->dev, NULL); if (IS_ERR(clk)) return dev_err_probe(&client->dev, PTR_ERR(clk), "cannot get clock\n"); /* a missing provider returns -EPROBE_DEFER here; probe stops and is retried */ ... }
Two details are worth knowing. First, dev_err_probe() helps. When the error is -EPROBE_DEFER, the helper keeps the reason, and the source says it can "be checked later by reading devices_deferred debugfs attribute." Second, in drivers/clk/clk.c the lookup of a clock whose provider is not registered starts from ERR_PTR(-EPROBE_DEFER). So a clock reference to a provider that has not registered yet means “wait”, not “fail”.
This is why Linux can boot with drivers in any order. Consumers wait, providers arrive, retries run, and the dependency graph sorts itself out. The newer fw_devlink feature helps too. The kernel reads the tree, infers which node depends on which, and creates links so that suppliers probe before consumers. The kernel parameter documentation describes it as ensuring "suppliers first, then consumers."
Try it. The device below has six drivers. Three wait for providers. Press Shuffle order to change the order in which they register, then Run and count the passes. Whatever the order, all six bind. Then switch off the clock provider.
Arrows run from a provider to the driver that needs it. Yellow: deferred. Green: bound. Red: waiting for a provider that has no driver. The number in a box counts its probe attempts.
The retry rule (a successful probe makes every pending device try again) follows the comment in drivers/base/dd.c in Linux 6.12. The six drivers, their dependencies and the shuffle are an illustrative model; a real kernel retries from a work queue, not in strict passes.
When the clock provider is missing, the clock consumer, i2c1, waits. The sensor waits for i2c1. The other three bind. Linux does not give up at once. It just keeps the two devices on the list.
Waiting forever is bad for a developer who sees nothing. So the kernel has a time limit. At the end of the late initcalls, deferred_probe_initcall() triggers one more round. In Linux 6.12 the default for the parameter deferred_probe_timeout is 10 seconds when the kernel supports modules, and 0 when it does not. When the timeout ends, the kernel prints deferred probe pending: followed by the stored reason, for each device still on the list. Drivers that opt in then stop treating the missing supplier as a reason to wait. Note the limits: the timeout is a debugging aid, and only dependencies that opted in are ignored.
The symptom is a device that never appears: no driver link, but this time the match was fine. The measurement is cat /sys/kernel/debug/devices_deferred. It lists each stuck device with the reason the driver gave. Add initcall_debug to the kernel command line to see probe calls and their return values. Read the reason, find the named provider in the tree, and check its node: is it present, is its status okay, does it have a driver? The fix is nearly always a missing or disabled provider node, a wrong phandle, or a provider driver not built into the kernel.
"disabled", boot, and run cat /sys/kernel/debug/devices_deferred as root. Find the consumer in the list and read the reason. Wait for the timeout and compare the deferred probe pending lines in dmesg with the file.devices_deferred lists it. What do you check first?Chapter 4
Learn the five things a chip block needs before it can work, and read the counts that show who holds them
The sensor driver is bound. Its probe ran. You ask for a reading and the I2C transfer times out. You put a scope on the two I2C wires. Both sit high. There are no clock pulses at all. The processor is not even trying to send.
The I2C block inside the chip is fine. It simply has no way to reach the board’s pins, because nobody told the chip to connect them. A chip block needs more than a driver to work. It needs a small set of resources. Each resource has a kernel framework with a consumer side and a provider side, exactly like the regulator in Chapter 0.
A pin on a processor can do several jobs. The same metal leg can be a GPIO, an I2C data wire, or a UART transmit wire. The pinctrl framework chooses the job. This is pin multiplexing, or pinmux. The kernel documentation says the subsystem deals with naming pins, multiplexing them and configuring them, such as bias and drive strength.
A clock is a repeating signal that makes a block tick. Most blocks in a modern chip have their clock switched off until needed, to save power. The clock framework keeps a tree of clocks, because one source feeds a divider that feeds a gate that feeds a block.
A regulator supplies voltage, as Chapter 0 showed. A reset line holds a block in its starting state until you release it; the reset framework has calls to assert and deassert a line. A power domain is a region of the chip with its own power switch; a node joins one with a power-domains property that points at the controller, and the kernel’s generic power domain code (genpd) switches the region on before the driver runs.
// the sensor's bus controller asks for all five, by name (illustrative values) &i2c1 { pinctrl-names = "default"; pinctrl-0 = <&i2c1_pins>; // which pins, which job clocks = <&clk_i2c1>; // its gate in the clock tree resets = <&rst_i2c1>; // its reset line power-domains = <&pd_periph>; // its power region };
The driver never names these pieces. It calls functions such as devm_clk_get() and devm_reset_control_get_exclusive(). The framework reads the property from the tree and finds the provider. Remember Chapter 3: if the provider has not registered yet, the call returns -EPROBE_DEFER. If the property is missing, the call returns an ordinary error.
Pin setup is special. The pin documentation says that a device may define a state named default, and "if default is defined in the device tree, it is selected before device probe." The driver core does it, through pinctrl_bind_pins(). The driver writes no pin code. If the tree lacks pinctrl-0, the pins stay in whatever state the bootloader left, and the block never reaches the wires. That is the scope picture above: high, silent wires.
A clock must be prepared (which may sleep, for example to wait for a PLL, a circuit that makes a fast clock) and then enabled (a quick gate). A consumer calls clk_prepare_enable() to do both. Each call adds to a counter named enable_count.
The counts climb the tree. In clk_core_enable() of Linux 6.12, when a clock’s count is zero, the kernel first enables the parent, and then the clock itself. So a parent’s count equals the number of its children that are on, plus its own direct consumers. When the last child switches off, the parent switches off too.
enable_count(clock) = direct consumers + children whose count is above 0
Work an example. A source feeds a PLL. The PLL feeds a bus clock and a UART clock. The bus clock feeds the I2C and SPI blocks. If the I2C block and the UART are on, the bus clock has count 1 (one child, I2C), the UART clock has 1 (its console), the PLL has 2 (bus and UART), and the source has 1 (the PLL). Turn on SPI too: the bus clock goes to 2, but the PLL stays at 2, since the bus was already counted once. Turn the I2C block off again: the bus keeps running for SPI. Try it.
Press a consumer to enable its clock. Each box shows the clock name and its enable count. A green box is running. Watch the counts change up the tree.
The rule that a clock enables its parent only when its own count goes from 0 to 1 is read from clk_core_enable() in drivers/clk/clk.c, Linux 6.12. The tree and its shape are illustrative; real trees are much larger. The real file /sys/kernel/debug/clk/clk_summary prints enable, prepare and protect counts, the rate, and each consumer’s device name.
On a real board you read this table as text. The file /sys/kernel/debug/clk/clk_summary prints one row per clock, indented by depth. The columns, taken from clk_summary_show_one(), are the name, enable count, prepare count, protect count, rate, accuracy, phase, duty cycle, an enabled flag, and then the devices that use the clock. It is the truth about what is running.
The symptom is a block that probes without an error but does nothing, or whose registers read back strange. What a read does when the block’s clock is off depends on the chip. Some chips return zeros. Some return stale data. Some stall the bus and raise a fault. Read the reference manual of your SoC for its case. The measurement has three tools. Read clk_summary and check that the block’s clock shows a count above zero. Read /sys/kernel/debug/pinctrl/<controller>/pinmux-pins: each pin line says which device or GPIO owns it, or UNCLAIMED. And put a scope on the wires. The fix is to add the missing clocks, pinctrl-0, resets or power-domains property.
cat /sys/kernel/debug/pinctrl/*/pinmux-pins as root and find the two I2C pins. Note the owner. Then remove the pinctrl-0 line from the bus node, reboot, and look again, with a scope on the SDA and SCL pins while you run i2cdetect.Chapter 5
Decode the numbers in a node by hand, and see how one wrong cell or one wrong trigger type loses data
The sensor is bound, powered and clocked. It has a data-ready pin. You expect one interrupt for every new sample. You send 100 samples and count the interrupts the kernel saw. You find 38. No error anywhere. Either the sensor or the tree is lying, and the tree is the cheaper place to look.
Some properties are easy: a string, a flag. A few are lists of bare numbers, and their meaning depends on a different node. Those are the ones that bite. This chapter takes three of them apart: reg, interrupts and dma-coherent, plus the phandle that links nodes together.
A cell is one 32-bit number in a property value, written between angle brackets. The property reg says where a device lives. The Devicetree specification defines its value as "an arbitrary number of pairs of address and length." But how many cells make one address, and how many make one length? The node does not say. Its parent says, with two properties: #address-cells and #size-cells.
That sounds odd, and it has a reason. On an I2C bus, a device has an address and no size, so the I2C controller sets #address-cells = <1> and #size-cells = <0>, and a child writes reg = <0x76>. The specification says that with a size-cells value of zero, "the length field ... shall be omitted." On a 64-bit memory bus, an address needs two cells, because 32 bits cannot hold it. If the parent sets neither property, the default is 2 address cells and 1 size cell.
Work a decode. Take the four cells 0x0 0x40011000 0x0 0x400. With 2 address cells and 2 size cells, the first two cells form the address 0x40011000, and the last two form the size 0x400, which is 1 024 bytes. That is one region. With 1 and 1, the same four numbers read as two regions, and the first has size 0x40011000, about a gigabyte. With 1 and 0, they read as four bare addresses. The data did not change. The parent’s counts changed the reading.
The four boxes are the raw cells of a reg property. Choose the parent’s #address-cells and #size-cells. Warm brackets are addresses. Blue brackets are sizes.
The cell values are illustrative. The rule that the parent’s #address-cells and #size-cells set the layout, and the defaults of 2 and 1, are from the Devicetree specification v0.4.
The interrupts property is also a list of cells, and again another node sets the format: the interrupt controller, the chip block that collects interrupt wires. The specification says the format "is defined by the binding of the interrupt domain root." For the Arm GIC, three cells give a type, a number and flags. For a typical GPIO interrupt controller, two cells give a pin and flags.
The flags choose the trigger type: what electrical event counts as an interrupt. The Linux header irq.h defines them. Rising edge is 1. Falling edge is 2. Both edges is 3. Level high is 4. Level low is 8. An edge trigger fires once when the wire changes. A level trigger fires for as long as the wire sits at the active level.
// a data-ready pin that goes high and stays high until the status register is read sensor@76 { compatible = "vendor,sensor"; reg = <0x76>; interrupt-parent = <&gpio1>; interrupts = <20 IRQ_TYPE_LEVEL_HIGH>; // pin 20; 4 = level, active high };
The datasheet says how the pin behaves, and the tree must say the same. The device below models two kinds of source. A held source holds its pin high until the driver reads the status register. A pulse source gives a short blip and lets go. Pick a trigger type and see what the kernel sees. Four events arrive; two are close together.
Top lane: the wire. Bottom lane: the processor in its handler (blue bars). Dots mark the four events: green if served, red if lost. Try each trigger on each source.
A toy model with stated rules: events at ticks 6, 26, 28 and 44; each handler runs 3 ticks; it clears the events that existed when it started, at its end; a pulse source needs one interrupt per pulse. The trigger type values 1, 2, 4 and 8 are from include/dt-bindings/interrupt-controller/irq.h, Linux 6.12. Real controllers differ in how they latch edges.
The pattern is worth remembering. A held source with an edge trigger can lose events: in the model above, edge rising serves 2 of 4. The wire stays high while a later event arrives, so no new edge appears. A pulse source with a level trigger can lose pulses that end while the processor is busy. A level trigger with the wrong polarity, or a handler that never clears the source, makes an interrupt storm: the handler runs again and again with nothing to do.
Two more properties bite less often but harder. dma-coherent is an empty flag. The specification says it marks a device that is capable of coherent DMA, on architectures that are not coherent by default. Coherent means the processor’s cache and the device see the same memory. Set the flag wrongly and the CPU reads stale data. The matching topic, caches and DMA, has its own lesson in this series, not yet built.
A phandle is a number that names a node. In source you write a label reference such as &gpio1, and the compiler gives that node a unique number. The specification says the phandle property holds "a numerical identifier for a node that is unique within the devicetree." The reference interrupt-parent = <&gpio1> is therefore just a number that the kernel looks up. Point it at the wrong label and your interrupt goes to the wrong chip, silently.
The symptom is a count of interrupts that does not match the event rate: too few, or far too many. The measurement is /proc/interrupts. For each line, it shows the per-CPU counts, the controller, the hardware number, a Level or Edge label for the type, and the driver name. Compare the label with the datasheet’s description of the pin. The fix is to change the flag in interrupts to match the pin, and to make the handler clear the source.
watch -n1 cat /proc/interrupts and trigger events at a known rate, such as 10 per second. Note whether the count rises by 10 each second. Change the flag in the tree between edge and level, reboot, and compare the counts.Chapter 6
Change the tree without rebuilding it, and let a checker catch the typo that would cost you a day
You sell a base board, and customers plug add-on boards into it. One add-on carries the sensor from this lesson. You do not want a different full tree for every combination of add-ons. You want a small patch that says: “also add this node.” You write the patch, copy it to the board, reboot, and nothing happens. The sensor is not in the tree.
Two tools solve this chapter’s problems. Overlays let you patch a tree. Schemas let a program check a tree against a written contract. Together they move many mistakes from the lab bench to your keyboard.
A device tree overlay is a small tree that names a place in the base tree and says what to add or change there. The kernel documentation states the purpose: an overlay modifies the kernel’s live tree. Newly enabled nodes should produce devices, and removed nodes should have their devices deregistered. You compile an overlay with the same compiler, into a .dtbo file.
/* sensor-addon.dts: adds the sensor under the base board's i2c1 */ /dts-v1/; /plugin/; &i2c1 { sensor@76 { compatible = "bosch,bme280"; reg = <0x76>; vddd-supply = <&vdd_sens>; }; };
The line &i2c1 names the target by its label, and the kernel documentation prefers this form "because the overlay can be applied to any base DT." There is a catch, stated in the same document: if the base tree was not compiled with the -@ option, the label "will not be available." The -@ flag keeps a table of labels inside the blob. Without it, the overlay cannot find its target.
Who applies the overlay? Something must merge it before the kernel starts, or the kernel must do it at run time through the function of_overlay_fdt_apply(). In U-Boot the usual way is to load the base blob and the overlay into memory and run the command fdt apply on the overlay’s address, as the U-Boot documentation shows. Many vendor images do it for you from a configuration file.
Now follow the pipeline. Four things must be true, in order: the overlay file exists on the boot medium, the bootloader step runs, the base tree has its labels, and the merge succeeds. Break each in turn.
Switch the three conditions on and off. The first stage that fails turns red and everything after it stays grey. Then choose a typo and read what the checker says.
A model of the pipeline described in the kernel overlay notes and the U-Boot overlay page. The checker output is paraphrased in plain words, not copied from a real run; real dtbs_check messages name the file, the node and the property.
Look at the typo case. The misspelled supply property means the sensor node names no supply at all. The kernel sees no consumer for the rail. That is exactly the dead sensor from Chapter 0. A schema check finds the mistake in seconds, before any boot.
A binding is the written contract for one kind of node. It lists the compatible strings, the required properties, the optional ones and their formats. In older kernels bindings were plain text files. In the Linux 6.12 documentation, "Devicetree bindings are written using json-schema vocabulary", in YAML files. A tool can read them. The tool installs with pip3 install dtschema.
Two commands do the work. make dt_binding_check checks that the binding files themselves are valid and that their examples pass. make dtbs_check checks the real trees against all the bindings. The documentation warns that dtbs_check skips any binding file that has errors, so run the first before the second.
# vendor,sensor.yaml: the contract for the node (shape follows the Linux bmp085.yaml binding)
%YAML 1.2
---
$id: http://devicetree.org/schemas/iio/vendor,sensor.yaml#
$schema: http://devicetree.org/meta-schemas/core.yaml#
title: Vendor sensor
properties:
compatible:
items: [ { const: vendor,sensor-v2 }, { const: vendor,sensor } ]
reg: { maxItems: 1 }
vdd-supply: true
required: [ compatible, reg ]
additionalProperties: false
This is also where the capital letter from Chapter 2 gets caught. The kernel compares compatible strings without regard to case. The schema lists only the lowercase string, so a capital letter fails the check.
If you write a new binding, the kernel project asks for the rules in its own file on submitting binding patches. The binding files are written in the schema format and "must pass validation by running" make dt_binding_check. The binding goes in a patch of its own, separate from driver code, with a subject that starts dt-bindings:. The preferred licence tag is (GPL-2.0-only OR BSD-2-Clause), and the series goes to the devicetree mailing list. Reviewers read bindings carefully, because a binding is a promise to every board that will use it.
One more piece of housekeeping in the same area. The old GPIO sysfs interface under /sys/class/gpio is listed in the Linux 6.12 documentation under “Obsolete GPIO APIs.” The libgpiod project says it has been deprecated since Linux 4.8, and its version 2 uses the character device interface, version 2 of which arrived in Linux 5.10. Use the character device from user space. The same pin you named in the tree with reset-gpios is then reachable by name, not by a magic number.
The symptom is a node you wrote that does not exist on the running board. The measurement is ls /proc/device-tree and the reconstructed source from Chapter 1; if the node is absent, step back through the pipeline. Is the file on the boot medium? Did the bootloader log an apply error? Does the base tree have its labels? The fix follows the first failing stage. Run make dtbs_check on every tree you ship.
ls /proc/device-tree/ocp and look for the node. Then break a property name in the source, run make dtbs_check on the kernel tree, and read the warning before you boot.&i2c1. The base tree was built without -@. What is the most likely result?Chapter 7
Read the kernel’s own picture of your hardware as files, and write the rule that gives a device a stable name
The driver is bound. The sensor reads fine. Now your application needs to open it. The kernel named it iio:device0 on this boot. On the next boot, with a second sensor attached, the same chip is iio:device1. Your program opens the wrong one and reports the temperature of the wrong room.
To fix this you need two skills. You must read what the kernel knows, and you must tell user space how to name things. Both start with one idea: the device model is exported as a tree of files.
A kobject is the small kernel structure that every object in the device model carries: devices, drivers, buses. The kernel documentation says it plainly: for every kobject registered with the system, "a directory is created for it in sysfs", as a subdirectory of the kobject’s parent. So the shape of the device model is the shape of the directory tree. Attributes appear as regular files. The documentation describes sysfs as a way to export "kernel data structures, their attributes, and the linkages between them to userspace."
The linkages are symlinks. A device directory holds a link called driver that points at its driver’s directory, and a link called subsystem that points at its bus. A driver directory holds a link back to each device it runs. Follow the links and you walk the same graph that the kernel matched in Chapter 2. This is why Chapter 2 told you to look for the driver link: its absence is the missing binding.
The device tree gets its own mirror. Each device made from a node keeps an of_node link to its node, and the whole live tree is also readable as files under /proc/device-tree. Two other places tell the truth about what runs. The file /sys/kernel/debug/clk/clk_summary from Chapter 4 shows which clocks are on. The directory /sys/class/regulator/ shows each rail with its state and num_users files.
One more file deserves a mention. For a platform device, driver_override lets you pick the driver by hand. The ABI document says writing a name to it overrides standard "OF, ACPI, ID table, and name matching", and that writing none opts the device out of binding. It is a debugging tool, and a good test of whether the match rule is your problem.
Try the browser below. Pick a file and read what the kernel returns. Then unbind the driver and see which files vanish.
Press a file name to read it. The tree on the canvas shows where it lives. Use the switch to unbind the driver, then choose a udev rule and see whether /dev/env0 appears.
The directory layout, file contents and the name attribute are illustrative of an I2C sensor with an IIO driver; names on your board will differ. The rules about kobjects, directories and symlinks are from the Linux 6.12 sysfs document; udev matching, globs and the case-insensitive i prefix are from the udev(7) manual page.
When a kobject is added or removed, the kernel sends a message called a uevent. A user-space daemon, udev, listens. For each event it reads a set of rule files. A rule has match keys and assignments. The keys use == to compare and != to reject. SUBSYSTEM matches the subsystem. ATTR{name} matches a sysfs attribute of the device. Most fields accept shell-style patterns: a star matches any run of characters, and a question mark matches one.
# /etc/udev/rules.d/90-env-sensor.rules SUBSYSTEM=="iio", ATTR{name}=="bme280", SYMLINK+="env0"
This rule says: for any device in the iio subsystem whose name attribute equals bme280, add a symlink /dev/env0. Your program opens /dev/env0 and never cares about the number. The manual page does not call the compare case-insensitive, and it offers an i prefix on a string to make it so. So treat the default as case-sensitive. That is why the second rule above fails: the attribute holds lowercase, and the rule asks for capitals.
Notice the chain of dependencies. For the symlink to exist, the compatible string must match (Chapter 2), the providers must be ready (Chapters 3 and 4), the rail must stay on (Chapter 0), and then the rule must match. Each link can fail in its own way, and each has its own file to read.
The symptom is a device that works under its kernel name but whose stable name never appears. The measurement is to ask udev what it sees. The tool udevadm info -a -p /sys/bus/iio/devices/iio:device0 prints the device and its parents with their attributes in rule syntax, so you can copy a real value. The tool udevadm monitor shows each uevent as it arrives. The fix is to match on an attribute that exists, with the exact value, and to reload the rules.
cat /sys/bus/iio/devices/iio:device0/name and note the exact string. Write the rule with that string, reload the rules with udevadm control --reload, and replug or run udevadm trigger. Then check that ls -l /dev/env0 points at the right device.ATTR{name}=="Bme280" but the attribute holds bme280. What do you expect?Chapter 8
Keep the numbers, the debugging order and a parser you can run, then pick your next lesson
Here is the whole lesson in one paragraph. The kernel can enumerate some buses and not others, so a data file, the device tree, declares what it cannot find. A node’s compatible list picks a driver by score. The driver then asks for pins, clocks, regulators, resets and power domains, and it says “not yet” with -EPROBE_DEFER until each provider is ready. A regulator nobody claims is switched off 30 seconds after start-up. Cell counts and trigger types change what plain numbers mean. Overlays patch the tree and schemas check it. Sysfs and udev show and name the result.
| Item | Value | Source |
|---|---|---|
| Regulator cleanup delay | 30 000 ms after late_initcall_sync | Linux 6.12 drivers/regulator/core.c |
| Probe retry error | -EPROBE_DEFER = error 517 | include/linux/errno.h, Linux 6.12 |
| deferred_probe_timeout default | 10 s with module support, 0 without | drivers/base/dd.c, Linux 6.12 |
| Compatible match score | INT_MAX/2 minus 4 times the index (1 073 741 823 at index 0) | drivers/of/base.c, Linux 6.12 |
| Compatible compare | strcasecmp, so case is ignored by the kernel | include/linux/of.h, Linux 6.12 |
| Default cell counts | #address-cells 2, #size-cells 1 | Devicetree specification v0.4 |
| IRQ trigger flags | 1 rising, 2 falling, 3 both, 4 level high, 8 level low | include/dt-bindings/interrupt-controller/irq.h |
| Devicetree specification | v0.4, published 28 June 2023 | devicetree-org/devicetree-specification |
| Common embedded kernel base | 6.12 is a longterm series (6.12.115 on 30 Oct 2026); Android 16 publishes GKI builds for android16-6.12 | kernel.org releases.json; source.android.com |
| Newest example | Linux 7.2 (Aug 2026) boots on Apple M3 Macs, far from daily use | Phoronix report on the 7.2 merge |
When a device does not work, walk down this list. Each step rules out one layer, and each uses a file you met in this lesson.
dtc -I fs -O dts /proc/device-tree and look. If not, check the overlay pipeline (Chapter 6).status okay? A missing property counts as okay. "disabled" means no device (Chapter 2)./sys/bus/<bus>/devices/ (Chapter 7).driver link? If not, compare the compatible list with the driver’s of_match_table (Chapter 2).devices_deferred? Read the reason and find the named provider (Chapter 3).clk_summary, pinmux-pins and the regulator num_users (Chapters 0 and 4).#address-cells and the interrupt controller’s binding (Chapter 5).make dtbs_check pass? It catches typos and missing properties (Chapter 6).udevadm info (Chapter 7).The parser below reads a small tree, builds the nodes, resolves a phandle label and decodes reg with the parent’s cell counts. It handles a fraction of the real format and checks nothing against a binding. We ran it, and the output follows.
# mini_dts.py: a tiny device tree reader (about 45 lines, plain Python) def parse(text): toks = re.findall(r'"[^"]*"|[\w#,.@+-]+:|[\w#,.@+&/-]+|[{};=<>]', text) pos = 2 # skip the root's '/' and '{' def node(name, label): nonlocal pos n = {'name': name, 'label': label, 'props': {}, 'kids': []} while toks[pos] != '}': t = toks[pos] if toks[pos + 1] == '{' or (t.endswith(':') and toks[pos + 2] == '{'): lab = None if t.endswith(':'): lab = t[:-1]; pos += 1; t = toks[pos] pos += 2; n['kids'].append(node(t, lab)); pos += 2 # skip '}' and ';' else: pos += 1; val = [] if toks[pos] == '=': pos += 1 while toks[pos] != ';': if toks[pos] == '<': pos += 1 while toks[pos] != '>' and toks[pos] != ';': if toks[pos] != ',': val.append(toks[pos].strip('"')) pos += 1 if toks[pos] == '>': pos += 1 if toks[pos] == ',': pos += 1 n['props'][t] = val pos += 1 # ';' return n root = node('/', None); return root def walk(n, labels, path=''): # a node's #address-cells / #size-cells describe the reg of its CHILDREN ac = int(n['props'].get('#address-cells', ['2'])[0], 0) sc = int(n['props'].get('#size-cells', ['1'])[0], 0) for k in n['kids']: p = path + '/' + k['name'] if k['label']: labels[k['label']] = p reg = k['props'].get('reg') if reg: r = [int(x, 0) for x in reg]; step = ac + sc regs = [(r[i], r[i + ac] if sc else None) for i in range(0, len(r), step)] print(p, 'reg ->', [(hex(a), s) for a, s in regs]) walk(k, labels, p) root = parse(SRC) labels = {} walk(root, labels) print('labels', labels) sensor = root['kids'][1]['kids'][0]['kids'][0] ref = sensor['props']['vdd-supply'][0].lstrip('&') print('sensor vdd-supply ->', labels[ref], ' compatible', sensor['props']['compatible'])
# output of the program above
/soc/i2c@40005400 reg -> [('0x40005400', 1024)]
/soc/i2c@40005400/sensor@76 reg -> [('0x76', None)]
labels {'vdd_sens': '/regulator', 'i2c1': '/soc/i2c@40005400'}
sensor vdd-supply -> /regulator compatible ['vendor,sensor-v2', 'vendor,sensor']
Read the output against Chapter 5. The I2C controller sits under a node with one address cell and one size cell, so its reg is an address plus a size of 1 024 bytes. The sensor sits under the controller, which sets one address cell and zero size cells, so its reg is the bare address 0x76. The label vdd_sens resolves to the regulator node, the link that Chapter 0 needed.
Device trees are how Linux describes boards on Arm and many other architectures. A BSP is mostly a tree plus a bootloader and a configuration. Vendor kernels often carry device-tree patches across kernel baselines. Keep those patches small and send them upstream, so that the next baseline does not break them. The 6.12 series is a longterm kernel and the base for Android 16’s published GKI builds, so much embedded work meets it. Newer kernels still add trees: Linux 7.2 added initial support to boot Apple M3 Macs, with much left to do.
Linux 6.12 source and documentation, read at tag v6.12 on GitHub: drivers/regulator/core.c, drivers/base/dd.c, drivers/base/platform.c, drivers/of/base.c, include/linux/of.h, drivers/clk/clk.c, drivers/pinctrl/pinmux.c, irq.h, bmp280-i2c.c, bmp085.yaml, arm,gic.yaml, sysfs-class-regulator, sysfs-bus-platform, sysfs.rst, submitting-patches.rst. Kernel documentation pages: devicetree usage model, driver model: drivers, pin control, overlay notes, writing schema. Standards and tools: Devicetree specification v0.4, U-Boot device tree overlays, udev(7), libgpiod. Release facts: kernel.org releases, Phoronix on Linux 7.2 and Apple M3, Android 16 6.12 GKI release builds. Every example value (addresses, pins, vendor strings, boot times) is illustrative unless a source above states it.
Open Teach and explain a deferred probe to an empty chair, with a drawing. Open Spark for the one-idea cards. Then go back to the instrument at the top and break each switch on purpose.