flash: Zynq tier-2 update in place through the verified writer; verify-live for Zynq
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m24s
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m24s
The Zynq tier-2 install wrote raw images at device-relative offsets on /dev/mtd0 and /dev/mtd1. On the current alkane image those are stock-cfg and alkane-cfg, not the boot regions, so it would have erased alkane-cfg first, and its raw zImage/cpio are not bootable by the stock U-Boot. Its preflight only checked that mtd0 and mtd1 existed. - Add StockMethod::update_in_place: refuses a board not running alkane, re-registers the boot regions (as restore does), saves every slot locally before any erase, writes rootfs/dtb/kernel as the uImages the stock U-Boot boots via the shared target builder (BOOT.bin guard, md5 readback), reboots and waits for alkane. --dry-run reports the live storage map and the plan. - boards::zynq keeps the manifest gate; the plan is now in absolute NAND slots with ceilings that leave room for the uImage header. The stale writer and preflight are removed. - CLI: Zynq preflight/install use the new path before the generic user transport connects. - verify-live gains a Zynq check (HTTP marker, case-insensitive, plus root SSH reporting alkane and the installed kernel; prints the kernel cmdline). It previously fell through to the CV1835 check. - Tests for the protected alkane map, registered and split boot maps, slot overrun, and the BOOT.bin guard. Verified on an S17 (Zynq-7010): dry run, install from a RAM-booted alkane, NAND boot confirmed on the serial console, verify-live PASS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
This commit is contained in:
+126
-48
@@ -14,8 +14,8 @@ use alkane_flash::boards::am335x::{
|
||||
self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions,
|
||||
};
|
||||
use alkane_flash::boards::cv1835::Cv1835Plan;
|
||||
use alkane_flash::boards::zynq::{self, ZynqInstallOptions, ZynqOutcome, ZynqPlan};
|
||||
use alkane_flash::stock::RestoreImages;
|
||||
use alkane_flash::boards::zynq::{self, ZynqPlan};
|
||||
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
|
||||
use alkane_flash::stock_firmware;
|
||||
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
|
||||
use alkane_flash::install::{
|
||||
@@ -422,6 +422,28 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
.first()
|
||||
.ok_or("usage: alkane-cli afw preflight <file> --host <ip>")?;
|
||||
let verified = load_afw(path, &opts)?;
|
||||
// Zynq is reached through the compiled-in method (root SSH, boot regions
|
||||
// re-registered), not the generic user transport below.
|
||||
if zynq::owns_board(&verified.manifest.board) {
|
||||
let host = opts.value("host").ok_or("--host is required")?;
|
||||
let plan = ZynqPlan::from_afw(&verified)?;
|
||||
println!("{}", plan.render());
|
||||
let password = read_board_password(&opts)?;
|
||||
let options = InPlaceOptions {
|
||||
dry_run: true,
|
||||
reboot: false,
|
||||
backup_dir: None,
|
||||
};
|
||||
match stock::update_in_place(host, &verified, password.as_deref(), &options) {
|
||||
Ok(InPlaceOutcome::DryRun(report)) => print!("{report}"),
|
||||
Ok(InPlaceOutcome::Updated(_)) => {
|
||||
return Err("internal error: preflight reported a write".into())
|
||||
}
|
||||
Err(e) => return Err(format!("preflight failed; do not write: {e}").into()),
|
||||
}
|
||||
println!("preflight is read-only; no write performed");
|
||||
return Ok(());
|
||||
}
|
||||
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
|
||||
let mut transport = SshTransport::connect(ssh, true)?;
|
||||
if am335x::owns_board(&verified.manifest.board) {
|
||||
@@ -433,15 +455,6 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if zynq::owns_board(&verified.manifest.board) {
|
||||
let plan = ZynqPlan::from_afw(&verified)?;
|
||||
let report = zynq::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
|
||||
print!("{}", report.render());
|
||||
if !report.ok() {
|
||||
return Err("preflight failed; do not write".into());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if a113d::owns_board(&verified.manifest.board) {
|
||||
let plan = A113dPlan::from_afw(&verified)?;
|
||||
let report = a113d::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
|
||||
@@ -470,6 +483,61 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update a Zynq board that already runs alkane, in place, through the
|
||||
/// compiled-in method: it re-registers the boot regions (not exposed to Linux on
|
||||
/// alkane), keeps a copy of every slot before any erase, writes the kernel and
|
||||
/// rootfs as the uImages the stock U-Boot boots, reads each back, and never
|
||||
/// writes BOOT.bin. A board on stock is refused (use --from-stock).
|
||||
fn install_zynq_in_place(
|
||||
verified: &VerifiedAfw,
|
||||
opts: &Opts,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
let plan = ZynqPlan::from_afw(verified)?;
|
||||
println!("{}", plan.render());
|
||||
let dry_run = opts.flag("dry-run");
|
||||
if !dry_run && opts.value("confirm") != Some("FLASH") {
|
||||
return Err("refusing to write without --confirm FLASH (use --dry-run to inspect)".into());
|
||||
}
|
||||
let backup_dir = opts
|
||||
.value("backup-dir")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| platform::config_path("backups"));
|
||||
let password = read_board_password(opts)?;
|
||||
let options = InPlaceOptions {
|
||||
dry_run,
|
||||
reboot: !opts.flag("no-reboot"),
|
||||
backup_dir: Some(backup_dir),
|
||||
};
|
||||
match stock::update_in_place(&host, verified, password.as_deref(), &options)? {
|
||||
InPlaceOutcome::DryRun(report) => {
|
||||
print!("{report}");
|
||||
println!("DRY RUN: no board erase or write was performed.");
|
||||
println!("Re-run with --confirm FLASH to write rootfs, dtb and kernel (BOOT.bin preserved).");
|
||||
}
|
||||
InPlaceOutcome::Updated(receipt) => {
|
||||
for held in &receipt.backups {
|
||||
println!(
|
||||
"held {} abs 0x{:x} ({} B) {} md5 {}",
|
||||
held.name,
|
||||
held.absolute,
|
||||
held.size,
|
||||
held.path.display(),
|
||||
held.md5
|
||||
);
|
||||
}
|
||||
println!("all read-backs matched before reboot; BOOT.bin never touched");
|
||||
if receipt.rebooted {
|
||||
println!("board rebooted and answered as alkane again (SSH banner)");
|
||||
print!("{}", zynq_verify_hint(&host));
|
||||
} else {
|
||||
println!("reboot skipped (--no-reboot); the new images run after the next reboot");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Install onto a board currently on stock via the from-stock install method.
|
||||
fn install_from_stock_flow(
|
||||
verified: &VerifiedAfw,
|
||||
@@ -498,11 +566,23 @@ fn install_from_stock_flow(
|
||||
);
|
||||
stock::install_from_stock(host, afw, verified, password.as_deref())?;
|
||||
println!("from-stock install reported success.");
|
||||
println!("verify the board is now reachable as alkane:");
|
||||
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
|
||||
if zynq::owns_board(&verified.manifest.board) {
|
||||
print!("{}", zynq_verify_hint(host));
|
||||
} else {
|
||||
println!("verify the board is now reachable as alkane:");
|
||||
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How to confirm a Zynq board came up on alkane.
|
||||
fn zynq_verify_hint(host: &str) -> String {
|
||||
format!(
|
||||
"verify independently:\n\
|
||||
\x20 alkane-cli afw verify-live <the .afw> --host {host} --password-file <alkane root pw> --timeout 300\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let opts = parse_args(
|
||||
args,
|
||||
@@ -537,6 +617,9 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
return install_from_stock_flow(&verified, &host, &path, &opts);
|
||||
}
|
||||
if zynq::owns_board(&verified.manifest.board) {
|
||||
return install_zynq_in_place(&verified, &opts);
|
||||
}
|
||||
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
|
||||
let mut transport = SshTransport::connect(ssh, true)?;
|
||||
let backup_dir = opts
|
||||
@@ -593,39 +676,6 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if zynq::owns_board(&verified.manifest.board) {
|
||||
let plan = ZynqPlan::from_afw(&verified)?;
|
||||
println!("{}", plan.render());
|
||||
let install_options = ZynqInstallOptions {
|
||||
dry_run: opts.flag("dry-run"),
|
||||
confirm: opts.value("confirm").map(str::to_owned),
|
||||
no_reboot: opts.flag("no-reboot"),
|
||||
backup_dir,
|
||||
};
|
||||
match zynq::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
|
||||
ZynqOutcome::DryRun(report) => {
|
||||
print!("{}", report.render());
|
||||
println!("DRY RUN: no board erase or write was performed.");
|
||||
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
|
||||
println!("Re-run with --confirm FLASH to write {targets} (BOOT.bin preserved).");
|
||||
}
|
||||
ZynqOutcome::Installed(receipt) => {
|
||||
for backup in &receipt.backups {
|
||||
println!(
|
||||
"held {} {} offset 0x{:x} md5 {}",
|
||||
backup.image_name, backup.path.display(), backup.offset, backup.md5
|
||||
);
|
||||
}
|
||||
println!("all read-backs matched before reboot; BOOT.bin never touched");
|
||||
if receipt.rebooted {
|
||||
println!("reboot issued; an SSH drop here is the success signature");
|
||||
} else {
|
||||
println!("reboot skipped (--no-reboot)");
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if a113d::owns_board(&verified.manifest.board) {
|
||||
let plan = A113dPlan::from_afw(&verified)?;
|
||||
println!("{}", plan.render());
|
||||
@@ -722,7 +772,16 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() {
|
||||
let verified = load_afw(path, &opts)?;
|
||||
let board = verified.manifest.board.clone();
|
||||
if board == "am335x" {
|
||||
if zynq::owns_board(&board) {
|
||||
let plan = ZynqPlan::from_afw(&verified)?;
|
||||
(
|
||||
board,
|
||||
opts.value("marker").unwrap_or(&plan.marker).to_owned(),
|
||||
opts.value("kernel-version")
|
||||
.unwrap_or(&plan.kernel_version)
|
||||
.to_owned(),
|
||||
)
|
||||
} else if board == "am335x" {
|
||||
let plan = Am335xPlan::from_afw(&verified)?;
|
||||
(
|
||||
board,
|
||||
@@ -745,6 +804,8 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let board = requested_board.clone().unwrap_or_else(|| "cv1835".to_owned());
|
||||
let (marker, kernel) = if board == "am335x" {
|
||||
("Alkane".to_owned(), "6.18.48".to_owned())
|
||||
} else if zynq::owns_board(&board) {
|
||||
("Alkane".to_owned(), String::new())
|
||||
} else {
|
||||
("CVBOOT".to_owned(), String::new())
|
||||
};
|
||||
@@ -760,12 +821,29 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
|
||||
let timeout = opts
|
||||
.value("timeout")
|
||||
.map(str::parse::<u64>)
|
||||
.transpose()?
|
||||
.unwrap_or(DEFAULT_TIMEOUT);
|
||||
if zynq::owns_board(&board) {
|
||||
// Zynq is checked through the compiled-in method's root SSH (the host
|
||||
// key changes on every reflash, so it is not pinned) plus the web page.
|
||||
let password = read_board_password(&opts)?;
|
||||
let report = stock::verify_zynq_live(
|
||||
&host,
|
||||
password.as_deref(),
|
||||
&marker,
|
||||
&kernel_version,
|
||||
Duration::from_secs(timeout),
|
||||
)?;
|
||||
print!("{}", report.render());
|
||||
if !report.ok() {
|
||||
return Err("live verification failed: HTTP marker and SSH did not both confirm alkane".into());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
|
||||
if board == "am335x" {
|
||||
let report = am335x::verify_live(
|
||||
&host,
|
||||
|
||||
@@ -1,45 +1,47 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
|
||||
//! alkane (the first install from stock, past the RSA gate, is handled elsewhere
|
||||
//! and is not this module). It writes our kernel (zImage) into the mtd0
|
||||
//! kernel slot, the dtb, and the rootfs into mtd1, and PRESERVES BOOT.bin
|
||||
//! (FSBL + FPGA bitstream + stock U-Boot) at the front of mtd0.
|
||||
//! Zynq-7010 board module: the manifest gate and write plan for putting our
|
||||
//! OS onto a Zynq control board (Antminer S17/S19 class).
|
||||
//!
|
||||
//! The write offsets are DEVICE-RELATIVE and authoritative here (like the
|
||||
//! am335x MTD_MAP): dtb at 0x1a00000 and kernel at 0x2000000 within /dev/mtd0,
|
||||
//! rootfs at 0 within /dev/mtd1 - the layout the on-board stock U-Boot
|
||||
//! `nandboot` reads, confirmed live on an S17 (alkane-sdk install plan
|
||||
//! install/plans/zynq-7010.yaml, 2026-11-10). The module REFUSES to erase or
|
||||
//! write /dev/mtd0 below BOOTBIN_PRESERVE, so a bad offset can never clobber
|
||||
//! BOOT.bin.
|
||||
//! This module decides WHAT may be written and WHERE, in absolute NAND terms.
|
||||
//! It does not write. The write itself (for a board already on alkane, and for
|
||||
//! the first install from stock) is done by the compiled-in method behind
|
||||
//! `crate::stock` (`update_in_place` / `install_from_stock`), because on a board
|
||||
//! running alkane the boot regions are deliberately not exposed to Linux and
|
||||
//! have to be re-registered first; that mechanism lives with the method.
|
||||
//!
|
||||
//! Layout (absolute NAND offsets, 128 KiB erase blocks): BOOT.bin (FSBL + FPGA
|
||||
//! bitstream + stock U-Boot + env) occupies 0x0..0x1a00000 and is never
|
||||
//! written. The stock U-Boot reads the dtb at 0x1a00000, the kernel at
|
||||
//! 0x2000000 and the ramdisk at 0x2800000, and boots the kernel and ramdisk as
|
||||
//! legacy uImages, so both are written with a 64-byte uImage header.
|
||||
//!
|
||||
//! History: an earlier version of this module wrote raw images at
|
||||
//! device-relative offsets on /dev/mtd0 and /dev/mtd1. That matched an early
|
||||
//! alkane image that exposed the whole NAND, not the current one (which exposes
|
||||
//! only the small `stock-cfg` and `alkane-cfg` partitions), and its raw kernel
|
||||
//! and ramdisk were not bootable by the stock U-Boot. It was removed.
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
use crate::preflight::{classify, parse_digest};
|
||||
use crate::transport::{Remote, RemoteError};
|
||||
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const BOARD: &str = "zynq-7010";
|
||||
pub const ARCH: &str = "armv7";
|
||||
/// mtd0 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) + the
|
||||
/// U-Boot env, and is NEVER erased or written by this module. (Was 0x2200000
|
||||
/// under the superseded stage-2 map; the live S17 layout places the dtb at
|
||||
/// 0x1a00000, so BOOT.bin ends there.)
|
||||
/// Absolute NAND 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock
|
||||
/// U-Boot) + the U-Boot env, and is NEVER erased or written.
|
||||
pub const BOOTBIN_PRESERVE: u64 = 0x1A00000;
|
||||
|
||||
/// Authoritative write targets: (image, device, device-relative offset, ceiling, format).
|
||||
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a new
|
||||
/// rootfs under an old kernel. Offsets and ceilings match the alkane-sdk install
|
||||
/// plan (install/plans/zynq-7010.yaml): dtb slot 0x1a00000 (0x600000), kernel
|
||||
/// slot 0x2000000 (0x800000), rootfs mtd1 (0x2000000).
|
||||
const TARGETS: [(&str, &str, u64, u64, &str); 3] = [
|
||||
("rootfs", "/dev/mtd1", 0x0, 0x2000000, "cpio-gzip"),
|
||||
("dtb", "/dev/mtd0", 0x1A00000, 0x20000, "fdt"),
|
||||
("kernel", "/dev/mtd0", 0x2000000, 0x800000, "zimage"),
|
||||
/// Size of the legacy uImage header the stock U-Boot needs on the kernel and
|
||||
/// the ramdisk.
|
||||
const UIMAGE_HEADER: u64 = 64;
|
||||
|
||||
/// Write targets in write order (rootfs, dtb, kernel, so an interrupted write
|
||||
/// never leaves a new rootfs under an old kernel): (image, absolute NAND
|
||||
/// offset, slot size, expected manifest format, uImage-wrapped).
|
||||
const TARGETS: [(&str, u64, u64, &str, bool); 3] = [
|
||||
("rootfs", 0x2800000, 0x2000000, "cpio-gzip", true),
|
||||
("dtb", 0x1A00000, 0x20000, "fdt", false),
|
||||
("kernel", 0x2000000, 0x800000, "zimage", true),
|
||||
];
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -62,20 +64,23 @@ pub enum ZynqPlanError {
|
||||
MissingImage(String),
|
||||
#[error("zynq-7010 {image} format is {actual}, expected {expected}")]
|
||||
ImageFormat { image: String, actual: String, expected: &'static str },
|
||||
#[error("zynq-7010 {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
|
||||
ImageTooLarge { image: String, size: u64, ceiling: u64 },
|
||||
#[error("zynq-7010 {image} is {size} bytes, over the {ceiling}-byte ceiling for its 0x{slot:x} slot")]
|
||||
ImageTooLarge { image: String, size: u64, ceiling: u64, slot: u64 },
|
||||
#[error("zynq-7010 {image} is not an ARM zImage")]
|
||||
NotZImage { image: String },
|
||||
#[error("zynq-7010 refuses to place {image} at 0x{offset:x} on {device}: below BOOT.bin (0x{bootbin:x})")]
|
||||
WouldClobberBootbin { image: String, device: String, offset: u64, bootbin: u64 },
|
||||
#[error("zynq-7010 refuses to place {image} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
|
||||
WouldClobberBootbin { image: String, offset: u64, bootbin: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqTarget {
|
||||
pub image_name: String,
|
||||
pub device: String,
|
||||
pub offset: u64,
|
||||
/// Absolute NAND offset of the slot.
|
||||
pub absolute: u64,
|
||||
pub slot: u64,
|
||||
/// Size of the image as shipped in the `.afw` (before any uImage header).
|
||||
pub size: u64,
|
||||
pub uimage_wrapped: bool,
|
||||
pub data: Vec<u8>,
|
||||
pub expected_md5: String,
|
||||
}
|
||||
@@ -88,7 +93,6 @@ pub struct ZynqPlan {
|
||||
pub sdk_revision: String,
|
||||
pub os_revision: String,
|
||||
pub afw_sha256: String,
|
||||
pub min_free_bytes: u64,
|
||||
}
|
||||
|
||||
fn is_bootloaderish(image: &AfwImage) -> bool {
|
||||
@@ -130,7 +134,7 @@ impl ZynqPlan {
|
||||
}
|
||||
|
||||
let mut targets = Vec::with_capacity(TARGETS.len());
|
||||
for (image_name, device, offset, ceiling, expected_format) in TARGETS {
|
||||
for (image_name, absolute, slot, expected_format, wrapped) in TARGETS {
|
||||
let image = manifest
|
||||
.images
|
||||
.iter()
|
||||
@@ -143,20 +147,20 @@ impl ZynqPlan {
|
||||
expected: expected_format,
|
||||
});
|
||||
}
|
||||
let ceiling = if wrapped { slot - UIMAGE_HEADER } else { slot };
|
||||
if image.size > ceiling {
|
||||
return Err(ZynqPlanError::ImageTooLarge {
|
||||
image: image_name.to_owned(),
|
||||
size: image.size,
|
||||
ceiling,
|
||||
slot,
|
||||
});
|
||||
}
|
||||
// The one hard brick guard: a write on /dev/mtd0 must sit entirely
|
||||
// above BOOT.bin.
|
||||
if device == "/dev/mtd0" && offset < BOOTBIN_PRESERVE {
|
||||
// The hard brick guard: nothing is ever placed inside BOOT.bin.
|
||||
if absolute < BOOTBIN_PRESERVE {
|
||||
return Err(ZynqPlanError::WouldClobberBootbin {
|
||||
image: image_name.to_owned(),
|
||||
device: device.to_owned(),
|
||||
offset,
|
||||
offset: absolute,
|
||||
bootbin: BOOTBIN_PRESERVE,
|
||||
});
|
||||
}
|
||||
@@ -171,9 +175,10 @@ impl ZynqPlan {
|
||||
}
|
||||
targets.push(ZynqTarget {
|
||||
image_name: image_name.to_owned(),
|
||||
device: device.to_owned(),
|
||||
offset,
|
||||
absolute,
|
||||
slot,
|
||||
size: image.size,
|
||||
uimage_wrapped: wrapped,
|
||||
expected_md5: md5_hex(data),
|
||||
data: data.to_vec(),
|
||||
});
|
||||
@@ -186,25 +191,26 @@ impl ZynqPlan {
|
||||
sdk_revision: manifest.sdk_revision.clone(),
|
||||
os_revision: manifest.os_revision.clone(),
|
||||
afw_sha256: afw.archive_sha256.clone(),
|
||||
min_free_bytes: manifest
|
||||
.preflight
|
||||
.get("min_free_bytes")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(16 * 1024 * 1024),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("board {BOARD} arch {ARCH}\n");
|
||||
out.push_str(&format!(
|
||||
"tier 2 update: write the kernel slot + mtd1; BOOT.bin (mtd0 0..0x{:x}) preserved, never written\n",
|
||||
BOOTBIN_PRESERVE
|
||||
"boot slots (absolute NAND); BOOT.bin 0x0..0x{BOOTBIN_PRESERVE:x} preserved, never written\n"
|
||||
));
|
||||
out.push_str("image format kernel=zImage, dtb=fdt, rootfs=cpio-gzip\n");
|
||||
out.push_str(
|
||||
"kernel and rootfs are written as legacy uImages (what the stock U-Boot boots); dtb raw\n",
|
||||
);
|
||||
for target in &self.targets {
|
||||
out.push_str(&format!(
|
||||
"write {} {} offset 0x{:x} size {} B md5 {}\n",
|
||||
target.image_name, target.device, target.offset, target.size, target.expected_md5
|
||||
"write {:<6} abs 0x{:x} slot 0x{:x} size {} B{} md5 {}\n",
|
||||
target.image_name,
|
||||
target.absolute,
|
||||
target.slot,
|
||||
target.size,
|
||||
if target.uimage_wrapped { " +64 B header" } else { "" },
|
||||
target.expected_md5
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
@@ -222,273 +228,6 @@ fn short(rev: &str) -> &str {
|
||||
rev.get(..12).unwrap_or(rev)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ZynqError {
|
||||
#[error("preflight failed:\n{0}")]
|
||||
Preflight(String),
|
||||
#[error("--confirm FLASH is required to write")]
|
||||
Confirm,
|
||||
#[error("refusing to write {device} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
|
||||
BootbinGuard { device: String, offset: u64, bootbin: u64 },
|
||||
#[error("{0} staged md5 differs from the verified bundle")]
|
||||
StageMismatch(String),
|
||||
#[error("{0} read-back md5 mismatch; do not reboot")]
|
||||
Readback(String),
|
||||
#[error(transparent)]
|
||||
Remote(#[from] RemoteError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqCheck {
|
||||
pub name: String,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqPreflight {
|
||||
pub host: String,
|
||||
pub checks: Vec<ZynqCheck>,
|
||||
}
|
||||
|
||||
impl ZynqPreflight {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.checks.iter().all(|c| c.ok)
|
||||
}
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("preflight {}\n", self.host);
|
||||
for c in &self.checks {
|
||||
out.push_str(&format!("check {} {}: {}\n", c.name, if c.ok { "ok" } else { "FAIL" }, c.detail));
|
||||
}
|
||||
out.push_str(&format!("result {}", if self.ok() { "PASS" } else { "FAIL (do not write)" }));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preflight(
|
||||
plan: &ZynqPlan,
|
||||
remote: &mut dyn Remote,
|
||||
host: &str,
|
||||
) -> Result<ZynqPreflight, ZynqError> {
|
||||
let mut checks = Vec::new();
|
||||
|
||||
let fingerprint = remote.user_command(
|
||||
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
|
||||
echo __RELEASE__; cat /etc/os-release 2>/dev/null; cat /etc/alkane-release 2>/dev/null \
|
||||
|| true",
|
||||
Duration::from_secs(20),
|
||||
)?;
|
||||
let text = String::from_utf8_lossy(&fingerprint).into_owned();
|
||||
let mut it = text.split("__MODEL__");
|
||||
let kernel = it.next().unwrap_or("").trim().to_owned();
|
||||
let rest = it.next().unwrap_or("");
|
||||
let mut it2 = rest.split("__RELEASE__");
|
||||
let _model = it2.next().unwrap_or("");
|
||||
let release = it2.next().unwrap_or("");
|
||||
let source = classify(&kernel, release, &text);
|
||||
checks.push(ZynqCheck {
|
||||
name: "source-os".to_owned(),
|
||||
ok: source == "alkane",
|
||||
detail: format!("{source} (update path requires alkane)"),
|
||||
});
|
||||
|
||||
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
checks.push(ZynqCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
|
||||
|
||||
let tools = remote.user_command(
|
||||
"for c in /usr/sbin/flash_erase /usr/sbin/nandwrite /usr/sbin/nanddump md5sum sync; do \
|
||||
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let missing: Vec<String> = String::from_utf8_lossy(&tools)
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
|
||||
.collect();
|
||||
checks.push(ZynqCheck {
|
||||
name: "commands".to_owned(),
|
||||
ok: missing.is_empty(),
|
||||
detail: if missing.is_empty() { "flash tools present".to_owned() } else { format!("missing {}", missing.join(", ")) },
|
||||
});
|
||||
|
||||
let mtd = String::from_utf8_lossy(&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?).into_owned();
|
||||
let have_mtd01 = mtd.contains("mtd0:") && mtd.contains("mtd1:");
|
||||
checks.push(ZynqCheck {
|
||||
name: "mtd".to_owned(),
|
||||
ok: have_mtd01,
|
||||
detail: if have_mtd01 { "mtd0 (BOOT.bin+kernel) and mtd1 present".to_owned() } else { format!("mtd0/mtd1 not found: {mtd}") },
|
||||
});
|
||||
|
||||
// The guard, asserted again at preflight: no target writes mtd0 below BOOT.bin.
|
||||
let guard_ok = plan
|
||||
.targets
|
||||
.iter()
|
||||
.all(|t| !(t.device == "/dev/mtd0" && t.offset < BOOTBIN_PRESERVE));
|
||||
checks.push(ZynqCheck {
|
||||
name: "preserve-bootbin".to_owned(),
|
||||
ok: guard_ok,
|
||||
detail: format!("no write on /dev/mtd0 below 0x{BOOTBIN_PRESERVE:x}"),
|
||||
});
|
||||
|
||||
Ok(ZynqPreflight { host: host.to_owned(), checks })
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqInstallOptions {
|
||||
pub dry_run: bool,
|
||||
pub confirm: Option<String>,
|
||||
pub no_reboot: bool,
|
||||
pub backup_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqBackup {
|
||||
pub image_name: String,
|
||||
pub device: String,
|
||||
pub offset: u64,
|
||||
pub path: PathBuf,
|
||||
pub md5: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqReceipt {
|
||||
pub backups: Vec<ZynqBackup>,
|
||||
pub rebooted: bool,
|
||||
}
|
||||
|
||||
pub enum ZynqOutcome {
|
||||
DryRun(Box<ZynqPreflight>),
|
||||
Installed(ZynqReceipt),
|
||||
}
|
||||
|
||||
|
||||
/// flash_erase/nandwrite erase-block count that covers `size` bytes at a 128 KiB
|
||||
/// erase block (the Zynq pl35x-nand block size).
|
||||
fn erase_blocks(size: u64) -> u64 {
|
||||
const BLOCK: u64 = 0x20000;
|
||||
size.div_ceil(BLOCK)
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
plan: &ZynqPlan,
|
||||
remote: &mut dyn Remote,
|
||||
options: &ZynqInstallOptions,
|
||||
host: &str,
|
||||
) -> Result<ZynqOutcome, ZynqError> {
|
||||
let report = preflight(plan, remote, host)?;
|
||||
if !report.ok() {
|
||||
return Err(ZynqError::Preflight(report.render()));
|
||||
}
|
||||
if options.dry_run {
|
||||
return Ok(ZynqOutcome::DryRun(Box::new(report)));
|
||||
}
|
||||
if options.confirm.as_deref() != Some("FLASH") {
|
||||
return Err(ZynqError::Confirm);
|
||||
}
|
||||
fs::create_dir_all(&options.backup_dir)?;
|
||||
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
let mut backups = Vec::new();
|
||||
|
||||
for target in &plan.targets {
|
||||
// Hard guard, right before touching NAND: never below BOOT.bin on mtd0.
|
||||
if target.device == "/dev/mtd0" && target.offset < BOOTBIN_PRESERVE {
|
||||
return Err(ZynqError::BootbinGuard {
|
||||
device: target.device.clone(),
|
||||
offset: target.offset,
|
||||
bootbin: BOOTBIN_PRESERVE,
|
||||
});
|
||||
}
|
||||
let name = &target.image_name;
|
||||
let device = &target.device;
|
||||
let offset = target.offset;
|
||||
|
||||
// Back up the region we are about to overwrite, offset-aware.
|
||||
let remote_backup = format!("/tmp/.alkane-z-{name}-backup.img");
|
||||
remote.root_command(
|
||||
&format!(
|
||||
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_backup} {device}",
|
||||
target.size
|
||||
),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
let local = options.backup_dir.join(format!("{name}-{epoch}.img"));
|
||||
remote.pull(&remote_backup, &local, Duration::from_secs(300))?;
|
||||
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
|
||||
let data = fs::read(&local)?;
|
||||
let md5 = md5_hex(&data);
|
||||
backups.push(ZynqBackup {
|
||||
image_name: name.clone(),
|
||||
device: device.clone(),
|
||||
offset,
|
||||
path: local,
|
||||
md5,
|
||||
size: target.size,
|
||||
});
|
||||
|
||||
// Stage the verified payload and prove its remote md5 before writing.
|
||||
let mut staged = tempfile::NamedTempFile::new()?;
|
||||
staged.write_all(&target.data)?;
|
||||
staged.flush()?;
|
||||
let remote_stage = format!("/tmp/.alkane-z-{name}-stage.img");
|
||||
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
|
||||
let staged_md5 = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
if staged_md5 != target.expected_md5 {
|
||||
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
|
||||
return Err(ZynqError::StageMismatch(name.clone()));
|
||||
}
|
||||
|
||||
// Erase and write exactly the region at its offset. flash_erase takes an
|
||||
// offset + block count, so BOOT.bin (below the offset) is never touched.
|
||||
let blocks = erase_blocks(target.size);
|
||||
remote.root_command(
|
||||
&format!("/usr/sbin/flash_erase {device} 0x{offset:x} {blocks}"),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
remote.root_command(
|
||||
&format!("/usr/sbin/nandwrite -p --start=0x{offset:x} {device} {remote_stage} && sync"),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
|
||||
// Read back exactly what we wrote and compare.
|
||||
let remote_readback = format!("/tmp/.alkane-z-{name}-readback.img");
|
||||
remote.root_command(
|
||||
&format!(
|
||||
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_readback} {device}",
|
||||
target.size
|
||||
),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
let readback = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {remote_readback}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let _ = remote.root_command(
|
||||
&format!("rm -f {remote_stage} {remote_readback}"),
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
if readback != target.expected_md5 {
|
||||
return Err(ZynqError::Readback(name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let rebooted = if options.no_reboot {
|
||||
false
|
||||
} else {
|
||||
remote.reboot()?;
|
||||
true
|
||||
};
|
||||
Ok(ZynqOutcome::Installed(ZynqReceipt { backups, rebooted }))
|
||||
}
|
||||
|
||||
pub fn owns_board(board: &str) -> bool {
|
||||
board == BOARD
|
||||
}
|
||||
@@ -557,11 +296,22 @@ mod tests {
|
||||
assert_eq!(plan.targets[0].image_name, "rootfs");
|
||||
assert_eq!(plan.targets[2].image_name, "kernel");
|
||||
for t in &plan.targets {
|
||||
if t.device == "/dev/mtd0" {
|
||||
assert!(t.offset >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
|
||||
}
|
||||
assert!(t.absolute >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
|
||||
}
|
||||
assert!(plan.render().contains("BOOT.bin"));
|
||||
let render = plan.render();
|
||||
assert!(render.contains("BOOT.bin"));
|
||||
assert!(render.contains("uImage"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_match_the_stock_uboot_layout() {
|
||||
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
|
||||
let at = |name: &str| plan.targets.iter().find(|t| t.image_name == name).unwrap();
|
||||
assert_eq!((at("dtb").absolute, at("dtb").slot), (0x1A00000, 0x20000));
|
||||
assert_eq!((at("kernel").absolute, at("kernel").slot), (0x2000000, 0x800000));
|
||||
assert_eq!((at("rootfs").absolute, at("rootfs").slot), (0x2800000, 0x2000000));
|
||||
assert!(at("kernel").uimage_wrapped && at("rootfs").uimage_wrapped);
|
||||
assert!(!at("dtb").uimage_wrapped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -571,11 +321,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_oversize_kernel() {
|
||||
// Over the kernel-slot ceiling (0x800000).
|
||||
let big = zimage(&vec![0u8; 0x800001]);
|
||||
fn refuses_a_kernel_that_would_not_fit_with_its_uimage_header() {
|
||||
// Exactly the slot size is too big once the 64-byte header is added.
|
||||
let big = zimage(&vec![0u8; 0x800000 - 64]);
|
||||
assert_eq!(big.len(), 0x800000);
|
||||
let result = ZynqPlan::from_afw(&afw(big, dtb(), b"\x1f\x8brf".to_vec()));
|
||||
assert!(matches!(result, Err(ZynqPlanError::ImageTooLarge { .. })));
|
||||
let fits = zimage(&vec![0u8; 0x800000 - 128]);
|
||||
assert!(ZynqPlan::from_afw(&afw(fits, dtb(), b"\x1f\x8brf".to_vec())).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -596,12 +349,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_mtd0_target_is_above_bootbin() {
|
||||
// Compile-time-ish guarantee from the TARGETS table.
|
||||
for (image, device, offset, _ceiling, _fmt) in TARGETS {
|
||||
if device == "/dev/mtd0" {
|
||||
assert!(offset >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
|
||||
}
|
||||
fn every_target_is_above_bootbin() {
|
||||
for (image, absolute, _slot, _fmt, _wrapped) in TARGETS {
|
||||
assert!(absolute >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
//! network-only.
|
||||
|
||||
use alkane_artifacts::afw::VerifiedAfw;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -43,6 +43,78 @@ pub struct RestoreImages<'a> {
|
||||
pub rootfs: &'a [u8],
|
||||
}
|
||||
|
||||
/// Options for updating a board that already runs alkane, in place.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InPlaceOptions {
|
||||
/// Read-only: report the board state, the storage map and the write plan,
|
||||
/// and write nothing.
|
||||
pub dry_run: bool,
|
||||
/// Reboot after the images are written and read back, then wait for the
|
||||
/// board to return as alkane.
|
||||
pub reboot: bool,
|
||||
/// Where to keep a copy of each boot slot as it was before the write. When
|
||||
/// set, every slot is read and saved before any erase; a failed backup
|
||||
/// aborts the update with nothing written.
|
||||
pub backup_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// One boot slot as it was before an in-place update.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HeldSlot {
|
||||
pub name: String,
|
||||
/// Absolute NAND offset of the slot.
|
||||
pub absolute: u64,
|
||||
pub size: u64,
|
||||
pub path: PathBuf,
|
||||
pub md5: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InPlaceReceipt {
|
||||
pub backups: Vec<HeldSlot>,
|
||||
pub rebooted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum InPlaceOutcome {
|
||||
/// The dry-run report; nothing was written.
|
||||
DryRun(String),
|
||||
Updated(InPlaceReceipt),
|
||||
}
|
||||
|
||||
/// Result of a live check that a Zynq board is up on alkane: two channels
|
||||
/// (HTTP page marker, SSH kernel/OS) must agree.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LiveCheck {
|
||||
pub attempts: u32,
|
||||
pub http: String,
|
||||
pub http_ok: bool,
|
||||
pub ssh: String,
|
||||
pub ssh_ok: bool,
|
||||
/// The running kernel command line (informational: on a NAND boot it is
|
||||
/// the board's U-Boot env bootargs).
|
||||
pub cmdline: String,
|
||||
}
|
||||
|
||||
impl LiveCheck {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.http_ok && self.ssh_ok
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
format!(
|
||||
"verify-live attempts {}\n http {}: {}\n ssh {}: {}\n cmdline: {}\nresult {}\n",
|
||||
self.attempts,
|
||||
if self.http_ok { "PASS" } else { "FAIL" },
|
||||
self.http,
|
||||
if self.ssh_ok { "PASS" } else { "FAIL" },
|
||||
self.ssh,
|
||||
if self.cmdline.is_empty() { "(not read)" } else { &self.cmdline },
|
||||
if self.ok() { "PASS" } else { "FAIL" }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The stock-side methods, implemented by `stock_method`. All implementations
|
||||
/// must be NETWORK-ONLY (no serial-console dependency).
|
||||
pub trait StockMethod {
|
||||
@@ -67,6 +139,20 @@ pub trait StockMethod {
|
||||
images: &RestoreImages,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError>;
|
||||
|
||||
/// Update a board that already runs alkane to the `.afw`'s images, over the
|
||||
/// network only. Refuses a board that is not running alkane (a board on
|
||||
/// stock is installed with `install_from_stock`). The boot regions are not
|
||||
/// exposed to Linux on alkane, so they are re-registered the same way as for
|
||||
/// a restore; the images are written in the form the board's stock U-Boot
|
||||
/// boots, each read back before reboot, and BOOT.bin is never written.
|
||||
fn update_in_place(
|
||||
&self,
|
||||
host: &str,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
options: &InPlaceOptions,
|
||||
) -> Result<InPlaceOutcome, StockError>;
|
||||
}
|
||||
|
||||
/// The compiled-in method implementation.
|
||||
@@ -94,6 +180,30 @@ pub fn restore_to_stock(
|
||||
method().restore_to_stock(host, images, password)
|
||||
}
|
||||
|
||||
/// Check, over the network, that a Zynq board is up on alkane: the web page
|
||||
/// carries `marker` (case-insensitive) and SSH reports alkane with a kernel
|
||||
/// containing `kernel_version` (if non-empty). Retries until `timeout`.
|
||||
pub fn verify_zynq_live(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
marker: &str,
|
||||
kernel_version: &str,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<LiveCheck, StockError> {
|
||||
crate::stock_method::live_check(host, password, marker, kernel_version, timeout)
|
||||
}
|
||||
|
||||
/// Update a board already on alkane to the `.afw`'s images, in place
|
||||
/// (network-only), via the compiled-in method.
|
||||
pub fn update_in_place(
|
||||
host: &str,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
options: &InPlaceOptions,
|
||||
) -> Result<InPlaceOutcome, StockError> {
|
||||
method().update_in_place(host, afw, password, options)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -15,7 +15,10 @@
|
||||
//! bitstream and U-Boot). Every write target in this module is checked to sit
|
||||
//! at or above that boundary before any erase or write is issued.
|
||||
|
||||
use crate::stock::{RestoreImages, StockError, StockMethod};
|
||||
use crate::stock::{
|
||||
HeldSlot, InPlaceOptions, InPlaceOutcome, InPlaceReceipt, RestoreImages, StockError,
|
||||
StockMethod,
|
||||
};
|
||||
use alkane_artifacts::afw::VerifiedAfw;
|
||||
use std::borrow::Cow;
|
||||
use std::env;
|
||||
@@ -1284,6 +1287,7 @@ struct FlashTarget {
|
||||
file: &'static str,
|
||||
device: String,
|
||||
rel: u64,
|
||||
absolute: u64,
|
||||
slot: u64,
|
||||
data: Cow<'static, [u8]>,
|
||||
raw_md5: String,
|
||||
@@ -1435,6 +1439,7 @@ fn make_target(
|
||||
file,
|
||||
device,
|
||||
rel,
|
||||
absolute,
|
||||
slot,
|
||||
data,
|
||||
raw_md5,
|
||||
@@ -1685,14 +1690,16 @@ fn install_via_web(
|
||||
}
|
||||
}
|
||||
|
||||
fn install_via_ssh(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
/// The alkane write set for this board, placed on the given storage map:
|
||||
/// rootfs, then dtb, then kernel (so an interrupted write never leaves a new
|
||||
/// rootfs under an old kernel). `kernel` and `rootfs` are the uImage-wrapped
|
||||
/// forms from `load_install_images`.
|
||||
fn alkane_targets(
|
||||
map: &[Mtd],
|
||||
kernel: Vec<u8>,
|
||||
dtb: Vec<u8>,
|
||||
rootfs: Vec<u8>,
|
||||
) -> Result<(), StockError> {
|
||||
let map = get_mtd_map(host, password)?;
|
||||
) -> Result<Vec<FlashTarget>, StockError> {
|
||||
let images = vec![
|
||||
(
|
||||
"rootfs",
|
||||
@@ -1710,7 +1717,18 @@ fn install_via_ssh(
|
||||
Cow::Owned(kernel),
|
||||
),
|
||||
];
|
||||
let targets = targets_from_map(&map, images)?;
|
||||
targets_from_map(map, images)
|
||||
}
|
||||
|
||||
fn install_via_ssh(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
kernel: Vec<u8>,
|
||||
dtb: Vec<u8>,
|
||||
rootfs: Vec<u8>,
|
||||
) -> Result<(), StockError> {
|
||||
let map = get_mtd_map(host, password)?;
|
||||
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
|
||||
flash_via_ssh(host, password, &targets)?;
|
||||
reboot_target(host, password);
|
||||
if wait_alkane(host, Duration::from_secs(240)) {
|
||||
@@ -1759,6 +1777,279 @@ fn flash_via_ssh(
|
||||
Err(classify_ssh(&result))
|
||||
}
|
||||
|
||||
/// Read each target's whole slot as it is now and keep it under `dir`, before
|
||||
/// anything is erased. Any short read or local write failure is an error, so
|
||||
/// the caller aborts with nothing written.
|
||||
fn hold_slots(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
targets: &[FlashTarget],
|
||||
dir: &Path,
|
||||
) -> Result<Vec<HeldSlot>, StockError> {
|
||||
fs::create_dir_all(dir)
|
||||
.map_err(|e| StockError::Io(format!("could not create the backup directory: {e}")))?;
|
||||
let stamp = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
let safe_host: String = host
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '.' { c } else { '_' })
|
||||
.collect();
|
||||
let mut held = Vec::with_capacity(targets.len());
|
||||
for target in targets {
|
||||
let remote = format!(
|
||||
"dd if={} bs={} skip={} count={} 2>/dev/null",
|
||||
target.device,
|
||||
BLK,
|
||||
target.rel / BLK,
|
||||
target.slot / BLK
|
||||
);
|
||||
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
|
||||
if !result.ok() {
|
||||
return Err(classify_ssh(&result));
|
||||
}
|
||||
if result.stdout.len() as u64 != target.slot {
|
||||
return Err(StockError::Method(format!(
|
||||
"backup of the {} slot was short ({} of {} bytes); nothing was written",
|
||||
target.name,
|
||||
result.stdout.len(),
|
||||
target.slot
|
||||
)));
|
||||
}
|
||||
let absolute = target.absolute;
|
||||
let path = dir.join(format!(
|
||||
"zynq-{safe_host}-{}-0x{absolute:x}-{stamp}.img",
|
||||
target.name
|
||||
));
|
||||
write_private_new(&path, &result.stdout)?;
|
||||
held.push(HeldSlot {
|
||||
name: target.name.to_string(),
|
||||
absolute,
|
||||
size: target.slot,
|
||||
path,
|
||||
md5: md5_hex(&result.stdout),
|
||||
});
|
||||
}
|
||||
Ok(held)
|
||||
}
|
||||
|
||||
fn render_map(map: &[Mtd]) -> String {
|
||||
let mut out = String::new();
|
||||
for mtd in map {
|
||||
out.push_str(&format!(
|
||||
" {} 0x{:08x}..0x{:08x} (0x{:x})\n",
|
||||
mtd.device,
|
||||
mtd.offset,
|
||||
mtd.offset + mtd.size,
|
||||
mtd.size
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn render_targets(targets: &[FlashTarget]) -> String {
|
||||
let mut out = String::new();
|
||||
for t in targets {
|
||||
out.push_str(&format!(
|
||||
" {:<6} -> {} +0x{:x} (abs 0x{:x}) slot 0x{:x}, {} bytes, md5 {}\n",
|
||||
t.name,
|
||||
t.device,
|
||||
t.rel,
|
||||
t.absolute,
|
||||
t.slot,
|
||||
t.data.len(),
|
||||
t.raw_md5
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Planned images in absolute NAND terms, independent of how the board's
|
||||
/// partitions are currently registered.
|
||||
fn render_absolute_plan(kernel: &[u8], dtb: &[u8], rootfs: &[u8]) -> String {
|
||||
let mut out = String::new();
|
||||
for (name, absolute, slot, data) in [
|
||||
("rootfs", ABS_ROOTFS, ROOTFS_SLOT, rootfs),
|
||||
("dtb", ABS_DTB, DTB_SLOT, dtb),
|
||||
("kernel", ABS_KERNEL, KERNEL_SLOT, kernel),
|
||||
] {
|
||||
out.push_str(&format!(
|
||||
" {:<6} -> abs 0x{:x} slot 0x{:x}, {} bytes, md5 {}\n",
|
||||
name,
|
||||
absolute,
|
||||
slot,
|
||||
data.len(),
|
||||
md5_hex(data)
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn update_in_place_impl(
|
||||
host: &str,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
options: &InPlaceOptions,
|
||||
) -> Result<InPlaceOutcome, StockError> {
|
||||
validate_host(host)?;
|
||||
let (kernel, dtb, rootfs) = load_install_images(afw)?;
|
||||
if !ssh_port_open(host) {
|
||||
return Err(StockError::Network("target unreachable".into()));
|
||||
}
|
||||
let resolved = resolve_password(password);
|
||||
let password = resolved.as_deref();
|
||||
ssh_probe(host, password)?;
|
||||
let state = board_state(host, password)?;
|
||||
if state != "alkane" {
|
||||
return Err(StockError::Method(format!(
|
||||
"the board is not running alkane (detected: {state}); a board on stock is installed with --from-stock"
|
||||
)));
|
||||
}
|
||||
|
||||
if options.dry_run {
|
||||
let map = read_mtd_map(host, password)?;
|
||||
let mut report = String::new();
|
||||
report.push_str(&format!("board {host}: running alkane\n"));
|
||||
report.push_str("storage as registered now:\n");
|
||||
report.push_str(&render_map(&map));
|
||||
if map_covers_boot_regions(&map) {
|
||||
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
|
||||
report.push_str("boot regions are registered; writes would go to:\n");
|
||||
report.push_str(&render_targets(&targets));
|
||||
} else {
|
||||
report.push_str(
|
||||
"boot regions are NOT registered (normal on alkane); the update re-registers \
|
||||
them first, as a restore does, then writes:\n",
|
||||
);
|
||||
report.push_str(&render_absolute_plan(&kernel, &dtb, &rootfs));
|
||||
}
|
||||
report.push_str(&format!(
|
||||
"BOOT.bin (abs 0x0..0x{BOOTBIN_PRESERVE:x}) is never written.\n"
|
||||
));
|
||||
if options.backup_dir.is_some() {
|
||||
report.push_str("each slot would be saved locally before any erase.\n");
|
||||
}
|
||||
return Ok(InPlaceOutcome::DryRun(report));
|
||||
}
|
||||
|
||||
let map = get_mtd_map(host, password)?;
|
||||
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
|
||||
let backups = match &options.backup_dir {
|
||||
Some(dir) => hold_slots(host, password, &targets, dir)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
flash_via_ssh(host, password, &targets)?;
|
||||
if !options.reboot {
|
||||
return Ok(InPlaceOutcome::Updated(InPlaceReceipt {
|
||||
backups,
|
||||
rebooted: false,
|
||||
}));
|
||||
}
|
||||
reboot_target(host, password);
|
||||
// Wait for the board to actually go down before waiting for it to return,
|
||||
// so a slow reboot is not mistaken for the old system still answering.
|
||||
let _ = wait_for(|| !ssh_port_open(host), Duration::from_secs(60));
|
||||
if wait_alkane(host, Duration::from_secs(300)) {
|
||||
Ok(InPlaceOutcome::Updated(InPlaceReceipt {
|
||||
backups,
|
||||
rebooted: true,
|
||||
}))
|
||||
} else {
|
||||
Err(StockError::Method(
|
||||
"images were written and read back, but the board did not return as alkane after reboot"
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP GET / and report (status-200, marker present case-insensitively).
|
||||
fn http_marker(host: &str, marker: &str) -> (String, bool) {
|
||||
let mut command = Command::new("curl");
|
||||
command.args(["-sS", "-i", "--max-time", "6", &format!("http://{host}/")]);
|
||||
match run_command(command, Duration::from_secs(12), None) {
|
||||
Ok(result) if result.ok() => {
|
||||
let body = text(&result.stdout);
|
||||
let status = body.lines().next().unwrap_or("").trim().to_string();
|
||||
let is_200 = status.contains(" 200");
|
||||
let has = body.to_lowercase().contains(&marker.to_lowercase());
|
||||
let title = body
|
||||
.split("<title>")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split("</title>").next())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let detail = format!(
|
||||
"{status}; title \"{title}\"; marker {marker} {}",
|
||||
if has { "present" } else { "absent" }
|
||||
);
|
||||
(detail, is_200 && has)
|
||||
}
|
||||
Ok(result) => (format!("no HTTP answer ({})", text(&result.stderr).trim()), false),
|
||||
Err(e) => (format!("{e}"), false),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn live_check(
|
||||
host: &str,
|
||||
password: Option<&str>,
|
||||
marker: &str,
|
||||
kernel_version: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<crate::stock::LiveCheck, StockError> {
|
||||
validate_host(host)?;
|
||||
let resolved = resolve_password(password);
|
||||
let password = resolved.as_deref();
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
attempts += 1;
|
||||
let (http, http_ok) = http_marker(host, marker);
|
||||
let (ssh, ssh_ok, cmdline) = match ssh_exec(
|
||||
host,
|
||||
password,
|
||||
"uname -r; echo '##'; cat /proc/cmdline; echo '##'; \
|
||||
cat /etc/os-release /etc/issue 2>/dev/null; hostname; [ -d /etc/alkane ] && echo alkane-etc",
|
||||
Duration::from_secs(20),
|
||||
) {
|
||||
Ok(result) if result.ok() => {
|
||||
let out = text(&result.stdout);
|
||||
let mut parts = out.split("##\n");
|
||||
let kernel = parts.next().unwrap_or("").trim().to_string();
|
||||
let cmdline = parts.next().unwrap_or("").trim().to_string();
|
||||
let os = parts.next().unwrap_or("").to_lowercase();
|
||||
let is_alkane = os.contains("alkane");
|
||||
let kernel_ok =
|
||||
!kernel.is_empty() && (kernel_version.is_empty() || kernel.contains(kernel_version));
|
||||
(
|
||||
format!(
|
||||
"kernel {kernel}; os {}{}",
|
||||
if is_alkane { "alkane" } else { "not alkane" },
|
||||
if kernel_ok { "" } else { " (expected the installed kernel)" }
|
||||
),
|
||||
is_alkane && kernel_ok,
|
||||
cmdline,
|
||||
)
|
||||
}
|
||||
Ok(result) => (format!("{}", classify_ssh(&result)), false, String::new()),
|
||||
Err(e) => (format!("{e}"), false, String::new()),
|
||||
};
|
||||
let done = (http_ok && ssh_ok) || Instant::now() >= deadline;
|
||||
if done {
|
||||
return Ok(crate::stock::LiveCheck {
|
||||
attempts,
|
||||
http,
|
||||
http_ok,
|
||||
ssh,
|
||||
ssh_ok,
|
||||
cmdline,
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
|
||||
fn board_state(host: &str, password: Option<&str>) -> Result<String, StockError> {
|
||||
let result = ssh_exec(
|
||||
host,
|
||||
@@ -1887,6 +2178,16 @@ impl StockMethod for Method {
|
||||
let _ = wait_stock(host, Duration::from_secs(90));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_in_place(
|
||||
&self,
|
||||
host: &str,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
options: &InPlaceOptions,
|
||||
) -> Result<InPlaceOutcome, StockError> {
|
||||
update_in_place_impl(host, afw, password, options)
|
||||
}
|
||||
}
|
||||
|
||||
static METHOD: Method = Method;
|
||||
@@ -2005,6 +2306,99 @@ mod tests {
|
||||
assert_eq!(data_crc, crc32(b"payload"));
|
||||
}
|
||||
|
||||
fn mtd(device: &str, offset: u64, size: u64) -> Mtd {
|
||||
Mtd {
|
||||
device: device.to_string(),
|
||||
offset,
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The storage map the current alkane image registers: only the two small
|
||||
/// config partitions, at absolute offsets. The boot regions are absent.
|
||||
fn alkane_protected_map() -> Vec<Mtd> {
|
||||
vec![
|
||||
mtd("/dev/mtd0", 0x4800000, 0x800000), // stock-cfg (read-only)
|
||||
mtd("/dev/mtd1", 0x5000000, 0x100000), // alkane-cfg
|
||||
]
|
||||
}
|
||||
|
||||
fn images() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||
(vec![0xAA; 0x300000], vec![0xBB; 0x3000], vec![0xCC; 0x400000])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protected_alkane_map_yields_no_write_targets() {
|
||||
// On the current alkane layout the boot regions are not registered, so
|
||||
// nothing may be planned at all - in particular nothing on stock-cfg or
|
||||
// alkane-cfg (the old tier-2 path erased alkane-cfg here).
|
||||
let map = alkane_protected_map();
|
||||
assert!(!map_covers_boot_regions(&map));
|
||||
let (k, d, r) = images();
|
||||
assert!(alkane_targets(&map, k, d, r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_boot_regions_place_targets_on_the_stock_uboot_slots() {
|
||||
// Whole NAND registered as one device (as after re-registration).
|
||||
let map = vec![mtd("/dev/mtd2", 0x0, 0x8000000)];
|
||||
assert!(map_covers_boot_regions(&map));
|
||||
let (k, d, r) = images();
|
||||
let targets = alkane_targets(&map, k, d, r).unwrap();
|
||||
let names: Vec<_> = targets.iter().map(|t| t.name).collect();
|
||||
assert_eq!(names, ["rootfs", "dtb", "kernel"]);
|
||||
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
|
||||
assert_eq!((at("rootfs").rel, at("rootfs").absolute), (0x2800000, 0x2800000));
|
||||
assert_eq!((at("dtb").rel, at("dtb").absolute), (0x1A00000, 0x1A00000));
|
||||
assert_eq!((at("kernel").rel, at("kernel").absolute), (0x2000000, 0x2000000));
|
||||
for t in &targets {
|
||||
assert!(t.absolute >= BOOTBIN_PRESERVE);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_boot_partitions_resolve_relative_offsets() {
|
||||
// Boot regions registered as separate partitions: offsets become
|
||||
// partition-relative, absolute stays the NAND address.
|
||||
let map = vec![
|
||||
mtd("/dev/mtd2", 0x1A00000, 0x600000),
|
||||
mtd("/dev/mtd3", 0x2000000, 0x800000),
|
||||
mtd("/dev/mtd4", 0x2800000, 0x2000000),
|
||||
];
|
||||
let (k, d, r) = images();
|
||||
let targets = alkane_targets(&map, k, d, r).unwrap();
|
||||
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
|
||||
assert_eq!((at("dtb").device.as_str(), at("dtb").rel), ("/dev/mtd2", 0));
|
||||
assert_eq!((at("kernel").device.as_str(), at("kernel").rel), ("/dev/mtd3", 0));
|
||||
assert_eq!((at("rootfs").device.as_str(), at("rootfs").rel), ("/dev/mtd4", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_that_overruns_its_partition_is_refused() {
|
||||
// Rootfs slot (0x2000000) does not fit a 1 MiB partition at its offset.
|
||||
let map = vec![
|
||||
mtd("/dev/mtd2", 0x1A00000, 0x600000),
|
||||
mtd("/dev/mtd3", 0x2000000, 0x800000),
|
||||
mtd("/dev/mtd4", 0x2800000, 0x100000),
|
||||
];
|
||||
let (k, d, r) = images();
|
||||
assert!(alkane_targets(&map, k, d, r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_ever_placed_inside_bootbin() {
|
||||
let target = make_target(
|
||||
"x",
|
||||
"x.bin",
|
||||
"/dev/mtd2".to_string(),
|
||||
0x100000,
|
||||
0x100000,
|
||||
0x20000,
|
||||
Cow::Owned(vec![0u8; 16]),
|
||||
);
|
||||
assert!(target.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gzip_and_tar_are_well_formed() {
|
||||
let entries = vec![
|
||||
|
||||
+29
-4
@@ -68,13 +68,38 @@ verify the board came up as alkane:
|
||||
alkane-cli afw verify-live --host <miner-ip> --timeout 300
|
||||
```
|
||||
|
||||
On Zynq (S17/S19 class) pass the `.afw` (or `--board zynq-7010`) and the board's
|
||||
alkane root credential; the check needs the web page to carry the image marker
|
||||
and SSH to report alkane with the installed kernel, and prints the running kernel
|
||||
command line (on a NAND boot it is the board's U-Boot env bootargs):
|
||||
|
||||
```
|
||||
alkane-cli afw verify-live path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
|
||||
--host <miner-ip> --password-file <alkane-root-pw> --timeout 300
|
||||
```
|
||||
|
||||
For a bench image that is not signed, add `--allow-unsigned`.
|
||||
|
||||
Without `--from-stock`, `install` performs a tier-2 update of a board already on
|
||||
alkane: it writes the dtb (`/dev/mtd0 @ 0x1a00000`), the kernel
|
||||
(`/dev/mtd0 @ 0x2000000`) and the rootfs (`/dev/mtd1`), holds a backup of each,
|
||||
reads them back (md5), and never writes `/dev/mtd0` below `0x1a00000`
|
||||
(BOOT.bin/FSBL/FPGA/U-Boot are preserved).
|
||||
alkane, in place, over the network:
|
||||
|
||||
```
|
||||
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
|
||||
--host <miner-ip> --password-file <alkane-root-pw> --dry-run
|
||||
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
|
||||
--host <miner-ip> --password-file <alkane-root-pw> --confirm FLASH
|
||||
```
|
||||
|
||||
On Zynq (S17/S19 class) the update refuses a board that is not running alkane.
|
||||
Alkane does not expose the NAND boot regions to Linux (only the small
|
||||
`stock-cfg` and `alkane-cfg` partitions), so the toolkit re-registers them
|
||||
first, the same way a restore does. It saves each boot slot to `--backup-dir`
|
||||
(default: the toolkit's `backups` directory) before any erase, then writes the
|
||||
rootfs (absolute NAND `0x2800000`), dtb (`0x1a00000`) and kernel (`0x2000000`),
|
||||
with the kernel and rootfs wrapped as the legacy uImages the board's stock
|
||||
U-Boot boots, and reads each back (md5) before rebooting. Nothing below
|
||||
`0x1a00000` (BOOT.bin: FSBL, FPGA bitstream, U-Boot) is ever written.
|
||||
`afw preflight` runs the same checks read-only. `--no-reboot` skips the reboot.
|
||||
|
||||
## Remove (back to stock)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user