Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
117e572407 | ||
|
|
036b44f6bb | ||
|
|
0873d2c79d | ||
|
|
12a11edfd7 | ||
|
|
71ab5a957c | ||
|
|
f6c740bc24 | ||
|
|
968173095e |
@@ -60,12 +60,47 @@ const SLOT_STOCK_BACKUP: u64 = 0x2000000;
|
||||
/// Where the backup data lives inside the 32 MiB stock-backup region: the first
|
||||
/// erase block holds the manifest, the images follow, each erase-block aligned.
|
||||
const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000
|
||||
const BK_MAGIC: &[u8; 8] = b"ALKSTKB1";
|
||||
/// v1 (data-only) backup magic. v1 backups cannot be safely restored: they lack
|
||||
/// the genuine stock OOB, so a restore recomputes the alkane soft-BCH ECC which
|
||||
/// the stock boot chain cannot read (boot-loop brick).
|
||||
const BK_MAGIC_V1: &[u8; 8] = b"ALKSTKB1";
|
||||
/// v2 backup magic. v2 stores each boot image's genuine NAND data *with its OOB*
|
||||
/// (the stock ECC bytes), so a restore writes the slots back via
|
||||
/// `nandwrite --noecc --oob` byte-identical to original stock and the stock
|
||||
/// boot chain reads them. See alkane-zynq-image-bringup.md, 2026-11-13.
|
||||
const BK_MAGIC_V2: &[u8; 8] = b"ALKSTKB2";
|
||||
/// Scratch erase block (the last block of the 32 MiB stock-backup region),
|
||||
/// used to prove `nandwrite --noecc --oob` round-trips on this board's tools
|
||||
/// before any boot slot is written. Never holds backup images or the manifest.
|
||||
const BK_SCRATCH: u64 = OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE; // 0x7fe0000
|
||||
|
||||
fn round_up(value: u64, to: u64) -> u64 {
|
||||
value.div_ceil(to) * to
|
||||
}
|
||||
|
||||
/// Append a method-free progress line to the file named by `$ALKANE_OUTCOME_LOG`,
|
||||
/// if set. This lets a sealed, DSH-driven from-stock install report its own
|
||||
/// progress (root obtained, carve step, write+verify, reboot) WITHOUT relying on
|
||||
/// DSH to summarise the run. Every line is written by this code and carries only
|
||||
/// NAND/flow facts - never the stock-access or root-on-stock method, which lives
|
||||
/// behind `crate::stock` and never calls this. The file is written by the
|
||||
/// toolkit process on the workstation, so the operator can read it even though
|
||||
/// the sealed DSH stdout is quarantined.
|
||||
fn outcome(msg: &str) {
|
||||
if let Ok(path) = std::env::var("ALKANE_OUTCOME_LOG") {
|
||||
if !path.is_empty() {
|
||||
use std::io::Write as _;
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
{
|
||||
let _ = writeln!(f, "{msg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Root shells
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -352,32 +387,221 @@ fn write_abs(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst`
|
||||
/// (used when carving the on-board stock backup). `dst` must be erase aligned.
|
||||
fn copy_abs(
|
||||
/// NAND page (write) size and OOB size for a partition, from sysfs. Needed to
|
||||
/// reason about the data+OOB blob geometry and to run the OOB self-check.
|
||||
fn oob_geometry(sh: &mut dyn Shell, dev: &str) -> Result<(u64, u64), StockError> {
|
||||
let ws = sh
|
||||
.exec(&format!("cat /sys/class/mtd/{dev}/writesize 2>/dev/null"))?
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StockError::Method(format!("{dev}: no writesize in sysfs")))?;
|
||||
let oob = sh
|
||||
.exec(&format!("cat /sys/class/mtd/{dev}/oobsize 2>/dev/null"))?
|
||||
.trim()
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StockError::Method(format!("{dev}: no oobsize in sysfs")))?;
|
||||
if ws == 0 || oob == 0 {
|
||||
return Err(StockError::Method(format!(
|
||||
"{dev}: implausible NAND geometry (write {ws}, oob {oob})"
|
||||
)));
|
||||
}
|
||||
Ok((ws, oob))
|
||||
}
|
||||
|
||||
/// Dump `data_len` bytes of NAND at absolute `abs` *with OOB* into a board file,
|
||||
/// returning (remote_path, blob_len). `data_len` is rounded up to a whole page
|
||||
/// by the caller so `nanddump` emits only complete pages. The blob is data
|
||||
/// interleaved with OOB exactly as `nanddump` emits it and `nandwrite --oob`
|
||||
/// consumes it.
|
||||
fn dump_with_oob(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
src: u64,
|
||||
dst: u64,
|
||||
len: u64,
|
||||
abs: u64,
|
||||
data_len: u64,
|
||||
label: &str,
|
||||
) -> Result<(String, u64), StockError> {
|
||||
let (dev, rel) = locate(table, abs, data_len)?;
|
||||
let dev = dev.to_owned();
|
||||
let remote = format!("/tmp/alk/{label}.oob");
|
||||
sh.exec("mkdir -p /tmp/alk")?;
|
||||
sh.exec_long(&format!(
|
||||
"nanddump --oob -s 0x{rel:x} -l {data_len} /dev/{dev} -f {remote} >/dev/null 2>&1 && echo DUMPED"
|
||||
))
|
||||
.and_then(|o| {
|
||||
if o.contains("DUMPED") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method(format!(
|
||||
"{label}: nanddump (with OOB) failed: {o}"
|
||||
)))
|
||||
}
|
||||
})?;
|
||||
let blob_len = first_token(&sh.exec(&format!("wc -c < {remote}"))?)
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StockError::Method(format!("{label}: cannot size the OOB blob")))?;
|
||||
if blob_len <= data_len {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label}: OOB blob {blob_len} B not larger than data {data_len} B - OOB was not \
|
||||
captured (nanddump omitted OOB?). Refusing: a restore from this backup could not \
|
||||
reproduce the stock ECC."
|
||||
)));
|
||||
}
|
||||
Ok((remote, blob_len))
|
||||
}
|
||||
|
||||
/// Store a board file verbatim into the backup region at absolute `abs` (opaque
|
||||
/// bytes written as data with `nandwrite -p`; the backup region's own ECC is
|
||||
/// irrelevant because the blob is read back from the data area with
|
||||
/// `--omitoob`). Read-back-verified by md5 against the source file.
|
||||
fn store_blob(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
abs: u64,
|
||||
remote: &str,
|
||||
blob_len: u64,
|
||||
label: &str,
|
||||
) -> Result<(), StockError> {
|
||||
let (sdev, srel) = locate(table, src, len)?;
|
||||
let sdev = sdev.to_owned();
|
||||
let (ddev, drel) = locate(table, dst, len)?;
|
||||
let ddev = ddev.to_owned();
|
||||
let blocks = round_up(len, ERASE) / ERASE;
|
||||
let tmp = format!("/tmp/alk/{label}.bak");
|
||||
sh.exec("mkdir -p /tmp/alk")?;
|
||||
let out = sh.exec_long(&format!(
|
||||
"nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \
|
||||
flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
|
||||
nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \
|
||||
rm -f {tmp} && echo COPIED"
|
||||
))?;
|
||||
if !out.contains("COPIED") {
|
||||
if !abs.is_multiple_of(ERASE) {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label}: backup copy failed: {out}"
|
||||
"{label}: blob dst 0x{abs:x} not erase-aligned"
|
||||
)));
|
||||
}
|
||||
let (dev, rel) = locate(table, abs, blob_len)?;
|
||||
let dev = dev.to_owned();
|
||||
let blocks = round_up(blob_len, ERASE) / ERASE;
|
||||
sh.exec_long(&format!(
|
||||
"flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \
|
||||
nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo STORED"
|
||||
))
|
||||
.and_then(|o| {
|
||||
if o.contains("STORED") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method(format!("{label}: store blob failed: {o}")))
|
||||
}
|
||||
})?;
|
||||
let want = first_token(&sh.exec(&format!("md5sum {remote}"))?);
|
||||
let got = first_token(&sh.exec_long(&format!(
|
||||
"nanddump -s 0x{rel:x} -l {blob_len} --omitoob /dev/{dev} 2>/dev/null | md5sum"
|
||||
))?);
|
||||
if want != got {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label}: stored blob read-back md5 {got} != {want}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prove `nandwrite --noecc --oob` + `nanddump` round-trip the genuine stock OOB
|
||||
/// on this board, using the throwaway scratch block, BEFORE any boot slot is
|
||||
/// written. The test vector is the first real page (data+OOB) of the kernel
|
||||
/// backup blob, so this tests the exact bytes the restore will write. A board
|
||||
/// whose tools ignore --noecc/--oob (e.g. the busybox applets) or lay the OOB
|
||||
/// out differently fails here and the restore aborts untouched - the
|
||||
/// alternative is an ECC-mismatch brick recoverable only by the SD card.
|
||||
fn scratch_selfcheck(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
kernel_blob_abs: u64,
|
||||
) -> Result<(), StockError> {
|
||||
let (sdev, srel) = locate(table, BK_SCRATCH, ERASE)?;
|
||||
let sdev = sdev.to_owned();
|
||||
let (ws, oob) = oob_geometry(sh, &sdev)?;
|
||||
let page = ws + oob;
|
||||
let (bdev, brel) = locate(table, kernel_blob_abs, page)?;
|
||||
let bdev = bdev.to_owned();
|
||||
sh.exec("mkdir -p /tmp/alk")?;
|
||||
// Take the first page+OOB of the kernel blob (data area of the backup
|
||||
// region), write it raw to scratch, read it back with OOB and compare.
|
||||
let out = sh.exec_long(&format!(
|
||||
"nanddump -s 0x{brel:x} -l {page} --omitoob /dev/{bdev} -f /tmp/alk/sc.in >/dev/null 2>&1 && \
|
||||
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 && \
|
||||
nandwrite --noecc --oob -s 0x{srel:x} /dev/{sdev} /tmp/alk/sc.in >/dev/null 2>&1 && \
|
||||
nanddump --noecc --oob -s 0x{srel:x} -l {ws} /dev/{sdev} -f /tmp/alk/sc.out >/dev/null 2>&1 && \
|
||||
A=$(md5sum < /tmp/alk/sc.in) && B=$(md5sum < /tmp/alk/sc.out) && \
|
||||
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 ; \
|
||||
rm -f /tmp/alk/sc.in /tmp/alk/sc.out ; \
|
||||
[ \"$A\" = \"$B\" ] && echo SCOK || echo SCFAIL"
|
||||
))?;
|
||||
if !out.contains("SCOK") {
|
||||
return Err(StockError::Method(
|
||||
"OOB self-check failed: `nandwrite --noecc --oob` does not round-trip the stock OOB on \
|
||||
this board (busybox applet without --noecc/--oob, or a different OOB layout). Refusing \
|
||||
to write the boot slots: an ECC-mismatch restore would brick the board (SD-card \
|
||||
recovery only). The alkane image must ship full mtd-utils nandwrite/nanddump."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restore one boot slot from its v2 backup entry: retrieve the data+OOB blob
|
||||
/// from the backup region, write it to the slot with `nandwrite --noecc --oob`
|
||||
/// (reproducing the exact stock ECC), and read it back WITH OOB to confirm the
|
||||
/// slot is byte-identical to original stock. Never reboots; the caller reboots
|
||||
/// only after every slot verifies.
|
||||
fn restore_slot_raw_oob(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
entry: &BackupEntry,
|
||||
dst_abs: u64,
|
||||
label: &str,
|
||||
) -> Result<(), StockError> {
|
||||
if dst_abs < BOOTBIN_PRESERVE {
|
||||
return Err(StockError::Method(format!(
|
||||
"refusing to restore {label} at 0x{dst_abs:x}: inside preserved BOOT.bin"
|
||||
)));
|
||||
}
|
||||
if !dst_abs.is_multiple_of(ERASE) {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label} dst 0x{dst_abs:x} not erase-aligned"
|
||||
)));
|
||||
}
|
||||
// Retrieve the opaque blob (data+OOB) from the backup region's data area.
|
||||
let (bdev, brel) = locate(table, entry.blob_abs, entry.blob_len)?;
|
||||
let bdev = bdev.to_owned();
|
||||
let blob = format!("/tmp/alk/{label}.rst");
|
||||
sh.exec("mkdir -p /tmp/alk")?;
|
||||
sh.exec_long(&format!(
|
||||
"nanddump -s 0x{brel:x} -l {blen} --omitoob /dev/{bdev} -f {blob} >/dev/null 2>&1 && echo GOT",
|
||||
blen = entry.blob_len
|
||||
))
|
||||
.and_then(|o| {
|
||||
if o.contains("GOT") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method(format!("{label}: blob retrieve failed: {o}")))
|
||||
}
|
||||
})?;
|
||||
// Write raw (data+OOB) to the boot slot.
|
||||
let (ddev, drel) = locate(table, dst_abs, entry.data_len)?;
|
||||
let ddev = ddev.to_owned();
|
||||
let blocks = round_up(entry.data_len, ERASE) / ERASE;
|
||||
sh.exec_long(&format!(
|
||||
"flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
|
||||
nandwrite --noecc --oob -s 0x{drel:x} /dev/{ddev} {blob} >/dev/null 2>&1 && echo WROTE"
|
||||
))
|
||||
.and_then(|o| {
|
||||
if o.contains("WROTE") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method(format!("{label}: raw restore write failed: {o}")))
|
||||
}
|
||||
})?;
|
||||
// Read back RAW (no ECC correction) WITH OOB and compare to the blob:
|
||||
// byte-identical data+stock-ECC. `nanddump` defaults to --omitoob and to
|
||||
// ECC-correcting; both are wrong here (the slot carries foreign stock ECC
|
||||
// the alkane soft-BCH engine would "correct" into garbage), so read raw.
|
||||
let want = first_token(&sh.exec(&format!("md5sum {blob}"))?);
|
||||
let got = first_token(&sh.exec_long(&format!(
|
||||
"nanddump --noecc --oob -s 0x{drel:x} -l {dlen} /dev/{ddev} 2>/dev/null | md5sum",
|
||||
dlen = entry.data_len
|
||||
))?);
|
||||
sh.exec(&format!("rm -f {blob}"))?;
|
||||
if want != got {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label}: restored slot read-back md5 {got} != backup {want} (data+OOB mismatch); \
|
||||
NOT rebooting"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
@@ -430,34 +654,37 @@ fn first_token(s: &str) -> String {
|
||||
// On-board stock backup manifest
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
/// One backed-up boot image: where its genuine data+OOB blob lives in the
|
||||
/// stock-backup region (`blob_abs`), the blob's byte length (`blob_len`, data
|
||||
/// interleaved with OOB as `nanddump` emits it), and the original on-NAND data
|
||||
/// length (`data_len`, OOB excluded) that the boot slot occupies.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct BackupEntry {
|
||||
blob_abs: u64,
|
||||
blob_len: u64,
|
||||
data_len: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct BackupManifest {
|
||||
kernel_abs: u64,
|
||||
kernel_len: u64,
|
||||
dtb_abs: u64,
|
||||
dtb_len: u64,
|
||||
rootfs_abs: u64,
|
||||
rootfs_len: u64,
|
||||
kernel: BackupEntry,
|
||||
dtb: BackupEntry,
|
||||
rootfs: BackupEntry,
|
||||
}
|
||||
|
||||
impl BackupManifest {
|
||||
fn encode(&self) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity(64);
|
||||
v.extend_from_slice(BK_MAGIC);
|
||||
for n in [
|
||||
self.kernel_abs,
|
||||
self.kernel_len,
|
||||
self.dtb_abs,
|
||||
self.dtb_len,
|
||||
self.rootfs_abs,
|
||||
self.rootfs_len,
|
||||
] {
|
||||
v.extend_from_slice(&n.to_be_bytes());
|
||||
let mut v = Vec::with_capacity(8 + 9 * 8);
|
||||
v.extend_from_slice(BK_MAGIC_V2);
|
||||
for e in [self.kernel, self.dtb, self.rootfs] {
|
||||
for n in [e.blob_abs, e.blob_len, e.data_len] {
|
||||
v.extend_from_slice(&n.to_be_bytes());
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
fn decode(b: &[u8]) -> Option<Self> {
|
||||
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
|
||||
if b.len() < 8 + 9 * 8 || &b[..8] != BK_MAGIC_V2 {
|
||||
return None;
|
||||
}
|
||||
let g = |i: usize| {
|
||||
@@ -465,52 +692,102 @@ impl BackupManifest {
|
||||
a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]);
|
||||
u64::from_be_bytes(a)
|
||||
};
|
||||
let e = |base: usize| BackupEntry {
|
||||
blob_abs: g(base),
|
||||
blob_len: g(base + 1),
|
||||
data_len: g(base + 2),
|
||||
};
|
||||
Some(BackupManifest {
|
||||
kernel_abs: g(0),
|
||||
kernel_len: g(1),
|
||||
dtb_abs: g(2),
|
||||
dtb_len: g(3),
|
||||
rootfs_abs: g(4),
|
||||
rootfs_len: g(5),
|
||||
kernel: e(0),
|
||||
dtb: e(3),
|
||||
rootfs: e(6),
|
||||
})
|
||||
}
|
||||
/// A v1 (data-only) backup is present but NOT safely restorable (no stock
|
||||
/// OOB captured). Detected so restore can refuse with a clear message.
|
||||
fn is_v1(b: &[u8]) -> bool {
|
||||
b.len() >= 8 && &b[..8] == BK_MAGIC_V1
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture one genuine-stock image (data+OOB) into the backup region at
|
||||
/// `dst_abs`, checking it stays below the scratch block, and return its entry.
|
||||
fn capture_entry(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
src_abs: u64,
|
||||
data_len: u64,
|
||||
dst_abs: u64,
|
||||
label: &str,
|
||||
) -> Result<BackupEntry, StockError> {
|
||||
let (remote, blob_len) = dump_with_oob(sh, table, src_abs, data_len, label)?;
|
||||
if dst_abs + round_up(blob_len, ERASE) > BK_SCRATCH {
|
||||
return Err(StockError::Method(
|
||||
"stock backup (with OOB) does not fit in the backup region below the scratch block"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
store_blob(sh, table, dst_abs, &remote, blob_len, label)?;
|
||||
sh.exec(&format!("rm -f {remote}"))?;
|
||||
Ok(BackupEntry {
|
||||
blob_abs: dst_abs,
|
||||
blob_len,
|
||||
data_len,
|
||||
})
|
||||
}
|
||||
|
||||
/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the
|
||||
/// stock-backup region, with a manifest in its first block, so the board can be
|
||||
/// returned to its own factory stock later with no vendor file. Called on the
|
||||
/// stock side during a from-stock install, before the boot slots are overwritten.
|
||||
/// stock-backup region *with their OOB* (a v2 backup), with a manifest in its
|
||||
/// first block, so the board can be returned to its own factory stock later -
|
||||
/// over the network, byte-identical to stock ECC - with no vendor file. Called
|
||||
/// on the stock side during a from-stock install, before the boot slots are
|
||||
/// overwritten. Each image's data+OOB blob is captured and stored sequentially
|
||||
/// so only one lives in `/tmp` at a time.
|
||||
fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, StockError> {
|
||||
// Size the genuine images from their on-NAND headers (uImage data size at
|
||||
// header offset 12; fdt totalsize at offset 4).
|
||||
let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64;
|
||||
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
|
||||
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
|
||||
// Sanity: headers must look like a uImage/fdt, sizes within slots.
|
||||
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
|
||||
// Genuine image sizes from their on-NAND headers (uImage data size at header
|
||||
// offset 12 plus the 64-byte header; fdt totalsize at offset 4), rounded up
|
||||
// to a whole NAND page so nanddump captures only complete pages.
|
||||
let (kdev, _) = locate(table, OFF_KERNEL, 64)?;
|
||||
let (ws, oob) = oob_geometry(sh, kdev)?;
|
||||
outcome(&format!("carve: geometry writesize={ws} oobsize={oob} (dev {kdev})"));
|
||||
let pr = |n: u64| round_up(n, ws);
|
||||
let kernel_data = pr(64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64);
|
||||
let dtb_data = pr(read_header_u32_be(sh, table, OFF_DTB, 4)? as u64);
|
||||
let rootfs_data = pr(64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64);
|
||||
if !(ws..=SLOT_KERNEL).contains(&kernel_data) || !(ws..=SLOT_ROOTFS).contains(&rootfs_data) {
|
||||
return Err(StockError::Method(format!(
|
||||
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
|
||||
"stock image sizes implausible (kernel {kernel_data}, rootfs {rootfs_data}); \
|
||||
refusing to back up"
|
||||
)));
|
||||
}
|
||||
let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block
|
||||
let d_dst = k_dst + round_up(kernel_len, ERASE);
|
||||
let r_dst = d_dst + round_up(dtb_len, ERASE);
|
||||
if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP {
|
||||
return Err(StockError::Method(
|
||||
"stock backup does not fit in the 32 MiB backup region".into(),
|
||||
));
|
||||
}
|
||||
copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?;
|
||||
copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?;
|
||||
copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?;
|
||||
let kernel = capture_entry(sh, table, OFF_KERNEL, kernel_data, k_dst, "stock-kernel")?;
|
||||
outcome(&format!(
|
||||
"carve: kernel data={} blob={} (OOB {})",
|
||||
kernel.data_len,
|
||||
kernel.blob_len,
|
||||
if kernel.blob_len > kernel.data_len {
|
||||
"captured"
|
||||
} else {
|
||||
"MISSING"
|
||||
}
|
||||
));
|
||||
let d_dst = k_dst + round_up(kernel.blob_len, ERASE);
|
||||
let dtb = capture_entry(sh, table, OFF_DTB, dtb_data, d_dst, "stock-dtb")?;
|
||||
outcome(&format!(
|
||||
"carve: dtb data={} blob={}",
|
||||
dtb.data_len, dtb.blob_len
|
||||
));
|
||||
let r_dst = d_dst + round_up(dtb.blob_len, ERASE);
|
||||
let rootfs = capture_entry(sh, table, OFF_ROOTFS, rootfs_data, r_dst, "stock-rootfs")?;
|
||||
outcome(&format!(
|
||||
"carve: rootfs data={} blob={}",
|
||||
rootfs.data_len, rootfs.blob_len
|
||||
));
|
||||
let manifest = BackupManifest {
|
||||
kernel_abs: k_dst,
|
||||
kernel_len,
|
||||
dtb_abs: d_dst,
|
||||
dtb_len,
|
||||
rootfs_abs: r_dst,
|
||||
rootfs_len,
|
||||
kernel,
|
||||
dtb,
|
||||
rootfs,
|
||||
};
|
||||
write_abs(
|
||||
sh,
|
||||
@@ -522,19 +799,24 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// Read and validate the on-board backup manifest, if present.
|
||||
fn read_backup_manifest(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
) -> Result<Option<BackupManifest>, StockError> {
|
||||
let (dev, rel) = match locate(table, BK_MANIFEST, 64) {
|
||||
/// Read the manifest block header bytes (enough for a v2 manifest: 8 magic +
|
||||
/// 9*8 fields = 80 B; 128 read for slack). `None` if the region is not mapped.
|
||||
fn read_manifest_bytes(sh: &mut dyn Shell, table: &[Mtd]) -> Result<Option<Vec<u8>>, StockError> {
|
||||
let (dev, rel) = match locate(table, BK_MANIFEST, 128) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Ok(None), // region not mapped -> treat as absent
|
||||
};
|
||||
let dev = dev.to_owned();
|
||||
// Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse.
|
||||
let bytes = read_small(sh, &dev, rel, 64)?;
|
||||
Ok(BackupManifest::decode(&bytes))
|
||||
// Pull the manifest off NAND via `od -v -x` (busybox-safe) and parse.
|
||||
Ok(Some(read_small(sh, &dev, rel, 128)?))
|
||||
}
|
||||
|
||||
/// Read and validate the on-board v2 backup manifest, if present and complete.
|
||||
fn read_backup_manifest(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
) -> Result<Option<BackupManifest>, StockError> {
|
||||
Ok(read_manifest_bytes(sh, table)?.and_then(|b| BackupManifest::decode(&b)))
|
||||
}
|
||||
|
||||
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
|
||||
@@ -619,77 +901,82 @@ pub fn install_from_stock(
|
||||
rootfs_cpio_gz: &[u8],
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError> {
|
||||
outcome(&format!(
|
||||
"install_from_stock: begin host={host} kernel={} dtb={} rootfs={} (zImage/fdt/cpio-gz)",
|
||||
kernel_zimage.len(),
|
||||
dtb.len(),
|
||||
rootfs_cpio_gz.len()
|
||||
));
|
||||
let mut sh = StockShell {
|
||||
host: host.to_owned(),
|
||||
password: password.map(str::to_owned),
|
||||
};
|
||||
let r = install_from_stock_inner(&mut sh, kernel_zimage, dtb, rootfs_cpio_gz);
|
||||
match &r {
|
||||
Ok(()) => outcome("install_from_stock: COMPLETE (boot slots written+verified, rebooting)"),
|
||||
Err(e) => outcome(&format!("install_from_stock: ERROR {e}")),
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn install_from_stock_inner(
|
||||
sh: &mut dyn Shell,
|
||||
kernel_zimage: &[u8],
|
||||
dtb: &[u8],
|
||||
rootfs_cpio_gz: &[u8],
|
||||
) -> Result<(), StockError> {
|
||||
if first_token(&sh.exec("id -u")?) != "0" {
|
||||
return Err(StockError::Auth(
|
||||
"did not obtain root on the stock board".into(),
|
||||
));
|
||||
}
|
||||
let table = read_mtd_table(&mut sh)?;
|
||||
// Carve the genuine-stock backup from the live stock NAND before any write.
|
||||
carve_backup(&mut sh, &table)?;
|
||||
outcome("root: ok");
|
||||
let table = read_mtd_table(sh)?;
|
||||
outcome(&format!("mtd-table: {} partitions", table.len()));
|
||||
// Carve the genuine-stock backup (with OOB) from the live stock NAND before
|
||||
// any write, so a safe return-to-stock is possible later.
|
||||
outcome("carve: begin (v2, OOB-preserving)");
|
||||
carve_backup(sh, &table)?;
|
||||
outcome("carve: ok (v2 stock backup written)");
|
||||
let img = BootImages {
|
||||
kernel_uimage: uimage::wrap(Kind::Kernel, kernel_zimage, 0, "alkane-kernel"),
|
||||
dtb: dtb.to_vec(),
|
||||
rootfs_uimage: uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, 0, "alkane-rootfs"),
|
||||
};
|
||||
write_boot_slots(&mut sh, &table, &img)?;
|
||||
reboot(&mut sh);
|
||||
outcome("boot-slots: writing rootfs, dtb, kernel");
|
||||
write_boot_slots(sh, &table, &img)?;
|
||||
outcome("boot-slots: written+verified");
|
||||
reboot(sh);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return an alkane board to genuine stock by writing the vendor images back to
|
||||
/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the
|
||||
/// vendor package); if `None`, the stock dtb saved in the on-board backup is
|
||||
/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is.
|
||||
/// Return an alkane board to genuine stock from a vendor firmware FILE.
|
||||
///
|
||||
/// This is refused on the Zynq-7010: a vendor file carries image data only, with
|
||||
/// no OOB, so writing it from alkane userspace recomputes the kernel's soft-BCH
|
||||
/// ECC, which the stock boot chain cannot read -> boot-loop brick recoverable
|
||||
/// only by the SD card. The safe network return-to-stock is
|
||||
/// [`restore_from_onboard`], which replays the genuine stock data+OOB captured
|
||||
/// in the on-board v2 backup. (Once the own stage-2 U-Boot lands, a soft-BCH
|
||||
/// reader makes vendor-file restore viable; until then it is blocked.)
|
||||
pub fn restore_to_stock(
|
||||
host: &str,
|
||||
kernel_uimage: &[u8],
|
||||
rootfs_uimage: &[u8],
|
||||
dtb: Option<&[u8]>,
|
||||
_kernel_uimage: &[u8],
|
||||
_rootfs_uimage: &[u8],
|
||||
_dtb: Option<&[u8]>,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError> {
|
||||
let mut sh = AlkaneShell::connect(host, password)?;
|
||||
if !shell_is_zynq(&mut sh) {
|
||||
return Err(StockError::NotApplicable);
|
||||
}
|
||||
let table = read_mtd_table(&mut sh)?;
|
||||
if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL {
|
||||
return Err(StockError::Method("vendor image over slot ceiling".into()));
|
||||
}
|
||||
// rootfs, dtb, kernel order (same safety ordering as install).
|
||||
write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?;
|
||||
match dtb {
|
||||
Some(d) => {
|
||||
if d.len() as u64 > SLOT_DTB {
|
||||
return Err(StockError::Method("dtb over slot ceiling".into()));
|
||||
}
|
||||
write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?;
|
||||
}
|
||||
None => {
|
||||
// No vendor dtb (an OTA package omits it): restore the genuine
|
||||
// per-board dtb from the on-board backup by copying within NAND.
|
||||
let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| {
|
||||
StockError::Method(
|
||||
"no stock dtb supplied and no on-board backup to take one from".into(),
|
||||
)
|
||||
})?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.dtb_abs,
|
||||
OFF_DTB,
|
||||
manifest.dtb_len,
|
||||
"dtb",
|
||||
)?;
|
||||
}
|
||||
}
|
||||
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
|
||||
reboot(&mut sh);
|
||||
Ok(())
|
||||
Err(StockError::Method(
|
||||
"Zynq-7010 vendor-file restore-to-stock is disabled: a vendor file has no OOB, so an \
|
||||
alkane-side write recomputes soft-BCH ECC that the stock U-Boot cannot read (boot-loop \
|
||||
brick; SD-card recovery only). Use restore-from-onboard, which replays the genuine stock \
|
||||
data+OOB from the on-board backup."
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether the board holds a complete, restorable on-board stock backup.
|
||||
@@ -710,33 +997,30 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
|
||||
return Err(StockError::NotApplicable);
|
||||
}
|
||||
let table = read_mtd_table(&mut sh)?;
|
||||
let manifest = read_backup_manifest(&mut sh, &table)?
|
||||
let raw = read_manifest_bytes(&mut sh, &table)?.ok_or_else(|| {
|
||||
StockError::Method("no on-board stock backup (backup region not mapped)".into())
|
||||
})?;
|
||||
if BackupManifest::is_v1(&raw) {
|
||||
return Err(StockError::Method(
|
||||
"on-board backup is the old data-only (v1) format with no stock OOB; it cannot be \
|
||||
restored safely (a plain write recomputes alkane soft-BCH ECC and bricks the stock \
|
||||
boot chain). Re-install from stock to capture a v2 backup, or use the SD recovery \
|
||||
card."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let manifest = BackupManifest::decode(&raw)
|
||||
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
|
||||
// Copy within NAND: backup region -> boot slots.
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.rootfs_abs,
|
||||
OFF_ROOTFS,
|
||||
manifest.rootfs_len,
|
||||
"rootfs",
|
||||
)?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.dtb_abs,
|
||||
OFF_DTB,
|
||||
manifest.dtb_len,
|
||||
"dtb",
|
||||
)?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.kernel_abs,
|
||||
OFF_KERNEL,
|
||||
manifest.kernel_len,
|
||||
"kernel",
|
||||
)?;
|
||||
// Prove the raw-OOB write path round-trips the stock OOB on this board
|
||||
// before touching a boot slot (abort, do not brick).
|
||||
scratch_selfcheck(&mut sh, &table, manifest.kernel.blob_abs)?;
|
||||
// rootfs, dtb, kernel order (an interrupted run never leaves a new rootfs
|
||||
// under an old kernel). Each write is read-back-verified WITH OOB; a
|
||||
// mismatch returns an error WITHOUT rebooting, leaving the running alkane in
|
||||
// place rather than booting a corrupt slot.
|
||||
restore_slot_raw_oob(&mut sh, &table, &manifest.rootfs, OFF_ROOTFS, "rootfs")?;
|
||||
restore_slot_raw_oob(&mut sh, &table, &manifest.dtb, OFF_DTB, "dtb")?;
|
||||
restore_slot_raw_oob(&mut sh, &table, &manifest.kernel, OFF_KERNEL, "kernel")?;
|
||||
reboot(&mut sh);
|
||||
Ok(())
|
||||
}
|
||||
@@ -762,22 +1046,38 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_roundtrips() {
|
||||
fn manifest_v2_roundtrips_and_rejects_v1() {
|
||||
let e = |a, b, c| BackupEntry {
|
||||
blob_abs: a,
|
||||
blob_len: b,
|
||||
data_len: c,
|
||||
};
|
||||
let m = BackupManifest {
|
||||
kernel_abs: 0x6020000,
|
||||
kernel_len: 4006832,
|
||||
dtb_abs: 0x6420000,
|
||||
dtb_len: 7650,
|
||||
rootfs_abs: 0x6440000,
|
||||
rootfs_len: 26620582,
|
||||
kernel: e(0x6020000, 4133808, 4063232),
|
||||
dtb: e(0x6440000, 8320, 8192),
|
||||
rootfs: e(0x6460000, 27336704, 26624000),
|
||||
};
|
||||
let enc = m.encode();
|
||||
let dec = BackupManifest::decode(&enc).unwrap();
|
||||
assert_eq!(dec.kernel_abs, m.kernel_abs);
|
||||
assert_eq!(dec.rootfs_len, m.rootfs_len);
|
||||
assert_eq!(&enc[..8], BK_MAGIC_V2);
|
||||
assert_eq!(enc.len(), 8 + 9 * 8);
|
||||
assert_eq!(BackupManifest::decode(&enc).unwrap(), m);
|
||||
// A v1 (data-only) header is detected and NOT decoded as a v2 manifest.
|
||||
let mut v1 = BK_MAGIC_V1.to_vec();
|
||||
v1.extend_from_slice(&[0u8; 72]);
|
||||
assert!(BackupManifest::is_v1(&v1));
|
||||
assert!(BackupManifest::decode(&v1).is_none());
|
||||
assert!(!BackupManifest::is_v1(&enc));
|
||||
assert!(BackupManifest::decode(b"nope").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_block_is_inside_the_backup_region_and_aligned() {
|
||||
assert!(BK_SCRATCH.is_multiple_of(ERASE));
|
||||
assert!(BK_SCRATCH >= OFF_STOCK_BACKUP + ERASE); // above manifest block
|
||||
assert_eq!(BK_SCRATCH, OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE);
|
||||
assert!(BK_SCRATCH + ERASE <= OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locate_maps_absolute_to_partition() {
|
||||
let table = vec![
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Headless bench automation (`ALKANE_BENCH_SEQUENCE`): drive the GUI's real
|
||||
//! install/restore operation layer (`stock_ops`) through the A113D network-only
|
||||
//! install <-> flag-restore cycle, with no window. This exercises the GUI
|
||||
//! operator flow end-to-end against real hardware, for bench proofs, without the
|
||||
//! wx event loop (the worker functions stream progress over a channel, exactly
|
||||
//! as the UI drains them).
|
||||
//!
|
||||
//! Spec: `ALKANE_BENCH_SEQUENCE="<host> <local.afw> [iterations]"`.
|
||||
//! The alkane root credential is read from the saved SSH credentials file.
|
||||
//!
|
||||
//! On the A113D, "restore to stock" is the one-byte flag flip (the install
|
||||
//! overwrites no stock partition), so the cycle is: install (stock -> alkane) ->
|
||||
//! verify alkane -> restore (flag flip -> stock) -> verify stock.
|
||||
|
||||
use std::io::Read;
|
||||
use std::net::TcpStream;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::credentials;
|
||||
use crate::stock_ops::{self, AfwSource, StockHandle, StockMsg};
|
||||
|
||||
/// Drain a `StockHandle` to completion, printing progress; returns true iff
|
||||
/// every board reported ok and at least one `Result` arrived.
|
||||
fn drive(label: &str, handle: StockHandle) -> bool {
|
||||
let mut ok = true;
|
||||
let mut saw = false;
|
||||
loop {
|
||||
match handle.rx.recv() {
|
||||
Ok(StockMsg::Started) => println!(" [{label}] started"),
|
||||
Ok(StockMsg::Progress(s)) => println!(" [{label}] {s}"),
|
||||
Ok(StockMsg::Result { ip, ok: r, detail }) => {
|
||||
saw = true;
|
||||
ok = ok && r;
|
||||
println!(
|
||||
" [{label}] {ip}: {} - {detail}",
|
||||
if r { "OK" } else { "FAIL" }
|
||||
);
|
||||
}
|
||||
Ok(StockMsg::Done) => break,
|
||||
Err(_) => {
|
||||
println!(" [{label}] channel closed early");
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ok && saw
|
||||
}
|
||||
|
||||
/// Read the SSH identification banner (no auth), e.g. `SSH-2.0-dropbear_2026.93`.
|
||||
fn ssh_banner(host: &str) -> Option<String> {
|
||||
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
|
||||
let mut buf = [0u8; 256];
|
||||
let n = stream.read(&mut buf).ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
String::from_utf8_lossy(&buf[..n])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// HTTP server header probe (stock serves lighttpd / an antMiner realm).
|
||||
fn http_is_stock(host: &str) -> Option<bool> {
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"-m",
|
||||
"6",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-D",
|
||||
"-",
|
||||
&format!("http://{host}/"),
|
||||
])
|
||||
.output()
|
||||
.ok()?;
|
||||
let h = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||||
if h.is_empty() {
|
||||
None
|
||||
} else if h.contains("lighttpd") || h.contains("antminer configuration") {
|
||||
Some(true)
|
||||
} else {
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify the board: `Some(true)` = looks like genuine stock, `Some(false)` =
|
||||
/// looks like alkane, `None` = no decisive answer (e.g. mid-reboot).
|
||||
///
|
||||
/// Primary signal is the SSH banner: stock A113D is `dropbear_2018.76`; alkane
|
||||
/// ships a much newer dropbear. HTTP (lighttpd) is a stock fallback.
|
||||
fn classify(host: &str) -> (String, Option<bool>) {
|
||||
let banner = ssh_banner(host);
|
||||
if let Some(b) = &banner {
|
||||
let lb = b.to_lowercase();
|
||||
if lb.contains("dropbear_2018") || lb.contains("dropbear_2019") {
|
||||
return (format!("ssh \"{b}\" -> stock"), Some(true));
|
||||
}
|
||||
if lb.contains("dropbear") || lb.contains("openssh") {
|
||||
return (format!("ssh \"{b}\" -> alkane"), Some(false));
|
||||
}
|
||||
}
|
||||
match http_is_stock(host) {
|
||||
Some(true) => ("http lighttpd/antMiner -> stock".to_string(), Some(true)),
|
||||
Some(false) => ("http non-stock -> alkane".to_string(), Some(false)),
|
||||
None => (
|
||||
banner
|
||||
.map(|b| format!("ssh \"{b}\" (unclassified), no http"))
|
||||
.unwrap_or_else(|| "no ssh, no http (mid-reboot?)".to_string()),
|
||||
None,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The MAC (lladdr) the kernel has cached for `host` (pings first to populate).
|
||||
fn mac_of(host: &str) -> Option<String> {
|
||||
let _ = Command::new("ping")
|
||||
.args(["-c", "1", "-W", "1", host])
|
||||
.output();
|
||||
let out = Command::new("ip")
|
||||
.args(["neigh", "show", host])
|
||||
.output()
|
||||
.ok()?;
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let mut it = s.split_whitespace();
|
||||
while let Some(t) = it.next() {
|
||||
if t == "lladdr" {
|
||||
return it.next().map(|m| m.to_lowercase());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Populate the neighbour table by parallel-pinging the /24 of `sample` (a bench
|
||||
/// board can take a different DHCP lease across a reboot, so we must re-find it).
|
||||
fn sweep_subnet(sample: &str) {
|
||||
let base = match sample.rsplit_once('.') {
|
||||
Some((net, _)) => net.to_string(),
|
||||
None => return,
|
||||
};
|
||||
let mut kids = Vec::new();
|
||||
for h in 2..=254 {
|
||||
if let Ok(c) = Command::new("ping")
|
||||
.args(["-c", "1", "-W", "1", &format!("{base}.{h}")])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
kids.push(c);
|
||||
}
|
||||
}
|
||||
for mut c in kids {
|
||||
let _ = c.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Current IPv4 for `mac` from the neighbour table, if present.
|
||||
fn ip_for_mac(mac: &str) -> Option<String> {
|
||||
let out = Command::new("ip").args(["neigh"]).output().ok()?;
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let mac = mac.to_lowercase();
|
||||
for line in s.lines() {
|
||||
if line.to_lowercase().contains(&mac) {
|
||||
if let Some(ip) = line.split_whitespace().next() {
|
||||
if ip.contains('.') {
|
||||
return Some(ip.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Poll until the board (located by MAC, so a changed DHCP lease is followed)
|
||||
/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's
|
||||
/// current IP, a description, and whether the target state was reached.
|
||||
fn wait_for(
|
||||
mac: Option<&str>,
|
||||
fallback: &str,
|
||||
want_stock: bool,
|
||||
timeout: Duration,
|
||||
) -> (String, String, bool) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut ip = fallback.to_string();
|
||||
let mut swept = Instant::now() - Duration::from_secs(60);
|
||||
loop {
|
||||
// Re-locate by MAC; sweep the subnet at most every ~25s to catch a new lease.
|
||||
if let Some(m) = mac {
|
||||
if ip_for_mac(m).is_none() && swept.elapsed() >= Duration::from_secs(25) {
|
||||
sweep_subnet(fallback);
|
||||
swept = Instant::now();
|
||||
}
|
||||
if let Some(found) = ip_for_mac(m) {
|
||||
ip = found;
|
||||
}
|
||||
}
|
||||
let (desc, is_stock) = classify(&ip);
|
||||
let line = format!("[{ip}] {desc}");
|
||||
if is_stock == Some(want_stock) {
|
||||
return (ip, line, true);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return (ip, line, false);
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(spec: &str) -> i32 {
|
||||
let mut it = spec.split_whitespace();
|
||||
let host = match it.next() {
|
||||
Some(h) => h.to_string(),
|
||||
None => {
|
||||
eprintln!("ALKANE_BENCH_SEQUENCE=\"<host> <local.afw> [iterations]\"");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let afw = match it.next() {
|
||||
Some(a) => PathBuf::from(a),
|
||||
None => {
|
||||
eprintln!("missing local .afw path");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let iterations: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||
let board = "a113d".to_string();
|
||||
// Install reaches STOCK via the compiled-in from-stock method; pass the saved
|
||||
// board SSH credential through to it.
|
||||
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
|
||||
// The flag-restore reaches the running ALKANE board over SSH as `root` - a
|
||||
// DIFFERENT credential from the stock login. Alkane bench images bake
|
||||
// root/alkane; allow an override via ALKANE_ROOT_PASSWORD.
|
||||
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
|
||||
.ok()
|
||||
.or_else(|| Some("alkane".to_string()));
|
||||
|
||||
println!("== A113D headless GUI bench sequence (network-only install <-> flag-restore) ==");
|
||||
println!(
|
||||
"host={host} afw={} board={board} iterations={iterations} stock_cred={} alkane_cred={}",
|
||||
afw.display(),
|
||||
if stock_password.is_some() { "loaded" } else { "none" },
|
||||
if alkane_password.is_some() { "set" } else { "none" }
|
||||
);
|
||||
if !afw.exists() {
|
||||
eprintln!("afw not found: {}", afw.display());
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Resolve the board's MAC now (on stock) so we can re-find it after each
|
||||
// reboot even if its DHCP lease changes under alkane.
|
||||
let mac = mac_of(&host);
|
||||
println!(
|
||||
"board MAC: {}",
|
||||
mac.as_deref()
|
||||
.unwrap_or("unknown (will use the fixed host)")
|
||||
);
|
||||
|
||||
let boot_timeout = Duration::from_secs(300);
|
||||
let mut all_ok = true;
|
||||
|
||||
for i in 1..=iterations {
|
||||
println!("\n-- iteration {i}/{iterations} --");
|
||||
|
||||
// 1. install (stock -> alkane) through the GUI operation layer
|
||||
println!("[1/4] install: stock -> alkane");
|
||||
let h = stock_ops::start_install(
|
||||
vec![host.clone()],
|
||||
board.clone(),
|
||||
AfwSource::Local(afw.clone()),
|
||||
true, // allow unsigned (bench image)
|
||||
stock_password.clone(),
|
||||
false, // not an in-place update
|
||||
);
|
||||
if !drive("install", h) {
|
||||
all_ok = false;
|
||||
println!("[1/4] install FAILED; aborting");
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. verify alkane is live (board reboots into alkane)
|
||||
println!(
|
||||
"[2/4] verify alkane (awaiting reboot, up to {}s)...",
|
||||
boot_timeout.as_secs()
|
||||
);
|
||||
let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
|
||||
println!(
|
||||
" {desc} => {}",
|
||||
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
|
||||
);
|
||||
all_ok = all_ok && ok;
|
||||
|
||||
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
|
||||
println!("[3/4] restore: alkane -> stock (flag flip) at {alkane_ip}");
|
||||
let h = stock_ops::start_restore_flag(vec![alkane_ip.clone()], alkane_password.clone());
|
||||
if !drive("restore", h) {
|
||||
all_ok = false;
|
||||
println!("[3/4] restore FAILED");
|
||||
}
|
||||
|
||||
// 4. verify stock is back
|
||||
println!(
|
||||
"[4/4] verify stock (awaiting reboot, up to {}s)...",
|
||||
boot_timeout.as_secs()
|
||||
);
|
||||
let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
|
||||
println!(
|
||||
" {desc} => {}",
|
||||
if ok { "STOCK" } else { "NOT STOCK (fail)" }
|
||||
);
|
||||
all_ok = all_ok && ok;
|
||||
}
|
||||
|
||||
println!(
|
||||
"\n== BENCH RESULT: {} ==",
|
||||
if all_ok { "PASS" } else { "FAIL" }
|
||||
);
|
||||
if all_ok {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
mod access_probe;
|
||||
mod alkane_detect;
|
||||
mod askpass;
|
||||
mod bench_sequence;
|
||||
mod bug_report;
|
||||
mod credentials;
|
||||
mod export;
|
||||
@@ -41,6 +42,13 @@ fn main() {
|
||||
std::process::exit(run_selftest());
|
||||
}
|
||||
|
||||
// Headless bench automation: drive the real install/restore operation layer
|
||||
// (stock_ops) through the A113D network-only install <-> flag-restore cycle
|
||||
// against real hardware, with no window. See bench_sequence.rs.
|
||||
if let Some(spec) = std::env::var_os("ALKANE_BENCH_SEQUENCE") {
|
||||
std::process::exit(bench_sequence::run(&spec.to_string_lossy()));
|
||||
}
|
||||
|
||||
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
|
||||
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
|
||||
// :4028 token check and the Antminer digest check can be verified directly.
|
||||
@@ -123,9 +131,14 @@ fn run_selftest() -> i32 {
|
||||
|
||||
/// True when the process runs one of the headless check modes instead of the GUI.
|
||||
fn headless_mode() -> bool {
|
||||
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
|
||||
.iter()
|
||||
.any(|v| std::env::var_os(v).is_some())
|
||||
[
|
||||
"ALKANE_SELFTEST",
|
||||
"ALKANE_ACCESS_PROBE",
|
||||
"ALKANE_LOG_SCAN",
|
||||
"ALKANE_BENCH_SEQUENCE",
|
||||
]
|
||||
.iter()
|
||||
.any(|v| std::env::var_os(v).is_some())
|
||||
}
|
||||
|
||||
/// A Windows GUI-subsystem process has no console, so output from the headless
|
||||
|
||||
@@ -24,8 +24,13 @@ use crate::scan::fake_scan_enabled;
|
||||
|
||||
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
|
||||
/// `SUPPORTED`). Only these are offered as install targets.
|
||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] =
|
||||
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
|
||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
|
||||
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
|
||||
(
|
||||
"a113d",
|
||||
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
|
||||
),
|
||||
];
|
||||
|
||||
/// The default install board when the user has not chosen another.
|
||||
pub const DEFAULT_BOARD: &str = "zynq-7010";
|
||||
@@ -408,3 +413,65 @@ pub fn start_restore_onboard(ips: Vec<String>, password: Option<String>) -> Stoc
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
|
||||
/// Restore the given alkane A113D boards to genuine Bitmain stock, over the
|
||||
/// network, by clearing the one-byte boot flag in-band from the running alkane
|
||||
/// OS. The A113D install overwrites no stock partition, so this flag flip is the
|
||||
/// complete restore: clear `ALAN`, reboot, and stock boots via `storeboot` from
|
||||
/// the untouched `boot` MTD. No vendor firmware file or on-board backup needed.
|
||||
/// `password`, if set, is the board's alkane root credential.
|
||||
pub fn start_restore_flag(ips: Vec<String>, password: Option<String>) -> StockHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
|
||||
if fake_scan_enabled() {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip,
|
||||
ok: true,
|
||||
detail: "restored to stock (flag flip, demo)".into(),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return StockHandle { rx, cancel };
|
||||
}
|
||||
|
||||
let tc = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("restore-flag".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
if tc.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let _ = tx.send(StockMsg::Progress(format!(
|
||||
"restoring {ip} to stock (clearing the alkane boot flag)..."
|
||||
)));
|
||||
let (ok, detail) = match stock::restore_aml_flag(&ip, password.as_deref()) {
|
||||
Ok(()) => (
|
||||
true,
|
||||
"restored to stock (flag cleared, rebooting; verify over the network)"
|
||||
.to_string(),
|
||||
),
|
||||
Err(e) => (false, format!("restore failed: {e}")),
|
||||
};
|
||||
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
});
|
||||
|
||||
if spawned.is_err() {
|
||||
let _ = err_tx.send(StockMsg::Result {
|
||||
ip: String::new(),
|
||||
ok: false,
|
||||
detail: "could not start the restore worker thread".into(),
|
||||
});
|
||||
let _ = err_tx.send(StockMsg::Done);
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user