Install AM335x mtd7/mtd8 over SSH with held backups

This commit is contained in:
2026-11-04 17:03:14 -06:00
parent 628c0630a5
commit 4d1adeb05e
7 changed files with 2026 additions and 21 deletions
+21 -1
View File
@@ -47,13 +47,20 @@ and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md).
Discovery is read-only. Control and restore actions change miners. Check the
selected devices before applying them.
## Headless .afw install (CV1835)
## Headless .afw install (CV1835 and AM335x)
`alkane-cli` is the headless engine; the GUI uses the same engine. A verified
`.afw` is a full OS bundle for exactly one board. The CV1835 installer writes
only `/dev/mmcblk0p1` over SSH, holds the current p1 first, reads the whole
partition back, and reboots only after the read-back matches.
The AM335x installer writes mtd8 (type-3 ramdisk), mtd6 (dtb) and mtd7
(legacy kernel uImage) with `flash_erase` + `nandwrite`. It never touches
mtd0-5 (SPL/U-Boot/bootenv), holds a backup of each target before writing it,
and reads every target back before reboot. Its `verify-live` checks SSH
(kernel string), the HTTP marker on port 80, the API on port 4028, and the
eth0 DHCP lease.
```sh
alkane-cli afw verify BUNDLE.afw --allow-unsigned
alkane-cli afw plan BUNDLE.afw --host 10.255.1.167
@@ -64,6 +71,19 @@ alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.167
alkane-cli afw restore --host 10.255.1.167 --held-backup p1.img --confirm FLASH
```
For AM335x the same subcommands infer the board from the bundle; restore names
the three held copies explicitly:
```sh
alkane-cli afw plan BUNDLE.afw --host 10.255.1.64
alkane-cli afw preflight BUNDLE.afw --host 10.255.1.64
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --dry-run
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --confirm FLASH
alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.64 --timeout 300
alkane-cli afw restore --board am335x --host 10.255.1.64 \
--held-backup mtd8.img --held-kernel mtd7.img --held-dtb mtd6.img --confirm FLASH
```
On stock Bitmain CV1835 the SSH login is the unprivileged `miner` account; the
toolkit obtains root through the stock update-daemon loopback channel, not a
serial console. Credentials come only from `ALKANE_BOARD_PASSWORD` or
+123 -1
View File
@@ -18,6 +18,28 @@ pub const BLOCK: usize = 512;
pub const MAX_ARCHIVE: usize = 512 * 1024 * 1024;
pub const MAX_MANIFEST: usize = 64 * 1024;
pub const CV1835_P1_SIZE: u64 = 16 * 1024 * 1024;
pub const AM335X_HOLE_OFFSET: u64 = 0x780000;
pub const AM335X_HOLE_SIZE: u64 = 0x80000;
pub const AM335X_CHIP_SIZE: u64 = 0x8000000;
const AM335X_MAP: &[(&str, u64, u64, bool, bool, i64, Option<&str>)] = &[
("mtd0", 0x0000000, 0x20000, true, true, 0, None),
("mtd1", 0x0020000, 0x20000, true, true, 0, None),
("mtd2", 0x0040000, 0x20000, true, true, 0, None),
("mtd3", 0x0060000, 0x20000, true, true, 0, None),
("mtd4", 0x0080000, 0x1C0000, true, true, 0, None),
("mtd5", 0x0240000, 0x20000, true, true, 0, None),
("mtd6", 0x0260000, 0x20000, false, true, 2, Some("dtb")),
("mtd7", 0x0280000, 0x500000, false, true, 3, Some("kernel")),
("mtd8", 0x0800000, 0x1400000, false, true, 1, Some("rootfs")),
("mtd9", 0x1C00000, 0x200000, true, false, 0, None),
("mtd10", 0x1E00000, 0x200000, true, false, 0, None),
("mtd11", 0x2000000, 0x6000000, true, false, 0, None),
];
const AM335X_CEILINGS: &[(&str, u64, &str)] = &[
("kernel", 0x500000, "mtd7"),
("dtb", 0x20000, "mtd6"),
("rootfs", 0x1400000, "mtd8"),
];
const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"];
const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "fdt", "cpio-gzip", "uimage", "raw"];
@@ -48,11 +70,12 @@ pub struct BoardProfile {
/// in this table is refused rather than treated as generic.
pub fn board_profile(board: &str) -> Option<BoardProfile> {
let (arch, bootloader_policy) = match board {
"am335x" => ("arm", BootloaderPolicy::Preserve),
"cv1835" => ("arm64", BootloaderPolicy::Preserve),
"zynq-7010" => ("armv7", BootloaderPolicy::Preserve),
"a113d" => ("armv7", BootloaderPolicy::Preserve),
"a113d-s21pro" => ("armv7", BootloaderPolicy::Preserve),
"am335x-bb" => ("armv7", BootloaderPolicy::Include),
"am335x-bb" => ("armv7", BootloaderPolicy::Preserve),
"zynq-s17" => ("armv7", BootloaderPolicy::Include),
_ => return None,
};
@@ -509,6 +532,10 @@ fn validate_manifest(manifest: &AfwManifest, options: &VerifyOptions) -> Result<
}
}
if manifest.board == "am335x" {
validate_am335x(manifest)?;
}
let has_bootloader = manifest
.images
.iter()
@@ -564,6 +591,101 @@ fn validate_manifest(manifest: &AfwManifest, options: &VerifyOptions) -> Result<
Ok(())
}
fn validate_am335x(manifest: &AfwManifest) -> Result<(), AfwError> {
for image in &manifest.images {
let lowered = format!("{} {}", image.name, image.file).to_lowercase();
if lowered.contains("spl") || lowered.contains("u-boot") || lowered.contains("uboot") {
return Err(AfwError::Manifest(format!(
"am335x bundle carries an spl/u-boot member: {}",
image.file
)));
}
}
let install: Vec<&AfwImage> = manifest.images.iter().filter(|image| image.install).collect();
if install.len() != 3 {
return Err(AfwError::Manifest(
"am335x must install exactly kernel, dtb and rootfs".to_owned(),
));
}
for (name, ceiling, partition) in AM335X_CEILINGS {
let Some(image) = manifest.images.iter().find(|image| image.name == *name) else {
return Err(AfwError::Manifest(format!("am335x is missing {name}")));
};
let expected_format = if *name == "dtb" { "fdt" } else { "uimage" };
if !image.install
|| image.format != expected_format
|| image.partition.as_deref() != Some(*partition)
{
return Err(AfwError::Manifest(format!(
"am335x {name} must be an installing {expected_format} for {partition}"
)));
}
if image.size > *ceiling {
return Err(AfwError::ImageTooLarge(image.name.clone()));
}
}
if manifest.partitions.len() != AM335X_MAP.len() {
return Err(AfwError::Manifest(
"am335x must plan all 12 mtd partitions".to_owned(),
));
}
for (name, offset, size, secure, boot_critical, write_order, image) in AM335X_MAP {
let Some(partition) = manifest.partitions.iter().find(|part| part.name == *name) else {
return Err(AfwError::Manifest(format!("am335x is missing {name}")));
};
if partition.offset != *offset
|| partition.size != *size
|| partition.secure != *secure
|| partition.boot_critical != *boot_critical
|| partition.write_order != *write_order
|| partition.image.as_deref() != *image
|| partition.device != format!("/dev/{name}")
{
return Err(AfwError::Manifest(format!(
"am335x {name} geometry is wrong"
)));
}
if partition.offset < AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE
&& partition.offset + partition.size > AM335X_HOLE_OFFSET
{
return Err(AfwError::Manifest(format!(
"am335x {name} overlaps the 0x780000-0x800000 hole"
)));
}
if (name.starts_with("mtd0") || ["mtd1", "mtd2", "mtd3", "mtd4", "mtd5"].contains(name))
&& (partition.write_order != 0 || partition.image.is_some())
{
return Err(AfwError::Manifest(format!(
"am335x {name} is preserved and must not be written"
)));
}
}
let mtd7 = manifest
.partitions
.iter()
.find(|part| part.name == "mtd7")
.unwrap();
let mtd8 = manifest
.partitions
.iter()
.find(|part| part.name == "mtd8")
.unwrap();
if mtd7.offset + mtd7.size != AM335X_HOLE_OFFSET
|| mtd8.offset != AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE
{
return Err(AfwError::Manifest(
"am335x mtd7 must end at the 0x780000 hole and mtd8 start at 0x800000".to_owned(),
));
}
let total: u64 = manifest.partitions.iter().map(|part| part.size).sum();
if total != AM335X_CHIP_SIZE - AM335X_HOLE_SIZE {
return Err(AfwError::Manifest(
"am335x partition sizes must sum to 0x7F80000".to_owned(),
));
}
Ok(())
}
fn check_image_format(
manifest: &AfwManifest,
image: &AfwImage,
+201 -16
View File
@@ -8,6 +8,9 @@
use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions};
use alkane_artifacts::{seed_manifest, verify_file};
use alkane_core::platform;
use alkane_flash::boards::am335x::{
self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions,
};
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
@@ -313,6 +316,34 @@ fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.first()
.ok_or("usage: alkane-cli afw plan <file> --host <ip>")?;
let verified = load_afw(path, &opts)?;
if verified.manifest.board == "am335x" {
let plan = Am335xPlan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let kernel =
String::from_utf8_lossy(&transport.user_command("uname -r", Duration::from_secs(15))?)
.trim()
.to_owned();
let uid =
String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?)
.trim()
.to_owned();
let mtd = String::from_utf8_lossy(&transport.user_command(
"cat /proc/mtd 2>/dev/null",
Duration::from_secs(15),
)?)
.into_owned();
println!("{}", plan.render());
println!("current kernel {kernel} uid {uid}");
println!("board mtd table:\n{mtd}");
println!(
"root channel {} (transport {}, never serial)",
transport.root_method(),
transport.channel()
);
println!("plan is read-only; no write performed");
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
@@ -357,9 +388,18 @@ 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)?;
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
if verified.manifest.board == "am335x" {
let plan = Am335xPlan::from_afw(&verified)?;
let report = am335x::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(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let held_backup = opts.value("held-backup").map(PathBuf::from);
let report = preflight(
&plan,
@@ -399,13 +439,57 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.first()
.ok_or("usage: alkane-cli afw install <file> --host <ip> --dry-run|--confirm FLASH")?;
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let backup_dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
if verified.manifest.board == "am335x" {
let plan = Am335xPlan::from_afw(&verified)?;
let install_options = AmInstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
println!("{}", plan.render());
match am335x::install(
&plan,
&mut transport,
&install_options,
opts.value("host").unwrap_or(""),
)? {
AmInstallOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no board erase or write was performed.");
println!("Re-run with --confirm FLASH to write mtd8, mtd6 and mtd7.");
}
AmInstallOutcome::Installed(receipt) => {
for backup in &receipt.backups {
println!(
"held {} {} md5 {} sha256 {}",
backup.partition,
backup.path.display(),
backup.md5,
backup.sha256
);
}
println!("all three mtd read-backs matched before reboot");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
println!(
"next: alkane-cli afw verify-live --host {} --timeout 300",
opts.value("host").unwrap_or("")
);
} else {
println!("reboot skipped (--no-reboot); verify-live will fail until the board reboots");
}
}
}
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let install_options = InstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
@@ -455,26 +539,52 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
args,
&[
ssh_values(),
&["marker", "kernel-version", "timeout", "expect-board"],
&["marker", "kernel-version", "timeout", "expect-board", "board"],
]
.concat(),
&["allow-unsigned"],
)?;
let (marker, kernel_version) = if let Some(path) = opts.positionals.first() {
let requested_board = opts.value("board").map(str::to_owned);
let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() {
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
(
opts.value("marker").unwrap_or(&plan.marker).to_owned(),
opts.value("kernel-version")
.unwrap_or(&plan.kernel_version)
.to_owned(),
)
let board = verified.manifest.board.clone();
if board == "am335x" {
let plan = Am335xPlan::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 {
let plan = Cv1835Plan::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 {
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 {
("CVBOOT".to_owned(), String::new())
};
(
opts.value("marker").unwrap_or("CVBOOT").to_owned(),
opts.value("kernel-version").unwrap_or("").to_owned(),
board,
opts.value("marker").unwrap_or(&marker).to_owned(),
opts.value("kernel-version").unwrap_or(&kernel).to_owned(),
)
};
if let Some(expected) = &requested_board {
if expected != &board {
return Err(format!("bundle is for {board}, expected {expected}").into());
}
}
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let timeout = opts
@@ -482,6 +592,20 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.map(str::parse::<u64>)
.transpose()?
.unwrap_or(DEFAULT_TIMEOUT);
if board == "am335x" {
let report = am335x::verify_live(
&host,
&marker,
&kernel_version,
Duration::from_secs(timeout),
&ssh,
);
print!("{}", report.render());
if !report.ok() {
return Err("live verification failed: SSH, HTTP marker, API or DHCP disagreed".into());
}
return Ok(());
}
let report = verify_live(
&host,
&marker,
@@ -500,11 +624,54 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
fn run_restore(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["held-backup", "backup-dir", "confirm"]].concat(),
&[
ssh_values(),
&["held-backup", "backup-dir", "confirm", "board", "held-kernel", "held-dtb"],
]
.concat(),
&["no-reboot"],
)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
if opts.value("board") == Some("am335x") {
let dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
let mut backups: Vec<(String, PathBuf)> = Vec::new();
for (name, value, prefix) in [
("mtd8", opts.value("held-backup"), "mtd8-"),
("mtd7", opts.value("held-kernel"), "mtd7-"),
("mtd6", opts.value("held-dtb"), "mtd6-"),
] {
let path = match value {
Some(path) => PathBuf::from(path),
None => latest_backup_for(&dir, prefix).ok_or_else(|| {
format!(
"no held {name} backup in {}; pass the matching --held-* option",
dir.display()
)
})?,
};
backups.push((name.to_owned(), path));
}
let receipt = am335x::restore(
&backups,
&mut transport,
&AmRestoreOptions {
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
},
)?;
for (name, path) in &receipt.restored {
println!("restored {name} from {}", path.display());
}
println!("all mtd read-backs matched before reboot");
if receipt.rebooted {
println!("reboot issued; the board should return to its held OS");
}
return Ok(());
}
let backup = if let Some(path) = opts.value("held-backup") {
PathBuf::from(path)
} else {
@@ -536,6 +703,23 @@ fn run_restore(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn latest_backup_for(dir: &Path, prefix: &str) -> Option<PathBuf> {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)
.ok()?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.extension() == Some(std::ffi::OsStr::new("img"))
&& path
.file_name()
.map(|name| name.to_string_lossy().starts_with(prefix))
.unwrap_or(false)
})
.collect();
entries.sort();
entries.pop()
}
fn latest_backup(dir: &Path) -> Option<PathBuf> {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)
.ok()?
@@ -604,8 +788,9 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
alkane-cli afw preflight <file> --host <ip> [ssh options] [--held-backup <p1.img>]\n \
alkane-cli afw install <file> --host <ip> --dry-run [ssh options]\n \
alkane-cli afw install <file> --host <ip> --confirm FLASH [ssh options]\n \
alkane-cli afw verify-live [<file>] --host <ip> [--timeout <secs>] [ssh options]\n \
alkane-cli afw restore --host <ip> --held-backup <p1.img> --confirm FLASH [ssh options]\n\
alkane-cli afw verify-live [<file>] --host <ip> [--board <board>] [--timeout <secs>] [ssh options]\n \
alkane-cli afw restore --host <ip> --held-backup <p1.img> --confirm FLASH [ssh options]\n \
alkane-cli afw restore --board am335x --host <ip> --held-backup <mtd8.img> \\\n --held-kernel <mtd7.img> --held-dtb <mtd6.img> --confirm FLASH [ssh options]\n\
\nssh options: --user --port --identity-file --password-file --known-hosts \
--root-method auto|direct|update-daemon|rroot --update-daemon-port\n\
credentials: ALKANE_BOARD_PASSWORD or ALKANE_BOARD_PASSWORD_FILE; \
File diff suppressed because it is too large Load Diff
+1
View File
@@ -2,4 +2,5 @@
//! Board modules. Each module validates the verified manifest for its family
//! and exposes the exact write plan the installer follows.
pub mod am335x;
pub mod cv1835;
+2 -2
View File
@@ -480,7 +480,7 @@ pub fn verify_live(
}
}
fn http_get(host: &str, path: &str, timeout: Duration) -> Result<String, String> {
pub(crate) fn http_get(host: &str, path: &str, timeout: Duration) -> Result<String, String> {
let address = (host, 80_u16)
.to_socket_addrs()
.map_err(|error| format!("resolve: {error}"))?
@@ -524,7 +524,7 @@ fn http_get(host: &str, path: &str, timeout: Duration) -> Result<String, String>
}
}
fn api_version(host: &str, timeout: Duration) -> Result<String, String> {
pub(crate) fn api_version(host: &str, timeout: Duration) -> Result<String, String> {
let address = (host, 4028_u16)
.to_socket_addrs()
.map_err(|error| format!("resolve: {error}"))?
+1 -1
View File
@@ -341,7 +341,7 @@ pub fn preflight(
})
}
fn classify(kernel: &str, release: &str, all: &str) -> String {
pub(crate) fn classify(kernel: &str, release: &str, all: &str) -> String {
if all.contains("/etc/bos_version") || release.contains("Braiins") {
return "braiins".to_owned();
}