diff --git a/flake.nix b/flake.nix index f4a8c3c6..d71219c9 100644 --- a/flake.nix +++ b/flake.nix @@ -553,6 +553,9 @@ pkgs.lib.optionalAttrs (self.formatter ? ${system}) { formatting = treefmtEval.config.build.check self; } + // { + raspberry-pi-config-txt = pkgs.callPackage ./tests/config-txt-tests.nix { }; + } // nixosTests ); }; diff --git a/raspberry-pi/README.md b/raspberry-pi/README.md index bf96213b..8db72bd6 100644 --- a/raspberry-pi/README.md +++ b/raspberry-pi/README.md @@ -49,11 +49,11 @@ Board profiles import `hardware.raspberry-pi.configtxt`, which renders `config.t { hardware.raspberry-pi.configtxt.settings = { all = { - dtparam = [ "audio=on" ]; - dtoverlay = [ - "vc4-kms-v3d" - "disable-bt" + dtparam = [ + "audio=on" + "i2c_arm=on" ]; + disable_overscan = true; }; pi5.arm_freq = 2400; cm4.otg_mode = true; @@ -61,15 +61,61 @@ Board profiles import `hardware.raspberry-pi.configtxt`, which renders `config.t } ``` -List values become repeated keys in the rendered file, so the `dtoverlay` above expands to: +List values become repeated keys in the rendered file, so the `dtparam` above expands to: -``` -dtoverlay=vc4-kms-v3d -dtoverlay=disable-bt +```ini +dtparam=audio=on +dtparam=i2c_arm=on ``` Top-level attrs are conditional sections (`all`, `pi4`, `pi5`, `cm4`, and so on). Nesting stacks filters. To drop a default, set the key to `null` with `mkForce`. +Every rendered group opens with `[all]` and then its own filters. Filters of different types stack rather than replace, so `[all]` is what clears the previous group before the next one starts. + +The firmware applies these filters at boot, not Nix at evaluation time. This matters in two cases. One image can boot on more than one board, such as a CM4 and a CM5 swapped into the same carrier. Filters like `[EDID=...]`, `[gpio4=1]`, `[tryboot]` and `[bootvar0=42]` also depend on state that Nix cannot see: the attached monitor, a jumper, an EEPROM value. + +### Device tree overlays + +Overlays go in `configtxt.deviceTreeOverlays`, not in a `dtoverlay` key under `settings`. Filters nest the same way, and the leaf is an ordered list where each element names one overlay and its parameters: + +```nix +{ + hardware.raspberry-pi.configtxt.deviceTreeOverlays.pi4 = [ + { dwc2.dr_mode = "host"; } + { + gpio-fan = { + gpiopin = 14; + temp = 80000; + }; + } + ]; +} +``` + +This renders after `configtxt.settings` as: + +```ini +[all] +[pi4] +dtoverlay=dwc2 +dtparam=dr_mode=host +dtoverlay= +dtoverlay=gpio-fan +dtparam=gpiopin=14 +dtparam=temp=80000 +dtoverlay= +``` + +A separate option is necessary because `settings` groups values by key. That grouping cannot keep an overlay next to the `dtparam` lines that belong to it. The order is functional. A `dtparam` applies to the overlay that loaded last, and the parameters of an overlay stay in scope only until the next overlay loads. The bare `dtoverlay=` line closes that scope, so later parameters apply to the base device tree. The order between overlays can also matter, because one overlay can build on another. + +Overlays render after `settings`. This order keeps base parameters such as `dtparam=audio=on` out of the scope of an overlay. An overlay can export a parameter with the same name as a base parameter. While that overlay is in scope, the firmware uses the parameter of the overlay. + +Each parameter becomes its own `dtparam` line rather than an addition to the `dtoverlay` line, which keeps them clear of the 98-character line limit. Booleans render as `on` or `off`. Use `null` with `mkForce` to remove a parameter. + +The module concatenates lists from separate modules, but the order is not the order of definition. If one overlay must load before another, set the order with `mkBefore` or `mkAfter`. + +To supply your own file, set `configtxt.file`. The module then ignores `settings` and `deviceTreeOverlays`. + ## Current limits - No bootloader module: There's no `boot.loader.raspberry-pi` here. Boards rely on `generic-extlinux-compatible` plus U-Boot. Raspberry Pi OS has the GPU firmware load the kernel directly; we go through U-Boot so it reads `extlinux.conf`, which is what gives you the NixOS boot-generation menu and rollbacks. The firmware install module just stages the boot code and (optionally) U-Boot; it doesn't add a firmware-level direct-boot path. Pi 5 boots from SD via U-Boot, but USB, PCIe, and the RP1 don't come up until Linux takes over, so a USB keyboard at the U-Boot prompt won't work on Pi 5 today. diff --git a/raspberry-pi/common/config-txt-defaults.nix b/raspberry-pi/common/config-txt-defaults.nix index d52af85f..a184547c 100644 --- a/raspberry-pi/common/config-txt-defaults.nix +++ b/raspberry-pi/common/config-txt-defaults.nix @@ -8,30 +8,37 @@ { lib, ... }: { - hardware.raspberry-pi.configtxt.settings = { - all = { - camera_auto_detect = lib.mkDefault true; - display_auto_detect = lib.mkDefault true; - max_framebuffers = lib.mkDefault 2; - disable_fw_kms_setup = lib.mkDefault true; - disable_overscan = lib.mkDefault true; - arm_boost = lib.mkDefault true; - dtparam = lib.mkDefault [ "audio=on" ]; - dtoverlay = lib.mkDefault [ "vc4-kms-v3d" ]; - # U-Boot needs the UART enabled to boot (see arch/arm/mach-bcm283x/Kconfig - # in the U-Boot tree). Without it U-Boot hangs on the Pi 4. - enable_uart = lib.mkDefault true; + hardware.raspberry-pi.configtxt = { + settings = { + all = { + camera_auto_detect = lib.mkDefault true; + display_auto_detect = lib.mkDefault true; + max_framebuffers = lib.mkDefault 2; + disable_fw_kms_setup = lib.mkDefault true; + disable_overscan = lib.mkDefault true; + arm_boost = lib.mkDefault true; + # A base DTB parameter rather than an overlay one, so it stays here. It + # has to apply before any overlay loads: vc4-kms-v3d exports its own + # `audio` parameter, which would otherwise capture this line and set + # HDMI audio instead of enabling the onboard audio. + dtparam = lib.mkDefault [ "audio=on" ]; + # U-Boot needs the UART enabled to boot (see arch/arm/mach-bcm283x/Kconfig + # in the U-Boot tree). Without it U-Boot hangs on the Pi 4. + enable_uart = lib.mkDefault true; + }; + # The Pi 5 has a dedicated debug UART. Leaving the mini UART on feeds ghost + # input into boot, so turn it back off. + pi5 = { + enable_uart = lib.mkDefault false; + }; + cm4 = { + otg_mode = lib.mkDefault true; + }; }; - # The Pi 5 has a dedicated debug UART. Leaving the mini UART on feeds ghost - # input into boot, so turn it back off. - pi5 = { - enable_uart = lib.mkDefault false; - }; - cm4 = { - otg_mode = lib.mkDefault true; - }; - cm5 = { - dtoverlay = lib.mkDefault [ "dwc2,dr_mode=host" ]; + + deviceTreeOverlays = { + all = lib.mkDefault [ { vc4-kms-v3d = { }; } ]; + cm5 = lib.mkDefault [ { dwc2.dr_mode = "host"; } ]; }; }; } diff --git a/raspberry-pi/common/config-txt.nix b/raspberry-pi/common/config-txt.nix index 7dcc2fca..66501bf2 100644 --- a/raspberry-pi/common/config-txt.nix +++ b/raspberry-pi/common/config-txt.nix @@ -1,9 +1,13 @@ # config.txt generation module for Raspberry Pi # -# Generates config.txt from structured Nix options. The type system models -# config.txt as nested attrs: each nesting level adds a conditional filter, -# and leaves are config values. Repeated keys (dtparam, dtoverlay, gpio) -# are supported via lists. +# This module renders config.txt from structured Nix options. The type models +# config.txt as nested attrs: each level of nesting adds a conditional filter, +# and the leaves are config values. Lists produce repeated keys for dtparam, +# dtoverlay and gpio. +# +# Device tree overlays have their own option. A dtparam applies to the overlay +# that loaded last, and values grouped by key cannot express that order. +# Overlays render after settings, so base parameters apply first. # # Based on work from nvmd/nixos-raspberrypi (MIT License) and rendering # approach suggested by @quentinmit. Follows RFC 42. @@ -35,48 +39,156 @@ let mkKeyValue = lib.generators.mkKeyValueDefault { inherit mkValueString; } "="; - # Recursively flatten nested attrs into a list of { conditionals, name, value } records. - # Each nesting level (except the leaf) is a conditional filter. - # "all" filters are omitted from the conditionals list since they reset state. - # null values are filtered out, allowing `mkForce null` to remove defaults. - recurse = + # Overlay parameters use on/off for booleans. This follows the Raspberry Pi + # documentation and the overlay README. Plain settings keep 1/0. + mkParamValue = v: if builtins.isBool v then (if v then "on" else "off") else mkValueString v; + + # An "all" filter resets state rather than narrowing it, so it never has to be + # recorded. The rest are sorted, which makes two paths that stack the same + # filters in a different order compare equal. + mkConditionals = + path: + lib.pipe path [ + (lib.filter (k: k != "all")) + (lib.sort builtins.lessThan) + ]; + + # Flatten settings into { conditionals, items } groups, one group per leaf. + # Every level above the leaf is a conditional filter. A null value drops out, + # so `mkForce null` removes a default. + recurseSettings = path: value: if value == null then [ ] else if !(builtins.isAttrs value) then - { - conditionals = lib.sort builtins.lessThan (lib.filter (k: k != "all") (lib.tail path)); - name = lib.head path; - inherit value; - } + [ + { + conditionals = mkConditionals (lib.init path); + items = [ + { + name = lib.last path; + inherit value; + } + ]; + } + ] else - lib.flatten (lib.mapAttrsToList (name: recurse ([ name ] ++ path)) value); + lib.pipe value [ + (lib.mapAttrsToList (name: recurseSettings (path ++ [ name ]))) + lib.concatLists + ]; - # Group flattened items by their conditional filter set, then render. - groupItems = - items: - lib.mapAttrsToList (groupJSON: groupItems: { - conditionals = builtins.fromJSON groupJSON; - items = builtins.listToAttrs groupItems; - }) (builtins.groupBy (x: builtins.toJSON x.conditionals) items); + # The same flattening for overlays. Here the leaf is already the ordered + # overlay list for that filter set, so every level of nesting is a filter. + recurseOverlays = + path: value: + if value == null then + [ ] + else if builtins.isList value then + [ + { + conditionals = mkConditionals path; + items = value; + } + ] + else + lib.pipe value [ + (lib.mapAttrsToList (name: recurseOverlays (path ++ [ name ]))) + lib.concatLists + ]; - mkGroup = + # Merge groups that share a filter set. Two paths can reduce to the same set + # (all.pi4 and pi4.all both yield [ "pi4" ]), so merging is needed even though + # each recursion returns one group per leaf. + # + # Sorting first puts equal sets next to each other, so a single pass coalesces + # them. Folding from the right lets each step prepend, which keeps the result + # in order without a second pass. builtins.sort is stable, so items keep their + # original relative order, which overlays depend on. + # + # The sort is not redundant with mkConditionals, which only orders the filters + # within one group. Groups arrive in attrs walk order, driven by the raw names + # before "all" is stripped, so all.z.foo walks before b.bar. + groupByConditionals = + groups: + lib.pipe groups [ + (lib.sort (a: b: a.conditionals < b.conditionals)) + (lib.foldr ( + group: merged: + let + next = lib.head merged; + in + if merged != [ ] && next.conditionals == group.conditionals then + [ (group // { items = group.items ++ next.items; }) ] ++ lib.tail merged + else + [ group ] ++ merged + ) [ ]) + ]; + + # Every group opens with [all] plus its own filters. For settings that leading + # [all] is only a reset. For overlays it is required: a bare `dtoverlay=` ends + # overlay scope but leaves the conditional filters set, and only [all] clears + # them. + mkFilterHeader = conditionals: lib.concatMapStrings (f: "[${f}]\n") ([ "all" ] ++ conditionals); + + renderSettingsGroup = group: - lib.concatMapStrings (k: "[${k}]\n") group.conditionals - + lib.generators.toKeyValue { - inherit mkKeyValue; - listsAsDuplicateKeys = true; - } group.items; + mkFilterHeader group.conditionals + + lib.pipe group.items [ + builtins.listToAttrs + (lib.generators.toKeyValue { + inherit mkKeyValue; + listsAsDuplicateKeys = true; + }) + ]; - toConfigTxt = - attrs: - let - groups = lib.sort (a: b: a.conditionals < b.conditionals) ( - groupItems (lib.flatten (recurse [ ] attrs)) - ); - in - lib.concatMapStringsSep "\n[all]\n" mkGroup groups; + # Each entry ends with a bare `dtoverlay=`. This terminator closes the parameter + # scope of that overlay, so a later dtparam applies to the base DTB instead. A + # terminator must never come first in the file, where it means "load no HAT + # overlay". Settings render first, and every terminator here follows a + # dtoverlay=, so no terminator comes first today. A change to the section + # order can break this guarantee. + renderOverlayGroup = + group: + mkFilterHeader group.conditionals + + lib.concatMapStrings ( + entry: + let + name = lib.head (lib.attrNames entry); + in + lib.concatMapStrings (line: line + "\n") ( + [ "dtoverlay=${name}" ] + ++ lib.pipe entry.${name} [ + (lib.filterAttrs (_: v: v != null)) + (lib.mapAttrsToList (p: v: "dtparam=${p}=${mkParamValue v}")) + ] + ++ [ "dtoverlay=" ] + ) + ) group.items; + render = + conf: renderSectionFunc: recurseFunc: + lib.pipe conf [ + (recurseFunc [ ]) + groupByConditionals + (map renderSectionFunc) + (lib.concatStringsSep "\n") + ]; + + # Settings render first, so base DT parameters apply before any overlay loads. + # The overlay groups follow. A blank line separates the two sections, and the + # filter keeps that separator from becoming a stray leading or trailing line + # when one of the two is empty. + generatedConfig = + lib.pipe + [ + (render cfg.settings renderSettingsGroup recurseSettings) + (render cfg.deviceTreeOverlays renderOverlayGroup recurseOverlays) + ] + [ + (lib.filter (section: section != "")) + (lib.concatStringsSep "\n") + ]; in { options.hardware.raspberry-pi.configtxt = { @@ -115,6 +227,10 @@ in Booleans render as `0`/`1`. Use `null` with `mkForce` to remove a default. + Set device tree overlays through {option}`deviceTreeOverlays` rather + than a `dtoverlay` key here. A `dtoverlay` written here gets no + terminator, so it captures every `dtparam` that follows it. + See ''; example = lib.literalExpression '' @@ -131,13 +247,95 @@ in ''; }; + deviceTreeOverlays = lib.mkOption { + type = + let + inherit (lib.types) + addCheck + attrsOf + bool + int + listOf + nullOr + oneOf + str + ; + params = attrsOf ( + nullOr (oneOf [ + str + int + bool + ]) + ); + # Each list element names one overlay. Without this check one element + # can name two overlays, as in [ { a = { }; b = { }; } ]. Nix sorts + # attribute names, so the order between them is lost. + entry = addCheck (attrsOf params) (e: builtins.length (builtins.attrNames e) == 1) // { + description = "attribute set naming exactly one overlay, mapped to its parameters"; + }; + node = oneOf [ + (listOf entry) + (attrsOf node) + ]; + in + attrsOf node // { description = "config.txt device tree overlay type"; }; + default = { }; + description = '' + Device tree overlays for the Raspberry Pi firmware, rendered in list + order. + + Keys are conditional filter sections and nest exactly like + {option}`settings`. The leaf is an ordered list, and each element names + one overlay mapped to its parameters. + + Use this instead of a `dtoverlay` key in {option}`settings` when an + overlay has parameters. `settings` groups values by key and cannot keep + an overlay next to the `dtparam` lines that belong to it. A parameter + stays in scope only until the next overlay loads. + + Each parameter becomes its own `dtparam` line rather than an addition to + the `dtoverlay` line, which keeps them clear of the 98-character limit + on `config.txt` lines. Booleans render as `on` or `off`. Use `null` with + `mkForce` to remove a default. + + Overlays render after {option}`settings`, so base device tree parameters + set there apply before any overlay loads. The example renders as: + + ```ini + [all] + [pi4] + dtoverlay=dwc2 + dtparam=dr_mode=host + dtoverlay= + dtoverlay=gpio-fan + dtparam=gpiopin=14 + dtparam=temp=80000 + dtoverlay= + ``` + ''; + example = lib.literalExpression '' + { + pi4 = [ + { dwc2.dr_mode = "host"; } + { + gpio-fan = { + gpiopin = 14; + temp = 80000; + }; + } + ]; + } + ''; + }; + file = lib.mkOption { type = lib.types.path; - default = pkgs.writeText "config.txt" (toConfigTxt cfg.settings); - defaultText = lib.literalExpression ''pkgs.writeText "config.txt" (generated from settings)''; + default = pkgs.writeText "config.txt" generatedConfig; + defaultText = lib.literalExpression ''pkgs.writeText "config.txt" (generated from settings and deviceTreeOverlays)''; description = '' - Path to the generated config.txt file. Defaults to the rendered output - of `settings`, but can be overridden to supply a custom config.txt. + Path to the config.txt file to install. Defaults to the rendered output + of {option}`settings` and {option}`deviceTreeOverlays`. A custom file + replaces that output, so the module then ignores both options. ''; }; }; diff --git a/tests/config-txt-tests.nix b/tests/config-txt-tests.nix new file mode 100644 index 00000000..86615a06 --- /dev/null +++ b/tests/config-txt-tests.nix @@ -0,0 +1,246 @@ +# Rendering tests for config.txt. Board profile builds only prove the module +# evaluates, not that the output is right. +# +# Each case diffs the generated file against an expected one at build time, +# which avoids import-from-derivation. +# +# nix build .#checks..raspberry-pi-config-txt + +{ + lib, + pkgs, + runCommand, + writeText, +}: + +let + configtxt = ../raspberry-pi/common/config-txt.nix; + + # Render without a full NixOS evaluation. + render = + module: + (lib.evalModules { + modules = [ + configtxt + { _module.args = { inherit pkgs; }; } + module + ]; + }).config.hardware.raspberry-pi.configtxt.file; + + cases = { + empty = { + module = { }; + expected = ""; + }; + + settingsOnly = { + module = { + hardware.raspberry-pi.configtxt.settings.all.arm_boost = true; + }; + expected = '' + [all] + arm_boost=1 + ''; + }; + + settingsValueTypes = { + module = { + hardware.raspberry-pi.configtxt.settings.all = { + yes = true; + no = false; + num = 2; + text = "abc"; + }; + }; + expected = '' + [all] + no=0 + num=2 + text=abc + yes=1 + ''; + }; + + stackedFilters = { + module = { + hardware.raspberry-pi.configtxt.settings.pi4."gpio4=1".arm_freq = 1000; + }; + expected = '' + [all] + [gpio4=1] + [pi4] + arm_freq=1000 + ''; + }; + + # "all" is stripped before sorting, so all.z lands after b. + groupSortOrder = { + module = { + hardware.raspberry-pi.configtxt.settings = { + all.z.foo = 1; + b.bar = 2; + }; + }; + expected = '' + [all] + [b] + bar=2 + + [all] + [z] + foo=1 + ''; + }; + + # This is what makes mkForce null remove a default. + nullDropsOut = { + module = { + hardware.raspberry-pi.configtxt.settings.all = { + kept = true; + dropped = null; + }; + }; + expected = '' + [all] + kept=1 + ''; + }; + + listsRepeatKeys = { + module = { + hardware.raspberry-pi.configtxt.settings.all.dtparam = [ + "audio=on" + "i2c_arm=on" + ]; + }; + expected = '' + [all] + dtparam=audio=on + dtparam=i2c_arm=on + ''; + }; + + overlayWithParams = { + module = { + hardware.raspberry-pi.configtxt.deviceTreeOverlays.all = [ + { dwc2.dr_mode = "host"; } + ]; + }; + expected = '' + [all] + dtoverlay=dwc2 + dtparam=dr_mode=host + dtoverlay= + ''; + }; + + # Overlay parameters use on/off, unlike settings. + overlayBooleans = { + module = { + hardware.raspberry-pi.configtxt.deviceTreeOverlays.all = [ + { + example = { + yes = true; + no = false; + dropped = null; + }; + } + ]; + }; + expected = '' + [all] + dtoverlay=example + dtparam=no=off + dtparam=yes=on + dtoverlay= + ''; + }; + + duplicateOverlays = { + module = { + hardware.raspberry-pi.configtxt.deviceTreeOverlays.all = [ + { mcp251xfd.interrupt = 25; } + { mcp251xfd.interrupt = 24; } + ]; + }; + expected = '' + [all] + dtoverlay=mcp251xfd + dtparam=interrupt=25 + dtoverlay= + dtoverlay=mcp251xfd + dtparam=interrupt=24 + dtoverlay= + ''; + }; + + overlayOrder = { + module = { + hardware.raspberry-pi.configtxt.deviceTreeOverlays.all = [ + { first = { }; } + { second = { }; } + ]; + }; + expected = '' + [all] + dtoverlay=first + dtoverlay= + dtoverlay=second + dtoverlay= + ''; + }; + + # all.pi4 and pi4.all are the same filter set, so they merge. + mergedFilterPaths = { + module = { + hardware.raspberry-pi.configtxt.deviceTreeOverlays = { + all.pi4 = [ { first = { }; } ]; + pi4.all = [ { second = { }; } ]; + }; + }; + expected = '' + [all] + [pi4] + dtoverlay=first + dtoverlay= + dtoverlay=second + dtoverlay= + ''; + }; + + # dtoverlay sorts before dtparam, so rendering settings first is what keeps a + # base parameter out of an overlay's scope. + settingsRenderBeforeOverlays = { + module = { + hardware.raspberry-pi.configtxt = { + settings.all.dtparam = [ "audio=on" ]; + deviceTreeOverlays.all = [ { vc4-kms-v3d = { }; } ]; + }; + }; + expected = '' + [all] + dtparam=audio=on + + [all] + dtoverlay=vc4-kms-v3d + dtoverlay= + ''; + }; + }; + + # One derivation per case, so a single test can be built on its own. + tests = lib.mapAttrs ( + name: case: + runCommand "config-txt-${name}" { } '' + diff -u ${writeText "${name}-expected.txt" case.expected} ${render case.module} + touch $out + '' + ) cases; +in +# Building this builds every case, because naming them here makes them inputs. +# passthru re-exposes each one, so a single case can be built on its own with +# `nix build .#checks..raspberry-pi-config-txt.`. +runCommand "raspberry-pi-config-txt-tests" { + cases = lib.attrValues tests; + passthru = tests; +} "touch $out"