Эх сурвалжийг харах

Add Banana Pi M2 Berry/Ultra support with per-board configuration and board selection

k4be 5 өдөр өмнө
parent
commit
ad02a7f82e

+ 1 - 0
.gitignore

@@ -2,3 +2,4 @@
 /src/
 /out/
 /mnt/
+/.board

+ 16 - 6
NOTES.md

@@ -6,17 +6,16 @@
 "Other systems" in the README). Plan:
 
 - Move what both boards need out of
-  `files/dts/sun8i-h2-plus-orangepi-zero-radio.dts` into
-  `files/dts/orangepi-zero-common.dtsi`: `ehci2`/`ohci2`, `ehci3`/`ohci3` and
+  `files/opi0/dts/sun8i-h2-plus-orangepi-zero-radio.dts` into
+  `files/opi0/dts/orangepi-zero-common.dtsi`: `ehci2`/`ohci2`, `ehci3`/`ohci3` and
   the `xr819` block (xradio compatible, PG10 host-wake).
 - `sun8i-h2-plus-orangepi-zero-radio.dts` = mainline board file + common
   `.dtsi` + codec, i2c1, panel, U2, radio-keys.
 - `sun8i-h2-plus-orangepi-zero-solar.dts` = mainline board file + common
   `.dtsi`, nothing else.
-- `build-kernel.sh`: turn `BOARD_DTS`/`BOARD_DTB` into a list (e.g.
-  `BOARD_DTS_LIST`). `prepare_source` links each into the kernel tree,
-  `do_build` builds each with `DTC_FLAGS=-@` and `do_package` copies each to
-  `boot/opi0/<release>/`. Also link the `.dtsi`.
+- `boards/opi0.sh`: add the solar DTB to `BOARD_DTBS`. `build-kernel.sh`
+  already links every `files/opi0/dts/*.dts{,i}` into the kernel tree, builds
+  each DTB in `BOARD_DTBS` with `-@` and stages it in `boot/opi0/<release>/`.
 - Solar install: `BOOT_DTB=sun8i-h2-plus-orangepi-zero-solar.dtb ./install-kernel.sh ssh:root@solar1.lo`.
   Their `KERNEL_CONSOLE` can drop `console=tty1 fbcon=…`.
 
@@ -49,6 +48,17 @@ restore `KD_TEXT` on exit. Then neither fbcon nor a getty/journald writer on
 tty1 can draw over it. Until then: `systemctl mask getty@tty1.service` on the
 target.
 
+## Banana Pi M2 (bpi-m2): open
+
+- U-Boot and kernel are installed on marlena and banana-backup; both boot
+  and are tested and working.
+- Is marlena an M2 Berry? If yes, boot it on the Berry DTB
+  (`BOOT_DTB=sun8i-v40-bananapi-m2-berry-k4be.dtb`, after changing its
+  `load_dt` name or keeping the Ultra name) and drop the Ultra DTS.
+- Kernel source: kernel.org 7.3.4 like the OPi0 (`KERNEL_VERSION` in
+  `boards/bpi-m2.sh`); the notes mention gentoo-sources 6.18.63 (LTS) as an
+  alternative.
+
 ## Untested
 
 - Armbian's `boot.scr` under the new U-Boot (fallback when `extlinux.conf`

+ 295 - 49
README.md

@@ -1,28 +1,61 @@
-# Orange Pi Zero (original, H2+): mainline U-Boot and kernel
+# Allwinner boards: mainline U-Boot and kernel
 
 Builds mainline U-Boot and a self-contained mainline kernel (no initramfs) for
-the radio's Orange Pi Zero. The userspace is the existing Armbian (Debian
-bookworm) root filesystem. Its Armbian boot files (`boot.scr`,
-`armbianEnv.txt`, `uInitrd`, Armbian overlays) are left in place and are not
-used: our U-Boot reads `/boot/extlinux/extlinux.conf`.
+two board types, and installs them on a card or on the running board over ssh:
+
+| Board type | Id | Boards | Boot chain |
+|---|---|---|---|
+| Orange Pi Zero (Allwinner H2+) | `opi0` | the radio (`radio.lo`); also the solar boards | `extlinux.conf`, Armbian rootfs |
+| Banana Pi M2 Berry/Ultra (Allwinner V40/R40) | `bpi-m2` | marlena (192.168.2.1), banana-backup (192.168.2.150) | hand-written U-Boot environment in `/boot/uboot.env`, legacy `uImage`, Gentoo |
+
+Both board types are tested and working with these builds.
 
 | | Version | Source |
 |---|---|---|
-| Kernel | 7.3.4 (stable) | cdn.kernel.org tarball, sha256 checked |
-| U-Boot | v2026.10 | GitHub tag tarball (ftp.denx.de as fallback) |
-| xradio (XR819 Wi-Fi, out of tree) | fifteenhex/xradio @ 3ce657ae | GitHub tarball |
+| Kernel | 7.3.4 (stable), both board types | cdn.kernel.org tarball, sha256 checked |
+| U-Boot | v2026.10, both board types | GitHub tag tarball (ftp.denx.de as fallback) |
+| xradio (OPi0 XR819 Wi-Fi, out of tree) | fifteenhex/xradio @ 3ce657ae | GitHub tarball |
+
+## Selecting the board type
+
+    ./select-board.sh          # menu
+    ./select-board.sh bpi-m2   # directly (no terminal needed)
+    ./select-board.sh -l       # list, * marks the selected one
+
+The choice is kept in `.board` (not in git). Every script reads it and prints
+it first, so each command's output starts with the board type it works for:
+
+    === board: Banana Pi M2 Berry/Ultra (Allwinner V40/R40) [bpi-m2] (selected with select-board.sh)
+
+`BOARD=<id>` in the environment overrides the selection for one command
+(`BOARD=opi0 ./build-kernel.sh`); the banner then says so. Without a
+selection the scripts stop and ask for one.
+
+Each board type keeps its own settings and results:
+
+| | Where |
+|---|---|
+| versions, toolchain, defconfig, DTBs, install method, build hooks | `boards/<id>.sh` |
+| kernel/U-Boot config fragments, device trees, overlays | `files/<id>/` |
+| build directories, tarballs, U-Boot image | `out/<id>/` |
+| downloads and extracted sources (shared, built out of tree) | `dl/`, `src/` |
+| bootloader areas saved by `write-uboot.sh` (all boards) | `out/backup/` |
+
+Switching the board type does not touch the other one's build: both can be
+built one after the other, and incremental builds stay incremental.
 
-Versions, toolchain (`armv7a-hardfloat-linux-gnueabi-`) and boot settings are in
-`config.sh`. Any of them can be overridden from the environment.
+`install-kernel.sh` and `write-uboot.sh` in ssh mode refuse a board whose
+`/proc/device-tree/compatible` does not match the selected type
+(`allwinner,sun8i-h2-plus` / `allwinner,sun8i-r40`); `FORCE=1` overrides.
 
 ## Building
 
-    ./build-uboot.sh        # -> out/u-boot/u-boot-sunxi-with-spl.bin
-    ./build-kernel.sh       # -> out/opi0-kernel-<release>.tar.gz
+    ./build-uboot.sh        # -> out/<id>/u-boot/u-boot-sunxi-with-spl.bin
+    ./build-kernel.sh       # -> out/<id>/<id>-kernel-<release>.tar.gz
 
 Both scripts download what is missing into `dl/`, unpack into `src/` and build
-out of tree in `out/`. Without a subcommand they run `all`: configure if there
-is no `.config` yet, then build (the kernel script also builds the
+out of tree in `out/<id>/`. Without a subcommand they run `all`: configure if
+there is no `.config` yet, then build (the kernel script also builds the
 out-of-tree modules and packs the tarball). Subcommands:
 
 | | `build-uboot.sh` | `build-kernel.sh` |
@@ -30,15 +63,39 @@ out-of-tree modules and packs the tarball). Subcommands:
 | `all` (default) | configure if needed, build | configure if needed, build, `modules`, `package` |
 | `config` | regenerate `.config` | regenerate `.config` |
 | `menuconfig` | edit the current `.config` | edit the current `.config` |
-| `build` | build | kernel, in-tree modules and DTBs only |
-| `modules` | | only the out-of-tree xradio module |
+| `build` | build | kernel, in-tree modules and the board's DTBs only |
+| `modules` | | only the out-of-tree modules (OPi0: xradio) |
 | `package` | | only stage and pack the tarball |
-| `clean` | remove `out/ubuild`, `out/u-boot` | remove `out/kbuild`, `out/kernel` |
+| `clean` | remove `out/<id>/ubuild`, `out/<id>/u-boot` | remove `out/<id>/kbuild`, `out/<id>/kernel` |
 
 A menuconfig change is kept until the next `config`. Put lasting changes in
-`files/kernel.config` or `files/u-boot.config`. Both `config` commands fail if
-any option of the fragment did not survive (renamed symbol or missing
-dependency).
+the fragments. Both `config` commands fail if any option of the fragments did
+not survive (renamed symbol or missing dependency).
+
+### Kernel configuration
+
+`sunxi_defconfig`, then `files/kernel-common.config`, then
+`files/<id>/kernel.config` (a later fragment overrides an earlier one). The
+policy for both board types:
+
+- **Self-contained**: no initramfs; MMC, ext4, and for the Bananas SATA,
+  ethernet and the RTC, are built in.
+- **Built in wherever that works.** A module only where it has to be one, and
+  the fragment says why next to it. bpi-m2 has no modules at all; OPi0 keeps
+  zram, dummy, snd-aloop and the legacy USB gadgets as modules (plus xradio,
+  which is out of tree). `build-kernel.sh config` prints how many `=m` are left.
+- **Stripped**: `sunxi_defconfig` serves every Allwinner SoC from the A10 to
+  the A80. Both of ours are sun8i, so the other `MACH_*` families, their pin
+  controllers and clock units, and drivers for hardware neither board has
+  (CAN, A10 EMAC, touchscreen, PS/2, LRADC keys, IR, camera, video
+  decoder/deinterlacer, Mali GPU, LVDS/eDP panels, other SoCs' crypto
+  engines, NFS root, IP autoconfig) are off. Each board fragment also drops
+  the other board's pin controller and clocks (H3 vs R40) and what that
+  board lacks (OPi0: PMIC, SATA, HDMI; bpi-m2: sound, OTG/gadget, Wi-Fi/BT).
+- Common: what systemd, OpenRC/udev, portage's sandboxes and OpenSSH need
+  (cgroups, namespaces, seccomp filter, devtmpfs, `UEVENT_HELPER` off, …),
+  `/proc/config.gz`, nftables with the iptables compat layer, NFS client,
+  USB serial adapters (FTDI, PL2303, CH341, CP210x, ACM) and USB storage.
 
 ### Host tools
 
@@ -46,19 +103,29 @@ The scripts check for these and stop if any are missing. They never install
 anything.
 
 - both: `curl`, `tar`, `make`, a host C compiler, the cross compiler
-  `${CROSS_COMPILE}gcc`, `bison`, `flex`, `bc`, `dtc`
-- kernel: `xz`, `sha256sum`, `perl`, `depmod` (kmod), `fdtget` (dtc)
+  `${CROSS_COMPILE}gcc`, `bison`, `flex`, `bc`, `dtc`, `python3`
+- kernel: `xz`, `sha256sum`, `perl`, `depmod` (kmod), `fdtget` (dtc);
+  bpi-m2 also `mkimage` (u-boot-tools) and `fdtoverlay` (dtc)
 - U-Boot: `gzip`, `swig`, `python3` with `pyelftools` and `setuptools` (binman
   assembles `u-boot-sunxi-with-spl.bin`), and OpenSSL development headers for
-  the host tools. GnuTLS is not needed: `files/u-boot.config` disables
+  the host tools. GnuTLS is not needed: the U-Boot fragments disable
   `mkeficapsule`, the only tool that uses it.
 
-The H2+/H3 is 32-bit and boots straight from SPL into U-Boot, so there is no
-TF-A (ARM Trusted Firmware) or crust to build, unlike the 64-bit sunxi chips.
+Toolchains: OPi0 `armv7a-hardfloat-linux-gnueabi-`, bpi-m2
+`armv7a-unknown-linux-gnueabihf-` (the boards' CHOST since the Gentoo 23.0
+migration). The H2+ and the R40 are 32-bit and boot straight from SPL into
+U-Boot, so there is no TF-A (ARM Trusted Firmware) or crust to build.
 
-## Installing
+## Orange Pi Zero (`opi0`)
 
-### Bootloader
+The radio's Orange Pi Zero. The userspace is the existing Armbian (Debian
+bookworm) root filesystem. Its Armbian boot files (`boot.scr`,
+`armbianEnv.txt`, `uInitrd`, Armbian overlays) are left in place and are not
+used: our U-Boot reads `/boot/extlinux/extlinux.conf`.
+
+### Installing
+
+#### Bootloader
 
 Card in a reader on this PC, or in the running board:
 
@@ -98,7 +165,7 @@ filesystem (on mainline that is `/dev/mmcblk0`, the SD slot; the XR819 on
 mmc1 is SDIO and has no block device). `DEV=/dev/mmcblkN` overrides it. The
 PC-side checks do not apply there; the partition check and the backup do.
 
-#### The U-Boot environment and the 544 KiB mark
+##### The U-Boot environment and the 544 KiB mark
 
 Older sunxi U-Boot, including Armbian's 2019.04, kept its environment raw on
 the card at 544 KiB (`CONFIG_ENV_OFFSET=0x88000`, 128 KiB), which used to cap
@@ -116,23 +183,23 @@ already a little over 536 KiB, and that is fine:
   everything boot-related is in `extlinux.conf`. There is no stale
   environment to clear with `env default -a`.
 - `write-uboot.sh` reads the build's `.config`: if `CONFIG_ENV_IS_IN_MMC` is
-  ever turned on in `files/u-boot.config`, it refuses an image that would
+  ever turned on in `files/opi0/u-boot.config`, it refuses an image that would
   reach `CONFIG_ENV_OFFSET`.
 
 The SPI NOR flash on the board also has an environment slot
 (`CONFIG_ENV_IS_IN_SPI_FLASH`), but only for SPI boot. The boot ROM tries the
 SD card first, so it is not used.
 
-### Kernel
+#### Kernel
 
 Into the card's root partition mounted on this PC, or over ssh:
 
     sudo ./install-kernel.sh /mnt/root
     ./install-kernel.sh ssh:root@radio.lo
 
-This installs `out/opi0-kernel-<release>.tar.gz` for the release of the last
-build (`out/kernel-release`); `RELEASE=<release>` picks another tarball still
-in `out/`. The kernel, DTBs and overlays go to `/boot/opi0/<release>/` and
+This installs `out/opi0/opi0-kernel-<release>.tar.gz` for the release of the last
+build (`out/opi0/kernel-release`); `RELEASE=<release>` picks another tarball still
+in `out/opi0/`. The kernel, DTBs and overlays go to `/boot/opi0/<release>/` and
 the modules to `/lib/modules/<release>/`. `modules.dep` is generated at build
 time (`depmod -b <stage> <release>`) and is in the tarball, so nothing runs
 on the target. Then `/boot/extlinux/extlinux.conf` is regenerated (the
@@ -172,7 +239,7 @@ is regenerated:
 Do not remove the release that is running or the only one that is known to
 boot.
 
-#### If a new kernel does not boot
+##### If a new kernel does not boot
 
 The highest release always boots by default, and only the serial console
 (UART header, 115200) can pick another entry. A kernel that panics reboots
@@ -182,7 +249,7 @@ the card: mount it on the PC, delete the bad `/boot/opi0/<release>/` and run
 An automatic fallback (U-Boot bootcount with the watchdog) is not set up yet;
 see `NOTES.md`.
 
-### Going back to the Armbian kernel
+#### Going back to the Armbian kernel
 
 With the **old** U-Boot still on the card: the Armbian U-Boot (2019.04) also
 prefers `extlinux.conf` over `boot.scr`, so once the kernel is installed the
@@ -200,7 +267,7 @@ whether that script (written for 2019.04 and Armbian's environment) works
 under 2026.10. The reliable way back is to restore the old bootloader from
 the backup (see above) *and* remove `extlinux.conf`.
 
-### Armbian packages on the rootfs
+#### Armbian packages on the rootfs
 
 Some Armbian packages can undo this setup. `install-kernel.sh` warns about
 them, but changes nothing:
@@ -219,11 +286,11 @@ them, but changes nothing:
 - `armbian-zram-config` sets the compression from `SWAP_ALGORITHM` in
   `/etc/default/armbian-zram-config`. The kernel has lzo, lzo-rle, lz4 (the
   default) and zstd for zram; anything else must be added to
-  `files/kernel.config`.
+  `files/opi0/kernel.config`.
 
-## What is in the build
+### What is in the build
 
-`files/dts/sun8i-h2-plus-orangepi-zero-radio.dts` (the DTB used to boot)
+`files/opi0/dts/sun8i-h2-plus-orangepi-zero-radio.dts` (the DTB used to boot)
 includes the mainline board file and adds:
 
 - analog codec (line out/mic on the 13-pin header), USB host 2 and 3: the
@@ -245,11 +312,19 @@ includes the mainline board file and adds:
   xradio driver needs. U-Boot sets the Wi-Fi MAC from the SoC ID through the
   `ethernet1` alias.
 
-Kernel: `sunxi_defconfig` plus `files/kernel.config`. This adds systemd needs
+Kernel: `sunxi_defconfig` plus `files/kernel-common.config` and
+`files/opi0/kernel.config`. This adds systemd needs
 (cgroups, namespaces, autofs…), zram, NFS, nftables (with the compat layer for
 iptables-nft), cfg80211/mac80211, the H3 codec, USB host/gadget (g_serial,
 configfs), USB storage, serial adapters and audio. It drops the HDMI/GPU/video
-drivers: this board has no display output. Built in and checked by `config`:
+drivers and the display clocks (this board has no display output), the PMIC
+drivers (no AXP chip here), SATA and the R40 pin controller and clocks.
+Everything is built in except four modules, each for a reason given in the
+fragment: zram (armbian-zram-config passes module parameters), dummy (built
+in it would create `dummy0`), snd-aloop (built in it would always take a sound
+card index) and the legacy gadgets g_serial/g_ether (a built-in one would bind
+the only UDC at boot). xradio is out of tree and always a module. Built in and
+checked by `config`:
 
 - the sunxi MMC driver and ext4: there is no initramfs to load them from
 - cpufreq-dt with the GPIO regulator for the CPU supply (PL6, already in the
@@ -258,7 +333,7 @@ drivers: this board has no display output. Built in and checked by `config`:
 - the sunxi watchdog and the sun6i RTC
 - `FONT_6x8` for `fbcon=font:6x8`
 
-### Drivers for the radio panel and keys
+#### Drivers for the radio panel and keys
 
 The panel driver and its overlay come from the s1d13700-tca repository
 (`$PANEL_DIR`, default `/home/k4be/git/radio/s1d13700-tca`), the key overlay
@@ -317,7 +392,7 @@ starts using renamed helper functions (`drm_atomic_state_*` →
 `drm_atomic_commit_*`), they need their own lines in that header (in
 `build-kernel.sh`).
 
-## Consoles and boot logging
+### Consoles and boot logging
 
 The kernel command line has `console=tty1` (the panel, through fbcon)
 followed by `console=ttyS0,115200`. Kernel messages go to both. The last
@@ -370,7 +445,7 @@ and optionally add `vt.global_cursor_default=0` to `KERNEL_CMDLINE_EXTRA` to
 hide the text cursor. The proper fix belongs in radio-ui: switching the VT to
 `KD_GRAPHICS` while it owns the display (see `NOTES.md`).
 
-## Other systems
+### Other systems
 
 The same Orange Pi Zero board is also used in the two solar monitoring
 systems (`solar1.lo` and `solar2.lo`), which have no radio panel. They can
@@ -390,15 +465,186 @@ plain mainline board file, also in `/boot/opi0/<release>/`). That loses USB
 2/3 on the 13-pin header and the xradio binding, so no Wi-Fi. A dedicated
 solar DTS is planned (see `NOTES.md`).
 
+## Banana Pi M2 Berry/Ultra (`bpi-m2`)
+
+Two Gentoo servers. **marlena is the LAN's core server** (DNS, DHCP, gateway
+address, NFS, samba, the furnace page); every reboot of it has to be agreed
+with its owner and needs a window without DNS/DHCP. Background, risks and
+recovery are in `BANANA-V40-notes.md`; the option list with evidence in
+`/mnt/d/SBC/bananapi-build/M2U/2026/kernel-options-report.md`.
+
+| | marlena | banana-backup |
+|---|---|---|
+| ssh | `root@192.168.2.1` (`marlena.lo`) | `root@192.168.2.150` |
+| DT it boots | `sun8i-r40-bananapi-m2-ultra.dtb` | `sun8i-v40-bananapi-m2-berry-k4be.dtb` |
+| our DTB for it | `sun8i-r40-bananapi-m2-ultra-k4be.dtb` | `sun8i-v40-bananapi-m2-berry-k4be.dtb` |
+| extra | applies `sun8i-r40-bananapi-m2-ultra-led.dtbo` in U-Boot | |
+
+Most likely the boards are the same hardware (an M2 Berry): same SoC, RAM,
+Wi-Fi, PHY, SATA and DS1307, and marlena's eMMC host (`mmc2`) finds no card.
+One kernel and one U-Boot serve both; each keeps its own DT base until that
+is confirmed physically.
+
+### Boot chain
+
+There is no `boot.scr`, `extlinux.conf` or initramfs. U-Boot runs a
+hand-written environment saved in `/boot/uboot.env` on the FAT partition 1:
+`fatload mmc 0:1 0x47000000 uImage`, `fatload mmc 0:1 0x43000000 <dtb>`,
+`bootm 0x47000000 - 0x43000000`, on marlena also `fdt apply` of the LED
+overlay. `bootargs` is `earlyprintk root=/dev/mmcblk0p2 rootfstype=ext4
+rootwait`; the console comes from the DTB's `stdout-path`. Nothing here
+changes that environment.
+
+The kernel is therefore a legacy `uImage` (load and entry 0x40008000), and
+`build-kernel.sh` stops if it grows past 32 MiB (it would reach the area where
+U-Boot relocates the DTB). Currently it is about 7.5 MB.
+
+### U-Boot
+
+    ./build-uboot.sh
+    ./write-uboot.sh ssh:root@192.168.2.150     # or /dev/sdX for the card in a reader
+
+`bananapi_m2_berry_defconfig` plus `files/bpi-m2/u-boot.config`, for both
+boards: the Ultra defconfig differs only in its U-Boot DT and the eMMC slot.
+The image is about 555 KiB from 8 KiB on; banana-backup's first partition
+starts at 1 MiB, marlena's at 100 MiB.
+
+**The environment size matters.** Both boards' `uboot.env` files are 128 KiB
+and their CRC covers 0x20000 bytes, as the 2018 and 2021 U-Boots wrote them.
+Mainline sunxi U-Boot now defaults to 64 KiB (`CONFIG_ENV_SIZE=0x10000`); with
+that, the CRC fails, U-Boot silently uses its built-in environment, finds no
+`extlinux.conf` or `boot.scr` and does not boot. The fragment sets
+`CONFIG_ENV_SIZE=0x20000` and pins the file to `mmc 0:1` (`uboot.env`), and
+enables what the environment uses (`fatload`, `bootm` of legacy images,
+`fdt apply`). Before writing, `write-uboot.sh` reads the target's
+`/boot/uboot.env` (ssh: mounting `/boot` read-only if needed; `/dev/sdX`:
+partition 1 must be mounted) and refuses to write unless the file passes this
+build's CRC check (`lib/uboot-env.py check`). `ENV_CHECK_SKIP=1` overrides.
+The environment's `preboot=usb start` now runs (banana-backup's 2021 U-Boot
+was built without USB and ethernet); that costs a second or two at boot.
+
+The backup and restore of the old bootloader area work as for the OPi0 (see
+there): `out/backup/u-boot-area-<host>-<date>.bin`.
+
+### Kernel
+
+    ./build-kernel.sh
+    ./install-kernel.sh ssh:root@192.168.2.150
+    sudo ./install-kernel.sh /mnt/root         # card on the PC: root partition on /mnt/root,
+                                               # partition 1 (FAT) on /mnt/root/boot
+
+The tarball holds `boot/bpi-m2/<release>/` (`uImage`, both DTBs, `overlay/`,
+`config`, `System.map`) and `lib/modules/<release>/` (only the `modules.*`
+index files: everything is built in). `install-kernel.sh`:
+
+1. refuses to run while Gentoo builds are running on the board (screen session
+   `profile23`, `emerge`); `FORCE_BUSY=1` overrides;
+2. mounts `/boot` if needed (it is `noauto`) and unmounts it again at the end.
+   It stops if the FAT dirty flag is set (read from the boot sector while
+   unmounted, or from the kernel's "not properly unmounted" message if it was
+   already mounted): fsck the partition first, or `FAT_DIRTY_OK=1`;
+3. reads `/boot/uboot.env` to find the kernel and DTB names it loads, and
+   picks our DTB by that name (`*m2-ultra*` → the Ultra DTB, `*m2-berry*` →
+   the Berry DTB; `BOOT_DTB=<ours>` overrides);
+4. if the environment applies an overlay, checks with `fdtoverlay` that the
+   board's own `.dtbo` applies to the new DTB (a failed `fdt apply` in U-Boot
+   can leave the tree broken);
+5. warns if `/etc/conf.d/net` configures `eth0` (marlena): with udev working
+   again on the new kernel the interface will most likely be renamed `end0`,
+   as on banana-backup, and the static configuration of the LAN's gateway
+   would not apply;
+6. copies the release to `/boot/bpi-m2/<release>/`, keeps the current kernel
+   and DTB as `uImage-<old release>` / `<dtb>.<old release>` (unless they are
+   our own build, already in `/boot/bpi-m2/<old release>/`), then copies the
+   new `uImage` and DTB over the names the environment loads and verifies
+   them by checksum;
+7. prints the U-Boot commands to boot the previous kernel. It never reboots.
+
+Rollback at the U-Boot prompt (serial console, 115200, stop autoboot), e.g.
+for banana-backup:
+
+    fatload mmc 0:1 0x47000000 uImage-5.4.80-gentoo-r1-k4be
+    fatload mmc 0:1 0x43000000 sun8i-v40-bananapi-m2-berry-k4be.dtb.5.4.80-gentoo-r1-k4be
+    bootm 0x47000000 - 0x43000000
+
+An older release of ours boots the same way from `bpi-m2/<release>/uImage`
+and `bpi-m2/<release>/<dtb>`. To delete one, remove its directory in
+`/boot/bpi-m2/` and `/lib/modules/<release>/`; FAT `/boot` is 200 MB on
+banana-backup, and each release takes about 11 MB.
+
+### Device trees
+
+`files/bpi-m2/dts/`: the mainline board file of each board plus
+`bananapi-m2-k4be.dtsi`:
+
+- the battery-backed DS1307 at 0x68 on i2c2 (`ds1307: rtc@68`), with aliases
+  `rtc0 = &ds1307` and `rtc1 = &rtc`: the SoC RTC is built in as well (it
+  provides the 32 kHz clock) and must not become `rtc0`, which
+  `RTC_HCTOSYS`/`RTC_SYSTOHC`, hwclock and chrony use. `build-kernel.sh`
+  checks the alias in both DTBs;
+- `mmc0`/`mmc1` (and `mmc2` on the Ultra) aliases, so the SD card stays
+  `mmcblk0` for `root=/dev/mmcblk0p2` whatever probes first;
+- LED triggers as deployed: red power LED heartbeat, green user LED `mmc0`;
+  the nodes carry the labels `pwr_led` and `user_led_green` that marlena's
+  overlay targets. The overlay is now redundant but still applies;
+  `build-kernel.sh` test-applies a copy of it (`files/bpi-m2/overlay/`) to the
+  Ultra DTB.
+
+Built with symbols (`-@`). Compared with the deployed DTBs, the same devices
+are enabled; the Ultra file additionally enables HDMI, IR and the Bluetooth
+UART, which have no driver in this kernel (HDMI does: see below).
+
+### What is in the kernel
+
+`files/bpi-m2/kernel.config` on top of the common fragment, `-k4be`
+releases, everything built in:
+
+- AXP221 PMIC (regulators for SATA, the PHY, the CPU; power key, charger,
+  battery gauge), DS1307 + SoC RTC with `RTC_HCTOSYS`/`RTC_SYSTOHC` on `rtc0`
+- SATA (`AHCI_SUNXI`), dwmac-sun8i with the Realtek PHY, sunxi MMC, cpufreq
+  and thermal, watchdog
+- NFS server (v3/v4) and client, CIFS, bridge, overlayfs, ISO 9660, nftables
+- FTDI and other USB serial adapters (marlena's furnace controller), USB
+  storage, HID
+- HDMI console (`DRM_SUN4I`, dw-hdmi, fbcon) for local recovery without the
+  serial cable
+- seccomp filter (OpenSSH ≥ 10), `UEVENT_HELPER` off, namespaces, cgroups,
+  `IKCONFIG_PROC`, `NET_SCHED`, kTLS, task I/O accounting (htop)
+
+Left out: sound, the OTG port (neither DT enables it), the AP6212 Wi-Fi and
+Bluetooth (unused, no firmware on banana-backup; the fragment says what to
+enable, as a module, if needed), 1-Wire (no master in either DT), IR, video
+engines, the Mali GPU.
+
+### After installing: before and after the reboot
+
+On the board, before rebooting (see `BANANA-V40-notes.md` sections 0, 5, 7):
+
+- the Gentoo builds are done; marlena: a reboot window is agreed;
+- marlena: the `eth0` → `end0` question above is settled;
+- the serial console is attached.
+
+After booting the new kernel: `uname -r`, `ls -l /dev/rtc*` (`rtc0` is the
+DS1307; `hwclock -r` vs `date`), `rc-service udev-trigger status`,
+`zcat /proc/config.gz | head`, ssh login, and on marlena `/dev/mydev0`, DNS,
+dhcpd, samba, nfs. Then the migration's workarounds can go (table in the
+notes, section 7).
+
 ## Layout
 
 | Path | What |
 |---|---|
-| `config.sh` | versions, toolchain, paths, boot settings, shared helpers |
+| `select-board.sh` | pick the board type (kept in `.board`) |
+| `config.sh` | board selection, paths, shared helpers |
+| `boards/<id>.sh` | per board type: versions, toolchain, defconfig, DTBs, install method, build hooks |
 | `build-kernel.sh`, `build-uboot.sh` | download, configure, build |
 | `write-uboot.sh`, `install-kernel.sh` | put the results on a card or board |
-| `files/kernel.config`, `files/u-boot.config` | config fragments |
-| `files/dts/` | board device tree |
-| `NOTES.md` | planned changes and open questions |
-| `dl/`, `src/`, `out/` | downloads, sources, build output (all regenerable) |
+| `lib/install-extlinux.sh`, `lib/install-ubootenv.sh` | the two install methods |
+| `lib/uboot-env.py` | read and CRC-check a `uboot.env` |
+| `files/kernel-common.config` | kernel fragment for all board types |
+| `files/<id>/kernel.config`, `files/<id>/u-boot.config` | per-board fragments |
+| `files/<id>/dts/`, `files/bpi-m2/overlay/` | board device trees, overlay sources |
+| `NOTES.md`, `BANANA-V40-notes.md` | planned changes, open questions; the Banana handover notes |
+| `dl/`, `src/` | downloads, sources (shared, regenerable) |
+| `out/<id>/` | build output per board type (regenerable) |
 | `out/backup/` | bootloader areas saved by `write-uboot.sh` (**not** regenerable) |

+ 91 - 0
boards/bpi-m2.sh

@@ -0,0 +1,91 @@
+# Board type: Banana Pi M2 Berry / M2 Ultra (Allwinner V40 / R40), the two
+# Gentoo servers marlena (192.168.2.1, DT "M2-Ultra") and banana-backup
+# (192.168.2.150, DT "M2 Berry"). Most likely the same hardware: one kernel and
+# one U-Boot for both, one DTB per board until that is confirmed (see
+# BANANA-V40-notes.md). Sourced by config.sh; everything here can be overridden
+# from the environment.
+BOARD_NAME="Banana Pi M2 Berry/Ultra (Allwinner V40/R40)"
+# install-kernel.sh and write-uboot.sh refuse an ssh target whose
+# /proc/device-tree/compatible lacks this.
+BOARD_DT_COMPAT="allwinner,sun8i-r40"
+
+# ---- versions ---------------------------------------------------------------
+# udev from systemd-utils 260 needs >= 5.10 (>= 5.14 recommended).
+: "${KERNEL_VERSION:=7.3.4}"
+: "${UBOOT_VERSION:=v2026.10}"
+
+# ---- toolchain --------------------------------------------------------------
+# The CHOST of both boards after the Gentoo 23.0 migration.
+: "${CROSS_COMPILE:=armv7a-unknown-linux-gnueabihf-}"
+
+# ---- U-Boot -----------------------------------------------------------------
+# Berry and Ultra defconfigs differ only in the U-Boot DT and the eMMC slot
+# (MMC_SUNXI_SLOT_EXTRA=2): same DRAM settings. Neither board has eMMC (marlena's
+# mmc2 host finds no card), so the Berry one serves both.
+UBOOT_DEFCONFIG=bananapi_m2_berry_defconfig
+UBOOT_SEEK_KIB=8
+UBOOT_OLD_RAW_ENV_KIB=
+# The boot commands are a hand-written environment in uboot.env on the FAT
+# /boot partition (mmc 0:1). write-uboot.sh checks that the new U-Boot will
+# accept that file (size and CRC against CONFIG_ENV_SIZE) before writing.
+UBOOT_ENV_FAT=1
+UBOOT_ENV_FILE=uboot.env
+
+# ---- kernel -----------------------------------------------------------------
+# Legacy uImage, started by "bootm 0x47000000 - 0x43000000" from the
+# environment; the kernel runs at 0x40008000.
+KERNEL_IMAGE=uImage
+UIMAGE_LOADADDR=0x40008000
+# Our device trees from files/bpi-m2/dts/: mainline board file + DS1307 RTC,
+# rtc0 alias, LED triggers. Built with symbols (-@) for marlena's overlay.
+BOARD_DTBS="sun8i-r40-bananapi-m2-ultra-k4be.dtb sun8i-v40-bananapi-m2-berry-k4be.dtb"
+
+# ---- installation: U-Boot environment (lib/install-ubootenv.sh) --------------
+INSTALL_SCHEME=ubootenv
+# Every release is kept in /boot/bpi-m2/<release>/ (FAT); the one booted is
+# copied to the fixed names the environment loads (uImage, <dtb>).
+BOOT_SUBDIR=bpi-m2
+# Which of our DTBs replaces the file the target's environment loads
+# (load_dt): "pattern:our-dtb", first match wins. BOOT_DTB=<our dtb> overrides.
+BOOT_DTB_MAP="*m2-ultra*:sun8i-r40-bananapi-m2-ultra-k4be.dtb *m2-berry*:sun8i-v40-bananapi-m2-berry-k4be.dtb"
+: "${BOOT_DTB:=}"
+# Overlay sources (files/bpi-m2/overlay/*.dts) compiled into overlay/ and
+# test-applied to this DTB at build time: marlena's environment applies
+# sun8i-r40-bananapi-m2-ultra-led.dtbo, and a failing "fdt apply" can leave the
+# tree in memory broken.
+OVERLAY_TEST_DTB=sun8i-r40-bananapi-m2-ultra-k4be.dtb
+
+# =============================================================================
+# Hooks called by build-kernel.sh
+# =============================================================================
+
+# board_package BOOTDIR: extra files for boot/bpi-m2/<release>/
+board_package() {
+	local boot="$1" d o
+	need_tools fdtoverlay fdtget
+	mkdir -p "$boot/overlay"
+	for d in "$BFILES"/overlay/*.dts; do
+		[ -e "$d" ] || continue
+		o="$boot/overlay/$(basename "${d%.dts}").dtbo"
+		dtc -q -@ -I dts -O dtb -o "$o" "$d"
+		fdtoverlay -i "$boot/$OVERLAY_TEST_DTB" -o "$OUT/overlay-test.dtb" "$o" ||
+			die "overlay $(basename "$o") does not apply to $OVERLAY_TEST_DTB"
+		info "overlay $(basename "$o") applies to $OVERLAY_TEST_DTB"
+	done
+	rm -f "$OUT/overlay-test.dtb"
+	# The DS1307 must be rtc0 (hwclock, RTC_HCTOSYS) in every DTB.
+	for d in $BOARD_DTBS; do
+		[ "$(fdtget -t s "$boot/$d" /aliases rtc0 2>/dev/null)" = /soc/i2c@1c2b400/rtc@68 ] ||
+			die "$d: rtc0 alias does not point to the DS1307"
+	done
+	info "rtc0 is the DS1307 in all DTBs"
+	# vdd-cpu must not start below the vendor's 1008 MHz voltage (see the dtsi).
+	local p
+	for d in $BOARD_DTBS; do
+		p="$(fdtget -t s "$boot/$d" /__symbols__ reg_dcdc2)" || die "$d: no reg_dcdc2 symbol"
+		[ "$(fdtget -t u "$boot/$d" "$p" regulator-min-microvolt)" = 1160000 ] ||
+			die "$d: vdd-cpu minimum is not 1160000 uV"
+	done
+	info "vdd-cpu minimum is 1.16 V in all DTBs"
+	ls -la "$boot/overlay"
+}

+ 211 - 0
boards/opi0.sh

@@ -0,0 +1,211 @@
+# Board type: Orange Pi Zero (original version, Allwinner H2+), the radio.
+# Sourced by config.sh; everything here can be overridden from the environment.
+BOARD_NAME="Orange Pi Zero (Allwinner H2+)"
+# install-kernel.sh and write-uboot.sh refuse an ssh target whose
+# /proc/device-tree/compatible lacks this.
+BOARD_DT_COMPAT="allwinner,sun8i-h2-plus"
+
+# ---- versions ---------------------------------------------------------------
+: "${KERNEL_VERSION:=7.3.4}"
+: "${UBOOT_VERSION:=v2026.10}"
+# Out-of-tree XR819 Wi-Fi driver (not in mainline). Pinned commit; see README.
+: "${XRADIO_REPO:=fifteenhex/xradio}"
+: "${XRADIO_COMMIT:=3ce657ae533e2213f6fda2297da1598fa11d7a03}"
+
+# ---- toolchain --------------------------------------------------------------
+: "${CROSS_COMPILE:=armv7a-hardfloat-linux-gnueabi-}"
+
+# ---- U-Boot -----------------------------------------------------------------
+UBOOT_DEFCONFIG=orangepi_zero_defconfig
+# sunxi boot ROM loads the SPL from 8 KiB on the card.
+UBOOT_SEEK_KIB=8
+# Where 2019-era sunxi U-Boot (Armbian's 2019.04) kept a raw-MMC environment:
+# CONFIG_ENV_OFFSET=0x88000, 128 KiB. write-uboot.sh mentions it if the new
+# image reaches past it. Empty: no such legacy area.
+UBOOT_OLD_RAW_ENV_KIB=544
+# Where this U-Boot keeps its environment: none (no FAT partition on the card,
+# everything boot related is in extlinux.conf).
+UBOOT_ENV_FAT=0
+
+# ---- kernel -----------------------------------------------------------------
+KERNEL_IMAGE=zImage
+# Device trees built and staged: our board DTS from files/opi0/dts/ and the
+# plain mainline one (fallback, see README "Other systems").
+BOARD_DTBS="sun8i-h2-plus-orangepi-zero-radio.dtb sun8i-h2-plus-orangepi-zero.dtb"
+# The DTB with the radio key table (checked against radio-keyboard-tca).
+BOARD_DTB="sun8i-h2-plus-orangepi-zero-radio.dtb"
+
+# ---- installation: extlinux.conf (lib/install-extlinux.sh) -------------------
+INSTALL_SCHEME=extlinux
+# Staging subdirectory: boot/opi0/<release>/ on the target.
+BOOT_SUBDIR=opi0
+BOOT_MENU_TITLE="Orange Pi Zero"
+# Device tree U-Boot hands to the kernel (built from files/opi0/dts/).
+: "${BOOT_DTB:=sun8i-h2-plus-orangepi-zero-radio.dtb}"
+# Extra overlays from boot/opi0/<release>/overlay/, space separated, no .dtbo.
+: "${BOOT_OVERLAYS:=}"
+# Kernel messages go to every console= listed, but only the LAST one becomes
+# /dev/console: init's output, systemd's emergency/rescue shell and the
+# "Give root password" prompt. The serial port goes last so it is a usable
+# emergency console when ssh is not (tty1, fbcon on the radio panel, has no
+# keyboard). install-kernel.sh moves a console=ttyS* entry to the end anyway.
+# The panel driver maps white to "pixel off" (the light background), so fbcon's
+# light-grey-on-black looks inverted there. This VT palette is the VGA one
+# inverted, with entry 0 (background) white and 7/15 (normal/bold text) black.
+# Only text VTs use it; radio-ui draws through DRM and is not affected.
+VT_PALETTE="vt.default_red=0xff,0x55,0xff,0x55,0xff,0x55,0xff,0x00,0xaa,0x00,0xaa,0x00,0xaa,0x00,0xaa,0x00"
+VT_PALETTE+=" vt.default_grn=0xff,0xff,0x55,0xaa,0xff,0xff,0x55,0x00,0xaa,0xaa,0x00,0x00,0xaa,0xaa,0x00,0x00"
+VT_PALETTE+=" vt.default_blu=0xff,0xff,0xff,0xff,0x55,0x55,0x55,0x00,0xaa,0xaa,0xaa,0xaa,0x00,0x00,0x00,0x00"
+: "${KERNEL_CONSOLE:=console=tty1 fbcon=font:6x8 $VT_PALETTE console=ttyS0,115200}"
+# usb-storage quirks carried over from the Armbian setup (armbianEnv.txt).
+: "${KERNEL_CMDLINE_EXTRA:=usb-storage.quirks=0x2537:0x1066:u,0x2537:0x1068:u}"
+
+# ---- radio sources ------------------------------------------------------------
+PANEL_DIR="${PANEL_DIR:-/home/k4be/git/radio/s1d13700-tca}"   # s1d13700-tca: panel driver, overlay
+KEYBOARD_DIR="${KEYBOARD_DIR:-/home/k4be/git/radio/radio-keyboard-tca}"   # radio-keyboard-tca: key overlay
+
+# =============================================================================
+# Hooks called by build-kernel.sh (kmake, fetch etc. come from there and
+# config.sh). XSRC is set when the hooks run, after config.sh set SRC.
+# =============================================================================
+
+board_prepare_source() {
+	XSRC="$SRC/xradio"
+	if [ ! -d "$XSRC" ]; then
+		local xt="$DL/xradio-$XRADIO_COMMIT.tar.gz"
+		fetch "$xt" "https://github.com/$XRADIO_REPO/archive/$XRADIO_COMMIT.tar.gz"
+		mkdir -p "$XSRC"
+		tar xzf "$xt" -C "$XSRC" --strip-components=1
+	fi
+	sync_radio_driver
+}
+
+# Put the radio panel driver into the kernel tree as a DRM tiny driver, so it
+# can be built in (needed for the boot console on the panel). The sources are
+# copied from the s1d13700-tca repository ($PANEL_DIR) on every run; only
+# Kconfig/Makefile are ours. The tree is shared with the other board types;
+# for them the driver is just one more option that is off.
+sync_radio_driver() {
+	local rd="$PANEL_DIR/driver" td="$KSRC/drivers/gpu/drm/tiny/s1d13700-tca"
+	[ -f "$rd/s1d13700_drm.c" ] || die "s1d13700-tca driver not found in $rd"
+	mkdir -p "$td"
+	# cp -u keeps timestamps sane, so unchanged sources are not rebuilt
+	cp -u "$rd"/s1d13700_drm.c "$rd"/s1d13700_core.c "$rd"/s1d13700_core.h "$td/"
+	cat > "$td/Kconfig.new" <<-'EOF'
+	# Generated by build-kernel.sh (OPi0); sources from the s1d13700-tca repository.
+	config DRM_S1D13700_TCA
+		tristate "S1D13700 panel behind a TCA9539 I2C expander (radio)"
+		depends on DRM && I2C
+		select DRM_CLIENT_SELECTION
+		select DRM_KMS_HELPER
+		select DRM_GEM_SHMEM_HELPER
+		select BACKLIGHT_CLASS_DEVICE
+		help
+		    Epson S1D13700 graphic LCD controller driven through a TCA9539
+		    I2C GPIO expander, as on the radio front panel.
+	EOF
+	cat > "$td/Makefile.new" <<-'EOF'
+	# Generated by build-kernel.sh (OPi0); sources from the s1d13700-tca repository.
+	obj-$(CONFIG_DRM_S1D13700_TCA) += s1d13700-tca.o
+	s1d13700-tca-y := s1d13700_drm.o s1d13700_core.o
+	# API compatibility for the DRM part only (see s1d13700_compat.h).
+	CFLAGS_s1d13700_drm.o += -include $(src)/s1d13700_compat.h
+	EOF
+	# Kernel 7.3 renamed struct drm_atomic_state to struct drm_atomic_commit;
+	# the driver uses the old name, only as the type of the atomic hooks'
+	# argument. The DRM headers are included before the rename is defined,
+	# so it applies to the driver's own code only, never inside a kernel
+	# header. s1d13700_compat_check() stops the build if the new struct is
+	# not a complete type with the expected members (rename reverted or
+	# done differently): adjust the version check then, rather than build
+	# against the wrong type. Below 7.3 the header does nothing.
+	cat > "$td/s1d13700_compat.h.new" <<-'EOF'
+	/* Generated by build-kernel.sh (OPi0). Forced in with -include. */
+	#ifndef S1D13700_COMPAT_H
+	#define S1D13700_COMPAT_H
+
+	#include <linux/version.h>
+
+	#if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 3, 0) && !defined(drm_atomic_state)
+	#include <drm/drm_atomic.h>
+	#include <drm/drm_atomic_helper.h>
+	#include <drm/drm_crtc.h>
+	#include <drm/drm_gem_atomic_helper.h>
+	#include <drm/drm_modeset_helper_vtables.h>
+	#include <drm/drm_plane.h>
+
+	#define drm_atomic_state drm_atomic_commit
+
+	/* Fails if the headers above still define the old struct. */
+	struct drm_atomic_commit;
+	static inline void s1d13700_compat_check(struct drm_atomic_commit *c)
+	{
+		(void)sizeof(c->dev);
+	}
+	#endif
+
+	#endif /* S1D13700_COMPAT_H */
+	EOF
+	local f
+	for f in Kconfig Makefile s1d13700_compat.h; do
+		cmp -s "$td/$f.new" "$td/$f" && rm "$td/$f.new" || mv "$td/$f.new" "$td/$f"
+	done
+	local tk="$KSRC/drivers/gpu/drm/tiny/Kconfig" tm="$KSRC/drivers/gpu/drm/tiny/Makefile"
+	grep -q 's1d13700-tca/Kconfig' "$tk" ||
+		printf '\nsource "drivers/gpu/drm/tiny/s1d13700-tca/Kconfig"\n' >> "$tk"
+	grep -q 's1d13700-tca/' "$tm" ||
+		echo 'obj-$(CONFIG_DRM_S1D13700_TCA)	+= s1d13700-tca/' >> "$tm"
+}
+
+# Out-of-tree modules, built after the kernel.
+board_build_extmod() {
+	XSRC="$SRC/xradio"
+	# xradio: built out of tree in its own (extracted) source directory.
+	info "building xradio (XR819 Wi-Fi)"
+	kmake M="$XSRC" modules
+}
+
+board_install_extmod() {
+	XSRC="$SRC/xradio"
+	kmake INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 M="$XSRC" modules_install
+}
+
+# keys_of DTB NODE -> one "label pin flags keycode" line per key, sorted
+keys_of() {
+	local n
+	for n in $(fdtget -l "$1" "$2"); do
+		printf '%s %s %s\n' "$(fdtget -t s "$1" "$2/$n" label)" \
+			"$(fdtget -t u "$1" "$2/$n" gpios | cut -d' ' -f2,3)" \
+			"$(fdtget -t u "$1" "$2/$n" linux,code)"
+	done | sort
+}
+
+# The key table exists twice: in files/opi0/dts (board DTB) and in
+# radio-keyboard-tca's dts/radio-keys.dts, which deliberately avoids #include
+# so it also works with armbian-add-overlay. Compare the compiled tables
+# instead of sharing a .dtsi: label, U2 pin, flags and key code must all match.
+check_key_tables() {
+	local boot="$1" ov="$1/overlay/radio-keys.dtbo"
+	[ -f "$ov" ] || return 0
+	if ! diff -u <(keys_of "$boot/$BOARD_DTB" /radio-keys) \
+		<(keys_of "$ov" /fragment@1/__overlay__/radio-keys) >&2; then
+		die "key tables differ: files/opi0/dts/${BOARD_DTB%.dtb}.dts vs $KEYBOARD_DIR/dts/radio-keys.dts (-board +overlay)"
+	fi
+	info "key tables match (board DTB and radio-keys overlay)"
+}
+
+# board_package BOOTDIR: extra files for boot/opi0/<release>/
+board_package() {
+	local boot="$1" d
+	need_tools fdtget
+	# Panel and key overlays (dts/*.dts in s1d13700-tca and
+	# radio-keyboard-tca), for extlinux fdtoverlays.
+	mkdir -p "$boot/overlay"
+	for d in "$PANEL_DIR"/dts/*.dts "$KEYBOARD_DIR"/dts/*.dts; do
+		[ -e "$d" ] || continue
+		dtc -q -@ -I dts -O dtb -o "$boot/overlay/$(basename "${d%.dts}").dtbo" "$d"
+	done
+	check_key_tables "$boot"
+	ls -la "$boot/overlay"
+	find "$STAGE/lib/modules" -path '*/updates/*' -name '*.ko*'
+}

+ 54 - 144
build-kernel.sh

@@ -1,13 +1,14 @@
 #!/bin/bash
-# Download, configure and build the mainline kernel for the Orange Pi Zero,
-# plus the out-of-tree modules (xradio Wi-Fi, s1d13700-tca radio panel) and
-# the radio device tree overlays (s1d13700-tca, radio-keyboard-tca). Result: out/opi0-kernel-<release>.tar.gz
-# with boot/opi0/<release>/ and lib/modules/<release>/, ready for
+# Download, configure and build the mainline kernel for the selected board type
+# (./select-board.sh), plus the board's device trees, overlays and out-of-tree
+# modules (boards/<board>.sh). Result: out/<board>/<board>-kernel-<release>.tar.gz
+# with boot/<subdir>/<release>/ and lib/modules/<release>/, ready for
 # install-kernel.sh.
 #
 # Usage: ./build-kernel.sh [all|config|menuconfig|build|modules|package|clean]
 #   all         (default) config if needed, build, modules, package
-#   config      regenerate .config from sunxi_defconfig + files/kernel.config
+#   config      regenerate .config from sunxi_defconfig + files/kernel-common.config
+#               + files/<board>/kernel.config
 #   menuconfig  edit the current .config (kept until "config" is run again)
 #   build       kernel, in-tree modules and DTBs only
 #   modules     only the out-of-tree modules (needs a built kernel)
@@ -18,14 +19,14 @@ set -euo pipefail
 
 KBUILD="$OUT/kbuild"
 STAGE="$KOUT/stage"
-BOARD_DTS="$FILES/dts/sun8i-h2-plus-orangepi-zero-radio.dts"
-BOARD_DTB="sun8i-h2-plus-orangepi-zero-radio.dtb"
 DTSDIR="arch/arm/boot/dts/allwinner"
+FRAGMENTS=("$FILES/kernel-common.config" "$BFILES/kernel.config")
 
 kmake() { make -C "$KSRC" O="$KBUILD" -j"$JOBS" "$@"; }
 
 prepare_source() {
 	need_tools curl tar xz sha256sum make "${CROSS_COMPILE}gcc" bison flex bc perl dtc
+	[ "$KERNEL_IMAGE" != uImage ] || need_tools mkimage
 	local tarball="linux-$KERNEL_VERSION.tar.xz"
 	local major="${KERNEL_VERSION%%.*}"
 	local base="https://cdn.kernel.org/pub/linux/kernel/v$major.x"
@@ -39,178 +40,87 @@ prepare_source() {
 		mkdir -p "$SRC"
 		tar xJf "$DL/$tarball" -C "$SRC"
 	fi
-	if [ ! -d "$XSRC" ]; then
-		local xt="$DL/xradio-$XRADIO_COMMIT.tar.gz"
-		fetch "$xt" "https://github.com/$XRADIO_REPO/archive/$XRADIO_COMMIT.tar.gz"
-		mkdir -p "$XSRC"
-		tar xzf "$xt" -C "$XSRC" --strip-components=1
-	fi
-	# The board DTS lives in files/; link it next to the mainline one it includes.
-	ln -sf "$BOARD_DTS" "$KSRC/$DTSDIR/$(basename "$BOARD_DTS")"
-	sync_radio_driver
-}
-
-# Put the radio panel driver into the kernel tree as a DRM tiny driver, so it
-# can be built in (needed for the boot console on the panel). The sources are
-# copied from the s1d13700-tca repository ($PANEL_DIR) on every run; only
-# Kconfig/Makefile are ours.
-sync_radio_driver() {
-	local rd="$PANEL_DIR/driver" td="$KSRC/drivers/gpu/drm/tiny/s1d13700-tca"
-	[ -f "$rd/s1d13700_drm.c" ] || die "s1d13700-tca driver not found in $rd"
-	mkdir -p "$td"
-	# cp -u keeps timestamps sane, so unchanged sources are not rebuilt
-	cp -u "$rd"/s1d13700_drm.c "$rd"/s1d13700_core.c "$rd"/s1d13700_core.h "$td/"
-	cat > "$td/Kconfig.new" <<-'EOF'
-	# Generated by build-kernel.sh (OPi0); sources from the s1d13700-tca repository.
-	config DRM_S1D13700_TCA
-		tristate "S1D13700 panel behind a TCA9539 I2C expander (radio)"
-		depends on DRM && I2C
-		select DRM_CLIENT_SELECTION
-		select DRM_KMS_HELPER
-		select DRM_GEM_SHMEM_HELPER
-		select BACKLIGHT_CLASS_DEVICE
-		help
-		    Epson S1D13700 graphic LCD controller driven through a TCA9539
-		    I2C GPIO expander, as on the radio front panel.
-	EOF
-	cat > "$td/Makefile.new" <<-'EOF'
-	# Generated by build-kernel.sh (OPi0); sources from the s1d13700-tca repository.
-	obj-$(CONFIG_DRM_S1D13700_TCA) += s1d13700-tca.o
-	s1d13700-tca-y := s1d13700_drm.o s1d13700_core.o
-	# API compatibility for the DRM part only (see s1d13700_compat.h).
-	CFLAGS_s1d13700_drm.o += -include $(src)/s1d13700_compat.h
-	EOF
-	# Kernel 7.3 renamed struct drm_atomic_state to struct drm_atomic_commit;
-	# the driver uses the old name, only as the type of the atomic hooks'
-	# argument. The DRM headers are included before the rename is defined,
-	# so it applies to the driver's own code only, never inside a kernel
-	# header. s1d13700_compat_check() stops the build if the new struct is
-	# not a complete type with the expected members (rename reverted or
-	# done differently): adjust the version check then, rather than build
-	# against the wrong type. Below 7.3 the header does nothing.
-	cat > "$td/s1d13700_compat.h.new" <<-'EOF'
-	/* Generated by build-kernel.sh (OPi0). Forced in with -include. */
-	#ifndef S1D13700_COMPAT_H
-	#define S1D13700_COMPAT_H
-
-	#include <linux/version.h>
-
-	#if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 3, 0) && !defined(drm_atomic_state)
-	#include <drm/drm_atomic.h>
-	#include <drm/drm_atomic_helper.h>
-	#include <drm/drm_crtc.h>
-	#include <drm/drm_gem_atomic_helper.h>
-	#include <drm/drm_modeset_helper_vtables.h>
-	#include <drm/drm_plane.h>
-
-	#define drm_atomic_state drm_atomic_commit
-
-	/* Fails if the headers above still define the old struct. */
-	struct drm_atomic_commit;
-	static inline void s1d13700_compat_check(struct drm_atomic_commit *c)
-	{
-		(void)sizeof(c->dev);
-	}
-	#endif
-
-	#endif /* S1D13700_COMPAT_H */
-	EOF
-	local f
-	for f in Kconfig Makefile s1d13700_compat.h; do
-		cmp -s "$td/$f.new" "$td/$f" && rm "$td/$f.new" || mv "$td/$f.new" "$td/$f"
+	# The board DTS files live in files/<board>/dts/; link them next to the
+	# mainline ones they include. The source tree is shared by all board
+	# types, so the links of the other boards are there too (harmless).
+	local d
+	for d in "$BFILES"/dts/*.dts "$BFILES"/dts/*.dtsi; do
+		[ -e "$d" ] || continue
+		ln -sf "$d" "$KSRC/$DTSDIR/$(basename "$d")"
 	done
-	local tk="$KSRC/drivers/gpu/drm/tiny/Kconfig" tm="$KSRC/drivers/gpu/drm/tiny/Makefile"
-	grep -q 's1d13700-tca/Kconfig' "$tk" ||
-		printf '\nsource "drivers/gpu/drm/tiny/s1d13700-tca/Kconfig"\n' >> "$tk"
-	grep -q 's1d13700-tca/' "$tm" ||
-		echo 'obj-$(CONFIG_DRM_S1D13700_TCA)	+= s1d13700-tca/' >> "$tm"
+	if declare -F board_prepare_source >/dev/null; then board_prepare_source; fi
 }
 
 do_config() {
 	mkdir -p "$KBUILD"
-	info "configuring: sunxi_defconfig + files/kernel.config"
+	info "configuring: sunxi_defconfig + ${FRAGMENTS[*]#"$TOP"/}"
 	kmake sunxi_defconfig
 	"$KSRC/scripts/kconfig/merge_config.sh" -m -O "$KBUILD" \
-		"$KBUILD/.config" "$FILES/kernel.config" >/dev/null
+		"$KBUILD/.config" "${FRAGMENTS[@]}" >/dev/null
 	kmake olddefconfig
-	check_fragment "$FILES/kernel.config" "$KBUILD/.config"
+	check_fragment "$KBUILD/.config" "${FRAGMENTS[@]}"
+	local mods
+	mods="$(grep -c '=m$' "$KBUILD/.config" || true)"
+	info "$mods options are modules (=m): grep '=m\$' $KBUILD/.config"
 }
 
 do_build() {
 	[ -f "$KBUILD/.config" ] || do_config
-	info "building kernel $KERNEL_VERSION"
-	kmake zImage modules dtbs
-	kmake DTC_FLAGS=-@ "allwinner/$BOARD_DTB"
+	info "building kernel $KERNEL_VERSION ($KERNEL_IMAGE)"
+	if [ "$KERNEL_IMAGE" = uImage ]; then
+		kmake LOADADDR="$UIMAGE_LOADADDR" uImage modules
+		# The environment loads the uImage to 0x47000000 and U-Boot
+		# relocates the DTB below 0x4a000000 (bootm_size=0xa000000):
+		# keep the image well inside those 48 MiB.
+		local size; size=$(stat -c %s "$KBUILD/arch/arm/boot/uImage")
+		[ "$size" -lt $(( 32 * 1024 * 1024 )) ] ||
+			die "uImage is $size bytes; over 32 MiB it may collide with the relocated DTB"
+	else
+		kmake "$KERNEL_IMAGE" modules
+	fi
+	# Only this board's device trees, with symbols so overlays can be applied.
+	local dtb targets=()
+	for dtb in $BOARD_DTBS; do targets+=("allwinner/$dtb"); done
+	kmake DTC_FLAGS=-@ "${targets[@]}"
 }
 
 krelease() { cat "$KBUILD/include/config/kernel.release"; }
 
 do_modules() {
 	[ -f "$KBUILD/vmlinux" ] || die "kernel not built yet"
-	# xradio: built out of tree in its own (extracted) source directory.
-	info "building xradio (XR819 Wi-Fi)"
-	kmake M="$XSRC" modules
-}
-
-# keys_of DTB NODE -> one "label pin flags keycode" line per key, sorted
-keys_of() {
-	local n
-	for n in $(fdtget -l "$1" "$2"); do
-		printf '%s %s %s\n' "$(fdtget -t s "$1" "$2/$n" label)" \
-			"$(fdtget -t u "$1" "$2/$n" gpios | cut -d' ' -f2,3)" \
-			"$(fdtget -t u "$1" "$2/$n" linux,code)"
-	done | sort
-}
-
-# The key table exists twice: in files/dts (board DTB) and in radio-keyboard-tca's
-# dts/radio-keys.dts, which deliberately avoids #include so it
-# also works with armbian-add-overlay. Compare the compiled tables instead
-# of sharing a .dtsi: label, U2 pin, flags and key code must all match.
-check_key_tables() {
-	local boot="$1" ov="$1/overlay/radio-keys.dtbo"
-	[ -f "$ov" ] || return 0
-	if ! diff -u <(keys_of "$boot/$BOARD_DTB" /radio-keys) \
-		<(keys_of "$ov" /fragment@1/__overlay__/radio-keys) >&2; then
-		die "key tables differ: files/dts/$(basename "$BOARD_DTS") vs $KEYBOARD_DIR/dts/radio-keys.dts (-board +overlay)"
+	if declare -F board_build_extmod >/dev/null; then
+		board_build_extmod
+	else
+		info "no out-of-tree modules for this board"
 	fi
-	info "key tables match (board DTB and radio-keys overlay)"
 }
 
 do_package() {
-	need_tools depmod dtc fdtget
+	need_tools depmod dtc
 	local rel; rel="$(krelease)"
-	local boot="$STAGE/boot/opi0/$rel"
+	local boot="$STAGE/boot/$BOOT_SUBDIR/$rel" dtb
 	info "staging $rel"
 	rm -rf "$STAGE"
-	mkdir -p "$boot/overlay"
+	mkdir -p "$boot"
 	kmake INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 modules_install
-	kmake INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 M="$XSRC" modules_install
+	if declare -F board_install_extmod >/dev/null; then board_install_extmod; fi
 	# The build/source links point into this PC's tree; useless on the target.
 	rm -f "$STAGE/lib/modules/$rel/build" "$STAGE/lib/modules/$rel/source"
 	depmod -b "$STAGE" "$rel"
 
-	cp "$KBUILD/arch/arm/boot/zImage" "$boot/zImage"
-	cp "$KBUILD/$DTSDIR/$BOARD_DTB" "$boot/"
-	cp "$KBUILD/$DTSDIR/$KERNEL_DTB" "$boot/"
+	cp "$KBUILD/arch/arm/boot/$KERNEL_IMAGE" "$boot/$KERNEL_IMAGE"
+	for dtb in $BOARD_DTBS; do cp "$KBUILD/$DTSDIR/$dtb" "$boot/"; done
 	cp "$KBUILD/.config" "$boot/config"
 	cp "$KBUILD/System.map" "$boot/System.map"
 
-	# Panel and key overlays (dts/*.dts in s1d13700-tca and
-	# radio-keyboard-tca), for extlinux fdtoverlays.
-	local d
-	for d in "$PANEL_DIR"/dts/*.dts "$KEYBOARD_DIR"/dts/*.dts; do
-		[ -e "$d" ] || continue
-		dtc -q -@ -I dts -O dtb -o "$boot/overlay/$(basename "${d%.dts}").dtbo" "$d"
-	done
-
-	check_key_tables "$boot"
+	if declare -F board_package >/dev/null; then board_package "$boot"; fi
 
-	local tarball="$OUT/opi0-kernel-$rel.tar.gz"
+	local tarball="$OUT/$BOARD-kernel-$rel.tar.gz"
 	tar czf "$tarball" --owner=0 --group=0 -C "$STAGE" boot lib
 	echo "$rel" > "$OUT/kernel-release"
-	info "done: $tarball"
-	ls -la "$boot" "$boot/overlay"
-	find "$STAGE/lib/modules/$rel/updates" -name '*.ko*'
+	info "done ($BOARD_NAME): $tarball"
+	ls -la "$boot"
+	info "modules: $(find "$STAGE/lib/modules/$rel" -name '*.ko*' | wc -l)"
 }
 
 cmd="${1:-all}"
@@ -221,6 +131,6 @@ menuconfig) prepare_source; [ -f "$KBUILD/.config" ] || do_config; kmake menucon
 build)      prepare_source; do_build ;;
 modules)    do_modules ;;
 package)    do_package ;;
-clean)      rm -rf "$KBUILD" "$KOUT" "$OUT/extmod" ;;
+clean)      rm -rf "$KBUILD" "$KOUT" ;;
 *)          die "unknown command: $cmd" ;;
 esac

+ 11 - 10
build-uboot.sh

@@ -1,21 +1,22 @@
 #!/bin/bash
-# Download, configure and build mainline U-Boot for the Orange Pi Zero.
-# Result: out/u-boot/u-boot-sunxi-with-spl.bin (SPL + U-Boot proper; the H2+
-# is 32-bit, so no TF-A/crust is needed). Write it with write-uboot.sh.
+# Download, configure and build mainline U-Boot for the selected board type
+# (./select-board.sh). Result: out/<board>/u-boot/u-boot-sunxi-with-spl.bin
+# (SPL + U-Boot proper; the H2+ and R40 are 32-bit, so no TF-A/crust is
+# needed). Write it with write-uboot.sh.
 #
 # Usage: ./build-uboot.sh [all|config|menuconfig|build|clean]
 #   all         (default) configure if needed, then build
-#   config      regenerate .config from orangepi_zero_defconfig
-#               (+ files/u-boot.config if present; like build-kernel.sh, fails
+#   config      regenerate .config from the board's defconfig (boards/<board>.sh)
+#               (+ files/<board>/u-boot.config if present; like build-kernel.sh, fails
 #               if an option of the fragment did not survive)
 #   menuconfig  edit the current .config (kept until "config" is run again)
 #   build       build only (configures first if there is no .config)
-#   clean       remove the U-Boot build directory and out/u-boot/
+#   clean       remove the U-Boot build directory and out/<board>/u-boot/
 set -euo pipefail
 . "$(dirname "$0")/config.sh"
 
 UBUILD="$OUT/ubuild"
-UFRAG="$FILES/u-boot.config"
+UFRAG="$BFILES/u-boot.config"
 
 umake() { make -C "$USRC" O="$UBUILD" -j"$JOBS" "$@"; }
 
@@ -43,11 +44,11 @@ do_config() {
 	info "configuring: $UBOOT_DEFCONFIG"
 	umake "$UBOOT_DEFCONFIG"
 	if [ -f "$UFRAG" ]; then
-		info "merging files/u-boot.config"
+		info "merging ${UFRAG#"$TOP"/}"
 		"$USRC/scripts/kconfig/merge_config.sh" -m -O "$UBUILD" \
 			"$UBUILD/.config" "$UFRAG" >/dev/null
 		umake olddefconfig
-		check_fragment "$UFRAG" "$UBUILD/.config"
+		check_fragment "$UBUILD/.config" "$UFRAG"
 	fi
 }
 
@@ -57,7 +58,7 @@ do_build() {
 	umake
 	mkdir -p "$UOUT"
 	cp "$UBUILD/u-boot-sunxi-with-spl.bin" "$UOUT/"
-	info "done: $UOUT/u-boot-sunxi-with-spl.bin"
+	info "done ($BOARD_NAME): $UOUT/u-boot-sunxi-with-spl.bin"
 	ls -la "$UOUT/u-boot-sunxi-with-spl.bin"
 }
 

+ 83 - 67
config.sh

@@ -1,63 +1,68 @@
-# Shared settings for the Orange Pi Zero (H2+, original version) build.
-# Sourced by the other scripts; override any of these from the environment.
+# Shared settings for all scripts. Sourced by the other scripts; override any
+# of these from the environment.
+#
+# The board type is picked with ./select-board.sh and kept in .board; BOARD=<id>
+# in the environment overrides it for one command. Board specifics (versions,
+# toolchain, defconfigs, device trees, install method, build hooks) are in
+# boards/<id>.sh, config fragments and device trees in files/<id>/.
 
 TOP="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BOARDS_DIR="$TOP/boards"
+BOARD_SELECTION="$TOP/.board"
 
-# ---- versions ---------------------------------------------------------------
-: "${KERNEL_VERSION:=7.3.4}"
-: "${UBOOT_VERSION:=v2026.10}"
-# Out-of-tree XR819 Wi-Fi driver (not in mainline). Pinned commit; see README.
-: "${XRADIO_REPO:=fifteenhex/xradio}"
-: "${XRADIO_COMMIT:=3ce657ae533e2213f6fda2297da1598fa11d7a03}"
+die()  { echo "ERROR: $*" >&2; exit 1; }
+info() { echo ">>> $*"; }
 
-# ---- toolchain --------------------------------------------------------------
-: "${CROSS_COMPILE:=armv7a-hardfloat-linux-gnueabi-}"
-: "${JOBS:=$(nproc)}"
-export ARCH=arm CROSS_COMPILE
+# list_boards -> "id<TAB>name" per supported board
+list_boards() {
+	local f
+	for f in "$BOARDS_DIR"/*.sh; do
+		[ -e "$f" ] || continue
+		printf '%s\t%s\n' "$(basename "$f" .sh)" \
+			"$(sed -n 's/^BOARD_NAME="\(.*\)"$/\1/p' "$f" | head -1)"
+	done
+}
 
-# ---- board ------------------------------------------------------------------
-UBOOT_DEFCONFIG=orangepi_zero_defconfig
-KERNEL_DTB=sun8i-h2-plus-orangepi-zero.dtb
-# sunxi boot ROM loads the SPL from 8 KiB on the card.
-UBOOT_SEEK_KIB=8
+# ---- board selection --------------------------------------------------------
+# select-board.sh sets CONFIG_NO_BOARD=1: it must work without a selection.
+if [ "${CONFIG_NO_BOARD:-0}" != 1 ]; then
+	if [ -n "${BOARD:-}" ]; then
+		BOARD_FROM="BOARD from the environment"
+	else
+		BOARD="$(cat "$BOARD_SELECTION" 2>/dev/null || true)"
+		BOARD_FROM="selected with select-board.sh"
+	fi
+	[ -n "$BOARD" ] || die "no board type selected; run ./select-board.sh first"
+	[ -f "$BOARDS_DIR/$BOARD.sh" ] ||
+		die "unknown board type '$BOARD' (known: $(list_boards | cut -f1 | tr '\n' ' '))"
+	. "$BOARDS_DIR/$BOARD.sh"
 
-# ---- extlinux.conf (install-kernel.sh) --------------------------------------
-# Device tree U-Boot hands to the kernel (built from files/dts/).
-: "${BOOT_DTB:=sun8i-h2-plus-orangepi-zero-radio.dtb}"
-# Extra overlays from boot/opi0/<release>/overlay/, space separated, no .dtbo.
-: "${BOOT_OVERLAYS:=}"
-# Kernel messages go to every console= listed, but only the LAST one becomes
-# /dev/console: init's output, systemd's emergency/rescue shell and the
-# "Give root password" prompt. The serial port goes last so it is a usable
-# emergency console when ssh is not (tty1, fbcon on the radio panel, has no
-# keyboard). install-kernel.sh moves a console=ttyS* entry to the end anyway.
-# The panel driver maps white to "pixel off" (the light background), so fbcon's
-# light-grey-on-black looks inverted there. This VT palette is the VGA one
-# inverted, with entry 0 (background) white and 7/15 (normal/bold text) black.
-# Only text VTs use it; radio-ui draws through DRM and is not affected.
-VT_PALETTE="vt.default_red=0xff,0x55,0xff,0x55,0xff,0x55,0xff,0x00,0xaa,0x00,0xaa,0x00,0xaa,0x00,0xaa,0x00"
-VT_PALETTE+=" vt.default_grn=0xff,0xff,0x55,0xaa,0xff,0xff,0x55,0x00,0xaa,0xaa,0x00,0x00,0xaa,0xaa,0x00,0x00"
-VT_PALETTE+=" vt.default_blu=0xff,0xff,0xff,0xff,0x55,0x55,0x55,0x00,0xaa,0xaa,0xaa,0xaa,0x00,0x00,0x00,0x00"
-: "${KERNEL_CONSOLE:=console=tty1 fbcon=font:6x8 $VT_PALETTE console=ttyS0,115200}"
-# usb-storage quirks carried over from the Armbian setup (armbianEnv.txt).
-: "${KERNEL_CMDLINE_EXTRA:=usb-storage.quirks=0x2537:0x1066:u,0x2537:0x1068:u}"
+	# ---- defaults the board file did not set --------------------------
+	: "${KERNEL_VERSION:=7.3.4}"
+	: "${UBOOT_VERSION:=v2026.10}"
+	: "${JOBS:=$(nproc)}"
+	export ARCH=arm CROSS_COMPILE
 
-# ---- directories ------------------------------------------------------------
-DL="$TOP/dl"            # downloaded tarballs
-SRC="$TOP/src"          # extracted sources
-OUT="$TOP/out"          # build results
-FILES="$TOP/files"      # config fragments, overlays, boot config templates
-PANEL_DIR="${PANEL_DIR:-/home/k4be/git/radio/s1d13700-tca}"   # s1d13700-tca: panel driver, overlay
-KEYBOARD_DIR="${KEYBOARD_DIR:-/home/k4be/git/radio/radio-keyboard-tca}"   # radio-keyboard-tca: key overlay
+	# ---- directories --------------------------------------------------
+	DL="$TOP/dl"                 # downloaded tarballs (shared)
+	SRC="$TOP/src"               # extracted sources (shared, built out of tree)
+	OUT="$TOP/out/$BOARD"        # build results of this board type
+	BACKUP_DIR="$TOP/out/backup" # bootloader areas saved by write-uboot.sh (all boards)
+	FILES="$TOP/files"           # config fragments shared by all boards
+	BFILES="$FILES/$BOARD"       # this board's fragments, device trees, overlays
 
-KSRC="$SRC/linux-$KERNEL_VERSION"
-USRC="$SRC/u-boot-${UBOOT_VERSION#v}"
-XSRC="$SRC/xradio"
-KOUT="$OUT/kernel"      # staging: boot/ and lib/modules/
-UOUT="$OUT/u-boot"
+	KSRC="$SRC/linux-$KERNEL_VERSION"
+	USRC="$SRC/u-boot-${UBOOT_VERSION#v}"
+	KOUT="$OUT/kernel"           # staging: boot/ and lib/modules/
+	UOUT="$OUT/u-boot"
 
-die()  { echo "ERROR: $*" >&2; exit 1; }
-info() { echo ">>> $*"; }
+	# Every command states which board type it works for.
+	if [ -t 2 ]; then
+		printf '\033[1;36m=== board: %s [%s] (%s)\033[0m\n' "$BOARD_NAME" "$BOARD" "$BOARD_FROM" >&2
+	else
+		printf '=== board: %s [%s] (%s)\n' "$BOARD_NAME" "$BOARD" "$BOARD_FROM" >&2
+	fi
+fi
 
 # Fail early if a required program is missing; don't install anything.
 need_tools() {
@@ -66,29 +71,40 @@ need_tools() {
 	[ ${#missing[@]} -eq 0 ] || die "missing tools: ${missing[*]} (install them and re-run)"
 }
 
-# check_fragment FRAGMENT DOTCONFIG
-# Every option in a config fragment must have survived olddefconfig; a renamed
-# symbol or a missing dependency silently drops options otherwise.
+# check_fragment DOTCONFIG FRAGMENT...
+# Every option in the config fragments must have survived olddefconfig; a
+# renamed symbol or a missing dependency silently drops options otherwise.
+# Fragments are read in order and a later one overrides an earlier one, as
+# with merge_config.sh.
 check_fragment() {
-	local frag="$1" dotconfig="$2" bad=0 line sym want have
-	while IFS= read -r line; do
-		case "$line" in
-		CONFIG_*=*) sym="${line%%=*}"; want="${line#*=}" ;;
-		"# CONFIG_"*" is not set") sym="${line#\# }"; sym="${sym%% *}"; want=n ;;
-		*) continue ;;
-		esac
+	local dotconfig="$1"; shift
+	local -A want=() from=()
+	local -a order=()
+	local frag line sym val bad=0 have
+	for frag in "$@"; do
+		while IFS= read -r line; do
+			case "$line" in
+			CONFIG_*=*) sym="${line%%=*}"; val="${line#*=}" ;;
+			"# CONFIG_"*" is not set") sym="${line#\# }"; sym="${sym%% *}"; val=n ;;
+			*) continue ;;
+			esac
+			[ -n "${want[$sym]+x}" ] || order+=("$sym")
+			want[$sym]="$val"; from[$sym]="${frag#"$TOP"/}"
+		done < "$frag"
+	done
+	for sym in "${order[@]}"; do
 		have="$(grep -E "^$sym=" "$dotconfig" | cut -d= -f2- || true)"
 		[ -n "$have" ] || have=n
-		if [ "$have" != "$want" ]; then
-			echo "  config: $sym wanted $want, got $have" >&2
+		if [ "$have" != "${want[$sym]}" ]; then
+			echo "  config: $sym wanted ${want[$sym]} (${from[$sym]}), got $have" >&2
 			bad=1
 		fi
-	done < "$frag"
-	[ $bad -eq 0 ] || die ".config does not match ${frag#"$TOP"/} (see above)"
-	info "config check passed (${frag#"$TOP"/})"
+	done
+	[ $bad -eq 0 ] || die ".config does not match the fragments (see above)"
+	info "config check passed ($(for frag in "$@"; do printf '%s ' "${frag#"$TOP"/}"; done))"
 }
 
-# fetch URL DEST [fallback URL...]
+# fetch DEST URL [fallback URL...]
 fetch() {
 	local dest="$1"; shift
 	[ -s "$dest" ] && return 0

+ 63 - 0
files/bpi-m2/dts/bananapi-m2-k4be.dtsi

@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+/*
+ * Local additions shared by both Banana Pi M2 boards (marlena, banana-backup),
+ * included after the mainline board file by the two board DTS files here.
+ */
+
+/ {
+	aliases {
+		/*
+		 * The battery-backed DS1307 must be rtc0: RTC_HCTOSYS and
+		 * RTC_SYSTOHC use rtc0, and so do hwclock and chrony's rtcsync.
+		 * Without the aliases the SoC RTC (needed anyway, it provides the
+		 * 32 kHz clock) may register first.
+		 */
+		rtc0 = &ds1307;
+		rtc1 = &rtc;
+		/*
+		 * Linux numbers MMC hosts in probe order without aliases. The
+		 * environment boots root=/dev/mmcblk0p2, so the SD slot must
+		 * stay mmc0 whatever probes first (mmc1 is the SDIO Wi-Fi).
+		 */
+		mmc0 = &mmc0;
+		mmc1 = &mmc1;
+	};
+
+	leds {
+		/*
+		 * Labels for marlena's U-Boot overlay
+		 * (sun8i-r40-bananapi-m2-ultra-led.dtbo targets &pwr_led and
+		 * &user_led_green), and the same triggers set here, so the
+		 * overlay is no longer needed. The Berry's green LED node is
+		 * "user-led", the Ultra's "user-led-green", see the board files.
+		 */
+		pwr_led: pwr-led {
+			linux,default-trigger = "heartbeat";
+		};
+	};
+};
+
+/*
+ * CPU core voltage floor. The old 4.18/5.4 kernels had no cpufreq, so the CPU
+ * ran at U-Boot's 1008 MHz with U-Boot's CONFIG_AXP_DCDC2_VOLT=1100 mV, below
+ * the vendor's 1160 mV for 1008 MHz; both boards locked up silently under
+ * sustained multi-core load (2026-11-18/19). The mainline board files include
+ * sun8i-r40-cpu-opp.dtsi (720-1200 MHz, the vendor's dvfs_table voltages), so
+ * with cpufreq-dt this floor only matters until cpufreq takes over and lifts
+ * the 720/912 MHz points slightly (1.00/1.10 -> 1.16 V): a margin, kept on
+ * purpose. The regulator core raises a voltage below the minimum at boot
+ * (machine_constraints_voltage, apply_uV).
+ */
+&reg_dcdc2 {
+	regulator-min-microvolt = <1160000>;
+};
+
+/* DS1307 at 0x68 on TWI2 (PB20/PB21, the mainline default pins). */
+&i2c2 {
+	status = "okay";
+
+	ds1307: rtc@68 {
+		compatible = "dallas,ds1307";
+		reg = <0x68>;
+	};
+};

+ 29 - 0
files/bpi-m2/dts/sun8i-r40-bananapi-m2-ultra-k4be.dts

@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+/*
+ * Banana Pi M2-Ultra DT for marlena (192.168.2.1). marlena very likely is an
+ * M2 Berry too (its mmc2/eMMC host finds no card), but it has always booted an
+ * Ultra DT; until that is checked physically it stays on it, plus the DS1307
+ * RTC, the rtc0/mmc aliases and the LED triggers (bananapi-m2-k4be.dtsi).
+ * USB: the Ultra file enables EHCI/OHCI 1 and 2; the FTDI adapters (furnace
+ * controller) are behind a hub on ehci1, which the Berry file enables too.
+ *
+ * Built by build-kernel.sh inside the kernel tree, with symbols (-@), so
+ * marlena's environment can still apply sun8i-r40-bananapi-m2-ultra-led.dtbo.
+ */
+
+#include "sun8i-r40-bananapi-m2-ultra.dts"
+#include "bananapi-m2-k4be.dtsi"
+
+/ {
+	model = "Banana Pi BPI-M2-Ultra + k4be";
+
+	aliases {
+		mmc2 = &mmc2;
+	};
+
+	leds {
+		user_led_green: user-led-green {
+			linux,default-trigger = "mmc0";
+		};
+	};
+};

+ 21 - 0
files/bpi-m2/dts/sun8i-v40-bananapi-m2-berry-k4be.dts

@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+/*
+ * Banana Pi M2 Berry (V40): banana-backup (192.168.2.150). The mainline board
+ * file plus the DS1307 RTC, the rtc0/mmc aliases and the LED triggers the
+ * deployed "+ k4be" DTB had (bananapi-m2-k4be.dtsi).
+ *
+ * Built by build-kernel.sh inside the kernel tree, with symbols (-@).
+ */
+
+#include "sun8i-v40-bananapi-m2-berry.dts"
+#include "bananapi-m2-k4be.dtsi"
+
+/ {
+	model = "Banana Pi M2 Berry + k4be";
+
+	leds {
+		user_led_green: user-led {
+			linux,default-trigger = "mmc0";
+		};
+	};
+};

+ 101 - 0
files/bpi-m2/kernel.config

@@ -0,0 +1,101 @@
+# Banana Pi M2 Berry/Ultra (V40/R40): marlena and banana-backup. Merged after
+# files/kernel-common.config (sunxi_defconfig + common + this).
+# build-kernel.sh checks that every option here ended up in the final .config
+# with the requested value. Evidence for the options:
+# /mnt/d/SBC/bananapi-build/M2U/2026/kernel-options-report.md and
+# BANANA-V40-notes.md.
+
+CONFIG_LOCALVERSION="-k4be"
+
+# R40 pin controller (in the A10/A20 driver) and clocks; no R_PIO/R_CCU on the
+# R40, and the H3 ones are not needed
+CONFIG_PINCTRL_SUN4I_A10=y
+CONFIG_SUN8I_R40_CCU=y
+CONFIG_SUN8I_DE2_CCU=y
+# CONFIG_PINCTRL_SUN8I_H3 is not set
+# CONFIG_PINCTRL_SUN8I_H3_R is not set
+# CONFIG_SUN8I_H3_CCU is not set
+# CONFIG_SUN8I_R_CCU is not set
+
+# ---- PMIC: AXP221 on i2c0; its regulators feed SATA, the PHY, Wi-Fi, CPU ----
+CONFIG_MFD_AXP20X_I2C=y
+# CONFIG_MFD_AXP20X_RSB is not set
+CONFIG_REGULATOR_AXP20X=y
+CONFIG_AXP20X_POWER=y
+CONFIG_CHARGER_AXP20X=y
+CONFIG_BATTERY_AXP20X=y
+CONFIG_AXP20X_ADC=y
+# power button on the PMIC
+CONFIG_INPUT_AXP20X_PEK=y
+# no GPIO regulators and nothing on the SPI header
+# CONFIG_REGULATOR_GPIO is not set
+# CONFIG_SPI_SUN6I is not set
+
+# ---- RTC: battery-backed DS1307 at 0x68 on i2c2 is rtc0 (DT alias) ----
+CONFIG_RTC_DRV_DS1307=y
+CONFIG_RTC_HCTOSYS=y
+CONFIG_RTC_HCTOSYS_DEVICE="rtc0"
+# chrony's rtcsync (kernel 11-minute mode)
+CONFIG_RTC_SYSTOHC=y
+CONFIG_RTC_SYSTOHC_DEVICE="rtc0"
+
+# ---- SATA: /home and swap on both boards ----
+CONFIG_ATA=y
+CONFIG_SATA_AHCI_PLATFORM=y
+CONFIG_AHCI_SUNXI=y
+CONFIG_BLK_DEV_SD=y
+CONFIG_LEDS_TRIGGER_DISK=y
+
+# ---- ethernet: dwmac-sun8i (common fragment) with a Realtek RGMII PHY ----
+CONFIG_REALTEK_PHY=y
+
+# ---- file serving: NFS export of /home (marlena), samba is userspace ----
+CONFIG_NFSD=y
+CONFIG_NFSD_V4=y
+CONFIG_CIFS=y
+CONFIG_BRIDGE=y
+CONFIG_OVERLAY_FS=y
+CONFIG_ISO9660_FS=y
+CONFIG_JOLIET=y
+CONFIG_LEDS_TRIGGER_ACTIVITY=y
+
+# ---- HDMI console (local recovery without the serial cable) ----
+CONFIG_DRM=y
+CONFIG_DRM_SUN4I=y
+CONFIG_DRM_SUN8I_DW_HDMI=y
+CONFIG_DRM_FBDEV_EMULATION=y
+CONFIG_FRAMEBUFFER_CONSOLE=y
+# A10/A20 HDMI CEC; VGA bridges; PWM backlights (no panel)
+# CONFIG_DRM_SUN4I_HDMI_CEC is not set
+# CONFIG_DRM_SIMPLE_BRIDGE is not set
+# CONFIG_BACKLIGHT_PWM is not set
+
+# ---- diagnosing silent lockups (2026-11-18/19, see BANANA-V40-notes.md) ----
+# Both boards hung under sustained multi-core load with nothing in the logs.
+# netconsole (dynamic: target set up from userspace via configfs) sends kernel
+# messages over UDP even when userspace is frozen; the detectors print what
+# a stuck CPU or task is doing. The hard-lockup detector is the "buddy" one
+# (CPUs watch each other), the only kind available on 32-bit ARM.
+# DEBUG_KERNEL only makes the detectors selectable; it costs nothing itself.
+CONFIG_DEBUG_KERNEL=y
+CONFIG_NETCONSOLE=y
+CONFIG_NETCONSOLE_DYNAMIC=y
+CONFIG_SOFTLOCKUP_DETECTOR=y
+CONFIG_HARDLOCKUP_DETECTOR=y
+CONFIG_DETECT_HUNG_TASK=y
+
+# ---- not used on these servers ----
+# Sound: no speakers, HDMI audio unused.
+# CONFIG_SOUND is not set
+# OTG port: not enabled in either board DT (no usb_otg node), so neither
+# MUSB host mode nor gadgets can work.
+# CONFIG_USB_MUSB_HDRC is not set
+# CONFIG_USB_GADGET is not set
+# AP6212 Wi-Fi/BT: unused (no wlan config on either board, no firmware on
+# banana-backup). To use it: CONFIG_WIRELESS, CONFIG_WLAN, CONFIG_CFG80211,
+# CONFIG_BRCMFMAC=m (a module: its firmware comes from the rootfs).
+# CONFIG_WIRELESS is not set
+# CONFIG_WLAN is not set
+# CONFIG_BT is not set
+# banana-backup's 5.4 had 1-Wire (W1_SLAVE_THERM), but neither DT has a
+# w1-gpio master and /sys/bus/w1 has no devices: left out.

+ 24 - 0
files/bpi-m2/overlay/sun8i-r40-bananapi-m2-ultra-led.dts

@@ -0,0 +1,24 @@
+// Copy of marlena's /boot/sun8i-r40-bananapi-m2-ultra-led.dts (2018), kept for the
+// build-time test that it still applies to our Ultra DTB. Not installed by
+// install-kernel.sh: marlena keeps its own .dtbo in /boot.
+/dts-v1/;
+/plugin/;
+
+/ {
+	compatible = "sinovoip,bpi-m2-ultra", "allwinner,sun8i-r40";
+
+	fragment@0 {
+		target = <&pwr_led>;
+		__overlay__ {
+			linux,default-trigger = "heartbeat";
+		};
+	};
+	
+	fragment@1 {
+		target = <&user_led_green>;
+		__overlay__ {
+			linux,default-trigger = "mmc0";
+		};
+	};		
+};
+

+ 25 - 0
files/bpi-m2/u-boot.config

@@ -0,0 +1,25 @@
+# Merged on top of bananapi_m2_berry_defconfig by build-uboot.sh.
+#
+# Both boards boot from a hand-written environment in /boot/uboot.env on the
+# first (FAT) partition of the card. That file is 128 KiB: its CRC covers
+# 0x20000 bytes, as the 2018/2021 U-Boots wrote it. Mainline sunxi now defaults
+# to 64 KiB, and with that size the CRC fails, U-Boot falls back to its
+# built-in environment and does not find a kernel (no extlinux.conf, no
+# boot.scr). write-uboot.sh checks the target's file against this value.
+CONFIG_ENV_SIZE=0x20000
+CONFIG_ENV_IS_IN_FAT=y
+CONFIG_ENV_FAT_INTERFACE="mmc"
+CONFIG_ENV_FAT_DEVICE_AND_PART="0:1"
+CONFIG_ENV_FAT_FILE="uboot.env"
+# Commands the environment uses: fatload, bootm of a legacy uImage, and on
+# marlena "fdt resize" / "fdt apply" for the LED overlay.
+CONFIG_CMD_FAT=y
+CONFIG_CMD_BOOTM=y
+CONFIG_LEGACY_IMAGE_FORMAT=y
+CONFIG_CMD_FDT=y
+CONFIG_OF_LIBFDT_OVERLAY=y
+CONFIG_CMD_SAVEENV=y
+
+# mkeficapsule is a host tool for signed EFI capsule updates, unused here; the
+# host GnuTLS is built without PKCS#11, so it would not link anyway.
+# CONFIG_TOOLS_MKEFICAPSULE is not set

+ 228 - 0
files/kernel-common.config

@@ -0,0 +1,228 @@
+# Fragment merged on top of sunxi_defconfig for every board type, before
+# files/<board>/kernel.config (which may override it). build-kernel.sh checks
+# that every option here ended up in the final .config with the requested value.
+#
+# Policy for all boards:
+# - self-contained: no initramfs, everything needed to boot is built in;
+# - built in (=y) wherever that works; a module only where it must be one
+#   (out-of-tree code, module parameters set by userspace, drivers that must
+#   not bind at boot), with the reason next to it in the board fragment;
+# - sunxi_defconfig serves every Allwinner SoC from the A10 to the A80; drivers
+#   for other SoCs and for hardware none of our boards has are switched off.
+
+# CONFIG_LOCALVERSION_AUTO is not set
+# CONFIG_BLK_DEV_INITRD is not set
+CONFIG_IKCONFIG=y
+CONFIG_IKCONFIG_PROC=y
+# CONFIG_ARM_APPENDED_DTB is not set
+# CONFIG_ARM_ATAG_DTB_COMPAT is not set
+
+# ---- SoC families: both the H2+ and the R40/V40 are sun8i --------------------
+# (the SoC-specific clock, pinctrl and PHY drivers depend on these)
+# CONFIG_MACH_SUN4I is not set
+# CONFIG_MACH_SUN5I is not set
+# CONFIG_MACH_SUN6I is not set
+# CONFIG_MACH_SUN7I is not set
+CONFIG_MACH_SUN8I=y
+# CONFIG_MACH_SUN9I is not set
+# CONFIG_MACH_SUNIV is not set
+# quad Cortex-A7 on all boards
+CONFIG_NR_CPUS=4
+# Pin controllers and clock units of other sun8i (and D1) chips; they have
+# prompts, so sunxi_defconfig's =y survives MACH_* being switched off. Each
+# board fragment also drops the one of the other board type (H3 vs R40).
+# CONFIG_PINCTRL_SUN5I is not set
+# CONFIG_PINCTRL_SUN6I_A31 is not set
+# CONFIG_PINCTRL_SUN6I_A31_R is not set
+# CONFIG_PINCTRL_SUN8I_A23 is not set
+# CONFIG_PINCTRL_SUN8I_A23_R is not set
+# CONFIG_PINCTRL_SUN8I_A33 is not set
+# CONFIG_PINCTRL_SUN8I_A83T is not set
+# CONFIG_PINCTRL_SUN8I_A83T_R is not set
+# CONFIG_PINCTRL_SUN8I_V3S is not set
+# CONFIG_PINCTRL_SUN9I_A80 is not set
+# CONFIG_PINCTRL_SUN9I_A80_R is not set
+# CONFIG_PINCTRL_SUN20I_D1 is not set
+# CONFIG_SUN8I_A23_CCU is not set
+# CONFIG_SUN8I_A33_CCU is not set
+# CONFIG_SUN8I_A83T_CCU is not set
+# CONFIG_SUN8I_V3S_CCU is not set
+# CONFIG_SUN20I_D1_CCU is not set
+# CONFIG_SUN20I_D1_R_CCU is not set
+
+# ---- general, init (systemd on the OPi0, OpenRC + udev on the Bananas) -------
+CONFIG_SYSVIPC=y
+CONFIG_POSIX_MQUEUE=y
+CONFIG_AUDIT=y
+CONFIG_NO_HZ_IDLE=y
+CONFIG_PREEMPT_VOLUNTARY=y
+CONFIG_PSI=y
+CONFIG_CGROUPS=y
+CONFIG_MEMCG=y
+CONFIG_BLK_CGROUP=y
+CONFIG_CGROUP_SCHED=y
+CONFIG_CGROUP_PIDS=y
+CONFIG_CGROUP_FREEZER=y
+CONFIG_CPUSETS=y
+CONFIG_CGROUP_DEVICE=y
+CONFIG_CGROUP_CPUACCT=y
+CONFIG_CGROUP_BPF=y
+# portage's ipc-, pid- and network-sandbox; systemd services
+CONFIG_NAMESPACES=y
+CONFIG_UTS_NS=y
+CONFIG_IPC_NS=y
+CONFIG_PID_NS=y
+CONFIG_NET_NS=y
+CONFIG_USER_NS=y
+CONFIG_BPF_SYSCALL=y
+CONFIG_FHANDLE=y
+CONFIG_EPOLL=y
+CONFIG_SIGNALFD=y
+CONFIG_ADVISE_SYSCALLS=y
+CONFIG_KEYS=y
+# OpenSSH >= 10 refuses logins without a working seccomp filter, and chrony's
+# -F 2 needs it too (caused an outage on marlena)
+CONFIG_SECCOMP=y
+CONFIG_SECCOMP_FILTER=y
+# htop's I/O columns
+CONFIG_TASKSTATS=y
+CONFIG_TASK_XACCT=y
+CONFIG_TASK_IO_ACCOUNTING=y
+CONFIG_AUTOFS_FS=y
+CONFIG_TMPFS_POSIX_ACL=y
+CONFIG_TMPFS_XATTR=y
+CONFIG_INOTIFY_USER=y
+CONFIG_FANOTIFY=y
+CONFIG_DEVTMPFS=y
+CONFIG_DEVTMPFS_MOUNT=y
+# udev (systemd-utils) requires it off: one forked helper per uevent
+# CONFIG_UEVENT_HELPER is not set
+# CONFIG_SYSFS_DEPRECATED is not set
+CONFIG_BLK_DEV_BSG=y
+CONFIG_CONFIGFS_FS=y
+CONFIG_FUSE_FS=y
+CONFIG_BINFMT_MISC=y
+CONFIG_KERNEL_MODE_NEON=y
+CONFIG_MAGIC_SYSRQ=y
+
+# ---- power, thermal, cpufreq, watchdog, RTC ----------------------------------
+CONFIG_CPU_FREQ_STAT=y
+CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL=y
+CONFIG_CPU_FREQ_GOV_ONDEMAND=y
+CONFIG_CPU_FREQ_GOV_POWERSAVE=y
+CONFIG_CPU_FREQ_GOV_PERFORMANCE=y
+CONFIG_CPUFREQ_DT=y
+CONFIG_THERMAL=y
+CONFIG_SUN8I_THERMAL=y
+CONFIG_WATCHDOG=y
+CONFIG_SUNXI_WATCHDOG=y
+# SoC RTC: also the clock source for the 32 kHz oscillator
+CONFIG_RTC_CLASS=y
+CONFIG_RTC_DRV_SUN6I=y
+CONFIG_RTC_INTF_SYSFS=y
+CONFIG_RTC_INTF_PROC=y
+CONFIG_RTC_INTF_DEV=y
+# A10/A20 RTC and the A80/A83T AC100 companion chip
+# CONFIG_RTC_DRV_SUNXI is not set
+# CONFIG_RTC_DRV_AC100 is not set
+# CONFIG_MFD_AC100 is not set
+
+# ---- storage / filesystems ---------------------------------------------------
+CONFIG_MMC_SUNXI=y
+CONFIG_EXT4_FS=y
+CONFIG_EXT4_FS_POSIX_ACL=y
+CONFIG_EXT4_FS_SECURITY=y
+CONFIG_VFAT_FS=y
+CONFIG_EXFAT_FS=y
+CONFIG_NLS_UTF8=y
+CONFIG_NLS_CODEPAGE_437=y
+CONFIG_NLS_ISO8859_1=y
+CONFIG_SWAP=y
+CONFIG_NFS_FS=y
+CONFIG_NFS_V3=y
+CONFIG_NFS_V4=y
+# root is never on NFS
+# CONFIG_ROOT_NFS is not set
+# CONFIG_IP_PNP is not set
+CONFIG_BLK_DEV_LOOP=y
+CONFIG_USB_STORAGE=y
+CONFIG_USB_UAS=y
+
+# ---- networking ----------------------------------------------------------------
+CONFIG_IPV6=y
+# 6in4 tunnels (sit0): unconfigured everywhere, and =m by default
+# CONFIG_IPV6_SIT is not set
+CONFIG_INET_DIAG=y
+CONFIG_NET_SCHED=y
+CONFIG_TLS=y
+CONFIG_NETFILTER=y
+CONFIG_NF_CONNTRACK=y
+CONFIG_NF_TABLES=y
+CONFIG_NF_TABLES_INET=y
+CONFIG_NFT_CT=y
+CONFIG_NFT_NAT=y
+CONFIG_NFT_MASQ=y
+CONFIG_NFT_REJECT=y
+# iptables-nft uses nftables plus the xtables compat layer
+CONFIG_NETFILTER_XTABLES=y
+CONFIG_NFT_COMPAT=y
+CONFIG_TUN=y
+CONFIG_DWMAC_SUN8I=y
+CONFIG_STMMAC_ETH=y
+CONFIG_PHYLIB=y
+# A10/A20 EMAC; Micrel PHYs (not on our boards: H3 internal PHY, Realtek)
+# CONFIG_SUN4I_EMAC is not set
+# CONFIG_MICREL_PHY is not set
+# no CAN transceiver on any board
+# CONFIG_CAN is not set
+
+# ---- USB host, serial adapters -------------------------------------------------
+CONFIG_USB_EHCI_HCD_PLATFORM=y
+CONFIG_USB_OHCI_HCD_PLATFORM=y
+CONFIG_PHY_SUN4I_USB=y
+# A80 USB PHY
+# CONFIG_PHY_SUN9I_USB is not set
+CONFIG_USB_SERIAL=y
+CONFIG_USB_SERIAL_FTDI_SIO=y
+CONFIG_USB_SERIAL_PL2303=y
+CONFIG_USB_SERIAL_CH341=y
+CONFIG_USB_SERIAL_CP210X=y
+CONFIG_USB_ACM=y
+CONFIG_USB_HID=y
+CONFIG_HID_GENERIC=y
+
+# ---- input / misc buses --------------------------------------------------------
+CONFIG_INPUT_EVDEV=y
+CONFIG_I2C_MV64XXX=y
+CONFIG_I2C_CHARDEV=y
+# A31 P2WI bus, A10 SPI, A10/A20 PS/2, resistive touchscreen, LRADC keys,
+# IR receivers: not used on any board
+# CONFIG_I2C_SUN6I_P2WI is not set
+# CONFIG_SPI_SUN4I is not set
+# CONFIG_SERIO_SUN4I_PS2 is not set
+# CONFIG_INPUT_TOUCHSCREEN is not set
+# CONFIG_KEYBOARD_SUN4I_LRADC is not set
+# CONFIG_RC_CORE is not set
+
+# ---- video/camera engines: neither board decodes video or has a camera -----------
+# CONFIG_MEDIA_SUPPORT is not set
+# CONFIG_STAGING_MEDIA is not set
+# CONFIG_DRM_LIMA is not set
+# CONFIG_DRM_PANEL_LVDS is not set
+# CONFIG_DRM_PANEL_SIMPLE is not set
+# CONFIG_DRM_PANEL_EDP is not set
+
+# ---- crypto ------------------------------------------------------------------------
+# sun8i-ce serves the H3 and the R40; the A10/A20 and A83T engines don't
+CONFIG_CRYPTO_DEV_SUN8I_CE=y
+# CONFIG_CRYPTO_DEV_SUN4I_SS is not set
+# CONFIG_CRYPTO_DEV_SUN8I_SS is not set
+CONFIG_CRYPTO_USER_API_HASH=y
+CONFIG_CRYPTO_USER_API_SKCIPHER=y
+
+# ---- LEDs ----------------------------------------------------------------------
+CONFIG_LEDS_TRIGGER_HEARTBEAT=y
+CONFIG_LEDS_TRIGGER_NETDEV=y
+CONFIG_LEDS_TRIGGER_TIMER=y
+CONFIG_LEDS_TRIGGER_DEFAULT_ON=y
+CONFIG_HW_RANDOM=y

+ 0 - 215
files/kernel.config

@@ -1,215 +0,0 @@
-# Fragment merged on top of sunxi_defconfig for the Orange Pi Zero (H2+).
-# The kernel is self-contained: no initramfs, everything needed to mount the
-# root filesystem (sunxi MMC, ext4) is built in. build-kernel.sh checks that
-# every option here ended up in the final .config with the requested value.
-
-CONFIG_LOCALVERSION="-opi0"
-# CONFIG_LOCALVERSION_AUTO is not set
-# CONFIG_BLK_DEV_INITRD is not set
-CONFIG_IKCONFIG=y
-CONFIG_IKCONFIG_PROC=y
-
-# ---- general / systemd requirements ----
-CONFIG_SYSVIPC=y
-CONFIG_POSIX_MQUEUE=y
-CONFIG_AUDIT=y
-CONFIG_NO_HZ_IDLE=y
-CONFIG_PREEMPT_VOLUNTARY=y
-CONFIG_PSI=y
-CONFIG_CGROUPS=y
-CONFIG_MEMCG=y
-CONFIG_BLK_CGROUP=y
-CONFIG_CGROUP_SCHED=y
-CONFIG_CGROUP_PIDS=y
-CONFIG_CGROUP_FREEZER=y
-CONFIG_CPUSETS=y
-CONFIG_CGROUP_DEVICE=y
-CONFIG_CGROUP_CPUACCT=y
-CONFIG_CGROUP_BPF=y
-CONFIG_NAMESPACES=y
-CONFIG_USER_NS=y
-CONFIG_BPF_SYSCALL=y
-CONFIG_FHANDLE=y
-CONFIG_SECCOMP=y
-CONFIG_AUTOFS_FS=y
-CONFIG_TMPFS_POSIX_ACL=y
-CONFIG_TMPFS_XATTR=y
-CONFIG_INOTIFY_USER=y
-CONFIG_FANOTIFY=y
-CONFIG_DEVTMPFS=y
-CONFIG_DEVTMPFS_MOUNT=y
-CONFIG_CONFIGFS_FS=y
-CONFIG_FUSE_FS=m
-CONFIG_BINFMT_MISC=m
-CONFIG_KERNEL_MODE_NEON=y
-# CONFIG_ARM_APPENDED_DTB is not set
-# CONFIG_ARM_ATAG_DTB_COMPAT is not set
-
-# ---- power, thermal, cpufreq ----
-CONFIG_CPU_FREQ_STAT=y
-CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL=y
-CONFIG_CPU_FREQ_GOV_ONDEMAND=y
-CONFIG_CPU_FREQ_GOV_POWERSAVE=y
-CONFIG_CPU_FREQ_GOV_PERFORMANCE=y
-CONFIG_CPUFREQ_DT=y
-# CPU supply: GPIO regulator on PL6 (reg_vdd_cpux in the mainline board file);
-# without it cpufreq-dt cannot scale the voltage
-CONFIG_REGULATOR_GPIO=y
-CONFIG_THERMAL=y
-CONFIG_SUN8I_THERMAL=y
-CONFIG_WATCHDOG=y
-CONFIG_SUNXI_WATCHDOG=y
-# SoC RTC (no battery on this board, but it is the clock source for the
-# 32 kHz oscillator and keeps time across a warm reboot)
-CONFIG_RTC_CLASS=y
-CONFIG_RTC_DRV_SUN6I=y
-
-# ---- storage / filesystems ----
-CONFIG_MMC_SUNXI=y
-CONFIG_EXT4_FS=y
-CONFIG_EXT4_FS_POSIX_ACL=y
-CONFIG_EXT4_FS_SECURITY=y
-CONFIG_VFAT_FS=y
-CONFIG_EXFAT_FS=m
-CONFIG_NLS_UTF8=y
-CONFIG_NLS_CODEPAGE_437=y
-CONFIG_NLS_ISO8859_1=y
-CONFIG_ZRAM=m
-# armbian-zram-config sets the algorithm from SWAP_ALGORITHM in
-# /etc/default/armbian-zram-config (lzo, lzo-rle, lz4 or zstd depending on
-# the Armbian version); writing one the kernel lacks fails. Cover all four.
-CONFIG_ZRAM_BACKEND_LZ4=y
-CONFIG_ZRAM_BACKEND_ZSTD=y
-CONFIG_ZRAM_BACKEND_LZO=y
-CONFIG_CRYPTO_LZ4=y
-CONFIG_CRYPTO_ZSTD=y
-CONFIG_SWAP=y
-CONFIG_NFS_FS=y
-CONFIG_NFS_V3=y
-CONFIG_NFS_V4=y
-CONFIG_BLK_DEV_LOOP=m
-CONFIG_USB_STORAGE=m
-CONFIG_USB_UAS=m
-
-# ---- networking ----
-CONFIG_IPV6=y
-CONFIG_INET_DIAG=m
-CONFIG_NETFILTER=y
-CONFIG_NF_CONNTRACK=m
-CONFIG_NF_TABLES=m
-CONFIG_NF_TABLES_INET=y
-CONFIG_NFT_CT=m
-CONFIG_NFT_NAT=m
-CONFIG_NFT_MASQ=m
-CONFIG_NFT_REJECT=m
-# iptables-nft (Debian default) uses nftables plus the xtables compat layer
-CONFIG_NETFILTER_XTABLES=m
-CONFIG_NFT_COMPAT=m
-CONFIG_TUN=m
-CONFIG_DUMMY=m
-CONFIG_DWMAC_SUN8I=y
-CONFIG_STMMAC_ETH=y
-CONFIG_PHYLIB=y
-
-# ---- Wi-Fi: XR819 (out-of-tree xradio module needs these) ----
-CONFIG_WIRELESS=y
-CONFIG_WLAN=y
-CONFIG_CFG80211=m
-CONFIG_CFG80211_WEXT=y
-CONFIG_MAC80211=m
-CONFIG_MAC80211_LEDS=y
-CONFIG_RFKILL=m
-CONFIG_CRYPTO_CCM=y
-CONFIG_CRYPTO_GCM=y
-CONFIG_CRYPTO_CMAC=y
-CONFIG_CRYPTO_AES=y
-CONFIG_CRYPTO_AES_ARM_BS=m
-CONFIG_PWRSEQ_SIMPLE=y
-
-# ---- audio (H3 analog codec on the 13-pin header) ----
-CONFIG_SND_SUN4I_CODEC=y
-CONFIG_SND_SUN8I_CODEC_ANALOG=y
-CONFIG_SND_SUN4I_I2S=m
-CONFIG_SND_SIMPLE_CARD=m
-CONFIG_SND_USB_AUDIO=m
-CONFIG_SND_ALOOP=m
-
-# ---- USB host and gadget ----
-CONFIG_USB_EHCI_HCD_PLATFORM=y
-CONFIG_USB_OHCI_HCD_PLATFORM=y
-CONFIG_USB_MUSB_HDRC=y
-CONFIG_USB_MUSB_SUNXI=y
-CONFIG_PHY_SUN4I_USB=y
-CONFIG_USB_GADGET=y
-CONFIG_USB_CONFIGFS=m
-CONFIG_USB_CONFIGFS_SERIAL=y
-CONFIG_USB_CONFIGFS_ACM=y
-CONFIG_USB_CONFIGFS_ECM=y
-CONFIG_USB_CONFIGFS_RNDIS=y
-CONFIG_USB_G_SERIAL=m
-CONFIG_USB_ETH=m
-CONFIG_USB_SERIAL=m
-CONFIG_USB_SERIAL_FTDI_SIO=m
-CONFIG_USB_SERIAL_PL2303=m
-CONFIG_USB_SERIAL_CH341=m
-CONFIG_USB_SERIAL_CP210X=m
-CONFIG_USB_ACM=m
-CONFIG_USB_HID=y
-CONFIG_HID_GENERIC=y
-CONFIG_USB_NET_DRIVERS=m
-CONFIG_USB_USBNET=m
-CONFIG_USB_NET_CDCETHER=m
-CONFIG_USB_RTL8152=m
-
-# ---- radio front panel ($PANEL_DIR, see config.sh) ----
-# I2C bus (mv64xxx on H3) and userspace access for radio-ui i2c
-CONFIG_I2C_MV64XXX=y
-CONFIG_I2C_CHARDEV=y
-# i2c-tiny-usb bridge used on the test rig
-CONFIG_I2C_TINY_USB=m
-# U2 key expander: TCA9539 via gpio-pca953x (INT on PA6), keys via gpio-keys;
-# built in, like the panel driver, so the keys need no module loading
-CONFIG_GPIO_PCA953X=y
-CONFIG_GPIO_PCA953X_IRQ=y
-CONFIG_GPIO_CDEV=y
-CONFIG_KEYBOARD_GPIO=y
-CONFIG_KEYBOARD_GPIO_POLLED=m
-CONFIG_INPUT_EVDEV=y
-CONFIG_INPUT_UINPUT=m
-# s1d13700-tca DRM driver, put into drivers/gpu/drm/tiny/ by build-kernel.sh
-# from $PANEL_DIR/driver and built in, so the panel exists before the root
-# filesystem is mounted and fbcon shows the boot log on it.
-CONFIG_DRM=y
-CONFIG_DRM_KMS_HELPER=y
-CONFIG_DRM_S1D13700_TCA=y
-CONFIG_DRM_FBDEV_EMULATION=y
-CONFIG_BACKLIGHT_CLASS_DEVICE=y
-CONFIG_FB=y
-CONFIG_FRAMEBUFFER_CONSOLE=y
-# CONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER is not set
-# 240x160 panel: 6x8 font gives 40x20 characters (fbcon=font:6x8)
-CONFIG_FONTS=y
-CONFIG_FONT_8x8=y
-CONFIG_FONT_8x16=y
-CONFIG_FONT_6x8=y
-
-# ---- no display output on this board: drop HDMI/GPU/video engines ----
-# CONFIG_DRM_SUN4I is not set
-# CONFIG_DRM_LIMA is not set
-# CONFIG_MEDIA_SUPPORT is not set
-# CONFIG_STAGING_MEDIA is not set
-# CONFIG_CAN is not set
-# CONFIG_ATA is not set
-# CONFIG_INPUT_TOUCHSCREEN is not set
-
-# ---- misc ----
-CONFIG_LEDS_TRIGGER_HEARTBEAT=y
-CONFIG_LEDS_TRIGGER_NETDEV=y
-CONFIG_LEDS_TRIGGER_TIMER=y
-CONFIG_LEDS_TRIGGER_DEFAULT_ON=y
-CONFIG_RTC_INTF_SYSFS=y
-CONFIG_RTC_INTF_PROC=y
-CONFIG_HW_RANDOM=y
-CONFIG_CRYPTO_USER_API_HASH=m
-CONFIG_CRYPTO_USER_API_SKCIPHER=m
-CONFIG_MAGIC_SYSRQ=y

+ 0 - 0
files/dts/sun8i-h2-plus-orangepi-zero-radio.dts → files/opi0/dts/sun8i-h2-plus-orangepi-zero-radio.dts


+ 134 - 0
files/opi0/kernel.config

@@ -0,0 +1,134 @@
+# Orange Pi Zero (H2+), the radio. Merged after files/kernel-common.config
+# (sunxi_defconfig + common + this). build-kernel.sh checks that every option
+# here ended up in the final .config with the requested value.
+
+CONFIG_LOCALVERSION="-opi0"
+
+# H2+ = H3 pin controllers and clocks; the R40 ones (also A10/A20 pinctrl)
+# and the display engine clocks are not needed
+CONFIG_PINCTRL_SUN8I_H3=y
+CONFIG_PINCTRL_SUN8I_H3_R=y
+CONFIG_SUN8I_H3_CCU=y
+CONFIG_SUN8I_R_CCU=y
+# CONFIG_PINCTRL_SUN4I_A10 is not set
+# CONFIG_SUN8I_R40_CCU is not set
+# CONFIG_SUN8I_DE2_CCU is not set
+
+# CPU supply: GPIO regulator on PL6 (reg_vdd_cpux in the mainline board file);
+# without it cpufreq-dt cannot scale the voltage
+CONFIG_REGULATOR_GPIO=y
+# SPI NOR flash on spi0 (sun6i driver serves the H3)
+CONFIG_SPI_SUN6I=y
+
+# ---- no PMIC: the board runs from fixed and GPIO regulators ----
+# CONFIG_MFD_AXP20X_I2C is not set
+# CONFIG_MFD_AXP20X_RSB is not set
+# CONFIG_REGULATOR_AXP20X is not set
+# CONFIG_AXP20X_POWER is not set
+# CONFIG_CHARGER_AXP20X is not set
+# CONFIG_BATTERY_AXP20X is not set
+# CONFIG_AXP20X_ADC is not set
+# CONFIG_INPUT_AXP20X_PEK is not set
+
+# ---- storage ----
+# no SATA on the H2+
+# CONFIG_ATA is not set
+# Module, not built in: armbian-zram-config loads it with module parameters
+# (number of devices for swap and armbian-ramlog), which a built-in driver
+# would not get.
+CONFIG_ZRAM=m
+# armbian-zram-config sets the algorithm from SWAP_ALGORITHM in
+# /etc/default/armbian-zram-config (lzo, lzo-rle, lz4 or zstd depending on
+# the Armbian version); writing one the kernel lacks fails. Cover all four.
+CONFIG_ZRAM_BACKEND_LZ4=y
+CONFIG_ZRAM_BACKEND_ZSTD=y
+CONFIG_ZRAM_BACKEND_LZO=y
+CONFIG_CRYPTO_LZ4=y
+CONFIG_CRYPTO_ZSTD=y
+
+# ---- networking ----
+# Module, not built in: built in, it creates dummy0 at boot (numdummies=1),
+# an interface nobody configured.
+CONFIG_DUMMY=m
+CONFIG_USB_NET_DRIVERS=y
+CONFIG_USB_USBNET=y
+CONFIG_USB_NET_CDCETHER=y
+CONFIG_USB_RTL8152=y
+
+# ---- Wi-Fi: XR819 (the out-of-tree xradio module needs these) ----
+# Built in; xradio itself is always a module (out of tree, firmware from the
+# rootfs). Built-in cfg80211 can't read regulatory.db before the rootfs is
+# mounted and logs that once; it loads the file when a country is set.
+CONFIG_WIRELESS=y
+CONFIG_WLAN=y
+CONFIG_CFG80211=y
+CONFIG_CFG80211_WEXT=y
+CONFIG_MAC80211=y
+CONFIG_MAC80211_LEDS=y
+CONFIG_RFKILL=y
+CONFIG_CRYPTO_CCM=y
+CONFIG_CRYPTO_GCM=y
+CONFIG_CRYPTO_CMAC=y
+CONFIG_CRYPTO_AES=y
+CONFIG_CRYPTO_AES_ARM_BS=y
+CONFIG_PWRSEQ_SIMPLE=y
+
+# ---- audio (H3 analog codec on the 13-pin header) ----
+CONFIG_SND_SUN4I_CODEC=y
+CONFIG_SND_SUN8I_CODEC_ANALOG=y
+CONFIG_SND_SUN4I_I2S=y
+CONFIG_SND_SIMPLE_CARD=y
+CONFIG_SND_USB_AUDIO=y
+# Module, not built in: built in, the loopback card would always exist and
+# take a card index from the real ones.
+CONFIG_SND_ALOOP=m
+# A33 digital codec, S/PDIF: not on the H2+ board
+# CONFIG_SND_SUN8I_CODEC is not set
+# CONFIG_SND_SUN4I_SPDIF is not set
+
+# ---- USB OTG port: host and gadget ----
+CONFIG_USB_MUSB_HDRC=y
+CONFIG_USB_MUSB_SUNXI=y
+CONFIG_USB_GADGET=y
+CONFIG_USB_CONFIGFS=y
+CONFIG_USB_CONFIGFS_SERIAL=y
+CONFIG_USB_CONFIGFS_ACM=y
+CONFIG_USB_CONFIGFS_ECM=y
+CONFIG_USB_CONFIGFS_RNDIS=y
+# Modules, not built in: a built-in legacy gadget binds the only UDC at boot,
+# so only one could be built in and configfs gadgets could no longer be used.
+CONFIG_USB_G_SERIAL=m
+CONFIG_USB_ETH=m
+
+# ---- radio front panel ($PANEL_DIR, see boards/opi0.sh) ----
+# i2c-tiny-usb bridge used on the test rig
+CONFIG_I2C_TINY_USB=y
+# U2 key expander: TCA9539 via gpio-pca953x (INT on PA6), keys via gpio-keys;
+# built in, like the panel driver, so the keys need no module loading
+CONFIG_GPIO_PCA953X=y
+CONFIG_GPIO_PCA953X_IRQ=y
+CONFIG_GPIO_CDEV=y
+CONFIG_KEYBOARD_GPIO=y
+CONFIG_KEYBOARD_GPIO_POLLED=y
+CONFIG_INPUT_UINPUT=y
+# s1d13700-tca DRM driver, put into drivers/gpu/drm/tiny/ by build-kernel.sh
+# from $PANEL_DIR/driver and built in, so the panel exists before the root
+# filesystem is mounted and fbcon shows the boot log on it.
+CONFIG_DRM=y
+CONFIG_DRM_KMS_HELPER=y
+CONFIG_DRM_S1D13700_TCA=y
+CONFIG_DRM_FBDEV_EMULATION=y
+CONFIG_BACKLIGHT_CLASS_DEVICE=y
+CONFIG_FB=y
+CONFIG_FRAMEBUFFER_CONSOLE=y
+# CONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER is not set
+# 240x160 panel: 6x8 font gives 40x20 characters (fbcon=font:6x8)
+CONFIG_FONTS=y
+CONFIG_FONT_8x8=y
+CONFIG_FONT_8x16=y
+CONFIG_FONT_6x8=y
+
+# ---- no display output on this board: drop HDMI/display engine ----
+# CONFIG_DRM_SUN4I is not set
+# CONFIG_FB_SIMPLE is not set
+# CONFIG_BACKLIGHT_PWM is not set

+ 0 - 0
files/u-boot.config → files/opi0/u-boot.config


+ 27 - 137
install-kernel.sh

@@ -1,40 +1,50 @@
 #!/bin/bash
-# Install the kernel built by build-kernel.sh into an existing root filesystem
-# and (re)generate /boot/extlinux/extlinux.conf for mainline U-Boot.
-# Nothing else in the root filesystem is touched: no initramfs, no Armbian
-# boot.scr/armbianEnv.txt changes (they stay as they are, unused by our U-Boot,
-# which tries extlinux.conf first).
+# Install the kernel built by build-kernel.sh for the selected board type
+# (./select-board.sh) into a card's root filesystem mounted on this PC, or into
+# a running board over ssh. How depends on the board type's boot chain
+# (INSTALL_SCHEME in boards/<board>.sh):
+#   extlinux  (opi0)    /boot/<subdir>/<release>/ + generated extlinux.conf,
+#                       see lib/install-extlinux.sh
+#   ubootenv  (bpi-m2)  /boot/<subdir>/<release>/ on the FAT /boot, copied to the
+#                       fixed names the U-Boot environment loads (uImage, DTB),
+#                       see lib/install-ubootenv.sh
+# Nothing is ever rebooted.
 #
 # Usage:
 #   sudo ./install-kernel.sh /mnt/card-root     card's root partition mounted
+#                                               (bpi-m2: its FAT partition 1
+#                                               mounted on <root>/boot too)
 #   ./install-kernel.sh ssh:root@radio.lo       running board, over ssh
-# Installs out/opi0-kernel-$RELEASE.tar.gz; RELEASE defaults to the last
-# build (out/kernel-release). modules.dep is already in the tarball (depmod
-# runs at build time), so nothing is run on the target.
-# Every kernel under /boot/opi0/ gets a menu entry, highest version first
-# (sort -V on the release name, not file dates); the highest is the default.
-# An older one can be picked on the serial console if a new one fails.
-# Settings (config.sh / environment): PARTUUID, BOOT_DTB, BOOT_OVERLAYS, KERNEL_CONSOLE,
-# KERNEL_CMDLINE_EXTRA, RELEASE.
+# Installs out/<board>/<board>-kernel-$RELEASE.tar.gz; RELEASE defaults to the
+# last build (out/<board>/kernel-release). modules.dep is already in the
+# tarball (depmod runs at build time).
 set -euo pipefail
 . "$(dirname "$0")/config.sh"
 
 [ $# -eq 1 ] || die "usage: $0 /path/to/mounted/root | ssh:user@host"
 TARGET="$1"
 RELEASE="${RELEASE:-$(cat "$OUT/kernel-release" 2>/dev/null || true)}"
-[ -n "$RELEASE" ] || die "no kernel built yet, run ./build-kernel.sh"
-TARBALL="$OUT/opi0-kernel-$RELEASE.tar.gz"
+[ -n "$RELEASE" ] || die "no kernel built yet for $BOARD, run ./build-kernel.sh"
+TARBALL="$OUT/$BOARD-kernel-$RELEASE.tar.gz"
 [ -f "$TARBALL" ] || die "$TARBALL not found"
+info "installing $RELEASE ($BOARD_NAME) to $TARGET"
 
 # run CMD on the target root (as shell code; paths relative to its /)
 case "$TARGET" in
 ssh:*)
 	HOST="${TARGET#ssh:}"
+	ROOT=
 	need_tools ssh
 	trun() { ssh "$HOST" "cd / && $1"; }
 	tput_file() { ssh "$HOST" "cat > '/$1.new' && mv '/$1.new' '/$1'"; }
+	# A kernel for one board type must not land on another.
+	compat="$(trun 'tr "\0" "\n" < /proc/device-tree/compatible' 2>/dev/null || true)"
+	grep -qx "$BOARD_DT_COMPAT" <<<"$compat" || [ "${FORCE:-0}" = 1 ] ||
+		die "$HOST is not a $BOARD_NAME (compatible: $(echo $compat)); select its board type with ./select-board.sh (FORCE=1 overrides)"
+	info "target: $(trun 'cat /proc/device-tree/model' 2>/dev/null | tr -d '\0'), running $(trun 'uname -r')"
 	;;
 *)
+	HOST=
 	ROOT="$(cd "$TARGET" && pwd -P)"
 	[ "$ROOT" != / ] || die "refusing to install into this PC's own /"
 	[ -e "$ROOT/etc/os-release" ] || die "$ROOT does not look like a root filesystem"
@@ -44,125 +54,5 @@ ssh:*)
 	;;
 esac
 
-# Root partition by PARTUUID: no initramfs, so root=UUID= cannot work.
-# PARTUUID=... in the environment overrides the detection.
-partuuid="${PARTUUID:-}"
-if [ -n "${ROOT:-}" ]; then
-	if [ -z "$partuuid" ]; then
-		[ "$(findmnt -no TARGET --target "$ROOT")" = "$ROOT" ] ||
-			die "$ROOT is not a mount point; mount the card's root partition there (or set PARTUUID)"
-		partuuid="$(blkid -s PARTUUID -o value "$(findmnt -no SOURCE --target "$ROOT")" || true)"
-	fi
-	fstype="$(findmnt -no FSTYPE --target "$ROOT" || true)"
-else
-	[ -n "$partuuid" ] || partuuid="$(trun 'blkid -s PARTUUID -o value "$(findmnt -no SOURCE /)"' || true)"
-	fstype="$(trun 'findmnt -no FSTYPE /' || true)"
-fi
-[ -n "$partuuid" ] || die "could not find the PARTUUID of the root partition"
-case "$fstype" in ext[234]|btrfs|f2fs|xfs) ;; *) fstype=ext4 ;; esac
-info "root: PARTUUID=$partuuid ($fstype)"
-
-# Writing below follows the target's own symlinks (tar
-# --keep-directory-symlink, cp, mv). A relative link such as Debian's
-# lib -> usr/lib stays inside the target, but an absolute one (or ../..)
-# would resolve on this PC and write into its own /usr/lib or /boot.
-if [ -n "${ROOT:-}" ]; then
-	for p in boot boot/opi0 "boot/opi0/$RELEASE" boot/extlinux \
-		boot/extlinux/extlinux.conf boot/extlinux/extlinux.conf.bak \
-		boot/extlinux/extlinux.conf.new lib lib/modules "lib/modules/$RELEASE"; do
-		r="$(realpath -m -- "$ROOT/$p")"
-		case "$r" in
-		"$ROOT"/*) ;;
-		*) die "/$p on the target resolves to $r, outside $ROOT (absolute symlink?); not writing there" ;;
-		esac
-	done
-	for p in "boot/opi0/$RELEASE" "lib/modules/$RELEASE"; do
-		[ -d "$ROOT/$p" ] || continue
-		r="$(find "$ROOT/$p" -type l -lname '/*' -print -quit)"
-		[ -z "$r" ] || die "absolute symlink $r in the target; not extracting over it"
-	done
-fi
-
-# Armbian packages that can undo this setup on an apt upgrade. Warnings only.
-check_target_packages() {
-	local st unheld
-	st="$(trun 'cat var/lib/dpkg/status 2>/dev/null' | awk 'BEGIN { RS = ""; FS = "\n" }
-		{ p = s = ""
-		  for (i = 1; i <= NF; i++) {
-			if ($i ~ /^Package: /) p = substr($i, 10)
-			else if ($i ~ /^Status: /) s = substr($i, 9)
-		  }
-		  if (s ~ / installed$/) print p, s }' || true)"
-	[ -n "$st" ] || return 0
-	unheld="$(awk '$1 ~ /^linux-(image|dtb|u-boot)-/ && $2 != "hold" { print $1 }' <<<"$st" | tr '\n' ' ')"
-	[ -z "$unheld" ] || echo "WARNING: not on hold: ${unheld% }; an upgrade may rewrite Armbian's boot files or the bootloader. On the target: apt-mark hold ${unheld% }" >&2
-	! grep -q '^u-boot-menu ' <<<"$st" ||
-		echo "WARNING: u-boot-menu is installed; it rewrites /boot/extlinux/extlinux.conf on kernel changes. Remove it." >&2
-	trun 'test -e lib/firmware/xr819/fw_xr819.bin' ||
-		echo "WARNING: /lib/firmware/xr819/ is missing (package armbian-firmware); the XR819 Wi-Fi will not work" >&2
-	local alg
-	alg="$(trun 'cat etc/default/armbian-zram-config 2>/dev/null' |
-		sed -n "s/^[[:space:]]*SWAP_ALGORITHM=[\"']*\([a-z0-9-]*\).*/\1/p" | tail -1 || true)"
-	case "$alg" in
-	""|lz4|zstd|lzo|lzo-rle) ;;
-	*) echo "WARNING: armbian-zram-config uses SWAP_ALGORITHM=$alg, which files/kernel.config does not enable" >&2 ;;
-	esac
-}
-check_target_packages
-
-info "installing $RELEASE to $TARGET"
-# --keep-directory-symlink: /lib is a symlink to usr/lib on merged-/usr systems
-case "$TARGET" in
-ssh:*) ssh "$HOST" "tar --keep-directory-symlink --no-same-owner -xzf - -C /" < "$TARBALL" ;;
-*)     tar --keep-directory-symlink -xzf "$TARBALL" -C "$ROOT" ;;
-esac
-
-# Releases on the target, highest version first (by name, not by date).
-releases="$(trun 'ls -1 boot/opi0 2>/dev/null' | sort -rV)"
-[ -n "$releases" ] || die "no kernels in /boot/opi0 on the target"
-
-# The last console= becomes /dev/console (emergency shell, init output). Keep
-# the serial console there even if KERNEL_CONSOLE is overridden in a different
-# order; the relative order of everything else is kept.
-console_args() {
-	local a serial="" rest=""
-	for a in $KERNEL_CONSOLE; do
-		case "$a" in
-		console=ttyS*) serial="${serial:+$serial }$a" ;;
-		*)             rest="${rest:+$rest }$a" ;;
-		esac
-	done
-	echo "$rest${rest:+${serial:+ }}$serial"
-}
-cmdline_console="$(console_args)"
-case "$cmdline_console" in
-*console=ttyS*) ;;
-*) echo "WARNING: no console=ttyS* in KERNEL_CONSOLE; no serial emergency console" >&2 ;;
-esac
-
-gen_extlinux() {
-	local r ov
-	echo "# Generated by install-kernel.sh (OPi0 build) - rerun it to update."
-	echo "# Booted by mainline U-Boot; no initramfs."
-	echo "menu title Orange Pi Zero"
-	echo "timeout 20"
-	echo "default $(head -1 <<<"$releases")"
-	for r in $releases; do
-		echo
-		echo "label $r"
-		echo "	kernel /boot/opi0/$r/zImage"
-		echo "	fdt /boot/opi0/$r/$BOOT_DTB"
-		if [ -n "$BOOT_OVERLAYS" ]; then
-			echo -n "	fdtoverlays"
-			for ov in $BOOT_OVERLAYS; do echo -n " /boot/opi0/$r/overlay/$ov.dtbo"; done
-			echo
-		fi
-		echo "	append root=PARTUUID=$partuuid rootfstype=$fstype rootwait rw $cmdline_console panic=10 consoleblank=0 $KERNEL_CMDLINE_EXTRA"
-	done
-}
-
-trun 'mkdir -p boot/extlinux && { [ ! -f boot/extlinux/extlinux.conf ] || cp boot/extlinux/extlinux.conf boot/extlinux/extlinux.conf.bak; }'
-gen_extlinux | tput_file boot/extlinux/extlinux.conf
-trun 'sync'
-info "installed; /boot/extlinux/extlinux.conf:"
-trun 'cat boot/extlinux/extlinux.conf'
+[ -f "$TOP/lib/install-$INSTALL_SCHEME.sh" ] || die "no install method '$INSTALL_SCHEME'"
+. "$TOP/lib/install-$INSTALL_SCHEME.sh"

+ 137 - 0
lib/install-extlinux.sh

@@ -0,0 +1,137 @@
+# Install method "extlinux" (Orange Pi Zero), sourced by install-kernel.sh:
+# unpack the tarball into the target root and (re)generate
+# /boot/extlinux/extlinux.conf for mainline U-Boot. Nothing else in the root
+# filesystem is touched: no initramfs, no Armbian boot.scr/armbianEnv.txt
+# changes (they stay as they are, unused by our U-Boot, which tries
+# extlinux.conf first).
+# Every kernel under /boot/<subdir>/ gets a menu entry, highest version first
+# (sort -V on the release name, not file dates); the highest is the default.
+# An older one can be picked on the serial console if a new one fails.
+# Settings (boards/<board>.sh / environment): PARTUUID, BOOT_DTB, BOOT_OVERLAYS,
+# KERNEL_CONSOLE, KERNEL_CMDLINE_EXTRA.
+# Provided by install-kernel.sh: TARGET, TARBALL, RELEASE, ROOT or HOST, trun,
+# tput_file.
+
+
+# Root partition by PARTUUID: no initramfs, so root=UUID= cannot work.
+# PARTUUID=... in the environment overrides the detection.
+partuuid="${PARTUUID:-}"
+if [ -n "${ROOT:-}" ]; then
+	if [ -z "$partuuid" ]; then
+		[ "$(findmnt -no TARGET --target "$ROOT")" = "$ROOT" ] ||
+			die "$ROOT is not a mount point; mount the card's root partition there (or set PARTUUID)"
+		partuuid="$(blkid -s PARTUUID -o value "$(findmnt -no SOURCE --target "$ROOT")" || true)"
+	fi
+	fstype="$(findmnt -no FSTYPE --target "$ROOT" || true)"
+else
+	[ -n "$partuuid" ] || partuuid="$(trun 'blkid -s PARTUUID -o value "$(findmnt -no SOURCE /)"' || true)"
+	fstype="$(trun 'findmnt -no FSTYPE /' || true)"
+fi
+[ -n "$partuuid" ] || die "could not find the PARTUUID of the root partition"
+case "$fstype" in ext[234]|btrfs|f2fs|xfs) ;; *) fstype=ext4 ;; esac
+info "root: PARTUUID=$partuuid ($fstype)"
+
+# Writing below follows the target's own symlinks (tar
+# --keep-directory-symlink, cp, mv). A relative link such as Debian's
+# lib -> usr/lib stays inside the target, but an absolute one (or ../..)
+# would resolve on this PC and write into its own /usr/lib or /boot.
+if [ -n "${ROOT:-}" ]; then
+	for p in boot boot/$BOOT_SUBDIR "boot/$BOOT_SUBDIR/$RELEASE" boot/extlinux \
+		boot/extlinux/extlinux.conf boot/extlinux/extlinux.conf.bak \
+		boot/extlinux/extlinux.conf.new lib lib/modules "lib/modules/$RELEASE"; do
+		r="$(realpath -m -- "$ROOT/$p")"
+		case "$r" in
+		"$ROOT"/*) ;;
+		*) die "/$p on the target resolves to $r, outside $ROOT (absolute symlink?); not writing there" ;;
+		esac
+	done
+	for p in "boot/$BOOT_SUBDIR/$RELEASE" "lib/modules/$RELEASE"; do
+		[ -d "$ROOT/$p" ] || continue
+		r="$(find "$ROOT/$p" -type l -lname '/*' -print -quit)"
+		[ -z "$r" ] || die "absolute symlink $r in the target; not extracting over it"
+	done
+fi
+
+# Armbian packages that can undo this setup on an apt upgrade. Warnings only.
+check_target_packages() {
+	local st unheld
+	st="$(trun 'cat var/lib/dpkg/status 2>/dev/null' | awk 'BEGIN { RS = ""; FS = "\n" }
+		{ p = s = ""
+		  for (i = 1; i <= NF; i++) {
+			if ($i ~ /^Package: /) p = substr($i, 10)
+			else if ($i ~ /^Status: /) s = substr($i, 9)
+		  }
+		  if (s ~ / installed$/) print p, s }' || true)"
+	[ -n "$st" ] || return 0
+	unheld="$(awk '$1 ~ /^linux-(image|dtb|u-boot)-/ && $2 != "hold" { print $1 }' <<<"$st" | tr '\n' ' ')"
+	[ -z "$unheld" ] || echo "WARNING: not on hold: ${unheld% }; an upgrade may rewrite Armbian's boot files or the bootloader. On the target: apt-mark hold ${unheld% }" >&2
+	! grep -q '^u-boot-menu ' <<<"$st" ||
+		echo "WARNING: u-boot-menu is installed; it rewrites /boot/extlinux/extlinux.conf on kernel changes. Remove it." >&2
+	trun 'test -e lib/firmware/xr819/fw_xr819.bin' ||
+		echo "WARNING: /lib/firmware/xr819/ is missing (package armbian-firmware); the XR819 Wi-Fi will not work" >&2
+	local alg
+	alg="$(trun 'cat etc/default/armbian-zram-config 2>/dev/null' |
+		sed -n "s/^[[:space:]]*SWAP_ALGORITHM=[\"']*\([a-z0-9-]*\).*/\1/p" | tail -1 || true)"
+	case "$alg" in
+	""|lz4|zstd|lzo|lzo-rle) ;;
+	*) echo "WARNING: armbian-zram-config uses SWAP_ALGORITHM=$alg, which files/opi0/kernel.config does not enable" >&2 ;;
+	esac
+}
+check_target_packages
+
+info "installing $RELEASE to $TARGET"
+# --keep-directory-symlink: /lib is a symlink to usr/lib on merged-/usr systems
+case "$TARGET" in
+ssh:*) ssh "$HOST" "tar --keep-directory-symlink --no-same-owner -xzf - -C /" < "$TARBALL" ;;
+*)     tar --keep-directory-symlink -xzf "$TARBALL" -C "$ROOT" ;;
+esac
+
+# Releases on the target, highest version first (by name, not by date).
+releases="$(trun "ls -1 boot/$BOOT_SUBDIR 2>/dev/null" | sort -rV)"
+[ -n "$releases" ] || die "no kernels in /boot/$BOOT_SUBDIR on the target"
+
+# The last console= becomes /dev/console (emergency shell, init output). Keep
+# the serial console there even if KERNEL_CONSOLE is overridden in a different
+# order; the relative order of everything else is kept.
+console_args() {
+	local a serial="" rest=""
+	for a in $KERNEL_CONSOLE; do
+		case "$a" in
+		console=ttyS*) serial="${serial:+$serial }$a" ;;
+		*)             rest="${rest:+$rest }$a" ;;
+		esac
+	done
+	echo "$rest${rest:+${serial:+ }}$serial"
+}
+cmdline_console="$(console_args)"
+case "$cmdline_console" in
+*console=ttyS*) ;;
+*) echo "WARNING: no console=ttyS* in KERNEL_CONSOLE; no serial emergency console" >&2 ;;
+esac
+
+gen_extlinux() {
+	local r ov
+	echo "# Generated by install-kernel.sh ($BOARD_NAME) - rerun it to update."
+	echo "# Booted by mainline U-Boot; no initramfs."
+	echo "menu title $BOOT_MENU_TITLE"
+	echo "timeout 20"
+	echo "default $(head -1 <<<"$releases")"
+	for r in $releases; do
+		echo
+		echo "label $r"
+		echo "	kernel /boot/$BOOT_SUBDIR/$r/zImage"
+		echo "	fdt /boot/$BOOT_SUBDIR/$r/$BOOT_DTB"
+		if [ -n "$BOOT_OVERLAYS" ]; then
+			echo -n "	fdtoverlays"
+			for ov in $BOOT_OVERLAYS; do echo -n " /boot/$BOOT_SUBDIR/$r/overlay/$ov.dtbo"; done
+			echo
+		fi
+		echo "	append root=PARTUUID=$partuuid rootfstype=$fstype rootwait rw $cmdline_console panic=10 consoleblank=0 $KERNEL_CMDLINE_EXTRA"
+	done
+}
+
+trun 'mkdir -p boot/extlinux && { [ ! -f boot/extlinux/extlinux.conf ] || cp boot/extlinux/extlinux.conf boot/extlinux/extlinux.conf.bak; }'
+gen_extlinux | tput_file boot/extlinux/extlinux.conf
+trun 'sync'
+info "installed; /boot/extlinux/extlinux.conf:"
+trun 'cat boot/extlinux/extlinux.conf'

+ 235 - 0
lib/install-ubootenv.sh

@@ -0,0 +1,235 @@
+# Install method "ubootenv" (Banana Pi M2 Berry/Ultra), sourced by
+# install-kernel.sh.
+#
+# These boards boot from a hand-written U-Boot environment in /boot/uboot.env
+# (FAT, mmc 0:1): fatload a fixed uImage and DTB name, bootm, and on marlena
+# also apply an LED overlay. The environment is read, never changed:
+#   - every release goes to /boot/<subdir>/<release>/ (uImage, DTBs, overlays,
+#     config, System.map), so older ones stay loadable by hand;
+#   - the one to boot is copied over the files the environment loads
+#     (load_kernel, load_dt), after the previous ones were kept as
+#     uImage-<old release> / <dtb>.<old release> unless they are already in
+#     /boot/<subdir>/<old release>/;
+#   - modules to /lib/modules/<release>/.
+# /boot is noauto on these boards: it is mounted for the install and unmounted
+# again if it was not mounted before.
+#
+# Safety checks (ssh): Gentoo builds running (screen "profile23", emerge) stop
+# the install (FORCE_BUSY=1 overrides); a FAT dirty flag on /boot stops it
+# (FAT_DIRTY_OK=1 overrides); marlena's overlay must apply to the new DTB.
+# Settings: BOOT_DTB (our DTB to boot instead of the BOOT_DTB_MAP guess).
+# Provided by install-kernel.sh: TARGET, TARBALL, RELEASE, ROOT or HOST, trun,
+# tput_file.
+
+SUB="boot/$BOOT_SUBDIR"
+NEW="$SUB/$RELEASE"
+TMP="$(mktemp -d "${TMPDIR:-/tmp}/install-$BOARD.XXXXXX")"
+MOUNTED_BOOT=
+cleanup() {
+	if [ -n "$MOUNTED_BOOT" ]; then
+		info "unmounting /boot again"
+		trun 'sync; umount /boot' || echo "WARNING: could not unmount /boot on the target" >&2
+	fi
+	rm -rf "$TMP"
+}
+trap cleanup EXIT
+
+texists() { trun "test -e '$1'"; }
+
+# ---- 1. nothing else running that a reboot or a full /boot would hurt --------
+if [ -n "$HOST" ]; then
+	busy="$(trun 'screen -ls 2>/dev/null | grep -E "[.]profile23[[:space:]]"; pgrep -a -x emerge' || true)"
+	if [ -n "$busy" ]; then
+		echo "$busy" | sed 's/^/  /' >&2
+		[ "${FORCE_BUSY:-0}" = 1 ] ||
+			die "Gentoo builds are running on $HOST (above); install after they are done (FORCE_BUSY=1 overrides)"
+		echo "WARNING: builds running on $HOST; installing anyway (FORCE_BUSY=1)" >&2
+	fi
+fi
+
+# ---- 2. /boot: the FAT partition U-Boot reads -----------------------------------
+# Linux sets the FAT dirty flag itself while a volume is mounted read-write and
+# restores it on unmount, so the flag only tells something about an unmounted
+# volume. fat_dirty DEVICE: exit 0 if the flag is set.
+fat_dirty() {
+	trun "dd if='$1' bs=512 count=1 status=none" > "$TMP/bootsector"
+	python3 -I -c '
+import sys
+b = open(sys.argv[1], "rb").read()
+fat32 = b[82:90] == b"FAT32   "
+sys.exit(0 if b[0x41 if fat32 else 0x25] & 1 else 1)' "$TMP/bootsector"
+}
+fat_dirty_stop() {
+	[ "${FAT_DIRTY_OK:-0}" = 1 ] && { echo "WARNING: $1; going on (FAT_DIRTY_OK=1)" >&2; return 0; }
+	die "$1. Check it first: umount /boot; fsck.vfat -a $2 (sys-fs/dosfstools), or check the card on the PC. FAT_DIRTY_OK=1 overrides."
+}
+if [ -n "$HOST" ]; then
+	if trun 'mountpoint -q /boot'; then
+		bdev="$(trun 'findmnt -no SOURCE /boot')"
+		if trun "dmesg | grep -q 'FAT-fs (${bdev#/dev/}): Volume was not properly unmounted'"; then
+			fat_dirty_stop "/boot ($bdev) was not cleanly unmounted before it was mounted (dmesg)" "$bdev"
+		fi
+	else
+		bdev="$(trun 'findmnt -sno SOURCE /boot')"
+		[ -n "$bdev" ] || die "/boot is neither mounted nor in fstab on $HOST"
+		if fat_dirty "$bdev"; then
+			fat_dirty_stop "the FAT dirty flag is set on $bdev (/boot)" "$bdev"
+		fi
+		info "mounting /boot ($bdev)"
+		trun 'mount /boot'
+		MOUNTED_BOOT=1
+	fi
+else
+	findmnt -no TARGET "$ROOT/boot" | grep -qx "$ROOT/boot" ||
+		die "$ROOT/boot is not a mount point; mount the card's first (FAT) partition there"
+	bdev="$(findmnt -no SOURCE "$ROOT/boot")"
+fi
+if [ -n "$ROOT" ]; then bfs="$(findmnt -no FSTYPE "$ROOT/boot")"; else bfs="$(trun 'findmnt -no FSTYPE /boot')"; fi
+[ "$bfs" = vfat ] || die "/boot on the target is $bfs, not the FAT partition U-Boot reads"
+info "/boot: $bdev"
+
+# ---- 3. what the environment loads ------------------------------------------------
+texists "boot/$UBOOT_ENV_FILE" || die "no /boot/$UBOOT_ENV_FILE on the target; this install method needs its environment"
+trun "cat 'boot/$UBOOT_ENV_FILE'" > "$TMP/env"
+python3 -I "$TOP/lib/uboot-env.py" vars "$TMP/env" > "$TMP/env.txt" ||
+	die "/boot/$UBOOT_ENV_FILE has no valid CRC; U-Boot is not using it"
+envvar() { sed -n "s/^$1=//p" "$TMP/env.txt" | head -1; }
+# last word of the fatload command in a variable
+envfile() { envvar "$1" | sed -n 's/.*fatload mmc 0:1 [^ ;]* \([^ ;]*\).*/\1/p'; }
+distro="$(envvar distro_bootcmd)"
+kfile="$(envfile load_kernel)"
+dfile="$(envfile load_dt)"
+case "$distro" in *"run load_kernel"*) ;; *) die "distro_bootcmd ($distro) does not run load_kernel" ;; esac
+case "$distro" in *"run load_dt"*) ;; *) die "distro_bootcmd ($distro) does not run load_dt" ;; esac
+[ -n "$kfile" ] && [ -n "$dfile" ] || die "could not find the kernel/DTB names in load_kernel/load_dt"
+case "$(envvar boot_kernel)" in bootm*) ;; *) die "boot_kernel ($(envvar boot_kernel)) is not bootm; our image is a uImage" ;; esac
+ofile=
+case "$distro" in *"run load_overlay"*) ofile="$(envvar load_overlay | grep -o '[^ ;]*\.dtbo' | head -1)" ;; esac
+info "environment loads: kernel /boot/$kfile, DTB /boot/$dfile${ofile:+, overlay /boot/$ofile}"
+info "bootargs: $(envvar bootargs)"
+
+# Our DTB for this board: BOOT_DTB, or the first BOOT_DTB_MAP pattern that
+# matches the name the environment loads.
+dtb="$BOOT_DTB"
+if [ -z "$dtb" ]; then
+	for m in $BOOT_DTB_MAP; do
+		# shellcheck disable=SC2254 # the map holds glob patterns
+		case "$dfile" in ${m%%:*}) dtb="${m#*:}"; break ;; esac
+	done
+fi
+[ -n "$dtb" ] || die "don't know which DTB replaces $dfile; set BOOT_DTB to one of: $BOARD_DTBS"
+case " $BOARD_DTBS " in *" $dtb "*) ;; *) die "BOOT_DTB=$dtb is not one of ours ($BOARD_DTBS)" ;; esac
+info "booting $dtb (as /boot/$dfile)"
+
+# ---- 4. unpack the boot files here, test the overlay --------------------------
+tar xzf "$TARBALL" -C "$TMP" "$NEW"
+[ -f "$TMP/$NEW/uImage" ] && [ -f "$TMP/$NEW/$dtb" ] || die "$TARBALL lacks uImage or $dtb"
+if [ -n "$ofile" ]; then
+	texists "boot/$ofile" || die "the environment applies /boot/$ofile, which is missing; boot would fail"
+	trun "cat 'boot/$ofile'" > "$TMP/overlay.dtbo"
+	fdtoverlay -i "$TMP/$NEW/$dtb" -o "$TMP/overlay-test.dtb" "$TMP/overlay.dtbo" ||
+		die "/boot/$ofile does not apply to $dtb; a failed 'fdt apply' can break the boot. Remove 'run load_overlay;' from distro_bootcmd first"
+	info "/boot/$ofile applies to $dtb"
+fi
+
+# ---- 5. warnings about the running system -----------------------------------------
+# Working udev (kernel >= 5.10) names DT ethernet by its alias: end0, not eth0.
+if trun "grep -qE '^config_eth[0-9]+=' etc/conf.d/net 2>/dev/null" &&
+	! grep -q 'net.ifnames=0' <<<"$(envvar bootargs)" &&
+	! trun 'test -e etc/udev/rules.d/80-net-setup-link.rules || ls etc/systemd/network/*.link >/dev/null 2>&1'; then
+	cat >&2 <<-EOF
+	WARNING: /etc/conf.d/net configures eth0, but with this kernel udev works again and
+	  will most likely rename the interface to end0 (as on banana-backup), leaving
+	  the network unconfigured. Before rebooting, either rename the config to end0
+	  (config_end0, mac_end0, routes_end0, /etc/init.d/net.end0 in the runlevel) or
+	  keep the old name: ln -s /dev/null /etc/udev/rules.d/80-net-setup-link.rules
+	EOF
+fi
+
+# ---- 6. space on /boot --------------------------------------------------------------
+need_kb=$(( $(du -sk "$TMP/$NEW" | cut -f1) + $(du -k "$TMP/$NEW/uImage" | cut -f1) + 1024 ))
+free_kb="$(trun 'df -Pk boot | awk "NR==2 {print \$4}"')"
+[ "$free_kb" -gt "$need_kb" ] || die "/boot has $free_kb KiB free, $need_kb KiB needed; remove old releases from /boot/$BOOT_SUBDIR/"
+
+# ---- 7. keep what boots now ------------------------------------------------------------
+# The uImage header holds the release ("Linux-4.18.0-k4be") at offset 32.
+old_rel=
+if texists "boot/$kfile"; then
+	old_rel="$(trun "dd if='boot/$kfile' bs=32 skip=1 count=1 status=none" | tr -d '\0')"
+	case "$old_rel" in
+	Linux-*) old_rel="${old_rel#Linux-}" ;;
+	*) old_rel="unknown-$(date +%Y%m%d)" ;;
+	esac
+	old_rel="${old_rel//[^A-Za-z0-9._+-]/_}"
+fi
+roll_k=; roll_d=
+if [ -n "$old_rel" ] && [ "$old_rel" != "$RELEASE" ]; then
+	if texists "$SUB/$old_rel/uImage"; then
+		roll_k="$BOOT_SUBDIR/$old_rel/uImage"
+	else
+		texists "boot/$kfile-$old_rel" || trun "cp 'boot/$kfile' 'boot/$kfile-$old_rel'"
+		roll_k="$kfile-$old_rel"
+	fi
+	if texists "boot/$dfile"; then
+		if texists "$SUB/$old_rel/$dtb" && trun "cmp -s 'boot/$dfile' '$SUB/$old_rel/$dtb'"; then
+			roll_d="$BOOT_SUBDIR/$old_rel/$dtb"
+		else
+			texists "boot/$dfile.$old_rel" || trun "cp 'boot/$dfile' 'boot/$dfile.$old_rel'"
+			roll_d="$dfile.$old_rel"
+		fi
+	fi
+	info "kept the current kernel ($old_rel): /boot/$roll_k, /boot/$roll_d"
+fi
+# Reinstalling the release that is already in place: the way back is the
+# newest older release in /boot/<subdir>/, else the newest kept original.
+if [ -z "$roll_k" ]; then
+	prev="$(trun "ls -1 '$SUB' 2>/dev/null" | grep -vx "$RELEASE" | sort -V | tail -1 || true)"
+	if [ -n "$prev" ]; then
+		roll_k="$BOOT_SUBDIR/$prev/uImage"; roll_d="$BOOT_SUBDIR/$prev/$dtb"
+	else
+		prev="$(trun 'ls -1 boot' | sed -n "s/^$kfile-//p" | sort -V | tail -1 || true)"
+		if [ -n "$prev" ]; then roll_k="$kfile-$prev"; roll_d="$dfile.$prev"; fi
+	fi
+fi
+
+# ---- 8. install -----------------------------------------------------------------------------
+info "copying /$NEW/"
+trun "mkdir -p '$NEW/overlay'"
+(cd "$TMP" && find "$NEW" -type f) | while read -r f; do
+	tput_file "$f" < "$TMP/$f"
+done
+info "modules to /lib/modules/$RELEASE/"
+if [ -n "$HOST" ]; then
+	ssh "$HOST" "tar --keep-directory-symlink --no-same-owner -xzf - -C / lib" < "$TARBALL"
+else
+	for p in lib lib/modules "lib/modules/$RELEASE"; do
+		r="$(realpath -m -- "$ROOT/$p")"
+		case "$r" in "$ROOT"/*) ;; *) die "/$p on the target resolves to $r, outside $ROOT; not writing there" ;; esac
+	done
+	tar --keep-directory-symlink -xzf "$TARBALL" -C "$ROOT" lib
+fi
+trun "sync"
+info "switching /boot/$kfile and /boot/$dfile to $RELEASE"
+trun "cp '$NEW/uImage' 'boot/$kfile.new' && mv -f 'boot/$kfile.new' 'boot/$kfile'"
+trun "cp '$NEW/$dtb' 'boot/$dfile.new' && mv -f 'boot/$dfile.new' 'boot/$dfile'"
+trun "sync"
+
+# verify what U-Boot will read
+want="$(cd "$TMP/$NEW" && md5sum uImage "$dtb" | cut -d' ' -f1)"
+have="$(trun "md5sum 'boot/$kfile' 'boot/$dfile'" | cut -d' ' -f1)"
+[ "$want" = "$have" ] || die "/boot/$kfile or /boot/$dfile does not match the build after copying"
+info "verified: /boot/$kfile and /boot/$dfile are $RELEASE"
+
+echo
+info "installed $RELEASE ($BOARD_NAME). Not rebooted."
+info "releases in /boot/$BOOT_SUBDIR/: $(trun "ls -1 '$SUB'" | sort -V | tr '\n' ' ')"
+cat <<EOF
+Rollback from the U-Boot prompt (serial console, stop autoboot):
+  fatload mmc 0:1 0x47000000 ${roll_k:-<old uImage>}
+  fatload mmc 0:1 0x43000000 ${roll_d:-<old dtb>}
+EOF
+[ -z "$ofile" ] || echo "  fdt addr 0x43000000; fdt resize; fatload mmc 0:1 0x4300F000 $ofile; fdt apply 0x4300F000"
+cat <<EOF
+  bootm 0x47000000 - 0x43000000
+then, once booted, copy the old files back over /boot/$kfile and /boot/$dfile.
+EOF

+ 65 - 0
lib/uboot-env.py

@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""Read a U-Boot environment file (uboot.env, non-redundant format).
+
+Format: 4-byte little-endian CRC32 of the data area, then NUL-terminated
+"name=value" strings, ended by an empty string. U-Boot reads CONFIG_ENV_SIZE
+bytes and computes the CRC over all of them but the first 4, so the file is
+only accepted by a U-Boot built with the size it was saved with.
+
+Usage:
+  uboot-env.py check FILE ENV_SIZE   exit 0 if a U-Boot with this
+                                     CONFIG_ENV_SIZE accepts FILE, else 1
+  uboot-env.py size FILE             print the size the CRC is valid for
+                                     (empty and exit 1 if none)
+  uboot-env.py vars FILE             print name=value per line (newlines in
+                                     values become spaces); exit 1 if no size
+                                     validates the CRC
+"""
+import struct
+import sys
+import zlib
+
+
+def crc_ok(data, size):
+    if len(data) < size or size <= 4:
+        return False
+    return zlib.crc32(data[4:size]) == struct.unpack("<I", data[:4])[0]
+
+
+def valid_size(data):
+    size = 0x1000
+    while size <= 0x100000:
+        if crc_ok(data, size):
+            return size
+        size *= 2
+    return None
+
+
+def main(argv):
+    if len(argv) < 3:
+        sys.stderr.write(__doc__)
+        return 2
+    cmd, path = argv[1], argv[2]
+    with open(path, "rb") as f:
+        data = f.read()
+    if cmd == "check":
+        return 0 if crc_ok(data, int(argv[3], 0)) else 1
+    size = valid_size(data)
+    if cmd == "size":
+        if size is None:
+            return 1
+        print(hex(size))
+        return 0
+    if cmd == "vars":
+        area = data[4:size] if size else data[4:]
+        for entry in area.split(b"\0"):
+            if not entry:
+                break
+            print(entry.decode("latin-1").replace("\n", " "))
+        return 0 if size else 1
+    sys.stderr.write(__doc__)
+    return 2
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv))

+ 69 - 0
select-board.sh

@@ -0,0 +1,69 @@
+#!/bin/bash
+# Pick the board type every other script builds and installs for. The choice is
+# kept in .board; each script prints it first. BOARD=<id> in the environment
+# overrides it for a single command.
+#
+# Usage: ./select-board.sh            menu
+#        ./select-board.sh <id>       select directly (scripts, ssh without tty)
+#        ./select-board.sh -l         list board types, mark the selected one
+set -euo pipefail
+CONFIG_NO_BOARD=1 . "$(dirname "$0")/config.sh"
+
+current="$(cat "$BOARD_SELECTION" 2>/dev/null || true)"
+mapfile -t ids < <(list_boards | cut -f1)
+mapfile -t names < <(list_boards | cut -f2)
+[ ${#ids[@]} -gt 0 ] || die "no board files in $BOARDS_DIR"
+
+describe() { # describe ID
+	local i
+	for i in "${!ids[@]}"; do
+		[ "${ids[$i]}" != "$1" ] || { echo "${names[$i]} [$1]"; return; }
+	done
+	echo "$1"
+}
+
+set_board() {
+	local id="$1" i
+	for i in "${ids[@]}"; do
+		if [ "$i" = "$id" ]; then
+			echo "$id" > "$BOARD_SELECTION"
+			info "board type: $(describe "$id")"
+			info "build output goes to out/$id/, configuration from boards/$id.sh and files/$id/"
+			return 0
+		fi
+	done
+	die "unknown board type '$id' (known: ${ids[*]})"
+}
+
+case "${1:-}" in
+-l|--list)
+	for i in "${!ids[@]}"; do
+		mark=" "; [ "${ids[$i]}" != "$current" ] || mark="*"
+		printf '%s %-8s %s\n' "$mark" "${ids[$i]}" "${names[$i]}"
+	done
+	exit 0 ;;
+-h|--help)
+	sed -n '2,10s/^# \{0,1\}//p' "$0"; exit 0 ;;
+"") ;;
+*)  set_board "$1"; exit 0 ;;
+esac
+
+[ -t 0 ] || die "no terminal for the menu; give the board id: $0 <$(IFS='|'; echo "${ids[*]}")>"
+cur_desc=none; [ -z "$current" ] || cur_desc="$(describe "$current")"
+echo "Current board type: $cur_desc"
+echo "Select the board type:"
+labels=()
+for i in "${!ids[@]}"; do
+	mark=""; [ "${ids[$i]}" != "$current" ] || mark="  (current)"
+	labels+=("${names[$i]} [${ids[$i]}]$mark")
+done
+PS3="Number (Ctrl-D to keep the current one): "
+select _ in "${labels[@]}"; do
+	if [ -n "${REPLY:-}" ] && [ "$REPLY" -ge 1 ] 2>/dev/null && [ "$REPLY" -le ${#ids[@]} ]; then
+		set_board "${ids[$((REPLY - 1))]}"
+		exit 0
+	fi
+	echo "Pick 1-${#ids[@]}."
+done
+echo
+info "unchanged: $cur_desc"

+ 51 - 10
write-uboot.sh

@@ -1,9 +1,15 @@
 #!/bin/bash
-# Write out/u-boot/u-boot-sunxi-with-spl.bin to an SD card (or image file) at
-# 8 KiB, where the H2+ boot ROM looks for the SPL. The partition table and
-# the partitions are not touched. The area about to be overwritten (8 KiB up
-# to 1 MiB, or to the first partition if that is lower) is saved to
-# out/backup/ first, so the old bootloader can be put back.
+# Write out/<board>/u-boot/u-boot-sunxi-with-spl.bin of the selected board type
+# (./select-board.sh) to an SD card (or image file) at 8 KiB, where the sunxi
+# boot ROM looks for the SPL. The partition table and the partitions are not
+# touched. The area about to be overwritten (8 KiB up to 1 MiB, or to the
+# first partition if that is lower) is saved to out/backup/ first, so the old
+# bootloader can be put back.
+#
+# Boards whose U-Boot keeps its environment in uboot.env on the FAT partition
+# (bpi-m2: the boot commands live only there) are checked first: the target's
+# file must pass the CRC check for this build's CONFIG_ENV_SIZE, otherwise
+# U-Boot would ignore it and not find the kernel.
 #
 # Usage:
 #   sudo ./write-uboot.sh /dev/sdX            card in a USB reader on this PC
@@ -19,6 +25,8 @@
 #   DEV=/dev/xxx   ssh: the card's device on the board (default: the disk
 #                  that holds the board's root filesystem)
 #   NO_BACKUP=1    don't save the old area first
+#   ENV_CHECK_SKIP=1  don't check the target's uboot.env (FAT-environment boards)
+#   FORCE=1        also: write over ssh to a board of another type
 set -euo pipefail
 . "$(dirname "$0")/config.sh"
 
@@ -33,8 +41,8 @@ END_KIB=$(( (END + 1023) / 1024 ))   # rounded up, for messages
 # environment slot older U-Boots used at 544 KiB fit well below it).
 BACKUP_END_KIB=1024
 # Where 2019-era sunxi U-Boot (e.g. Armbian's 2019.04) kept a raw-MMC
-# environment: CONFIG_ENV_OFFSET=0x88000, 128 KiB.
-OLD_ENV_KIB=544
+# environment (boards/<board>.sh; empty: no such area).
+OLD_ENV_KIB=${UBOOT_OLD_RAW_ENV_KIB:-0}
 
 confirm() {
 	[ "${YES:-0}" = 1 ] && return 0
@@ -49,12 +57,13 @@ confirm() {
 check_env() {
 	local cfg="$OUT/ubuild/.config" off
 	[ -z "${UBOOT_BIN:-}" ] && [ -f "$cfg" ] || return 0
+	[ -n "$UBOOT_OLD_RAW_ENV_KIB" ] || OLD_ENV_KIB=0
 	if grep -qx 'CONFIG_ENV_IS_IN_MMC=y' "$cfg"; then
 		off=$(( $(sed -n 's/^CONFIG_ENV_OFFSET=//p' "$cfg") ))
 		[ "$END" -le "$off" ] ||
 			die "U-Boot would end at $END_KIB KiB, past its own MMC environment at $(( off / 1024 )) KiB; make CONFIG_ENV_OFFSET larger or the image smaller"
 	fi
-	if [ "$END" -gt $(( OLD_ENV_KIB * 1024 )) ]; then
+	if [ "$OLD_ENV_KIB" -gt 0 ] && [ "$END" -gt $(( OLD_ENV_KIB * 1024 )) ]; then
 		echo "note: U-Boot ends at $END_KIB KiB ($END bytes), past ${OLD_ENV_KIB} KiB where the old Armbian U-Boot kept its environment; this U-Boot does not read it there, and the backup keeps the old one"
 	fi
 }
@@ -82,7 +91,7 @@ backup_kib() {
 backup() {
 	local name="$1" kib="$2"; shift 2
 	if [ "${NO_BACKUP:-0}" = 1 ]; then echo "backup skipped (NO_BACKUP=1)"; return 0; fi
-	local dir="$OUT/backup"
+	local dir="$BACKUP_DIR"
 	local f; f="$dir/u-boot-area-${name//[^A-Za-z0-9._-]/_}-$(date +%Y%m%d-%H%M%S).bin"
 	mkdir -p "$dir"
 	"$@" > "$f" || die "could not read the old area for the backup"
@@ -93,6 +102,21 @@ backup() {
 	echo "  restore: UBOOT_BIN=$f $0 $TARGET"
 }
 
+# check_fat_env FILE WHERE: FILE is the target's uboot.env; die unless this
+# U-Boot accepts it (CRC over CONFIG_ENV_SIZE bytes).
+check_fat_env() {
+	local f="$1" where="$2" cfg="$OUT/ubuild/.config" size
+	size="$(sed -n 's/^CONFIG_ENV_SIZE=//p' "$cfg" 2>/dev/null)"
+	[ -n "$size" ] || die "no CONFIG_ENV_SIZE in $cfg; build U-Boot first (or ENV_CHECK_SKIP=1 with UBOOT_BIN)"
+	[ -s "$f" ] || die "$where has no $UBOOT_ENV_FILE: U-Boot would start with its default environment and not find the kernel (ENV_CHECK_SKIP=1 overrides)"
+	if python3 -I "$TOP/lib/uboot-env.py" check "$f" "$size"; then
+		echo "$where: $UBOOT_ENV_FILE is valid for CONFIG_ENV_SIZE=$size: OK"
+		python3 -I "$TOP/lib/uboot-env.py" vars "$f" | grep -E '^(bootcmd|distro_bootcmd)=' | sed 's/^/  /'
+	else
+		die "$where: $UBOOT_ENV_FILE ($(python3 -I "$TOP/lib/uboot-env.py" size "$f" || echo "no valid CRC")) does not pass the CRC check of this U-Boot (CONFIG_ENV_SIZE=$size); it would boot the default environment. Fix files/$BOARD/u-boot.config (ENV_CHECK_SKIP=1 overrides)"
+	fi
+}
+
 first_start() { sfdisk -d "$1" 2>/dev/null | sed -n 's/.*start= *\([0-9]*\).*/\1/p' | head -1; }
 
 check_env
@@ -106,7 +130,17 @@ ssh:*)
 	# apply here: this is the board's own boot card by definition.
 	dev="${DEV:-$(ssh "$host" 'p=$(lsblk -no PKNAME "$(findmnt -no SOURCE /)" | head -1); [ -n "$p" ] && echo "/dev/$p"')}"
 	[ -n "$dev" ] || die "could not find the board's root disk; set DEV=/dev/mmcblkN"
+	compat="$(ssh "$host" 'tr "\0" "\n" < /proc/device-tree/compatible' 2>/dev/null || true)"
+	grep -qx "$BOARD_DT_COMPAT" <<<"$compat" || [ "${FORCE:-0}" = 1 ] ||
+		die "$host is not a $BOARD_NAME (compatible: $(echo $compat)); select its board type with ./select-board.sh (FORCE=1 overrides)"
 	info "card in $host: $dev"
+	if [ "$UBOOT_ENV_FAT" = 1 ] && [ "${ENV_CHECK_SKIP:-0}" != 1 ]; then
+		envf="$(mktemp)"
+		# /boot may be noauto: mount it read-only just for reading
+		ssh "$host" "if mountpoint -q /boot; then cat /boot/$UBOOT_ENV_FILE; else mount -o ro /boot && { cat /boot/$UBOOT_ENV_FILE; umount /boot; }; fi" > "$envf" || true
+		( check_fat_env "$envf" "$host:/boot" ) || { rm -f "$envf"; exit 1; }
+		rm -f "$envf"
+	fi
 	ssh "$host" "cat /proc/device-tree/model 2>/dev/null; echo; lsblk -o NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS $dev; echo \"device type: \$(cat /sys/block/${dev#/dev/}/device/type 2>/dev/null || echo unknown)\""
 	start=$(ssh "$host" "sfdisk -d $dev 2>/dev/null | sed -n 's/.*start= *\([0-9]*\).*/\1/p' | head -1")
 	check_gap "$start"
@@ -136,6 +170,12 @@ ssh:*)
 		die "$TARGET is neither removable, hotplug nor an SD card${mmc_type:+ (MMC type: $mmc_type)}; set FORCE=1 if this really is the card"
 	fi
 	lsblk -o NAME,SIZE,TYPE,FSTYPE,LABEL,MOUNTPOINTS,MODEL "$TARGET"
+	if [ "$UBOOT_ENV_FAT" = 1 ] && [ "${ENV_CHECK_SKIP:-0}" != 1 ]; then
+		p1="$(lsblk -lnpo NAME,TYPE "$TARGET" | awk '$2 == "part" { print $1; exit }')"
+		mp="$(lsblk -no MOUNTPOINT "$p1" 2>/dev/null | head -1)"
+		[ -n "$mp" ] || die "mount the card's first partition ($p1, read-only is fine) so its $UBOOT_ENV_FILE can be checked (ENV_CHECK_SKIP=1 overrides)"
+		check_fat_env "$mp/$UBOOT_ENV_FILE" "$p1"
+	fi
 	start=$(first_start "$TARGET")
 	check_gap "$start"
 	confirm "$TARGET"
@@ -146,6 +186,7 @@ ssh:*)
 	;;
 *)
 	[ -f "$TARGET" ] || die "$TARGET: no such image file"
+	[ "$UBOOT_ENV_FAT" != 1 ] || echo "note: $UBOOT_ENV_FILE in the image is not checked; make sure it suits CONFIG_ENV_SIZE"
 	start=$(first_start "$TARGET")
 	check_gap "$start"
 	confirm "$TARGET"
@@ -154,4 +195,4 @@ ssh:*)
 	dd if="$BIN" of="$TARGET" bs=1024 seek="$UBOOT_SEEK_KIB" conv=notrunc,fsync status=none
 	;;
 esac
-info "U-Boot written to $TARGET"
+info "U-Boot ($BOARD_NAME) written to $TARGET; it is used from the next reboot on"