zynq: ECC-preserving (OOB) on-board restore so return-to-stock does not brick

The alkane kernel writes NAND with soft-BCH 8b/512 ECC, which the stock Zynq
U-Boot nandboot reader cannot decode: an alkane-side `nandwrite -p` of the boot
slots leaves them unreadable by the stock boot chain ("ECC unrecoverable" loop),
and these boards have no U-Boot prompt, so recovery is SD-card only. This was
the S17 .111 brick of 2026-11-13.

Make the on-board backup/restore preserve the genuine stock OOB (the stock ECC
bytes) so a restore writes the boot slots byte-identical to original stock:

- Backup format v2 ("ALKSTKB2"): carve captures each boot image's data+OOB with
  nanddump and stores the blob in the stock-backup region; the manifest records
  blob offset/length and the on-NAND data length. v1 (data-only) backups are
  detected and refused for restore (they cannot reproduce stock ECC).
- restore_from_onboard: a scratch-block self-check proves `nandwrite --noecc
  --oob` round-trips the stock OOB on this board BEFORE any boot slot is written
  (abort, never brick); each slot is written raw (--noecc --oob) and read back
  WITH OOB; the board reboots only if all three slots are byte-identical to the
  backup.
- restore_to_stock (vendor FILE path): disabled on Zynq - a vendor file carries
  no OOB, so it cannot be restored without recomputing soft-BCH ECC (brick). The
  safe network return-to-stock is restore_from_onboard.

Removes the ECC-recomputing copy_abs. 93 flash-crate tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 13:02:46 -06:00
co-authored by Claude Opus 4.8
parent 0873d2c79d
commit 036b44f6bb
+388 -160
View File
@@ -60,7 +60,19 @@ const SLOT_STOCK_BACKUP: u64 = 0x2000000;
/// Where the backup data lives inside the 32 MiB stock-backup region: the first
/// erase block holds the manifest, the images follow, each erase-block aligned.
const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000
const BK_MAGIC: &[u8; 8] = b"ALKSTKB1";
/// v1 (data-only) backup magic. v1 backups cannot be safely restored: they lack
/// the genuine stock OOB, so a restore recomputes the alkane soft-BCH ECC which
/// the stock boot chain cannot read (boot-loop brick).
const BK_MAGIC_V1: &[u8; 8] = b"ALKSTKB1";
/// v2 backup magic. v2 stores each boot image's genuine NAND data *with its OOB*
/// (the stock ECC bytes), so a restore writes the slots back via
/// `nandwrite --noecc --oob` byte-identical to original stock and the stock
/// boot chain reads them. See alkane-zynq-image-bringup.md, 2026-11-13.
const BK_MAGIC_V2: &[u8; 8] = b"ALKSTKB2";
/// Scratch erase block (the last block of the 32 MiB stock-backup region),
/// used to prove `nandwrite --noecc --oob` round-trips on this board's tools
/// before any boot slot is written. Never holds backup images or the manifest.
const BK_SCRATCH: u64 = OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE; // 0x7fe0000
fn round_up(value: u64, to: u64) -> u64 {
value.div_ceil(to) * to
@@ -352,32 +364,218 @@ fn write_abs(
Ok(())
}
/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst`
/// (used when carving the on-board stock backup). `dst` must be erase aligned.
fn copy_abs(
/// NAND page (write) size and OOB size for a partition, from sysfs. Needed to
/// reason about the data+OOB blob geometry and to run the OOB self-check.
fn oob_geometry(sh: &mut dyn Shell, dev: &str) -> Result<(u64, u64), StockError> {
let ws = sh
.exec(&format!("cat /sys/class/mtd/{dev}/writesize 2>/dev/null"))?
.trim()
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{dev}: no writesize in sysfs")))?;
let oob = sh
.exec(&format!("cat /sys/class/mtd/{dev}/oobsize 2>/dev/null"))?
.trim()
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{dev}: no oobsize in sysfs")))?;
if ws == 0 || oob == 0 {
return Err(StockError::Method(format!(
"{dev}: implausible NAND geometry (write {ws}, oob {oob})"
)));
}
Ok((ws, oob))
}
/// Dump `data_len` bytes of NAND at absolute `abs` *with OOB* into a board file,
/// returning (remote_path, blob_len). `data_len` is rounded up to a whole page
/// by the caller so `nanddump` emits only complete pages. The blob is data
/// interleaved with OOB exactly as `nanddump` emits it and `nandwrite --oob`
/// consumes it.
fn dump_with_oob(
sh: &mut dyn Shell,
table: &[Mtd],
src: u64,
dst: u64,
len: u64,
abs: u64,
data_len: u64,
label: &str,
) -> Result<(String, u64), StockError> {
let (dev, rel) = locate(table, abs, data_len)?;
let dev = dev.to_owned();
let remote = format!("/tmp/alk/{label}.oob");
sh.exec("mkdir -p /tmp/alk")?;
sh.exec_long(&format!(
"nanddump -s 0x{rel:x} -l {data_len} /dev/{dev} -f {remote} >/dev/null 2>&1 && echo DUMPED"
))
.and_then(|o| {
if o.contains("DUMPED") {
Ok(())
} else {
Err(StockError::Method(format!(
"{label}: nanddump (with OOB) failed: {o}"
)))
}
})?;
let blob_len = first_token(&sh.exec(&format!("wc -c < {remote}"))?)
.parse::<u64>()
.map_err(|_| StockError::Method(format!("{label}: cannot size the OOB blob")))?;
if blob_len <= data_len {
return Err(StockError::Method(format!(
"{label}: OOB blob {blob_len} B not larger than data {data_len} B - OOB was not \
captured (nanddump omitted OOB?). Refusing: a restore from this backup could not \
reproduce the stock ECC."
)));
}
Ok((remote, blob_len))
}
/// Store a board file verbatim into the backup region at absolute `abs` (opaque
/// bytes written as data with `nandwrite -p`; the backup region's own ECC is
/// irrelevant because the blob is read back from the data area with
/// `--omitoob`). Read-back-verified by md5 against the source file.
fn store_blob(
sh: &mut dyn Shell,
table: &[Mtd],
abs: u64,
remote: &str,
blob_len: u64,
label: &str,
) -> Result<(), StockError> {
let (sdev, srel) = locate(table, src, len)?;
let sdev = sdev.to_owned();
let (ddev, drel) = locate(table, dst, len)?;
let ddev = ddev.to_owned();
let blocks = round_up(len, ERASE) / ERASE;
let tmp = format!("/tmp/alk/{label}.bak");
sh.exec("mkdir -p /tmp/alk")?;
let out = sh.exec_long(&format!(
"nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \
flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \
rm -f {tmp} && echo COPIED"
))?;
if !out.contains("COPIED") {
if !abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label}: backup copy failed: {out}"
"{label}: blob dst 0x{abs:x} not erase-aligned"
)));
}
let (dev, rel) = locate(table, abs, blob_len)?;
let dev = dev.to_owned();
let blocks = round_up(blob_len, ERASE) / ERASE;
sh.exec_long(&format!(
"flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \
nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo STORED"
))
.and_then(|o| {
if o.contains("STORED") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: store blob failed: {o}")))
}
})?;
let want = first_token(&sh.exec(&format!("md5sum {remote}"))?);
let got = first_token(&sh.exec_long(&format!(
"nanddump -s 0x{rel:x} -l {blob_len} --omitoob /dev/{dev} 2>/dev/null | md5sum"
))?);
if want != got {
return Err(StockError::Method(format!(
"{label}: stored blob read-back md5 {got} != {want}"
)));
}
Ok(())
}
/// Prove `nandwrite --noecc --oob` + `nanddump` round-trip the genuine stock OOB
/// on this board, using the throwaway scratch block, BEFORE any boot slot is
/// written. The test vector is the first real page (data+OOB) of the kernel
/// backup blob, so this tests the exact bytes the restore will write. A board
/// whose tools ignore --noecc/--oob (e.g. the busybox applets) or lay the OOB
/// out differently fails here and the restore aborts untouched - the
/// alternative is an ECC-mismatch brick recoverable only by the SD card.
fn scratch_selfcheck(
sh: &mut dyn Shell,
table: &[Mtd],
kernel_blob_abs: u64,
) -> Result<(), StockError> {
let (sdev, srel) = locate(table, BK_SCRATCH, ERASE)?;
let sdev = sdev.to_owned();
let (ws, oob) = oob_geometry(sh, &sdev)?;
let page = ws + oob;
let (bdev, brel) = locate(table, kernel_blob_abs, page)?;
let bdev = bdev.to_owned();
sh.exec("mkdir -p /tmp/alk")?;
// Take the first page+OOB of the kernel blob (data area of the backup
// region), write it raw to scratch, read it back with OOB and compare.
let out = sh.exec_long(&format!(
"nanddump -s 0x{brel:x} -l {page} --omitoob /dev/{bdev} -f /tmp/alk/sc.in >/dev/null 2>&1 && \
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 && \
nandwrite --noecc --oob -s 0x{srel:x} /dev/{sdev} /tmp/alk/sc.in >/dev/null 2>&1 && \
nanddump -s 0x{srel:x} -l {ws} /dev/{sdev} -f /tmp/alk/sc.out >/dev/null 2>&1 && \
A=$(md5sum < /tmp/alk/sc.in) && B=$(md5sum < /tmp/alk/sc.out) && \
flash_erase /dev/{sdev} 0x{srel:x} 1 >/dev/null 2>&1 ; \
rm -f /tmp/alk/sc.in /tmp/alk/sc.out ; \
[ \"$A\" = \"$B\" ] && echo SCOK || echo SCFAIL"
))?;
if !out.contains("SCOK") {
return Err(StockError::Method(
"OOB self-check failed: `nandwrite --noecc --oob` does not round-trip the stock OOB on \
this board (busybox applet without --noecc/--oob, or a different OOB layout). Refusing \
to write the boot slots: an ECC-mismatch restore would brick the board (SD-card \
recovery only). The alkane image must ship full mtd-utils nandwrite/nanddump."
.into(),
));
}
Ok(())
}
/// Restore one boot slot from its v2 backup entry: retrieve the data+OOB blob
/// from the backup region, write it to the slot with `nandwrite --noecc --oob`
/// (reproducing the exact stock ECC), and read it back WITH OOB to confirm the
/// slot is byte-identical to original stock. Never reboots; the caller reboots
/// only after every slot verifies.
fn restore_slot_raw_oob(
sh: &mut dyn Shell,
table: &[Mtd],
entry: &BackupEntry,
dst_abs: u64,
label: &str,
) -> Result<(), StockError> {
if dst_abs < BOOTBIN_PRESERVE {
return Err(StockError::Method(format!(
"refusing to restore {label} at 0x{dst_abs:x}: inside preserved BOOT.bin"
)));
}
if !dst_abs.is_multiple_of(ERASE) {
return Err(StockError::Method(format!(
"{label} dst 0x{dst_abs:x} not erase-aligned"
)));
}
// Retrieve the opaque blob (data+OOB) from the backup region's data area.
let (bdev, brel) = locate(table, entry.blob_abs, entry.blob_len)?;
let bdev = bdev.to_owned();
let blob = format!("/tmp/alk/{label}.rst");
sh.exec("mkdir -p /tmp/alk")?;
sh.exec_long(&format!(
"nanddump -s 0x{brel:x} -l {blen} --omitoob /dev/{bdev} -f {blob} >/dev/null 2>&1 && echo GOT",
blen = entry.blob_len
))
.and_then(|o| {
if o.contains("GOT") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: blob retrieve failed: {o}")))
}
})?;
// Write raw (data+OOB) to the boot slot.
let (ddev, drel) = locate(table, dst_abs, entry.data_len)?;
let ddev = ddev.to_owned();
let blocks = round_up(entry.data_len, ERASE) / ERASE;
sh.exec_long(&format!(
"flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
nandwrite --noecc --oob -s 0x{drel:x} /dev/{ddev} {blob} >/dev/null 2>&1 && echo WROTE"
))
.and_then(|o| {
if o.contains("WROTE") {
Ok(())
} else {
Err(StockError::Method(format!("{label}: raw restore write failed: {o}")))
}
})?;
// Read back WITH OOB and compare to the blob: byte-identical data+ECC.
let want = first_token(&sh.exec(&format!("md5sum {blob}"))?);
let got = first_token(&sh.exec_long(&format!(
"nanddump -s 0x{drel:x} -l {dlen} /dev/{ddev} 2>/dev/null | md5sum",
dlen = entry.data_len
))?);
sh.exec(&format!("rm -f {blob}"))?;
if want != got {
return Err(StockError::Method(format!(
"{label}: restored slot read-back md5 {got} != backup {want} (data+OOB mismatch); \
NOT rebooting"
)));
}
Ok(())
@@ -430,34 +628,37 @@ fn first_token(s: &str) -> String {
// On-board stock backup manifest
// ---------------------------------------------------------------------------
#[derive(Clone, Debug)]
/// One backed-up boot image: where its genuine data+OOB blob lives in the
/// stock-backup region (`blob_abs`), the blob's byte length (`blob_len`, data
/// interleaved with OOB as `nanddump` emits it), and the original on-NAND data
/// length (`data_len`, OOB excluded) that the boot slot occupies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct BackupEntry {
blob_abs: u64,
blob_len: u64,
data_len: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct BackupManifest {
kernel_abs: u64,
kernel_len: u64,
dtb_abs: u64,
dtb_len: u64,
rootfs_abs: u64,
rootfs_len: u64,
kernel: BackupEntry,
dtb: BackupEntry,
rootfs: BackupEntry,
}
impl BackupManifest {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::with_capacity(64);
v.extend_from_slice(BK_MAGIC);
for n in [
self.kernel_abs,
self.kernel_len,
self.dtb_abs,
self.dtb_len,
self.rootfs_abs,
self.rootfs_len,
] {
v.extend_from_slice(&n.to_be_bytes());
let mut v = Vec::with_capacity(8 + 9 * 8);
v.extend_from_slice(BK_MAGIC_V2);
for e in [self.kernel, self.dtb, self.rootfs] {
for n in [e.blob_abs, e.blob_len, e.data_len] {
v.extend_from_slice(&n.to_be_bytes());
}
}
v
}
fn decode(b: &[u8]) -> Option<Self> {
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
if b.len() < 8 + 9 * 8 || &b[..8] != BK_MAGIC_V2 {
return None;
}
let g = |i: usize| {
@@ -465,52 +666,83 @@ impl BackupManifest {
a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]);
u64::from_be_bytes(a)
};
let e = |base: usize| BackupEntry {
blob_abs: g(base),
blob_len: g(base + 1),
data_len: g(base + 2),
};
Some(BackupManifest {
kernel_abs: g(0),
kernel_len: g(1),
dtb_abs: g(2),
dtb_len: g(3),
rootfs_abs: g(4),
rootfs_len: g(5),
kernel: e(0),
dtb: e(3),
rootfs: e(6),
})
}
/// A v1 (data-only) backup is present but NOT safely restorable (no stock
/// OOB captured). Detected so restore can refuse with a clear message.
fn is_v1(b: &[u8]) -> bool {
b.len() >= 8 && &b[..8] == BK_MAGIC_V1
}
}
/// Capture one genuine-stock image (data+OOB) into the backup region at
/// `dst_abs`, checking it stays below the scratch block, and return its entry.
fn capture_entry(
sh: &mut dyn Shell,
table: &[Mtd],
src_abs: u64,
data_len: u64,
dst_abs: u64,
label: &str,
) -> Result<BackupEntry, StockError> {
let (remote, blob_len) = dump_with_oob(sh, table, src_abs, data_len, label)?;
if dst_abs + round_up(blob_len, ERASE) > BK_SCRATCH {
return Err(StockError::Method(
"stock backup (with OOB) does not fit in the backup region below the scratch block"
.into(),
));
}
store_blob(sh, table, dst_abs, &remote, blob_len, label)?;
sh.exec(&format!("rm -f {remote}"))?;
Ok(BackupEntry {
blob_abs: dst_abs,
blob_len,
data_len,
})
}
/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the
/// stock-backup region, with a manifest in its first block, so the board can be
/// returned to its own factory stock later with no vendor file. Called on the
/// stock side during a from-stock install, before the boot slots are overwritten.
/// stock-backup region *with their OOB* (a v2 backup), with a manifest in its
/// first block, so the board can be returned to its own factory stock later -
/// over the network, byte-identical to stock ECC - with no vendor file. Called
/// on the stock side during a from-stock install, before the boot slots are
/// overwritten. Each image's data+OOB blob is captured and stored sequentially
/// so only one lives in `/tmp` at a time.
fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, StockError> {
// Size the genuine images from their on-NAND headers (uImage data size at
// header offset 12; fdt totalsize at offset 4).
let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64;
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
// Sanity: headers must look like a uImage/fdt, sizes within slots.
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
// Genuine image sizes from their on-NAND headers (uImage data size at header
// offset 12 plus the 64-byte header; fdt totalsize at offset 4), rounded up
// to a whole NAND page so nanddump captures only complete pages.
let (kdev, _) = locate(table, OFF_KERNEL, 64)?;
let (ws, _oob) = oob_geometry(sh, kdev)?;
let pr = |n: u64| round_up(n, ws);
let kernel_data = pr(64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64);
let dtb_data = pr(read_header_u32_be(sh, table, OFF_DTB, 4)? as u64);
let rootfs_data = pr(64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64);
if !(ws..=SLOT_KERNEL).contains(&kernel_data) || !(ws..=SLOT_ROOTFS).contains(&rootfs_data) {
return Err(StockError::Method(format!(
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
"stock image sizes implausible (kernel {kernel_data}, rootfs {rootfs_data}); \
refusing to back up"
)));
}
let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block
let d_dst = k_dst + round_up(kernel_len, ERASE);
let r_dst = d_dst + round_up(dtb_len, ERASE);
if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP {
return Err(StockError::Method(
"stock backup does not fit in the 32 MiB backup region".into(),
));
}
copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?;
copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?;
copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?;
let kernel = capture_entry(sh, table, OFF_KERNEL, kernel_data, k_dst, "stock-kernel")?;
let d_dst = k_dst + round_up(kernel.blob_len, ERASE);
let dtb = capture_entry(sh, table, OFF_DTB, dtb_data, d_dst, "stock-dtb")?;
let r_dst = d_dst + round_up(dtb.blob_len, ERASE);
let rootfs = capture_entry(sh, table, OFF_ROOTFS, rootfs_data, r_dst, "stock-rootfs")?;
let manifest = BackupManifest {
kernel_abs: k_dst,
kernel_len,
dtb_abs: d_dst,
dtb_len,
rootfs_abs: r_dst,
rootfs_len,
kernel,
dtb,
rootfs,
};
write_abs(
sh,
@@ -522,19 +754,24 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
Ok(manifest)
}
/// Read and validate the on-board backup manifest, if present.
fn read_backup_manifest(
sh: &mut dyn Shell,
table: &[Mtd],
) -> Result<Option<BackupManifest>, StockError> {
let (dev, rel) = match locate(table, BK_MANIFEST, 64) {
/// Read the manifest block header bytes (enough for a v2 manifest: 8 magic +
/// 9*8 fields = 80 B; 128 read for slack). `None` if the region is not mapped.
fn read_manifest_bytes(sh: &mut dyn Shell, table: &[Mtd]) -> Result<Option<Vec<u8>>, StockError> {
let (dev, rel) = match locate(table, BK_MANIFEST, 128) {
Ok(v) => v,
Err(_) => return Ok(None), // region not mapped -> treat as absent
};
let dev = dev.to_owned();
// Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse.
let bytes = read_small(sh, &dev, rel, 64)?;
Ok(BackupManifest::decode(&bytes))
// Pull the manifest off NAND via `od -v -x` (busybox-safe) and parse.
Ok(Some(read_small(sh, &dev, rel, 128)?))
}
/// Read and validate the on-board v2 backup manifest, if present and complete.
fn read_backup_manifest(
sh: &mut dyn Shell,
table: &[Mtd],
) -> Result<Option<BackupManifest>, StockError> {
Ok(read_manifest_bytes(sh, table)?.and_then(|b| BackupManifest::decode(&b)))
}
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
@@ -641,55 +878,33 @@ pub fn install_from_stock(
Ok(())
}
/// Return an alkane board to genuine stock by writing the vendor images back to
/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the
/// vendor package); if `None`, the stock dtb saved in the on-board backup is
/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is.
/// Return an alkane board to genuine stock from a vendor firmware FILE.
///
/// This is refused on the Zynq-7010: a vendor file carries image data only, with
/// no OOB, so writing it from alkane userspace recomputes the kernel's soft-BCH
/// ECC, which the stock boot chain cannot read -> boot-loop brick recoverable
/// only by the SD card. The safe network return-to-stock is
/// [`restore_from_onboard`], which replays the genuine stock data+OOB captured
/// in the on-board v2 backup. (Once the own stage-2 U-Boot lands, a soft-BCH
/// reader makes vendor-file restore viable; until then it is blocked.)
pub fn restore_to_stock(
host: &str,
kernel_uimage: &[u8],
rootfs_uimage: &[u8],
dtb: Option<&[u8]>,
_kernel_uimage: &[u8],
_rootfs_uimage: &[u8],
_dtb: Option<&[u8]>,
password: Option<&str>,
) -> Result<(), StockError> {
let mut sh = AlkaneShell::connect(host, password)?;
if !shell_is_zynq(&mut sh) {
return Err(StockError::NotApplicable);
}
let table = read_mtd_table(&mut sh)?;
if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL {
return Err(StockError::Method("vendor image over slot ceiling".into()));
}
// rootfs, dtb, kernel order (same safety ordering as install).
write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?;
match dtb {
Some(d) => {
if d.len() as u64 > SLOT_DTB {
return Err(StockError::Method("dtb over slot ceiling".into()));
}
write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?;
}
None => {
// No vendor dtb (an OTA package omits it): restore the genuine
// per-board dtb from the on-board backup by copying within NAND.
let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| {
StockError::Method(
"no stock dtb supplied and no on-board backup to take one from".into(),
)
})?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
}
}
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
reboot(&mut sh);
Ok(())
Err(StockError::Method(
"Zynq-7010 vendor-file restore-to-stock is disabled: a vendor file has no OOB, so an \
alkane-side write recomputes soft-BCH ECC that the stock U-Boot cannot read (boot-loop \
brick; SD-card recovery only). Use restore-from-onboard, which replays the genuine stock \
data+OOB from the on-board backup."
.into(),
))
}
/// Whether the board holds a complete, restorable on-board stock backup.
@@ -710,33 +925,30 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
return Err(StockError::NotApplicable);
}
let table = read_mtd_table(&mut sh)?;
let manifest = read_backup_manifest(&mut sh, &table)?
let raw = read_manifest_bytes(&mut sh, &table)?.ok_or_else(|| {
StockError::Method("no on-board stock backup (backup region not mapped)".into())
})?;
if BackupManifest::is_v1(&raw) {
return Err(StockError::Method(
"on-board backup is the old data-only (v1) format with no stock OOB; it cannot be \
restored safely (a plain write recomputes alkane soft-BCH ECC and bricks the stock \
boot chain). Re-install from stock to capture a v2 backup, or use the SD recovery \
card."
.into(),
));
}
let manifest = BackupManifest::decode(&raw)
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
// Copy within NAND: backup region -> boot slots.
copy_abs(
&mut sh,
&table,
manifest.rootfs_abs,
OFF_ROOTFS,
manifest.rootfs_len,
"rootfs",
)?;
copy_abs(
&mut sh,
&table,
manifest.dtb_abs,
OFF_DTB,
manifest.dtb_len,
"dtb",
)?;
copy_abs(
&mut sh,
&table,
manifest.kernel_abs,
OFF_KERNEL,
manifest.kernel_len,
"kernel",
)?;
// Prove the raw-OOB write path round-trips the stock OOB on this board
// before touching a boot slot (abort, do not brick).
scratch_selfcheck(&mut sh, &table, manifest.kernel.blob_abs)?;
// rootfs, dtb, kernel order (an interrupted run never leaves a new rootfs
// under an old kernel). Each write is read-back-verified WITH OOB; a
// mismatch returns an error WITHOUT rebooting, leaving the running alkane in
// place rather than booting a corrupt slot.
restore_slot_raw_oob(&mut sh, &table, &manifest.rootfs, OFF_ROOTFS, "rootfs")?;
restore_slot_raw_oob(&mut sh, &table, &manifest.dtb, OFF_DTB, "dtb")?;
restore_slot_raw_oob(&mut sh, &table, &manifest.kernel, OFF_KERNEL, "kernel")?;
reboot(&mut sh);
Ok(())
}
@@ -762,22 +974,38 @@ mod tests {
}
#[test]
fn manifest_roundtrips() {
fn manifest_v2_roundtrips_and_rejects_v1() {
let e = |a, b, c| BackupEntry {
blob_abs: a,
blob_len: b,
data_len: c,
};
let m = BackupManifest {
kernel_abs: 0x6020000,
kernel_len: 4006832,
dtb_abs: 0x6420000,
dtb_len: 7650,
rootfs_abs: 0x6440000,
rootfs_len: 26620582,
kernel: e(0x6020000, 4133808, 4063232),
dtb: e(0x6440000, 8320, 8192),
rootfs: e(0x6460000, 27336704, 26624000),
};
let enc = m.encode();
let dec = BackupManifest::decode(&enc).unwrap();
assert_eq!(dec.kernel_abs, m.kernel_abs);
assert_eq!(dec.rootfs_len, m.rootfs_len);
assert_eq!(&enc[..8], BK_MAGIC_V2);
assert_eq!(enc.len(), 8 + 9 * 8);
assert_eq!(BackupManifest::decode(&enc).unwrap(), m);
// A v1 (data-only) header is detected and NOT decoded as a v2 manifest.
let mut v1 = BK_MAGIC_V1.to_vec();
v1.extend_from_slice(&[0u8; 72]);
assert!(BackupManifest::is_v1(&v1));
assert!(BackupManifest::decode(&v1).is_none());
assert!(!BackupManifest::is_v1(&enc));
assert!(BackupManifest::decode(b"nope").is_none());
}
#[test]
fn scratch_block_is_inside_the_backup_region_and_aligned() {
assert!(BK_SCRATCH.is_multiple_of(ERASE));
assert!(BK_SCRATCH >= OFF_STOCK_BACKUP + ERASE); // above manifest block
assert_eq!(BK_SCRATCH, OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP - ERASE);
assert!(BK_SCRATCH + ERASE <= OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP);
}
#[test]
fn locate_maps_absolute_to_partition() {
let table = vec![