Compare commits

..
Author SHA1 Message Date
noahandClaude Opus 4.8 795f80a44c fix(gui): bench driver uses the alkane root credential for the restore leg
source / check (pull_request) Skipped
verify / verify (pull_request) Skipped
The flag-restore reaches the running alkane board over SSH as root, which is a
different credential from the stock login used for install. Alkane bench images
bake root/alkane; pass that (overridable via ALKANE_ROOT_PASSWORD) to the
restore, and keep the saved board SSH credential for the install. The previous
single-credential handoff sent the stock login to the alkane root restore and
hit "Permission denied".

Hardware note (2026-11-16): the PHY-fixed afw installs and comes up REACHABLE on
alkane (both the image PHY fix and the driver's MAC rediscovery proven); the
in-band flag-restore still needs the alkane DTB to expose the `misc` MTD (it
currently exposes only nvdata), tracked separately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 13:22:48 -06:00
noahandClaude Opus 4.8 79f9efc3e3 fix(gui): headless bench driver re-finds the board by MAC across reboots
The A113D can take a different DHCP lease (or lose its v4 lease) across the
install/restore reboots, so assuming the board keeps its initial IP broke the
verify/restore steps. Resolve the board's MAC up front (on stock) and, after
each reboot, re-locate it in the neighbour table (sweeping the /24 when it is
not cached) so verify and the flag-restore target the board's CURRENT address.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 12:22:40 -06:00
noahandClaude Opus 4.8 bdd94dad8a feat(gui): A113D install support + flag-restore + headless bench driver
- stock_ops: add "a113d" to SUPPORTED_BOARDS so the GUI offers A113D install
  (it was zynq-7010 only); add start_restore_flag() - the A113D restore is the
  in-band ALAN flag flip (install overwrites no stock partition), which the GUI
  lacked a clean path for (start_restore needs a firmware file, which the A113D
  ignores).
- bench_sequence (new) + main.rs ALKANE_BENCH_SEQUENCE: a headless driver that
  drives the real GUI operation layer (start_install(AfwSource::Local) -> verify
  -> start_restore_flag) through the A113D network-only install<->restore cycle,
  no wx window. Classifies stock vs alkane by SSH dropbear version / HTTP.

Hardware status (bench A113D, 2026-11-16): the install leg is PROVEN on real
hardware via the GUI operation layer. The verify/restore legs are NOT yet
validated end-to-end because the 0.1.0 a113d alkane image does not fully boot on
the bench board (kernel+eth up, no DHCP/SSH) - an alkane-os image bringup issue,
tracked separately. Known limitation: the driver assumes the board keeps its IP
across reboots; it should re-discover the board (A113D can change/lose its lease
under alkane). Not released pending a working image + the discovery fix.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-16 12:03:07 -06:00
12 changed files with 212 additions and 710 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
publish:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -7,7 +7,7 @@ on:
jobs:
publish:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
permissions:
+1 -1
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
check:
runs-on: alkane-ci
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
+6 -71
View File
@@ -11,7 +11,7 @@ concurrency:
jobs:
verify:
runs-on: alkane-ci
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
outputs:
@@ -195,73 +195,8 @@ jobs:
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of the same change (main's release gate, run on the PR):
# clippy for the Windows target, the release .exe, every unit test under
# Wine, and the headless UI self-test under Wine. Only for changes that can
# affect the binary (the "full" surface).
verify-windows:
needs: verify
if: needs.verify.outputs.surface == 'full'
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Windows toolchain
run: bash ci/windows-ci.sh toolchain
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxMSW cache key
id: wx-key
run: bash ci/wx-cache-key.sh windows
- name: Check prebuilt wxMSW
id: wx-image
run: bash ci/check-wx-image-prefix.sh windows
- name: Cache vendored wxMSW build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Build wxMSW (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh windows
- name: Save vendored wxMSW build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-mingw
key: ${{ steps.wx-key.outputs.key }}
- name: Clippy (Windows target, warnings are errors)
run: bash ci/windows-ci.sh clippy
- name: Build (Windows)
run: bash ci/windows-ci.sh build
- name: Unit tests (Windows build, under Wine)
run: bash ci/windows-ci.sh test
- name: Headless UI self-test (Windows build, under Wine)
run: bash ci/windows-ci.sh selftest
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
# The Windows build of each change is validated on the main release run
# (build-test-release / windows-native), not on the PR gate: it is a full
# mingw + Wine cross-build that roughly doubled PR wall-clock. PRs verify Linux
# (clippy, build, tests, self-test) fast; Windows is still built and shipped at
# release, so a Windows-only break surfaces on the merge to main.
+18 -58
View File
@@ -22,8 +22,8 @@ use alkane_flash::preflight::{preflight, PreflightOptions};
use alkane_flash::stock;
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
use alkane_flash::stock_firmware;
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use alkane_flash::zynq_nand;
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
@@ -1042,10 +1042,7 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
/// of these; `compat` lists them so an operator knows what is supported.
const SUPPORTED: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
),
("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"),
];
fn is_supported(board: &str) -> bool {
@@ -1131,9 +1128,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
None => {
if opts.flag("dry-run") {
println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag");
println!(
"(no stock firmware needed; the untouched stock boot partition is booted)."
);
println!("(no stock firmware needed; the untouched stock boot partition is booted).");
println!("Re-run with --confirm FLASH.");
return Ok(());
}
@@ -1143,9 +1138,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
println!("restoring {host} to genuine stock (A113D flag flip, network-only)...");
match stock::restore_aml_flag(&host, password.as_deref()) {
Ok(()) => {
println!(
"restore reported success (boot flag cleared; stock boots via storeboot)."
);
println!("restore reported success (boot flag cleared; stock boots via storeboot).");
println!("verify independently: the board should present genuine stock");
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
return Ok(());
@@ -1193,7 +1186,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, ssh_values(), &[])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let cmd = opts.positionals.join(" ");
let cmd = opts
.positionals
.join(" ");
if cmd.trim().is_empty() {
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
}
@@ -1208,11 +1203,7 @@ fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// backup, write the boot slots and reboot. Drives the DSH root-on-stock
/// primitive; board must be on stock (credential root/root).
fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["confirm"]].concat(),
&["allow-unsigned"],
)?;
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["allow-unsigned"])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let afw_path = opts
.positionals
@@ -1220,33 +1211,18 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.ok_or("usage: alkane-cli afw nand-install <afw> --host <ip> --confirm FLASH")?;
let verified = load_afw(afw_path, &opts)?;
if !zynq::owns_board(&verified.manifest.board) {
return Err(format!(
"nand-install is zynq-7010 only, not {}",
verified.manifest.board
)
.into());
return Err(format!("nand-install is zynq-7010 only, not {}", verified.manifest.board).into());
}
if opts.value("confirm") != Some("FLASH") {
return Err("refusing to install without --confirm FLASH".into());
}
let kernel = verified
.image("kernel")
.ok_or("afw missing kernel image")?
.1;
let kernel = verified.image("kernel").ok_or("afw missing kernel image")?.1;
let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1;
let rootfs = verified
.image("rootfs")
.ok_or("afw missing rootfs image")?
.1;
let rootfs = verified.image("rootfs").ok_or("afw missing rootfs image")?.1;
let password = read_board_password(&opts)?;
println!(
"installing {} onto stock board {host} (readable NAND path)...",
verified.manifest.board
);
println!("installing {} onto stock board {host} (readable NAND path)...", verified.manifest.board);
zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?;
println!(
"install reported success (on-board stock backup carved; boot slots written; rebooting)."
);
println!("install reported success (on-board stock backup carved; boot slots written; rebooting).");
print!("{}", zynq_verify_hint(&host));
Ok(())
}
@@ -1255,15 +1231,9 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
/// back to the boot slots over SSH (board on alkane). Needs the alkane image
/// that exposes the boot partitions.
fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["confirm", "stock-firmware"]].concat(),
&["dry-run"],
)?;
let opts = parse_args(args, &[ssh_values(), &["confirm", "stock-firmware"]].concat(), &["dry-run"])?;
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let firmware = opts
.value("stock-firmware")
.ok_or("--stock-firmware <file> is required")?;
let firmware = opts.value("stock-firmware").ok_or("--stock-firmware <file> is required")?;
let fw = stock_firmware::parse(Path::new(firmware))?;
println!("stock firmware: {}", fw.summary());
if opts.value("confirm") != Some("FLASH") {
@@ -1271,16 +1241,8 @@ fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Err
}
let password = read_board_password(&opts)?;
println!("restoring {host} to genuine stock (readable NAND path)...");
zynq_nand::restore_to_stock(
&host,
&fw.kernel,
&fw.rootfs,
fw.dtb.as_deref(),
password.as_deref(),
)?;
println!(
"restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."
);
zynq_nand::restore_to_stock(&host, &fw.kernel, &fw.rootfs, fw.dtb.as_deref(), password.as_deref())?;
println!("restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved).");
Ok(())
}
@@ -1382,9 +1344,7 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>
password.as_deref(),
std::time::Duration::from_secs(300),
)?;
println!(
"restore-from-onboard reported success. Verify independently the board answers as stock."
);
println!("restore-from-onboard reported success. Verify independently the board answers as stock.");
Ok(())
}
+8 -12
View File
@@ -53,7 +53,8 @@ const FLAG_MAGIC: [u8; 4] = *b"ALAN";
const KRNADDR: &str = "0x1200000";
const FDTADDR: &str = "0x8000000";
const RDADDR: &str = "0x8100000";
const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
const ALK_BOOTARGS: &str =
"console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
const ALKANE_DIR: &str = "alkane";
@@ -109,8 +110,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -219,7 +220,7 @@ fn b64_decode(s: &str) -> Option<Vec<u8>> {
fn b64_encode(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
@@ -606,10 +607,7 @@ mod tests {
#[test]
fn env_roundtrips_with_crc() {
let vars = vec![
(
"bootcmd".to_owned(),
"run checkalk; run storeboot".to_owned(),
),
("bootcmd".to_owned(), "run checkalk; run storeboot".to_owned()),
("bootdelay".to_owned(), "1".to_owned()),
("checkalk".to_owned(), checkalk_value()),
];
@@ -618,10 +616,8 @@ mod tests {
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
assert_eq!(crc32(&blob[4..]), stored);
let parsed = parse_env(&blob);
assert_eq!(
parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot"
);
assert_eq!(parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
"run checkalk; run storeboot");
assert!(parsed.iter().any(|(k, _)| k == "checkalk"));
}
+1 -2
View File
@@ -30,8 +30,7 @@ pub mod zynq_nand;
clippy::too_many_arguments,
clippy::manual_repeat_n,
clippy::manual_is_multiple_of,
clippy::unnecessary_map_or,
clippy::question_mark
clippy::unnecessary_map_or
)]
mod stock_method;
pub mod transport;
+160 -500
View File
@@ -34,6 +34,7 @@ use crate::md5::md5_hex;
use crate::stock::StockError;
use crate::transport::{Remote, SshOptions, SshTransport};
use crate::uimage::{self, Kind};
use std::io::Write as _;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
@@ -60,47 +61,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
// ---------------------------------------------------------------------------
@@ -165,7 +131,6 @@ impl Drop for TempFile {
#[cfg(unix)]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new()
.create(true)
@@ -177,11 +142,6 @@ fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
f.flush()
}
#[cfg(not(unix))]
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
std::fs::write(path, contents)
}
impl AlkaneShell {
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
@@ -197,8 +157,8 @@ impl AlkaneShell {
root_method: crate::transport::RootMethod::Auto,
update_daemon_port: None,
};
let transport =
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
let transport = SshTransport::connect(options, true)
.map_err(|e| StockError::Network(e.to_string()))?;
Ok(AlkaneShell {
transport,
_secret: secret,
@@ -265,7 +225,11 @@ fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
.and_then(|h| u64::from_str_radix(h, 16).ok())
.ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?;
let _erase = it.next();
let name = line.split('"').nth(1).unwrap_or("").to_owned();
let name = line
.split('"')
.nth(1)
.unwrap_or("")
.to_owned();
let base = match sysfs_offset(sh, dev) {
Some(off) => off,
None => cursor,
@@ -293,7 +257,11 @@ fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
/// Find the partition that contains `abs` and holding at least `len` bytes from
/// there; return (device, relative offset).
fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> {
fn locate<'a>(
table: &'a [Mtd],
abs: u64,
len: u64,
) -> Result<(&'a str, u64), StockError> {
for m in table {
if abs >= m.base && abs < m.base + m.size {
let rel = abs - m.base;
@@ -340,7 +308,7 @@ fn write_abs(
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
)));
}
if !abs.is_multiple_of(ERASE) {
if abs % ERASE != 0 {
return Err(StockError::Method(format!(
"{label} offset 0x{abs:x} is not erase-block aligned"
)));
@@ -367,9 +335,7 @@ fn write_abs(
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!(
"{label}: erase/write failed: {o}"
)))
Err(StockError::Method(format!("{label}: erase/write failed: {o}")))
}
})?;
let readlen = round_up(data.len() as u64, PAGE);
@@ -387,221 +353,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 +431,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,131 +466,70 @@ 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 kernel_len < 64 || kernel_len > SLOT_KERNEL || rootfs_len < 64 || rootfs_len > SLOT_ROOTFS {
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,
table,
BK_MANIFEST,
&manifest.encode(),
"stock-backup-manifest",
)?;
write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?;
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`
@@ -856,7 +569,11 @@ struct BootImages {
rootfs_uimage: Vec<u8>,
}
fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> {
fn write_boot_slots(
sh: &mut dyn Shell,
table: &[Mtd],
img: &BootImages,
) -> Result<(), StockError> {
// rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs
// under an old kernel.
if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS {
@@ -901,82 +618,68 @@ 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(),
));
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,34 +700,17 @@ 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(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1046,53 +732,27 @@ 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![
Mtd {
dev: "mtd0".into(),
base: 0x0,
size: 0x2800000,
name: "x".into(),
},
Mtd {
dev: "mtd1".into(),
base: 0x2800000,
size: 0x2000000,
name: "y".into(),
},
Mtd { dev: "mtd0".into(), base: 0x0, size: 0x2800000, name: "x".into() },
Mtd { dev: "mtd1".into(), base: 0x2800000, size: 0x2000000, name: "y".into() },
];
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
+9 -22
View File
@@ -53,7 +53,9 @@ fn drive(label: &str, handle: StockHandle) -> bool {
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()?;
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 {
@@ -127,10 +129,7 @@ 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 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() {
@@ -184,12 +183,7 @@ fn ip_for_mac(mac: &str) -> Option<String> {
/// 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) {
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);
@@ -261,8 +255,7 @@ pub fn run(spec: &str) -> i32 {
let mac = mac_of(&host);
println!(
"board MAC: {}",
mac.as_deref()
.unwrap_or("unknown (will use the fixed host)")
mac.as_deref().unwrap_or("unknown (will use the fixed host)")
);
let boot_timeout = Duration::from_secs(300);
@@ -277,7 +270,7 @@ pub fn run(spec: &str) -> i32 {
vec![host.clone()],
board.clone(),
AfwSource::Local(afw.clone()),
true, // allow unsigned (bench image)
true, // allow unsigned (bench image)
stock_password.clone(),
false, // not an in-place update
);
@@ -293,10 +286,7 @@ pub fn run(spec: &str) -> i32 {
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)" }
);
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
@@ -313,10 +303,7 @@ pub fn run(spec: &str) -> i32 {
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)" }
);
println!(" {desc} => {}", if ok { "STOCK" } else { "NOT STOCK (fail)" });
all_ok = all_ok && ok;
}
+1 -1
View File
@@ -138,7 +138,7 @@ fn headless_mode() -> bool {
"ALKANE_BENCH_SEQUENCE",
]
.iter()
.any(|v| std::env::var_os(v).is_some())
.any(|v| std::env::var_os(v).is_some())
}
/// A Windows GUI-subsystem process has no console, so output from the headless
+1 -4
View File
@@ -26,10 +26,7 @@ use crate::scan::fake_scan_enabled;
/// `SUPPORTED`). Only these are offered as install targets.
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
(
"a113d",
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
),
("a113d", "Antminer S19j Pro (Amlogic A113D/AXG control board)"),
];
/// The default install board when the user has not chosen another.
+5 -37
View File
@@ -7,7 +7,6 @@ import json
import pathlib
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
@@ -17,12 +16,6 @@ import relay # noqa: E402
TOKEN = "test-token-123"
# The repository's labels, as the real Gitea /labels endpoint would return them.
# The mock serves these, and setUp seeds the relay client's label cache from the
# same list so label resolution is deterministic (see RelayTests.setUp).
REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
{"name": "feature", "id": 3}, {"name": "from-app", "id": 9}]
class FakeGitea:
"""Records issue creations; serves the repository's labels."""
@@ -47,7 +40,9 @@ class FakeGitea:
def do_GET(self):
assert self.headers["Authorization"] == f"token {TOKEN}"
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
return self._json(200, REPO_LABELS)
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
{"name": "feature", "id": 3},
{"name": "from-app", "id": 9}])
self._json(404, {})
def do_POST(self):
@@ -63,23 +58,6 @@ class FakeGitea:
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
# Block until the serve_forever thread is actually handling requests, so
# the relay's first label fetch cannot race server startup. The socket
# listens from __init__, but under load the daemon thread can be starved
# past the relay's HTTP timeout, which silently drops labels to [] and
# made the first test flaky in CI.
probe = urllib.request.Request(
self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels",
headers={"Authorization": f"token {TOKEN}"})
deadline = time.monotonic() + 5
while True:
try:
urllib.request.urlopen(probe, timeout=1).read()
break
except Exception:
if time.monotonic() >= deadline:
raise
time.sleep(0.02)
def close(self):
self.server.shutdown()
@@ -92,18 +70,8 @@ class RelayTests(unittest.TestCase):
self.now = [1000.0]
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
self.logs = []
client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN)
# Seed the relay client's label cache directly from REPO_LABELS instead
# of letting a request handler fetch it live. Gitea.label_ids() caches
# for 10 minutes and silently falls back to [] on any fetch error; in CI
# that first live GET -- a second server-to-server hop made from inside
# the relay's own request thread -- failed reliably and dropped the
# labels to [], while the issue-filing POST on the same path still
# worked. Seeding the cache keeps label resolution deterministic (the
# name->id mapping is still exercised) and leaves the issue POST live.
client.labels = {label["name"]: label["id"] for label in REPO_LABELS}
client.labels_at = time.monotonic()
r = relay.Relay(client, self.limiter, log=self.logs.append)
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
self.limiter, log=self.logs.append)
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"