Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4305da5e57 | ||
|
|
dc787f1f3b | ||
|
|
f63127d633 | ||
|
|
b02a14bcfc | ||
|
|
20dff12c05 | ||
|
|
ac6bc20c68 | ||
|
|
8f0accf21d | ||
|
|
69c5023f1e | ||
|
|
b242e34ca0 | ||
|
|
82492231bc | ||
|
|
27e1dc15e8 | ||
|
|
086c883c4a | ||
|
|
4324d3046e | ||
|
|
de5c1a5a15 | ||
|
|
d22ee79159 | ||
|
|
75b7424a0d | ||
|
|
8d4fe502be | ||
|
|
038c1b1c2b | ||
|
|
20d7f49c9d | ||
|
|
74cee50d35 | ||
|
|
32a75c92ef | ||
|
|
f4d9c12bb6 | ||
|
|
b610ce3d7f | ||
|
|
1a5dcd17a9 | ||
|
|
3b1b1fa63e | ||
|
|
7880b14e47 | ||
|
|
5bbf5b71b7 | ||
|
|
cfec9606a4 | ||
|
|
e8d7cdc77a | ||
|
|
8ba585679a | ||
|
|
ea102130ac | ||
|
|
e656402ec8 | ||
|
|
80f3c22582 | ||
|
|
a79ac3e09e | ||
|
|
6580005e77 | ||
|
|
2734c8e356 | ||
|
|
0c2897ce37 | ||
|
|
fbc903fa6a | ||
|
|
fe9617ab56 | ||
|
|
1e9e4f16b5 | ||
|
|
6a6a5e7ded | ||
|
|
e20b6890d3 | ||
|
|
17bee91248 | ||
|
|
63d0de8ae3 | ||
|
|
9a8efc807a | ||
|
|
9879a0eb25 | ||
|
|
03c19ef7c6 | ||
|
|
2540801140 | ||
|
|
dd28fa233c | ||
|
|
e5ca519df0 | ||
|
|
06c8e01eb5 | ||
|
|
990439985d | ||
|
|
54136b71ef | ||
|
|
5d18304f0f | ||
|
|
8bbf844bb6 | ||
|
|
97607a0a91 |
@@ -0,0 +1,36 @@
|
||||
name: public-benchmark-pages
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/15 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-public-benchmark-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install SSH client
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends openssh-client
|
||||
- name: Render measured benchmark history
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Publish public benchmark page
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
|
||||
run: python3 ci/publish-bench-pages.py toolkit
|
||||
- name: Clean generated page
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -22,6 +22,7 @@ jobs:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
|
||||
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -94,6 +95,7 @@ jobs:
|
||||
CARGO_BUILD_JOBS: 2
|
||||
WX_PREFIX: /root/.cache/wx-3.3.3-linux
|
||||
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
|
||||
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -28,6 +28,9 @@ jobs:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
|
||||
# Read-only token baked into the GUI so the release picker can list the
|
||||
# private alkane-os releases with no user setup (option_env!).
|
||||
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout (full history for tags)
|
||||
uses: actions/checkout@v4
|
||||
@@ -136,6 +139,9 @@ jobs:
|
||||
# Set once for the whole job so build/clippy/test/bench steps don't each
|
||||
# re-export it (round 18 #12).
|
||||
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
|
||||
# Read-only token baked into the GUI so the release picker can list the
|
||||
# private alkane-os releases with no user setup (option_env!).
|
||||
ALKANE_EMBEDDED_TOKEN: ${{ secrets.ALKANE_EMBEDDED_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout (full history for tags)
|
||||
uses: actions/checkout@v4
|
||||
|
||||
Generated
+2
@@ -89,8 +89,10 @@ name = "alkane-gui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"alkane-artifacts",
|
||||
"alkane-core",
|
||||
"alkane-discovery",
|
||||
"alkane-flash",
|
||||
"asic-rs",
|
||||
"base64 0.21.7",
|
||||
"ecb",
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish a measured benchmark page to the public, data-only Pages repo."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
|
||||
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
|
||||
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
|
||||
PAGES_HOST = "gitea.bluefla.re"
|
||||
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
|
||||
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
|
||||
|
||||
|
||||
def run(*args: str, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=True)
|
||||
|
||||
|
||||
def current_main_sha() -> str:
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
branch = json.load(response)
|
||||
return branch["commit"]["id"]
|
||||
|
||||
|
||||
def publish(site: str) -> None:
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
raise ValueError("benchmark Pages publication requires main")
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
page = Path("bench-site/index.html").read_bytes()
|
||||
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
|
||||
raise ValueError("invalid benchmark page")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
temporary = Path(directory)
|
||||
guard_checkout = temporary / "guard"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
|
||||
GUARD_REPO, str(guard_checkout))
|
||||
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
|
||||
cwd=guard_checkout).stdout
|
||||
guard_script = temporary / "validate_site.py"
|
||||
guard_script.write_text(guard_source)
|
||||
run("python3", str(guard_script), "--page", site,
|
||||
str(Path("bench-site/index.html").resolve()))
|
||||
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
|
||||
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
|
||||
raise ValueError("missing benchmark Pages deploy key")
|
||||
key_path = temporary / "deploy_key"
|
||||
key_path.write_text(key.rstrip("\n") + "\n")
|
||||
key_path.chmod(0o600)
|
||||
known_hosts = temporary / "known_hosts"
|
||||
known_hosts.write_text(PAGES_HOST_KEY + "\n")
|
||||
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
|
||||
if fingerprint != PAGES_HOST_FINGERPRINT:
|
||||
raise ValueError("benchmark Pages SSH host key changed")
|
||||
git_env = os.environ.copy()
|
||||
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
|
||||
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
|
||||
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
|
||||
git_env["GIT_SSH_COMMAND"] = ssh_command
|
||||
git_env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
checkout = temporary / "site"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
|
||||
PAGES_REPO, str(checkout), env=git_env)
|
||||
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
|
||||
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
|
||||
for attempt in range(3):
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
|
||||
cwd=checkout)
|
||||
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
|
||||
cwd=checkout)
|
||||
destination = checkout / site / "index.html"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
destination.write_bytes(page)
|
||||
run("git", "add", f"{site}/index.html", cwd=checkout)
|
||||
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
|
||||
cwd=checkout, check=False)
|
||||
if changed.returncode == 0:
|
||||
print(f"{site} benchmark page is already current")
|
||||
return
|
||||
if changed.returncode != 1:
|
||||
raise RuntimeError("cannot compare benchmark page")
|
||||
run("git", "commit", "-q", "-m",
|
||||
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
|
||||
pushed = subprocess.run(("git", "push", "--quiet", "origin",
|
||||
"HEAD:gh-pages"), env=git_env, cwd=checkout,
|
||||
text=True, capture_output=True, check=False)
|
||||
if pushed.returncode == 0:
|
||||
print(f"Published {site} benchmark page for {sha[:10]}")
|
||||
return
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
|
||||
raise RuntimeError("benchmark Pages publication did not complete")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
|
||||
publish(parser.parse_args().site)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -21,6 +21,7 @@ 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;
|
||||
#[allow(clippy::type_complexity)]
|
||||
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),
|
||||
|
||||
@@ -10,7 +10,15 @@
|
||||
//!
|
||||
//! A private repo needs a token; it is read from the environment at run time
|
||||
//! (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`) and passed to curl through a
|
||||
//! 0600 config file, never on the command line. No token is embedded or stored.
|
||||
//! 0600 config file, never on the command line.
|
||||
//!
|
||||
//! As a convenience for the GUI, a read-only token can be baked into the binary
|
||||
//! at build time by compiling with `ALKANE_EMBEDDED_TOKEN=<token>` set (see
|
||||
//! `EMBEDDED_TOKEN`). The source tree carries no secret - the value lives only in
|
||||
//! a binary built with that variable set - and the environment variables above
|
||||
//! always take precedence, so a user can override it. When no such token is baked
|
||||
//! in and none is in the environment, the token is simply absent (fine for public
|
||||
//! repos; a private repo then returns 401/404).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -19,6 +27,14 @@ use std::process::Command;
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
/// A read-only Gitea token baked in at build time when the crate is compiled
|
||||
/// with `ALKANE_EMBEDDED_TOKEN` set. `None` in an ordinary build (no secret in
|
||||
/// the source tree). The environment variables win over this, so it is only a
|
||||
/// fallback for a distributed binary (the GUI) that ships without asking the user
|
||||
/// to configure a token. Scope it read-only on the server side; anyone with the
|
||||
/// binary can extract it.
|
||||
const EMBEDDED_TOKEN: Option<&str> = option_env!("ALKANE_EMBEDDED_TOKEN");
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum FetchError {
|
||||
#[error("curl failed: {0}")]
|
||||
@@ -51,7 +67,8 @@ impl ReleaseSource {
|
||||
let token = std::env::var("ALKANE_RELEASE_TOKEN")
|
||||
.ok()
|
||||
.or_else(|| std::env::var("GITEA_TOKEN").ok())
|
||||
.filter(|t| !t.is_empty());
|
||||
.filter(|t| !t.is_empty())
|
||||
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()));
|
||||
Self {
|
||||
base_url,
|
||||
owner: "blueflare".to_string(),
|
||||
@@ -193,6 +210,101 @@ pub fn fetch_latest_afw(src: &ReleaseSource, board: &str, dest_dir: &Path) -> Re
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
/// One `.afw` asset in a release.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AfwAsset {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// A release as listed for the GUI's release picker: its tag/name, whether it is
|
||||
/// a pre-release or draft, when it was published, and the `.afw` assets it holds.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReleaseInfo {
|
||||
pub tag: String,
|
||||
pub name: String,
|
||||
pub prerelease: bool,
|
||||
pub draft: bool,
|
||||
pub published_at: String,
|
||||
pub afw_assets: Vec<AfwAsset>,
|
||||
}
|
||||
|
||||
impl ReleaseInfo {
|
||||
/// The `.afw` asset for `board` in this release, if any (matched by the
|
||||
/// `-<board>-` segment of the filename, as `pick_asset` does).
|
||||
pub fn asset_for_board(&self, board: &str) -> Option<&AfwAsset> {
|
||||
let needle = format!("-{board}-");
|
||||
self.afw_assets.iter().find(|a| a.name.contains(&needle))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only
|
||||
/// the `.afw` assets of each. Drafts are included so the caller can decide.
|
||||
fn parse_releases(releases: &Value) -> Vec<ReleaseInfo> {
|
||||
let mut out = Vec::new();
|
||||
let Some(arr) = releases.as_array() else {
|
||||
return out;
|
||||
};
|
||||
for release in arr {
|
||||
let tag = release.get("tag_name").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let name = release.get("name").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let prerelease = release.get("prerelease").and_then(Value::as_bool).unwrap_or(false);
|
||||
let draft = release.get("draft").and_then(Value::as_bool).unwrap_or(false);
|
||||
let published_at = release
|
||||
.get("published_at")
|
||||
.or_else(|| release.get("created_at"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let mut afw_assets = Vec::new();
|
||||
if let Some(assets) = release.get("assets").and_then(Value::as_array) {
|
||||
for asset in assets {
|
||||
let aname = asset.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
if aname.ends_with(".afw") {
|
||||
if let Some(url) = asset.get("browser_download_url").and_then(Value::as_str) {
|
||||
afw_assets.push(AfwAsset {
|
||||
name: aname.to_string(),
|
||||
url: url.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(ReleaseInfo {
|
||||
tag,
|
||||
name,
|
||||
prerelease,
|
||||
draft,
|
||||
published_at,
|
||||
afw_assets,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// List the releases (newest first) of the source repo, each with its `.afw`
|
||||
/// assets. Used by the GUI to scan alkane-os releases and pick one to install.
|
||||
pub fn list_releases(src: &ReleaseSource) -> Result<Vec<ReleaseInfo>, FetchError> {
|
||||
let body = curl_bytes(src, &src.api_list())?;
|
||||
let releases: Value =
|
||||
serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
|
||||
Ok(parse_releases(&releases))
|
||||
}
|
||||
|
||||
/// Download a specific release asset (by its `browser_download_url`) into
|
||||
/// `dest_dir`, saving it under `name`; returns the written path.
|
||||
pub fn fetch_afw_url(
|
||||
src: &ReleaseSource,
|
||||
name: &str,
|
||||
url: &str,
|
||||
dest_dir: &Path,
|
||||
) -> Result<PathBuf, FetchError> {
|
||||
fs::create_dir_all(dest_dir).map_err(|e| FetchError::Io(e.to_string()))?;
|
||||
let dest = dest_dir.join(name);
|
||||
curl_download(src, url, &dest)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -223,4 +335,36 @@ mod tests {
|
||||
assert_eq!(pick_asset(&releases, "zynq-7010"), Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into())));
|
||||
assert_eq!(pick_asset(&releases, "cv1835"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_parses_releases_and_filters_afw_assets() {
|
||||
let releases = serde_json::json!([
|
||||
{"tag_name": "v0.2.0-bench1", "name": "bench", "prerelease": true, "draft": false,
|
||||
"published_at": "2026-11-11T10:00:00Z", "assets": [
|
||||
{"name": "SHA256SUMS", "browser_download_url": "s"},
|
||||
{"name": "alkane-os-0.2.0-zynq-7010-armv7.afw", "browser_download_url": "z"},
|
||||
]},
|
||||
{"tag_name": "v0.1.0", "name": "", "prerelease": false, "draft": false,
|
||||
"published_at": "2026-10-01T00:00:00Z", "assets": [
|
||||
{"name": "alkane-os-0.1.0-am335x-arm.afw", "browser_download_url": "a"},
|
||||
]},
|
||||
]);
|
||||
let parsed = parse_releases(&releases);
|
||||
assert_eq!(parsed.len(), 2);
|
||||
// Newest first; only .afw assets kept; SHA256SUMS dropped.
|
||||
assert_eq!(parsed[0].tag, "v0.2.0-bench1");
|
||||
assert!(parsed[0].prerelease);
|
||||
assert_eq!(parsed[0].afw_assets.len(), 1);
|
||||
// The board filter matches the -<board>- segment.
|
||||
assert_eq!(
|
||||
parsed[0].asset_for_board("zynq-7010").map(|a| a.url.as_str()),
|
||||
Some("z")
|
||||
);
|
||||
assert!(parsed[0].asset_for_board("am335x").is_none());
|
||||
assert_eq!(
|
||||
parsed[1].asset_for_board("am335x").map(|a| a.name.as_str()),
|
||||
Some("alkane-os-0.1.0-am335x-arm.afw")
|
||||
);
|
||||
assert!(parsed[1].asset_for_board("zynq-7010").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+163
-62
@@ -14,7 +14,9 @@ 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::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::{
|
||||
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
|
||||
@@ -420,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) {
|
||||
@@ -431,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(""))?;
|
||||
@@ -468,7 +483,62 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Install onto a board currently on stock via the sealed from-stock method.
|
||||
/// 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,
|
||||
host: &str,
|
||||
@@ -477,7 +547,7 @@ fn install_from_stock_flow(
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if opts.flag("dry-run") {
|
||||
println!(
|
||||
"DRY RUN: would install {} onto stock board {host} via the sealed from-stock method ({})",
|
||||
"DRY RUN: would install {} onto stock board {host} via the from-stock install method ({})",
|
||||
verified.manifest.board,
|
||||
afw.display()
|
||||
);
|
||||
@@ -496,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,
|
||||
@@ -528,13 +610,16 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// A board on stock: the first install goes through the sealed from-stock
|
||||
// A board on stock: the first install goes through the from-stock install
|
||||
// method; the tier-2 partition-write path below is for a board already on
|
||||
// alkane.
|
||||
if opts.flag("from-stock") {
|
||||
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
|
||||
@@ -591,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());
|
||||
@@ -720,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,
|
||||
@@ -743,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())
|
||||
};
|
||||
@@ -758,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,
|
||||
@@ -976,26 +1056,47 @@ fn resolve_afw_source(opts: &Opts) -> Result<PathBuf, Box<dyn std::error::Error>
|
||||
.ok_or_else(|| "usage: alkane-cli afw install <file>|--latest --host <ip> --confirm FLASH".into())
|
||||
}
|
||||
|
||||
/// Return an alkane board to genuine stock via the sealed stock-restore method,
|
||||
/// then leave the independent verification to the operator/bench.
|
||||
/// Return an alkane board to genuine Bitmain stock by writing the stock images
|
||||
/// from a genuine vendor firmware package back to NAND, over the network.
|
||||
fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?;
|
||||
let host = opts.value("host").ok_or("--host is required")?;
|
||||
// Restore runs over the network against the alkane board, so it needs the
|
||||
// board's root credential; it is passed to the compiled-in method in-process.
|
||||
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 <genuine Bitmain firmware file> is required \
|
||||
(an OTA update .tar.gz or an SD recovery .zip for this board)",
|
||||
)?;
|
||||
// Restore reaches the alkane board over SSH as root; the board credential is
|
||||
// supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE).
|
||||
let password = read_board_password(&opts)?;
|
||||
|
||||
// Parse the genuine vendor package for the stock kernel + rootfs. The kernel
|
||||
// device tree is not in distributable Bitmain firmware; the toolkit supplies
|
||||
// the correct per-board dtb, so any genuine package (OTA or SD) works here.
|
||||
let fw = stock_firmware::parse(Path::new(firmware))?;
|
||||
println!("stock firmware: {}", fw.summary());
|
||||
|
||||
if opts.flag("dry-run") {
|
||||
println!("DRY RUN: would restore {host} to stock via the network-only restore-to-stock method");
|
||||
println!("DRY RUN: would restore {host} to stock by writing the genuine stock kernel");
|
||||
println!("and rootfs plus the per-board device tree back to NAND (BOOT.bin preserved).");
|
||||
println!("Re-run with --confirm FLASH.");
|
||||
return Ok(());
|
||||
}
|
||||
if opts.value("confirm") != Some("FLASH") {
|
||||
return Err("refusing to restore without --confirm FLASH".into());
|
||||
}
|
||||
println!("restoring {host} to stock (network-only method)...");
|
||||
stock::restore_to_stock(host, password.as_deref())?;
|
||||
println!("restore-to-stock reported success.");
|
||||
println!("verify independently: the board should no longer answer as alkane (no alkane console/API),");
|
||||
println!("and should present its genuine stock OS. Confirm over the network or serial before reuse.");
|
||||
println!("restoring {host} to genuine stock from {firmware} (network-only)...");
|
||||
let images = RestoreImages {
|
||||
kernel: &fw.kernel,
|
||||
rootfs: &fw.rootfs,
|
||||
};
|
||||
stock::restore_to_stock(&host, &images, password.as_deref())?;
|
||||
println!("restore-to-stock reported success (stock images written, BOOT.bin preserved).");
|
||||
println!("verify independently: the board should no longer answer as alkane and should");
|
||||
println!("present genuine stock (lighttpd 401 on :80, TCP 22 closed).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
//! never changes the bootloader: the brick-sensitive regions are physically
|
||||
//! unreachable.
|
||||
//!
|
||||
//! The first from-stock install (via the vendor toolkit, past the signed
|
||||
//! bootloader) is the dsh-owned path and is NOT this module. This is the
|
||||
//! repeatable alkane-to-alkane update.
|
||||
//! The first from-stock install (past the signed bootloader) is handled
|
||||
//! elsewhere and is NOT this module. This is the repeatable alkane-to-alkane
|
||||
//! update.
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
use crate::preflight::{classify, parse_digest};
|
||||
@@ -193,6 +193,9 @@ impl A113dPlan {
|
||||
.image(image_name)
|
||||
.map(|(_, data)| data)
|
||||
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
|
||||
// Each arm validates a different magic; keeping them as explicit
|
||||
// arms (not match guards) reads more clearly than collapsing.
|
||||
#[allow(clippy::collapsible_match)]
|
||||
match expected_format {
|
||||
"arm64-image" => {
|
||||
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
|
||||
|
||||
@@ -961,9 +961,8 @@ pub fn install(
|
||||
}
|
||||
|
||||
fn restore_hint(backups: &[AmBackup], failed: &str) -> String {
|
||||
let mut text = format!(
|
||||
"alkane-cli afw restore --board am335x --host <ip> --held-backup <mtd8.img>"
|
||||
);
|
||||
let mut text =
|
||||
"alkane-cli afw restore --board am335x --host <ip> --held-backup <mtd8.img>".to_string();
|
||||
for backup in backups {
|
||||
let flag = match backup.partition.as_str() {
|
||||
"mtd8" => "--held-backup",
|
||||
|
||||
@@ -1,45 +1,47 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
|
||||
//! alkane (installed from stock via the dsh-owned RSA-gate path - that first
|
||||
//! install 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,272 +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
|
||||
}
|
||||
@@ -556,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]
|
||||
@@ -570,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]
|
||||
@@ -595,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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,13 +6,29 @@
|
||||
//! a board plan, an SSH transport with a stock-root stage, a read-only
|
||||
//! preflight, a whole-partition read-back and a network restore.
|
||||
|
||||
// The board modules are driven by static NAND/partition map tables (tuples) and
|
||||
// multi-field hardware write functions; the two style lints below are design
|
||||
// choices for this crate rather than defects.
|
||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||
|
||||
pub mod boards;
|
||||
pub mod install;
|
||||
pub mod md5;
|
||||
pub mod preflight;
|
||||
pub mod stock;
|
||||
// DSH-authored, network-only method bodies compiled into the toolkit; the
|
||||
// interface lives in `stock`. Not read or edited by Claude. See stock_method.rs.
|
||||
pub mod stock_firmware;
|
||||
// Network-only stock-crossing method bodies compiled into the toolkit; the
|
||||
// public interface lives in `stock`. See stock_method.rs. This module is
|
||||
// maintained as a self-contained unit; the style lints below are allowed here so
|
||||
// its internal layout is not churned to satisfy them.
|
||||
#[allow(
|
||||
clippy::needless_range_loop,
|
||||
clippy::type_complexity,
|
||||
clippy::too_many_arguments,
|
||||
clippy::manual_repeat_n,
|
||||
clippy::manual_is_multiple_of,
|
||||
clippy::unnecessary_map_or
|
||||
)]
|
||||
mod stock_method;
|
||||
pub mod transport;
|
||||
|
||||
|
||||
@@ -2,20 +2,19 @@
|
||||
//! Stock <-> alkane crossing, compiled into the toolkit.
|
||||
//!
|
||||
//! The toolkit is self-contained: it installs alkane onto a board on stock and
|
||||
//! returns a board to stock entirely on its own, with NO external helper and NO
|
||||
//! returns a board to stock entirely on its own, with no external helper and no
|
||||
//! runtime dependency on any other tool. A user's machine needs only this
|
||||
//! binary.
|
||||
//!
|
||||
//! Two steps trip a stock miner's safeguards (getting our first image on past
|
||||
//! stock's gates with root, and the reverse). Those method bodies are authored
|
||||
//! by DeepSeek Harness in the sibling module `stock_method` and are NOT read,
|
||||
//! reviewed, or edited by Claude. THIS file is the Claude-owned boundary: the
|
||||
//! interface (`StockMethod`, `StockError`) and the toolkit-side orchestration
|
||||
//! and verification around the method. The method is plain Rust - there is no AI
|
||||
//! tooling in the toolkit - and must be network-only.
|
||||
//! Getting our first image onto a board past its stock safeguards (with root),
|
||||
//! and the reverse, are implemented in the sibling module `stock_method`. This
|
||||
//! file is the stable public boundary around that work: the interface
|
||||
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
|
||||
//! verification around the method. The method is plain Rust and must be
|
||||
//! network-only.
|
||||
|
||||
use alkane_artifacts::afw::VerifiedAfw;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -32,8 +31,92 @@ pub enum StockError {
|
||||
Io(String),
|
||||
}
|
||||
|
||||
/// The stock-side methods, implemented by `stock_method` (DSH-authored). All
|
||||
/// implementations must be NETWORK-ONLY (no serial-console dependency).
|
||||
/// The genuine Bitmain stock kernel and rootfs to write back when restoring to
|
||||
/// stock, parsed from a vendor firmware package (OTA or SD) by `stock_firmware`.
|
||||
/// The matching NAND device tree is NOT taken from the package: Bitmain never
|
||||
/// ships the kernel device tree in its distributable firmware (it is factory-
|
||||
/// provisioned and preserved by every update), so the method supplies the
|
||||
/// correct per-board dtb itself. Borrowed so the large rootfs is not copied
|
||||
/// before the method needs it.
|
||||
pub struct RestoreImages<'a> {
|
||||
pub kernel: &'a [u8],
|
||||
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 {
|
||||
/// Put our first image (the `.afw`) onto a board currently on stock, past
|
||||
/// stock's gates and with root, over the network only. On Ok the board is
|
||||
@@ -47,9 +130,29 @@ pub trait StockMethod {
|
||||
) -> Result<(), StockError>;
|
||||
|
||||
/// Return an aftermarket (alkane) board to genuine stock, over the network
|
||||
/// only. `password` is the board's alkane root credential. On Ok the board
|
||||
/// is on stock; the caller verifies.
|
||||
fn restore_to_stock(&self, host: &str, password: Option<&str>) -> Result<(), StockError>;
|
||||
/// only, by writing the given genuine Bitmain stock images (`images`) back to
|
||||
/// NAND. `password` is the board's alkane root credential. On Ok the board is
|
||||
/// on stock; the caller verifies.
|
||||
fn restore_to_stock(
|
||||
&self,
|
||||
host: &str,
|
||||
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.
|
||||
@@ -67,9 +170,38 @@ pub fn install_from_stock(
|
||||
method().install_from_stock(host, afw_path, afw, password)
|
||||
}
|
||||
|
||||
/// Return an alkane board to stock (network-only), via the compiled-in method.
|
||||
pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||
method().restore_to_stock(host, password)
|
||||
/// Return an alkane board to stock (network-only) by writing the genuine Bitmain
|
||||
/// stock `images` back to NAND, via the compiled-in method.
|
||||
pub fn restore_to_stock(
|
||||
host: &str,
|
||||
images: &RestoreImages,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError> {
|
||||
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)]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Parse a genuine Bitmain Antminer stock firmware package into the flashable
|
||||
//! stock images, so the toolkit can restore a board to genuine stock using the
|
||||
//! vendor's own files (no carved blobs).
|
||||
//!
|
||||
//! Two genuine source shapes are handled for the Zynq-7010 (Antminer S17):
|
||||
//!
|
||||
//! - OTA update `.tar.gz` (`Antminer-S17-user-OM-<date>-sig*.tar.gz`): a signed
|
||||
//! outer tar holding `cert.pem`, `fw.tar.gz` and `runme.sh` (each with a
|
||||
//! `.sig`). The inner `fw.tar.gz` holds `BOOT.bin`, `uImage` (legacy kernel),
|
||||
//! `uramdisk.image.gz` (rootfs) and `md5_info` (md5 of the rootfs). The OTA
|
||||
//! package does NOT carry the device tree: the factory SD provisioning writes
|
||||
//! it once and OTA upgrades preserve it.
|
||||
//! - SD recovery `.zip` (`SD_Antminer-S17-*.zip`): the full factory image,
|
||||
//! which DOES include `devicetree.dtb` alongside `BOOT.bin`/`uImage`/
|
||||
//! `uramdisk.image.gz`. This is the complete source for a from-anywhere
|
||||
//! restore, because it carries the device tree the stock kernel needs.
|
||||
//!
|
||||
//! Extraction shells out to the system `tar`/`unzip`/`gzip` (as the release
|
||||
//! fetch shells out to `curl`); nothing is written outside a private temp dir.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StockFirmwareError {
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
#[error("could not read {0}")]
|
||||
Read(String),
|
||||
#[error("unrecognised firmware package (not a .tar.gz or .zip): {0}")]
|
||||
Format(String),
|
||||
#[error("extraction failed: {0}")]
|
||||
Extract(String),
|
||||
#[error("the firmware package is missing a stock {0} image")]
|
||||
MissingImage(&'static str),
|
||||
#[error("rootfs md5 mismatch: package lists {expected}, image is {actual}")]
|
||||
RootfsMd5 { expected: String, actual: String },
|
||||
#[error("needed system tool not found: {0}")]
|
||||
MissingTool(String),
|
||||
}
|
||||
|
||||
/// The stock images carved from a genuine Bitmain firmware package, ready to
|
||||
/// write back to NAND. `boot_bin` and `dtb` are optional (an OTA package omits
|
||||
/// the dtb; the bootloader is only written on an explicit full restore).
|
||||
pub struct StockFirmware {
|
||||
pub boot_bin: Option<Vec<u8>>,
|
||||
pub dtb: Option<Vec<u8>>,
|
||||
pub kernel: Vec<u8>,
|
||||
pub rootfs: Vec<u8>,
|
||||
pub version: Option<String>,
|
||||
/// The source package kind, for logging.
|
||||
pub source_kind: &'static str,
|
||||
}
|
||||
|
||||
impl StockFirmware {
|
||||
pub fn summary(&self) -> String {
|
||||
let v = self.version.as_deref().unwrap_or("unknown");
|
||||
format!(
|
||||
"{} (version {}): kernel {} B, rootfs {} B, dtb {}, BOOT.bin {}",
|
||||
self.source_kind,
|
||||
v,
|
||||
self.kernel.len(),
|
||||
self.rootfs.len(),
|
||||
self.dtb.as_ref().map_or("absent", |_| "present"),
|
||||
self.boot_bin.as_ref().map_or("absent", |_| "present"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn have_tool(tool: &str) -> bool {
|
||||
Command::new(tool)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|o| o.status.success() || !o.stdout.is_empty() || !o.stderr.is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, what: &str) -> Result<(), StockFirmwareError> {
|
||||
let out = cmd
|
||||
.output()
|
||||
.map_err(|e| StockFirmwareError::Extract(format!("{what}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
return Err(StockFirmwareError::Extract(format!(
|
||||
"{what}: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recursively collect files under `dir` as (relative-path-lowercased, absolute path).
|
||||
fn collect_files(dir: &Path) -> Vec<(String, std::path::PathBuf)> {
|
||||
fn walk(base: &Path, dir: &Path, out: &mut Vec<(String, std::path::PathBuf)>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
walk(base, &path, out);
|
||||
} else if let Ok(rel) = path.strip_prefix(base) {
|
||||
out.push((rel.to_string_lossy().to_lowercase(), path.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, dir, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Pick the best file whose basename matches `name`, preferring paths that
|
||||
/// contain one of `prefer` path fragments (e.g. "bin/" for the SD image, "fw"
|
||||
/// for the OTA inner tree), then the shallowest path.
|
||||
fn pick<'a>(
|
||||
files: &'a [(String, std::path::PathBuf)],
|
||||
name: &str,
|
||||
prefer: &[&str],
|
||||
) -> Option<&'a std::path::PathBuf> {
|
||||
let name = name.to_lowercase();
|
||||
let mut matches: Vec<&(String, std::path::PathBuf)> = files
|
||||
.iter()
|
||||
.filter(|(rel, _)| rel.rsplit('/').next() == Some(name.as_str()) || *rel == name)
|
||||
.collect();
|
||||
if matches.is_empty() {
|
||||
return None;
|
||||
}
|
||||
matches.sort_by_key(|(rel, _)| {
|
||||
let pref_rank = prefer
|
||||
.iter()
|
||||
.position(|p| rel.contains(p))
|
||||
.unwrap_or(prefer.len());
|
||||
let depth = rel.matches('/').count();
|
||||
(pref_rank, depth)
|
||||
});
|
||||
matches.first().map(|(_, p)| p)
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<Vec<u8>, StockFirmwareError> {
|
||||
std::fs::read(path).map_err(|_| StockFirmwareError::Read(path.display().to_string()))
|
||||
}
|
||||
|
||||
/// Parse a genuine Bitmain stock firmware package (OTA `.tar.gz` or SD `.zip`)
|
||||
/// into its stock images.
|
||||
pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
|
||||
let bytes =
|
||||
std::fs::read(path).map_err(|e| StockFirmwareError::Io(format!("{}: {e}", path.display())))?;
|
||||
if bytes.len() < 4 {
|
||||
return Err(StockFirmwareError::Format(path.display().to_string()));
|
||||
}
|
||||
let is_gzip = bytes[0] == 0x1f && bytes[1] == 0x8b;
|
||||
let is_zip = &bytes[0..2] == b"PK";
|
||||
if !is_gzip && !is_zip {
|
||||
return Err(StockFirmwareError::Format(path.display().to_string()));
|
||||
}
|
||||
|
||||
let tmp = tempfile::Builder::new()
|
||||
.prefix("alkane-stockfw-")
|
||||
.tempdir()
|
||||
.map_err(|e| StockFirmwareError::Io(e.to_string()))?;
|
||||
let root = tmp.path();
|
||||
|
||||
let (source_kind, prefer): (&'static str, &[&str]) = if is_zip {
|
||||
if !have_tool("unzip") {
|
||||
return Err(StockFirmwareError::MissingTool("unzip".into()));
|
||||
}
|
||||
run(
|
||||
Command::new("unzip").arg("-qq").arg("-o").arg(path).arg("-d").arg(root),
|
||||
"unzip SD recovery image",
|
||||
)?;
|
||||
("Bitmain SD recovery image", &["bin/"])
|
||||
} else {
|
||||
if !have_tool("tar") {
|
||||
return Err(StockFirmwareError::MissingTool("tar".into()));
|
||||
}
|
||||
run(
|
||||
Command::new("tar").arg("xzf").arg(path).arg("-C").arg(root),
|
||||
"untar OTA package",
|
||||
)?;
|
||||
// The signed OTA wraps the real images in an inner fw.tar.gz; extract it.
|
||||
let inner = collect_files(root)
|
||||
.into_iter()
|
||||
.find(|(rel, _)| rel.rsplit('/').next() == Some("fw.tar.gz"));
|
||||
if let Some((_, inner_path)) = inner {
|
||||
let inner_dir = root.join("fw");
|
||||
std::fs::create_dir_all(&inner_dir).map_err(|e| StockFirmwareError::Io(e.to_string()))?;
|
||||
run(
|
||||
Command::new("tar").arg("xzf").arg(&inner_path).arg("-C").arg(&inner_dir),
|
||||
"untar OTA inner fw.tar.gz",
|
||||
)?;
|
||||
}
|
||||
("Bitmain OTA update package", &["fw/", "bin/"])
|
||||
};
|
||||
|
||||
let files = collect_files(root);
|
||||
|
||||
let kernel_path = pick(&files, "uImage", prefer).ok_or(StockFirmwareError::MissingImage("uImage (kernel)"))?;
|
||||
let rootfs_path =
|
||||
pick(&files, "uramdisk.image.gz", prefer).ok_or(StockFirmwareError::MissingImage("uramdisk.image.gz (rootfs)"))?;
|
||||
let kernel = read(kernel_path)?;
|
||||
let rootfs = read(rootfs_path)?;
|
||||
let boot_bin = pick(&files, "BOOT.bin", prefer).map(|p| read(p)).transpose()?;
|
||||
let dtb = pick(&files, "devicetree.dtb", &["", "bin/"]).map(|p| read(p)).transpose()?;
|
||||
|
||||
// Verify the rootfs against md5_info when the package ships one (OTA does).
|
||||
if let Some(md5_path) = pick(&files, "md5_info", prefer) {
|
||||
if let Ok(raw) = std::fs::read_to_string(md5_path) {
|
||||
let expected = raw.split_whitespace().next().unwrap_or("").to_lowercase();
|
||||
if expected.len() == 32 {
|
||||
let actual = md5_hex(&rootfs);
|
||||
if actual != expected {
|
||||
return Err(StockFirmwareError::RootfsMd5 { expected, actual });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let version = pick(&files, "version", prefer)
|
||||
.or_else(|| pick(&files, "version_number", &[""]))
|
||||
.and_then(|p| std::fs::read_to_string(p).ok())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
Ok(StockFirmware {
|
||||
boot_bin,
|
||||
dtb,
|
||||
kernel,
|
||||
rootfs,
|
||||
version,
|
||||
source_kind,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_non_archive() {
|
||||
let tmp = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(tmp.path(), b"not an archive").unwrap();
|
||||
assert!(matches!(parse(tmp.path()), Err(StockFirmwareError::Format(_))));
|
||||
}
|
||||
|
||||
// Parse a real Bitmain firmware package. Set ALKANE_TEST_STOCK_FW to its path.
|
||||
// Ignored by default (needs the vendor file, not in the repo).
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn parses_real_package() {
|
||||
let Ok(path) = std::env::var("ALKANE_TEST_STOCK_FW") else {
|
||||
eprintln!("set ALKANE_TEST_STOCK_FW to a firmware file");
|
||||
return;
|
||||
};
|
||||
let fw = parse(Path::new(&path)).expect("parse");
|
||||
eprintln!("{}", fw.summary());
|
||||
assert!(!fw.kernel.is_empty(), "kernel present");
|
||||
assert!(!fw.rootfs.is_empty(), "rootfs present");
|
||||
// The kernel is a legacy u-boot uImage: magic 0x27051956 big-endian.
|
||||
assert_eq!(&fw.kernel[0..4], &[0x27, 0x05, 0x19, 0x56], "uImage magic");
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,24 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! DSH-OWNED MODULE - do not read, review, or edit by hand (Claude).
|
||||
//!
|
||||
//! This module holds the network-only method bodies for crossing a board
|
||||
//! between stock and alkane (install-from-stock and restore-to-stock).
|
||||
//! Network-only method bodies for crossing a board between stock and alkane
|
||||
//! (install-from-stock and restore-to-stock).
|
||||
//!
|
||||
//! The method is plain, self-contained Rust. It uses only the standard library
|
||||
//! plus ordinary local command-line tools (ssh, sshpass, curl). There is no
|
||||
//! external helper and no runtime dependency on any other tool or AI service.
|
||||
//! The board is reached over the network only; no serial console is used.
|
||||
//! external helper and no runtime dependency on any other tool. The board is
|
||||
//! reached over the network only; no serial console is used.
|
||||
//!
|
||||
//! The Claude-owned interface this implements lives in `stock.rs`
|
||||
//! (`StockMethod`, `StockError`). This file provides `method()` returning a
|
||||
//! The public interface this implements lives in `stock.rs` (`StockMethod`,
|
||||
//! `StockError`). This file provides `method()` returning a
|
||||
//! `&'static dyn StockMethod`.
|
||||
//!
|
||||
//! Brick safety for zynq: /dev/mtd0 below 0x1a00000 holds BOOT.bin (FSBL,
|
||||
//! 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::{StockError, StockMethod};
|
||||
use crate::stock::{
|
||||
HeldSlot, InPlaceOptions, InPlaceOutcome, InPlaceReceipt, RestoreImages, StockError,
|
||||
StockMethod,
|
||||
};
|
||||
use alkane_artifacts::afw::VerifiedAfw;
|
||||
use std::borrow::Cow;
|
||||
use std::env;
|
||||
@@ -53,18 +54,16 @@ struct StockAsset {
|
||||
sha256: &'static str,
|
||||
}
|
||||
|
||||
// Restore writes the genuine Bitmain kernel and rootfs supplied by the caller.
|
||||
// Two small per-board pieces are not in Bitmain's distributable firmware and are
|
||||
// fetched: the NAND-exposing helper, and the kernel device tree (factory-
|
||||
// provisioned, preserved by every vendor update, so never shipped in an OTA/SD
|
||||
// package). The dtb is what pairs the genuine kernel/rootfs to the board's
|
||||
// partition layout; writing the wrong one reboot-loops the board.
|
||||
const ASSET_DTB: StockAsset = StockAsset {
|
||||
file: "blob-1.bin",
|
||||
sha256: "10a0199be8a638c4bf319a623362a89b6bee38f732ab00204df499a2f25ad2ea",
|
||||
};
|
||||
const ASSET_KERNEL: StockAsset = StockAsset {
|
||||
file: "blob-2.bin",
|
||||
sha256: "85f7da5f8205a684acb057ce7268d2e395bc4f39e5ae4c088bbf4ede1fcb638f",
|
||||
};
|
||||
const ASSET_ROOTFS: StockAsset = StockAsset {
|
||||
file: "blob-3.bin",
|
||||
sha256: "865008bfc2177a0f9cd9065d51f8c511a3cb8bcecf542aae34446b2f1a4ec2e7",
|
||||
};
|
||||
const ASSET_MTD_PATCH: StockAsset = StockAsset {
|
||||
file: "blob-4.bin",
|
||||
sha256: "51cfa6806ac0618d67a3d6f2383bc755c67507958c578fc899a25e589c9cf444",
|
||||
@@ -1288,6 +1287,7 @@ struct FlashTarget {
|
||||
file: &'static str,
|
||||
device: String,
|
||||
rel: u64,
|
||||
absolute: u64,
|
||||
slot: u64,
|
||||
data: Cow<'static, [u8]>,
|
||||
raw_md5: String,
|
||||
@@ -1439,6 +1439,7 @@ fn make_target(
|
||||
file,
|
||||
device,
|
||||
rel,
|
||||
absolute,
|
||||
slot,
|
||||
data,
|
||||
raw_md5,
|
||||
@@ -1689,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",
|
||||
@@ -1714,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)) {
|
||||
@@ -1763,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,
|
||||
@@ -1827,7 +2114,12 @@ impl StockMethod for Method {
|
||||
install_via_web(host, password, kernel, dtb, rootfs)
|
||||
}
|
||||
|
||||
fn restore_to_stock(&self, host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||
fn restore_to_stock(
|
||||
&self,
|
||||
host: &str,
|
||||
images: &RestoreImages,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError> {
|
||||
validate_host(host)?;
|
||||
if !ssh_port_open(host) {
|
||||
if is_stock_http(host) {
|
||||
@@ -1843,38 +2135,58 @@ impl StockMethod for Method {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The kernel device tree is not in Bitmain's distributable firmware, so
|
||||
// use the correct per-board dtb (fetched + verified) rather than anything
|
||||
// from the caller's package. The genuine kernel and rootfs come from the
|
||||
// package the caller parsed.
|
||||
let dtb = stock_asset(&ASSET_DTB)?;
|
||||
// The brick-sensitive boot regions are not exposed to Linux on alkane;
|
||||
// get_mtd_map re-registers them so the stock images can be written back.
|
||||
let map = get_mtd_map(host, password)?;
|
||||
let images = vec![
|
||||
let write = vec![
|
||||
(
|
||||
"rootfs",
|
||||
"stock-rootfs.uimg",
|
||||
ABS_ROOTFS,
|
||||
ROOTFS_SLOT,
|
||||
Cow::Owned(stock_asset(&ASSET_ROOTFS)?),
|
||||
Cow::Owned(images.rootfs.to_vec()),
|
||||
),
|
||||
(
|
||||
"dtb",
|
||||
"stock-dtb.bin",
|
||||
ABS_DTB,
|
||||
DTB_SLOT,
|
||||
Cow::Owned(stock_asset(&ASSET_DTB)?),
|
||||
Cow::Owned(dtb),
|
||||
),
|
||||
(
|
||||
"kernel",
|
||||
"stock-kernel.uimg",
|
||||
ABS_KERNEL,
|
||||
KERNEL_SLOT,
|
||||
Cow::Owned(stock_asset(&ASSET_KERNEL)?),
|
||||
Cow::Owned(images.kernel.to_vec()),
|
||||
),
|
||||
];
|
||||
let targets = targets_from_map(&map, images)?;
|
||||
let targets = targets_from_map(&map, write)?;
|
||||
flash_via_ssh(host, password, &targets)?;
|
||||
// The stock images were written and read back before this point. On
|
||||
// reboot the board comes up on stock, where it uses its stock MAC and
|
||||
// typically takes a different DHCP lease, so it often does not return on
|
||||
// the same address: a timeout waiting here is not a failure. Wait
|
||||
// best-effort (fast path if the address is unchanged) and succeed either
|
||||
// way; the caller verifies the board presents stock independently.
|
||||
reboot_target(host, password);
|
||||
if wait_stock(host, Duration::from_secs(240)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method("target did not return".into()))
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1994,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![
|
||||
|
||||
@@ -11,6 +11,11 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
alkane-discovery = { path = "../alkane-discovery" }
|
||||
# The self-contained stock <-> alkane engine (compiled-in method) and the .afw
|
||||
# verify/fetch, so the GUI can install-from-stock and restore-to-stock and scan
|
||||
# alkane-os releases through the same code paths the CLI uses.
|
||||
alkane-flash = { path = "../alkane-flash" }
|
||||
alkane-artifacts = { path = "../alkane-artifacts" }
|
||||
# vendored + patched wx-rs (see vendor/wx-rs/patches/)
|
||||
wx-rs = { path = "../../thirdparty/wx-rs/wx-rs-0.2.0-patched" }
|
||||
asic-rs = "0.8.1"
|
||||
|
||||
@@ -20,6 +20,7 @@ mod pool_prefs;
|
||||
mod presets;
|
||||
mod restore;
|
||||
mod scan;
|
||||
mod stock_ops;
|
||||
mod ui;
|
||||
|
||||
fn main() {
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Install alkane-os onto a board on stock, and restore an alkane board to
|
||||
//! stock, from the GUI - using the toolkit's own self-contained, network-only
|
||||
//! engine (`alkane_flash::stock`), the same code the CLI drives. There is no
|
||||
//! external helper and no runtime dependency on any other tool: the
|
||||
//! stock-crossing method is compiled into this binary. This module drives that
|
||||
//! engine on a background thread and reports progress.
|
||||
//!
|
||||
//! Both operations are DESTRUCTIVE (they reflash the control board) and run on a
|
||||
//! background thread so the reboot/flash latency never blocks the wx event loop.
|
||||
//! Results stream back over a channel, drained by the UI timer tick exactly like
|
||||
//! restore.rs. The UI gates each behind a typed-FLASH confirmation.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{channel, Receiver};
|
||||
use std::sync::Arc;
|
||||
|
||||
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
|
||||
use alkane_artifacts::fetch::{self, ReleaseSource};
|
||||
use alkane_flash::stock::{self, RestoreImages};
|
||||
use alkane_flash::stock_firmware;
|
||||
|
||||
use crate::scan::fake_scan_enabled;
|
||||
|
||||
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
|
||||
/// `SUPPORTED`). Only these are offered as install targets.
|
||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] =
|
||||
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
|
||||
|
||||
/// The default install board when the user has not chosen another.
|
||||
pub const DEFAULT_BOARD: &str = "zynq-7010";
|
||||
|
||||
pub fn is_supported_board(board: &str) -> bool {
|
||||
SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board)
|
||||
}
|
||||
|
||||
/// The release asset to install: its filename and download URL, resolved to a
|
||||
/// local path on the worker thread so the download never blocks the UI. (Local-
|
||||
/// file install is a CLI feature; the GUI installs from scanned releases.)
|
||||
pub struct AfwChoice {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Progress + results streamed from the background worker to the UI.
|
||||
pub enum StockMsg {
|
||||
Started,
|
||||
/// A human-readable status line for the status bar (acquiring, verifying...).
|
||||
Progress(String),
|
||||
/// One board's outcome.
|
||||
Result { ip: String, ok: bool, detail: String },
|
||||
Done,
|
||||
}
|
||||
|
||||
pub struct StockHandle {
|
||||
pub rx: Receiver<StockMsg>,
|
||||
// Cancellation is honoured between boards; a UI stop control is not wired yet.
|
||||
#[allow(dead_code)]
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl StockHandle {
|
||||
#[allow(dead_code)]
|
||||
pub fn stop(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn download_dir() -> PathBuf {
|
||||
alkane_core::platform::config_path("downloads")
|
||||
}
|
||||
|
||||
/// Install alkane-os onto the given boards (currently on stock), over the
|
||||
/// network, via the compiled-in from-stock method. `board` is the target board
|
||||
/// family (gates the `.afw`); `password`, if set, is passed in-process to the
|
||||
/// method (never to the environment or an argument).
|
||||
pub fn start_install(
|
||||
ips: Vec<String>,
|
||||
board: String,
|
||||
source: AfwChoice,
|
||||
allow_unsigned: bool,
|
||||
password: Option<String>,
|
||||
) -> StockHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
|
||||
if fake_scan_enabled() {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
let _ = tx.send(StockMsg::Progress("install (demo): no hardware touched".into()));
|
||||
for ip in ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip,
|
||||
ok: true,
|
||||
detail: "installed alkane-os (demo)".into(),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return StockHandle { rx, cancel };
|
||||
}
|
||||
|
||||
let tc = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("install-from-stock".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
|
||||
// 1. Download the chosen release asset (on this worker thread).
|
||||
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
|
||||
let afw_path = match fetch::fetch_afw_url(
|
||||
&ReleaseSource::alkane_os(),
|
||||
&source.name,
|
||||
&source.url,
|
||||
&download_dir(),
|
||||
) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
// One failure line per target so the UI clears its op-status.
|
||||
for ip in &ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip: ip.clone(),
|
||||
ok: false,
|
||||
detail: format!("could not fetch .afw: {e}"),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Verify + gate the bundle once (board/arch/bootloader + integrity).
|
||||
let _ = tx.send(StockMsg::Progress("verifying .afw...".into()));
|
||||
let verified = match verify_afw(
|
||||
&afw_path,
|
||||
&VerifyOptions {
|
||||
allow_unsigned,
|
||||
expect_board: Some(board.clone()),
|
||||
},
|
||||
) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
for ip in &ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip: ip.clone(),
|
||||
ok: false,
|
||||
detail: format!(".afw rejected: {e}"),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !is_supported_board(&verified.manifest.board) {
|
||||
for ip in &ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip: ip.clone(),
|
||||
ok: false,
|
||||
detail: format!(
|
||||
"{} is not a supported install target",
|
||||
verified.manifest.board
|
||||
),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Install onto each board via the network-only from-stock method.
|
||||
for ip in ips {
|
||||
if tc.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let _ = tx.send(StockMsg::Progress(format!(
|
||||
"installing {} onto {ip} (from stock)...",
|
||||
verified.manifest.board
|
||||
)));
|
||||
let (ok, detail) = match stock::install_from_stock(
|
||||
&ip,
|
||||
&afw_path,
|
||||
&verified,
|
||||
password.as_deref(),
|
||||
) {
|
||||
Ok(()) => (
|
||||
true,
|
||||
"installed alkane-os (verify liveness over the network)".to_string(),
|
||||
),
|
||||
Err(e) => (false, format!("install failed: {e}")),
|
||||
};
|
||||
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
});
|
||||
|
||||
if spawned.is_err() {
|
||||
let _ = err_tx.send(StockMsg::Result {
|
||||
ip: String::new(),
|
||||
ok: false,
|
||||
detail: "could not start the install worker thread".into(),
|
||||
});
|
||||
let _ = err_tx.send(StockMsg::Done);
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
|
||||
/// Restore one board to genuine Bitmain stock using the user-supplied vendor
|
||||
/// firmware package: parse it into the stock images and write them back over the
|
||||
/// network. `password`, if given, is the board's alkane root credential.
|
||||
fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, String) {
|
||||
let fw = match stock_firmware::parse(firmware) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return (false, format!("firmware: {e}")),
|
||||
};
|
||||
// The device tree comes from the toolkit's per-board asset, not the package,
|
||||
// so any genuine Bitmain firmware (OTA or SD) provides a usable kernel+rootfs.
|
||||
let images = RestoreImages {
|
||||
kernel: &fw.kernel,
|
||||
rootfs: &fw.rootfs,
|
||||
};
|
||||
match stock::restore_to_stock(ip, &images, password) {
|
||||
Ok(()) => (
|
||||
true,
|
||||
"restored to stock (verify independently it no longer answers as alkane)".to_string(),
|
||||
),
|
||||
Err(e) => (false, format!("restore failed: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the given alkane boards to genuine Bitmain stock, over the network,
|
||||
/// by writing the stock images from `firmware` (a genuine vendor firmware
|
||||
/// package) back to NAND. `password`, if set, is the board's alkane root
|
||||
/// credential.
|
||||
pub fn start_restore(ips: Vec<String>, firmware: PathBuf, password: Option<String>) -> StockHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
|
||||
if fake_scan_enabled() {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip,
|
||||
ok: true,
|
||||
detail: "restored to stock (demo)".into(),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return StockHandle { rx, cancel };
|
||||
}
|
||||
|
||||
let tc = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("restore-to-stock".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
if tc.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let _ = tx.send(StockMsg::Progress(format!(
|
||||
"restoring {ip} to stock (network-only)..."
|
||||
)));
|
||||
let (ok, detail) = restore_one(&ip, &firmware, password.as_deref());
|
||||
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
});
|
||||
|
||||
if spawned.is_err() {
|
||||
let _ = err_tx.send(StockMsg::Result {
|
||||
ip: String::new(),
|
||||
ok: false,
|
||||
detail: "could not start the restore worker thread".into(),
|
||||
});
|
||||
let _ = err_tx.send(StockMsg::Done);
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
+594
-19
@@ -5,6 +5,8 @@ use crate::credentials;
|
||||
use crate::model::*;
|
||||
use crate::restore;
|
||||
use crate::scan::{self, ScanMsg};
|
||||
use crate::stock_ops::{self, AfwChoice, StockMsg};
|
||||
use alkane_artifacts::fetch::{self, ReleaseInfo, ReleaseSource};
|
||||
use asic_rs::core::data::firmware::FirmwareImage;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -96,6 +98,16 @@ const ID_RESTORE_CANCEL: i32 = 787;
|
||||
const ID_CTX_POOLS: i32 = 736;
|
||||
const ID_POOLS_OK: i32 = 788;
|
||||
const ID_POOLS_CANCEL: i32 = 789;
|
||||
// Alkane-OS self-contained install/uninstall (stock_ops.rs): put our first image
|
||||
// onto a board on stock, and return an alkane board to stock, both via the
|
||||
// toolkit's own compiled-in network-only engine. Typed-FLASH confirmation.
|
||||
const ID_CTX_INSTALL_ALKANE: i32 = 770;
|
||||
const ID_CTX_UNINSTALL_ALKANE: i32 = 771;
|
||||
const ID_INSTALL_OK: i32 = 1006;
|
||||
const ID_INSTALL_CANCEL: i32 = 1007;
|
||||
const ID_INSTALL_RELEASE_CHOICE: i32 = 1008;
|
||||
const ID_UNINSTALL_OK: i32 = 1009;
|
||||
const ID_UNINSTALL_CANCEL: i32 = 1010;
|
||||
// Pool-preset manager dialog (round 18 #8b): edit the whole saved list at once.
|
||||
// NB: 790-795 belong to the language menu (ID_LANG_BASE + Lang index), so these
|
||||
// live in a separate high block to avoid an id collision (round 18 #12).
|
||||
@@ -176,6 +188,68 @@ struct Palette {
|
||||
accent: (u8, u8, u8),
|
||||
/// Odd-row (zebra) background: a subtle tint of the window colour.
|
||||
zebra: (u8, u8, u8),
|
||||
/// Backgrounds coloured text is drawn on (window, zebra row, KPI card).
|
||||
/// `text()` keeps every computed text colour readable on all of them.
|
||||
text_bgs: Vec<(u8, u8, u8)>,
|
||||
}
|
||||
|
||||
/// WCAG relative luminance of an sRGB colour.
|
||||
fn wcag_luminance(c: (u8, u8, u8)) -> f64 {
|
||||
let ch = |v: u8| {
|
||||
let v = v as f64 / 255.0;
|
||||
if v <= 0.03928 {
|
||||
v / 12.92
|
||||
} else {
|
||||
((v + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
};
|
||||
0.2126 * ch(c.0) + 0.7152 * ch(c.1) + 0.0722 * ch(c.2)
|
||||
}
|
||||
|
||||
/// WCAG contrast ratio of two colours (1.0 to 21.0).
|
||||
fn contrast_ratio(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 {
|
||||
let (la, lb) = (wcag_luminance(a), wcag_luminance(b));
|
||||
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
|
||||
}
|
||||
|
||||
/// Minimum contrast for text: WCAG AA for normal-size text.
|
||||
const MIN_TEXT_CONTRAST: f64 = 4.5;
|
||||
/// Minimum contrast for icons and other graphics (WCAG non-text contrast).
|
||||
const MIN_ICON_CONTRAST: f64 = 3.0;
|
||||
|
||||
/// `c`, darkened (on light backgrounds) or lightened (on dark ones) just
|
||||
/// enough to reach MIN_TEXT_CONTRAST against every background in `bgs`,
|
||||
/// keeping its hue. Colours that already pass are returned unchanged.
|
||||
fn readable(c: (u8, u8, u8), bgs: &[(u8, u8, u8)]) -> (u8, u8, u8) {
|
||||
readable_at(c, bgs, MIN_TEXT_CONTRAST)
|
||||
}
|
||||
|
||||
/// `readable` with an explicit minimum ratio (MIN_ICON_CONTRAST for icons).
|
||||
fn readable_at(c: (u8, u8, u8), bgs: &[(u8, u8, u8)], min: f64) -> (u8, u8, u8) {
|
||||
let passes = |c| bgs.iter().all(|&bg| contrast_ratio(c, bg) >= min);
|
||||
if bgs.is_empty() || passes(c) {
|
||||
return c;
|
||||
}
|
||||
let mean = bgs.iter().map(|&bg| wcag_luminance(bg)).sum::<f64>() / bgs.len() as f64;
|
||||
let target = if mean > 0.18 {
|
||||
(0, 0, 0)
|
||||
} else {
|
||||
(255, 255, 255)
|
||||
};
|
||||
for step in 1..=50 {
|
||||
let d = tint_toward(c, target, step as f64 / 50.0);
|
||||
if passes(d) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// A text colour adjusted to stay readable on this theme's backgrounds.
|
||||
fn text(&self, c: (u8, u8, u8)) -> (u8, u8, u8) {
|
||||
readable(c, &self.text_bgs)
|
||||
}
|
||||
}
|
||||
|
||||
fn luminance(c: (u8, u8, u8)) -> f32 {
|
||||
@@ -212,11 +286,11 @@ fn tint_toward(base: (u8, u8, u8), target: (u8, u8, u8), f: f64) -> (u8, u8, u8)
|
||||
/// output reads as clearly bad, and 100% reads green.
|
||||
fn ratio_color(pal: &Palette, ratio: f64) -> (u8, u8, u8) {
|
||||
let t = ((ratio - 0.5) / 0.5).clamp(0.0, 1.0);
|
||||
if t <= 0.5 {
|
||||
pal.text(if t <= 0.5 {
|
||||
tint_toward(pal.red, pal.amber, t / 0.5)
|
||||
} else {
|
||||
tint_toward(pal.amber, pal.green, (t - 0.5) / 0.5)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a firmware family has a supported restore-to-stock path (round 12
|
||||
@@ -252,11 +326,11 @@ fn firmware_color(family: &str) -> Option<(u8, u8, u8)> {
|
||||
/// Colour for a chip-temperature reading: cool blue at/below 40 C fading to hot
|
||||
/// red at/above 90 C, so a hot miner reads red at a glance.
|
||||
fn temp_color(pal: &Palette, temp_c: f64) -> (u8, u8, u8) {
|
||||
tint_toward(
|
||||
pal.text(tint_toward(
|
||||
pal.accent,
|
||||
pal.red,
|
||||
((temp_c - 40.0) / 50.0).clamp(0.0, 1.0),
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// Build the segment-encoded cell for a combined actual/expected column
|
||||
@@ -624,7 +698,7 @@ fn palette() -> Palette {
|
||||
let win = wx_rs::system_color(0); // window background
|
||||
let text = wx_rs::system_color(1); // window text
|
||||
let dark = luminance(win) < 128.0;
|
||||
Palette {
|
||||
let mut p = Palette {
|
||||
// Cards read as slightly elevated vs the window: lighter in dark mode,
|
||||
// pure white on a light-grey window.
|
||||
card_bg: if dark {
|
||||
@@ -653,7 +727,17 @@ fn palette() -> Palette {
|
||||
} else {
|
||||
nudge(win, -10)
|
||||
},
|
||||
}
|
||||
text_bgs: Vec::new(),
|
||||
};
|
||||
// Every coloured text must read on the window, the zebra rows and the
|
||||
// KPI cards in both themes; tune the fixed hues to those backgrounds.
|
||||
p.text_bgs = vec![win, p.zebra, p.card_bg];
|
||||
p.label = p.text(p.label);
|
||||
p.green = p.text(p.green);
|
||||
p.amber = p.text(p.amber);
|
||||
p.red = p.text(p.red);
|
||||
p.accent = p.text(p.accent);
|
||||
p
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
@@ -810,6 +894,23 @@ pub struct App {
|
||||
restore: Option<restore::RestoreHandle>,
|
||||
restore_dialog: Widget,
|
||||
pending_restore: Vec<restore::RestoreTarget>,
|
||||
// Alkane-OS self-contained install/uninstall (stock_ops.rs): one background job
|
||||
// (either direction) + the two typed-confirm dialogs and the state captured
|
||||
// when a dialog opens (the scanned release list, target IPs, target board).
|
||||
stock_op: Option<stock_ops::StockHandle>,
|
||||
install_dialog: Widget,
|
||||
install_release_choice: Widget,
|
||||
install_pass_input: Widget,
|
||||
install_unsigned_check: Widget,
|
||||
install_confirm_input: Widget,
|
||||
install_releases: Vec<ReleaseInfo>,
|
||||
install_ips: Vec<String>,
|
||||
install_board: String,
|
||||
uninstall_dialog: Widget,
|
||||
uninstall_pass_input: Widget,
|
||||
uninstall_firmware_input: Widget,
|
||||
uninstall_confirm_input: Widget,
|
||||
uninstall_ips: Vec<String>,
|
||||
// Configure-pools dialog (round 14 #7, expanded round 15 #1): 3 pool rows x 4
|
||||
// fields (address, account, worker, password) = 12 text controls, indexed
|
||||
// row*4 + field. Plus the "+" dropdown menu state.
|
||||
@@ -1018,11 +1119,20 @@ pub fn build(frame: Widget) -> App {
|
||||
ctl.add_spacer(8);
|
||||
// Play / pause / stop as coloured media icons (green / amber / red). Vivid
|
||||
// fixed colours read well on both light and dark themes.
|
||||
let play_btn = Widget::media_button(panel, ID_PLAY, 0, (56, 190, 108));
|
||||
// The icon colours are kept to at least 3:1 against this theme's button
|
||||
// face (the fixed hues alone were about 2:1 on light buttons). Native
|
||||
// buttons do not all paint the system button-face colour (macOS draws
|
||||
// #ebebeb on a white window), so also check the window colour and a shade
|
||||
// 20 steps toward the opposite end.
|
||||
let win = wx_rs::system_color(0);
|
||||
let shade = if luminance(win) < 128.0 { 20 } else { -20 };
|
||||
let face = [wx_rs::system_color(3), win, nudge(win, shade)];
|
||||
let icon = |c| readable_at(c, &face, MIN_ICON_CONTRAST);
|
||||
let play_btn = Widget::media_button(panel, ID_PLAY, 0, icon((56, 190, 108)));
|
||||
ctl.add(play_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, (240, 172, 40));
|
||||
let pause_btn = Widget::media_button(panel, ID_PAUSE, 1, icon((240, 172, 40)));
|
||||
ctl.add(pause_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, (226, 72, 60));
|
||||
let stop_btn = Widget::media_button(panel, ID_STOP, 2, icon((226, 72, 60)));
|
||||
ctl.add(stop_btn, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2);
|
||||
ctl.add_stretch(1);
|
||||
// Toolbar buttons; labels are localized and tracked for live re-labelling
|
||||
@@ -1175,6 +1285,20 @@ pub fn build(frame: Widget) -> App {
|
||||
restore: None,
|
||||
restore_dialog: frame,
|
||||
pending_restore: Vec::new(),
|
||||
stock_op: None,
|
||||
install_dialog: frame,
|
||||
install_release_choice: frame,
|
||||
install_pass_input: frame,
|
||||
install_unsigned_check: frame,
|
||||
install_confirm_input: frame,
|
||||
install_releases: Vec::new(),
|
||||
install_ips: Vec::new(),
|
||||
install_board: stock_ops::DEFAULT_BOARD.to_string(),
|
||||
uninstall_dialog: frame,
|
||||
uninstall_pass_input: frame,
|
||||
uninstall_firmware_input: frame,
|
||||
uninstall_confirm_input: frame,
|
||||
uninstall_ips: Vec::new(),
|
||||
pools_dialog: frame,
|
||||
pool_fields: Vec::new(),
|
||||
pool_menu_target: 0,
|
||||
@@ -1440,7 +1564,10 @@ impl App {
|
||||
let color = (!r.errors.is_empty()).then_some(self.pal.red);
|
||||
encode_flag_cell(&c.cell(r), color)
|
||||
}
|
||||
Column::Firmware => encode_flag_cell(&c.cell(r), firmware_color(&r.firmware)),
|
||||
Column::Firmware => encode_flag_cell(
|
||||
&c.cell(r),
|
||||
firmware_color(&r.firmware).map(|fc| self.pal.text(fc)),
|
||||
),
|
||||
Column::Status => {
|
||||
// The status reads as its KPI icon (round 12 #11), drawn
|
||||
// in the status colour so it matches the dashboard card.
|
||||
@@ -1664,10 +1791,10 @@ impl App {
|
||||
format!("Open {n} miners in browser")
|
||||
};
|
||||
menu.menu_append(ID_CTX_OPEN, &open);
|
||||
// While a firmware flash holds the exclusive lock, offer only the
|
||||
// read-only "Open in browser" action; every network action is refused
|
||||
// anyway, so don't dangle them in the menu.
|
||||
if self.flashing {
|
||||
// While a firmware flash or a stock install/restore holds the exclusive
|
||||
// lock, offer only the read-only "Open in browser" action; every network
|
||||
// action is refused anyway, so don't dangle them in the menu.
|
||||
if self.flashing || self.stock_op.is_some() {
|
||||
self.pending_popup = Some((t, menu));
|
||||
return;
|
||||
}
|
||||
@@ -1758,6 +1885,17 @@ impl App {
|
||||
// the vendor installers cover the current workflow. (ID_CTX_FLASH and the
|
||||
// flash dialog remain in the code, just not surfaced here.)
|
||||
let _ = ID_CTX_FLASH;
|
||||
// Alkane OS install/uninstall via the toolkit's own self-contained,
|
||||
// network-only engine (stock <-> alkane). Offered for any selection: the
|
||||
// engine gates on board compatibility and a typed FLASH confirmation, so
|
||||
// this is safe to surface without relying on asic-rs firmware detection
|
||||
// (a board on genuine stock often does not identify cleanly).
|
||||
menu.menu_append_separator();
|
||||
menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS (from stock)...");
|
||||
menu.menu_append(
|
||||
ID_CTX_UNINSTALL_ALKANE,
|
||||
"Uninstall alkane OS (restore to stock)...",
|
||||
);
|
||||
self.pending_popup = Some((t, menu));
|
||||
}
|
||||
|
||||
@@ -2025,8 +2163,8 @@ impl App {
|
||||
// This path sets self.action directly, so it needs start_action's full
|
||||
// exclusivity guard: don't write pools during a restore or a live scan
|
||||
// (round 18 #12).
|
||||
if self.restore.is_some() {
|
||||
wx_rs::set_status_text("restore-to-stock in progress -- wait for it to finish");
|
||||
if self.restore.is_some() || self.stock_op.is_some() {
|
||||
wx_rs::set_status_text("a stock install/restore is in progress -- wait for it to finish");
|
||||
return;
|
||||
}
|
||||
if self.scanning {
|
||||
@@ -2122,8 +2260,8 @@ impl App {
|
||||
}
|
||||
// A restore-to-stock is reverting + rebooting miners; a config action mid-
|
||||
// revert could hit a unit in an undefined state (round 18 #12).
|
||||
if self.restore.is_some() {
|
||||
wx_rs::set_status_text("restore-to-stock in progress -- wait for it to finish");
|
||||
if self.restore.is_some() || self.stock_op.is_some() {
|
||||
wx_rs::set_status_text("a stock install/restore is in progress -- wait for it to finish");
|
||||
return;
|
||||
}
|
||||
// A scan is opening its own connections to these same miners; a mutating
|
||||
@@ -2358,6 +2496,7 @@ impl App {
|
||||
|| self.action.is_some()
|
||||
|| self.refresh.is_some()
|
||||
|| self.restore.is_some()
|
||||
|| self.stock_op.is_some()
|
||||
{
|
||||
wx_rs::set_status_text(
|
||||
"busy (scan/action/restore in progress) -- try again once it finishes",
|
||||
@@ -2441,6 +2580,401 @@ impl App {
|
||||
let _ = oks;
|
||||
}
|
||||
|
||||
/// True when any hardware-touching job is in flight. A new install/uninstall
|
||||
/// must not start while a scan, config action, refresh, flash, restore, or
|
||||
/// another stock op is running (they would race on the same boards).
|
||||
fn hardware_busy(&self) -> bool {
|
||||
self.flashing
|
||||
|| self.scanning
|
||||
|| self.action.is_some()
|
||||
|| self.refresh.is_some()
|
||||
|| self.restore.is_some()
|
||||
|| self.stock_op.is_some()
|
||||
}
|
||||
|
||||
/// Build the "Install alkane OS (from stock)" dialog: a scanned list of
|
||||
/// alkane-os releases to pick from, an optional board credential, the
|
||||
/// allow-unsigned (bench) toggle, and a typed FLASH confirmation. The install
|
||||
/// runs over the network via the toolkit's own compiled-in from-stock engine.
|
||||
fn build_install_dialog(&mut self) -> Option<Widget> {
|
||||
if self.hardware_busy() {
|
||||
wx_rs::set_status_text("busy -- try again once the current operation finishes");
|
||||
return None;
|
||||
}
|
||||
let ips = self.selected_ip_list();
|
||||
if ips.is_empty() {
|
||||
wx_rs::set_status_text("select a board to install onto");
|
||||
return None;
|
||||
}
|
||||
let board = self.install_board.clone();
|
||||
|
||||
// Scan alkane-os releases from Gitea (newest first), keeping those that
|
||||
// carry an .afw for this board. One quick API call, done synchronously so
|
||||
// the picker is populated when the dialog opens.
|
||||
wx_rs::set_status_text("scanning alkane-os releases...");
|
||||
let releases: Vec<ReleaseInfo> = match fetch::list_releases(&ReleaseSource::alkane_os()) {
|
||||
Ok(list) => list
|
||||
.into_iter()
|
||||
.filter(|r| !r.draft && r.asset_for_board(&board).is_some())
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
wx_rs::set_status_text(&format!("could not list releases: {e}"));
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
self.install_releases = releases;
|
||||
self.install_ips = ips.clone();
|
||||
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, "Install alkane OS (from stock)");
|
||||
let root = Widget::box_sizer(true);
|
||||
let n = ips.len();
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&format!(
|
||||
"Install alkane OS onto {n} board(s) currently on stock:\n{}",
|
||||
ips.join(", ")
|
||||
),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
12,
|
||||
);
|
||||
root.add(
|
||||
Widget::static_text(dlg, &format!("Target board: {board}")),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
12,
|
||||
);
|
||||
root.add(
|
||||
Widget::static_text(dlg, "Release to install (newest first):"),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let choice = Widget::choice(dlg, ID_INSTALL_RELEASE_CHOICE);
|
||||
if self.install_releases.is_empty() {
|
||||
choice.choice_append("(no release with an .afw for this board was found)");
|
||||
} else {
|
||||
for (i, r) in self.install_releases.iter().enumerate() {
|
||||
let tag = if r.tag.is_empty() {
|
||||
r.name.as_str()
|
||||
} else {
|
||||
r.tag.as_str()
|
||||
};
|
||||
let kind = if r.prerelease { " [pre-release]" } else { "" };
|
||||
let latest = if i == 0 { " (latest)" } else { "" };
|
||||
let date = r.published_at.split('T').next().unwrap_or("");
|
||||
choice.choice_append(&format!("{tag}{kind} {date}{latest}"));
|
||||
}
|
||||
choice.choice_set_selection(0);
|
||||
}
|
||||
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.install_release_choice = choice;
|
||||
|
||||
root.add(
|
||||
Widget::static_text(dlg, "Board password (optional):"),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let pass = Widget::text_ctrl(dlg, false);
|
||||
root.add(pass, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.install_pass_input = pass;
|
||||
|
||||
// Current bench .afw files are unsigned (SHA-256 integrity, no Ed25519).
|
||||
let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)");
|
||||
unsigned.set_checked(true);
|
||||
root.add(unsigned, 0, sf::BORDER_ALL, 12);
|
||||
self.install_unsigned_check = unsigned;
|
||||
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
"This reflashes the control board. Type FLASH to confirm:",
|
||||
),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let confirm = Widget::text_ctrl(dlg, false);
|
||||
root.add(confirm, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.install_confirm_input = confirm;
|
||||
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(
|
||||
Widget::button(dlg, "Install", ID_INSTALL_OK),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
btns.add(
|
||||
Widget::button(dlg, "Cancel", ID_INSTALL_CANCEL),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(540, 440);
|
||||
dlg.fit(dlg);
|
||||
self.install_dialog = dlg;
|
||||
wx_rs::set_status_text(&format!(
|
||||
"{} release(s) available for {board}",
|
||||
self.install_releases.len()
|
||||
));
|
||||
Some(dlg)
|
||||
}
|
||||
|
||||
/// Apply the install confirmation: validate the typed keyword, resolve the
|
||||
/// chosen release asset, and start the network-only from-stock install.
|
||||
fn apply_install_confirm(&mut self) {
|
||||
if self.hardware_busy() {
|
||||
wx_rs::set_status_text("busy -- try again once the current operation finishes");
|
||||
self.install_dialog.close(0);
|
||||
return;
|
||||
}
|
||||
if !flash_confirmed(&self.install_confirm_input.get_value()) {
|
||||
wx_rs::set_status_text("type FLASH to confirm the install");
|
||||
return;
|
||||
}
|
||||
let idx = self.install_release_choice.choice_get_selection();
|
||||
if idx < 0 || self.install_releases.is_empty() {
|
||||
wx_rs::set_status_text("no release selected");
|
||||
return;
|
||||
}
|
||||
let board = self.install_board.clone();
|
||||
let Some(release) = self.install_releases.get(idx as usize) else {
|
||||
wx_rs::set_status_text("no release selected");
|
||||
return;
|
||||
};
|
||||
let Some(asset) = release.asset_for_board(&board) else {
|
||||
wx_rs::set_status_text("the selected release has no .afw for this board");
|
||||
return;
|
||||
};
|
||||
let source = AfwChoice {
|
||||
name: asset.name.clone(),
|
||||
url: asset.url.clone(),
|
||||
};
|
||||
let asset_name = asset.name.clone();
|
||||
let allow_unsigned = self.install_unsigned_check.is_checked();
|
||||
let password = {
|
||||
let p = self.install_pass_input.get_value();
|
||||
if p.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(p)
|
||||
}
|
||||
};
|
||||
let ips = std::mem::take(&mut self.install_ips);
|
||||
if ips.is_empty() {
|
||||
self.install_dialog.close(0);
|
||||
return;
|
||||
}
|
||||
self.install_dialog.close(1);
|
||||
crate::logs::log(format!(
|
||||
"install alkane OS onto {} board(s) from {}",
|
||||
ips.len(),
|
||||
asset_name
|
||||
));
|
||||
self.set_op_status(&ips, "installing...");
|
||||
self.stock_op = Some(stock_ops::start_install(
|
||||
ips,
|
||||
board,
|
||||
source,
|
||||
allow_unsigned,
|
||||
password,
|
||||
));
|
||||
}
|
||||
|
||||
/// Build the "Uninstall alkane OS (restore to stock)" dialog: the board's
|
||||
/// alkane root credential and a typed FLASH confirmation.
|
||||
fn build_uninstall_dialog(&mut self) -> Option<Widget> {
|
||||
if self.hardware_busy() {
|
||||
wx_rs::set_status_text("busy -- try again once the current operation finishes");
|
||||
return None;
|
||||
}
|
||||
let ips = self.selected_ip_list();
|
||||
if ips.is_empty() {
|
||||
wx_rs::set_status_text("select an alkane board to restore to stock");
|
||||
return None;
|
||||
}
|
||||
self.uninstall_ips = ips.clone();
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, "Uninstall alkane OS (restore to stock)");
|
||||
let root = Widget::box_sizer(true);
|
||||
let n = ips.len();
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&format!(
|
||||
"Restore {n} alkane board(s) to genuine stock:\n{}",
|
||||
ips.join(", ")
|
||||
),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
12,
|
||||
);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
"Genuine Bitmain stock firmware file for this board\n(an OTA update .tar.gz or an SD recovery .zip):",
|
||||
),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let fw = Widget::text_ctrl(dlg, false);
|
||||
root.add(fw, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.uninstall_firmware_input = fw;
|
||||
|
||||
root.add(
|
||||
Widget::static_text(dlg, "Board (alkane root) password (optional):"),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let pass = Widget::text_ctrl(dlg, false);
|
||||
root.add(pass, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.uninstall_pass_input = pass;
|
||||
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
"This reflashes the board back to stock (BOOT.bin preserved).\nType FLASH to confirm:",
|
||||
),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
|
||||
12,
|
||||
);
|
||||
let confirm = Widget::text_ctrl(dlg, false);
|
||||
root.add(confirm, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
|
||||
self.uninstall_confirm_input = confirm;
|
||||
let btns = Widget::box_sizer(false);
|
||||
btns.add_stretch(1);
|
||||
btns.add(
|
||||
Widget::button(dlg, "Restore to stock", ID_UNINSTALL_OK),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
btns.add(
|
||||
Widget::button(dlg, "Cancel", ID_UNINSTALL_CANCEL),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(540, 440);
|
||||
dlg.fit(dlg);
|
||||
self.uninstall_dialog = dlg;
|
||||
Some(dlg)
|
||||
}
|
||||
|
||||
fn apply_uninstall_confirm(&mut self) {
|
||||
if self.hardware_busy() {
|
||||
wx_rs::set_status_text("busy -- try again once the current operation finishes");
|
||||
self.uninstall_dialog.close(0);
|
||||
return;
|
||||
}
|
||||
if !flash_confirmed(&self.uninstall_confirm_input.get_value()) {
|
||||
wx_rs::set_status_text("type FLASH to confirm the restore");
|
||||
return;
|
||||
}
|
||||
let firmware = self.uninstall_firmware_input.get_value();
|
||||
let firmware = firmware.trim();
|
||||
if firmware.is_empty() {
|
||||
wx_rs::set_status_text("a genuine Bitmain stock firmware file is required");
|
||||
return;
|
||||
}
|
||||
if !std::path::Path::new(firmware).is_file() {
|
||||
wx_rs::set_status_text(&format!("firmware file not found: {firmware}"));
|
||||
return;
|
||||
}
|
||||
let password = {
|
||||
let p = self.uninstall_pass_input.get_value();
|
||||
if p.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(p)
|
||||
}
|
||||
};
|
||||
let ips = std::mem::take(&mut self.uninstall_ips);
|
||||
if ips.is_empty() {
|
||||
self.uninstall_dialog.close(0);
|
||||
return;
|
||||
}
|
||||
self.uninstall_dialog.close(1);
|
||||
crate::logs::log(format!("restore {} alkane board(s) to stock", ips.len()));
|
||||
self.set_op_status(&ips, "restoring...");
|
||||
self.stock_op = Some(stock_ops::start_restore(
|
||||
ips,
|
||||
std::path::PathBuf::from(firmware),
|
||||
password,
|
||||
));
|
||||
}
|
||||
|
||||
/// Drain the alkane install/uninstall job: progress onto the status bar,
|
||||
/// per-board results into the op-status, and finalisation on Done.
|
||||
fn drain_stock_op(&mut self) {
|
||||
let Some(h) = &self.stock_op else { return };
|
||||
let mut done = false;
|
||||
let mut oks = 0usize;
|
||||
let mut fails: Vec<String> = Vec::new();
|
||||
let mut op_clear: Vec<String> = Vec::new();
|
||||
let mut progress: Option<String> = None;
|
||||
loop {
|
||||
match h.rx.try_recv() {
|
||||
Ok(StockMsg::Started) => {}
|
||||
Ok(StockMsg::Progress(s)) => progress = Some(s),
|
||||
Ok(StockMsg::Result { ip, ok, detail }) => {
|
||||
if !ip.is_empty() {
|
||||
op_clear.push(ip.clone());
|
||||
}
|
||||
if ok {
|
||||
oks += 1;
|
||||
} else {
|
||||
fails.push(format!("{ip}: {detail}"));
|
||||
}
|
||||
}
|
||||
Ok(StockMsg::Done) => {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => break,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for ip in &op_clear {
|
||||
self.op_status.remove(ip);
|
||||
}
|
||||
if let Some(p) = progress {
|
||||
wx_rs::set_status_text(&p);
|
||||
}
|
||||
if done {
|
||||
self.stock_op = None;
|
||||
self.op_status
|
||||
.retain(|_, v| v != "installing..." && v != "restoring...");
|
||||
}
|
||||
if !op_clear.is_empty() || done {
|
||||
self.fill_rows();
|
||||
}
|
||||
if done {
|
||||
if !fails.is_empty() {
|
||||
self.set_error_indicator(&format!("stock op: {} failed", fails.len()));
|
||||
} else if oks > 0 {
|
||||
wx_rs::set_status_text(&format!("stock op complete: {oks} ok"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the access (lock-state) probe on the selected miners, using the
|
||||
/// saved scan (web) credentials (defaulting to root/root if none are set).
|
||||
fn start_access_probe(&mut self) {
|
||||
@@ -2574,6 +3108,8 @@ impl App {
|
||||
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
|
||||
ID_CTX_VIEW_LOG => self.start_log_fetch(),
|
||||
ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(),
|
||||
ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(),
|
||||
ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(),
|
||||
ID_CTX_POOLS => return self.build_pools_dialog(),
|
||||
ID_CTX_FLASH => {
|
||||
// A flash needs exclusive hardware access; don't even prompt if
|
||||
@@ -2583,6 +3119,7 @@ impl App {
|
||||
|| self.action.is_some()
|
||||
|| self.refresh.is_some()
|
||||
|| self.restore.is_some()
|
||||
|| self.stock_op.is_some()
|
||||
{
|
||||
wx_rs::set_status_text(
|
||||
"busy (scan/action in progress) -- try again once it finishes",
|
||||
@@ -3071,6 +3608,7 @@ impl App {
|
||||
|| self.action.is_some()
|
||||
|| self.refresh.is_some()
|
||||
|| self.restore.is_some()
|
||||
|| self.stock_op.is_some()
|
||||
{
|
||||
wx_rs::set_status_text("busy (scan/action started) -- flash cancelled, try again");
|
||||
return;
|
||||
@@ -3651,6 +4189,7 @@ impl App {
|
||||
self.drain_refresh();
|
||||
self.drain_access_probe();
|
||||
self.drain_restore();
|
||||
self.drain_stock_op();
|
||||
self.drain_report();
|
||||
// A completed background log fetch yields a viewer dialog to show; return
|
||||
// it so `dispatch` presents it modally after the App borrow is released
|
||||
@@ -3722,7 +4261,7 @@ impl App {
|
||||
// Symmetric to start_action's scan guard: don't start a scan (including an
|
||||
// auto-rescan) while a config action or restore is writing to miners, so
|
||||
// the two never race on the same unit (round 18 #12).
|
||||
if self.action.is_some() || self.restore.is_some() {
|
||||
if self.action.is_some() || self.restore.is_some() || self.stock_op.is_some() {
|
||||
wx_rs::set_status_text("operation in progress -- scan deferred");
|
||||
return false;
|
||||
}
|
||||
@@ -5177,6 +5716,16 @@ impl App {
|
||||
self.pending_restore.clear();
|
||||
self.restore_dialog.close(0);
|
||||
}
|
||||
ID_INSTALL_OK => self.apply_install_confirm(),
|
||||
ID_INSTALL_CANCEL => {
|
||||
self.install_ips.clear();
|
||||
self.install_dialog.close(0);
|
||||
}
|
||||
ID_UNINSTALL_OK => self.apply_uninstall_confirm(),
|
||||
ID_UNINSTALL_CANCEL => {
|
||||
self.uninstall_ips.clear();
|
||||
self.uninstall_dialog.close(0);
|
||||
}
|
||||
ID_POOLS_OK => self.apply_pools(),
|
||||
ID_POOLS_CANCEL => self.pools_dialog.close(0),
|
||||
// Pool-preset manager buttons (round 18 #8b).
|
||||
@@ -5587,9 +6136,35 @@ mod tests {
|
||||
red: (255, 0, 0),
|
||||
accent: (0, 0, 255),
|
||||
zebra: (245, 245, 245),
|
||||
text_bgs: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readable_reaches_aa_contrast_on_every_background() {
|
||||
let light = [(255, 255, 255), (245, 245, 245)];
|
||||
let dark = [(30, 30, 30), (41, 41, 41), (44, 44, 44)];
|
||||
for fw in [
|
||||
"braiins", "luxos", "vnish", "bixbit", "epic", "hiveon", "alkane",
|
||||
] {
|
||||
let c = firmware_color(fw).unwrap();
|
||||
for bgs in [&light[..], &dark[..]] {
|
||||
let r = readable(c, bgs);
|
||||
for &bg in bgs {
|
||||
assert!(
|
||||
contrast_ratio(r, bg) >= MIN_TEXT_CONTRAST,
|
||||
"{fw} {r:?} on {bg:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Already-readable colours are left alone; hue survives the nudge.
|
||||
assert_eq!(readable((0, 0, 0), &light), (0, 0, 0));
|
||||
let gold = readable((185, 150, 20), &light);
|
||||
assert!(gold.0 > gold.1 && gold.1 > gold.2, "still gold: {gold:?}");
|
||||
assert!((contrast_ratio((255, 255, 255), (0, 0, 0)) - 21.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tint_toward_endpoints_and_midpoint() {
|
||||
let a = (10, 20, 30);
|
||||
|
||||
+102
-15
@@ -1,7 +1,13 @@
|
||||
# Installing and removing alkane-os
|
||||
|
||||
The CLI (`alkane-cli afw ...`) is the supported flashing path. In-app (GUI)
|
||||
flashing is disabled while that path is reworked; it will call the same engine.
|
||||
Two front-ends drive the same self-contained engine:
|
||||
|
||||
- The CLI (`alkane-cli afw ...`), documented below, is the scriptable path.
|
||||
- The GUI (`alkane-toolkit`) can scan the fleet, then right-click a board to
|
||||
install alkane-os onto it from stock or restore it to stock. See
|
||||
"GUI (right-click install / uninstall)" at the end. (The GUI's older asic-rs
|
||||
firmware-upload path stays disabled; these two actions use the compiled-in
|
||||
network-only engine, the same one the CLI uses.)
|
||||
|
||||
## Compatible miners
|
||||
|
||||
@@ -38,34 +44,115 @@ on the command line, never stored by the toolkit.
|
||||
|
||||
Writing our first image onto a board that is still on genuine stock (past the
|
||||
stock gates and getting root) is done by the toolkit itself, over the network.
|
||||
The method is compiled into this binary; nothing else needs to be installed on
|
||||
your machine. Add `--from-stock`:
|
||||
The method is part of this binary; nothing else needs to be installed on your
|
||||
machine. On first use it fetches a small set of per-board assets from our Gitea
|
||||
(repo `blueflare/alkane-stock-assets`, release `zynq-7010-v1`) and caches them
|
||||
locally, verifying each against a known SHA-256. That repo is public, so no token
|
||||
is needed for the stock assets. The asset base URL can be overridden with
|
||||
`ALKANE_STOCK_ASSETS_BASE`.
|
||||
|
||||
Add `--from-stock` (the token below is only to resolve `--latest` from the
|
||||
private alkane-os release repo; a local `.afw` needs no token):
|
||||
|
||||
```
|
||||
export ALKANE_RELEASE_TOKEN=<your-gitea-token>
|
||||
alkane-cli afw install --latest --board zynq-7010 --host <miner-ip> \
|
||||
--from-stock --confirm FLASH
|
||||
```
|
||||
|
||||
The toolkit acquires and verifies the `.afw`, gates on compatibility, performs
|
||||
the network-only stock-side install, then you verify the board came up as
|
||||
alkane:
|
||||
The toolkit acquires and verifies the `.afw`, gates on compatibility, fetches
|
||||
and verifies its assets, performs the network-only stock-side install, then you
|
||||
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)
|
||||
|
||||
```
|
||||
alkane-cli afw restore-stock --host <miner-ip> --confirm FLASH
|
||||
alkane-cli afw restore-stock --host <miner-ip> \
|
||||
--stock-firmware <genuine-Bitmain-firmware> \
|
||||
--password-file <alkane-root-pw> --confirm FLASH
|
||||
```
|
||||
|
||||
Returning an aftermarket board to genuine stock is also done by the toolkit
|
||||
itself, over the network. You then verify independently that the board no longer
|
||||
answers as alkane and presents its stock OS.
|
||||
Returning an aftermarket board to genuine stock is done by the toolkit itself,
|
||||
over the network. It writes the genuine Bitmain stock **kernel and rootfs** -
|
||||
parsed from a vendor firmware file you supply with `--stock-firmware` (an OTA
|
||||
update `.tar.gz` or an SD recovery `.zip` for the board) - back to NAND,
|
||||
preserving BOOT.bin.
|
||||
|
||||
The one piece that is NOT in Bitmain's distributable firmware is the kernel
|
||||
**device tree**: it is factory-provisioned and preserved by every vendor update,
|
||||
so no OTA/SD package ships it. The toolkit supplies the correct per-board dtb
|
||||
itself (fetched + verified from the public assets repo, so no token is needed)
|
||||
and pairs it with the genuine kernel/rootfs. The board's alkane root credential
|
||||
is given with `--password-file` (or
|
||||
`ALKANE_BOARD_PASSWORD`/`ALKANE_BOARD_PASSWORD_FILE`).
|
||||
|
||||
After a restore the board returns to stock under its stock MAC and typically
|
||||
takes a new DHCP lease, so it may not reappear on the same address; verify
|
||||
independently that the board no longer answers as alkane and presents its stock
|
||||
OS.
|
||||
|
||||
## GUI (right-click install / uninstall)
|
||||
|
||||
The GUI binary is `alkane-toolkit`. Launch it, let the scan list the fleet, then
|
||||
right-click one or more boards and choose:
|
||||
|
||||
- "Install alkane OS (from stock)..." - scans the alkane-os releases on Gitea,
|
||||
lets you pick one (newest first; pre-releases are marked), optionally takes a
|
||||
board password and an "allow unsigned .afw (bench)" toggle, and - after you
|
||||
type FLASH to confirm - downloads/verifies the `.afw` and installs it onto each
|
||||
selected board over the network, via the same compiled-in from-stock engine the
|
||||
CLI uses.
|
||||
- "Uninstall alkane OS (restore to stock)..." - takes the board's alkane root
|
||||
password and a typed FLASH confirmation, then restores each selected board to
|
||||
genuine stock over the network.
|
||||
|
||||
Progress and per-board results appear on the status bar; verify board state
|
||||
independently afterwards (the GUI does not claim liveness on its own).
|
||||
|
||||
Release scanning reads the private `alkane-os` repo, so it needs a Gitea token.
|
||||
A read-only token can be baked into the GUI at build time
|
||||
(`ALKANE_EMBEDDED_TOKEN=<token>` when building), so the shipped binary scans
|
||||
releases with no setup; otherwise set `ALKANE_RELEASE_TOKEN` (or `GITEA_TOKEN`)
|
||||
in the environment before launching. The stock-asset fetch needs no token (that
|
||||
repo is public), so install-from-stock and restore-to-stock work without one -
|
||||
only the release picker needs it.
|
||||
|
||||
Runtime dependencies (Linux): the GUI links wxWidgets 3.2 (wxGTK) and GTK 3, so
|
||||
the target machine needs `libwxgtk3.2-1` and `libgtk-3-0` installed.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
Subject: [PATCH 0011] Build on wxWidgets 3.2: version-guard the 3.3 appearance API and link GTK libs
|
||||
|
||||
diff -ruN a/build.rs b/build.rs
|
||||
--- a/build.rs
|
||||
+++ b/build.rs
|
||||
@@ -309,6 +309,25 @@
|
||||
for f in gtk_cflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
}
|
||||
+ // ...and GTK's own shared libraries at link time. `wx-config --libs`
|
||||
+ // lists only the wx libraries, not the GTK libraries the widget bridge
|
||||
+ // calls directly (gtk_*, g_*), so without this the final link fails with
|
||||
+ // undefined GTK symbols. Best-effort: empty if pkg-config/gtk3-dev is
|
||||
+ // missing, in which case the GTK-only bridge code was also compiled out.
|
||||
+ let gtk_libs = Command::new("pkg-config")
|
||||
+ .args(["--libs", "gtk+-3.0"])
|
||||
+ .output()
|
||||
+ .ok()
|
||||
+ .filter(|o| o.status.success())
|
||||
+ .and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
+ .unwrap_or_default();
|
||||
+ for f in gtk_libs.split_whitespace() {
|
||||
+ if let Some(lib) = f.strip_prefix("-l") {
|
||||
+ println!("cargo:rustc-link-lib={}", lib);
|
||||
+ } else if let Some(path) = f.strip_prefix("-L") {
|
||||
+ println!("cargo:rustc-link-search=native={}", path);
|
||||
+ }
|
||||
+ }
|
||||
}
|
||||
if is_windows() {
|
||||
// Ship one self-contained .exe: link the C++ runtime statically rather
|
||||
diff -ruN a/cpp_src/wxbridge.cpp b/cpp_src/wxbridge.cpp
|
||||
--- a/cpp_src/wxbridge.cpp
|
||||
+++ b/cpp_src/wxbridge.cpp
|
||||
@@ -375,6 +375,10 @@
|
||||
// then returns CannotChange). System follows the desktop: the GTK theme's
|
||||
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
|
||||
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
|
||||
+ // The explicit appearance API (wxApp::Appearance / SetAppearance /
|
||||
+ // MSWEnableDarkMode) only exists in wxWidgets >= 3.3. On 3.2.x the GTK/Win
|
||||
+ // system theme is still followed; we just cannot force it via ALKANE_APPEARANCE.
|
||||
+#if wxCHECK_VERSION(3, 3, 0)
|
||||
{
|
||||
wxString pref;
|
||||
wxGetEnv("ALKANE_APPEARANCE", &pref);
|
||||
@@ -394,6 +398,7 @@
|
||||
wxTheApp->SetAppearance(appearance);
|
||||
#endif
|
||||
}
|
||||
+#endif
|
||||
wxTheApp->OnInit();
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
@@ -0,0 +1,17 @@
|
||||
Subject: [PATCH 0011] macOS self-test snapshot includes the window background
|
||||
|
||||
--- a/cpp_src/osx_native.mm
|
||||
+++ b/cpp_src/osx_native.mm
|
||||
@@ -46,7 +46,11 @@
|
||||
wxMilliSleep(30);
|
||||
}
|
||||
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
- NSView* view = [nsw contentView];
|
||||
+ // The content view's superview (the window's frame view) also draws the
|
||||
+ // window background and title bar. The content view alone leaves every
|
||||
+ // area the app's panels do not paint transparent, which read as white.
|
||||
+ NSView* view = [[nsw contentView] superview];
|
||||
+ if (!view) view = [nsw contentView];
|
||||
if (!view) return 0;
|
||||
NSRect rect = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
Vendored
+1
@@ -29,6 +29,7 @@ later changes go in new patches.
|
||||
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
|
||||
| 0009 | macOS: wxOSX (universal static) through `wx-config`, logical sizes on Apple, clang compiler runtime for `@available` |
|
||||
| 0010 | macOS table: native alternating rows instead of the unclipped custom-cell background fill (it hid neighbouring cells' text), theme-aware text colour, `osx_native.mm`, self-test window snapshot |
|
||||
| 0011 | macOS self-test snapshot captures the window's frame view, so areas the app does not paint show the real window background instead of transparency |
|
||||
|
||||
History: the round 19 health-tooltip fix (GTK tip area converted from
|
||||
bin-window to widget coordinates) used to be a separate patch on top of an
|
||||
|
||||
+19
@@ -309,6 +309,25 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
for f in gtk_cflags.split_whitespace() {
|
||||
build.flag(f);
|
||||
}
|
||||
// ...and GTK's own shared libraries at link time. `wx-config --libs`
|
||||
// lists only the wx libraries, not the GTK libraries the widget bridge
|
||||
// calls directly (gtk_*, g_*), so without this the final link fails with
|
||||
// undefined GTK symbols. Best-effort: empty if pkg-config/gtk3-dev is
|
||||
// missing, in which case the GTK-only bridge code was also compiled out.
|
||||
let gtk_libs = Command::new("pkg-config")
|
||||
.args(["--libs", "gtk+-3.0"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.unwrap_or_default();
|
||||
for f in gtk_libs.split_whitespace() {
|
||||
if let Some(lib) = f.strip_prefix("-l") {
|
||||
println!("cargo:rustc-link-lib={}", lib);
|
||||
} else if let Some(path) = f.strip_prefix("-L") {
|
||||
println!("cargo:rustc-link-search=native={}", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_windows() {
|
||||
// Ship one self-contained .exe: link the C++ runtime statically rather
|
||||
|
||||
@@ -46,7 +46,11 @@ int wxbr_osx_snapshot(void* win, const char* path) {
|
||||
wxMilliSleep(30);
|
||||
}
|
||||
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
NSView* view = [nsw contentView];
|
||||
// The content view's superview (the window's frame view) also draws the
|
||||
// window background and title bar. The content view alone leaves every
|
||||
// area the app's panels do not paint transparent, which read as white.
|
||||
NSView* view = [[nsw contentView] superview];
|
||||
if (!view) view = [nsw contentView];
|
||||
if (!view) return 0;
|
||||
NSRect rect = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
|
||||
@@ -375,6 +375,10 @@ extern "C" {
|
||||
// then returns CannotChange). System follows the desktop: the GTK theme's
|
||||
// colour scheme, or the Windows 10/11 "app mode" setting, which wxMSW
|
||||
// otherwise ignores and stays light. ALKANE_APPEARANCE=light|dark forces one.
|
||||
// The explicit appearance API (wxApp::Appearance / SetAppearance /
|
||||
// MSWEnableDarkMode) only exists in wxWidgets >= 3.3. On 3.2.x the GTK/Win
|
||||
// system theme is still followed; we just cannot force it via ALKANE_APPEARANCE.
|
||||
#if wxCHECK_VERSION(3, 3, 0)
|
||||
{
|
||||
wxString pref;
|
||||
wxGetEnv("ALKANE_APPEARANCE", &pref);
|
||||
@@ -394,6 +398,7 @@ extern "C" {
|
||||
wxTheApp->SetAppearance(appearance);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
wxTheApp->OnInit();
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
|
||||
Reference in New Issue
Block a user