Compare commits

..
Author SHA1 Message Date
noahandClaude Opus 4.8 d574118314 fix(gui): offer alkane install for the stock A113D (AML C76) board
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 30m58s
verify / verify-windows (pull_request) Successful in 19m55s
The right-click "Install alkane OS..." item never appeared for a stock
Amlogic A113D (Antminer BHB42XXX). board_family(), which gates the menu
via install_supported(), recognized only the Xilinx/Zynq S17 control
board, so it returned None for the A113D and the menu offered nothing.

Two things combined to hide it, both visible in a live scan of the bench
board at 10.255.1.18:

    brand=Unknown  model="Unknown: ANTMINER BHB42XXX"  board=AML (C76)

asic-rs has no make for the BHB42XXX, so the brand is "Unknown" and
board_family() bailed at the `!brand.contains("antminer")` guard before
any board-code check; and there was no AML -> a113d mapping anyway. Yet
SUPPORTED_BOARDS, the from-stock install engine (stock::install_from_stock
dispatches a113d -> aml_ubi) and the CLI's SUPPORTED list all already
support a113d -- only this detection gate was stale.

Map the "AML (C76)" control board (the a113d identity; board_labels
already maps a113d -> ("AML","C76")) directly to "a113d", ahead of the
brand guard, since this board legitimately reports no brand. The "AML"
code is only ever derived for an Amlogic Antminer control board, so it is
specific on its own. CBE (140mm S19k/S21-class) is deliberately not
mapped.

Verified against the bench A113D: live scan now reports install=true, and
a headless stock->alkane->stock cycle through the GUI operation layer
(ALKANE_BENCH_SEQUENCE) on the released v0.1.0-a113d-bench1 image passes
(install -> dropbear_2026.93 -> flag-restore -> dropbear_2018.76).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-17 09:33:52 -06:00
2 changed files with 203 additions and 468 deletions
+163 -463
View File
@@ -60,47 +60,12 @@ 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
/// 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
const BK_MAGIC: &[u8; 8] = b"ALKSTKB1";
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
// ---------------------------------------------------------------------------
@@ -387,221 +352,32 @@ fn write_abs(
Ok(())
}
/// 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(
/// 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(
sh: &mut dyn Shell,
table: &[Mtd],
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,
src: u64,
dst: u64,
len: u64,
label: &str,
) -> Result<(), StockError> {
if !abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{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, srel) = locate(table, src, len)?;
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, drel) = locate(table, dst, 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 {
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") {
return Err(StockError::Method(format!(
"{label}: restored slot read-back md5 {got} != backup {want} (data+OOB mismatch); \
NOT rebooting"
"{label}: backup copy failed: {out}"
)));
}
Ok(())
@@ -654,37 +430,34 @@ fn first_token(s: &str) -> String {
// On-board stock backup manifest
// ---------------------------------------------------------------------------
/// 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)]
#[derive(Clone, Debug)]
struct BackupManifest {
kernel: BackupEntry,
dtb: BackupEntry,
rootfs: BackupEntry,
kernel_abs: u64,
kernel_len: u64,
dtb_abs: u64,
dtb_len: u64,
rootfs_abs: u64,
rootfs_len: u64,
}
impl BackupManifest {
fn encode(&self) -> Vec<u8> {
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());
}
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());
}
v
}
fn decode(b: &[u8]) -> Option<Self> {
if b.len() < 8 + 9 * 8 || &b[..8] != BK_MAGIC_V2 {
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
return None;
}
let g = |i: usize| {
@@ -692,102 +465,52 @@ 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: e(0),
dtb: e(3),
rootfs: e(6),
kernel_abs: g(0),
kernel_len: g(1),
dtb_abs: g(2),
dtb_len: g(3),
rootfs_abs: g(4),
rootfs_len: g(5),
})
}
/// 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 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.
/// 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.
fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, StockError> {
// 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) {
// 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) {
return Err(StockError::Method(format!(
"stock image sizes implausible (kernel {kernel_data}, rootfs {rootfs_data}); \
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
refusing to back up"
)));
}
let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block
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 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 manifest = BackupManifest {
kernel,
dtb,
rootfs,
kernel_abs: k_dst,
kernel_len,
dtb_abs: d_dst,
dtb_len,
rootfs_abs: r_dst,
rootfs_len,
};
write_abs(
sh,
@@ -799,24 +522,19 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
Ok(manifest)
}
/// 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 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.
/// Read and validate the on-board backup manifest, if present.
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)))
let (dev, rel) = match locate(table, BK_MANIFEST, 64) {
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))
}
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
@@ -901,82 +619,77 @@ 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(),
));
}
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 table = read_mtd_table(&mut sh)?;
// Carve the genuine-stock backup from the live stock NAND before any write.
carve_backup(&mut sh, &table)?;
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"),
};
outcome("boot-slots: writing rootfs, dtb, kernel");
write_boot_slots(sh, &table, &img)?;
outcome("boot-slots: written+verified");
reboot(sh);
write_boot_slots(&mut sh, &table, &img)?;
reboot(&mut sh);
Ok(())
}
/// 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.)
/// 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.
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);
}
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(),
))
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(())
}
/// Whether the board holds a complete, restorable on-board stock backup.
@@ -997,30 +710,33 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
return Err(StockError::NotApplicable);
}
let table = read_mtd_table(&mut sh)?;
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)
let manifest = read_backup_manifest(&mut sh, &table)?
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
// 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")?;
// 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",
)?;
reboot(&mut sh);
Ok(())
}
@@ -1046,38 +762,22 @@ mod tests {
}
#[test]
fn manifest_v2_roundtrips_and_rejects_v1() {
let e = |a, b, c| BackupEntry {
blob_abs: a,
blob_len: b,
data_len: c,
};
fn manifest_roundtrips() {
let m = BackupManifest {
kernel: e(0x6020000, 4133808, 4063232),
dtb: e(0x6440000, 8320, 8192),
rootfs: e(0x6460000, 27336704, 26624000),
kernel_abs: 0x6020000,
kernel_len: 4006832,
dtb_abs: 0x6420000,
dtb_len: 7650,
rootfs_abs: 0x6440000,
rootfs_len: 26620582,
};
let enc = m.encode();
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));
let dec = BackupManifest::decode(&enc).unwrap();
assert_eq!(dec.kernel_abs, m.kernel_abs);
assert_eq!(dec.rootfs_len, m.rootfs_len);
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![
+40 -5
View File
@@ -143,12 +143,23 @@ pub fn is_alkane(row: &MinerRow) -> bool {
}
/// The alkane-os board family the row's control board is, when it can be told:
/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17
/// era, "XIL (C49)") control board.
/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era,
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
/// board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
// A stock A113D (Amlogic AXG) control board -- the "a113d" install target
// (board_labels maps a113d -> "AML (C76)"). Decided on the control-board
// code, not the brand: asic-rs has no make for the Antminer BHB42XXX and
// reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so
// the generic brand guard below would otherwise reject it. The "AML" code is
// only ever derived for an Amlogic Antminer control board, so this is
// specific on its own.
if row.cpu == "AML" && row.board_code == "C76" {
return Some("a113d".to_string());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
@@ -243,7 +254,10 @@ mod tests {
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
assert!(!install_supported(&stock("AML", "C76")));
// The Amlogic A113D control board is the "a113d" install target.
assert!(install_supported(&stock("AML", "C76")));
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
@@ -274,7 +288,9 @@ mod tests {
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model.
// A reported control board overrides the model: an "S17" model on an
// Amlogic A113D control board resolves to a113d (the control board),
// not zynq (the model).
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
@@ -282,7 +298,26 @@ mod tests {
board_code: "C76".into(),
..Default::default()
};
assert!(!install_supported(&s17_on_aml));
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
}
#[test]
fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() {
// Exactly as the live scan reports the bench A113D at 10.255.1.18:
// asic-rs cannot pin a make, so brand is "Unknown" and the model is
// "Unknown: ANTMINER BHB42XXX", but the control board classifies as
// "AML (C76)". Install must still be offered.
let bhb = MinerRow {
brand: "Unknown".into(),
model: "Unknown: ANTMINER BHB42XXX".into(),
firmware: "Stock".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert_eq!(board_family(&bhb).as_deref(), Some("a113d"));
assert!(install_supported(&bhb));
assert!(!is_alkane(&bhb));
}
/// Live check against a real board: