Browse Source

Orange Pi Zero kernel and U-Boot build tools with documentation

k4be 2 weeks ago
commit
7585ca3702
11 changed files with 1549 additions and 0 deletions
  1. 4 0
      .gitignore
  2. 56 0
      NOTES.md
  3. 401 0
      README.md
  4. 225 0
      build-kernel.sh
  5. 72 0
      build-uboot.sh
  6. 105 0
      config.sh
  7. 141 0
      files/dts/sun8i-h2-plus-orangepi-zero-radio.dts
  8. 215 0
      files/kernel.config
  9. 5 0
      files/u-boot.config
  10. 168 0
      install-kernel.sh
  11. 157 0
      write-uboot.sh

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+/dl/
+/src/
+/out/
+/mnt/

+ 56 - 0
NOTES.md

@@ -0,0 +1,56 @@
+# Notes: planned and open
+
+## Solar boards: their own DTS (planned)
+
+`solar1.lo` and `solar2.lo` are Orange Pi Zeros without the radio panel (see
+"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
+  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`.
+- 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=…`.
+
+## Automatic fallback to the previous kernel (idea)
+
+Right now a kernel that fails to boot is booted again on every reset (see
+"If a new kernel does not boot" in the README). For an unattended radio:
+
+- U-Boot `CONFIG_BOOTCOUNT_LIMIT` with a counter that survives a watchdog
+  reset. `BOOTCOUNT_ENV` needs `saveenv`, and there is no FAT partition for
+  `uboot.env`. Better: `BOOTCOUNT_GENERIC` in one of the RTC's
+  general-purpose registers (H3 RTC base 0x01f00000, GP registers from
+  0x100), which keep their value over a reset.
+- `bootlimit=3` and an `altbootcmd` that boots the second-newest extlinux
+  label. `sysboot`/`pxe` has no "boot label N" option, so it needs a second
+  file (e.g. `extlinux/fallback.conf`, generated by `install-kernel.sh` with
+  the previous release as `default`), loaded with
+  `sysboot mmc 0:1 any ${scriptaddr} /boot/extlinux/fallback.conf`.
+- Userspace must reset the counter once the system is up: a small systemd
+  unit that writes 0 to that register (via `/dev/mem` or `devmem2`) after
+  `multi-user.target`, and systemd's `RuntimeWatchdogSec=` on the sunxi
+  watchdog so a hang also counts as a failed boot.
+- Needs testing on the hardware with the serial console attached.
+
+## radio-ui and tty1 (radio-ui repository)
+
+radio-ui should switch its VT to `KD_GRAPHICS` (`ioctl(fd, KDSETMODE,
+KD_GRAPHICS)` on `/dev/tty1` or the active VT) while it owns the panel and
+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.
+
+## Untested
+
+- Armbian's `boot.scr` under the new U-Boot (fallback when `extlinux.conf`
+  is missing).
+- journald forwarding to tty1 while radio-ui owns the display.

+ 401 - 0
README.md

@@ -0,0 +1,401 @@
+# Orange Pi Zero (original, H2+): 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`.
+
+| | 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 |
+
+Versions, toolchain (`armv7a-hardfloat-linux-gnueabi-`) and boot settings are in
+`config.sh`. Any of them can be overridden from the environment.
+
+## Building
+
+    ./build-uboot.sh        # -> out/u-boot/u-boot-sunxi-with-spl.bin
+    ./build-kernel.sh       # -> out/opi0-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 modules and packs the tarball). Subcommands:
+
+| | `build-uboot.sh` | `build-kernel.sh` |
+|---|---|---|
+| `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 |
+| `package` | | only stage and pack the tarball |
+| `clean` | remove `out/ubuild`, `out/u-boot` | remove `out/kbuild`, `out/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).
+
+### Host tools
+
+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)
+- 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
+  `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.
+
+## Installing
+
+### Bootloader
+
+Card in a reader on this PC, or in the running board:
+
+    sudo ./write-uboot.sh /dev/sdX        # USB card reader
+    sudo ./write-uboot.sh /dev/mmcblkN    # built-in SD slot
+    ./write-uboot.sh ssh:root@radio.lo
+
+The image goes to 8 KiB, where the boot ROM looks for the SPL, and ends where
+the image ends (currently about 545 KiB). The partition table and the
+partitions are not touched; the script refuses an image that would reach the
+first partition (Armbian's starts at 4 MiB).
+
+Before writing, the script saves the area it is about to overwrite (8 KiB up
+to 1 MiB, or up to the first partition if that is lower) to
+`out/backup/u-boot-area-<device>-<date>.bin` and prints the restore command:
+
+    UBOOT_BIN=out/backup/u-boot-area-sdb-20261114-180000.bin sudo ./write-uboot.sh /dev/sdX
+
+That puts back exactly what was there, Armbian U-Boot and old environment
+included. Without a backup, Armbian's own bootloader is still on the rootfs,
+under `/usr/lib/linux-u-boot-*/` (package `linux-u-boot-*`). Copy it to the
+PC and write it the same way (`UBOOT_BIN` is always a file on the PC, also
+in `ssh:` mode):
+
+    scp root@radio.lo:'/usr/lib/linux-u-boot-*/u-boot-sunxi-with-spl.bin' armbian-u-boot.bin
+    UBOOT_BIN=armbian-u-boot.bin ./write-uboot.sh ssh:root@radio.lo
+
+Safety checks for `/dev/…` targets: the device must be a whole disk, must not
+hold a filesystem this PC is using (`/`, `/boot`, `/usr`, `/var`, `/home`,
+swap), and must look like an SD card: removable, hotplug, or reported as an SD
+card by the MMC core. Card readers in laptops (`/dev/mmcblk*`, SDHCI) usually
+report removable=0, so the last rule is what accepts them; soldered eMMC
+reports type `MMC` and is refused. `FORCE=1` overrides that check only.
+
+In `ssh:` mode the script writes to the disk holding the board's root
+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
+
+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
+U-Boot at 536 KiB. Mainline sunxi U-Boot no longer does: this build has
+`CONFIG_ENV_IS_IN_MMC` off and keeps the environment in `uboot.env` on the
+first FAT partition of the boot card (`CONFIG_ENV_IS_IN_FAT`). The image is
+already a little over 536 KiB, and that is fine:
+
+- An environment that an earlier `saveenv` left at 544 KiB is never read by
+  the new U-Boot, so its old `bootcmd`/distro-boot variables cannot leak into
+  bootstd. Writing the new U-Boot also overwrites the start of it, so it is
+  dead; the backup keeps a copy.
+- Armbian's rootfs has no FAT partition, so the new U-Boot always starts with
+  its built-in default environment and `saveenv` fails. That is intended:
+  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
+  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
+
+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
+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
+previous copy is kept as `.bak`).
+
+When installing into a mounted card, the script never writes through an
+absolute symlink (or a `..` link out of the mount): bookworm's merged-/usr
+`lib -> usr/lib` is relative and fine, but `lib -> /usr/lib` would resolve to
+this PC's own `/usr/lib`, so the script stops instead.
+
+Every release in `/boot/opi0/` gets a menu entry, highest version first. The
+order is `sort -V` on the release name, not file dates, and the highest is
+the default. Root is given as `root=PARTUUID=…`, which the script finds
+itself; without an initramfs, `UUID=` would not work. The default setup
+generates:
+
+    menu title Orange Pi Zero
+    timeout 20
+    default 7.3.4-opi0
+
+    label 7.3.4-opi0
+    	kernel /boot/opi0/7.3.4-opi0/zImage
+    	fdt /boot/opi0/7.3.4-opi0/sun8i-h2-plus-orangepi-zero-radio.dtb
+    	append root=PARTUUID=<partuuid> rootfstype=ext4 rootwait rw console=tty1 fbcon=font:6x8 vt.default_red=… vt.default_grn=… vt.default_blu=… console=ttyS0,115200 panic=10 consoleblank=0 usb-storage.quirks=0x2537:0x1066:u,0x2537:0x1068:u
+
+`timeout 20` is in tenths of a second: the menu waits 2 s on the serial
+console. Root is mounted `rw` directly; there is no initramfs to fsck it
+first, and Armbian's fstab remounts it with its own options anyway.
+`panic=10` reboots 10 s after a panic.
+
+To delete an old release, remove it on the target and reinstall, so the menu
+is regenerated:
+
+    ssh root@radio.lo 'rm -r /boot/opi0/7.2.9-opi0 /lib/modules/7.2.9-opi0'
+    ./install-kernel.sh ssh:root@radio.lo
+
+Do not remove the release that is running or the only one that is known to
+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
+after 10 s into the same entry again. On the unattended radio, the way back is
+the card: mount it on the PC, delete the bad `/boot/opi0/<release>/` and run
+`install-kernel.sh` on the mount again, or edit `default` in `extlinux.conf`.
+An automatic fallback (U-Boot bootcount with the watchdog) is not set up yet;
+see `NOTES.md`.
+
+### 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
+board boots it even before the new U-Boot is written. Remove or rename
+`/boot/extlinux/extlinux.conf` and it boots Armbian's `boot.scr` again.
+
+That old U-Boot predates `fdtoverlays` support in extlinux (added in U-Boot
+2021.01), so it ignores the `fdtoverlays` line: anything in `BOOT_OVERLAYS` is
+silently left out until the new U-Boot is written. The board DTB itself does
+not depend on overlays.
+
+With the **new** U-Boot: without `extlinux.conf` it falls back to the
+distro-boot script scan and runs Armbian's `/boot/boot.scr`. Nobody has tested
+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
+
+Some Armbian packages can undo this setup. `install-kernel.sh` warns about
+them, but changes nothing:
+
+- `linux-image-*`, `linux-dtb-*`, `linux-u-boot-*`: put them on hold (or
+  remove them), otherwise an upgrade refreshes Armbian's boot files and,
+  depending on the package version, writes its own U-Boot back to the card:
+
+      apt-mark hold linux-image-current-sunxi linux-dtb-current-sunxi linux-u-boot-orangepizero-current
+
+  (`dpkg -l 'linux-*'` shows the exact names).
+- `armbian-firmware` provides `/lib/firmware/xr819/*`. Keep it: without it the
+  XR819 Wi-Fi does not come up.
+- `u-boot-menu` must not be installed: it rewrites
+  `/boot/extlinux/extlinux.conf` on every kernel package change.
+- `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`.
+
+## What is in the build
+
+`files/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
+  former Armbian overlays `analog-codec`, `usbhost2`, `usbhost3`
+- i2c1 (PA18/PA19) at 400 kHz: the former `i2c1` and `i2c1-400k` overlays.
+  An `i2c1` alias keeps it at `/dev/i2c-1` (without one it would be `i2c-0`).
+  400 kHz relies on the pull-ups on the panel board: no SoC pull-up is enabled
+  on these pins, and the internal ones would be too weak for that speed.
+- the radio panel `panel@74` (`k4be,s1d13700-tca9539`) on i2c1. `k4be` is not
+  a registered vendor prefix, so `make dtbs_check` warns about this node;
+  that is expected.
+- the key expander U2 `gpio@76` (`ti,tca9539`) on i2c1, INT on PA6/PWM1
+  (level low, SoC pull-up on), and a `gpio-keys` device named `radio-keys`
+  with the 13 keys. s1d13700-tca's `dts/radio-panel.dts` has the same table.
+  It avoids `#include` so that it also works with `armbian-add-overlay`, so
+  the two files cannot share a `.dtsi`. Instead `build-kernel.sh` compares the
+  compiled tables (label, U2 pin, flags, key code) and stops if they differ.
+- `compatible = "xradio,xr819"` and the PG10 host-wake interrupt, which the
+  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
+(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`:
+
+- 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
+  mainline board file) and sun8i-thermal: the H2+ runs hot, so it must be able
+  to scale down
+- the sunxi watchdog and the sun6i RTC
+- `FONT_6x8` for `fbcon=font:6x8`
+
+### Drivers for the radio panel (`$PANEL_DIR`, default `/home/k4be/git/radio/s1d13700-tca`)
+
+The panel driver and its overlay come from the s1d13700-tca repository. The
+application on the board, radio-ui (`/home/k4be/git/radio/radio-ui`, with
+s1d13700-tca as a submodule), is not built here.
+
+- `s1d13700-tca` DRM driver: copied from `$PANEL_DIR/driver` into
+  `drivers/gpu/drm/tiny/s1d13700-tca/` on every build and **built in**, so
+  fbcon shows the boot log on the panel (40×20 characters). When
+  `radio-ui drm` starts, it takes over the display. Module parameters become
+  kernel arguments, e.g. `s1d13700_tca.tcr=162` in `KERNEL_CMDLINE_EXTRA`.
+- gpio-pca953x (TCA9539, with IRQ) and gpio-keys, built in. `radio-ui drm`
+  finds the `radio-keys` evdev device by itself.
+- i2c-dev, i2c-tiny-usb, gpio-keys-polled, evdev, uinput, backlight class
+- s1d13700-tca's `dts/*.dts` overlays are compiled into
+  `/boot/opi0/<release>/overlay/` and can be enabled with `BOOT_OVERLAYS`.
+  They aren't needed: the board DTB already has everything. `radio-panel`
+  would add a second panel and U2 on i2c0.
+
+The driver also registers the panel's backlight as
+`/sys/class/backlight/radio-backlight` (brightness 0 or 1, on at boot), and
+`radio-ui drm` switches it off after 30 s without a key press. The sysfs file
+is `root:root 0644` and radio-ui runs as an ordinary user, so the write fails.
+radio-ui ignores that error and the backlight just stays on. A udev rule on the
+target gives the `video` group write access, e.g.
+`/etc/udev/rules.d/70-radio-backlight.rules`:
+
+    ACTION=="add", SUBSYSTEM=="backlight", KERNEL=="radio-backlight", RUN+="/bin/chgrp video /sys%p/brightness", RUN+="/bin/chmod g+w /sys%p/brightness"
+
+The user needs to be in `video` (Armbian's default user is). Likewise,
+`/dev/input/event*` is `root:input 0660`, so reading `radio-keys` (radio-ui,
+`evtest`) needs the `input` group: `usermod -aG input <user>`.
+
+Because the kernel owns 0x74 and 0x76, the i2c-dev frontends (`radio-ui i2c`,
+the polling U2 code, most `hw_test.sh` modes) refuse to run on the target
+until the drivers are unbound. Unbind gpio-keys first, since it holds U2's
+GPIOs, then the expander, then the panel:
+
+    echo radio-keys > /sys/bus/platform/drivers/gpio-keys/unbind
+    echo 1-0076 > /sys/bus/i2c/drivers/pca953x/unbind
+    echo 1-0074 > /sys/bus/i2c/drivers/s1d13700-tca/unbind
+
+Bind them again in reverse order (`…/bind`), or reboot.
+
+Kernel 7.3 renamed `struct drm_atomic_state` to `struct drm_atomic_commit`.
+The radio sources use the old name, only as the argument type of the atomic
+hooks, and are not modified. Instead, the generated in-tree Makefile forces a
+generated `s1d13700_compat.h` into `s1d13700_drm.c` only (`-include`). For
+kernels ≥ 7.3 that header first includes the DRM headers the driver uses, and
+only then maps the old name to the new one. So the rename applies to the
+driver's own code and never inside a kernel header. It also checks that
+`struct drm_atomic_commit` really is the complete new type. If the driver
+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
+
+The kernel command line has `console=tty1` (the panel, through fbcon)
+followed by `console=ttyS0,115200`. Kernel messages go to both. The last
+`console=` becomes `/dev/console`, which is where init's output, the systemd
+`[  OK  ]` status lines, and the emergency/rescue shell go. So systemd's boot
+output only appears on the serial port. Serial comes last on purpose: the
+panel has keys but no keyboard, so a shell or a "Give root password" prompt
+there would be useless, while the UART header is an emergency console when ssh
+does not work. If `KERNEL_CONSOLE` is overridden, `install-kernel.sh` moves
+its `console=ttyS*` entry to the end, and warns if there is none.
+
+The panel driver maps white to "pixel off", the light background of the
+LCD, so fbcon's usual light grey on black would look inverted.
+`KERNEL_CONSOLE` therefore also sets `vt.default_red/grn/blu`: the VGA
+palette inverted, with the background (entry 0) white and normal and bold
+text (7 and 15) black. Other colours stay distinct gray levels. This only
+affects text VTs, not radio-ui.
+
+Armbian's `console-setup` loads the font from `/etc/default/console-setup`
+(`FONTFACE="Fixed"`, `FONTSIZE="8x16"`) about 10 s into boot, from
+`console-setup.service` and from a udev rule. That replaces the kernel's 6×8
+font and leaves 10 lines on the panel. To keep the kernel font (40×20), on
+the target clear both settings:
+
+    sed -i 's/^FONTFACE=.*/FONTFACE=""/; s/^FONTSIZE=.*/FONTSIZE=""/' /etc/default/console-setup
+
+With both empty, `setupcon` leaves the font alone and still sets up the
+keymap and charmap. To use a font from the rootfs instead,
+`FONTFACE="Terminus"` with `FONTSIZE="6x12"` (width×height; the file is
+`Terminus12x6`) gives 40×13 and better Unicode coverage than the kernel's
+CP437 font.
+
+For a userspace log on the panel too, the usual workaround is journald on the
+rootfs: `ForwardToConsole=yes`, `TTYPath=/dev/tty1`, `MaxLevelConsole=info`
+in a drop-in under `/etc/systemd/journald.conf.d/`. That prints journal lines
+like "Started X.service" rather than the `[  OK  ]` status lines, and on a
+40×20 screen it scrolls by fast. It may also be possible to switch
+`/dev/console` to the panel just after init starts, but that is not tested
+either.
+
+Once `radio-ui drm` runs, it is the DRM master and fbcon output is no longer
+pushed to the panel, but tty1 is still a text VT underneath. systemd starts
+`getty@tty1` there, and the journald forwarding above would keep writing to
+it. That is invisible while radio-ui holds the display, but it flashes up
+whenever radio-ui exits or restarts. To keep tty1 quiet, on the target:
+
+    systemctl mask getty@tty1.service
+
+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
+
+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
+run the same kernel and U-Boot. The question is which DTB they boot.
+
+The radio DTB works there, with harmless side effects:
+
+- The panel driver logs "expander not responding" and gives up.
+- The key expander at 0x76 fails to probe, so radio-keys stays deferred.
+- PA18, PA19 and PA6 on the header are claimed, but nothing on the solar
+  boards uses them.
+- An unused analog sound card appears.
+- `console=tty1` points at no display, which does no harm.
+
+Alternatively, install with `BOOT_DTB=sun8i-h2-plus-orangepi-zero.dtb` (the
+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`).
+
+## Layout
+
+| Path | What |
+|---|---|
+| `config.sh` | versions, toolchain, paths, boot settings, shared helpers |
+| `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) |
+| `out/backup/` | bootloader areas saved by `write-uboot.sh` (**not** regenerable) |

+ 225 - 0
build-kernel.sh

@@ -0,0 +1,225 @@
+#!/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. Result: out/opi0-kernel-<release>.tar.gz
+# with boot/opi0/<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
+#   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)
+#   package     only stage and pack the results
+#   clean       remove the kernel build directory and staging
+set -euo pipefail
+. "$(dirname "$0")/config.sh"
+
+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"
+
+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
+	local tarball="linux-$KERNEL_VERSION.tar.xz"
+	local major="${KERNEL_VERSION%%.*}"
+	local base="https://cdn.kernel.org/pub/linux/kernel/v$major.x"
+	if [ ! -d "$KSRC" ]; then
+		fetch "$DL/$tarball" "$base/$tarball"
+		rm -f "$DL/sha256sums-v$major.asc"
+		fetch "$DL/sha256sums-v$major.asc" "$base/sha256sums.asc"
+		info "verifying $tarball"
+		(cd "$DL" && grep " $tarball\$" "sha256sums-v$major.asc" | sha256sum -c -) ||
+			die "checksum mismatch for $tarball"
+		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"
+	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"
+}
+
+do_config() {
+	mkdir -p "$KBUILD"
+	info "configuring: sunxi_defconfig + files/kernel.config"
+	kmake sunxi_defconfig
+	"$KSRC/scripts/kconfig/merge_config.sh" -m -O "$KBUILD" \
+		"$KBUILD/.config" "$FILES/kernel.config" >/dev/null
+	kmake olddefconfig
+	check_fragment "$FILES/kernel.config" "$KBUILD/.config"
+}
+
+do_build() {
+	[ -f "$KBUILD/.config" ] || do_config
+	info "building kernel $KERNEL_VERSION"
+	kmake zImage modules dtbs
+	kmake DTC_FLAGS=-@ "allwinner/$BOARD_DTB"
+}
+
+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 s1d13700-tca's
+# dts/radio-panel.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-panel.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 $PANEL_DIR/dts/radio-panel.dts (-board +overlay)"
+	fi
+	info "key tables match (board DTB and radio-panel overlay)"
+}
+
+do_package() {
+	need_tools depmod dtc fdtget
+	local rel; rel="$(krelease)"
+	local boot="$STAGE/boot/opi0/$rel"
+	info "staging $rel"
+	rm -rf "$STAGE"
+	mkdir -p "$boot/overlay"
+	kmake INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 modules_install
+	kmake INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 M="$XSRC" modules_install
+	# 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/.config" "$boot/config"
+	cp "$KBUILD/System.map" "$boot/System.map"
+
+	# Panel overlays (dts/*.dts in s1d13700-tca), for extlinux fdtoverlays.
+	local d
+	for d in "$PANEL_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"
+
+	local tarball="$OUT/opi0-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*'
+}
+
+cmd="${1:-all}"
+case "$cmd" in
+all)        prepare_source; do_build; do_modules; do_package ;;
+config)     prepare_source; do_config ;;
+menuconfig) prepare_source; [ -f "$KBUILD/.config" ] || do_config; kmake menuconfig ;;
+build)      prepare_source; do_build ;;
+modules)    do_modules ;;
+package)    do_package ;;
+clean)      rm -rf "$KBUILD" "$KOUT" "$OUT/extmod" ;;
+*)          die "unknown command: $cmd" ;;
+esac

+ 72 - 0
build-uboot.sh

@@ -0,0 +1,72 @@
+#!/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.
+#
+# 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
+#               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/
+set -euo pipefail
+. "$(dirname "$0")/config.sh"
+
+UBUILD="$OUT/ubuild"
+UFRAG="$FILES/u-boot.config"
+
+umake() { make -C "$USRC" O="$UBUILD" -j"$JOBS" "$@"; }
+
+prepare_source() {
+	need_tools curl tar gzip make "${CROSS_COMPILE}gcc" bison flex bc swig python3 dtc
+	python3 -c 'import elftools, setuptools' 2>/dev/null ||
+		die "python3 modules pyelftools and setuptools are required"
+	[ -d "$USRC" ] && return 0
+	local tarball="u-boot-${UBOOT_VERSION#v}.tar.gz"
+	# GitHub mirror first (ftp.denx.de/source.denx.de are often unreachable);
+	# the denx tarball is .tar.bz2, so it is only a fallback via a temp name.
+	if ! fetch "$DL/$tarball" "https://github.com/u-boot/u-boot/archive/refs/tags/$UBOOT_VERSION.tar.gz" 2>/dev/null; then
+		fetch "$DL/u-boot-${UBOOT_VERSION#v}.tar.bz2" \
+			"https://ftp.denx.de/pub/u-boot/u-boot-${UBOOT_VERSION#v}.tar.bz2"
+		mkdir -p "$USRC"
+		tar xjf "$DL/u-boot-${UBOOT_VERSION#v}.tar.bz2" -C "$USRC" --strip-components=1
+		return 0
+	fi
+	mkdir -p "$USRC"
+	tar xzf "$DL/$tarball" -C "$USRC" --strip-components=1
+}
+
+do_config() {
+	mkdir -p "$UBUILD"
+	info "configuring: $UBOOT_DEFCONFIG"
+	umake "$UBOOT_DEFCONFIG"
+	if [ -f "$UFRAG" ]; then
+		info "merging files/u-boot.config"
+		"$USRC/scripts/kconfig/merge_config.sh" -m -O "$UBUILD" \
+			"$UBUILD/.config" "$UFRAG" >/dev/null
+		umake olddefconfig
+		check_fragment "$UFRAG" "$UBUILD/.config"
+	fi
+}
+
+do_build() {
+	[ -f "$UBUILD/.config" ] || do_config
+	info "building U-Boot $UBOOT_VERSION"
+	umake
+	mkdir -p "$UOUT"
+	cp "$UBUILD/u-boot-sunxi-with-spl.bin" "$UOUT/"
+	info "done: $UOUT/u-boot-sunxi-with-spl.bin"
+	ls -la "$UOUT/u-boot-sunxi-with-spl.bin"
+}
+
+cmd="${1:-all}"
+case "$cmd" in
+all)        prepare_source; do_build ;;
+config)     prepare_source; do_config ;;
+menuconfig) prepare_source; [ -f "$UBUILD/.config" ] || do_config; umake menuconfig ;;
+build)      prepare_source; do_build ;;
+clean)      rm -rf "$UBUILD" "$UOUT" ;;
+*)          die "unknown command: $cmd" ;;
+esac

+ 105 - 0
config.sh

@@ -0,0 +1,105 @@
+# Shared settings for the Orange Pi Zero (H2+, original version) build.
+# Sourced by the other scripts; override any of these from the environment.
+
+TOP="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# ---- 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-}"
+: "${JOBS:=$(nproc)}"
+export ARCH=arm CROSS_COMPILE
+
+# ---- 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
+
+# ---- 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}"
+
+# ---- 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
+
+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"
+
+die()  { echo "ERROR: $*" >&2; exit 1; }
+info() { echo ">>> $*"; }
+
+# Fail early if a required program is missing; don't install anything.
+need_tools() {
+	local t missing=()
+	for t in "$@"; do command -v "$t" >/dev/null 2>&1 || missing+=("$t"); done
+	[ ${#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() {
+	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
+		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
+			bad=1
+		fi
+	done < "$frag"
+	[ $bad -eq 0 ] || die ".config does not match ${frag#"$TOP"/} (see above)"
+	info "config check passed (${frag#"$TOP"/})"
+}
+
+# fetch URL DEST [fallback URL...]
+fetch() {
+	local dest="$1"; shift
+	[ -s "$dest" ] && return 0
+	mkdir -p "$(dirname "$dest")"
+	local url
+	for url in "$@"; do
+		info "downloading $url"
+		if curl -fL --connect-timeout 20 --retry 2 -o "$dest.part" "$url"; then
+			mv "$dest.part" "$dest"
+			return 0
+		fi
+	done
+	rm -f "$dest.part"
+	die "could not download $(basename "$dest")"
+}

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

@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+/*
+ * Orange Pi Zero (original, H2+) as used in the radio: the mainline board
+ * file plus what the Armbian setup enabled through overlays
+ * (analog-codec, usbhost2, usbhost3, i2c1, user overlay i2c1-400k), the
+ * binding the out-of-tree xradio driver needs for the XR819 Wi-Fi, and the
+ * radio front panel on i2c1: S1D13700 panel (U1, 0x74) and keys (U2, 0x76).
+ *
+ * Built by build-kernel.sh inside the kernel tree, with symbols (-@), so
+ * extra overlays can still be applied by U-Boot (extlinux "fdtoverlays").
+ */
+
+#include "sun8i-h2-plus-orangepi-zero.dts"
+
+/ {
+	model = "Xunlong Orange Pi Zero (radio)";
+
+	/*
+	 * Without an alias Linux numbers I2C adapters in probe order, so the
+	 * only enabled controller (i2c1) would be /dev/i2c-0. Pin it to
+	 * /dev/i2c-1 as under Armbian; dynamic buses (i2c-tiny-usb) start at 2.
+	 */
+	aliases {
+		i2c1 = &i2c1;
+	};
+};
+
+/* Line out / mic on the 13-pin header (was overlay "analog-codec"). */
+&codec {
+	status = "okay";
+};
+
+/* USB2/USB3 on the 13-pin header (were overlays "usbhost2", "usbhost3"). */
+&ehci2 {
+	status = "okay";
+};
+
+&ohci2 {
+	status = "okay";
+};
+
+&ehci3 {
+	status = "okay";
+};
+
+&ohci3 {
+	status = "okay";
+};
+
+/*
+ * I2C1 on PA18 (SCL) / PA19 (SDA), pins 5/3 of the 26-pin header, carrying
+ * the panel and key expanders; 400 kHz (was "i2c1" + user "i2c1-400k").
+ * 400 kHz relies on the pull-ups on the panel board: i2c1_pins enables no
+ * SoC bias, and the internal ~100 kOhm pull-ups would be too weak anyway.
+ */
+&i2c1 {
+	pinctrl-names = "default";
+	pinctrl-0 = <&i2c1_pins>;
+	clock-frequency = <400000>;
+	status = "okay";
+
+	/*
+	 * Radio panel: S1D13700 behind U1, TCA9539 at 0x74. The driver is
+	 * built in, so fbcon shows the boot log here. Without the panel the
+	 * probe stops at "expander not responding" and nothing else happens.
+	 * "k4be" is not in the kernel's vendor-prefixes.yaml and the binding
+	 * has no schema, so dtbs_check warns about this node; that is expected.
+	 */
+	panel@74 {
+		compatible = "k4be,s1d13700-tca9539";
+		reg = <0x74>;
+	};
+
+	/*
+	 * U2, TCA9539 at 0x76 (A1=H, A0=L): the keys. INT (open drain, active
+	 * low) is wired to PA6/PWM1 (pin 7 of the 26-pin header); the SoC's
+	 * pull-up is enabled in case there is none on the board.
+	 */
+	radio_u2: gpio@76 {
+		compatible = "ti,tca9539";
+		reg = <0x76>;
+		pinctrl-names = "default";
+		pinctrl-0 = <&radio_u2_int_pin>;
+		gpio-controller;
+		#gpio-cells = <2>;
+		interrupt-controller;
+		#interrupt-cells = <2>;
+		interrupt-parent = <&pio>;
+		interrupts = <0 6 IRQ_TYPE_LEVEL_LOW>;	/* PA6 */
+	};
+};
+
+&pio {
+	radio_u2_int_pin: radio-u2-int-pin {
+		pins = "PA6";
+		function = "irq";
+		bias-pull-up;
+	};
+};
+
+/ {
+	/*
+	 * Keys are active high, read directly: one pin each to the supply,
+	 * with an external pull-down. Pins 0-7 are P0.0-7, 8-15 are P1.0-7;
+	 * P0.0-P0.2 are unused. Same table as s1d13700-tca's
+	 * dts/radio-panel.dts and radio-ui's radio/keypad.py; build-kernel.sh compares
+	 * the compiled tables and stops if they differ. The input device is
+	 * named "radio-keys", which radio-ui looks for.
+	 */
+	radio-keys {
+		compatible = "gpio-keys";
+		label = "radio-keys";
+		autorepeat;
+
+		key-next  { label = "next";  gpios = <&radio_u2 3 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_NEXTSONG>;     debounce-interval = <20>; };
+		key-left  { label = "left";  gpios = <&radio_u2 4 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_LEFT>;         debounce-interval = <20>; };
+		key-down  { label = "down";  gpios = <&radio_u2 5 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_DOWN>;         debounce-interval = <20>; };
+		key-up    { label = "up";    gpios = <&radio_u2 6 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_UP>;           debounce-interval = <20>; };
+		key-right { label = "right"; gpios = <&radio_u2 7 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_RIGHT>;        debounce-interval = <20>; };
+		key-esc   { label = "esc";   gpios = <&radio_u2 8 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_ESC>;          debounce-interval = <20>; };
+		key-ok    { label = "ok";    gpios = <&radio_u2 9 GPIO_ACTIVE_HIGH>;  linux,code = <KEY_OK>;           debounce-interval = <20>; };
+		key-menu  { label = "menu";  gpios = <&radio_u2 10 GPIO_ACTIVE_HIGH>; linux,code = <KEY_MENU>;         debounce-interval = <20>; };
+		key-list  { label = "list";  gpios = <&radio_u2 11 GPIO_ACTIVE_HIGH>; linux,code = <KEY_LIST>;         debounce-interval = <20>; };
+		key-stop  { label = "stop";  gpios = <&radio_u2 12 GPIO_ACTIVE_HIGH>; linux,code = <KEY_STOPCD>;       debounce-interval = <20>; };
+		key-pause { label = "pause"; gpios = <&radio_u2 13 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PAUSECD>;      debounce-interval = <20>; };
+		key-play  { label = "play";  gpios = <&radio_u2 14 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PLAYCD>;       debounce-interval = <20>; };
+		key-prev  { label = "prev";  gpios = <&radio_u2 15 GPIO_ACTIVE_HIGH>; linux,code = <KEY_PREVIOUSSONG>; debounce-interval = <20>; };
+	};
+};
+
+/*
+ * XR819 on mmc1: the xradio driver matches this compatible and needs the
+ * host-wake interrupt on PG10. U-Boot fills in local-mac-address through
+ * the ethernet1 alias of the mainline file (derived from the SoC SID).
+ */
+&xr819 {
+	compatible = "xradio,xr819";
+	interrupt-parent = <&pio>;
+	interrupts = <6 10 IRQ_TYPE_EDGE_RISING>;	/* PG10 */
+	interrupt-names = "host-wake";
+};

+ 215 - 0
files/kernel.config

@@ -0,0 +1,215 @@
+# 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

+ 5 - 0
files/u-boot.config

@@ -0,0 +1,5 @@
+# Merged on top of orangepi_zero_defconfig by build-uboot.sh.
+#
+# 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

+ 168 - 0
install-kernel.sh

@@ -0,0 +1,168 @@
+#!/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).
+#
+# Usage:
+#   sudo ./install-kernel.sh /mnt/card-root     card's root partition mounted
+#   ./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.
+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"
+[ -f "$TARBALL" ] || die "$TARBALL not found"
+
+# run CMD on the target root (as shell code; paths relative to its /)
+case "$TARGET" in
+ssh:*)
+	HOST="${TARGET#ssh:}"
+	need_tools ssh
+	trun() { ssh "$HOST" "cd / && $1"; }
+	tput_file() { ssh "$HOST" "cat > '/$1.new' && mv '/$1.new' '/$1'"; }
+	;;
+*)
+	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"
+	[ -d "$ROOT/boot" ] || die "$ROOT has no /boot"
+	trun() { (cd "$ROOT" && bash -c "$1"); }
+	tput_file() { cat > "$ROOT/$1.new" && mv "$ROOT/$1.new" "$ROOT/$1"; }
+	;;
+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'

+ 157 - 0
write-uboot.sh

@@ -0,0 +1,157 @@
+#!/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.
+#
+# Usage:
+#   sudo ./write-uboot.sh /dev/sdX            card in a USB reader on this PC
+#   sudo ./write-uboot.sh /dev/mmcblkN        card in a built-in SD slot
+#   ./write-uboot.sh ssh:root@radio.lo        card in the running board
+#   ./write-uboot.sh card.img                 image file
+# Environment:
+#   YES=1          skip the confirmation prompt
+#   FORCE=1        allow a whole disk that does not look like an SD card
+#                  (neither removable, hotplug nor an SD card in an SD slot)
+#   UBOOT_BIN=f    write f instead of the build result, e.g. a backup from
+#                  out/backup/ or Armbian's u-boot-sunxi-with-spl.bin
+#   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
+set -euo pipefail
+. "$(dirname "$0")/config.sh"
+
+BIN="${UBOOT_BIN:-$UOUT/u-boot-sunxi-with-spl.bin}"
+[ -f "$BIN" ] || die "$BIN not found, run ./build-uboot.sh first"
+[ $# -eq 1 ] || die "usage: $0 /dev/sdX | /dev/mmcblkN | ssh:user@host | file.img"
+TARGET="$1"
+SIZE=$(stat -c %s "$BIN")
+END=$(( UBOOT_SEEK_KIB * 1024 + SIZE ))
+END_KIB=$(( (END + 1023) / 1024 ))   # rounded up, for messages
+# The backup covers at least this much (the Armbian U-Boot and the raw
+# 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
+
+confirm() {
+	[ "${YES:-0}" = 1 ] && return 0
+	local a
+	read -r -p "Write U-Boot ($SIZE bytes at ${UBOOT_SEEK_KIB} KiB) to $1? Type 'yes': " a
+	[ "$a" = yes ] || die "aborted"
+}
+
+# The environment of this U-Boot must not be inside the area written. The
+# sunxi default is a file (uboot.env) on a FAT partition, not raw MMC; only
+# when ENV_IS_IN_MMC is enabled does the raw offset limit the image size.
+check_env() {
+	local cfg="$OUT/ubuild/.config" off
+	[ -z "${UBOOT_BIN:-}" ] && [ -f "$cfg" ] || return 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
+		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
+}
+
+# check_gap FIRST_PARTITION_START_SECTOR
+check_gap() {
+	local start="$1"
+	[ -n "$start" ] || { echo "no partitions found"; return 0; }
+	if [ $(( start * 512 )) -lt "$END" ]; then
+		die "first partition starts at sector $start ($(( start / 2 )) KiB), U-Boot would end at $END_KIB KiB and overwrite it"
+	fi
+	echo "first partition starts at $(( start / 2 )) KiB, U-Boot ends at $END_KIB KiB: OK"
+}
+
+# backup_kib FIRST_PARTITION_START_SECTOR -> KiB to save from UBOOT_SEEK_KIB on
+backup_kib() {
+	local start="$1" end=$BACKUP_END_KIB need=$END_KIB
+	[ "$end" -ge "$need" ] || end=$need
+	if [ -n "$start" ] && [ $(( start / 2 )) -lt "$end" ]; then end=$(( start / 2 )); fi
+	echo $(( end - UBOOT_SEEK_KIB ))
+}
+
+# backup NAME KIB READER...: run READER (prints the area to stdout) into
+# out/backup/u-boot-area-NAME-DATE.bin and check the length.
+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 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"
+	[ "$(stat -c %s "$f")" -eq $(( kib * 1024 )) ] || die "backup $f is incomplete"
+	# under sudo, leave the backup to the invoking user
+	if [ -n "${SUDO_UID:-}" ]; then chown "$SUDO_UID:${SUDO_GID:-$SUDO_UID}" "$dir" "$f" || true; fi
+	echo "old ${UBOOT_SEEK_KIB}–$(( UBOOT_SEEK_KIB + kib )) KiB saved to $f"
+	echo "  restore: UBOOT_BIN=$f $0 $TARGET"
+}
+
+first_start() { sfdisk -d "$1" 2>/dev/null | sed -n 's/.*start= *\([0-9]*\).*/\1/p' | head -1; }
+
+check_env
+
+case "$TARGET" in
+ssh:*)
+	host="${TARGET#ssh:}"
+	need_tools ssh
+	# The card holding the board's / (mmcblk0 on mainline, but the number
+	# follows probe order, so look it up). The PC-side safety checks don't
+	# 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"
+	info "card in $host: $dev"
+	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"
+	confirm "$host:$dev"
+	kib=$(backup_kib "$start")
+	backup "$host" "$kib" ssh "$host" "dd if=$dev bs=1024 skip=$UBOOT_SEEK_KIB count=$kib status=none"
+	ssh "$host" "dd of=$dev bs=1024 seek=$UBOOT_SEEK_KIB conv=fsync status=none && sync" < "$BIN"
+	;;
+/dev/*)
+	need_tools lsblk sfdisk dd
+	[ -b "$TARGET" ] || die "$TARGET is not a block device"
+	[ "$(lsblk -dno TYPE "$TARGET")" = disk ] || die "$TARGET is not a whole disk (give /dev/sdX, not /dev/sdX1)"
+	name="$(basename "$(readlink -f "$TARGET")")"
+	case "$name" in
+	mmcblk*boot*|mmcblk*rpmb) die "$TARGET is an eMMC boot/RPMB area, not an SD card" ;;
+	esac
+	# Refuse disks with a filesystem mounted at a system path on this PC.
+	if lsblk -nro MOUNTPOINTS "$TARGET" | grep -qxE '/|/boot(/.*)?|/usr|/var|/home|\[SWAP\]'; then
+		die "$TARGET holds a system filesystem of this machine"
+	fi
+	rm_flag=$(lsblk -dno RM "$TARGET" | tr -d ' ')
+	hotplug=$(lsblk -dno HOTPLUG "$TARGET" | tr -d ' ')
+	# Built-in SD slots (SDHCI, /dev/mmcblkN) usually report RM=0; the MMC
+	# core's card type tells an SD card from soldered eMMC ("MMC").
+	mmc_type=$(cat "/sys/block/$name/device/type" 2>/dev/null || true)
+	if [ "$rm_flag" != 1 ] && [ "$hotplug" != 1 ] && [ "$mmc_type" != SD ] && [ "${FORCE:-0}" != 1 ]; then
+		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"
+	start=$(first_start "$TARGET")
+	check_gap "$start"
+	confirm "$TARGET"
+	kib=$(backup_kib "$start")
+	backup "$name" "$kib" dd if="$TARGET" bs=1024 skip="$UBOOT_SEEK_KIB" count="$kib" status=none
+	dd if="$BIN" of="$TARGET" bs=1024 seek="$UBOOT_SEEK_KIB" conv=fsync status=none
+	sync
+	;;
+*)
+	[ -f "$TARGET" ] || die "$TARGET: no such image file"
+	start=$(first_start "$TARGET")
+	check_gap "$start"
+	confirm "$TARGET"
+	kib=$(backup_kib "$start")
+	backup "$(basename "$TARGET")" "$kib" dd if="$TARGET" bs=1024 skip="$UBOOT_SEEK_KIB" count="$kib" status=none
+	dd if="$BIN" of="$TARGET" bs=1024 seek="$UBOOT_SEEK_KIB" conv=notrunc,fsync status=none
+	;;
+esac
+info "U-Boot written to $TARGET"