diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 9d623271..4f0d094b 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -574,10 +574,10 @@ fn run_install(args: &[String]) -> Result<(), Box> { print!("{}", report.render()); println!("DRY RUN: no file was written into the nvdata UBI."); let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::>().join(", "); - println!("Re-run with --confirm FLASH to stage {targets} into anthillos/ (FIP + mtd0-5 preserved)."); + println!("Re-run with --confirm FLASH to write {targets} into the alkane/ dir on nvdata (FIP + mtd0-5 are not MTD devices)."); } A113dOutcome::Installed(receipt) => { - println!("wrote OS files into {}", receipt.anthillos); + println!("wrote OS files into the alkane/ dir on nvdata volume {}", receipt.volume); for backup in &receipt.backups { match (&backup.path, &backup.md5) { (Some(path), Some(md5)) => println!( diff --git a/crates/alkane-flash/src/boards/a113d.rs b/crates/alkane-flash/src/boards/a113d.rs index 72ef8e60..dead6539 100644 --- a/crates/alkane-flash/src/boards/a113d.rs +++ b/crates/alkane-flash/src/boards/a113d.rs @@ -1,16 +1,18 @@ // SPDX-License-Identifier: MIT //! Amlogic A113D / AXG (Antminer S21 Pro-class) board module: tier-2 network //! UPDATE of a board already running alkane. Our OS is staged as FILES in the -//! nvdata UBI volume (mtd6): anthillos/{vmlinux.bin, devicetree.dtb, -//! uramdisk.image.gz}. The signed FIP bootloader (mtd0/mtd1), the stock boot -//! fallback (mtd4), and mtd2/3/5 are PRESERVED - this module performs ZERO raw -//! NAND writes. It copies three files into an already-mounted UBIFS volume and -//! nothing else, so no code path here can touch a raw /dev/mtd device. +//! nvdata UBI volume: alkane/{vmlinux.bin, devicetree.dtb, uramdisk.image.gz}. +//! (The legacy vendor path name "anthillos" from AnthillOS is no longer used; +//! our own bootcmd loads from alkane/.) //! -//! The brick guard is therefore STRUCTURAL: there is no flash_erase, nandwrite, -//! or dd-to-/dev/mtd anywhere in this module. Each file destination is checked -//! to be a bare basename inside the resolved anthillos directory of a ubifs -//! mount; the raw FIP partitions (mtd0-5) are never named. +//! The running alkane image exposes ONLY the nvdata region as an MTD (the board +//! DT declares a single `nvdata` fixed-partition; the FIP bootloader and the +//! stock boot/recovery/misc/config regions are deliberately undeclared, so they +//! are never registered as MTD devices and cannot be written from Linux). This +//! module attaches UBI to that one nvdata MTD, mounts the UBIFS volume, and +//! overwrites the three files under alkane/. It performs no raw mtd0-5 write and +//! never changes the bootloader: the brick-sensitive regions are physically +//! unreachable. //! //! The first from-stock install (via the vendor toolkit, past the signed //! bootloader) is the dsh-owned path and is NOT this module. This is the @@ -19,7 +21,7 @@ use crate::md5::md5_hex; use crate::preflight::{classify, parse_digest}; use crate::transport::{Remote, RemoteError}; -use alkane_artifacts::afw::{AfwImage, AfwPartition, BootloaderPolicy, VerifiedAfw}; +use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw}; use std::fs; use std::io::Write; use std::path::PathBuf; @@ -28,14 +30,14 @@ use thiserror::Error; pub const BOARD: &str = "a113d"; pub const ARCH: &str = "arm64"; -/// The UBI volume subdirectory the boot chain reads our OS files from. -pub const ANTHILLOS_DIR: &str = "anthillos"; +/// The UBI volume subdirectory our boot chain reads our OS files from. This is +/// alkane's own name; the board's `ourbootcmd` loads from here. +pub const ALKANE_DIR: &str = "alkane"; /// nvdata UBI usable size; the three files together must fit (0xB900000). pub const NVDATA_USABLE: u64 = 0xB900000; -/// Raw NAND partitions that are NEVER a write target (FIP + stock boot). -pub const PRESERVE_DEVICES: [&str; 6] = [ - "/dev/mtd0", "/dev/mtd1", "/dev/mtd2", "/dev/mtd3", "/dev/mtd4", "/dev/mtd5", -]; +/// The only MTD partition our DT exposes. mtd0-5 (FIP + stock boot) are not +/// declared in the DT at all, so they are not MTD devices on a running image. +pub const NVDATA_LABEL: &str = "nvdata"; /// Authoritative file targets: (image, on-board basename, ceiling, format). /// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a @@ -85,7 +87,7 @@ pub enum A113dPlanError { #[derive(Clone, Debug)] pub struct A113dTarget { pub image_name: String, - /// On-board basename inside the anthillos directory (never a device path). + /// On-board basename inside the alkane directory (never a device path). pub dest: String, pub size: u64, pub data: Vec, @@ -114,7 +116,7 @@ fn is_bootloaderish(image: &AfwImage) -> bool { } /// A destination is safe only as a bare basename (no separators, no traversal, -/// not a device path). This is what keeps every write inside anthillos/. +/// not a device path). This keeps every write inside the alkane/ directory. fn is_safe_dest(dest: &str) -> bool { !dest.is_empty() && !dest.contains('/') @@ -152,8 +154,6 @@ impl A113dPlan { if partition.name != "nvdata" && partition.image.is_some() { return Err(A113dPlanError::PreservedCarriesImage(partition.name.clone())); } - // A preserved partition device must be in the never-write set when listed. - let _ = &partition.device; } let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect(); @@ -193,7 +193,6 @@ impl A113dPlan { .image(image_name) .map(|(_, data)| data) .ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?; - // Magic checks, independent of the producer gate. match expected_format { "arm64-image" => { if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") { @@ -243,13 +242,14 @@ impl A113dPlan { pub fn render(&self) -> String { let mut out = format!("board {BOARD} arch {ARCH}\n"); out.push_str( - "tier 2 update: copy OS files into the nvdata UBI (anthillos/); \ - FIP (mtd0/1) + stock boot (mtd4) + mtd2/3/5 preserved, zero raw NAND writes\n", + "tier 2 update: attach UBI to the nvdata MTD, mount it, and overwrite the OS files \ + under alkane/; the FIP + stock boot/recovery/misc/config are not MTD devices at all, \ + so no raw NAND write is possible\n", ); out.push_str("image format kernel=arm64-image, dtb=fdt, rootfs=uimage\n"); for target in &self.targets { out.push_str(&format!( - "copy {} -> {ANTHILLOS_DIR}/{} size {} B md5 {}\n", + "write {} -> {ALKANE_DIR}/{} size {} B md5 {}\n", target.image_name, target.dest, target.size, target.expected_md5 )); } @@ -274,8 +274,12 @@ pub enum A113dError { Preflight(String), #[error("--confirm FLASH is required to write")] Confirm, - #[error("no mounted ubifs volume with an {0}/ directory was found; refusing to write")] - NoAnthillos(String), + #[error("the running image exposes no '{0}' MTD; it needs a NAND-enabled a113d kernel")] + NoNvdataMtd(String), + #[error("could not attach UBI to the nvdata MTD / find its volume")] + UbiAttach, + #[error("could not mount the nvdata UBIFS volume")] + Mount, #[error("refusing an unsafe destination: {0}")] UnsafeDest(String), #[error("{0} staged md5 differs from the verified bundle")] @@ -299,8 +303,9 @@ pub struct A113dCheck { pub struct A113dPreflight { pub host: String, pub checks: Vec, - /// Resolved absolute anthillos directory on a mounted ubifs volume. - pub anthillos: Option, + /// The nvdata MTD index (e.g. 0 for /dev/mtd0), when the running image + /// exposes it. Used for `ubiattach -m `. + pub nvdata_mtd: Option, } impl A113dPreflight { @@ -325,29 +330,20 @@ impl A113dPreflight { } } -/// Find a mounted ubifs volume that already holds an anthillos/ directory - that -/// is where the running alkane boots our OS files from, and the only place this -/// module ever writes. We never attach or mount a raw device ourselves. -fn resolve_anthillos(remote: &mut dyn Remote) -> Result, A113dError> { - let mounts = remote.user_command("cat /proc/mounts 2>/dev/null", Duration::from_secs(20))?; - for line in String::from_utf8_lossy(&mounts).lines() { - let mut fields = line.split_whitespace(); - let _dev = fields.next().unwrap_or(""); - let mountpoint = fields.next().unwrap_or(""); - let fstype = fields.next().unwrap_or(""); - if fstype != "ubifs" || mountpoint.is_empty() { +/// Parse /proc/mtd for a partition labelled "nvdata" and return its mtd index. +/// e.g. `mtd0: 0b900000 00020000 "nvdata"` -> Some(0). +fn parse_nvdata_mtd(proc_mtd: &str) -> Option { + for line in proc_mtd.lines() { + let line = line.trim(); + if !line.starts_with("mtd") { continue; } - let candidate = format!("{}/{ANTHILLOS_DIR}", mountpoint.trim_end_matches('/')); - let probe = remote.user_command( - &format!("test -d {candidate} && echo __HAVE__"), - Duration::from_secs(15), - )?; - if String::from_utf8_lossy(&probe).contains("__HAVE__") { - return Ok(Some(candidate)); + let (dev, rest) = line.split_once(':')?; + if rest.contains(&format!("\"{NVDATA_LABEL}\"")) { + return dev.trim_start_matches("mtd").parse::().ok(); } } - Ok(None) + None } pub fn preflight( @@ -383,7 +379,7 @@ pub fn preflight( checks.push(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") }); let tools = remote.user_command( - "for c in ubiattach mount cp md5sum sync; do \ + "for c in ubiattach ubidetach mount umount cp md5sum sync; do \ command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done", Duration::from_secs(15), )?; @@ -401,20 +397,21 @@ pub fn preflight( }, }); - // nvdata (mtd6) must be present; we never write it raw, but its absence means - // the board is not the expected layout. - let mtd = String::from_utf8_lossy( + // The nvdata MTD must be exposed (NAND-enabled a113d kernel). If absent, the + // running image cannot self-update - it needs the DT with the nvdata + // fixed-partition. mtd0-5 are intentionally never exposed, so nvdata is the + // ONLY mtd this board should ever present. + let proc_mtd = String::from_utf8_lossy( &remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?, ) .into_owned(); - let have_nvdata = mtd.contains("mtd6:"); + let nvdata_mtd = parse_nvdata_mtd(&proc_mtd); checks.push(A113dCheck { - name: "nvdata".to_owned(), - ok: have_nvdata, - detail: if have_nvdata { - "mtd6 (nvdata UBI) present".to_owned() - } else { - format!("mtd6 not found: {mtd}") + name: "nvdata-mtd".to_owned(), + ok: nvdata_mtd.is_some(), + detail: match nvdata_mtd { + Some(n) => format!("nvdata is /dev/mtd{n} (the only exposed MTD)"), + None => format!("no 'nvdata' MTD exposed: {}", proc_mtd.replace('\n', " ")), }, }); @@ -423,24 +420,10 @@ pub fn preflight( checks.push(A113dCheck { name: "file-only".to_owned(), ok: dests_safe, - detail: format!( - "all writes are files in {ANTHILLOS_DIR}/; raw {} never touched", - PRESERVE_DEVICES.join(",") - ), + detail: format!("all writes are files under {ALKANE_DIR}/ on the nvdata UBI"), }); - // Resolve the anthillos directory on a mounted ubifs volume. - let anthillos = resolve_anthillos(remote)?; - checks.push(A113dCheck { - name: "anthillos".to_owned(), - ok: anthillos.is_some(), - detail: match &anthillos { - Some(path) => format!("writing into {path}"), - None => "no mounted ubifs volume with anthillos/".to_owned(), - }, - }); - - Ok(A113dPreflight { host: host.to_owned(), checks, anthillos }) + Ok(A113dPreflight { host: host.to_owned(), checks, nvdata_mtd }) } #[derive(Clone, Debug)] @@ -462,7 +445,7 @@ pub struct A113dBackup { #[derive(Clone, Debug)] pub struct A113dReceipt { - pub anthillos: String, + pub volume: String, pub backups: Vec, pub rebooted: bool, } @@ -472,6 +455,54 @@ pub enum A113dOutcome { Installed(A113dReceipt), } +const MNT: &str = "/tmp/.alkane-nvdata"; + +/// Attach UBI to the nvdata MTD and mount its single user volume read-write. +/// Returns (ubi device number, volume name). The volume name is DISCOVERED, never +/// assumed (vendor histories leave different names: umc_os_rootfs, nvdada_log, +/// overlay, ...). +fn attach_and_mount( + remote: &mut dyn Remote, + nvdata_mtd: u32, +) -> Result { + // Attach (idempotent: if ubi0 already exists, reuse it). + let _ = remote.root_command( + &format!( + "if [ ! -d /sys/class/ubi/ubi0 ]; then ubiattach -m {nvdata_mtd} -d 0 >/dev/null 2>&1; fi" + ), + Duration::from_secs(60), + )?; + // Discover the first user volume name under ubi0. + let name = String::from_utf8_lossy(&remote.root_command( + "for n in /sys/class/ubi/ubi0_*/name; do [ -f \"$n\" ] && cat \"$n\" && break; done", + Duration::from_secs(20), + )?) + .trim() + .to_owned(); + if name.is_empty() { + return Err(A113dError::UbiAttach); + } + // Mount it read-write. + remote.root_command( + &format!("mkdir -p {MNT} && mount -t ubifs ubi0:{name} {MNT}"), + Duration::from_secs(60), + )?; + // Confirm the mount actually took. + let mounted = + remote.user_command(&format!("mount | grep -c ' {MNT} '"), Duration::from_secs(20))?; + if String::from_utf8_lossy(&mounted).trim() == "0" { + return Err(A113dError::Mount); + } + Ok(name) +} + +fn unmount(remote: &mut dyn Remote) { + let _ = remote.root_command( + &format!("sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"), + Duration::from_secs(60), + ); +} + pub fn install( plan: &A113dPlan, remote: &mut dyn Remote, @@ -488,83 +519,93 @@ pub fn install( if options.confirm.as_deref() != Some("FLASH") { return Err(A113dError::Confirm); } - let anthillos = report - .anthillos - .clone() - .ok_or_else(|| A113dError::NoAnthillos(ANTHILLOS_DIR.to_owned()))?; + let nvdata_mtd = report + .nvdata_mtd + .ok_or_else(|| A113dError::NoNvdataMtd(NVDATA_LABEL.to_owned()))?; fs::create_dir_all(&options.backup_dir)?; let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); + + let volume = attach_and_mount(remote, nvdata_mtd)?; + let alkane_dir = format!("{MNT}/{ALKANE_DIR}"); + let _ = remote.root_command(&format!("mkdir -p {alkane_dir}"), Duration::from_secs(20))?; + let mut backups = Vec::new(); + let result = (|| -> Result<(), A113dError> { + for target in &plan.targets { + // Structural guard at the point of writing: a bare basename only. + if !is_safe_dest(&target.dest) { + return Err(A113dError::UnsafeDest(target.dest.clone())); + } + let name = &target.image_name; + let dest_path = format!("{alkane_dir}/{}", target.dest); - for target in &plan.targets { - // Structural guard, re-asserted at the point of writing: the destination - // is a bare basename inside anthillos/. No raw device can be named here. - if !is_safe_dest(&target.dest) { - return Err(A113dError::UnsafeDest(target.dest.clone())); - } - let name = &target.image_name; - let dest_path = format!("{anthillos}/{}", target.dest); + // Back up the existing file, if present. + let have = remote.user_command( + &format!("test -f {dest_path} && echo __YES__"), + Duration::from_secs(15), + )?; + if String::from_utf8_lossy(&have).contains("__YES__") { + let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest)); + remote.pull(&dest_path, &local, Duration::from_secs(300))?; + let data = fs::read(&local)?; + backups.push(A113dBackup { + image_name: name.clone(), + dest: target.dest.clone(), + md5: Some(md5_hex(&data)), + size: data.len() as u64, + path: Some(local), + }); + } else { + backups.push(A113dBackup { + image_name: name.clone(), + dest: target.dest.clone(), + md5: None, + size: 0, + path: None, + }); + } - // Back up the existing file we are about to overwrite, if present. - let have = remote.user_command( - &format!("test -f {dest_path} && echo __YES__"), - Duration::from_secs(15), - )?; - if String::from_utf8_lossy(&have).contains("__YES__") { - let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest)); - remote.pull(&dest_path, &local, Duration::from_secs(300))?; - let data = fs::read(&local)?; - backups.push(A113dBackup { - image_name: name.clone(), - dest: target.dest.clone(), - md5: Some(md5_hex(&data)), - size: data.len() as u64, - path: Some(local), - }); - } else { - backups.push(A113dBackup { - image_name: name.clone(), - dest: target.dest.clone(), - md5: None, - size: 0, - path: None, - }); - } + // Stage the verified payload and prove its remote md5 before copying. + let mut staged = tempfile::NamedTempFile::new()?; + staged.write_all(&target.data)?; + staged.flush()?; + let remote_stage = format!("/tmp/.alkane-a113d-{name}.img"); + remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?; + let staged_md5 = parse_digest( + &remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?, + 32, + ) + .unwrap_or_default(); + if staged_md5 != target.expected_md5 { + let _ = + remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15)); + return Err(A113dError::StageMismatch(name.clone())); + } - // Stage the verified payload and prove its remote md5 before copying. - let mut staged = tempfile::NamedTempFile::new()?; - staged.write_all(&target.data)?; - staged.flush()?; - let remote_stage = format!("/tmp/.alkane-a113d-{name}.img"); - remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?; - let staged_md5 = parse_digest( - &remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?, - 32, - ) - .unwrap_or_default(); - if staged_md5 != target.expected_md5 { + // Copy into the UBIFS volume (file write only), then sync. + remote.root_command( + &format!("cp -f {remote_stage} {dest_path} && sync"), + Duration::from_secs(300), + )?; + + // Read back the copied file and compare md5. + let readback = parse_digest( + &remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?, + 32, + ) + .unwrap_or_default(); let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15)); - return Err(A113dError::StageMismatch(name.clone())); + if readback != target.expected_md5 { + return Err(A113dError::Readback(name.clone())); + } } + Ok(()) + })(); - // Copy into the UBI volume (file write only), then sync. No raw NAND. - remote.root_command( - &format!("cp -f {remote_stage} {dest_path} && sync"), - Duration::from_secs(300), - )?; - - // Read back the copied file and compare md5. - let readback = parse_digest( - &remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?, - 32, - ) - .unwrap_or_default(); - let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15)); - if readback != target.expected_md5 { - return Err(A113dError::Readback(name.clone())); - } - } + // Always unmount/detach, success or failure, before returning or rebooting. + unmount(remote); + result?; let rebooted = if options.no_reboot { false @@ -572,7 +613,7 @@ pub fn install( remote.reboot()?; true }; - Ok(A113dOutcome::Installed(A113dReceipt { anthillos, backups, rebooted })) + Ok(A113dOutcome::Installed(A113dReceipt { volume, backups, rebooted })) } pub fn owns_board(board: &str) -> bool { @@ -582,14 +623,7 @@ pub fn owns_board(board: &str) -> bool { /// True when no plan target would ever name a preserved raw partition. Used by /// tests to assert the structural guard holds for the fixed TARGETS table. pub fn no_raw_device_targets(plan: &A113dPlan) -> bool { - plan.targets.iter().all(|t| { - is_safe_dest(&t.dest) && !PRESERVE_DEVICES.iter().any(|d| t.dest.contains(d)) - }) -} - -#[allow(dead_code)] -fn _partition_is_preserved(p: &AfwPartition) -> bool { - p.name != "nvdata" + plan.targets.iter().all(|t| is_safe_dest(&t.dest)) } #[cfg(test)] @@ -679,13 +713,12 @@ mod tests { // write order rootfs, dtb, kernel (kernel file lands last) assert_eq!(plan.targets[0].image_name, "rootfs"); assert_eq!(plan.targets[2].image_name, "kernel"); - // Every destination is a bare basename - no raw device anywhere. assert!(no_raw_device_targets(&plan)); for t in &plan.targets { assert!(!t.dest.contains('/'), "{} has a path, not a basename", t.image_name); } - assert!(plan.render().contains("anthillos/")); - assert!(plan.render().contains("zero raw NAND writes")); + assert!(plan.render().contains("alkane/")); + assert!(plan.render().contains("no raw NAND write is possible")); } #[test] @@ -740,9 +773,6 @@ mod tests { fn every_target_is_a_basename_never_a_device() { for (image, dest, _ceiling, _fmt) in TARGETS { assert!(is_safe_dest(dest), "{image} dest {dest} is not a safe basename"); - for dev in PRESERVE_DEVICES { - assert!(!dest.contains(dev), "{image} dest names a preserved device"); - } } } @@ -753,4 +783,15 @@ mod tests { assert!(!is_safe_dest("sub/dir/file")); assert!(is_safe_dest("vmlinux.bin")); } + + #[test] + fn parses_the_nvdata_mtd_index() { + let proc_mtd = "dev: size erasesize name\n\ + mtd0: 0b900000 00020000 \"nvdata\"\n"; + assert_eq!(parse_nvdata_mtd(proc_mtd), Some(0)); + // No nvdata line -> None (the no-NAND running image). + assert_eq!(parse_nvdata_mtd("dev: size erasesize name\n"), None); + // Different index is honored. + assert_eq!(parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"), Some(3)); + } }