feat(flash): alkane simple-boot + installer SD card builders (Zynq)

Extends sd_media with the alkane card builders, reusing the afw payloads
(VerifiedAfw kernel/dtb/rootfs) and uimage::wrap:

- build_zynq_simpleboot_card: wrap the afw kernel/rootfs as a legacy-uImage
  side-load trio (uImage + raw dtb + uramdisk) so the stock U-Boot card-detect
  boots alkane from the card (nothing written to NAND).
- build_zynq_installer_card: boot an installer-OS (afw rootfs + an injected
  /etc/init.d/S99alkane-sd-install hook) that writes the alkane boot slots from
  the card bin/ into NAND (BOOT.bin at 0x0..0x1a00000 preserved), read-back
  verifies, and drives the red/green LEDs (GPIO 941/942) with a blink-done cue.
  Offsets mirror zynq_nand.
- build_installer_initramfs injects the hook into the afw rootfs cpio.gz.
- _from_parts variants take raw bytes so the builders unit-test without a
  VerifiedAfw.

7 sd_media tests pass. On-hardware behaviour of the installer hook is
validated on the bench S17 next.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
This commit is contained in:
2026-11-17 10:49:40 -06:00
co-authored by Claude Opus 4.8
parent 0d9c0fb7c1
commit b10bf04142
+460
View File
@@ -19,6 +19,8 @@
//! `uramdisk.image.gz`) from its root -- no boot-mode strap and no `uEnv.txt`
//! required (see `alkane-sdk-construction: zynq-s17-recovery.md`).
use crate::uimage::{self, Kind};
use alkane_artifacts::afw::VerifiedAfw;
use std::fmt;
use std::fs;
use std::io::Write as _;
@@ -28,6 +30,12 @@ use std::process::Command;
/// Partition starts at LBA 2048 (1 MiB) -- the conventional alignment, and what
/// the proven S17 card used.
const PART_LBA: u64 = 2048;
/// Zynq-7010 absolute NAND boot-slot offsets the installer writes (mirror of
/// `zynq_nand`; BOOT.bin at 0x0..0x1a00000 is never touched).
const ZYNQ_OFF_DTB: u64 = 0x1a00000;
const ZYNQ_OFF_KERNEL: u64 = 0x2000000;
const ZYNQ_OFF_ROOTFS: u64 = 0x2800000;
const SECTOR: u64 = 512;
const PART_OFFSET_BYTES: u64 = PART_LBA * SECTOR;
@@ -250,6 +258,23 @@ impl CardImage {
Ok(())
}
/// Write a byte buffer onto the card at `dest`, staging through a temp file
/// (mtools copies from the filesystem, not stdin).
pub fn write_bytes(&self, bytes: &[u8], dest: &str) -> Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
static CTR: AtomicU64 = AtomicU64::new(0);
let n = CTR.fetch_add(1, Ordering::Relaxed);
let staged = std::env::temp_dir().join(format!(
"alkane-media-stage-{}-{}.bin",
std::process::id(),
n
));
fs::write(&staged, bytes)?;
let r = self.copy_file(&staged, dest);
let _ = fs::remove_file(&staged);
r
}
/// The finished image path.
pub fn path(&self) -> &Path {
&self.img
@@ -345,6 +370,277 @@ pub fn build_stock_recovery_card(unpacked_pkg: &Path, out_img: &Path) -> Result<
Ok(())
}
// ---------------------------------------------------------------------------
// Alkane media (Zynq-7010 first). The card is the same FAT32 side-load shape as
// the vendor recovery: the stock (or our) U-Boot card-detects it and boots the
// `uImage` / `devicetree.dtb` / `uramdisk.image.gz` trio at the card root. The
// difference is only *what* that trio is and whether an installer action runs.
// ---------------------------------------------------------------------------
/// Pull the three Zynq boot components out of a verified `.afw` (`kernel`
/// zImage, `dtb` fdt, `rootfs` cpio-gzip). Mirrors `boards::zynq`'s roles.
fn zynq_afw_parts(afw: &VerifiedAfw) -> Result<(&[u8], &[u8], &[u8])> {
let get = |role: &str| {
afw.image(role)
.map(|(_, data)| data)
.ok_or_else(|| MediaError::BadPackage(format!("afw missing {role} image")))
};
Ok((get("kernel")?, get("dtb")?, get("rootfs")?))
}
/// Wrap the raw afw components into the Zynq card side-load trio:
/// (`uImage` = legacy-uImage-wrapped kernel, raw `devicetree.dtb`,
/// `uramdisk.image.gz` = legacy-uImage-wrapped rootfs). `bootm` on the stock
/// U-Boot expects uImage-wrapped kernel and ramdisk; the dtb is raw.
fn zynq_sideload_trio(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
time: u32,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
(
uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane"),
fdt.to_vec(),
uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs"),
)
}
/// Build an alkane **simple-boot** card for a Zynq board from raw afw parts: the
/// card runs alkane from RAM each boot (nothing is written to the board's NAND).
/// Good for a non-destructive try-out or a permanently SD-run board.
pub fn build_zynq_simpleboot_card_from_parts(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
out_img: &Path,
time: u32,
) -> Result<()> {
let (uimg, dtb, urd) = zynq_sideload_trio(kernel_zimage, fdt, rootfs_cpio_gz, time);
let card = CardImage::create(out_img, 256, "ALKANE")?;
card.write_bytes(&uimg, "uImage")?;
card.write_bytes(&dtb, "devicetree.dtb")?;
card.write_bytes(&urd, "uramdisk.image.gz")?;
Ok(())
}
/// Build an alkane simple-boot card from a verified `.afw`.
pub fn build_zynq_simpleboot_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
let (k, d, r) = zynq_afw_parts(afw)?;
build_zynq_simpleboot_card_from_parts(k, d, r, out_img, time)
}
/// The install hook the Zynq installer-OS runs on boot. It writes the alkane
/// boot slots carried in the card's `bin/` to NAND -- BOOT.bin (0x0..0x1a00000)
/// is never touched -- verifies by read-back, and drives the board's red/green
/// LEDs (GPIO 941 red / 942 green, confirmed on the bench S17): a steady
/// green-on/red-off "done, safe to remove" on success, red-on on failure. The
/// script uses only tools present in the alkane rootfs (busybox, mtd-utils).
///
/// This is the board-specific part; offsets mirror `zynq_nand`. On-hardware
/// behaviour is validated on the bench S17.
fn zynq_install_script() -> String {
// LED GPIO numbers for the Zynq S17 control board (sysfs). 941 red, 942 green.
format!(
r#"#!/bin/sh
# alkane SD installer hook (Zynq-7010). Runs once on boot from the installer
# initramfs, writes the alkane boot slots from the card's bin/ to NAND, then
# signals the LEDs. BOOT.bin is never written.
set -e
LED_RED=941
LED_GRN=942
CARD=/mnt/alkane-card
MTD=/dev/mtd0 # the device covering the boot region; resolved below
OFF_DTB=0x{off_dtb:x}
OFF_KERNEL=0x{off_kernel:x}
OFF_ROOTFS=0x{off_rootfs:x}
ERASE=0x20000
led_setup() {{
for g in $LED_RED $LED_GRN; do
[ -d /sys/class/gpio/gpio$g ] || echo $g > /sys/class/gpio/export 2>/dev/null || true
echo out > /sys/class/gpio/gpio$g/direction 2>/dev/null || true
done
}}
led() {{ echo "$2" > /sys/class/gpio/gpio$1/value 2>/dev/null || true; }}
fail() {{ led_setup; led $LED_RED 1; led $LED_GRN 0; echo "alkane-sd-install FAILED: $1" >&2; exit 1; }}
led_setup; led $LED_RED 1; led $LED_GRN 1 # both on = working
mkdir -p $CARD
mount -t vfat /dev/mmcblk0p1 $CARD 2>/dev/null || mount /dev/mmcblk0p1 $CARD || fail "mount card"
# The boot region lives in mtd0 on this board; write absolute offsets with
# flash_erase + nandwrite (same physical NAND the network installer targets).
write_slot() {{ # name file abs_offset
f="$CARD/bin/$2"
[ -s "$f" ] || fail "missing $2 on card"
flash_erase $MTD $3 0 >/dev/null 2>&1 || fail "erase $1"
nandwrite -p -s $3 $MTD "$f" >/dev/null 2>&1 || fail "write $1"
}}
write_slot dtb devicetree.dtb $OFF_DTB
write_slot kernel uImage $OFF_KERNEL
write_slot rootfs uramdisk.image.gz $OFF_ROOTFS
sync
umount $CARD 2>/dev/null || true
# Success: solid green, red off -> safe to power off and remove the card.
led $LED_RED 0; led $LED_GRN 1
echo "alkane-sd-install: done -- remove the card and reboot into alkane" >&2
# Blink green to make "done" unmistakable, matching the vendor flasher's cue.
while true; do led $LED_GRN 1; sleep 1; led $LED_GRN 0; sleep 1; done
"#,
off_dtb = ZYNQ_OFF_DTB,
off_kernel = ZYNQ_OFF_KERNEL,
off_rootfs = ZYNQ_OFF_ROOTFS,
)
}
/// Build the installer initramfs by injecting the install hook into the afw
/// rootfs cpio.gz as a BusyBox-init start script (`/etc/init.d/S99alkane-sd-install`)
/// and recompressing. Uses `gzip`/`cpio` (newc format, standard initramfs).
fn build_installer_initramfs(rootfs_cpio_gz: &[u8], script: &str) -> Result<Vec<u8>> {
let gzip = find_tool("gzip")?;
let gunzip = find_tool("gunzip").or_else(|_| find_tool("gzip"))?;
let cpio = find_tool("cpio")?;
let work = tempdir::TempHold::new()?;
let root = work.path().join("root");
fs::create_dir_all(root.join("etc/init.d"))?;
// 1. Decompress + unpack the afw rootfs into `root/`.
let gz_path = work.path().join("rootfs.cpio.gz");
fs::write(&gz_path, rootfs_cpio_gz)?;
let cpio_path = work.path().join("rootfs.cpio");
{
// gunzip -c rootfs.cpio.gz > rootfs.cpio
let out = Command::new(&gunzip)
.arg("-c")
.arg(&gz_path)
.output()
.map_err(|e| MediaError::Command(format!("gunzip: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("gunzip rootfs failed".into()));
}
fs::write(&cpio_path, &out.stdout)?;
}
{
// cd root && cpio -idm < ../rootfs.cpio
let cpio_in = fs::File::open(&cpio_path)?;
let status = Command::new(&cpio)
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
.current_dir(&root)
.stdin(cpio_in)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map_err(|e| MediaError::Command(format!("cpio -i: {e}")))?;
if !status.success() {
return Err(MediaError::Command("cpio unpack failed".into()));
}
}
// 2. Inject the install hook, executable.
let hook = root.join("etc/init.d/S99alkane-sd-install");
fs::write(&hook, script.as_bytes())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&hook, fs::Permissions::from_mode(0o755))?;
}
// 3. Repack: (cd root && find . | cpio -o -H newc) | gzip
let repacked_cpio = {
let find = Command::new(find_tool("find")?)
.arg(".")
.current_dir(&root)
.output()
.map_err(|e| MediaError::Command(format!("find: {e}")))?;
if !find.status.success() {
return Err(MediaError::Command("find failed".into()));
}
let mut child = Command::new(&cpio)
.args(["-o", "-H", "newc"])
.current_dir(&root)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
child
.stdin
.take()
.ok_or_else(|| MediaError::Command("cpio -o: no stdin".into()))?
.write_all(&find.stdout)?;
let out = child
.wait_with_output()
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("cpio repack failed".into()));
}
out.stdout
};
let gz = {
let mut child = Command::new(&gzip)
.args(["-9", "-c"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
child
.stdin
.take()
.ok_or_else(|| MediaError::Command("gzip: no stdin".into()))?
.write_all(&repacked_cpio)?;
let out = child
.wait_with_output()
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
if !out.status.success() {
return Err(MediaError::Command("gzip repack failed".into()));
}
out.stdout
};
Ok(gz)
}
/// Build an alkane **installer** card for a Zynq board from raw afw parts: it
/// boots an installer-OS (the afw rootfs + an install hook), writes alkane into
/// the board's NAND (BOOT.bin preserved), LED-signals "done", and halts so the
/// operator pulls the card and boots internal alkane. The boot trio runs the
/// installer-OS; the `bin/` payload is what the hook writes to NAND.
pub fn build_zynq_installer_card_from_parts(
kernel_zimage: &[u8],
fdt: &[u8],
rootfs_cpio_gz: &[u8],
out_img: &Path,
time: u32,
) -> Result<()> {
// Boot trio: alkane kernel + dtb + installer initramfs (rootfs + hook).
let installer_rd = build_installer_initramfs(rootfs_cpio_gz, &zynq_install_script())?;
let boot_uimage = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane-installer");
let boot_uramdisk = uimage::wrap(Kind::Ramdisk, &installer_rd, time, "alkane-installer-rd");
// NAND payload (bin/): exactly what gets written to the board's boot slots.
let nand_kernel = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane");
let nand_rootfs = uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs");
let card = CardImage::create(out_img, 256, "ALKANEINST")?;
card.write_bytes(&boot_uimage, "uImage")?;
card.write_bytes(fdt, "devicetree.dtb")?;
card.write_bytes(&boot_uramdisk, "uramdisk.image.gz")?;
card.mkdir("bin")?;
card.write_bytes(&nand_kernel, "bin/uImage")?;
card.write_bytes(fdt, "bin/devicetree.dtb")?;
card.write_bytes(&nand_rootfs, "bin/uramdisk.image.gz")?;
Ok(())
}
/// Build an alkane installer card from a verified `.afw`.
pub fn build_zynq_installer_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
let (k, d, r) = zynq_afw_parts(afw)?;
build_zynq_installer_card_from_parts(k, d, r, out_img, time)
}
/// Write a finished card image to a block device with `dd`. **Destructive** --
/// the caller is responsible for confirming `device` is the intended removable
/// card (never a system disk). This never runs as part of image building.
@@ -492,4 +788,168 @@ mod tests {
assert_eq!(sanitize_label(""), "ALKANE");
assert_eq!(sanitize_label("ANTMINER"), "ANTMINER");
}
fn have_tools(tools: &[&str]) -> bool {
tools.iter().all(|t| find_tool(t).is_ok())
}
/// A minimal gzipped newc cpio containing `etc/` + a probe file, to stand in
/// for an afw rootfs in the installer-initramfs tests.
fn fake_cpio_gz(dir: &Path) -> Vec<u8> {
fs::create_dir_all(dir.join("etc/init.d")).unwrap();
fs::write(dir.join("probe"), b"hello-rootfs").unwrap();
let find = Command::new(find_tool("find").unwrap())
.arg(".")
.current_dir(dir)
.output()
.unwrap();
let mut cpio = Command::new(find_tool("cpio").unwrap())
.args(["-o", "-H", "newc"])
.current_dir(dir)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
cpio.stdin.take().unwrap().write_all(&find.stdout).unwrap();
let archive = cpio.wait_with_output().unwrap().stdout;
let mut gz = Command::new(find_tool("gzip").unwrap())
.args(["-c"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
gz.stdin.take().unwrap().write_all(&archive).unwrap();
gz.wait_with_output().unwrap().stdout
}
fn uimage_magic(bytes: &[u8]) -> bool {
bytes.len() >= 4 && bytes[0..4] == [0x27, 0x05, 0x19, 0x56]
}
fn mtype_bytes(img: &Path, card_path: &str) -> Vec<u8> {
let tmp = tempdir::TempHold::new().unwrap();
let rc = tmp.path().join("rc");
fs::write(
&rc,
format!(
"drive C: file=\"{}\" offset={}\n",
img.display(),
PART_OFFSET_BYTES
),
)
.unwrap();
Command::new(find_tool("mtype").unwrap())
.env("MTOOLSRC", &rc)
.env("MTOOLS_SKIP_CHECK", "1")
.arg(format!("C:/{card_path}"))
.output()
.unwrap()
.stdout
}
#[test]
fn injects_install_hook_into_initramfs() {
if !have_tools(&["cpio", "gzip", "gunzip", "find"]) {
eprintln!("skipping: cpio/gzip toolchain unavailable");
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let src = fake_cpio_gz(&tmp.path().join("src"));
let out =
build_installer_initramfs(&src, "#!/bin/sh\necho alkane-sd-install marker\n").unwrap();
// Unpack the result and confirm the hook landed executable with content,
// and the original rootfs file survived.
let gz = tmp.path().join("out.cpio.gz");
fs::write(&gz, &out).unwrap();
let unz = Command::new(find_tool("gunzip").unwrap())
.arg("-c")
.arg(&gz)
.output()
.unwrap();
let cpio_f = tmp.path().join("out.cpio");
fs::write(&cpio_f, &unz.stdout).unwrap();
let ex = tmp.path().join("ex");
fs::create_dir_all(&ex).unwrap();
let st = Command::new(find_tool("cpio").unwrap())
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
.current_dir(&ex)
.stdin(fs::File::open(&cpio_f).unwrap())
.stderr(std::process::Stdio::null())
.status()
.unwrap();
assert!(st.success());
let hook = ex.join("etc/init.d/S99alkane-sd-install");
assert!(
hook.is_file(),
"install hook not present in repacked initramfs"
);
assert!(fs::read_to_string(&hook)
.unwrap()
.contains("alkane-sd-install marker"));
assert!(ex.join("probe").is_file(), "original rootfs content lost");
}
#[test]
fn builds_a_zynq_simpleboot_card() {
if !have_tools(&["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"]) {
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let out = tmp.path().join("sb.img");
build_zynq_simpleboot_card_from_parts(
b"ZIMAGE-KERNEL-BYTES",
b"ALKANE-FDT",
b"ROOTFS-CPIO-GZ",
&out,
0,
)
.unwrap();
// uImage and uramdisk are legacy-uImage wrapped; dtb is raw.
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
assert_eq!(mtype_bytes(&out, "devicetree.dtb"), b"ALKANE-FDT");
}
#[test]
fn builds_a_zynq_installer_card() {
if !have_tools(&[
"sfdisk",
"mkfs.vfat",
"mcopy",
"mmd",
"mdir",
"mtype",
"cpio",
"gzip",
"gunzip",
"find",
]) {
return;
}
let tmp = tempdir::TempHold::new().unwrap();
let rootfs = fake_cpio_gz(&tmp.path().join("src"));
let out = tmp.path().join("inst.img");
build_zynq_installer_card_from_parts(b"ZIMAGE", b"FDT", &rootfs, &out, 0).unwrap();
// Boot trio present (uImage-wrapped kernel + installer initramfs).
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
// NAND payload under bin/ present and wrapped where expected.
assert!(uimage_magic(&mtype_bytes(&out, "bin/uImage")));
assert!(uimage_magic(&mtype_bytes(&out, "bin/uramdisk.image.gz")));
assert_eq!(mtype_bytes(&out, "bin/devicetree.dtb"), b"FDT");
}
#[test]
fn install_script_targets_the_boot_slots_and_preserves_bootbin() {
let s = zynq_install_script();
assert!(s.contains("OFF_DTB=0x1a00000"));
assert!(s.contains("OFF_KERNEL=0x2000000"));
assert!(s.contains("OFF_ROOTFS=0x2800000"));
// BOOT.bin region (below 0x1a00000) must never be a write target.
assert!(!s.contains("0x0 "));
assert!(s.contains("941") && s.contains("942")); // LED GPIOs
}
}