From d5bb41a3f02c2ecbf0b6d2cec28b0a3a25d8da08 Mon Sep 17 00:00:00 2001 From: Alexandre Figueiredo <17xande@gmail.com> Date: Mon, 30 Nov 2026 20:00:26 +0200 Subject: [PATCH 1/2] initrd: boot read-only roots on scattered LwVM partitions Use a CRC-checked LwVM header to generate a read-only dm-linear map in the boot arguments. The shared initrd matches the mapping by the root PARTUUID, verifies the LwVM header checksum of the backing disk before mounting (a valid primary takes precedence over a stale backup), and starts the system with an opt-in tmpfs overlay, so writes do not reach the flash. If the device-mapper root cannot boot, it offers a serial-only USB rescue shell. Assisted-by: LLM Signed-off-by: Alexandre Figueiredo <17xande@gmail.com> --- boot/initramfs/root/init | 226 ++++++++++++++++---- chips/s5l8942x.toml | 1 + devices/p105/device.toml | 2 + docs/boot-contract.md | 35 +++ docs/device-protocol.md | 6 + src/orchard/lwvm_root.py | 115 ++++++++++ tests/fixtures/p105-scattered-lwvm.bin | Bin 0 -> 4096 bytes tests/test_identity.py | 21 +- tests/test_lwvm_root.py | 283 +++++++++++++++++++++++++ 9 files changed, 638 insertions(+), 51 deletions(-) create mode 100644 src/orchard/lwvm_root.py create mode 100644 tests/fixtures/p105-scattered-lwvm.bin create mode 100644 tests/test_lwvm_root.py diff --git a/boot/initramfs/root/init b/boot/initramfs/root/init index 8077943fc..963a12787 100755 --- a/boot/initramfs/root/init +++ b/boot/initramfs/root/init @@ -13,6 +13,30 @@ exec /dev/console 2>&1 stop() { echo "orchard initrd: $1" + # The serial-only rescue gadget is offered only for orchard.root=dm: those + # roots are the one stop path with no other way in (the whole disk map is + # checked here), and it exists so a bad map can be inspected over USB. On + # every other stop() it would raise a second gadget and a second shell on + # ttyGS0 where the normal gadget may already be up, and no board has booted + # that path yet. Widen it once a RAM boot has shown it safe. + if [ -n "$mapped_root" ]; then + if usb_gadget rescue; then + echo 'Starting a rescue shell on USB serial.' + ( + while :; do + if [ -c /dev/ttyGS0 ]; then + ( + echo "orchard initrd: $1" + exec setsid sh -i + ) /dev/ttyGS0 2>&1 + fi + sleep 1 + done + ) & + else + echo 'orchard initrd: USB serial rescue is unavailable.' + fi + fi echo 'Starting a shell on the console; the system did not start.' if [ -c /dev/ttyGS0 ]; then echo "orchard initrd: $1" >/dev/ttyGS0 2>&1 @@ -21,7 +45,55 @@ stop() { exec sh } -root= mode=rw flags= fstype= init=/sbin/init +# USB for the host: a serial console (ttyGS0), and on normal boots network +# (usb0) and the installed system's name. +usb_gadget() { + g=/sys/kernel/config/usb_gadget/orchard-system + mkdir -p /sys/kernel/config && mount -t configfs -o nodev,noexec,nosuid configfs /sys/kernel/config 2>/dev/null + [ ! -e "$g" ] || return 0 + if [ "${1:-}" = rescue ]; then + name='Orchard initrd rescue' + configuration='USB serial rescue' + else + name=$(sed -n 's/^NAME=//p' /newroot/etc/os-release /newroot/usr/lib/os-release 2>/dev/null | head -1 | tr -d "\"'") + configuration='USB network and serial' + fi + board=$(tr '\000' '\n' < /proc/device-tree/compatible | head -1) + # One serial for every boot of this unit (docs/device-protocol.md), or + # the per-boot one if the helper fails: USB must always come up. + serial=$(sh /etc/orchard/usb-identity 2>/dev/null) || + serial="BOOT:$(cat /proc/sys/kernel/random/boot_id) BOARD:${board#apple,}" + # Apple's vendor ID with a product ID macOS lists among the devices it + # grants 2400 mA (docs/device-protocol.md), so a Mac charges the tablet + # at full speed. As an interface-association composite (class 0xef/2/1) + # macOS binds its generic composite driver, which delivers the grant, + # and still the CDC network and serial drivers. + mkdir "$g" && + echo 0x05ac > "$g/idVendor" && + if [ "${1:-}" = rescue ]; then + echo 0x4144 > "$g/idProduct" + else + echo 0x1014 > "$g/idProduct" + fi && + echo 0xef > "$g/bDeviceClass" && + echo 0x02 > "$g/bDeviceSubClass" && + echo 0x01 > "$g/bDeviceProtocol" && + mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" && + echo 'Orchard Linux' > "$g/strings/0x409/manufacturer" && + echo "${name:-Linux}" > "$g/strings/0x409/product" && + echo "$serial" > "$g/strings/0x409/serialnumber" && + echo "$configuration" > "$g/configs/c.1/strings/0x409/configuration" && + echo 500 > "$g/configs/c.1/MaxPower" && + mkdir "$g/functions/acm.usb0" && + if [ "${1:-}" != rescue ]; then + mkdir "$g/functions/ncm.usb0" && + ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/ncm.usb0" + fi && + ln -s "$g/functions/acm.usb0" "$g/configs/c.1/acm.usb0" && + basename "$(ls -d /sys/class/udc/* | head -1)" > "$g/UDC" +} + +root= mode=rw flags= fstype= init=/sbin/init mapped_root= overlay= lwvm_crc= for argument in $(cat /proc/cmdline); do case "$argument" in root=PARTUUID=*) root=$(echo "${argument#root=PARTUUID=}" | tr A-F a-f) ;; @@ -29,6 +101,9 @@ for argument in $(cat /proc/cmdline); do rootflags=*) flags=${argument#rootflags=} ;; ro | rw) mode=$argument ;; init=*) init=${argument#init=} ;; + orchard.root=dm) mapped_root=1 ;; + orchard.overlay=tmpfs) overlay=1 ;; + orchard.lwvm_crc=*) lwvm_crc=${argument#orchard.lwvm_crc=} ;; esac done @@ -54,6 +129,7 @@ if [ -r /run/orchard/disk ]; then [ -b "$disk" ] && : < "$disk" fi [ -n "$root" ] || stop 'the boot entry names no root=PARTUUID=' +[ -z "$mapped_root" ] || [ -n "$overlay" ] || stop 'orchard.root=dm requires orchard.overlay=tmpfs' # gpt_partuuid DISK SECTOR_SIZE NUMBER: the unique GUID of GPT entry NUMBER, # read from the disk itself: the kernel's uevent does not report PARTUUID. @@ -78,9 +154,7 @@ lwvm_partuuid() { echo "$1$2$3$4-$5$6-$7$8-$9${10}-${11}${12}${13}${14}${15}${16}" } -device= -ticks=0 -while [ -z "$device" ]; do +partition_root() { for number in /sys/class/block/*/partition; do [ -e "$number" ] || continue part=${number%/partition} @@ -90,59 +164,123 @@ while [ -z "$device" ]; do id=$(gpt_partuuid "/dev/$disk" "$sector" "$(cat "$number")") || id=$(lwvm_partuuid "/dev/$disk" "$(cat "$number")") if [ "$id" = "$root" ]; then - device=/dev/${part##*/} - break + echo "/dev/${part##*/}" + return fi done +} + +# dm-mod.create registers the mapping before /init. Match its UUID to the +# LwVM PARTUUID, since the assigned dm-N number depends on other mappings. +dm_root() { + for part in /sys/class/block/dm-*; do + [ -r "$part/dm/uuid" ] || continue + [ "$(cat "$part/dm/uuid")" = "orchard-lwvm-$root" ] || continue + [ "$(cat "$part/ro")" = 1 ] || continue + [ -b "/dev/${part##*/}" ] || continue + echo "/dev/${part##*/}" + return + done +} + +# Print the current LwVM header's CRC as the four stored bytes, in hex. +# Verify the checksum before considering the backup: a valid primary takes +# precedence, even if an older backup happens to match the boot entry. +lwvm_header_crc() { + local header=$1 sectors=$2 stored calculated + [ "$(wc -c < "$header")" -eq 4096 ] || return 1 + [ "$(od -An -tx1 -v -N 16 "$header" | tr -d ' \n')" = 6a9088cf8afd630ae351e24887e0b98b ] || return 1 + set -- $(od -An -tx1 -v -j 32 -N 8 "$header") + [ "$#" -eq 8 ] && [ "$((0x$8$7$6$5$4$3$2$1))" -eq "$((sectors * 512))" ] || return 1 + stored=$(od -An -tx1 -v -j 44 -N 4 "$header" | tr -d ' \n') + # gzip's trailer starts with the same little-endian CRC32 that LwVM uses. + calculated=$( + { head -c 44 "$header"; printf '\000\000\000\000'; tail -c 4048 "$header"; } | + gzip -c | tail -c 8 | od -An -tx1 -v -N 4 | tr -d ' \n' + ) + [ "${#stored}" -eq 8 ] && [ "$stored" = "$calculated" ] || return 1 + echo "$stored" +} + +# Arguments: whole backing disk and disk size in 512-byte sectors from sysfs. +lwvm_disk_crc() { + local header crc chunk + [ "$2" -ge 16384 ] || return 1 + # /dev is the devtmpfs mounted at the top of this script; /newroot does not exist yet. + header=$(mktemp /dev/.lwvm-header.XXXXXX) || return 1 + if dd if="$1" of="$header" bs=4096 count=1 2>/dev/null && crc=$(lwvm_header_crc "$header" "$2"); then + : + else + chunk=16 + while [ $((chunk * 1024)) -lt "$2" ]; do + chunk=$((chunk * 2)) + done + crc= + if dd if="$1" of="$header" bs=4096 skip=$((chunk / 8 - 1)) count=1 2>/dev/null; then + crc=$(lwvm_header_crc "$header" "$2") + fi + fi + rm -f "$header" + [ -n "$crc" ] || return 1 + echo "$crc" +} + +check_lwvm_mapping() { + [ "${#lwvm_crc}" -eq 8 ] || stop 'the boot entry needs orchard.lwvm_crc= with eight hex digits' + case "$lwvm_crc" in + *[!0-9a-f]*) stop 'the boot entry needs orchard.lwvm_crc= with eight hex digits' ;; + esac + set -- "/sys/class/block/${device##*/}/slaves/"* + [ "$#" -eq 1 ] && [ -e "$1" ] || stop "expected one backing disk for $device" + disk=/dev/${1##*/} + sectors=$(cat "$1/size") || stop "could not read the size of $disk" + actual_crc=$(lwvm_disk_crc "$disk" "$sectors") || stop "could not read a valid LwVM header on $disk" + [ "$actual_crc" = "$lwvm_crc" ] || + stop "LwVM header CRC mismatch on $disk (expected $lwvm_crc, found $actual_crc); regenerate the boot options" +} + +description="partition $root" +[ -z "$mapped_root" ] || description="read-only device-mapper root $root" +ticks=0 +while :; do + if [ -n "$mapped_root" ]; then + device=$(dm_root) + else + device=$(partition_root) + fi [ -n "$device" ] && break if sleep 0.05 2>/dev/null; then ticks=$((ticks + 1)) - [ "$ticks" -le 600 ] || stop "no partition $root after 30 s" else ticks=$((ticks + 20)) - [ "$ticks" -le 600 ] || stop "no partition $root after 30 s" sleep 1 fi + [ "$ticks" -lt 600 ] || stop "no $description after 30 s" done -mkdir -p /newroot -mount ${fstype:+-t "$fstype"} -o "$mode${flags:+,$flags}" "$device" /newroot || stop "could not mount $device" -[ -x "/newroot$init" ] || [ -L "/newroot$init" ] || stop "the root has no $init" +[ -z "$mapped_root" ] || check_lwvm_mapping -# USB for the host: network (usb0) and a serial console (ttyGS0), named after -# the system, so `orchard devices` sees it. What runs on them is the system's. -usb_gadget() { - g=/sys/kernel/config/usb_gadget/orchard-system - mkdir -p /sys/kernel/config && mount -t configfs -o nodev,noexec,nosuid configfs /sys/kernel/config 2>/dev/null - [ ! -e "$g" ] || return 0 - name=$(sed -n 's/^NAME=//p' /newroot/etc/os-release /newroot/usr/lib/os-release 2>/dev/null | head -1 | tr -d "\"'") - board=$(tr '\000' '\n' < /proc/device-tree/compatible | head -1) - # One serial for every boot of this unit (docs/device-protocol.md), or - # the per-boot one if the helper fails: USB must always come up. - serial=$(sh /etc/orchard/usb-identity 2>/dev/null) || - serial="BOOT:$(cat /proc/sys/kernel/random/boot_id) BOARD:${board#apple,}" - # Apple's vendor ID with a product ID macOS lists among the devices it - # grants 2400 mA (docs/device-protocol.md), so a Mac charges the tablet - # at full speed. As an interface-association composite (class 0xef/2/1) - # macOS binds its generic composite driver, which delivers the grant, - # and still the CDC network and serial drivers. - mkdir "$g" && - echo 0x05ac > "$g/idVendor" && - echo 0x1014 > "$g/idProduct" && - echo 0xef > "$g/bDeviceClass" && - echo 0x02 > "$g/bDeviceSubClass" && - echo 0x01 > "$g/bDeviceProtocol" && - mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" && - echo 'Orchard Linux' > "$g/strings/0x409/manufacturer" && - echo "${name:-Linux}" > "$g/strings/0x409/product" && - echo "$serial" > "$g/strings/0x409/serialnumber" && - echo 'USB network and serial' > "$g/configs/c.1/strings/0x409/configuration" && - echo 500 > "$g/configs/c.1/MaxPower" && - mkdir "$g/functions/ncm.usb0" "$g/functions/acm.usb0" && - ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/ncm.usb0" && - ln -s "$g/functions/acm.usb0" "$g/configs/c.1/acm.usb0" && - basename "$(ls -d /sys/class/udc/* | head -1)" > "$g/UDC" +mount_root() { + mkdir -p /newroot || stop 'could not create the root mount point' + if [ -z "$overlay" ]; then + mount ${fstype:+-t "$fstype"} -o "$mode${flags:+,$flags}" "$device" /newroot || + stop "could not mount $device" + return + fi + + # Keep the filesystem and the overlay's backing directories on separate + # mounts. OverlayFS holds references to both after switch_root. + mkdir -p /root-lower /root-overlay || stop 'could not create the overlay mount points' + mount ${fstype:+-t "$fstype"} -o "${flags:+$flags,}ro" "$device" /root-lower || + stop "could not mount $device read-only" + mount -t tmpfs -o mode=0755,size=40% tmpfs /root-overlay || stop 'could not mount the overlay tmpfs' + mkdir /root-overlay/upper /root-overlay/work || stop 'could not create the overlay directories' + mount -t overlay -o lowerdir=/root-lower,upperdir=/root-overlay/upper,workdir=/root-overlay/work overlay /newroot || + stop 'could not mount the root overlay' } +mount_root +[ -x "/newroot$init" ] || [ -L "/newroot$init" ] || stop "the root has no $init" + usb_gadget || echo 'orchard initrd: no USB gadget; continuing without USB' for name in dev proc sys; do diff --git a/chips/s5l8942x.toml b/chips/s5l8942x.toml index 2f77e02bc..68104a164 100644 --- a/chips/s5l8942x.toml +++ b/chips/s5l8942x.toml @@ -19,4 +19,5 @@ reference_version = "Project Cascadia builds its A5 boot chain from 8.4.1 / 12H3 nand_reads = "The 64 GB P105 has eight CAUs per bus, 2088 blocks per CAU and 128 normal pages per block. PR #93 matched 29 live logical pages to physical data and verified both LwVM headers. With the fusion fix, all 954 ranges of the logical disk matched an independent reconstruction from raw flash (docs/bring-up/p105-sftl-device-qualification.md)." nand_program = "On the measured 64 GB P105, H2FMI programmed a 64 MiB file through SFTL with full readback. iOS then booted with clean System and Data filesystems (docs/bring-up/p105-nand-program.md)." nand_checkpoint_gc = "The 64 GB P105 erased all 16 lanes of block 122 and published native accounting before one reuse. Fresh Linux loads recovered the data and wear state; iOS reclaimed the block again before a cold Linux scan found every normal and SLC page blank (docs/bring-up/p105-sftl-device-qualification.md)." +lwvm_root = "The shared initrd supports a read-only device-mapper root with a RAM overlay for scattered LwVM partitions; this needs the armv7 device-mapper kernel options (docs/boot-contract.md)." usb_phy = "P105 uses a 24 MHz reference; the proposed S5L8942X cold-handoff callbacks await an exact-revision boot (docs/bring-up/p105-usb-handoff.md)." diff --git a/devices/p105/device.toml b/devices/p105/device.toml index cc21a027a..41f45ead0 100644 --- a/devices/p105/device.toml +++ b/devices/p105/device.toml @@ -17,6 +17,8 @@ methods = ["jailbreak-kdfu", "recovery-autogo"] entries = ["pico-checkm8", "kdfu"] # Python's CLI consumes an owner-private boot manifest. orchard starts the board by its ibss boot # route (routes.toml) with the public firmware keys in boot.json. +# For a pre-existing root on read-only scattered LwVM flash, the shared initrd +# uses the device-mapper and tmpfs overlay options in docs/boot-contract.md. [kernel] platform = "apple-armv7" # kernel/series/apple-armv7, kernel/configs/apple-armv7 diff --git a/docs/boot-contract.md b/docs/boot-contract.md index 22152d5f4..d68790a95 100644 --- a/docs/boot-contract.md +++ b/docs/boot-contract.md @@ -105,6 +105,14 @@ modules only. It loads them, waits up to 30 s for the partition that given) and starts its `/sbin/init` (or `init=`). If any step fails, it says which one and opens a shell on the console. +`orchard.overlay=tmpfs` makes the initrd mount the root filesystem read-only +and start the system on an OverlayFS mount backed by tmpfs (limited to 40% +of RAM). All changes to that overlay disappear at reboot. The lower +filesystem must be mountable read-only, and the installed system must not +try to fsck or remount it through an `/` entry in `/etc/fstab`. The overlay +requires kernel tmpfs and OverlayFS support. Without the option the initrd +mounts the filesystem directly as usual. + ## Partitions (GPT) | Partition | Type GUID | Filesystem | Count | @@ -130,6 +138,33 @@ take over. Meanwhile the host keeps the Cascadia bundle that starts the installed system (its tree's `bootargs` carry `root=PARTUUID=`), which has to be placed where iOS's boot chain finds it. +### Booting an existing scattered Linux partition + +The kernel's LwVM reader only registers contiguous partitions. To boot a +scattered Linux partition, generate the entry's options on the host from a +current 4096-byte LwVM header (primary or copy) and the partition's GUID: + +```sh +bin/orchard python -m orchard.lwvm_root lwvm-header.bin LINUX-PARTUUID +``` + +The options include `root=PARTUUID=…`, `orchard.root=dm`, +`orchard.overlay=tmpfs`, and a quoted `dm-mod.create=` with a read-only +linear map. The backing disk defaults to `/dev/applesftl0`; pass `--disk` if +the kernel exposes it under another name. Use the emitted line as the root +options for the entry or pass it as `bootargs` to Cascadia assembly, keeping +the literal double quotes around the map. Include any board-specific +console arguments as usual. The complete armv7 command line must fit in +1023 bytes; maps that would exceed that limit by themselves are rejected. + +The kernel must have `CONFIG_BLK_DEV_DM=y`, `CONFIG_DM_INIT=y` and the +backing disk available at device-mapper initialization. The shared initrd +waits for the read-only mapper device whose UUID matches the root PARTUUID, +then uses the tmpfs overlay described above. Recompute the options and +regenerate the payload whenever the LwVM map changes. This path boots an +already prepared filesystem. The automatic installer does not generate +these options or populate scattered partitions. + ## Entries The layout follows BLS: diff --git a/docs/device-protocol.md b/docs/device-protocol.md index a912f52fa..68f5d87dc 100644 --- a/docs/device-protocol.md +++ b/docs/device-protocol.md @@ -32,6 +32,12 @@ serial. No descriptor changes per boot, so macOS can retain accessory approval. Trees without a serial number warn and retain the legacy `BOOT:` identity to keep rescue USB available; those still need approval each boot. +The installed initrd's [scattered LwVM root rescue](boot-contract.md#booting-an-existing-scattered-linux-partition) +uses `0x05ac:0x4144` and the same stable `BOARD: ID:` serial +(or the same `BOOT:` fallback). Hosts may list it as a RAM payload because +it shares the RAM product ID. It offers only an ACM console, without USB +networking or the RAM session's SSH bootstrap. + For RAM sessions, ACM returns `/proc/sys/kernel/random/boot_id` and the SSH host public key together on every connection. The host validates the boot ID and pins that boot's key. Installed systems use their persistent SSH keys and diff --git a/src/orchard/lwvm_root.py b/src/orchard/lwvm_root.py new file mode 100644 index 000000000..e4490d25f --- /dev/null +++ b/src/orchard/lwvm_root.py @@ -0,0 +1,115 @@ +"""Write armv7 boot options for a read-only LwVM root with a RAM overlay.""" +import argparse +import os +from pathlib import Path +import re +import stat +import struct +import uuid +import zlib + + +HEADER_BYTES = 4096 +SECTOR_BYTES = 512 +CHUNKS = 1024 +MAGIC = uuid.UUID('6a9088cf-8afd-630a-e351-e24887e0b98b').bytes +LINUX_TYPE = uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes +ARM_COMMAND_LINE_SIZE = 1024 # includes the terminating NUL + + +def linear_runs(header, partuuid, media_bytes=None): + """Return merged (logical start, length, physical start) in 512-byte sectors.""" + if len(header) != HEADER_BYTES or header[:16] != MAGIC: + raise ValueError('Expected a 4096-byte CRC-protected LwVM header') + media, count, stored_crc = struct.unpack_from('> 12, entry & 0xfff + if partition == 0xf: + continue + if not 0 < physical < media // chunk or partition >= count: + raise ValueError('Invalid LwVM chunk owner or physical address') + if partition == owner: + if logical >= needed or logical in physical_chunks: + raise ValueError('LwVM root has an out-of-range or duplicate logical chunk') + physical_chunks[logical] = physical + if len(physical_chunks) != needed: + raise ValueError('LwVM root chunk coverage is incomplete') + + runs = [] + for index in range(needed): + logical = index * chunk + length = min(chunk, size - logical) + physical = physical_chunks[index] * chunk + if runs and runs[-1][2] + runs[-1][1] == physical: + runs[-1][1] += length + else: + runs.append([logical, length, physical]) + return [tuple(value // SECTOR_BYTES for value in run) for run in runs] + + +def boot_options(header, partuuid, disk='/dev/applesftl0', *, media_bytes=None): + """Return kernel options for the selected partition, using DISK on the device.""" + if not re.fullmatch(r'/dev/[a-zA-Z0-9_-]+', disk): + raise ValueError('Expected the backing disk as a simple /dev/ block device path') + partuuid = uuid.UUID(partuuid) + table = ','.join(f'{start} {length} linear {disk} {offset}' + for start, length, offset in linear_runs(header, partuuid, media_bytes)) + options = (f'root=PARTUUID={partuuid} ro orchard.root=dm orchard.overlay=tmpfs ' + f'orchard.lwvm_crc={header[0x2c:0x30].hex()} ' + f'dm-mod.create="orchard-root,orchard-lwvm-{partuuid},,ro,{table}"') + if len(options) >= ARM_COMMAND_LINE_SIZE: + raise ValueError('LwVM mapping does not fit in the armv7 kernel command line') + return options + + +def read_header(path): + """Read a header dump or the start of a disk image/block device, with its size if known.""" + with path.open('rb') as source: + info = os.fstat(source.fileno()) + media_bytes = None + if stat.S_ISBLK(info.st_mode): + media_bytes = source.seek(0, os.SEEK_END) + source.seek(0) + elif stat.S_ISREG(info.st_mode) and info.st_size != HEADER_BYTES: + media_bytes = info.st_size + return source.read(HEADER_BYTES), media_bytes + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('header', type=Path, help='4096-byte LwVM header (primary or copy), disk image or block device') + parser.add_argument('partuuid', help='Linux partition GUID') + parser.add_argument('--disk', default='/dev/applesftl0', help='backing disk path on the device') + args = parser.parse_args() + try: + header, media_bytes = read_header(args.header) + print(boot_options(header, args.partuuid, args.disk, media_bytes=media_bytes)) + except (OSError, ValueError) as error: + parser.error(str(error)) + + +if __name__ == '__main__': + main() diff --git a/tests/fixtures/p105-scattered-lwvm.bin b/tests/fixtures/p105-scattered-lwvm.bin new file mode 100644 index 0000000000000000000000000000000000000000..8542c215356476d9b97b67b87787a1335da0d866 GIT binary patch literal 4096 zcmeHKWpoxs7JVUTklY{%&b<$JcY+0y;1b+J2<{%--QC^YT}p*|sh2th>a>N@mKvpB zp|JaJ&+f0?JYL;-)h=~2O!8c>^T`6 zz<>2ScL#<(NIxF`UlfRqjti6$wrf|Il}e1dvFAZukM=*Ab@{u}1!t%KjqXozmSjV0 zs3lsze@_3~_+Rh`+e6+3XJdjMtsZQ3EIz;<|0wgHg3ybR`=?Bf89Xm3ve)I9vDYJ_ zxAeYup?;w$P11(XPRiOj!2f`^iyi#y3_NTNt(Wz;VK(w%;_>`gfyW9wR^We4ftzMQ zmMrkTC$|)q(o$J!OJgCH*3wye%V41f3$u)t$ue6O3%3Z%YS}Ei<*=NV%W_*DqsiRz zT0YBf1+1VIvcguxidr!%ZY8Xwm9o-S#>!ebD{mF7qE)iWR>i7XHH)
NvqEvs!& zfg8Q9MO%!;T0N_84XmLxvc}fLnwlX9$qNP(0{h15uc5Tr#qq(=sX0tiD!WI|?S zK{z6i71@v-Igk^%kQ;eG2#&nShx{mjf+&Q-D1xFWhT4JD1)*nhw`X^il~Ij zsDi4fhDcOL4b(&})J7EQpe~{jgILrxVVK??*FZN+S4&WdT;V_QiD30McPT(X?;WWbQGcc537&9^xGcyar8NsZ~#_Y_&oXo}C%tKOi=4C$SX8{&uAr@v4 z7G*IOX9<>MDVAm#mSs7XX9ZSdC01q?R%JCtvN~(9CTp=aqgaP^8O<2RvL5TR0UNRr z8?yCi z2XQcma43gyI7e_KlQ@c_Ifi37j^jCj6FG^KIfYX>jng@UGdYX1IfrvOkMp^J3%Q7k zxr9r(jLW%#E4hlRxrS@Gj_bLB8@Y*_xrJM~joZ0{JGqOyxrckXkNbIm2YHBxd4xxK zjK_I`CwYped4^|sj_3IVFYrk|#i#iUFY;MF$LIM1U*t=CnXm8?U*&6jop10>zQwos z4lnavzQ_0Z0YBtN{Fqnx39s@Ruk%xW#?Sc$zvNf^nm70jzvXwl$y@xMxA_Bq7l3aO}Px)0q1yx9eRYXNqOvP0~B~?nLRYql1PUTfW6;(-ZxAptv>3je(J9Q8mK`UtRWhzVH&Ox8mT0W(rAs*SdG(oP0&P5(qv81 zR87-#&CpEE(rnGqT+P#bEzm+O(qb*qQZ3VRtR!WZdM&T*QC`REdbG!Qtk?7U-oP7r zBX8_Yys0Dz9@aDPXYXx&tZ%@x^tS;v z&<5Gy`z~gf4Yv`2zkHI7ve7oi#@aX=AMn5vZIZRHme$HzTMKXLt-Q6j@o6^Qnpty; uv&lBardnHX=k2|Ncl1u)*}HhWcl8AC=84|jdw5Up "$g/idProduct"', gadget) self.assertIn('echo 0xef > "$g/bDeviceClass"', gadget) - diff --git a/tests/test_lwvm_root.py b/tests/test_lwvm_root.py new file mode 100644 index 000000000..a3f37f1f8 --- /dev/null +++ b/tests/test_lwvm_root.py @@ -0,0 +1,283 @@ +"""Scattered LwVM boot options and the shared initrd's overlay mount sequence.""" +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import uuid +import zlib + +from test_cascadia_loader import PROFILE, cascadia, kernel, loader, tree +from orchard import lwvm_root + + +HERE = Path(__file__).resolve().parent +# The measured 16 GB P105 header after installing the third partition. Only +# the medium and non-Linux partition UUIDs were replaced and the CRC updated. +FIXTURE = HERE / 'fixtures/p105-scattered-lwvm.bin' +PARTUUID = uuid.UUID('1746a46a-ffc1-4a28-844f-0b168b79185f') +SECTORS_PER_CHUNK = 32768 +RUNS = [(0, 19529728, 8978432), (19529728, 163840, 30048256), (19693568, 532840, 30474240)] +MEDIA = 16_000_000_000 +INIT = (HERE.parent / 'boot/initramfs/root/init').read_text() + + +def init_function(name): + return re.search(rf'^{name}\(\) \{{.*?^\}}', INIT, re.M | re.S).group(0) + + +def update_crc(header): + struct.pack_into('&2; exit 1; }\ncheck_lwvm_mapping\n' + result = subprocess.run([*self.shell, f'device=/dev/dm-3 lwvm_crc=$1\n{script}', 'sh', expected], + env=self.env, capture_output=True, text=True, timeout=10) + self.assertEqual([path.name for path in (root / 'dev').glob('.lwvm*')], [], + 'the check left a temporary file behind') + self.assertFalse((root / 'newroot').exists(), 'the check must not need /newroot') + return result + + def test_matching_primary_or_valid_backup_accepts_the_boot_options(self): + header = FIXTURE.read_bytes() + damaged = bytearray(header) + damaged[-1] ^= 1 + wrong_size = bytearray(header) + struct.pack_into('&2; exit 1; } + ''' + script = f'device=/dev/dm-3 mode=rw flags=relatime,rw fstype=ext4 overlay=$1 fail=$2\n{mocks}\n{function}\nmount_root' + return subprocess.run(['sh', '-c', script, 'sh', overlay, fail_at], + capture_output=True, text=True, timeout=10) + + def test_normal_root_uses_the_existing_rw_mount(self): + result = self.mount_commands('') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, 'mount -t ext4 -o rw,relatime,rw /dev/dm-3 /newroot\n') + + def test_overlay_forces_a_read_only_lower_mount(self): + result = self.mount_commands('1') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), [ + 'mount -t ext4 -o relatime,rw,ro /dev/dm-3 /root-lower', + 'mount -t tmpfs -o mode=0755,size=40% tmpfs /root-overlay', + 'mount -t overlay -o lowerdir=/root-lower,upperdir=/root-overlay/upper,workdir=/root-overlay/work overlay /newroot', + ]) + + def test_lower_mount_failure_never_proceeds_to_overlay(self): + result = self.mount_commands('1', '/root-lower') + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stderr, 'could not mount /dev/dm-3 read-only\n') + self.assertEqual(len(result.stdout.splitlines()), 1) From 90608e23c5d7c8035bda3b4007f5476dc674c7ce Mon Sep 17 00:00:00 2001 From: Alexandre Figueiredo <17xande@gmail.com> Date: Mon, 30 Nov 2026 20:10:53 +0200 Subject: [PATCH 2/2] docs: document scattered LwVM roots and the dm kernel options CONFIG_MD, CONFIG_BLK_DEV_DM and CONFIG_DM_INIT are built into the armv7 kernel, merged in OrchardLinux/linux and taken into orchard's lock. Document the generic boot contract and rescue path. The shared initrd's device-mapper path has not yet booted on a device (one RAM boot is pending), so no hardware evidence is claimed. Assisted-by: LLM Signed-off-by: Alexandre Figueiredo <17xande@gmail.com> --- chips/s5l8942x.toml | 1 - devices/p105/device.toml | 2 -- docs/boot-contract.md | 42 +++++++++++++++++++++++++++------------- 3 files changed, 29 insertions(+), 16 deletions(-) diff --git a/chips/s5l8942x.toml b/chips/s5l8942x.toml index 68104a164..2f77e02bc 100644 --- a/chips/s5l8942x.toml +++ b/chips/s5l8942x.toml @@ -19,5 +19,4 @@ reference_version = "Project Cascadia builds its A5 boot chain from 8.4.1 / 12H3 nand_reads = "The 64 GB P105 has eight CAUs per bus, 2088 blocks per CAU and 128 normal pages per block. PR #93 matched 29 live logical pages to physical data and verified both LwVM headers. With the fusion fix, all 954 ranges of the logical disk matched an independent reconstruction from raw flash (docs/bring-up/p105-sftl-device-qualification.md)." nand_program = "On the measured 64 GB P105, H2FMI programmed a 64 MiB file through SFTL with full readback. iOS then booted with clean System and Data filesystems (docs/bring-up/p105-nand-program.md)." nand_checkpoint_gc = "The 64 GB P105 erased all 16 lanes of block 122 and published native accounting before one reuse. Fresh Linux loads recovered the data and wear state; iOS reclaimed the block again before a cold Linux scan found every normal and SLC page blank (docs/bring-up/p105-sftl-device-qualification.md)." -lwvm_root = "The shared initrd supports a read-only device-mapper root with a RAM overlay for scattered LwVM partitions; this needs the armv7 device-mapper kernel options (docs/boot-contract.md)." usb_phy = "P105 uses a 24 MHz reference; the proposed S5L8942X cold-handoff callbacks await an exact-revision boot (docs/bring-up/p105-usb-handoff.md)." diff --git a/devices/p105/device.toml b/devices/p105/device.toml index 41f45ead0..cc21a027a 100644 --- a/devices/p105/device.toml +++ b/devices/p105/device.toml @@ -17,8 +17,6 @@ methods = ["jailbreak-kdfu", "recovery-autogo"] entries = ["pico-checkm8", "kdfu"] # Python's CLI consumes an owner-private boot manifest. orchard starts the board by its ibss boot # route (routes.toml) with the public firmware keys in boot.json. -# For a pre-existing root on read-only scattered LwVM flash, the shared initrd -# uses the device-mapper and tmpfs overlay options in docs/boot-contract.md. [kernel] platform = "apple-armv7" # kernel/series/apple-armv7, kernel/configs/apple-armv7 diff --git a/docs/boot-contract.md b/docs/boot-contract.md index d68790a95..6ecc17a7b 100644 --- a/docs/boot-contract.md +++ b/docs/boot-contract.md @@ -107,9 +107,11 @@ which one and opens a shell on the console. `orchard.overlay=tmpfs` makes the initrd mount the root filesystem read-only and start the system on an OverlayFS mount backed by tmpfs (limited to 40% -of RAM). All changes to that overlay disappear at reboot. The lower -filesystem must be mountable read-only, and the installed system must not -try to fsck or remount it through an `/` entry in `/etc/fstab`. The overlay +of RAM). All changes to that overlay disappear at reboot. Cleanly unmount the +lower filesystem before boot: journal replay cannot write to a read-only +backing device, and skipping replay could expose an inconsistent filesystem. +The installed system must not try to fsck or remount the lower filesystem +through an `/` entry in `/etc/fstab`. The overlay requires kernel tmpfs and OverlayFS support. Without the option the initrd mounts the filesystem directly as usual. @@ -148,22 +150,36 @@ current 4096-byte LwVM header (primary or copy) and the partition's GUID: bin/orchard python -m orchard.lwvm_root lwvm-header.bin LINUX-PARTUUID ``` -The options include `root=PARTUUID=…`, `orchard.root=dm`, -`orchard.overlay=tmpfs`, and a quoted `dm-mod.create=` with a read-only -linear map. The backing disk defaults to `/dev/applesftl0`; pass `--disk` if +The generator also accepts a disk image or block device, in which case it +reads the primary header and checks the recorded medium size against its +backing size. The options include `root=PARTUUID=…`, `orchard.root=dm`, +`orchard.overlay=tmpfs`, `orchard.lwvm_crc=` (the four stored CRC bytes as +lowercase hex), and a quoted `dm-mod.create=` with a read-only linear map. +The backing disk defaults to `/dev/applesftl0`; pass `--disk` if the kernel exposes it under another name. Use the emitted line as the root options for the entry or pass it as `bootargs` to Cascadia assembly, keeping the literal double quotes around the map. Include any board-specific console arguments as usual. The complete armv7 command line must fit in 1023 bytes; maps that would exceed that limit by themselves are rejected. -The kernel must have `CONFIG_BLK_DEV_DM=y`, `CONFIG_DM_INIT=y` and the -backing disk available at device-mapper initialization. The shared initrd -waits for the read-only mapper device whose UUID matches the root PARTUUID, -then uses the tmpfs overlay described above. Recompute the options and -regenerate the payload whenever the LwVM map changes. This path boots an -already prepared filesystem. The automatic installer does not generate -these options or populate scattered partitions. +This path requires an armv7 kernel with `CONFIG_MD=y`, `CONFIG_BLK_DEV_DM=y` +and `CONFIG_DM_INIT=y` built in; the armv7 kernel configuration +(`kernel/configs/apple-armv7/config`) enables all three. The backing disk +must be available at device-mapper initialization. + +The shared initrd waits up to 30 s for the read-only mapper device whose +UUID matches the root PARTUUID. Before mounting, it verifies the LwVM +header checksum and medium size against the mapping's backing disk and +compares the checksum with `orchard.lwvm_crc=`. It uses the backup at the +end of the first chunk only if the primary is unreadable or invalid. If the +mapper device never appears, the header cannot be read, or the checksum +differs, the initrd stops and offers a serial-only USB (ACM) rescue shell +in addition to the local console when the USB controller is available. + +Recompute the options and regenerate the payload whenever the LwVM map +changes. This path boots an already prepared filesystem. The shared initrd's +device-mapper path has not yet booted on a device; one RAM boot is pending. The automatic +installer does not generate these options or populate scattered partitions. ## Entries