From b70935f9bc8a67e862336e3f81303d319b543ed2 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Mon, 9 Nov 2026 10:08:03 -0600 Subject: [PATCH 1/3] initramfs: make development root protections descriptor-driven Opt in to labelled-root identification and strict fsck handling without changing old hand-installed roots. Pack neutral handover and USB-recovery settings; keep unknown modes and incomplete development boots in RAM. Exercise the actual shell functions and descriptor packer with isolated fixtures, including legacy roots and failed filesystem checks. Co-Authored-By: OpenAI Codex --- bin/omamobile | 24 +++++++++ docs/RELEASES.md | 23 +++++++++ initramfs/init | 57 ++++++++++++++++++++-- tests/all | 3 ++ tests/boot-arch-label.py | 39 +++++++++++++++ tests/initramfs-grow | 4 +- tests/initramfs-root-policy.py | 89 ++++++++++++++++++++++++++++++++++ tests/persistent-root-boot.py | 57 ++++++++++++++++++++++ 8 files changed, 290 insertions(+), 6 deletions(-) create mode 100755 tests/boot-arch-label.py create mode 100644 tests/initramfs-root-policy.py create mode 100644 tests/persistent-root-boot.py diff --git a/bin/omamobile b/bin/omamobile index b168f8b76..c3175160d 100755 --- a/bin/omamobile +++ b/bin/omamobile @@ -521,6 +521,20 @@ initramfs_config() { if [[ -n ${DEV_BRINGUP_PROBE:-} ]]; then [[ $DEV_BRINGUP_PROBE == 1 ]] || die "BRINGUP_PROBE must be 1 or absent" fi + if [[ -n ${DEV_INITRAMFS_ROOT_LABEL+x} ]]; then + [[ $DEV_INITRAMFS_ROOT_LABEL == omamobile-root ]] || + die "INITRAMFS_ROOT_LABEL must be omamobile-root or absent" + fi + if [[ -n ${DEV_INITRAMFS_ROOT_MODE+x} ]]; then + [[ $DEV_INITRAMFS_ROOT_MODE == persistent-development || $DEV_INITRAMFS_ROOT_MODE == ram-rescue ]] || + die "INITRAMFS_ROOT_MODE must be persistent-development, ram-rescue or absent" + [[ ${DEV_INITRAMFS_ROOT_LABEL:-} == omamobile-root ]] || + die "INITRAMFS_ROOT_MODE needs INITRAMFS_ROOT_LABEL=omamobile-root" + fi + if [[ -n ${DEV_INITRAMFS_USB_RECOVERY+x} ]]; then + [[ $DEV_INITRAMFS_USB_RECOVERY == yes || $DEV_INITRAMFS_USB_RECOVERY == no ]] || + die "INITRAMFS_USB_RECOVERY must be yes, no or absent" + fi # load_device has checked UFS_RW (names, slot B boot images, userdata); # pack it as one line with single spaces, the form the init accepts read -ra rw <<<"$DEV_UFS_RW" @@ -535,6 +549,16 @@ initramfs_config() { fi [[ -n $etc ]] || return 0 mkdir -p "$etc" + # Absent keys create no policy files and keep existing phones unchanged. + if [[ -n ${DEV_INITRAMFS_ROOT_LABEL:-} ]]; then + printf '%s\n' "$DEV_INITRAMFS_ROOT_LABEL" > "$etc/omamobile-root-label" + fi + if [[ -n ${DEV_INITRAMFS_ROOT_MODE:-} ]]; then + printf '%s\n' "$DEV_INITRAMFS_ROOT_MODE" > "$etc/omamobile-root-mode" + fi + if [[ -n ${DEV_INITRAMFS_USB_RECOVERY:-} ]]; then + printf '%s\n' "$DEV_INITRAMFS_USB_RECOVERY" > "$etc/omamobile-usb-recovery" + fi # This device's simplefb triggers, and nothing else's. The init writes # each pair, and only when the board matches COMPATIBLE. diff --git a/docs/RELEASES.md b/docs/RELEASES.md index ca3239b46..48878f853 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -99,6 +99,29 @@ Its `ram-only` descriptor has empty `BOOT_IMAGES` and `UFS_RW`; build it with `tools/build-flame-probe`, following [its runbook](../device/flame/BRINGUP-M1.md). It does not use the generic Tensor image builder or installer. +### Optional initramfs root policy + +Existing descriptors retain their current boot path. A descriptor may opt in: + +- `INITRAMFS_ROOT_LABEL=omamobile-root`: inspect userdata read-only before + repair or mounting; refuse another label or a failed ext4 header read. Only + `e2fsck -p` statuses 0 and 1 may proceed. Old hand-installed, unlabelled roots + are unaffected until their descriptor explicitly opts in. +- `INITRAMFS_ROOT_MODE=persistent-development`: require the label protection, + skip initramfs growth, and persist `/var/lib/omamobile/root-boot-pending` before + systemd handover. The installed SSH-ready service must clear it; a stale + marker holds the next boot in RAM. `ram-rescue` always stays in RAM. +- `INITRAMFS_USB_RECOVERY=no`: disable the separate 45-second no-host crash. + Development roots may finish booting without a USB host, and a failed root + handover must remain available in RAM instead of consuming slot retries. + This is an explicit choice, independent of root mode; the existing recovery + behavior remains the default. Retain a hardware-watchdog and buttons/fastboot + recovery runbook before using a development image. + +These keys change image construction only; no shipped descriptor opts in here. +Unknown root-mode files fail closed in RAM. This change has offline test evidence, +not a fresh phone boot. + ### 3.2 Keys to add later | Key | Step | Meaning | diff --git a/initramfs/init b/initramfs/init index 8c80204a9..a6ce9ac39 100755 --- a/initramfs/init +++ b/initramfs/init @@ -395,6 +395,7 @@ say "ready" # Self-recovery for bring-up: if the host never configures the USB gadget, # show why on screen, then crash so the phone falls back to stock Android. +if [ "$(cat /etc/omamobile-usb-recovery 2>/dev/null)" != no ]; then ( for i in $(seq 1 45); do grep -qx configured /sys/class/udc/*/state 2>/dev/null && exit 0 @@ -414,6 +415,7 @@ say "ready" # slot B is out of retries ABL boots stock Android, which adb can reach echo c > /proc/sysrq-trigger ) & +fi @@ -499,19 +501,53 @@ boot_nfs() { # missing we stay here in the initramfs shell. boot_arch() { grep -q omamobile.initramfs /proc/cmdline && return 1 - local dev="" s + local dev="" s info label check for s in /sys/block/sda/sda*; do grep -qx PARTNAME=userdata "$s/uevent" 2>/dev/null && dev=/dev/${s##*/} done [ -n "$dev" ] || { say "arch: no userdata partition"; return 1; } [ "$(cat /sys/block/sda/${dev#/dev/}/ro)" = 0 ] || { say "arch: userdata is read-only"; return 1; } + # Strict identification is opt-in: old hand-installed roots may be unlabelled. + # The descriptor packs this file only when it requests the root protection. + if [ -e /etc/omamobile-root-label ]; then + label=$(cat /etc/omamobile-root-label) + [ "$label" = omamobile-root ] || { say "arch: invalid root-label policy"; return 1; } + info=$(dumpe2fs -h "$dev" 2>/dev/null) || { say "arch: userdata is not an ext4 root"; return 1; } + [ "$(echo "$info" | sed -n 's/^Filesystem volume name: *//p')" = "$label" ] || { + say "arch: userdata is not labelled $label"; return 1; + } + fi mkdir -p /newroot - e2fsck -p "$dev" >/dev/null 2>&1 - grow_root "$dev" + check=0 + e2fsck -p "$dev" >/dev/null 2>&1 || check=$? + if [ -e /etc/omamobile-root-label ]; then + case $check in + 0|1) ;; + *) say "arch: root check failed (status $check); staying in the initramfs"; return 1 ;; + esac + fi + # Keep the development filesystem at its image size until persistent boot + # works. Growth can be done later from the installed system. + if [ "$(cat /etc/omamobile-root-mode 2>/dev/null)" != persistent-development ]; then + grow_root "$dev" + fi mount -t ext4 -o rw,relatime "$dev" /newroot || { say "arch: cannot mount $dev"; return 1; } if [ ! -x /newroot/usr/lib/systemd/systemd ]; then say "arch: no systemd on $dev"; umount /newroot; return 1 fi + if [ "$(cat /etc/omamobile-root-mode 2>/dev/null)" = persistent-development ]; then + # A failed development boot returns to the USB rescue environment after + # reset. The installed SSH-ready service clears this marker on success. + local pending=/newroot/var/lib/omamobile/root-boot-pending + if [ -e "$pending" ]; then + say "arch: previous development boot did not reach SSH; holding in RAM" + umount /newroot + return 1 + fi + mkdir -p /newroot/var/lib/omamobile || { umount /newroot; return 1; } + cat /proc/sys/kernel/random/boot_id > "$pending" || { umount /newroot; return 1; } + sync + fi # The guard loop dies below and nothing in Arch sets a partition read-only, # so make one last pass and check, while SSH still runs: anything outside # the allowlist still writable (a late partition, a failed setro) keeps @@ -535,12 +571,25 @@ boot_arch() { done exec switch_root /newroot /usr/lib/systemd/systemd } +# A descriptor selects development handover explicitly. An unknown mode never +# falls through into userdata. No mode file preserves the existing boot path. +boot_root() { + if [ ! -e /etc/omamobile-root-mode ]; then + boot_arch + return $? + fi + case "$(cat /etc/omamobile-root-mode)" in + persistent-development) boot_arch ;; + ram-rescue) say "arch: RAM rescue selected"; return 1 ;; + *) say "arch: unknown root mode; holding in RAM"; return 1 ;; + esac +} # A requested NFS root must not silently fall through to a writable UFS root. if [ -s /etc/omamobile-nfsroot ]; then boot_nfs say "nfsroot: requested root unavailable (staying in the initramfs)" else - boot_arch + boot_root fi # PID 1 must never exit: if it does the kernel panics and freezes (silently, diff --git a/tests/all b/tests/all index 27a3b1482..395d48ded 100755 --- a/tests/all +++ b/tests/all @@ -44,6 +44,9 @@ sh -n device/flame/initramfs/init sh -n device/flame/initramfs/build bash -n tools/build-flame-probe echo "ok - scripts parse" +python3 tests/boot-arch-label.py +python3 tests/persistent-root-boot.py +python3 tests/initramfs-root-policy.py python3 tests/bt-uart-gpio.py for t in tests/pr-check tests/kernel-pr-check tests/phone-smoke tests/alarm-wake-test tests/install-phone tests/build-rootfs tests/rootfs-resolve tests/phone-provision tests/nv-backup tests/initramfs-grow tests/images-layout tests/boot-update-parity tests/stage-boot-files tests/build-packages-host-tools tests/initramfs-reproducible tests/device-overlays tests/simplefb-trigger tests/initramfs-steps tests/storage-guard tests/usb-product tests/grep-q-pipes tests/boot-method tests/modules-push tests/make-bundle-keys tests/make-bundle tests/release-signing tests/pinned-packages tests/flame-probe packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all packages/omamobile-device-lynx/test/all packages/omamobile-device-panther/test/all tests/local-builds tests/phone-install-package tests/publish-kernel tests/fetch-toolchain tests/release-upload tests/extract-camera-data tests/release tests/lineage-ref tests/repo-publish tests/repo-publish-stage tests/extract-vendor-firmware tests/alpine-fetch-callers tests/alpine-fetch tests/tools-help tests/install-phone-initramfs; do echo "# $t" diff --git a/tests/boot-arch-label.py b/tests/boot-arch-label.py new file mode 100755 index 000000000..9b1b23863 --- /dev/null +++ b/tests/boot-arch-label.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise the actual boot_arch shell with isolated metadata and write spies.""" +from pathlib import Path +import subprocess,tempfile,os,json + +repo=Path(__file__).resolve().parent.parent +source=(repo/'initramfs/init').read_text() +body='boot_arch() {'+source.split('boot_arch() {',1)[1].split('\n}\n',1)[0]+'\n}\n' +cases=[('f2fs',0,1,False),('android_ext4',0,0,False),('no_label',0,0,False), + ('our_root',0,0,True),('corrected',1,0,True),('needs_reboot',2,0,False), + ('uncorrected',4,0,False),('operational_error',8,0,False)] +for name,fsck,header_error,can_mount in cases: + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);(p/'block/sda48').mkdir(parents=True) + (p/'block/sda48/uevent').write_text('PARTNAME=userdata\n') + (p/'block/sda48/ro').write_text('0\n');(p/'cmdline').write_text('rdinit=/init\n');(p/'policy').write_text('omamobile-root\n') + script=body.replace('/etc/omamobile-root-label',str(p/'policy')).replace('/sys/block/sda',str(p/'block')).replace('/proc/cmdline',str(p/'cmdline')) + label='userdata' if name=='android_ext4' else '' if name=='no_label' else 'omamobile-root' + spies=f''' +say() {{ printf 'say %s\n' "$*" >> "$LOG"; }} +dumpe2fs() {{ echo header >> "$LOG"; printf 'Filesystem volume name: %s\n' '{label}'; return {header_error}; }} +e2fsck() {{ echo fsck >> "$LOG"; return {fsck}; }} +grow_root() {{ echo grow >> "$LOG"; }} +mkdir() {{ echo mkdir >> "$LOG"; }} +mount() {{ echo mount >> "$LOG"; return 1; }} +''' + f=p/'run.sh';f.write_text(spies+script+'boot_arch\n') + env=os.environ.copy();env['LOG']=str(p/'calls') + shell=json.loads(env.get('OMAMOBILE_BOOT_ARCH_TEST_SHELL','["/bin/sh"]')) + result=subprocess.run(shell+[str(f)],env=env,capture_output=True,text=True,timeout=5) + assert result.returncode==1,(name,result.stdout,result.stderr) + calls=(p/'calls').read_text().splitlines() + assert ('mount' in calls)==can_mount,(name,calls) + if name in ('f2fs','android_ext4','no_label'): + assert not any(c in calls for c in ['fsck','grow','mkdir','mount']),(name,calls) + if fsck>1:assert 'grow' not in calls and 'mount' not in calls,(name,calls) + if can_mount:assert calls.index('header')/dev/null t=$(mktemp -d); trap 'rm -rf "$t"' EXIT init=initramfs/init -grep -q '^ grow_root "\$dev"$' "$init" || fail "boot_arch grows the root before mounting it" -awk '/^ grow_root "\$dev"$/ {g = NR} /^ mount -t ext4/ {m = NR} END {exit !(g && m && g < m)}' "$init" || fail "grow_root runs before mount" +grep -q '^[[:space:]]*grow_root "\$dev"$' "$init" || fail "boot_arch grows the root before mounting it" +awk '/^[[:space:]]*grow_root "\$dev"$/ {g = NR} /^ mount -t ext4/ {m = NR} END {exit !(g && m && g < m)}' "$init" || fail "grow_root runs before mount" grep -q 'e2fsprogs-extra' bin/omamobile || fail "bin/omamobile initramfs includes resize2fs (e2fsprogs-extra)" sed -n '/^grow_root() {$/,/^}$/p' "$init" > "$t/grow.sh" [[ -s $t/grow.sh ]] || fail "grow_root found in $init" diff --git a/tests/initramfs-root-policy.py b/tests/initramfs-root-policy.py new file mode 100644 index 000000000..c223f64ff --- /dev/null +++ b/tests/initramfs-root-policy.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Check descriptor packing, legacy handover and fail-closed development modes.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + +repo = Path(__file__).resolve().parent.parent +source = (repo / 'initramfs/init').read_text() + + +def function(name): + return name + '() {' + source.split(name + '() {', 1)[1].split('\n}\n', 1)[0] + '\n}\n' + + +with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) + fixture = p / 'repo' + (fixture / 'bin').mkdir(parents=True) + (fixture / 'device/six').mkdir(parents=True) + shutil.copy2(repo / 'bin/omamobile', fixture / 'bin/omamobile') + (fixture / 'omamobile.conf').write_text('DEVICE="${DEVICE:-six}"\nSRC_DIR=/nonexistent\n') + descriptor = (repo / 'device/bluejay/device.conf').read_text().replace('CODENAME=bluejay', 'CODENAME=six') + conf = fixture / 'device/six/device.conf' + + def pack(extra, name, valid=True): + conf.write_text(descriptor + '\n' + extra) + out = p / name + result = subprocess.run([str(fixture / 'bin/omamobile'), 'initramfs-config', str(out)], + env={**os.environ, 'DEVICE': 'six'}, capture_output=True, text=True) + assert (result.returncode == 0) == valid, result.stderr + if not valid: + assert not out.exists(), name + return out + + names = ('omamobile-root-label', 'omamobile-root-mode', 'omamobile-usb-recovery') + default = pack('', 'default') + assert not any((default / n).exists() for n in names) + for mode in ('persistent-development', 'ram-rescue'): + out = pack('INITRAMFS_ROOT_LABEL=omamobile-root\nINITRAMFS_ROOT_MODE=' + mode + + '\nINITRAMFS_USB_RECOVERY=no\n', mode) + assert [(out / n).read_text().strip() for n in names] == ['omamobile-root', mode, 'no'] + for i, bad in enumerate(('INITRAMFS_ROOT_LABEL=wrong\n', 'INITRAMFS_ROOT_LABEL=""\n', + 'INITRAMFS_ROOT_MODE=unknown\n', 'INITRAMFS_ROOT_MODE=ram-rescue\n', + 'INITRAMFS_USB_RECOVERY=maybe\n')): + pack(bad, 'bad-' + str(i), False) + print('ok - default packing is unchanged; explicit policies validated before output') + + modefile = p / 'mode' + for value, calls_arch in ((None, True), ('persistent-development', True), + ('ram-rescue', False), ('unknown', False), ('', False)): + if value is None: + modefile.unlink(missing_ok=True) + else: + modefile.write_text(value + '\n') + script = 'say() { :; }; boot_arch() { echo handover; return 1; }\n' + script += function('boot_root').replace('/etc/omamobile-root-mode', str(modefile)) + result = subprocess.run(['/bin/sh', '-c', script + 'boot_root'], capture_output=True, text=True) + assert result.returncode == 1 + assert ('handover' in result.stdout) == calls_arch, (value, result) + print('ok - absent mode preserves boot; rescue and malformed modes cannot hand over') + + block = p / 'block/sda27' + block.mkdir(parents=True) + (block / 'uevent').write_text('PARTNAME=userdata\n') + (block / 'ro').write_text('0\n') + (p / 'cmdline').write_text('console=null\n') + script = function('boot_arch').replace('/sys/block/sda', str(p / 'block')) + script = script.replace('/proc/cmdline', str(p / 'cmdline')) + script = script.replace('/etc/omamobile-root-label', str(p / 'absent-label')) + script = script.replace('/etc/omamobile-root-mode', str(p / 'absent-mode')) + # A legacy unlabelled root retains repair/growth/mount ordering, even if + # repair returns 4. Tightening that policy requires the descriptor opt-in. + spies = ''' +say() { :; } +dumpe2fs() { echo UNEXPECTED_HEADER; return 1; } +mkdir() { :; } +e2fsck() { echo fsck >> "$LOG"; return 4; } +grow_root() { echo grow >> "$LOG"; } +mount() { echo mount >> "$LOG"; return 1; } +''' + log = p / 'calls' + result = subprocess.run(['/bin/sh', '-c', spies + script + 'boot_arch'], + env={**os.environ, 'LOG': str(log)}, capture_output=True, text=True) + assert result.returncode == 1 and not result.stdout + assert log.read_text().splitlines() == ['fsck', 'grow', 'mount'] + print('ok - unlabelled legacy roots retain their existing handover path') diff --git a/tests/persistent-root-boot.py b/tests/persistent-root-boot.py new file mode 100644 index 000000000..bca3209ec --- /dev/null +++ b/tests/persistent-root-boot.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise the actual persistent boot function without mounts or phone access.""" +from pathlib import Path +import os +import json +import subprocess +import tempfile + +repo = Path(__file__).resolve().parent.parent +source = (repo / 'initramfs/init').read_text() +body = 'boot_arch() {' + source.split('boot_arch() {', 1)[1].split('\n}\n', 1)[0] + '\n}\n' +for stale in (False, True): + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp) + (p / 'block/sda48').mkdir(parents=True) + (p / 'block/sda48/uevent').write_text('PARTNAME=userdata\n') + (p / 'block/sda48/ro').write_text('0\n') + (p / 'cmdline').write_text('rdinit=/init\n') + (p / 'mode').write_text('persistent-development\n') + (p / 'policy').write_text('omamobile-root\n') + root = p / 'root' + (root / 'usr/lib/systemd').mkdir(parents=True) + systemd = root / 'usr/lib/systemd/systemd' + systemd.touch() + systemd.chmod(0o755) + pending = root / 'var/lib/omamobile/root-boot-pending' + pending.parent.mkdir(parents=True) + if stale: + pending.write_text('previous-boot\n') + script = body.replace('/etc/omamobile-root-label', str(p / 'policy')).replace('/sys/block/sda', str(p / 'block')).replace('/proc/cmdline', str(p / 'cmdline')).replace('/etc/omamobile-root-mode', str(p / 'mode')).replace('/newroot', str(root)) + spies = ''' +say() { echo "$*" >> "$LOG"; } +dumpe2fs() { echo 'Filesystem volume name: omamobile-root'; } +e2fsck() { return 0; } +grow_root() { echo UNEXPECTED_GROW >> "$LOG"; return 1; } +mount() { return 0; } +umount() { echo unmounted >> "$LOG"; } +sync() { echo synced >> "$LOG"; } +ufs_ro_pass() { :; } +# Stop before process quiescing: the test deliberately reports a guard fault. +ufs_unguarded() { echo test-stop; } +''' + f = p / 'run.sh' + f.write_text(spies + script + 'boot_arch\n') + shell = json.loads(os.environ.get('OMAMOBILE_BOOT_ARCH_TEST_SHELL', '["/bin/sh"]')) + result = subprocess.run(shell + [str(f)], env={**os.environ, 'LOG': str(p / 'log')}, capture_output=True, text=True, timeout=5) + assert result.returncode == 1, result + log = (p / 'log').read_text() + assert 'UNEXPECTED_GROW' not in log + if stale: + assert 'holding in RAM' in log and pending.read_text() == 'previous-boot\n' + assert 'synced' not in log + else: + assert pending.read_text() == Path('/proc/sys/kernel/random/boot_id').read_text() + assert 'synced' in log and 'test-stop' in log + print('PASS:', 'failed previous boot holds in RAM' if stale else 'fresh boot persists marker and skips growth') From a14324e4710fae5aa2fc4edbd3f35068c197b7e1 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 10 Nov 2026 12:12:52 -0600 Subject: [PATCH 2/3] initramfs: document root policy keys and readiness prerequisite List all three opt-in keys in the descriptor table. Require the matching SSH-ready service to be installed and enabled before persistent-development handover so its marker does not hold the following boot in RAM. Co-Authored-By: OpenAI Codex --- docs/RELEASES.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 48878f853..4b518630c 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -82,6 +82,9 @@ Bring-up tools (`*-stage`, `display-hz`, `usbc-deadman`) stay per plan: they pok | `UFS_RW` | `boot_b … dtbo_b userdata` | The storage guard's allowlist, packed into the initramfs as `/etc/omamobile-ufs-rw`. Only slot B's boot images (`boot_b`, `init_boot_b`, `vendor_boot_b`, `vendor_kernel_boot_b`, `dtbo_b`) and `userdata` are accepted, `userdata` and every `BOOT_IMAGES` entry must be on it, and each name only once. The init fails closed: a missing, empty or malformed file, or any other name in it, leaves every partition read-only | | `UFS_RW_LUNS` | (unset) | Optional. The LUNs besides `sda` that hold `UFS_RW` partitions, as disk names `sdb` to `sdz`, packed as `/etc/omamobile-ufs-rw-luns`. The init guards each as it guards `sda`: the whole-disk node removed, the disk left writable, and only its `UFS_RW` partitions left writable. Absent (every descriptor so far), malformed, or with a closed allowlist: every LUN but `sda` stays read-only at the disk level. Boot-image writers on the phone (`omamobile-boot-update`) still look only on `sda` | | `INITRAMFS_INIT` | `/initramfs/init` | The init script. A leading `/` is relative to the repo root, so devices share one script. Any other value is relative to the descriptor | +| `INITRAMFS_ROOT_LABEL` | (unset) | Optional: `omamobile-root` enables read-only label/header checks before ext4 repair or mounting; only `e2fsck -p` statuses 0 and 1 proceed. Omitted: existing root handling, including unlabelled hand-installed roots, is unchanged | +| `INITRAMFS_ROOT_MODE` | (unset) | Optional: `persistent-development` or `ram-rescue`, requiring `INITRAMFS_ROOT_LABEL=omamobile-root`. The former skips growth and writes `/var/lib/omamobile/root-boot-pending` before handover; an installed, enabled SSH-ready helper must clear it after USB SSH is ready, or the next boot stays in RAM. The latter always stays in RAM. Omitted: existing handover behavior | +| `INITRAMFS_USB_RECOVERY` | (unset) | Optional: `yes` or `no`; `no` disables the separate 45-second no-host crash for an attended development/recovery policy. Omitted or `yes`: existing USB recovery behavior. Independent of root mode; retain watchdog and buttons/fastboot recovery | | `INITRAMFS_MODULES` | (unset) | Optional: kernel modules the initramfs carries in `/lib/modules/omamobile/`, listed in load order in `/lib/modules/omamobile/order`, from this kernel build's `lib/modules/$(kernel_release)` (`omamobile modules` first). The shared init loads them before any other step, and only on a board whose first compatible is `COMPATIBLE`. For drivers the boot needs before the Arch root, such as the PMIC rails a `simple-framebuffer` waits for; `images` refuses an initramfs whose modules come from another build | | `INITRAMFS_I2C_TOOLS` | (unset) | `1`: `i2cget` and `i2cset` (and `libi2c`) from Alpine's i2c-tools in the initramfs, for an init that talks to a chip before any driver runs (raven closes the MAX77759 USB switch). Nothing else from the package | | `INITRAMFS_FB_WAIT` | (unset) | `1`: the init draws the early splash once `/dev/fb0` exists (waiting up to 3 s in the background) rather than at once, for a phone whose `simple-framebuffer` registers only after `INITRAMFS_MODULES` give it its rails (raven) | @@ -109,8 +112,11 @@ Existing descriptors retain their current boot path. A descriptor may opt in: are unaffected until their descriptor explicitly opts in. - `INITRAMFS_ROOT_MODE=persistent-development`: require the label protection, skip initramfs growth, and persist `/var/lib/omamobile/root-boot-pending` before - systemd handover. The installed SSH-ready service must clear it; a stale - marker holds the next boot in RAM. `ram-rescue` always stays in RAM. + systemd handover. Install and enable the matching SSH-ready service on the + root before using this mode; it must clear the marker after USB SSH is ready. + Without that helper, every second boot stays in RAM because the preceding + handover leaves the marker behind. A stale marker holds the next boot in RAM. + `ram-rescue` always stays in RAM. - `INITRAMFS_USB_RECOVERY=no`: disable the separate 45-second no-host crash. Development roots may finish booting without a USB host, and a failed root handover must remain available in RAM instead of consuming slot retries. From 63fa8bf63df9c5acba8ef8e68e1189a5f6e247d8 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Wed, 11 Nov 2026 12:06:37 -0600 Subject: [PATCH 3/3] initramfs: preserve NFS priority and document held-root recovery Write the development handover marker only after the final guard, keep every held boot in RAM until recovery clears the marker, and refuse local root policies in release images. Cover NFS failure isolation, guard refusals, persistent holds and release preflight. Co-Authored-By: Codex --- bin/omamobile | 6 ++++++ docs/RELEASES.md | 32 +++++++++++++++++++++++++++++--- initramfs/init | 10 +++++++--- tests/initramfs-root-policy.py | 27 +++++++++++++++++++++++++++ tests/persistent-root-boot.py | 24 +++++++++++++++++------- 5 files changed, 86 insertions(+), 13 deletions(-) diff --git a/bin/omamobile b/bin/omamobile index c3175160d..98f9503bd 100755 --- a/bin/omamobile +++ b/bin/omamobile @@ -649,6 +649,12 @@ cmd_initramfs() { [[ -f $init ]] || die "no init script $init" # Every per-device value is checked before anything is downloaded or built initramfs_config + if ((release)); then + [[ -z ${DEV_INITRAMFS_ROOT_MODE+x} ]] || + die "INITRAMFS_ROOT_MODE is for local bring-up only, not --release" + [[ ${DEV_INITRAMFS_USB_RECOVERY:-yes} != no ]] || + die "INITRAMFS_USB_RECOVERY=no is for local bring-up only, not --release" + fi if [[ -n ${OMAMOBILE_NFSROOT:-} ]]; then ((release == 0)) || die "OMAMOBILE_NFSROOT is for local bring-up only, not --release" [[ $OMAMOBILE_NFSROOT =~ ^[A-Za-z0-9.-]+:/[A-Za-z0-9._/-]+$ && $OMAMOBILE_NFSROOT != *..* && $OMAMOBILE_NFSROOT != *//* ]] || diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 4b518630c..b40d577e4 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -83,7 +83,7 @@ Bring-up tools (`*-stage`, `display-hz`, `usbc-deadman`) stay per plan: they pok | `UFS_RW_LUNS` | (unset) | Optional. The LUNs besides `sda` that hold `UFS_RW` partitions, as disk names `sdb` to `sdz`, packed as `/etc/omamobile-ufs-rw-luns`. The init guards each as it guards `sda`: the whole-disk node removed, the disk left writable, and only its `UFS_RW` partitions left writable. Absent (every descriptor so far), malformed, or with a closed allowlist: every LUN but `sda` stays read-only at the disk level. Boot-image writers on the phone (`omamobile-boot-update`) still look only on `sda` | | `INITRAMFS_INIT` | `/initramfs/init` | The init script. A leading `/` is relative to the repo root, so devices share one script. Any other value is relative to the descriptor | | `INITRAMFS_ROOT_LABEL` | (unset) | Optional: `omamobile-root` enables read-only label/header checks before ext4 repair or mounting; only `e2fsck -p` statuses 0 and 1 proceed. Omitted: existing root handling, including unlabelled hand-installed roots, is unchanged | -| `INITRAMFS_ROOT_MODE` | (unset) | Optional: `persistent-development` or `ram-rescue`, requiring `INITRAMFS_ROOT_LABEL=omamobile-root`. The former skips growth and writes `/var/lib/omamobile/root-boot-pending` before handover; an installed, enabled SSH-ready helper must clear it after USB SSH is ready, or the next boot stays in RAM. The latter always stays in RAM. Omitted: existing handover behavior | +| `INITRAMFS_ROOT_MODE` | (unset) | Optional: `persistent-development` or `ram-rescue`, requiring `INITRAMFS_ROOT_LABEL=omamobile-root`. The former skips growth and writes `/var/lib/omamobile/root-boot-pending` before handover; an installed, enabled SSH-ready helper must clear it after USB SSH is ready, or subsequent boots stay in RAM until the marker is cleared. The latter always stays in RAM. Omitted: existing handover behavior | | `INITRAMFS_USB_RECOVERY` | (unset) | Optional: `yes` or `no`; `no` disables the separate 45-second no-host crash for an attended development/recovery policy. Omitted or `yes`: existing USB recovery behavior. Independent of root mode; retain watchdog and buttons/fastboot recovery | | `INITRAMFS_MODULES` | (unset) | Optional: kernel modules the initramfs carries in `/lib/modules/omamobile/`, listed in load order in `/lib/modules/omamobile/order`, from this kernel build's `lib/modules/$(kernel_release)` (`omamobile modules` first). The shared init loads them before any other step, and only on a board whose first compatible is `COMPATIBLE`. For drivers the boot needs before the Arch root, such as the PMIC rails a `simple-framebuffer` waits for; `images` refuses an initramfs whose modules come from another build | | `INITRAMFS_I2C_TOOLS` | (unset) | `1`: `i2cget` and `i2cset` (and `libi2c`) from Alpine's i2c-tools in the initramfs, for an init that talks to a chip before any driver runs (raven closes the MAX77759 USB switch). Nothing else from the package | @@ -114,8 +114,8 @@ Existing descriptors retain their current boot path. A descriptor may opt in: skip initramfs growth, and persist `/var/lib/omamobile/root-boot-pending` before systemd handover. Install and enable the matching SSH-ready service on the root before using this mode; it must clear the marker after USB SSH is ready. - Without that helper, every second boot stays in RAM because the preceding - handover leaves the marker behind. A stale marker holds the next boot in RAM. + Without that helper, the first boot hands over and leaves the marker behind; + every subsequent boot stays in RAM until the marker is cleared manually. `ram-rescue` always stays in RAM. - `INITRAMFS_USB_RECOVERY=no`: disable the separate 45-second no-host crash. Development roots may finish booting without a USB host, and a failed root @@ -128,6 +128,32 @@ These keys change image construction only; no shipped descriptor opts in here. Unknown root-mode files fail closed in RAM. This change has offline test evidence, not a fresh phone boot. +`INITRAMFS_ROOT_MODE` and `INITRAMFS_USB_RECOVERY=no` are local development +settings and are refused by `initramfs --release`. With USB recovery left on, +each held boot without a USB host still spends a slot try when it restarts. +The handover marker is written only after the final storage-guard check passes. + +After investigating the failure, clear the marker from the RAM rescue shell +to permit one more handover attempt. Find userdata by its partition name, +confirm it is the installed root, then mount it, remove the marker and unmount: + +```sh +userdata= +for part in /sys/class/block/sd*; do + [ -r "$part/partition" ] || continue + if grep -qx PARTNAME=userdata "$part/uevent"; then userdata=/dev/${part##*/}; fi +done +mkdir -p /newroot +if [ -n "$userdata" ] && mount -t ext4 -o rw "$userdata" /newroot; then + rm -f /newroot/var/lib/omamobile/root-boot-pending + sync + umount /newroot +fi +``` + +Clearing the marker does not repair the failed startup or replace the SSH-ready +helper. A further failed handover sets it again and holds subsequent boots. + ### 3.2 Keys to add later | Key | Step | Meaning | diff --git a/initramfs/init b/initramfs/init index a6ce9ac39..60053788a 100755 --- a/initramfs/init +++ b/initramfs/init @@ -544,9 +544,6 @@ boot_arch() { umount /newroot return 1 fi - mkdir -p /newroot/var/lib/omamobile || { umount /newroot; return 1; } - cat /proc/sys/kernel/random/boot_id > "$pending" || { umount /newroot; return 1; } - sync fi # The guard loop dies below and nothing in Arch sets a partition read-only, # so make one last pass and check, while SSH still runs: anything outside @@ -560,6 +557,13 @@ boot_arch() { umount /newroot return 1 fi + if [ "$(cat /etc/omamobile-root-mode 2>/dev/null)" = persistent-development ]; then + # Record an attempted handover only after the final guard passes. A guard + # refusal must not be reported as a root that failed to reach SSH next boot. + mkdir -p /newroot/var/lib/omamobile || { umount /newroot; return 1; } + cat /proc/sys/kernel/random/boot_id > "$pending" || { umount /newroot; return 1; } + sync + fi say "arch: switching to Arch Linux on $dev" # Stop the initramfs helpers (dropbear, getty, guards); the kernel keeps # the USB gadget and the partition read-only flags across the switch diff --git a/tests/initramfs-root-policy.py b/tests/initramfs-root-policy.py index c223f64ff..ce1a2962c 100644 --- a/tests/initramfs-root-policy.py +++ b/tests/initramfs-root-policy.py @@ -48,6 +48,33 @@ def pack(extra, name, valid=True): pack(bad, 'bad-' + str(i), False) print('ok - default packing is unchanged; explicit policies validated before output') + (fixture / 'initramfs').mkdir() + (fixture / 'initramfs/init').write_text('#!/bin/sh\n') + for i, (extra, message) in enumerate(( + ('INITRAMFS_ROOT_LABEL=omamobile-root\nINITRAMFS_ROOT_MODE=persistent-development\n', 'INITRAMFS_ROOT_MODE'), + ('INITRAMFS_ROOT_LABEL=omamobile-root\nINITRAMFS_ROOT_MODE=ram-rescue\n', 'INITRAMFS_ROOT_MODE'), + ('INITRAMFS_USB_RECOVERY=no\n', 'INITRAMFS_USB_RECOVERY=no'), + )): + conf.write_text(descriptor + '\n' + extra) + output = p / ('release-' + str(i)) + result = subprocess.run([str(fixture / 'bin/omamobile'), 'initramfs', '--release'], + env={**os.environ, 'DEVICE': 'six', 'KERNEL_OUT': str(output), 'WORK': str(p / 'work')}, + capture_output=True, text=True) + assert result.returncode != 0 and message in result.stderr and 'not --release' in result.stderr, result + assert not output.exists() and not (p / 'work').exists() + print('ok - development root mode and disabled USB recovery refuse release builds before downloads') + + nfsfile = p / 'nfsroot' + dispatch = source.rsplit('# A requested NFS root must not silently fall through', 1)[1].split('\nfi', 1)[0].split('\n', 1)[1] + '\nfi\n' + assert len(dispatch.splitlines()) == 6 and dispatch.count('boot_nfs') == 1 and dispatch.count('boot_root') == 1 + assert all(word not in dispatch for word in ('/sys/', 'mount', 'kill', 'blockdev', 'devmem')) + for requested in (False, True): + nfsfile.write_text('host:/export\n' if requested else '') + spies = 'say() { :; }; boot_nfs() { echo nfs; return 1; }; boot_root() { echo userdata; return 1; }\n' + result = subprocess.run(['/bin/sh', '-c', spies + dispatch.replace('/etc/omamobile-nfsroot', str(nfsfile))], capture_output=True, text=True) + assert result.stdout.strip() == ('nfs' if requested else 'userdata'), result + print('ok - requested NFS failure never falls through to userdata policy') + modefile = p / 'mode' for value, calls_arch in ((None, True), ('persistent-development', True), ('ram-rescue', False), ('unknown', False), ('', False)): diff --git a/tests/persistent-root-boot.py b/tests/persistent-root-boot.py index bca3209ec..778922331 100644 --- a/tests/persistent-root-boot.py +++ b/tests/persistent-root-boot.py @@ -10,7 +10,7 @@ repo = Path(__file__).resolve().parent.parent source = (repo / 'initramfs/init').read_text() body = 'boot_arch() {' + source.split('boot_arch() {', 1)[1].split('\n}\n', 1)[0] + '\n}\n' -for stale in (False, True): +for stale, guard_fault in ((False, False), (False, True), (True, False)): with tempfile.TemporaryDirectory() as tmp: p = Path(tmp) (p / 'block/sda48').mkdir(parents=True) @@ -29,6 +29,10 @@ if stale: pending.write_text('previous-boot\n') script = body.replace('/etc/omamobile-root-label', str(p / 'policy')).replace('/sys/block/sda', str(p / 'block')).replace('/proc/cmdline', str(p / 'cmdline')).replace('/etc/omamobile-root-mode', str(p / 'mode')).replace('/newroot', str(root)) + # Stop immediately before process quiescing; never execute kill/switch_root. + stop = ' kill -9 -1 2>/dev/null' + assert script.count(stop) == 1 + script = script.replace(stop, ' return 42') spies = ''' say() { echo "$*" >> "$LOG"; } dumpe2fs() { echo 'Filesystem volume name: omamobile-root'; } @@ -38,20 +42,26 @@ umount() { echo unmounted >> "$LOG"; } sync() { echo synced >> "$LOG"; } ufs_ro_pass() { :; } -# Stop before process quiescing: the test deliberately reports a guard fault. -ufs_unguarded() { echo test-stop; } +ufs_unguarded() { [ "$GUARD_FAULT" = 1 ] && echo test-stop; } ''' f = p / 'run.sh' f.write_text(spies + script + 'boot_arch\n') shell = json.loads(os.environ.get('OMAMOBILE_BOOT_ARCH_TEST_SHELL', '["/bin/sh"]')) - result = subprocess.run(shell + [str(f)], env={**os.environ, 'LOG': str(p / 'log')}, capture_output=True, text=True, timeout=5) - assert result.returncode == 1, result + result = subprocess.run(shell + [str(f)], env={**os.environ, 'LOG': str(p / 'log'), 'GUARD_FAULT': str(int(guard_fault))}, capture_output=True, text=True, timeout=5) + assert result.returncode == (42 if not stale and not guard_fault else 1), result log = (p / 'log').read_text() assert 'UNEXPECTED_GROW' not in log if stale: assert 'holding in RAM' in log and pending.read_text() == 'previous-boot\n' assert 'synced' not in log + elif guard_fault: + assert not pending.exists(), 'guard refusal must not leave a handover marker' + assert 'test-stop' in log and 'synced' not in log else: assert pending.read_text() == Path('/proc/sys/kernel/random/boot_id').read_text() - assert 'synced' in log and 'test-stop' in log - print('PASS:', 'failed previous boot holds in RAM' if stale else 'fresh boot persists marker and skips growth') + assert 'synced' in log and 'switching to Arch' in log + # A held boot never clears the marker: every later boot stays held. + for _ in range(2): + held = subprocess.run(shell + [str(f)], env={**os.environ, 'LOG': str(p / 'log'), 'GUARD_FAULT': '0'}, capture_output=True, text=True, timeout=5) + assert held.returncode == 1 and pending.exists() + print('PASS:', 'failed previous boot holds in RAM' if stale else 'guard refusal leaves no marker' if guard_fault else 'fresh boot persists marker after guard; later boots remain held')