diff --git a/Cargo.lock b/Cargo.lock index f120d17c..39f6dfd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,6 +96,13 @@ dependencies = [ "ed25519-dalek", ] +[[package]] +name = "aienos-store-tool" +version = "0.1.0" +dependencies = [ + "aienos-kernel", +] + [[package]] name = "base64ct" version = "1.8.3" diff --git a/Cargo.toml b/Cargo.toml index aa341d7b..4765ee35 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ members = [ "crates/aienos-artifact", "crates/aienos-artifact-tool", "crates/aienos-evidence", + "crates/aienos-store-tool", ] [workspace.package] diff --git a/crates/aienos-boot/src/nvme_read.rs b/crates/aienos-boot/src/nvme_read.rs index b9198d31..f31dc59a 100644 --- a/crates/aienos-boot/src/nvme_read.rs +++ b/crates/aienos-boot/src/nvme_read.rs @@ -17,7 +17,9 @@ #[cfg(feature = "store-qual")] use crate::store_qual::{ - genesis_units, BoundedNvme, CONFIG_LBA, MODE_VERIFY, STORE_BASE_LBA, STORE_REGION_BLOCKS, + genesis_units, BoundedNvme, CONFIG_LBA, CONFIG_LBA_512, MODE_RUN_512B, MODE_VERIFY, + MODE_VERIFY_512B, STORE_BASE_LBA, STORE_BASE_LBA_512, STORE_REGION_BLOCKS, + STORE_REGION_BLOCKS_512, }; use aienos_kernel::acpi::{self, EcamWindow}; use aienos_kernel::arch::aarch64::{ @@ -52,7 +54,7 @@ const RW_LBA: u64 = 4096; #[cfg(feature = "nvme-write")] const RW_MAGIC: &[u8; 16] = b"AIENOS-NVME-RW01"; -const ARENA_BYTES: usize = 128 * 1024; +const ARENA_BYTES: usize = 512 * 1024; #[repr(C, align(4096))] struct DmaArena([u8; ARENA_BYTES]); @@ -812,41 +814,66 @@ fn run_store_phase(screen: &mut Option, mut controller: QualController, use aienos_kernel::store::checkpoint::Checkpoint; use aienos_kernel::store::engine::{ObjectInput, Store}; - // Qualified geometry: the 4096-byte Store unit must be one logical block. - if controller.block_size() != 4096 { - qualify_fail(screen, "geometry is not 4096-byte LBA"); + let block_size = controller.block_size(); + if block_size != 512 && block_size != 4096 { + qualify_fail(screen, "unsupported block size"); return; } - // Atomic-root predicate must PASS, else fail closed. - let atomic = |d| matches!(d, AtomicityDecision::Atomic { .. }); - let ok = controller - .atomicity() - .map(|a| atomic(a.store_root_decision(0)) && atomic(a.store_root_decision(1))) - .unwrap_or(false); - if !ok { - qualify_fail(screen, "atomic-root predicate"); - return; - } + let cfg_lba = if block_size == 512 { + CONFIG_LBA_512 + } else { + CONFIG_LBA + }; // Control block. let mut cfg = [0u8; 4096]; - if controller.read_blocks(CONFIG_LBA, &mut cfg).is_err() { + if controller.read_blocks(cfg_lba, &mut cfg).is_err() { qualify_fail(screen, "control block read"); return; } let mode = cfg[0]; let settle = cfg[1]; - if STORE_BASE_LBA - .checked_add(STORE_REGION_BLOCKS) + let is_512_qual = mode == MODE_RUN_512B || mode == MODE_VERIFY_512B; + if is_512_qual { + if block_size != 512 { + qualify_fail(screen, "512b qual requires 512-byte LBA"); + return; + } + say(screen, "STORE_512B_NONATOMIC_QUALIFICATION: ACTIVE\n"); + } else { + if block_size != 4096 { + qualify_fail(screen, "geometry is not 4096-byte LBA"); + return; + } + // Atomic-root predicate must PASS, else fail closed. + let atomic = |d| matches!(d, AtomicityDecision::Atomic { .. }); + let ok = controller + .atomicity() + .map(|a| atomic(a.store_root_decision(0)) && atomic(a.store_root_decision(1))) + .unwrap_or(false); + if !ok { + qualify_fail(screen, "atomic-root predicate"); + return; + } + } + + let (base_lba, region_blocks) = if is_512_qual { + (STORE_BASE_LBA_512, STORE_REGION_BLOCKS_512) + } else { + (STORE_BASE_LBA, STORE_REGION_BLOCKS) + }; + + if base_lba + .checked_add(region_blocks) .is_none_or(|end| end > block_count) { qualify_fail(screen, "region outside namespace"); return; } - let bounded = BoundedNvme::new(controller, STORE_BASE_LBA, STORE_REGION_BLOCKS); + let bounded = BoundedNvme::new(controller, base_lba, region_blocks); let mut adapter = match aienos_kernel::store::device::StoreDeviceAdapter::new(bounded) { Ok(a) => a, Err(e) => { @@ -858,8 +885,8 @@ fn run_store_phase(screen: &mut Option, mut controller: QualController, }; let region_units = adapter.region_units(); - if mode == MODE_VERIFY { - verify_reopen(screen, adapter, settle); + if mode == MODE_VERIFY || mode == MODE_VERIFY_512B { + verify_reopen(screen, adapter, settle, is_512_qual); return; } @@ -961,22 +988,61 @@ fn run_store_phase(screen: &mut Option, mut controller: QualController, } #[cfg(feature = "store-qual")] -fn verify_reopen(screen: &mut Option, adapter: QualAdapter, settle: u8) { - use aienos_kernel::store::engine::Store; +fn verify_reopen(screen: &mut Option, adapter: QualAdapter, settle: u8, is_512: bool) { + use aienos_kernel::store::engine::{MountState, ObjectInput, Store, StoreError}; use aienos_kernel::store::v1::ObjectId; let upper = u64::from(settle) + 2; + let mut store = match Store::open(adapter) { Ok(s) => s, Err(e) => { let mut l = aienos_kernel::report::ReportBuf::<192>::new(); let _ = writeln!(l, "STORE_REOPEN_QEMU: FAIL (open {e:?})"); say(screen, l.as_str()); + if is_512 { + let mut l2 = aienos_kernel::report::ReportBuf::<192>::new(); + let _ = writeln!(l2, "STORE_REOPEN_512B_QEMU: FAIL (open {e:?})"); + say(screen, l2.as_str()); + } return; } }; let generation = store.generation(); let state = store.mount_state(); + + if is_512 { + // Peer classification is the engine's own decision at open, not a + // re-derivation here. + let peer_class = store.peer_condition(); + let mut l512 = aienos_kernel::report::ReportBuf::<192>::new(); + let _ = writeln!( + l512, + "STORE_REOPEN_512B_QEMU: generation={} state={:?} peer_classification={:?}", + generation, state, peer_class + ); + say(screen, l512.as_str()); + + if state == MountState::DegradedRecovery { + let dummy = [0u8; 8]; + let obj = ObjectInput { + kind: 3, + version: 1, + bytes: &dummy, + }; + let mut r = aienos_kernel::report::ReportBuf::<128>::new(); + match store.transact(&[obj]) { + Err(StoreError::ReadOnlyDegraded) => { + let _ = writeln!(r, "STORE_DEGRADED_READONLY_QEMU: PASS"); + } + other => { + let _ = writeln!(r, "STORE_DEGRADED_READONLY_QEMU: FAIL ({other:?})"); + } + } + say(screen, r.as_str()); + } + } + let mut l = aienos_kernel::report::ReportBuf::<192>::new(); let _ = writeln!( l, diff --git a/crates/aienos-boot/src/store_qual.rs b/crates/aienos-boot/src/store_qual.rs index 2ef5ce61..e9c81d59 100644 --- a/crates/aienos-boot/src/store_qual.rs +++ b/crates/aienos-boot/src/store_qual.rs @@ -17,6 +17,13 @@ pub const CONFIG_LBA: u64 = 32; pub const MODE_VERIFY: u8 = 2; +/// 512-byte LBA qualification constants. +pub const MODE_RUN_512B: u8 = 3; +pub const MODE_VERIFY_512B: u8 = 4; +pub const STORE_BASE_LBA_512: u64 = 512; +pub const STORE_REGION_BLOCKS_512: u64 = 2048; +pub const CONFIG_LBA_512: u64 = 256; + /// Adds a fixed LBA offset and rejects accesses past the bounded region. pub struct BoundedNvme { inner: NvmeController, diff --git a/crates/aienos-kernel/src/store/engine.rs b/crates/aienos-kernel/src/store/engine.rs index 0b6f5571..2933c1af 100644 --- a/crates/aienos-kernel/src/store/engine.rs +++ b/crates/aienos-kernel/src/store/engine.rs @@ -31,6 +31,21 @@ pub enum MountState { DegradedRecovery, } +/// What `Store::open` found in the superblock slot that is not the active root. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PeerCondition { + /// All-zero slot (never written). + Zero, + /// A second fully validated root. + Valid, + /// Non-zero bytes that are not a CRC-valid, supported, decodable superblock. + Malformed, + /// CRC-valid superblock whose object graph fails validation, newer than the active root. + GraphBadNewer, + /// CRC-valid superblock whose object graph fails validation, older than the active root. + GraphBadOlder, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum MountError { Io, @@ -77,6 +92,7 @@ pub struct Store { device: D, root: ValidatedRoot, state: MountState, + peer: PeerCondition, poisoned: bool, } @@ -139,52 +155,59 @@ impl Store { } } + let mounted = |device, root, state, peer| Self { + device, + root, + state, + peer, + poisoned: false, + }; match (roots[0].take(), roots[1].take()) { (Some(a), Some(b)) => { let chosen = select_two(a, b)?; - Ok(Self { + Ok(mounted( device, - root: chosen, - state: MountState::Valid, - poisoned: false, - }) + chosen, + MountState::Valid, + PeerCondition::Valid, + )) } (Some(root), None) | (None, Some(root)) => { let good_slot = if root.superblock.slot_id == 0 { 0 } else { 1 }; let other = 1 - good_slot; if zero[other] { - Ok(Self { + Ok(mounted( device, root, - state: MountState::Valid, - poisoned: false, - }) + MountState::Valid, + PeerCondition::Zero, + )) } else if malformed[other] { if unsupported_superblock(&raw[other]) && crc_valid(&raw[other]) { Err(MountError::UnsupportedVersion) } else { - Ok(Self { + Ok(mounted( device, root, - state: MountState::DegradedRecovery, - poisoned: false, - }) + MountState::DegradedRecovery, + PeerCondition::Malformed, + )) } } else if graph_bad[other] && crc_supported[other] { if generation_of(&raw[other]) > root.superblock.generation { - Ok(Self { + Ok(mounted( device, root, - state: MountState::DegradedRecovery, - poisoned: false, - }) + MountState::DegradedRecovery, + PeerCondition::GraphBadNewer, + )) } else if generation_of(&raw[other]) < root.superblock.generation { - Ok(Self { + Ok(mounted( device, root, - state: MountState::Valid, - poisoned: false, - }) + MountState::Valid, + PeerCondition::GraphBadOlder, + )) } else { Err(MountError::CorruptRecoveryRequired) } @@ -199,6 +222,11 @@ impl Store { pub fn mount_state(&self) -> MountState { self.state } + /// Condition of the non-active superblock slot as classified at open, or + /// `Valid` once a committed transaction has made it the previous root. + pub fn peer_condition(&self) -> PeerCondition { + self.peer + } pub fn generation(&self) -> u64 { self.root.commit.generation } @@ -292,6 +320,7 @@ impl Store { })?; hook.on_checkpoint(Checkpoint::AfterFinalFlush); self.root = plan.root; + self.peer = PeerCondition::Valid; Ok(()) } @@ -1266,6 +1295,30 @@ mod tests { assert_eq!(store.transact(&one(b"again")), Err(StoreError::NeedsReopen)); } + #[test] + fn store_peer_condition_reports_open_classification() { + let store = Store::open(seed_genesis(blank(32))).unwrap(); + assert_eq!(store.peer_condition(), PeerCondition::Zero); + + let mut store = store; + store.transact(&one(b"second generation")).unwrap(); + assert_eq!(store.peer_condition(), PeerCondition::Valid); + let dev = store.into_device(); + let reopened = Store::open(dev).unwrap(); + assert_eq!(reopened.mount_state(), MountState::Valid); + assert_eq!(reopened.peer_condition(), PeerCondition::Valid); + + // Newer root whose commit record is gone: older root mounts read-only. + let mut dev = reopened.into_device(); + let newer = Superblock::decode(&dev.units[1], 1).unwrap(); + assert_eq!(newer.generation, 2); + dev.units[newer.commit_record_unit as usize] = [0; STORE_UNIT_BYTES]; + let store = Store::open(dev).unwrap(); + assert_eq!(store.generation(), 1); + assert_eq!(store.mount_state(), MountState::DegradedRecovery); + assert_eq!(store.peer_condition(), PeerCondition::GraphBadNewer); + } + #[test] fn store_malformed_peer_recovery_matrix() { let rechecksum = |bytes: &mut [u8; STORE_UNIT_BYTES]| { @@ -1280,6 +1333,7 @@ mod tests { dev.units[1][168] ^= 1; let store = Store::open(dev).unwrap(); assert_eq!(store.mount_state(), MountState::DegradedRecovery); + assert_eq!(store.peer_condition(), PeerCondition::Malformed); assert_eq!(store.generation(), 1); // 2. Wrong magic peer: Valid root in slot 0 + non-zero wrong magic in slot 1 -> DegradedRecovery @@ -1287,6 +1341,7 @@ mod tests { dev.units[1][..8].copy_from_slice(b"BADMAGIC"); let store = Store::open(dev).unwrap(); assert_eq!(store.mount_state(), MountState::DegradedRecovery); + assert_eq!(store.peer_condition(), PeerCondition::Malformed); assert_eq!(store.generation(), 1); // 3. Malformed shape peer: Valid root in slot 0 + non-zero reserved in slot 1 -> DegradedRecovery @@ -1299,6 +1354,7 @@ mod tests { rechecksum(&mut dev.units[1]); let store = Store::open(dev).unwrap(); assert_eq!(store.mount_state(), MountState::DegradedRecovery); + assert_eq!(store.peer_condition(), PeerCondition::Malformed); assert_eq!(store.generation(), 1); // 4. Unsupported version peer: Valid root in slot 0 + CRC-valid major=2 in slot 1 -> UnsupportedVersion diff --git a/crates/aienos-store-tool/Cargo.toml b/crates/aienos-store-tool/Cargo.toml new file mode 100644 index 00000000..40a11cad --- /dev/null +++ b/crates/aienos-store-tool/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "aienos-store-tool" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "Host tooling for System Store v1 qualification images (test-only)" + +[dependencies] +aienos-kernel = { path = "../aienos-kernel" } diff --git a/crates/aienos-store-tool/src/main.rs b/crates/aienos-store-tool/src/main.rs new file mode 100644 index 00000000..d444e6c3 --- /dev/null +++ b/crates/aienos-store-tool/src/main.rs @@ -0,0 +1,346 @@ +//! Host tooling for System Store v1 QEMU qualification images. +//! +//! Test-only. Every byte this tool writes is derived from the kernel's own +//! `store::v1` encoder and CRC, so the qualification scripts carry no second +//! implementation of the format. +//! +//! Commands: +//! cfg IMAGE BYTE_OFFSET MODE SETTLE +//! Write the 4096-byte qualification control block. +//! tear-closure OLD NEW STORE_BYTE_OFFSET SECTOR_BYTES +//! Prove that every sector-granular tear of the one superblock write that +//! separates OLD from NEW leaves either the old or the new slot bytes. +//! inject IMAGE STORE_BYTE_OFFSET SLOT CASE [SOURCE] +//! Overwrite superblock SLOT with one deterministic defect (see `CASES`). + +use std::env; +use std::fs::{self, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::process::ExitCode; + +use aienos_kernel::store::v1::{ + crc32c, FormatError, Superblock, STORE_UNIT_BYTES, SUPERBLOCK_CRC_OFFSET, +}; + +type Unit = [u8; STORE_UNIT_BYTES]; + +/// Injection cases. Every case except `bad_crc` and `seeded_garbage` keeps a +/// valid CRC, so each one reaches exactly the check it names. +const CASES: &[&str] = &[ + "bad_crc", + "wrong_magic", + "nonzero_reserved", + "wrong_slot_id", + "region_mismatch", + "unsupported_version", + "seeded_garbage", + "new_root", +]; + +fn main() -> ExitCode { + let args: Vec = env::args().skip(1).collect(); + let result = match args.first().map(String::as_str) { + Some("cfg") => cfg(&args[1..]), + Some("tear-closure") => tear_closure(&args[1..]), + Some("inject") => inject(&args[1..]), + _ => Err(format!( + "usage: aienos-store-tool cfg|tear-closure|inject ... (cases: {})", + CASES.join(",") + )), + }; + match result { + Ok(line) => { + println!("{line}"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("aienos-store-tool: {e}"); + ExitCode::FAILURE + } + } +} + +fn num(s: &str, what: &str) -> Result { + s.parse().map_err(|_| format!("bad {what}: {s}")) +} + +fn arity(args: &[String], min: usize, max: usize) -> Result<(), String> { + if args.len() < min || args.len() > max { + return Err(format!( + "expected {min}..={max} arguments, got {}", + args.len() + )); + } + Ok(()) +} + +fn read_unit_at(path: &str, offset: u64) -> Result { + let mut f = fs::File::open(path).map_err(|e| format!("{path}: {e}"))?; + f.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?; + let mut unit = [0u8; STORE_UNIT_BYTES]; + f.read_exact(&mut unit) + .map_err(|e| format!("{path}: {e}"))?; + Ok(unit) +} + +fn write_at(path: &str, offset: u64, bytes: &[u8]) -> Result<(), String> { + let mut f = OpenOptions::new() + .write(true) + .open(path) + .map_err(|e| format!("{path}: {e}"))?; + f.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?; + f.write_all(bytes).map_err(|e| format!("{path}: {e}"))?; + f.sync_all().map_err(|e| format!("{path}: {e}")) +} + +fn rechecksum(unit: &mut Unit) { + unit[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].fill(0); + let crc = crc32c(unit); + unit[SUPERBLOCK_CRC_OFFSET..SUPERBLOCK_CRC_OFFSET + 4].copy_from_slice(&crc.to_le_bytes()); +} + +fn cfg(args: &[String]) -> Result { + arity(args, 4, 4)?; + let offset = num(&args[1], "byte offset")?; + let mode = u8::try_from(num(&args[2], "mode")?).map_err(|_| "mode > 255")?; + let settle = u8::try_from(num(&args[3], "settle")?).map_err(|_| "settle > 255")?; + let mut block = [0u8; STORE_UNIT_BYTES]; + block[0] = mode; + block[1] = settle; + write_at(&args[0], offset, &block)?; + Ok(format!("cfg mode={mode} settle={settle}")) +} + +/// Describes a superblock slot's bytes for reports. +fn describe(unit: &Unit, slot: u32) -> String { + if unit.iter().all(|b| *b == 0) { + return "zero".into(); + } + match Superblock::decode(unit, slot) { + Ok(sb) => format!("gen{}", sb.generation), + Err(e) => format!("undecodable({e:?})"), + } +} + +fn tear_closure(args: &[String]) -> Result { + arity(args, 4, 4)?; + let old = fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?; + let new = fs::read(&args[1]).map_err(|e| format!("{}: {e}", args[1]))?; + let store_offset = + usize::try_from(num(&args[2], "store offset")?).map_err(|e| e.to_string())?; + let sector = usize::try_from(num(&args[3], "sector bytes")?).map_err(|e| e.to_string())?; + if old.len() != new.len() { + return Err("images differ in length".into()); + } + if sector == 0 || !STORE_UNIT_BYTES.is_multiple_of(sector) { + return Err(format!( + "sector size {sector} does not divide the store unit" + )); + } + if !store_offset.is_multiple_of(sector) { + return Err("store offset is not sector aligned".into()); + } + + // Every differing byte must lie inside one superblock slot of the store. + let mut slot_hit: Option = None; + for (i, (a, b)) in old.iter().zip(&new).enumerate() { + if a == b { + continue; + } + let rel = i + .checked_sub(store_offset) + .ok_or_else(|| format!("images differ outside the store at byte {i}"))?; + let slot = rel / STORE_UNIT_BYTES; + if slot > 1 { + return Err(format!( + "images differ outside the superblock slots (store unit {slot}); \ + the two runs did not persist identical payloads" + )); + } + match slot_hit { + None => slot_hit = Some(slot), + Some(s) if s == slot => {} + Some(_) => return Err("both superblock slots differ".into()), + } + } + let slot = slot_hit.ok_or("images are identical: nothing separates old from new")?; + let base = store_offset + slot * STORE_UNIT_BYTES; + let mut old_unit = [0u8; STORE_UNIT_BYTES]; + let mut new_unit = [0u8; STORE_UNIT_BYTES]; + old_unit.copy_from_slice(&old[base..base + STORE_UNIT_BYTES]); + new_unit.copy_from_slice(&new[base..base + STORE_UNIT_BYTES]); + + let new_sb = Superblock::decode(&new_unit, slot as u32) + .map_err(|e| format!("new slot {slot} is not a valid superblock: {e:?}"))?; + let old_desc = describe(&old_unit, slot as u32); + if old_desc.starts_with("undecodable") { + return Err(format!( + "old slot {slot} is {old_desc}; the engine never overwrites such a slot" + )); + } + + let sectors = STORE_UNIT_BYTES / sector; + let differing: Vec = (0..sectors) + .filter(|s| { + old_unit[s * sector..(s + 1) * sector] != new_unit[s * sector..(s + 1) * sector] + }) + .collect(); + let (as_old, as_new) = tear_outcomes(&old_unit, &new_unit, sector).map_err(|mask| { + format!( + "STORE_ROOT_TEAR_CLOSURE: FAIL (slot={slot} mask={mask:#x} yields a third state; \ + differing sectors {differing:?})" + ) + })?; + Ok(format!( + "STORE_ROOT_TEAR_CLOSURE: PASS (slot={slot} old={old_desc} new=gen{} sector_bytes={sector} \ + differing_sectors={differing:?} combinations={} as_old={as_old} as_new={as_new})", + new_sb.generation, + 1u32 << sectors + )) +} + +/// Applies every subset of `sector`-sized blocks of `new` over `old` (each +/// sector either reached the medium or did not). Returns how many subsets +/// reproduce `old` and `new`, or the first subset mask that yields neither. +fn tear_outcomes(old: &Unit, new: &Unit, sector: usize) -> Result<(u32, u32), u32> { + let sectors = STORE_UNIT_BYTES / sector; + assert!(sectors <= 16, "too many sectors per unit to enumerate"); + let (mut as_old, mut as_new) = (0u32, 0u32); + for mask in 0u32..(1 << sectors) { + let mut torn = *old; + for s in 0..sectors { + if mask & (1 << s) != 0 { + torn[s * sector..(s + 1) * sector] + .copy_from_slice(&new[s * sector..(s + 1) * sector]); + } + } + if torn == *old { + as_old += 1; + } else if torn == *new { + as_new += 1; + } else { + return Err(mask); + } + } + Ok((as_old, as_new)) +} + +/// xorshift64 stream with a fixed seed: the same 4096 bytes on every run. +fn seeded_garbage() -> Unit { + let mut state: u64 = 0x4149_454E_4F53_0136; + let mut unit = [0u8; STORE_UNIT_BYTES]; + for chunk in unit.as_chunks_mut::<8>().0 { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + chunk.copy_from_slice(&state.to_le_bytes()); + } + unit +} + +fn inject(args: &[String]) -> Result { + arity(args, 4, 5)?; + let image = &args[0]; + let store_offset = num(&args[1], "store offset")?; + let slot = u32::try_from(num(&args[2], "slot")?).map_err(|e| e.to_string())?; + if slot > 1 { + return Err("slot must be 0 or 1".into()); + } + let case = args[3].as_str(); + let slot_offset = store_offset + u64::from(slot) * STORE_UNIT_BYTES as u64; + + let source = || -> Result { + let path = args.get(4).ok_or("this case needs a SOURCE image")?; + let unit = read_unit_at(path, slot_offset)?; + Superblock::decode(&unit, slot) + .map_err(|e| format!("source slot {slot} is not a valid superblock: {e:?}"))?; + Ok(unit) + }; + + // (bytes, the decode error this case must produce, or None for a valid root) + let (unit, expect): (Unit, Option) = match case { + "bad_crc" => { + let mut u = source()?; + u[SUPERBLOCK_CRC_OFFSET] ^= 0x01; + (u, Some(FormatError::BadSuperblockCrc)) + } + "wrong_magic" => { + let mut u = source()?; + u[..8].copy_from_slice(b"AIENBAD1"); + rechecksum(&mut u); + (u, Some(FormatError::BadSuperblockMagic)) + } + "nonzero_reserved" => { + let mut u = source()?; + u[200] = 0x42; + rechecksum(&mut u); + (u, Some(FormatError::NonzeroReserved)) + } + "wrong_slot_id" => { + let mut u = source()?; + u[44..48].copy_from_slice(&(1 - slot).to_le_bytes()); + rechecksum(&mut u); + (u, Some(FormatError::WrongSuperblockSlot)) + } + "region_mismatch" => { + // Decodes cleanly; the engine rejects it because region_units does + // not match the device. + let mut u = source()?; + let region = u64::from_le_bytes(u[48..56].try_into().unwrap_or([0; 8])); + u[48..56].copy_from_slice(&(region + 1).to_le_bytes()); + rechecksum(&mut u); + (u, None) + } + "unsupported_version" => { + let mut u = source()?; + u[8..10].copy_from_slice(&2u16.to_le_bytes()); + rechecksum(&mut u); + (u, Some(FormatError::UnsupportedVersion)) + } + "seeded_garbage" => (seeded_garbage(), Some(FormatError::BadSuperblockMagic)), + "new_root" => (source()?, None), + other => return Err(format!("unknown case {other}; cases: {}", CASES.join(","))), + }; + + // Prove the case isolates the defect it names before touching the image. + let got = Superblock::decode(&unit, slot).err(); + if got != expect { + return Err(format!( + "case {case}: decode gave {got:?}, expected {expect:?}" + )); + } + write_at(image, slot_offset, &unit)?; + Ok(format!( + "inject case={case} slot={slot} decode={}", + expect.map_or("Ok".to_string(), |e| format!("{e:?}")) + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tear_outcomes_detects_a_third_state() { + let old = [0u8; STORE_UNIT_BYTES]; + let mut one_sector = old; + one_sector[7] = 1; + assert_eq!(tear_outcomes(&old, &one_sector, 512), Ok((128, 128))); + + let mut two_sectors = one_sector; + two_sectors[512 * 3] = 1; + // Sector 0 alone reaching the medium is neither old nor new. + assert_eq!(tear_outcomes(&old, &two_sectors, 512), Err(0x1)); + } + + #[test] + fn garbage_is_stable_and_not_a_superblock() { + let a = seeded_garbage(); + assert_eq!(a, seeded_garbage()); + assert_ne!(&a[..8], b"AIENSTR1"); + assert_eq!( + Superblock::decode(&a, 1).err(), + Some(FormatError::BadSuperblockMagic) + ); + } +} diff --git a/evidence/store_512b_qemu_2026-09-25.md b/evidence/store_512b_qemu_2026-09-25.md new file mode 100644 index 00000000..c6a04386 --- /dev/null +++ b/evidence/store_512b_qemu_2026-09-25.md @@ -0,0 +1,90 @@ +# Store v1 over NVMe, 512-byte LBA: QEMU qualification (2026-09-25) + +Lane: `feat/p3-store-512b-crash-qemu` (PR #136), code commit +`51eaa4c80bfa806d737c0068a0ce9b82c1695e0c` (clean tree), base `main` `123929a`. +Test-only. QEMU only. No ADR 0015 format, recovery-policy, NVMe-policy, or +Machine 1 changes. `P3_STORE_QEMU` and `P3_STORE_NATIVE` are not claimed. + +Reproduce: `./scripts/qemu_store_512b_crash_test.sh` +Same commit: `AIENOS_STRICT=1 ./scripts/verify_all.sh` exit 0, 273 PASS, +0 FAIL, 0 SKIPPED (this script is not yet part of verify_all). + +## What each tier proves, and what it does not + +| Tier | Marker | Method | Claim | Not claimed | +|---|---|---|---|---| +| Smoke | `STORE_NVME_INTEGRATION_512B_QEMU` | provision, one transaction, reopen through the real NVMe driver at 512-byte LBA | the Store engine runs over 512-byte geometry via `BoundedNvme` | Machine 1 behaviour | +| 1 | `STORE_512B_CRASH_OBSERVED_QEMU` | host `SIGKILL`s QEMU at each of the 7 engine checkpoints, settle 0 and 3, then reopens | after a VM/process crash at any checkpoint the store reopens `Valid` at generation N or N+1 as ADR 0015 orders | power loss: QEMU's accepted writes survive in the host file whether flushed or not; volatile-cache loss is #133's scope | +| 2a | `STORE_512B_ROOT_TEAR_CLOSURE` | host proof over the Tier 1 images killed at `after_first_flush` and `after_final_flush`: the images differ only in one superblock slot, and all 256 sector subsets of that 8-sector write are enumerated | on a 1-LBA-atomic device (AWUPF=0) a torn root write can only leave the old or the new slot, because every non-zero superblock byte lies in sector 0 and the engine only overwrites a zero or valid slot (sectors 1..7 zero in both) | device behaviour below one-LBA atomicity | +| 2b | `STORE_512B_INJECTED_ROOT_RECOVERY_QEMU` | deterministic media-corruption injection into the inactive slot by `aienos-store-tool` (kernel encoder and CRC; CRC recomputed so each case reaches the check it names) | the engine's malformed-peer, graph-bad-newer and unsupported-version decisions hold over the native NVMe path | these are not crashes and not torn writes | + +The peer classification in every line is `Store::peer_condition()`, the +engine's own decision at open, not a re-derivation in the guest. + +## Results + +```text +=== Integration Smoke (512-byte LBA) === +PASS integration smoke (provision + transact, 512b non-atomic qualification active) +PASS reopen smoke (generation=2 state=Valid peer=Valid) + +=== Tier 1: Checkpoint SIGKILL Campaign === +settle=0 cp=before_first_write saw=1 reopen=1 slot=1 gen=1 state=Valid peer=Zero expect=N -> OK +settle=0 cp=after_payloads saw=1 reopen=1 slot=1 gen=1 state=Valid peer=Zero expect=N -> OK +settle=0 cp=after_catalog saw=1 reopen=1 slot=1 gen=1 state=Valid peer=Zero expect=N -> OK +settle=0 cp=after_commit_record saw=1 reopen=1 slot=1 gen=1 state=Valid peer=Zero expect=N -> OK +settle=0 cp=after_first_flush saw=1 reopen=1 slot=1 gen=1 state=Valid peer=Zero expect=N -> OK +settle=0 cp=after_superblock_write saw=1 reopen=1 slot=1 gen=2 state=Valid peer=Valid expect=N_NP1 -> OK +settle=0 cp=after_final_flush saw=1 reopen=1 slot=1 gen=2 state=Valid peer=Valid expect=NP1 -> OK +settle=3 cp=before_first_write saw=1 reopen=1 slot=1 gen=4 state=Valid peer=Valid expect=N -> OK +settle=3 cp=after_payloads saw=1 reopen=1 slot=1 gen=4 state=Valid peer=Valid expect=N -> OK +settle=3 cp=after_catalog saw=1 reopen=1 slot=1 gen=4 state=Valid peer=Valid expect=N -> OK +settle=3 cp=after_commit_record saw=1 reopen=1 slot=1 gen=4 state=Valid peer=Valid expect=N -> OK +settle=3 cp=after_first_flush saw=1 reopen=1 slot=1 gen=4 state=Valid peer=Valid expect=N -> OK +settle=3 cp=after_superblock_write saw=1 reopen=1 slot=1 gen=5 state=Valid peer=Valid expect=N_NP1 -> OK +settle=3 cp=after_final_flush saw=1 reopen=1 slot=1 gen=5 state=Valid peer=Valid expect=NP1 -> OK +STORE_512B_CRASH_OBSERVED_QEMU: PASS + +=== Tier 2a: Root Tear Closure (host proof over Tier 1 images) === +settle=0 STORE_ROOT_TEAR_CLOSURE: PASS (slot=1 old=zero new=gen2 sector_bytes=512 differing_sectors=[0] combinations=256 as_old=128 as_new=128) +settle=3 STORE_ROOT_TEAR_CLOSURE: PASS (slot=0 old=gen3 new=gen5 sector_bytes=512 differing_sectors=[0] combinations=256 as_old=128 as_new=128) +STORE_512B_ROOT_TEAR_CLOSURE: PASS + +=== Tier 2b: Injected Root Recovery (media corruption, one defect per case) === +case=bad_crc decode=BadSuperblockCrc gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=wrong_magic decode=BadSuperblockMagic gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=nonzero_reserved decode=NonzeroReserved gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=wrong_slot_id decode=WrongSuperblockSlot gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=region_mismatch decode=Ok gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=seeded_garbage decode=BadSuperblockMagic gen=1 state=DegradedRecovery peer=Malformed readonly=1 expect=degraded:Malformed -> OK +case=unsupported_version decode=UnsupportedVersion gen=none state=none peer=none readonly=0 expect=refuse:UnsupportedVersion -> OK +case=graph_bad_newer decode=Ok gen=1 state=DegradedRecovery peer=GraphBadNewer readonly=1 expect=degraded:GraphBadNewer -> OK +case=control_new_root decode=Ok gen=2 state=Valid peer=Valid readonly=0 expect=valid:gen2 -> OK +STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: PASS + +=== Final Summary (commit 51eaa4c80bfa806d737c0068a0ce9b82c1695e0c) === +STORE_NVME_INTEGRATION_512B_QEMU: PASS +STORE_512B_CRASH_OBSERVED_QEMU: PASS +STORE_512B_ROOT_TEAR_CLOSURE: PASS +STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: PASS +STORE_512B_CRASH_RECOVERY_QEMU: PASS +P3_STORE_QEMU: NOT CLAIMED (QEMU campaign; native persistence conditions separate) +P3_STORE_NATIVE: NOT CLAIMED +``` + +Reading the settle=3 tear-closure line: generation 5 overwrites the +generation-3 superblock in slot 0, so the proof covers overwriting a live +older root, not only a zero slot. + +## Changes from the first #136 revision + +- Tier 2 renamed from "deterministic torn root recovery" to injected-root + recovery. The old cases pre-filled the slot with `0xAA`, a state the engine + never writes, and applied the magic and reserved defects after the CRC, so + all three only exercised the CRC check. +- Injection base moved from genesis (`before_first_write`) to + `after_first_flush`, with the real generation-2 superblock as the source. +- `os.urandom` garbage replaced by a fixed-seed xorshift64 stream. +- All `python3` removed from the script (`aienos-store-tool`). +- Guest peer telemetry now comes from the engine (`PeerCondition`); the old + guest heuristic labelled any decodable peer `GraphBad` from mount state. diff --git a/scripts/qemu_store_512b_crash_test.sh b/scripts/qemu_store_512b_crash_test.sh new file mode 100755 index 00000000..1724b24d --- /dev/null +++ b/scripts/qemu_store_512b_crash_test.sh @@ -0,0 +1,281 @@ +#!/usr/bin/env bash +# System Store v1 over the native NVMe driver: 512-byte-LBA QEMU qualification. +# +# Geometry: 512-byte LBA (the native DGX Spark geometry, AWUPF=0: one logical +# block is the power-fail atomic unit). A Store root write is 4096 bytes +# (8 logical blocks), so the device does not promise it lands atomically. +# +# Tier 1 STORE_512B_CRASH_OBSERVED_QEMU +# QEMU is killed (SIGKILL) at each engine checkpoint, then reopened through the +# real NVMe path. This models a VM/process crash: every write QEMU accepted is +# in the host file, flushed or not. It is not a power-loss model (volatile +# cache loss is covered by the #133 atomicity qualification). +# Tier 2a STORE_512B_ROOT_TEAR_CLOSURE +# Host proof on the Tier 1 images: the image killed at after_first_flush and +# the image killed at after_final_flush differ only inside one superblock +# slot, and every sector-granular tear of that write (all 2^8 subsets) +# reproduces either the old or the new slot bytes. So on this format a torn +# root write can only leave a state Tier 1 already booted. +# Tier 2b STORE_512B_INJECTED_ROOT_RECOVERY_QEMU +# Deterministic media-corruption injection, not a crash: one defect per case +# is written into the inactive slot of the after_first_flush image by +# aienos-store-tool (the kernel's own encoder and CRC), then the guest reopens. +# +# Emits STORE_512B_CRASH_RECOVERY_QEMU: PASS only when all tiers pass. +# Test-only. QEMU only. No ADR 0015, recovery, Store-format, NVMe-policy, or +# Machine 1 changes. P3_STORE_QEMU and P3_STORE_NATIVE remain unclaimed. +set -uo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" +img_bytes=67108864 +lba_bytes=512 +cfg_offset=$(( 256 * lba_bytes )) +store_offset=$(( 512 * lba_bytes )) + +machine="virt,virtualization=on,gic-version=3,iommu=smmuv3" +target_dir="target/qemu-store-512b-crash" + +echo "=== Building aienos-handoff (store-qual) and aienos-store-tool ===" +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +git diff --quiet HEAD 2>/dev/null || commit="${commit}-dirty" +AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features store-qual --bin aienos-handoff \ + --target-dir "${target_dir}" || { echo "build failed"; exit 2; } +cargo build --quiet --release -p aienos-store-tool || { echo "store tool build failed"; exit 2; } +tool="target/release/aienos-store-tool" + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { [[ -n "${qemu_pid}" ]] && kill -9 "${qemu_pid}" 2>/dev/null || true; rm -rf "${work}"; } +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" "${work}/saved" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${target_dir}/aarch64-unknown-uefi/release/aienos-handoff.efi" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +image="${work}/nvme.img" +serial="${work}/serial.log" + +fresh_image() { rm -f "${image}"; truncate -s "${img_bytes}" "${image}"; } +write_cfg() { "${tool}" cfg "${image}" "${cfg_offset}" "$1" "$2" >/dev/null || { echo "cfg write failed"; exit 2; }; } + +# run_qemu [kill] +run_qemu() { + cp -f "${vars_fd}" "${work}/vars.fd" + rm -f "${serial}" + qemu-system-aarch64 \ + -M "${machine}" -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=nvme0,format=raw,file="${image}" \ + -device nvme,drive=nvme0,serial=aienos-store-512b-crash,logical_block_size=${lba_bytes},physical_block_size=${lba_bytes} \ + -display none -nic none -serial file:"${serial}" -no-reboot & + qemu_pid=$! + local deadline=$(( $(date +%s) + boot_timeout )) + while (( $(date +%s) < deadline )); do + grep -q -- "$1" "${serial}" 2>/dev/null && break + kill -0 "${qemu_pid}" 2>/dev/null || break + sleep 0.1 + done + if [[ "${2:-}" == "kill" ]]; then + kill -9 "${qemu_pid}" 2>/dev/null || true + fi + wait "${qemu_pid}" 2>/dev/null || true + qemu_pid="" +} + +# Fields of this run's single STORE_REOPEN_512B_QEMU line (serial is per run). +reopen_fields() { + local line + line="$(grep -oE "STORE_REOPEN_512B_QEMU: generation=[0-9]+ state=[A-Za-z]+ peer_classification=[A-Za-z]+" "${serial}" | tail -1)" + gen="$(sed -nE 's/.*generation=([0-9]+).*/\1/p' <<<"${line}")" + st="$(sed -nE 's/.*state=([A-Za-z]+).*/\1/p' <<<"${line}")" + pclass="$(sed -nE 's/.*peer_classification=([A-Za-z]+).*/\1/p' <<<"${line}")" +} + +checkpoints=(before_first_write after_payloads after_catalog after_commit_record \ + after_first_flush after_superblock_write after_final_flush) + +fail=0 +integration_pass=0 +reopen_pass=0 +tier1_pass=0 +tier2a_pass=0 +tier2b_pass=0 +: > "${work}/results_tier1.txt" +: > "${work}/results_tier2b.txt" + +# --- integration smoke (no crash): provision, transact, reopen ------------- +echo "=== Integration Smoke (512-byte LBA) ===" +fresh_image; write_cfg 3 0 +run_qemu "STORE_CHECKPOINT_QEMU" +if grep -q "STORE_512B_NONATOMIC_QUALIFICATION: ACTIVE" "${serial}" && \ + grep -q "STORE_NVME_INTEGRATION_QEMU: PASS" "${serial}" && \ + grep -q "STORE_CHECKPOINT_QEMU: PASS" "${serial}"; then + integration_pass=1 + echo "PASS integration smoke (provision + transact, 512b non-atomic qualification active)" +else + echo "FAIL integration smoke" + fail=1 + grep -E "STORE_512B_NONATOMIC_QUALIFICATION|STORE_NVME_INTEGRATION_QEMU|STORE_CHECKPOINT_QEMU" "${serial}" | sed 's/^/ /' +fi + +write_cfg 4 0 +run_qemu "STORE_REOPEN_QEMU:" +reopen_fields +if [[ "${gen}" == 2 && "${st}" == Valid && "${pclass}" == Valid ]] && \ + grep -q "STORE_REOPEN_QEMU: PASS" "${serial}"; then + reopen_pass=1 + echo "PASS reopen smoke (generation=2 state=Valid peer=Valid)" +else + echo "FAIL reopen smoke" + fail=1 + grep -E "STORE_REOPEN_512B_QEMU|STORE_REOPEN_QEMU" "${serial}" | sed 's/^/ /' +fi + +# --- Tier 1: checkpoint SIGKILL campaign ------------------------------------ +echo +echo "=== Tier 1: Checkpoint SIGKILL Campaign ===" +expect_for() { # checkpoint + case "$1" in + after_superblock_write) echo "N_NP1" ;; + after_final_flush) echo "NP1" ;; + *) echo "N" ;; + esac +} + +for settle in 0 3; do + N=$(( 1 + settle )); NP1=$(( 2 + settle )) + for cp in "${checkpoints[@]}"; do + fresh_image; write_cfg 3 "${settle}" + run_qemu "CHECKPOINT: ${cp}" kill + saw_cp=0; grep -q -- "CHECKPOINT: ${cp}" "${serial}" && saw_cp=1 + # Keep the crashed image for Tier 2 before the verify boot touches it. + cp "${image}" "${work}/saved/s${settle}_${cp}.img" + write_cfg 4 "${settle}" + run_qemu "STORE_REOPEN_QEMU:" + guest_reopen=0; grep -q "STORE_REOPEN_QEMU: PASS" "${serial}" && guest_reopen=1 + guest_slot=1 + if [[ "${settle}" -ge 3 ]]; then + guest_slot=0; grep -q "STORE_SLOT_REUSE_QEMU: PASS" "${serial}" && guest_slot=1 + fi + reopen_fields + exp="$(expect_for "${cp}")" + gen_ok=0 + case "${exp}" in + N) [[ "${gen}" == "${N}" ]] && gen_ok=1 ;; + NP1) [[ "${gen}" == "${NP1}" ]] && gen_ok=1 ;; + N_NP1) [[ "${gen}" == "${N}" || "${gen}" == "${NP1}" ]] && gen_ok=1 ;; + esac + ok=0 + if [[ "${saw_cp}" == 1 && "${gen_ok}" == 1 && "${guest_reopen}" == 1 && "${guest_slot}" == 1 \ + && "${st}" == Valid ]]; then ok=1; fi + printf 'settle=%s cp=%-24s saw=%s reopen=%s slot=%s gen=%s state=%-16s peer=%-13s expect=%-5s -> %s\n' \ + "${settle}" "${cp}" "${saw_cp}" "${guest_reopen}" "${guest_slot}" "${gen:-none}" "${st:-none}" \ + "${pclass:-none}" "${exp}" "$([ "${ok}" = 1 ] && echo OK || echo BAD)" >> "${work}/results_tier1.txt" + if [[ "${ok}" != 1 ]]; then fail=1; fi + done +done +cat "${work}/results_tier1.txt" +tier1_pass=1 +grep -q ' -> BAD' "${work}/results_tier1.txt" && tier1_pass=0 +[[ "${tier1_pass}" == 1 ]] && echo "STORE_512B_CRASH_OBSERVED_QEMU: PASS" || echo "STORE_512B_CRASH_OBSERVED_QEMU: FAIL" + +# --- Tier 2a: root tear closure on the real Tier 1 images ------------------- +echo +echo "=== Tier 2a: Root Tear Closure (host proof over Tier 1 images) ===" +tier2a_pass=1 +for settle in 0 3; do + if ! "${tool}" tear-closure "${work}/saved/s${settle}_after_first_flush.img" \ + "${work}/saved/s${settle}_after_final_flush.img" "${store_offset}" "${lba_bytes}" \ + | sed "s/^/settle=${settle} /"; then + tier2a_pass=0; fail=1 + echo "settle=${settle} STORE_ROOT_TEAR_CLOSURE: FAIL" + fi +done +[[ "${tier2a_pass}" == 1 ]] && echo "STORE_512B_ROOT_TEAR_CLOSURE: PASS" || echo "STORE_512B_ROOT_TEAR_CLOSURE: FAIL" + +# --- Tier 2b: deterministic injected-root recovery -------------------------- +echo +echo "=== Tier 2b: Injected Root Recovery (media corruption, one defect per case) ===" +# Base: settle-0 image killed at after_first_flush (gen 1 in slot 0, gen 2 +# objects durable, slot 1 zero). Source: the real gen-2 superblock from the +# after_final_flush image. graph_bad_newer uses the after_payloads image, +# where the gen-2 catalog and commit record were never written. +base_flush="${work}/saved/s0_after_first_flush.img" +base_payloads="${work}/saved/s0_after_payloads.img" +source_root="${work}/saved/s0_after_final_flush.img" + +# case base tool-case expected-outcome +inject_cases=( + "bad_crc flush bad_crc degraded:Malformed" + "wrong_magic flush wrong_magic degraded:Malformed" + "nonzero_reserved flush nonzero_reserved degraded:Malformed" + "wrong_slot_id flush wrong_slot_id degraded:Malformed" + "region_mismatch flush region_mismatch degraded:Malformed" + "seeded_garbage flush seeded_garbage degraded:Malformed" + "unsupported_version flush unsupported_version refuse:UnsupportedVersion" + "graph_bad_newer payloads new_root degraded:GraphBadNewer" + "control_new_root flush new_root valid:gen2" +) + +tier2b_pass=1 +for row in "${inject_cases[@]}"; do + read -r name base tcase expect <<<"${row}" + if [[ "${base}" == flush ]]; then cp "${base_flush}" "${image}"; else cp "${base_payloads}" "${image}"; fi + if ! "${tool}" inject "${image}" "${store_offset}" 1 "${tcase}" "${source_root}" >"${work}/inject.txt" 2>&1; then + echo "case=${name} injection refused: $(cat "${work}/inject.txt")" >> "${work}/results_tier2b.txt" + tier2b_pass=0; fail=1; continue + fi + write_cfg 4 0 + run_qemu "STORE_REOPEN_QEMU:" + gen=""; st=""; pclass="" + reopen_fields + active=0; grep -q "STORE_512B_NONATOMIC_QUALIFICATION: ACTIVE" "${serial}" && active=1 + ro=0; grep -q "STORE_DEGRADED_READONLY_QEMU: PASS" "${serial}" && ro=1 + ok=0 + case "${expect}" in + degraded:*) + [[ "${active}" == 1 && "${gen}" == 1 && "${st}" == DegradedRecovery && \ + "${pclass}" == "${expect#degraded:}" && "${ro}" == 1 ]] && \ + grep -q "STORE_REOPEN_QEMU: PASS" "${serial}" && ok=1 ;; + refuse:*) + grep -q "STORE_REOPEN_QEMU: FAIL (open ${expect#refuse:})" "${serial}" && [[ -z "${gen}" ]] && ok=1 ;; + valid:gen2) + [[ "${gen}" == 2 && "${st}" == Valid && "${pclass}" == Valid ]] && \ + grep -q "STORE_REOPEN_QEMU: PASS" "${serial}" && ok=1 ;; + esac + printf 'case=%-20s %-32s gen=%s state=%-16s peer=%-13s readonly=%s expect=%-28s -> %s\n' \ + "${name}" "$(cut -d' ' -f4 "${work}/inject.txt")" "${gen:-none}" "${st:-none}" "${pclass:-none}" "${ro}" \ + "${expect}" "$([ "${ok}" = 1 ] && echo OK || echo BAD)" >> "${work}/results_tier2b.txt" + if [[ "${ok}" != 1 ]]; then tier2b_pass=0; fail=1; fi +done +cat "${work}/results_tier2b.txt" +[[ "${tier2b_pass}" == 1 ]] && echo "STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: PASS" || echo "STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: FAIL" + +echo +echo "=== Final Summary (commit ${commit}) ===" +[[ "${integration_pass}" == 1 && "${reopen_pass}" == 1 ]] && echo "STORE_NVME_INTEGRATION_512B_QEMU: PASS" || echo "STORE_NVME_INTEGRATION_512B_QEMU: FAIL" +[[ "${tier1_pass}" == 1 ]] && echo "STORE_512B_CRASH_OBSERVED_QEMU: PASS" || echo "STORE_512B_CRASH_OBSERVED_QEMU: FAIL" +[[ "${tier2a_pass}" == 1 ]] && echo "STORE_512B_ROOT_TEAR_CLOSURE: PASS" || echo "STORE_512B_ROOT_TEAR_CLOSURE: FAIL" +[[ "${tier2b_pass}" == 1 ]] && echo "STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: PASS" || echo "STORE_512B_INJECTED_ROOT_RECOVERY_QEMU: FAIL" + +if [[ "${fail}" == 0 && "${integration_pass}" == 1 && "${reopen_pass}" == 1 && "${tier1_pass}" == 1 \ + && "${tier2a_pass}" == 1 && "${tier2b_pass}" == 1 ]]; then + echo "STORE_512B_CRASH_RECOVERY_QEMU: PASS" +else + echo "STORE_512B_CRASH_RECOVERY_QEMU: FAIL" + exit 1 +fi + +echo "P3_STORE_QEMU: NOT CLAIMED (QEMU campaign; native persistence conditions separate)" +echo "P3_STORE_NATIVE: NOT CLAIMED"