From 728930ec6d235765b82a9ed660c056a70ce9c193 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 09:29:23 -0500 Subject: [PATCH 1/4] feat(nvme): explicit-namespace write/read and write-path corrections Make the namespace id a parameter of the transfer path and expose read_blocks_nsid / write_blocks_nsid. The BlockDevice trait still fixes NSID 1, so generic callers are unchanged, but the qualification phase can now exercise the invalid-namespace error path and future multi-namespace use does not need to special-case the driver. Also replace the stale build_prps overflow comment in tests/nvme_prp.rs with a regression-test note (the checked_add fix already landed). Adds a simulator test proving an explicit invalid-namespace write returns BlockError::DeviceError and a valid explicit-namespace write round-trips. --- crates/aienos-kernel/src/nvme/driver.rs | 71 +++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/crates/aienos-kernel/src/nvme/driver.rs b/crates/aienos-kernel/src/nvme/driver.rs index c5894dc0..0b795af2 100644 --- a/crates/aienos-kernel/src/nvme/driver.rs +++ b/crates/aienos-kernel/src/nvme/driver.rs @@ -290,7 +290,13 @@ impl NvmeController { } } - fn transfer(&mut self, write: bool, lba: u64, data: &mut [u8]) -> Result<(), BlockError> { + fn transfer( + &mut self, + nsid: u32, + write: bool, + lba: u64, + data: &mut [u8], + ) -> Result<(), BlockError> { let info = self.ensure_namespace()?; let block_size = info.block_size as usize; if data.is_empty() || !data.len().is_multiple_of(block_size) { @@ -347,9 +353,21 @@ impl NvmeController { .map_err(map_error)?; } self.submit_io(if write { - Submission::write(1, lba + (offset / block_size) as u64, count as u16, p1, p2) + Submission::write( + nsid, + lba + (offset / block_size) as u64, + count as u16, + p1, + p2, + ) } else { - Submission::read(1, lba + (offset / block_size) as u64, count as u16, p1, p2) + Submission::read( + nsid, + lba + (offset / block_size) as u64, + count as u16, + p1, + p2, + ) })?; if !write { self.dma @@ -423,11 +441,11 @@ impl crate::block::BlockDevice for NvmeCon self.namespace.map_or(0, |n| n.block_count) } fn read_blocks(&mut self, lba: u64, buffer: &mut [u8]) -> Result<(), BlockError> { - self.transfer(false, lba, buffer) + self.transfer(1, false, lba, buffer) } fn write_blocks(&mut self, lba: u64, buffer: &[u8]) -> Result<(), BlockError> { let mut owned = buffer.to_vec(); - self.transfer(true, lba, &mut owned) + self.transfer(1, true, lba, &mut owned) } fn flush(&mut self) -> Result<(), BlockError> { self.submit_io({ @@ -439,6 +457,32 @@ impl crate::block::BlockDevice for NvmeCon } } +impl NvmeController { + /// Read `buffer` from an explicit namespace id. The `BlockDevice` trait + /// path fixes NSID 1; this exists so a caller (and the qualification + /// phase) can exercise the invalid-namespace error path and any future + /// multi-namespace use without special-casing the driver. + pub fn read_blocks_nsid( + &mut self, + nsid: u32, + lba: u64, + buffer: &mut [u8], + ) -> Result<(), BlockError> { + self.transfer(nsid, false, lba, buffer) + } + + /// Write `buffer` to an explicit namespace id. See `read_blocks_nsid`. + pub fn write_blocks_nsid( + &mut self, + nsid: u32, + lba: u64, + buffer: &[u8], + ) -> Result<(), BlockError> { + let mut owned = buffer.to_vec(); + self.transfer(nsid, true, lba, &mut owned) + } +} + #[cfg(test)] mod tests { use super::*; @@ -1030,4 +1074,21 @@ mod tests { Some(NvmeError::InvalidIdentify) ); } + + #[test] + fn explicit_namespace_write_surfaces_device_error() { + let (regs, dma) = fixture(); + let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap(); + controller.create_io_queues(4).unwrap(); + // The simulator rejects any NSID other than 1 with a completion error. + assert_eq!( + controller.write_blocks_nsid(0xffff_ffff, 0, &[0xAB; 512]), + Err(BlockError::DeviceError) + ); + // A valid explicit namespace write still round-trips. + controller.write_blocks_nsid(1, 0, &[0xCD; 512]).unwrap(); + let mut out = [0u8; 512]; + controller.read_blocks_nsid(1, 0, &mut out).unwrap(); + assert_eq!(out, [0xCD; 512]); + } } From bdf77ae213d6032975a7bdd8d92746aed5c43527 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 09:29:23 -0500 Subject: [PATCH 2/4] test(nvme): qualify native write, flush, PRP, and completion paths Four external test crates, black-box against the public API, with their own programmable fakes: - tests/nvme_write.rs: opcode/NSID/LBA/NLB/PRP1 for one and many blocks, offset writes, out-of-range and non-block-multiple rejection, CID lifecycle, nonzero status, and an exact write-then-read round trip. - tests/nvme_flush.rs: Flush is opcode 0, NSID 1, results only on a successful completion, errors and timeouts propagate, and it is not a silent no-op (a command and doorbell must reach the device). - tests/nvme_write_prp.rs: one/multi-block, page crossing, PRP2, PRP list chaining at 4 KiB and 64 KiB, address and length overflow, misalignment, MDTS chunk splitting, and out-of-range writes rejected before any command. - tests/nvme_write_completion.rs: failed write and flush status, write and flush timeouts (bounded), completion queue wraparound across a write batch, invalid-namespace identify, CID mismatch, and wrong-phase completions ignored. All adversarial: no hardware, no sleeps, deterministic expectations. --- crates/aienos-kernel/tests/nvme_flush.rs | 510 +++++++++++++ crates/aienos-kernel/tests/nvme_prp.rs | 7 +- crates/aienos-kernel/tests/nvme_write.rs | 675 ++++++++++++++++++ .../tests/nvme_write_completion.rs | 551 ++++++++++++++ crates/aienos-kernel/tests/nvme_write_prp.rs | 578 +++++++++++++++ 5 files changed, 2317 insertions(+), 4 deletions(-) create mode 100644 crates/aienos-kernel/tests/nvme_flush.rs create mode 100644 crates/aienos-kernel/tests/nvme_write.rs create mode 100644 crates/aienos-kernel/tests/nvme_write_completion.rs create mode 100644 crates/aienos-kernel/tests/nvme_write_prp.rs diff --git a/crates/aienos-kernel/tests/nvme_flush.rs b/crates/aienos-kernel/tests/nvme_flush.rs new file mode 100644 index 00000000..6ae37a20 --- /dev/null +++ b/crates/aienos-kernel/tests/nvme_flush.rs @@ -0,0 +1,510 @@ +//! D2 integration tests: NVMe Flush (opcode 0x00) on the polled I/O queue. +//! +//! Target: `crates/aienos-kernel/tests/nvme_flush.rs`. +//! +//! Self-contained: this file uses only the public `aienos_kernel::nvme` and +//! `aienos_kernel::nvme::driver` API plus local `Registers`, `DmaMemory`, and +//! `Delay` fakes. The fake controller records every I/O command and every I/O +//! submission-doorbell write, so the tests can prove that `flush()` issues a +//! real Flush command that reaches the device instead of being a silent no-op. +//! +//! Base: aien-dev/aienos @ ef359ec. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use aienos_kernel::block::{BlockDevice, BlockError}; +use aienos_kernel::nvme::driver::{ + Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, +}; +use aienos_kernel::nvme::{ + doorbell_offset, Registers, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS, +}; + +const PAGE: usize = 4096; +/// CAP.DSTRD = 0 -> 4-byte doorbell stride. CAP.TO = 1 -> 500 ms ready budget. +const CAP_LOW: u32 = 0x0100_03ff; +const STRIDE: u32 = 4; +const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE); +const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE); +const NS_BLOCKS: u64 = 12_345; +/// The driver loops `for _ in 0..=1000`, i.e. 1001 polls, each backing off 1 ms. +const POLLS: u64 = 1_001; +const FLUSH_OPCODE: u8 = 0x00; +const WRITE_OPCODE: u8 = 0x01; +const IO_DEPTH: u16 = 4; + +type Shared = Rc>; + +// --------------------------------------------------------------------------- +// Device model +// --------------------------------------------------------------------------- + +/// Knobs the tests flip to shape I/O completion behaviour. +#[derive(Clone, Default)] +struct Behavior { + /// Raw status bits (SC/SCT/DNR) ORed with the phase bit before delivery. + io_raw_status: Option, + /// If true, never place an I/O completion (driver must bound its poll). + io_never_complete: bool, +} + +struct Region { + base: u64, + len: usize, + bytes: Vec, +} + +/// Every I/O command the device observed, parsed from its SQ entry. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct RecordedIo { + opcode: u8, + nsid: u32, + cid: u16, + cdw10: u32, + cdw11: u32, + prp1: u64, + prp2: u64, +} + +struct Device { + regions: Vec, + next_phys: u64, + cc: u32, + csts: u32, + asq: u64, + acq: u64, + admin_cq_base: Option, + admin_cq_len: usize, + io_sq_base: Option, + io_cq_base: Option, + io_depth: usize, + admin_sq_tail: usize, + admin_cq_tail: usize, + admin_phase: bool, + io_sq_tail: usize, + io_cq_tail: usize, + io_phase: bool, + admin_queue: VecDeque<[u8; 16]>, + io_queue: VecDeque<[u8; 16]>, + io_commands: u64, + io_sq_doorbells: u64, + io_log: Vec, + behavior: Behavior, +} + +impl Device { + fn new() -> Self { + Self { + regions: Vec::new(), + next_phys: 0x1000, + cc: 0, + csts: 0, + asq: 0, + acq: 0, + admin_cq_base: None, + admin_cq_len: 0, + io_sq_base: None, + io_cq_base: None, + io_depth: 0, + admin_sq_tail: 0, + admin_cq_tail: 0, + admin_phase: true, + io_sq_tail: 0, + io_cq_tail: 0, + io_phase: true, + admin_queue: VecDeque::new(), + io_queue: VecDeque::new(), + io_commands: 0, + io_sq_doorbells: 0, + io_log: Vec::new(), + behavior: Behavior::default(), + } + } + + fn alloc(&mut self, size: usize, alignment: usize) -> u64 { + let align = alignment.max(1) as u64; + let base = (self.next_phys + align - 1) & !(align - 1); + self.next_phys = base + size as u64; + self.regions.push(Region { + base, + len: size, + bytes: vec![0; size], + }); + base + } + + fn find_region(&self, physical: u64, len: usize) -> Option { + self.regions + .iter() + .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64) + } + + fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + if output.len() == 16 { + if let Some(base) = self.admin_cq_base { + if physical >= base && physical + 16 <= base + self.admin_cq_len as u64 { + match self.admin_queue.pop_front() { + Some(cqe) => output.copy_from_slice(&cqe), + None => output.fill(0), + } + return Ok(()); + } + } + if let Some(base) = self.io_cq_base { + let len = (self.io_depth * 16) as u64; + if physical >= base && physical + 16 <= base + len { + match self.io_queue.pop_front() { + Some(cqe) => output.copy_from_slice(&cqe), + None => output.fill(0), + } + return Ok(()); + } + } + } + match self.find_region(physical, output.len()) { + Some(i) => { + output.copy_from_slice(&self.regions[i].bytes[..output.len()]); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + match self.find_region(physical, input.len()) { + Some(i) => { + self.regions[i].bytes[..input.len()].copy_from_slice(input); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] { + let addr = base + (slot * 64) as u64; + let mut out = [0u8; 64]; + if let Some(i) = self.find_region(addr, 64) { + out.copy_from_slice(&self.regions[i].bytes[..64]); + } + out + } + + fn fill_identify(&mut self, prp: u64, cns: u32) { + if let Some(i) = self.find_region(prp, PAGE) { + let bytes = &mut self.regions[i].bytes; + if cns == 1 { + bytes[77] = 0; // MDTS = 0 -> 128 KiB chunk cap + } else { + bytes[0..8].copy_from_slice(&NS_BLOCKS.to_le_bytes()); + bytes[26] = 0; // FLBAS -> format 0 + bytes[128 + 2] = 9; // LBADS -> 512-byte blocks + } + } + } + + fn push_admin(&mut self, phase: bool, cid: u16, raw: u16) { + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); + self.admin_queue.push_back(cqe); + } + + fn push_io(&mut self, phase: bool, cid: u16, raw: u16) { + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); + self.io_queue.push_back(cqe); + } + + fn on_admin_doorbell(&mut self) { + let slot = self.admin_sq_tail; + let cmd = self.peek_command(self.asq, slot); + let opcode = cmd[0]; + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); + match opcode { + 0x06 => self.fill_identify(p1, cdw10), + 0x05 => { + // Create I/O CQ (QID 1): remember buffer and depth. + self.io_cq_base = Some(p1); + self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1; + } + 0x01 => self.io_sq_base = Some(p1), // Create I/O SQ (QID 1) + _ => {} + } + self.push_admin(self.admin_phase, cid, 0); + self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH; + self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH; + if self.admin_cq_tail == 0 { + self.admin_phase = !self.admin_phase; + } + } + + fn on_io_doorbell(&mut self) { + self.io_sq_doorbells += 1; + let Some(sq) = self.io_sq_base else { + return; + }; + if self.io_depth == 0 { + return; + } + let slot = self.io_sq_tail; + let cmd = self.peek_command(sq, slot); + let opcode = cmd[0]; + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); + let prp1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let prp2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap()); + let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); + let cdw11 = u32::from_le_bytes(cmd[44..48].try_into().unwrap()); + self.io_commands += 1; + self.io_log.push(RecordedIo { + opcode, + nsid, + cid, + cdw10, + cdw11, + prp1, + prp2, + }); + if !self.behavior.io_never_complete { + let raw = self.behavior.io_raw_status.unwrap_or(0); + self.push_io(self.io_phase, cid, raw); + } + self.io_sq_tail = (slot + 1) % self.io_depth; + self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth; + if self.io_cq_tail == 0 { + self.io_phase = !self.io_phase; + } + } + + fn reg_read(&mut self, offset: u32) -> u32 { + match offset { + 0 => CAP_LOW, + 4 => 0, + REG_CC => self.cc, + REG_CSTS => self.csts, + _ => 0, + } + } + + fn reg_write(&mut self, offset: u32, value: u32) { + match offset { + REG_CC => { + self.cc = value; + self.csts = if value & 1 == 0 { 0 } else { CSTS_RDY }; + } + REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value), + x if x == REG_ASQ + 4 => self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32), + REG_ACQ => { + self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value); + self.admin_cq_base = Some(self.acq); + self.admin_cq_len = PAGE; + } + x if x == REG_ACQ + 4 => { + self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32); + self.admin_cq_base = Some(self.acq); + self.admin_cq_len = PAGE; + } + ADMIN_DOORBELL => self.on_admin_doorbell(), + IO_SQ_DOORBELL => self.on_io_doorbell(), + _ => {} + } + } +} + +// --------------------------------------------------------------------------- +// Fakes implementing the public driver traits +// --------------------------------------------------------------------------- + +struct FakeRegs { + shared: Shared, +} + +impl Registers for FakeRegs { + fn read32(&mut self, offset: u32) -> u32 { + self.shared.borrow_mut().reg_read(offset) + } + fn write32(&mut self, offset: u32, value: u32) { + self.shared.borrow_mut().reg_write(offset, value); + } +} + +struct FakeDma { + shared: Shared, +} + +impl DmaMemory for FakeDma { + fn allocate(&mut self, size: usize, alignment: usize) -> Result { + let physical = self.shared.borrow_mut().alloc(size, alignment); + Ok(DmaRegion { + physical, + bytes: vec![0; size], + }) + } + fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().read_mem(physical, output) + } + fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().write_mem(physical, input) + } +} + +#[derive(Default)] +struct CountingDelay { + waited_us: Rc>, +} + +impl Delay for CountingDelay { + fn delay_us(&mut self, us: u32) { + *self.waited_us.borrow_mut() += u64::from(us); + } +} + +type Controller = NvmeController; + +fn make_controller() -> (Controller, Shared, Rc>) { + let shared: Shared = Rc::new(RefCell::new(Device::new())); + let regs = FakeRegs { + shared: shared.clone(), + }; + let dma = FakeDma { + shared: shared.clone(), + }; + let delay = CountingDelay::default(); + let waited = delay.waited_us.clone(); + let controller = NvmeController::init(regs, dma, delay).expect("init should succeed"); + (controller, shared, waited) +} + +fn recorded_io(shared: &Shared) -> Vec { + shared.borrow().io_log.clone() +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +/// Flush is opcode 0x00, addressed to NSID 1, with no PRP data pointer. +#[test] +fn flush_submits_opcode_zero_nsid_one_without_data_pointer() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + controller.flush().unwrap(); + + let log = recorded_io(&shared); + assert_eq!(log.len(), 1, "exactly one I/O command: the Flush"); + let flush = log[0]; + assert_eq!(flush.opcode, FLUSH_OPCODE, "Flush is opcode 0x00"); + assert_eq!(flush.nsid, 1, "Flush targets NSID 1"); + assert_eq!( + (flush.prp1, flush.prp2), + (0, 0), + "Flush is data-less: PRP1/PRP2 must stay zero" + ); + assert_eq!( + (flush.cdw10, flush.cdw11), + (0, 0), + "reserved CDW10/CDW11 must stay zero" + ); +} + +/// A zero-status completion means the controller reported the cache durable. +#[test] +fn successful_flush_completion_returns_ok() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + + assert_eq!(controller.flush(), Ok(())); + + let device = shared.borrow(); + assert_eq!(device.io_commands, 1, "the Flush reached the device"); + assert_eq!(device.io_log[0].opcode, FLUSH_OPCODE); +} + +/// Durability is exposed only through successful completion: any nonzero status +/// is a failure, never an assumed success. +#[test] +fn nonzero_flush_completion_status_returns_device_error() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + // status word 0x0002 -> status >> 1 == 1 (nonzero). + shared.borrow_mut().behavior.io_raw_status = Some(0x0002); + + assert_eq!(controller.flush(), Err(BlockError::DeviceError)); +} + +/// A missing completion is bounded and surfaced as a timeout, not an infinite +/// loop and not a fake success. +#[test] +fn flush_timeout_returns_timeout_and_is_bounded() { + let (mut controller, shared, waited) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_never_complete = true; + + let before = *waited.borrow(); + assert_eq!(controller.flush(), Err(BlockError::Timeout)); + assert_eq!( + *waited.borrow() - before, + POLLS * 1_000, + "the poll budget must be bounded" + ); +} + +/// Flush must not be a silent no-op: it must ring the I/O submission doorbell +/// and the command must actually reach the device simulator. +#[test] +fn flush_is_not_a_silent_no_op_doorbell_and_command_reach_device() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + let (doorbells_before, commands_before) = { + let device = shared.borrow(); + (device.io_sq_doorbells, device.io_commands) + }; + + controller.flush().unwrap(); + + let device = shared.borrow(); + assert_eq!( + device.io_sq_doorbells, + doorbells_before + 1, + "a Flush must ring the I/O submission-queue doorbell" + ); + assert_eq!( + device.io_commands, + commands_before + 1, + "the Flush command must reach the device" + ); + assert_eq!( + device.io_log.last().unwrap().opcode, + FLUSH_OPCODE, + "the delivered command is a Flush" + ); +} + +/// Flush after a write in the same session must use a fresh command id, never +/// reuse the write's CID. +#[test] +fn flush_after_write_in_same_session_uses_fresh_cid() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + + controller.write_blocks(0, &[0xAB; 512]).unwrap(); + controller.flush().unwrap(); + + let log = recorded_io(&shared); + assert_eq!(log.len(), 2, "one Write then one Flush"); + let write = log[0]; + let flush = log[1]; + assert_eq!(write.opcode, WRITE_OPCODE, "first command is a Write"); + assert_eq!(flush.opcode, FLUSH_OPCODE, "second command is a Flush"); + assert_ne!(flush.cid, write.cid, "Flush must not reuse the Write CID"); + assert_eq!( + flush.cid, + write.cid.wrapping_add(1), + "the CID must advance monotonically" + ); +} diff --git a/crates/aienos-kernel/tests/nvme_prp.rs b/crates/aienos-kernel/tests/nvme_prp.rs index bea048f5..064316b5 100644 --- a/crates/aienos-kernel/tests/nvme_prp.rs +++ b/crates/aienos-kernel/tests/nvme_prp.rs @@ -57,10 +57,9 @@ fn offset_plus_length_overflow_is_invalid() { #[test] fn max_address_short_length_is_invalid_without_panic() { - // Contract: address = usize::MAX, length = 2 -> Invalid, no panic. - // The baseline does not validate the end address; `build_prps` computes - // pages == 2 and then overflows u64 in `second` (debug panic / release wrap), - // so this fails until the end-address overflow is checked. + // Regression test for the end-address overflow fix: address = usize::MAX, + // length = 2 computes pages == 2, and the second data page would overflow + // u64. It must be rejected as Invalid with no panic and no wrap. let outcome = std::panic::catch_unwind(|| { let mut list = [0u64; 0]; build_prps(usize::MAX as u64, 2, P4K, 0, &mut list) diff --git a/crates/aienos-kernel/tests/nvme_write.rs b/crates/aienos-kernel/tests/nvme_write.rs new file mode 100644 index 00000000..fe11cd9f --- /dev/null +++ b/crates/aienos-kernel/tests/nvme_write.rs @@ -0,0 +1,675 @@ +//! External integration tests for the AIENOS P3 native NVMe write + flush lane. +//! +//! Target: `crates/aienos-kernel/tests/nvme_write.rs`. +//! Repo mirror (read-only): aien-dev/aienos @ ef359ec. +//! +//! Uses only the public `aienos_kernel::nvme` and +//! `aienos_kernel::nvme::driver` API plus our own `Registers`, `DmaMemory` +//! and `Delay` fakes. Unlike the completion fake, this device model is +//! *persistent*: `opcode 0x01` copies the DMA payload into a per-LBA disk map +//! and `opcode 0x02` copies it back, so a written buffer can be read back. +//! +//! Covered deterministically: +//! * one-block write command encoding (opcode/NSID/LBA/NLB/PRP1), +//! * 8-block single command within MDTS, +//! * starting LBA split across CDW10/CDW11 for an offset write, +//! * out-of-range writes rejected with no I/O doorbell / no DMA / no command, +//! * empty and non-block-multiple buffers -> InvalidInput, +//! * fresh command id per I/O command and CID-matched completion consumption, +//! * nonzero completion status -> DeviceError, +//! * 300-block MDTS chunking with correct per-chunk LBA and NLB, +//! * exact byte round-trip through `read_blocks`. + +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::rc::Rc; + +use aienos_kernel::block::{BlockDevice, BlockError}; +use aienos_kernel::nvme::driver::{ + Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, PAGE_SIZE, +}; +use aienos_kernel::nvme::{ + doorbell_offset, Registers, CC_EN, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS, +}; + +const CAP_LOW: u32 = 0x0100_03ff; // CAP.MQES = 1023, CAP.TO = 1 (500 ms), CAP.DSTRD = 0 +const STRIDE: u32 = 4; +const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE); +const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE); + +const NS_BLOCKS: u64 = 12_345; +const BLOCK_SIZE: usize = 512; + +type Shared = Rc>; + +// --------------------------------------------------------------------------- +// Persistent device model +// --------------------------------------------------------------------------- + +struct Region { + base: u64, + len: usize, + bytes: Vec, +} + +struct Device { + regions: Vec, + next_phys: u64, + cc: u32, + csts: u32, + asq: u64, + acq: u64, + io_sq_base: Option, + io_cq_base: Option, + io_depth: usize, + admin_sq_tail: usize, + admin_cq_tail: usize, + admin_phase: bool, + io_sq_tail: usize, + io_cq_tail: usize, + io_phase: bool, + /// I/O commands actually processed (one per I/O SQ doorbell that had a queue). + io_commands: u64, + /// I/O SQ doorbell register writes seen, including ones with no queue yet. + io_doorbell_writes: u64, + io_cids: Vec, + io_completed: Vec, + io_log: Vec<[u8; 64]>, + /// Persistent block store: LBA -> block payload. + disk: BTreeMap>, + namespace_blocks: u64, + lbads: u8, + mdts: u8, + completion_status: u16, + command_error: u16, +} + +impl Device { + fn new() -> Self { + Self { + regions: Vec::new(), + next_phys: 0x1000, + cc: 0, + csts: 0, + asq: 0, + acq: 0, + io_sq_base: None, + io_cq_base: None, + io_depth: 0, + admin_sq_tail: 0, + admin_cq_tail: 0, + admin_phase: true, + io_sq_tail: 0, + io_cq_tail: 0, + io_phase: true, + io_commands: 0, + io_doorbell_writes: 0, + io_cids: Vec::new(), + io_completed: Vec::new(), + io_log: Vec::new(), + disk: BTreeMap::new(), + namespace_blocks: NS_BLOCKS, + lbads: 9, + mdts: 0, + completion_status: 0, + command_error: 0, + } + } + + fn block_size(&self) -> usize { + 1usize << u32::from(self.lbads) + } + + fn alloc(&mut self, size: usize, alignment: usize) -> u64 { + let align = alignment.max(1) as u64; + let base = (self.next_phys + align - 1) & !(align - 1); + self.next_phys = base + size as u64; + self.regions.push(Region { + base, + len: size, + bytes: vec![0; size], + }); + base + } + + fn find_region(&self, physical: u64, len: usize) -> Option { + self.regions + .iter() + .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64) + } + + fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + let i = self + .find_region(physical, output.len()) + .ok_or(NvmeError::Dma)?; + let off = (physical - self.regions[i].base) as usize; + output.copy_from_slice(&self.regions[i].bytes[off..off + output.len()]); + Ok(()) + } + + fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + let i = self + .find_region(physical, input.len()) + .ok_or(NvmeError::Dma)?; + let off = (physical - self.regions[i].base) as usize; + self.regions[i].bytes[off..off + input.len()].copy_from_slice(input); + Ok(()) + } + + fn region_vec(&self, physical: u64, len: usize) -> Option> { + let i = self.find_region(physical, len)?; + let off = (physical - self.regions[i].base) as usize; + Some(self.regions[i].bytes[off..off + len].to_vec()) + } + + fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] { + let addr = base + (slot * 64) as u64; + let mut out = [0u8; 64]; + if let Some(bytes) = self.region_vec(addr, 64) { + out.copy_from_slice(&bytes); + } + out + } + + fn fill_identify(&mut self, prp: u64, cns: u32) { + if let Some(i) = self.find_region(prp, PAGE_SIZE) { + let bytes = &mut self.regions[i].bytes; + bytes.fill(0); + if cns == 1 { + bytes[77] = self.mdts; // MDTS + } else { + bytes[0..8].copy_from_slice(&self.namespace_blocks.to_le_bytes()); + bytes[26] = 0; // FLBAS -> format 0 + bytes[128 + 2] = self.lbads; // LBADS in descriptor 0 + } + } + } + + fn on_admin_doorbell(&mut self) { + let slot = self.admin_sq_tail; + let cmd = self.peek_command(self.asq, slot); + let opcode = cmd[0]; + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); + match opcode { + 0x06 => self.fill_identify(p1, cdw10), + 0x05 => { + self.io_cq_base = Some(p1); + self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1; + } + 0x01 => self.io_sq_base = Some(p1), + _ => {} + } + let at = self.acq + (self.admin_cq_tail * 16) as u64; + let mut raw = [0u8; 16]; + raw[12..14].copy_from_slice(&cid.to_le_bytes()); + raw[14..16].copy_from_slice(&u16::from(self.admin_phase).to_le_bytes()); + self.write_mem(at, &raw).ok(); + self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH; + self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH; + if self.admin_cq_tail == 0 { + self.admin_phase = !self.admin_phase; + } + } + + /// Decompose a transfer into (address, len) segments, mirroring the PRP + /// shapes `build_prps` produces: PRP1, optional PRP2, or a page list. + fn collect_segments(&self, p1: u64, p2: u64, len: usize) -> Vec<(u64, usize)> { + let mut segs = Vec::new(); + if len == 0 { + return segs; + } + let first = (PAGE_SIZE - (p1 as usize & (PAGE_SIZE - 1))).min(len); + segs.push((p1, first)); + let mut left = len - first; + if left == 0 { + return segs; + } + if p2 != 0 && left <= PAGE_SIZE { + segs.push((p2, left)); + return segs; + } + let per = PAGE_SIZE / 8; + let mut list_page = p2; + 'outer: while left > 0 { + let entries = match self.region_vec(list_page, PAGE_SIZE) { + Some(bytes) => bytes, + None => break, + }; + for i in 0..per { + let address = u64::from_le_bytes(entries[i * 8..i * 8 + 8].try_into().unwrap()); + if address == 0 { + break 'outer; + } + if i == per - 1 && left > PAGE_SIZE { + list_page = address; // chain pointer to the next list page + continue 'outer; + } + let n = left.min(PAGE_SIZE - (address as usize & (PAGE_SIZE - 1))); + segs.push((address, n)); + left -= n; + if left == 0 { + break 'outer; + } + } + } + segs + } + + fn on_io_doorbell(&mut self) { + let Some(sq) = self.io_sq_base else { return }; + if self.io_depth == 0 { + return; + } + let slot = self.io_sq_tail; + let cmd = self.peek_command(sq, slot); + self.io_commands += 1; + self.io_log.push(cmd); + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + self.io_cids.push(cid); + + let opcode = cmd[0]; + let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let p2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap()); + let lba = u64::from(u32::from_le_bytes(cmd[40..44].try_into().unwrap())) + | (u64::from(u32::from_le_bytes(cmd[44..48].try_into().unwrap())) << 32); + let nlb = u32::from_le_bytes(cmd[48..52].try_into().unwrap()) as usize; + let len = nlb.saturating_add(1) * self.block_size(); + let bs = self.block_size(); + + let mut err = 0u16; + if nsid != 1 { + err = 1 << 1; + } + match opcode { + 0x01 | 0x02 => { + let segs = self.collect_segments(p1, p2, len); + if opcode == 0x01 { + let mut flat = vec![0u8; len]; + let mut done = 0usize; + for (address, n) in segs { + if done + n > len { + break; + } + let bytes = self.region_vec(address, n).unwrap_or_else(|| vec![0; n]); + flat[done..done + n].copy_from_slice(&bytes); + done += n; + } + for b in 0..(len / bs) { + self.disk + .insert(lba + b as u64, flat[b * bs..(b + 1) * bs].to_vec()); + } + } else { + let mut flat = vec![0u8; len]; + for b in 0..(len / bs) { + if let Some(block) = self.disk.get(&(lba + b as u64)) { + flat[b * bs..(b + 1) * bs].copy_from_slice(block); + } + } + let mut done = 0usize; + for (address, n) in segs { + if done + n > len { + break; + } + self.write_mem(address, &flat[done..done + n]).ok(); + done += n; + } + } + } + 0x00 => {} // Flush: no payload. + _ => err = 1 << 1, + } + self.command_error = err; + self.push_io_completion(cid); + self.io_sq_tail = (slot + 1) % self.io_depth; + self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth; + if self.io_cq_tail == 0 { + self.io_phase = !self.io_phase; + } + } + + fn push_io_completion(&mut self, cid: u16) { + if let Some(base) = self.io_cq_base { + let at = base + (self.io_cq_tail * 16) as u64; + let mut raw = [0u8; 16]; + raw[12..14].copy_from_slice(&cid.to_le_bytes()); + let status = u16::from(self.io_phase) | self.completion_status | self.command_error; + raw[14..16].copy_from_slice(&status.to_le_bytes()); + self.write_mem(at, &raw).ok(); + } + self.io_completed.push(cid); + } + + fn reg_read(&mut self, offset: u32) -> u32 { + match offset { + 0 => CAP_LOW, + 4 => 0, + REG_CC => self.cc, + REG_CSTS => self.csts, + _ => 0, + } + } + + fn reg_write(&mut self, offset: u32, value: u32) { + match offset { + REG_CC => { + self.cc = value; + self.csts = if value & CC_EN == 0 { 0 } else { CSTS_RDY }; + } + REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value), + x if x == REG_ASQ + 4 => { + self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32); + } + REG_ACQ => self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value), + x if x == REG_ACQ + 4 => { + self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32); + } + ADMIN_DOORBELL => self.on_admin_doorbell(), + IO_SQ_DOORBELL => { + self.io_doorbell_writes += 1; + self.on_io_doorbell(); + } + _ => {} + } + } +} + +// --------------------------------------------------------------------------- +// Fakes implementing the public driver traits +// --------------------------------------------------------------------------- + +struct FakeRegs { + shared: Shared, +} + +impl Registers for FakeRegs { + fn read32(&mut self, offset: u32) -> u32 { + self.shared.borrow_mut().reg_read(offset) + } + fn write32(&mut self, offset: u32, value: u32) { + self.shared.borrow_mut().reg_write(offset, value); + } +} + +struct FakeDma { + shared: Shared, +} + +impl DmaMemory for FakeDma { + fn allocate(&mut self, size: usize, alignment: usize) -> Result { + let physical = self.shared.borrow_mut().alloc(size, alignment); + Ok(DmaRegion { + physical, + bytes: vec![0; size], + }) + } + fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().read_mem(physical, output) + } + fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().write_mem(physical, input) + } +} + +struct CountingDelay; + +impl Delay for CountingDelay { + fn delay_us(&mut self, _us: u32) {} +} + +type Controller = NvmeController; + +fn controller_with(namespace_blocks: u64, lbads: u8, mdts: u8) -> (Controller, Shared) { + let mut dev = Device::new(); + dev.namespace_blocks = namespace_blocks; + dev.lbads = lbads; + dev.mdts = mdts; + let shared: Shared = Rc::new(RefCell::new(dev)); + let regs = FakeRegs { + shared: shared.clone(), + }; + let dma = FakeDma { + shared: shared.clone(), + }; + let controller = + NvmeController::init(regs, dma, CountingDelay).expect("controller init should succeed"); + (controller, shared) +} + +fn controller() -> (Controller, Shared) { + controller_with(NS_BLOCKS, 9, 0) +} + +fn cdw(cmd: &[u8; 64], dword: usize) -> u32 { + u32::from_le_bytes(cmd[dword * 4..dword * 4 + 4].try_into().unwrap()) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[test] +fn write_one_block_encodes_opcode_nsid_lba_nlb_and_prp1() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + + let before = shared.borrow().regions.len(); + c.write_blocks(5, &[0xab; BLOCK_SIZE]).unwrap(); + + let dev = shared.borrow(); + assert_eq!(dev.io_commands, 1, "one block -> one I/O command"); + let cmd = *dev.io_log.last().unwrap(); + assert_eq!(cmd[0] & 0x7f, 0x01, "NVM Write opcode"); + assert_eq!(cdw(&cmd, 1), 1, "NSID = 1"); + assert_eq!(cdw(&cmd, 10), 5, "CDW10 = LBA low"); + assert_eq!(cdw(&cmd, 11), 0, "CDW11 = LBA high"); + assert_eq!(cdw(&cmd, 12), 0, "CDW12 = NLB = blocks - 1"); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let p2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap()); + assert_eq!(p2, 0, "single page transfer has no PRP2"); + assert_eq!(p1 & (PAGE_SIZE as u64 - 1), 0, "PRP1 is page aligned"); + assert_eq!( + dev.regions[before].base, p1, + "PRP1 points at the write buffer" + ); + assert_eq!(dev.regions[before].len, BLOCK_SIZE); + assert_eq!(dev.io_cids.len(), 1); +} + +#[test] +fn write_eight_blocks_is_one_command_with_nlb_seven() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + + let before = shared.borrow().regions.len(); + let data: Vec = (0..8 * BLOCK_SIZE).map(|i| i as u8).collect(); + c.write_blocks(100, &data).unwrap(); + + let dev = shared.borrow(); + assert_eq!(dev.io_commands, 1, "8 blocks fit in one MDTS chunk"); + let cmd = *dev.io_log.last().unwrap(); + assert_eq!(cdw(&cmd, 12), 7, "NLB = 8 - 1"); + assert_eq!(cdw(&cmd, 10), 100, "starting LBA"); + assert_eq!(cdw(&cmd, 1), 1, "NSID = 1"); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + assert_eq!(dev.regions[before].base, p1); + assert_eq!(dev.regions[before].len, 8 * BLOCK_SIZE); +} + +#[test] +fn offset_write_splits_lba_across_cdw10_and_cdw11() { + let (mut c, shared) = controller_with(0x1_0000_0010, 9, 0); + c.create_io_queues(4).unwrap(); + + let lba = 0x1_0000_0003u64; + c.write_blocks(lba, &[0x5a; 2 * BLOCK_SIZE]).unwrap(); + + let dev = shared.borrow(); + let cmd = *dev.io_log.last().unwrap(); + let lo = cdw(&cmd, 10); + let hi = cdw(&cmd, 11); + assert_eq!(lo, 3, "CDW10 = low 32 bits of LBA"); + assert_eq!(hi, 1, "CDW11 = high 32 bits of LBA"); + assert_eq!(u64::from(lo) | (u64::from(hi) << 32), lba); + assert_eq!(cdw(&cmd, 12), 1, "NLB for 2 blocks"); +} + +#[test] +fn write_past_block_count_is_out_of_range_without_io_submission() { + let (mut c, shared) = controller_with(16, 9, 0); + c.create_io_queues(4).unwrap(); + + let (cmds, doors, allocs) = { + let dev = shared.borrow(); + (dev.io_commands, dev.io_doorbell_writes, dev.regions.len()) + }; + + assert_eq!( + c.write_blocks(16, &[0u8; BLOCK_SIZE]), + Err(BlockError::OutOfRange) + ); + assert_eq!( + c.write_blocks(15, &[0u8; 2 * BLOCK_SIZE]), + Err(BlockError::OutOfRange) + ); + assert_eq!( + c.write_blocks(u64::MAX, &[0u8; BLOCK_SIZE]), + Err(BlockError::OutOfRange) + ); + + let dev = shared.borrow(); + assert_eq!(dev.io_commands, cmds, "no I/O command submitted"); + assert_eq!(dev.io_doorbell_writes, doors, "no I/O doorbell rung"); + assert_eq!( + dev.regions.len(), + allocs, + "no DMA allocated for a rejected write" + ); +} + +#[test] +fn empty_and_non_block_multiple_buffers_are_invalid_input() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + + let doors = shared.borrow().io_doorbell_writes; + assert_eq!(c.write_blocks(0, &[]), Err(BlockError::InvalidInput)); + assert_eq!( + c.write_blocks(0, &[0u8; BLOCK_SIZE + 1]), + Err(BlockError::InvalidInput) + ); + assert_eq!( + c.write_blocks(7, &[0u8; BLOCK_SIZE - 1]), + Err(BlockError::InvalidInput) + ); + assert_eq!( + shared.borrow().io_doorbell_writes, + doors, + "invalid input must not reach the doorbell" + ); + assert_eq!(shared.borrow().io_commands, 0); +} + +#[test] +fn each_io_command_gets_a_new_cid_and_completion_is_consumed() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + + c.write_blocks(0, &[1u8; BLOCK_SIZE]).unwrap(); + c.write_blocks(1, &[2u8; 2 * BLOCK_SIZE]).unwrap(); + c.write_blocks(10, &[3u8; BLOCK_SIZE]).unwrap(); + + let dev = shared.borrow(); + assert_eq!(dev.io_commands, 3); + assert_eq!(dev.io_cids.len(), 3, "one CID per submitted command"); + assert_eq!( + dev.io_completed, dev.io_cids, + "each completion echoed the submitted CID, so submit_io consumed it" + ); + for pair in dev.io_cids.windows(2) { + assert!(pair[0] < pair[1], "CIDs must be fresh and increasing"); + } + let mut unique = dev.io_cids.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), dev.io_cids.len(), "CIDs must never be reused"); +} + +#[test] +fn nonzero_write_completion_maps_to_device_error() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + shared.borrow_mut().completion_status = 2; // status >> 1 == 1 -> nonzero + + assert_eq!( + c.write_blocks(0, &[7u8; BLOCK_SIZE]), + Err(BlockError::DeviceError) + ); +} + +#[test] +fn mdts_chunking_submits_per_chunk_commands_with_correct_lba_and_nlb() { + let (mut c, shared) = controller(); + c.create_io_queues(4).unwrap(); + + let before = shared.borrow().regions.len(); + let blocks = 300usize; + let data: Vec = (0..blocks * BLOCK_SIZE).map(|i| (i % 251) as u8).collect(); + c.write_blocks(20, &data).unwrap(); + + let dev = shared.borrow(); + assert_eq!( + dev.io_commands, 2, + "300 blocks split at the 128 KiB MDTS cap -> 256 + 44" + ); + let c0 = dev.io_log[0]; + let c1 = dev.io_log[1]; + assert_eq!(cdw(&c0, 12), 255, "first chunk NLB = 256 - 1"); + assert_eq!(cdw(&c1, 12), 43, "second chunk NLB = 44 - 1"); + assert_eq!(cdw(&c0, 10), 20, "first chunk starting LBA"); + assert_eq!( + cdw(&c1, 10), + 20 + 256, + "second chunk advances by 256 blocks" + ); + assert_eq!( + dev.regions[before].base, + u64::from_le_bytes(c0[24..32].try_into().unwrap()), + "first chunk PRP1 points at its own data region" + ); + let c1_p1 = u64::from_le_bytes(c1[24..32].try_into().unwrap()); + assert!( + dev.regions.iter().any(|r| r.base == c1_p1), + "second chunk PRP1 points at its own data region" + ); + drop(dev); + + let mut out = vec![0u8; data.len()]; + c.read_blocks(20, &mut out).unwrap(); + assert_eq!(out, data, "chunked write round-trips exactly"); +} + +#[test] +fn written_bytes_read_back_exactly() { + let (mut c, _shared) = controller(); + c.create_io_queues(4).unwrap(); + + let data: Vec = (0..8 * BLOCK_SIZE).map(|i| (i * 31 + 7) as u8).collect(); + c.write_blocks(1234, &data).unwrap(); + + let mut out = vec![0u8; data.len()]; + c.read_blocks(1234, &mut out).unwrap(); + assert_eq!(out, data, "read-back must match the written bytes exactly"); + + // A never-written region reads back as zeros. + let mut zero = [0xffu8; BLOCK_SIZE]; + c.read_blocks(9999, &mut zero).unwrap(); + assert_eq!(zero, [0u8; BLOCK_SIZE]); + + // An offset read returns exactly the bytes written at that offset. + let mut tail = [0u8; BLOCK_SIZE]; + c.read_blocks(1234 + 7, &mut tail).unwrap(); + assert_eq!(tail, data[7 * BLOCK_SIZE..8 * BLOCK_SIZE]); +} diff --git a/crates/aienos-kernel/tests/nvme_write_completion.rs b/crates/aienos-kernel/tests/nvme_write_completion.rs new file mode 100644 index 00000000..17599e5a --- /dev/null +++ b/crates/aienos-kernel/tests/nvme_write_completion.rs @@ -0,0 +1,551 @@ +//! External integration tests for the native NVMe write + flush completion lane. +//! +//! Target: `crates/aienos-kernel/tests/nvme_write_completion.rs`. +//! +//! These tests drive `aienos_kernel::nvme::driver::NvmeController` only through +//! its public API plus local `Registers`, `DmaMemory`, and `Delay` fakes. The +//! fake device is programmable: it records every submitted I/O command and can +//! inject crafted 16-byte completions (wrong status, wrong command id, wrong +//! phase, all-zero, or none at all). +//! +//! Reachability notes for the negative paths: +//! * `NvmeController::identify_namespace(nsid)` is public and takes an arbitrary +//! `nsid`, so the invalid-namespace error path is reachable and tested here. +//! * `BlockDevice::write_blocks` and `BlockDevice::flush` both funnel through the +//! private `transfer`/`submit_io` path, which hard-codes namespace id `1` when +//! it builds `Submission::write(1, ...)`. There is no public method that takes +//! an NSID for I/O, so a *write-side* invalid-namespace test is NOT reachable +//! today. It would require a new public method such as +//! `write_blocks_ns(nsid, lba, buffer)`; we deliberately do not add it here. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use aienos_kernel::block::{BlockDevice, BlockError}; +use aienos_kernel::nvme::driver::{ + Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, +}; +use aienos_kernel::nvme::{ + doorbell_offset, Registers, Submission, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS, +}; + +const PAGE: usize = 4096; +/// CAP.DSTRD = 0 -> 4-byte doorbell stride; CAP.TO = 1 -> 500 ms ready budget; +/// CAP.MQES + 1 = 1024. +const CAP_LOW: u32 = 0x0100_03ff; +const STRIDE: u32 = 4; +const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE); +const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE); +const NS_BLOCKS: u64 = 12_345; +/// The driver's I/O poll budget is `for _ in 0..=1000`, i.e. 1001 iterations. +const POLLS: u64 = 1_001; +const IO_DEPTH: u16 = 4; + +type Shared = Rc>; + +/// One submitted I/O command, decoded from the SQ slot the driver filled. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct IoCommand { + opcode: u32, + cid: u16, + nsid: u32, + lba: u64, + blocks: u32, +} + +#[derive(Clone, Copy, Default)] +struct Behavior { + /// Raw SC/SCT/DNR bits delivered on I/O completions (phase bit added later). + io_raw_status: Option, + /// Added to the echoed command id; nonzero forces a command-id mismatch. + io_cid_delta: i32, + /// Emit this many wrong-phase (zeroed) completions before the real one. + io_stale_wrong_phase: u32, + /// If true, never place an I/O completion (driver must bound its poll). + io_never_complete: bool, + /// Reject `Identify` for any namespace other than NSID 1. + reject_bad_nsid: bool, +} + +struct Region { + base: u64, + len: usize, + bytes: Vec, +} + +struct Device { + regions: Vec, + next_phys: u64, + cc: u32, + csts: u32, + asq: u64, + acq: u64, + admin_cq_base: Option, + admin_cq_len: usize, + io_sq_base: Option, + io_cq_base: Option, + io_depth: usize, + admin_sq_tail: usize, + admin_cq_tail: usize, + admin_phase: bool, + io_sq_tail: usize, + io_cq_tail: usize, + io_phase: bool, + admin_queue: VecDeque<[u8; 16]>, + io_queue: VecDeque<[u8; 16]>, + io_commands: u64, + io_submissions: Vec, + behavior: Behavior, +} + +impl Device { + fn new() -> Self { + Self { + regions: Vec::new(), + next_phys: 0x1000, + cc: 0, + csts: 0, + asq: 0, + acq: 0, + admin_cq_base: None, + admin_cq_len: 0, + io_sq_base: None, + io_cq_base: None, + io_depth: 0, + admin_sq_tail: 0, + admin_cq_tail: 0, + admin_phase: true, + io_sq_tail: 0, + io_cq_tail: 0, + io_phase: true, + admin_queue: VecDeque::new(), + io_queue: VecDeque::new(), + io_commands: 0, + io_submissions: Vec::new(), + behavior: Behavior::default(), + } + } + + fn alloc(&mut self, size: usize, alignment: usize) -> u64 { + let align = alignment.max(1) as u64; + let base = (self.next_phys + align - 1) & !(align - 1); + self.next_phys = base + size as u64; + self.regions.push(Region { + base, + len: size, + bytes: vec![0; size], + }); + base + } + + fn find_region(&self, physical: u64, len: usize) -> Option { + self.regions + .iter() + .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64) + } + + /// Completion-queue reads are served from FIFO queues so a wrong-phase entry + /// can be parked ahead of the real one regardless of the exact slot address. + fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + if output.len() == 16 { + if let Some(base) = self.admin_cq_base { + if physical >= base && physical + 16 <= base + self.admin_cq_len as u64 { + match self.admin_queue.pop_front() { + Some(cqe) => output.copy_from_slice(&cqe), + None => output.fill(0), + } + return Ok(()); + } + } + if let Some(base) = self.io_cq_base { + let len = (self.io_depth * 16) as u64; + if physical >= base && physical + 16 <= base + len { + match self.io_queue.pop_front() { + Some(cqe) => output.copy_from_slice(&cqe), + None => output.fill(0), + } + return Ok(()); + } + } + } + match self.find_region(physical, output.len()) { + Some(i) => { + output.copy_from_slice(&self.regions[i].bytes[..output.len()]); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + match self.find_region(physical, input.len()) { + Some(i) => { + self.regions[i].bytes[..input.len()].copy_from_slice(input); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] { + let addr = base + (slot * 64) as u64; + let mut out = [0u8; 64]; + if let Some(i) = self.find_region(addr, 64) { + out.copy_from_slice(&self.regions[i].bytes[..64]); + } + out + } + + fn fill_identify(&mut self, prp: u64, cns: u32) { + if let Some(i) = self.find_region(prp, PAGE) { + let bytes = &mut self.regions[i].bytes; + if cns == 1 { + bytes[77] = 0; // MDTS = 0 -> 128 KiB default chunk limit. + } else { + bytes[0..8].copy_from_slice(&NS_BLOCKS.to_le_bytes()); + bytes[26] = 0; // FLBAS -> format 0 + bytes[128 + 2] = 9; // LBADS -> 512-byte blocks + } + } + } + + fn push_admin(&mut self, phase: bool, cid: u16, raw: u16) { + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); + self.admin_queue.push_back(cqe); + } + + fn push_io(&mut self, phase: bool, cid: u16, raw: u16) { + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); + self.io_queue.push_back(cqe); + } + + /// A malformed, all-zero-otherwise CQE tagged with the *wrong* phase bit. + fn push_io_wrong_phase(&mut self) { + let mut cqe = [0u8; 16]; + cqe[14..16].copy_from_slice(&u16::from(!self.io_phase).to_le_bytes()); + self.io_queue.push_back(cqe); + } + + fn on_admin_doorbell(&mut self) { + let slot = self.admin_sq_tail; + let cmd = self.peek_command(self.asq, slot); + let opcode = u32::from_le_bytes(cmd[0..4].try_into().unwrap()) & 0xff; // low byte; high half is the CID + let cid = u16::from_le_bytes(cmd[2..4].try_into().unwrap()); + let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); + let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); + let mut raw = 0u16; + match opcode { + 0x06 => { + if cdw10 == 0 && self.behavior.reject_bad_nsid && nsid != 1 { + raw |= 0x0002; // SC 0x01: invalid namespace, SCT 0. + } else { + self.fill_identify(p1, cdw10); + } + } + 0x05 => { + self.io_cq_base = Some(p1); + self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1; + } + 0x01 => self.io_sq_base = Some(p1), + _ => {} + } + let echo = if self.behavior.io_cid_delta == 0 { + cid + } else { + cid.wrapping_add(self.behavior.io_cid_delta as u16) + }; + self.push_admin(self.admin_phase, echo, raw); + self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH; + self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH; + if self.admin_cq_tail == 0 { + self.admin_phase = !self.admin_phase; + } + } + + fn on_io_doorbell(&mut self) { + let Some(sq) = self.io_sq_base else { return }; + if self.io_depth == 0 { + return; + } + let slot = self.io_sq_tail; + let cmd = self.peek_command(sq, slot); + let opcode = u32::from_le_bytes(cmd[0..4].try_into().unwrap()) & 0xff; // low byte; high half is the CID + let cid = u16::from_le_bytes(cmd[2..4].try_into().unwrap()); + let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); + let lba = u64::from(u32::from_le_bytes(cmd[40..44].try_into().unwrap())) + | (u64::from(u32::from_le_bytes(cmd[44..48].try_into().unwrap())) << 32); + let blocks = u32::from_le_bytes(cmd[48..52].try_into().unwrap()) + 1; + self.io_submissions.push(IoCommand { + opcode, + cid, + nsid, + lba, + blocks, + }); + self.io_commands += 1; + if !self.behavior.io_never_complete { + let mut stale = self.behavior.io_stale_wrong_phase; + while stale > 0 { + self.push_io_wrong_phase(); + stale -= 1; + } + let echo = if self.behavior.io_cid_delta == 0 { + cid + } else { + cid.wrapping_add(self.behavior.io_cid_delta as u16) + }; + let raw = self.behavior.io_raw_status.unwrap_or(0); + self.push_io(self.io_phase, echo, raw); + } + self.io_sq_tail = (slot + 1) % self.io_depth; + self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth; + if self.io_cq_tail == 0 { + self.io_phase = !self.io_phase; + } + } + + fn reg_read(&mut self, offset: u32) -> u32 { + match offset { + 0 => CAP_LOW, + 4 => 0, + REG_CC => self.cc, + REG_CSTS => self.csts, + _ => 0, + } + } + + fn reg_write(&mut self, offset: u32, value: u32) { + match offset { + REG_CC => { + self.cc = value; + self.csts = if value & 1 == 0 { 0 } else { CSTS_RDY }; + } + REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value), + x if x == REG_ASQ + 4 => self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32), + REG_ACQ => { + self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value); + self.admin_cq_base = Some(self.acq); + self.admin_cq_len = PAGE; + } + x if x == REG_ACQ + 4 => { + self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32); + self.admin_cq_base = Some(self.acq); + self.admin_cq_len = PAGE; + } + ADMIN_DOORBELL => self.on_admin_doorbell(), + IO_SQ_DOORBELL => self.on_io_doorbell(), + _ => {} + } + } +} + +// --------------------------------------------------------------------------- +// Fakes implementing the public driver traits +// --------------------------------------------------------------------------- + +struct FakeRegs { + shared: Shared, +} + +impl Registers for FakeRegs { + fn read32(&mut self, offset: u32) -> u32 { + self.shared.borrow_mut().reg_read(offset) + } + fn write32(&mut self, offset: u32, value: u32) { + self.shared.borrow_mut().reg_write(offset, value); + } +} + +struct FakeDma { + shared: Shared, +} + +impl DmaMemory for FakeDma { + fn allocate(&mut self, size: usize, alignment: usize) -> Result { + let physical = self.shared.borrow_mut().alloc(size, alignment); + Ok(DmaRegion { + physical, + bytes: vec![0; size], + }) + } + fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().read_mem(physical, output) + } + fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + self.shared.borrow_mut().write_mem(physical, input) + } +} + +#[derive(Default)] +struct CountingDelay { + waited_us: Rc>, +} + +impl Delay for CountingDelay { + fn delay_us(&mut self, us: u32) { + *self.waited_us.borrow_mut() += u64::from(us); + } +} + +type Controller = NvmeController; + +/// Build a controller that completes its initialization normally. +fn make_controller() -> (Controller, Shared, Rc>) { + let shared: Shared = Rc::new(RefCell::new(Device::new())); + let regs = FakeRegs { + shared: shared.clone(), + }; + let dma = FakeDma { + shared: shared.clone(), + }; + let delay = CountingDelay::default(); + let waited = delay.waited_us.clone(); + let controller = NvmeController::init(regs, dma, delay).expect("init should succeed"); + (controller, shared, waited) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[test] +fn failed_write_completion_maps_to_device_error() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_raw_status = Some(0x0002); + assert_eq!( + controller.write_blocks(0, &[0xAB; 512]), + Err(BlockError::DeviceError) + ); + let device = shared.borrow(); + assert_eq!(device.io_submissions.len(), 1); + let command = device.io_submissions[0]; + assert_eq!(command.opcode, 0x01, "write opcode"); + assert_eq!(command.nsid, 1, "writes are hard-coded to NSID 1"); + assert_eq!(command.lba, 0); + assert_eq!(command.blocks, 1); + // A failing completion is still consumed; the driver's CQ head advances. + assert_eq!(controller.io_queue().unwrap().completion_head, 1); +} + +#[test] +fn failed_flush_completion_maps_to_device_error() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_raw_status = Some(0x0084); + assert_eq!(controller.flush(), Err(BlockError::DeviceError)); + let device = shared.borrow(); + assert_eq!(device.io_submissions.len(), 1); + assert_eq!(device.io_submissions[0].opcode, 0x00, "flush opcode"); + assert_eq!(device.io_submissions[0].nsid, 1); +} + +#[test] +fn write_timeout_is_bounded_no_infinite_loop() { + let (mut controller, shared, waited) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_never_complete = true; + let before = *waited.borrow(); + assert_eq!( + controller.write_blocks(0, &[0; 512]), + Err(BlockError::Timeout) + ); + assert_eq!(*waited.borrow() - before, POLLS * 1_000); + // Nothing was consumed because nothing ever completed. + assert_eq!(controller.io_queue().unwrap().completion_head, 0); +} + +#[test] +fn flush_timeout_is_bounded_no_infinite_loop() { + let (mut controller, shared, waited) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_never_complete = true; + let before = *waited.borrow(); + assert_eq!(controller.flush(), Err(BlockError::Timeout)); + assert_eq!(*waited.borrow() - before, POLLS * 1_000); +} + +#[test] +fn write_batch_cq_wraparound_flips_phase_and_consumes_in_order() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + for lba in 0..4u64 { + controller.write_blocks(lba, &[(lba as u8); 512]).unwrap(); + } + { + let device = shared.borrow(); + assert_eq!(device.io_cq_tail, 0, "producer tail wraps at depth 4"); + assert!(!device.io_phase, "producer phase flips after the wrap"); + assert_eq!(device.io_commands, 4); + let lbas: Vec = device.io_submissions.iter().map(|c| c.lba).collect(); + assert_eq!(lbas, vec![0, 1, 2, 3], "commands recorded in submit order"); + } + { + let q = controller.io_queue().unwrap(); + assert_eq!(q.completion_head, 0, "consumer head wraps at depth 4"); + assert!(!q.phase, "consumer flips in lockstep with the producer"); + } + // The fifth write only completes if the driver flipped in lockstep. + controller.write_blocks(4, &[0x44; 512]).unwrap(); + let q = controller.io_queue().unwrap(); + assert_eq!(q.completion_head, 1); + assert!(!q.phase, "phase stays flipped past the wrap"); + assert!(shared.borrow().io_queue.is_empty()); +} + +#[test] +fn invalid_namespace_identify_surfaces_completion_status() { + let (mut controller, shared, _) = make_controller(); + shared.borrow_mut().behavior.reject_bad_nsid = true; + // NSID 1 stays reachable and valid. + assert_eq!( + controller.identify_namespace(1).unwrap().block_count, + NS_BLOCKS + ); + // NSID 2 is rejected by the controller with a non-zero status. + assert_eq!( + controller.identify_namespace(2), + Err(NvmeError::CompletionStatus { sct: 0, sc: 1 }) + ); +} + +#[test] +fn write_command_id_mismatch_maps_to_device_error() { + let (mut controller, shared, _) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + shared.borrow_mut().behavior.io_cid_delta = 1; + assert_eq!( + controller.write_blocks(0, &[0; 512]), + Err(BlockError::DeviceError) + ); + // A command-id mismatch is rejected before the head advances. + assert_eq!(controller.io_queue().unwrap().completion_head, 0); +} + +#[test] +fn wrong_phase_zero_completion_is_ignored_not_consumed() { + let (mut controller, shared, waited) = make_controller(); + controller.create_io_queues(IO_DEPTH).unwrap(); + // An all-zero CQE (phase bit 0) is parked ahead of the real completion. + shared.borrow_mut().behavior.io_stale_wrong_phase = 1; + let before = *waited.borrow(); + controller.write_blocks(0, &[0x5A; 512]).unwrap(); + // Exactly one backoff: the mismatched entry was read and skipped, never + // consumed. The CQ head advanced once, only for the real completion. + assert_eq!(*waited.borrow() - before, 1_000); + let q = controller.io_queue().unwrap(); + assert_eq!(q.completion_head, 1); + assert!(q.phase); +} + +// Keep `Submission` in scope and document the command layout the fake parses. +#[allow(dead_code)] +fn io_command_layout_probe() -> Submission { + Submission::write(1, 0, 1, 0, 0) +} diff --git a/crates/aienos-kernel/tests/nvme_write_prp.rs b/crates/aienos-kernel/tests/nvme_write_prp.rs new file mode 100644 index 00000000..30812edb --- /dev/null +++ b/crates/aienos-kernel/tests/nvme_write_prp.rs @@ -0,0 +1,578 @@ +//! D3 adversarial tests for the AIENOS P3 native NVMe **write + flush** lane. +//! +//! Target: `crates/aienos-kernel/tests/nvme_write_prp.rs`. Baseline: +//! aien-dev/aienos @ ef359ec. +//! +//! Pure PRP geometry is asserted against the real +//! `aienos_kernel::nvme::build_prps` with exact expected values. Transfer +//! behavior (one-block writes, page-crossing, MDTS chunk splitting, LBA range +//! rejection, flush) is driven through a self-contained fake controller built +//! only from the public `Registers`/`DmaMemory`/`Delay` traits, which records +//! every I/O command it is handed. No sleeps, no hardware, no repo internals. + +use std::cell::RefCell; +use std::rc::Rc; + +use aienos_kernel::block::{BlockDevice, BlockError}; +use aienos_kernel::nvme::driver::{ + Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, PAGE_SIZE, +}; +use aienos_kernel::nvme::{ + build_prps, doorbell_offset, PrpError, Registers, CC_EN, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, + REG_CSTS, +}; + +const P4K: usize = 4096; +const P64K: usize = 65536; +/// CAP.TO = 1 (500 ms units), MQES = 1023, DSTRD = 0, MPSMIN = 0. +const CAP_LOW: u32 = 0x0100_03ff; +const STRIDE: u32 = 4; +const ADMIN_SQ_DB: u32 = doorbell_offset(0, false, STRIDE); +const IO_SQ_DB: u32 = doorbell_offset(1, false, STRIDE); + +// --------------------------------------------------------------------------- +// Fake controller: an in-memory NVMe device answering admin and I/O commands. +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct IoCommand { + opcode: u8, + nsid: u32, + lba: u64, + blocks: u16, + prp1: u64, + prp2: u64, +} + +struct Region { + base: u64, + len: usize, + bytes: Vec, +} + +struct Device { + regions: Vec, + next_phys: u64, + cc: u32, + csts: u32, + namespace_size: u64, + mdts: u8, + command_error: u16, + admin_sq: u64, + admin_cq: u64, + admin_sq_tail: usize, + admin_cq_tail: usize, + admin_phase: bool, + io_sq: u64, + io_cq: u64, + io_sq_tail: usize, + io_cq_tail: usize, + io_phase: bool, + io_depth: usize, + io_commands: Vec, +} + +impl Device { + fn new(namespace_size: u64, mdts: u8) -> Self { + Self { + regions: Vec::new(), + next_phys: 0x1000, + cc: 0, + csts: 0, + namespace_size, + mdts, + command_error: 0, + admin_sq: 0, + admin_cq: 0, + admin_sq_tail: 0, + admin_cq_tail: 0, + admin_phase: true, + io_sq: 0, + io_cq: 0, + io_sq_tail: 0, + io_cq_tail: 0, + io_phase: true, + io_depth: 0, + io_commands: Vec::new(), + } + } + + fn alloc(&mut self, size: usize, alignment: usize) -> u64 { + let align = alignment.max(1) as u64; + let base = (self.next_phys + align - 1) & !(align - 1); + self.next_phys = base + size as u64; + self.regions.push(Region { + base, + len: size, + bytes: vec![0; size], + }); + base + } + + fn region_index(&self, physical: u64, len: usize) -> Option { + self.regions + .iter() + .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64) + } + + fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + match self.region_index(physical, output.len()) { + Some(i) => { + output.copy_from_slice(&self.regions[i].bytes[..output.len()]); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + match self.region_index(physical, input.len()) { + Some(i) => { + self.regions[i].bytes[..input.len()].copy_from_slice(input); + Ok(()) + } + None => Err(NvmeError::Dma), + } + } + + fn poke(&mut self, physical: u64, bytes: &[u8]) { + if let Some(i) = self.region_index(physical, bytes.len()) { + self.regions[i].bytes[..bytes.len()].copy_from_slice(bytes); + } + } + + fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] { + let addr = base + (slot * 64) as u64; + let mut out = [0u8; 64]; + if let Some(i) = self.region_index(addr, 64) { + out.copy_from_slice(&self.regions[i].bytes[..64]); + } + out + } + + fn fill_identify(&mut self, prp: u64, cns: u32) { + if let Some(i) = self.region_index(prp, PAGE_SIZE) { + let data = &mut self.regions[i].bytes; + data.fill(0); + if cns == 1 { + data[77] = self.mdts; + } else { + data[0..8].copy_from_slice(&self.namespace_size.to_le_bytes()); + data[26] = 0; // FLBAS -> format 0 + data[130] = 9; // LBADS -> 512-byte blocks + } + } + } + + fn run_admin(&mut self) { + let slot = self.admin_sq_tail; + let cmd = self.peek_command(self.admin_sq, slot); + let opcode = cmd[0]; + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + let prp = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); + let cdw11 = u32::from_le_bytes(cmd[44..48].try_into().unwrap()); + self.command_error = 0; + match opcode { + 0x06 => self.fill_identify(prp, cdw10), + 0x05 => { + self.io_cq = prp; + self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1; + } + 0x01 if cdw10 & 0xffff == 1 && cdw11 & 0xffff == 1 => self.io_sq = prp, + _ => {} + } + let at = self.admin_cq + (self.admin_cq_tail * 16) as u64; + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16] + .copy_from_slice(&((self.admin_phase as u16) | self.command_error).to_le_bytes()); + self.poke(at, &cqe); + self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH; + if self.admin_cq_tail == 0 { + self.admin_phase = !self.admin_phase; + } + self.admin_sq_tail = (self.admin_sq_tail + 1) % ADMIN_DEPTH; + } + + fn run_io(&mut self) { + let depth = self.io_depth; + if depth == 0 { + return; + } + let slot = self.io_sq_tail; + let cmd = self.peek_command(self.io_sq, slot); + let opcode = cmd[0]; + let cid = u16::from_le_bytes([cmd[2], cmd[3]]); + let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); + let prp1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); + let prp2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap()); + let lba = u64::from(u32::from_le_bytes(cmd[40..44].try_into().unwrap())) + | (u64::from(u32::from_le_bytes(cmd[44..48].try_into().unwrap())) << 32); + let cdw12 = u32::from_le_bytes(cmd[48..52].try_into().unwrap()); + self.io_commands.push(IoCommand { + opcode, + nsid, + lba, + blocks: ((cdw12 & 0xffff) as u16).wrapping_add(1), + prp1, + prp2, + }); + let at = self.io_cq + (self.io_cq_tail * 16) as u64; + let mut cqe = [0u8; 16]; + cqe[12..14].copy_from_slice(&cid.to_le_bytes()); + cqe[14..16].copy_from_slice(&((self.io_phase as u16) | self.command_error).to_le_bytes()); + self.poke(at, &cqe); + self.io_cq_tail = (self.io_cq_tail + 1) % depth; + if self.io_cq_tail == 0 { + self.io_phase = !self.io_phase; + } + self.io_sq_tail = (self.io_sq_tail + 1) % depth; + } +} + +// --------------------------------------------------------------------------- +// Public-trait fakes over the shared device. +// --------------------------------------------------------------------------- + +type Shared = Rc>; + +struct FakeRegs { + dev: Shared, +} + +impl Registers for FakeRegs { + fn read32(&mut self, offset: u32) -> u32 { + let dev = self.dev.borrow(); + match offset { + 0 => CAP_LOW, + 4 => 0, + REG_CC => dev.cc, + REG_CSTS => dev.csts, + _ => 0, + } + } + + fn write32(&mut self, offset: u32, value: u32) { + let mut dev = self.dev.borrow_mut(); + match offset { + REG_CC => { + dev.cc = value; + dev.csts = if value & CC_EN == 0 { 0 } else { CSTS_RDY }; + } + REG_ASQ => dev.admin_sq = (dev.admin_sq & !0xffff_ffff) | u64::from(value), + x if x == REG_ASQ + 4 => { + dev.admin_sq = (dev.admin_sq & 0xffff_ffff) | (u64::from(value) << 32) + } + REG_ACQ => dev.admin_cq = (dev.admin_cq & !0xffff_ffff) | u64::from(value), + x if x == REG_ACQ + 4 => { + dev.admin_cq = (dev.admin_cq & 0xffff_ffff) | (u64::from(value) << 32) + } + ADMIN_SQ_DB => dev.run_admin(), + IO_SQ_DB => dev.run_io(), + _ => {} + } + } +} + +struct FakeDma { + dev: Shared, +} + +impl DmaMemory for FakeDma { + fn allocate(&mut self, size: usize, alignment: usize) -> Result { + let physical = self.dev.borrow_mut().alloc(size, alignment); + Ok(DmaRegion { + physical, + bytes: vec![0; size], + }) + } + + fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { + self.dev.borrow_mut().read_mem(physical, output) + } + + fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { + self.dev.borrow_mut().write_mem(physical, input) + } +} + +/// Host stand-in for a real-time delay: the fake device is always ready, so no +/// wait is ever needed. This keeps the tests free of sleeps. +struct NoDelay; + +impl Delay for NoDelay { + fn delay_us(&mut self, _us: u32) {} +} + +type Ctrl = NvmeController; + +fn make(namespace_size: u64, mdts: u8) -> (Ctrl, Shared) { + let dev: Shared = Rc::new(RefCell::new(Device::new(namespace_size, mdts))); + let regs = FakeRegs { dev: dev.clone() }; + let dma = FakeDma { dev: dev.clone() }; + let controller = NvmeController::init(regs, dma, NoDelay).expect("init should succeed"); + (controller, dev) +} + +fn io_commands(dev: &Shared) -> Vec { + dev.borrow().io_commands.clone() +} + +// --------------------------------------------------------------------------- +// PRP geometry: one block, page crossings, PRP lists, chaining. +// --------------------------------------------------------------------------- + +#[test] +fn one_block_aligned_write_is_single_prp1_page() { + // 512 bytes from a 4 KiB-aligned address live entirely in page one: + // PRP1 is the raw address, PRP2 unused, no list entries consumed. + let mut list = [0xDEAD_BEEFu64; 4]; + assert_eq!( + build_prps(0x1000, 512, P4K, 0x8000, &mut list).unwrap(), + (0x1000, 0, 0) + ); + assert_eq!(list, [0xDEAD_BEEF; 4], "list must be untouched"); +} + +#[test] +fn write_crossing_page_boundary_uses_prp1_and_prp2() { + let mut list = [0u64; 0]; + assert_eq!( + build_prps(0x1000, 2 * P4K, P4K, 0, &mut list).unwrap(), + (0x1000, 0x2000, 0) + ); + // Unaligned start: PRP1 stays raw, PRP2 is the next page boundary. + assert_eq!( + build_prps(0x1080, P4K, P4K, 0, &mut list).unwrap(), + (0x1080, 0x2000, 0) + ); +} + +#[test] +fn write_spanning_three_pages_uses_prp_list() { + let list_at = 0x80_0000u64; + let mut list = [0u64; 4]; + let (p1, p2, used) = build_prps(0x1000, 3 * P4K, P4K, list_at, &mut list).unwrap(); + assert_eq!((p1, p2, used), (0x1000, list_at, 2)); + assert_eq!(list[..2], [0x2000, 0x3000]); +} + +#[test] +fn write_page_list_chains_at_4k_exact_entries() { + const PER: usize = P4K / 8; // 512 entries per 4 KiB list page + let list_at = 0x80_0000u64; + + let mut full = vec![0u64; PER]; + let (p1, p2, used) = build_prps(0x1000, (1 + PER) * P4K, P4K, list_at, &mut full).unwrap(); + assert_eq!((p1, p2, used), (0x1000, list_at, PER)); + assert_eq!(full[PER - 1], 0x2000 + ((PER - 1) * P4K) as u64); + + let mut chain = vec![0u64; PER + 2]; + let (p1, p2, used) = build_prps(0x1000, (2 + PER) * P4K, P4K, list_at, &mut chain).unwrap(); + assert_eq!((p1, p2, used), (0x1000, list_at, PER + 2)); + assert_eq!(chain[PER - 1], list_at + P4K as u64, "last slot chains"); + assert_eq!(chain[PER - 2], 0x2000 + ((PER - 2) * P4K) as u64); + assert_eq!(chain[PER], 0x2000 + ((PER - 1) * P4K) as u64); + assert_eq!(chain[PER + 1], 0x2000 + (PER * P4K) as u64); +} + +#[test] +fn write_page_list_chains_at_64k_exact_entries() { + const PER: usize = P64K / 8; // 8192 entries per 64 KiB list page + let list_at = 0x200_0000u64; + + let mut full = vec![0u64; PER]; + let (p1, p2, used) = build_prps(0x10000, (1 + PER) * P64K, P64K, list_at, &mut full).unwrap(); + assert_eq!((p1, p2, used), (0x10000, list_at, PER)); + assert_eq!(full[PER - 1], 0x20000 + ((PER - 1) * P64K) as u64); + + let mut chain = vec![0u64; PER + 2]; + let (p1, p2, used) = build_prps(0x10000, (2 + PER) * P64K, P64K, list_at, &mut chain).unwrap(); + assert_eq!((p1, p2, used), (0x10000, list_at, PER + 2)); + assert_eq!(chain[PER - 1], list_at + P64K as u64, "last slot chains"); + assert_eq!(chain[PER - 2], 0x20000 + ((PER - 2) * P64K) as u64); + assert_eq!(chain[PER], 0x20000 + ((PER - 1) * P64K) as u64); + assert_eq!(chain[PER + 1], 0x20000 + (PER * P64K) as u64); +} + +// --------------------------------------------------------------------------- +// Overflow and misalignment. +// --------------------------------------------------------------------------- + +#[test] +fn address_near_u64_max_is_invalid_without_panic_or_wrap() { + let outcome = std::panic::catch_unwind(|| { + let mut list = [0u64; 0]; + build_prps(u64::MAX, 2, P4K, 0, &mut list) + }); + assert_eq!( + outcome.ok(), + Some(Err(PrpError::Invalid)), + "address=u64::MAX length=2 must be Invalid with no panic" + ); + + // Page-aligned address whose second page would wrap past u64::MAX. + let outcome = std::panic::catch_unwind(|| { + let mut list = [0u64; 0]; + build_prps(u64::MAX - (P4K as u64 - 1), 2 * P4K, P4K, 0, &mut list) + }); + assert_eq!( + outcome.ok(), + Some(Err(PrpError::Invalid)), + "second-page wrap past u64::MAX must be Invalid with no panic" + ); +} + +#[test] +fn offset_plus_length_overflow_is_invalid() { + let mut list = [0u64; 4]; + // Unaligned offset + enormous length overflows the covered span. + assert_eq!( + build_prps(0x1080, usize::MAX, P4K, 0x8000, &mut list), + Err(PrpError::Invalid) + ); + // Aligned start, length at usize::MAX: page rounding overflows. + assert_eq!( + build_prps(0, usize::MAX, P4K, 0x8000, &mut list), + Err(PrpError::Invalid) + ); + assert_eq!( + build_prps(u64::MAX, u64::MAX as usize, P4K, 0x8000, &mut list), + Err(PrpError::Invalid) + ); +} + +#[test] +fn unaligned_prp1_spans_pages_correctly() { + let list_at = 0x80_0000u64; + let mut list = [0u64; 4]; + // 0x1080 + (2*P4K + 0x100) ends in the third page from an unaligned start. + // With 3+ pages the second return is the PRP list pointer, and the first + // list entry is the next page boundary after the raw PRP1. + let (p1, p2, used) = build_prps(0x1080, 2 * P4K + 0x100, P4K, list_at, &mut list).unwrap(); + assert_eq!((p1, p2, used), (0x1080, list_at, 2)); + assert_eq!(list[..2], [0x2000, 0x3000]); +} + +#[test] +fn list_address_zero_or_unaligned_is_invalid_for_list_cases() { + let mut list = [0u64; 4]; + assert_eq!( + build_prps(0x1000, 3 * P4K, P4K, 0, &mut list), + Err(PrpError::Invalid), + "zero list address with a required list" + ); + assert_eq!( + build_prps(0x1000, 3 * P4K, P4K, 0x8001, &mut list), + Err(PrpError::Invalid), + "unaligned list address" + ); + assert_eq!( + build_prps(0x1000, 3 * P4K, P4K, 0xFFF, &mut list), + Err(PrpError::Invalid), + "list address at the top of a page" + ); + // A zero list address is fine when no list is needed (two pages -> PRP2). + assert_eq!( + build_prps(0x1000, 2 * P4K, P4K, 0, &mut list).unwrap(), + (0x1000, 0x2000, 0) + ); +} + +// --------------------------------------------------------------------------- +// Transfer path through the fake controller. +// --------------------------------------------------------------------------- + +#[test] +fn write_one_aligned_block_carries_single_prp1() { + let (mut c, dev) = make(4096, 0); + c.create_io_queues(8).unwrap(); + c.write_blocks(0, &[0xABu8; 512]).unwrap(); + + let cmds = io_commands(&dev); + assert_eq!(cmds.len(), 1); + let cmd = cmds[0]; + assert_eq!(cmd.opcode, 0x01, "write opcode"); + assert_eq!(cmd.nsid, 1); + assert_eq!(cmd.lba, 0); + assert_eq!(cmd.blocks, 1); + assert_eq!( + cmd.prp1 & (PAGE_SIZE as u64 - 1), + 0, + "PRP1 must be 4 KiB aligned" + ); + assert_eq!(cmd.prp2, 0, "single-page write must not use PRP2"); +} + +#[test] +fn multi_block_write_crossing_page_emits_prp2() { + let (mut c, dev) = make(4096, 0); + c.create_io_queues(8).unwrap(); + // Nine 512-byte blocks = 4608 bytes: two pages, one command. + c.write_blocks(3, &vec![0u8; 9 * 512]).unwrap(); + + let cmds = io_commands(&dev); + assert_eq!(cmds.len(), 1); + assert_eq!(cmds[0].blocks, 9); + assert_eq!(cmds[0].lba, 3); + assert_eq!(cmds[0].prp2, cmds[0].prp1 + PAGE_SIZE as u64); +} + +#[test] +fn write_larger_than_mdts_is_split_into_commands() { + // MDTS = 1 -> PAGE_SIZE << 1 = 8 KiB per command. A 32 KiB write must be + // split into four sequential 16-block commands in a namespace big enough. + let (mut c, dev) = make(100_000, 1); + c.create_io_queues(8).unwrap(); + c.write_blocks(0, &vec![0u8; 32 * 1024]).unwrap(); + + let cmds = io_commands(&dev); + assert_eq!(cmds.len(), 4, "32 KiB / 8 KiB = four commands"); + for (i, cmd) in cmds.iter().enumerate() { + assert_eq!(cmd.opcode, 0x01); + assert_eq!(cmd.blocks, 16, "8 KiB = 16 blocks of 512"); + assert_eq!(cmd.lba, (i as u64) * 16, "chunks advance by 16 LBAs"); + } + + // MDTS = 0 -> 128 KiB cap; the same write fits in a single command. + let (mut c, dev) = make(100_000, 0); + c.create_io_queues(8).unwrap(); + c.write_blocks(0, &vec![0u8; 32 * 1024]).unwrap(); + assert_eq!(io_commands(&dev).len(), 1); +} + +#[test] +fn write_past_namespace_end_is_rejected_before_any_command() { + let (mut c, dev) = make(100_000, 0); + c.create_io_queues(8).unwrap(); + + // A write starting exactly at the last valid LBA. + assert_eq!( + c.write_blocks(100_000, &[0u8; 512]), + Err(BlockError::OutOfRange) + ); + // A write that starts in range but whose end exceeds block_count. + assert_eq!( + c.write_blocks(99_999, &[0u8; 1024]), + Err(BlockError::OutOfRange) + ); + + let dev = dev.borrow(); + assert!(dev.io_commands.is_empty(), "no PRP/command may be built"); + assert_eq!(dev.io_sq_tail, 0, "no I/O doorbell may be rung"); +} + +#[test] +fn flush_submits_opcode_zero_command() { + let (mut c, dev) = make(4096, 0); + c.create_io_queues(8).unwrap(); + assert_eq!(c.flush(), Ok(())); + + let cmds = io_commands(&dev); + assert_eq!(cmds.len(), 1); + assert_eq!(cmds[0].opcode, 0x00, "flush opcode"); + assert_eq!(cmds[0].nsid, 1); + assert_eq!(cmds[0].prp1, 0); + assert_eq!(cmds[0].prp2, 0); +} From 2f72544a8a679cf878a07f071ebbbff48460039b Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 09:29:23 -0500 Subject: [PATCH 3/4] feat(nvme): native write and flush phase plus durability harness Add the `nvme-write` feature (implies `nvme-read`) and a write + flush phase in crates/aienos-boot/src/nvme_read.rs. The phase: - rejects a write past the namespace end before any command; - writes a deterministic pattern to LBA 4096, issues a real NVMe Flush, and reads it back; - on a later boot whose target already holds the pattern, reports cross-restart durability instead of rewriting; - surfaces an explicit invalid-namespace write as a device error. It emits NVME_WRITE_QEMU, NVME_FLUSH_QEMU, NVME_WRITE_BOUNDS_QEMU, NVME_WRITE_ERROR_QEMU, and NVME_DURABILITY_QEMU alongside the read markers. Write DMA stays inside the same confined arena, SMMU Stage-1, and dma_gate decision as read DMA; no new window and no bus-master change outside dma_gate. scripts/qemu_nvme_rw_test.sh builds a disposable image seeded with known old bytes, runs two boots over the same file (write+flush, then restart verify), host-checks the persisted bytes and hash, and checks the markers in SMMU and fail-closed modes. verify_all.sh is intentionally not edited. No Store v1 dependency and no Store file touched. --- crates/aienos-boot/Cargo.toml | 3 + crates/aienos-boot/src/nvme_read.rs | 124 +++++++++++++++ scripts/qemu_nvme_rw_test.sh | 232 ++++++++++++++++++++++++++++ 3 files changed, 359 insertions(+) create mode 100755 scripts/qemu_nvme_rw_test.sh diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 3ecca6c3..1782ac25 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -21,6 +21,9 @@ usb-keyboard = ["handoff"] # P3 candidate: polled native NVMe read after firmware exit. Only # scripts/qemu_nvme_test.sh enables it; hardware staging never does. nvme-read = ["handoff"] +# P3 candidate: native NVMe write + flush qualification on top of nvme-read. +# Only scripts/qemu_nvme_rw_test.sh enables it; hardware staging never does. +nvme-write = ["nvme-read"] # SEED-0B qualification build (ADR 0014 §6): the kernel trusts the public, # TEST ONLY RFC 8032 qualification key in addition to the (empty) production # set, and every report says so. Without it, every artifact candidate is diff --git a/crates/aienos-boot/src/nvme_read.rs b/crates/aienos-boot/src/nvme_read.rs index d509932f..e7252129 100644 --- a/crates/aienos-boot/src/nvme_read.rs +++ b/crates/aienos-boot/src/nvme_read.rs @@ -40,6 +40,13 @@ const UNSAFE_NVME_BANNER: &str = pub const SENTINEL_MAGIC: &[u8; 16] = b"AIENOS-NVME-SENT"; pub const SENTINEL_LBA: u64 = 2048; +/// Write/durability target: a deterministic read-write LBA distinct from the +/// read-only sentinel, and the 512-byte pattern written and verified there. +#[cfg(feature = "nvme-write")] +const RW_LBA: u64 = 4096; +#[cfg(feature = "nvme-write")] +const RW_MAGIC: &[u8; 16] = b"AIENOS-NVME-RW01"; + const ARENA_BYTES: usize = 128 * 1024; #[repr(C, align(4096))] @@ -563,9 +570,126 @@ pub fn run( } say(screen, error_line.as_str()); + #[cfg(feature = "nvme-write")] + run_write_phase(screen, &mut controller, block_count); + revoke_dma(screen, &mut ecam, &at); } +/// Write + flush qualification, exercised only in `nvme-write` builds. +/// +/// Read-only callers never reach this. The phase proves: a write past the end +/// is rejected before any command; a known pattern is written, flushed, and +/// read back byte-for-byte; a later boot that already holds the pattern +/// reports cross-restart durability; and an explicit invalid-namespace write +/// surfaces a device error rather than being swallowed. +#[cfg(feature = "nvme-write")] +fn run_write_phase( + screen: &mut Option, + controller: &mut NvmeController, + block_count: u64, +) { + use aienos_kernel::block::BlockError; + + let mut new = [0u8; 512]; + for chunk in new.as_chunks_mut::<16>().0 { + chunk.copy_from_slice(RW_MAGIC); + } + let new_digest = aienos_kernel::crypto::sha256::hash(&new); + + // A write past the namespace end must be rejected before any command. + let mut bounds = aienos_kernel::report::ReportBuf::<256>::new(); + match controller.write_blocks(block_count, &new) { + Err(BlockError::OutOfRange) => { + let _ = writeln!( + bounds, + "NVME_WRITE_BOUNDS_QEMU: PASS (lba={block_count} rejected OutOfRange no_command)" + ); + } + other => { + let _ = writeln!(bounds, "NVME_WRITE_BOUNDS_QEMU: FAIL (got {other:?})"); + } + } + say(screen, bounds.as_str()); + + // If the target already holds the expected bytes, this boot is a restart + // after a prior successful write: report durability across the restart. + let mut readback = [0u8; 512]; + let persisted = controller.read_blocks(RW_LBA, &mut readback).is_ok() && readback == new; + if persisted { + let mut line = aienos_kernel::report::ReportBuf::<320>::new(); + let _ = write!( + line, + "NVME_DURABILITY_QEMU: PASS (persisted lba={RW_LBA} blocks=1 bytes=512 sha256=" + ); + hex_digest(&mut line, &new_digest); + let _ = writeln!(line, ")"); + say(screen, line.as_str()); + } else { + let mut write_line = aienos_kernel::report::ReportBuf::<320>::new(); + match controller.write_blocks(RW_LBA, &new) { + Ok(()) => { + let _ = write!( + write_line, + "NVME_WRITE_QEMU: PASS (lba={RW_LBA} blocks=1 bytes=512 sha256=" + ); + hex_digest(&mut write_line, &new_digest); + let _ = writeln!(write_line, ")"); + } + Err(error) => { + let _ = writeln!(write_line, "NVME_WRITE_QEMU: FAIL (write {error:?})"); + } + } + say(screen, write_line.as_str()); + + let mut flush_line = aienos_kernel::report::ReportBuf::<160>::new(); + match controller.flush() { + Ok(()) => { + let _ = writeln!(flush_line, "NVME_FLUSH_QEMU: PASS (nsid=1)"); + } + Err(error) => { + let _ = writeln!(flush_line, "NVME_FLUSH_QEMU: FAIL (flush {error:?})"); + } + } + say(screen, flush_line.as_str()); + + let mut durability = aienos_kernel::report::ReportBuf::<320>::new(); + let mut readback = [0u8; 512]; + match controller.read_blocks(RW_LBA, &mut readback) { + Ok(()) if readback == new => { + let _ = write!( + durability, + "NVME_DURABILITY_QEMU: PASS (lba={RW_LBA} blocks=1 bytes=512 sha256=" + ); + hex_digest(&mut durability, &new_digest); + let _ = writeln!(durability, ")"); + } + Ok(()) => { + let _ = writeln!(durability, "NVME_DURABILITY_QEMU: FAIL (readback mismatch)"); + } + Err(error) => { + let _ = writeln!(durability, "NVME_DURABILITY_QEMU: FAIL (read {error:?})"); + } + } + say(screen, durability.as_str()); + } + + // An explicit invalid namespace write must surface a device error. + let mut error_line = aienos_kernel::report::ReportBuf::<256>::new(); + match controller.write_blocks_nsid(0xffff_ffff, RW_LBA, &new) { + Err(BlockError::DeviceError) => { + let _ = writeln!( + error_line, + "NVME_WRITE_ERROR_QEMU: PASS (write nsid=0xffffffff rejected status=nonzero)" + ); + } + other => { + let _ = writeln!(error_line, "NVME_WRITE_ERROR_QEMU: FAIL (got {other:?})"); + } + } + say(screen, error_line.as_str()); +} + fn report_smmu_fault( screen: &mut Option, smmu_base: Option, diff --git a/scripts/qemu_nvme_rw_test.sh b/scripts/qemu_nvme_rw_test.sh new file mode 100755 index 00000000..ad589b1c --- /dev/null +++ b/scripts/qemu_nvme_rw_test.sh @@ -0,0 +1,232 @@ +#!/usr/bin/env bash +# P3 native NVMe WRITE + FLUSH durability proof in QEMU (disposable media). +# +# Two boots over ONE raw image file: +# boot 1 writes a deterministic pattern to a read-write LBA and issues a +# real NVMe Flush, then the host reads the image file back and checks +# the exact bytes and SHA-256 (power-off persistence). +# boot 2 boots again on the same image and reads the target natively; the +# kernel reports durability across the restart. +# +# Read side (sentinel LBA 2048) is unchanged from scripts/qemu_nvme_test.sh. +# Write side targets LBA 4096 with the 16-byte magic "AIENOS-NVME-RW01" x32. +# The image starts with "AIENOS-NVME-OLD0" x32 there. +# +# DMA rule (M3): no SMMU confinement means no DMA. Mirrors the read harness: +# default QEMU SMMUv3; NVMe DMA only via a translated stream. +# AIENOS_QEMU_SMMU=0 no SMMU, normal build: NVMe stays unavailable, +# no write, bus mastering off (fail-closed). +# +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +# +# NOTE: scripts/verify_all.sh is intentionally NOT edited here. Wiring this +# harness into verify_all.sh is a follow-up owned by the integration lane. +set -euo 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; } + +attempts="${AIENOS_NVME_ATTEMPTS:-3}" +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" +if [[ "${AIENOS_QEMU_SMMU:-1}" == "1" ]]; then + mode="smmu" + machine="virt,virtualization=on,gic-version=3,iommu=smmuv3" +else + mode="fail-closed" + machine="virt,virtualization=on,gic-version=3" +fi +target_dir="target/qemu-nvme-rw" + +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features nvme-write --bin aienos-handoff \ + --target-dir "${target_dir}" + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { + [[ -n "${qemu_pid}" ]] && kill "${qemu_pid}" 2>/dev/null || true + exec 3>&- 2>/dev/null || true + rm -rf "${work}" +} +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${target_dir}/aarch64-unknown-uefi/release/aienos-handoff.efi" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +# --------------------------------------------------------------------------- +# Disposable media. 64 MiB raw, 131072 LBAs of 512 bytes. +# sentinel (read) LBA 2048 : "AIENOS-NVME-SENT" x32 +# rw target LBA 4096 : "AIENOS-NVME-OLD0" x32 (host seed) +# written pattern LBA 4096 : "AIENOS-NVME-RW01" x32 (guest write) +# bounds write LBA 131072 (== block_count), must be rejected OutOfRange +# write error NSID 0xffffffff, must return a nonzero completion status +# --------------------------------------------------------------------------- +img_bytes=67108864 +lba_bytes=512 +sentinel_lba=2048 +rw_lba=4096 +bounds_lba=$(( img_bytes / lba_bytes )) + +pattern() { # magic -> 512-byte file + local out="$1" magic="$2" + : > "${out}" + for _ in {1..32}; do printf '%s' "${magic}" >> "${out}"; done + [[ "$(wc -c <"${out}")" == "512" ]] || { echo "STOP: payload must be 512 bytes"; exit 2; } +} + +image="${work}/nvme.img" +pattern "${work}/sentinel.bin" 'AIENOS-NVME-SENT' +pattern "${work}/old.bin" 'AIENOS-NVME-OLD0' +pattern "${work}/new.bin" 'AIENOS-NVME-RW01' +sentinel_sha="$(sha256sum "${work}/sentinel.bin" | cut -d' ' -f1)" +old_sha="$(sha256sum "${work}/old.bin" | cut -d' ' -f1)" +new_sha="$(sha256sum "${work}/new.bin" | cut -d' ' -f1)" + +truncate -s "${img_bytes}" "${image}" +dd if="${work}/sentinel.bin" of="${image}" bs="${lba_bytes}" seek="${sentinel_lba}" conv=notrunc status=none +dd if="${work}/old.bin" of="${image}" bs="${lba_bytes}" seek="${rw_lba}" conv=notrunc status=none +[[ "$(dd if="${image}" bs="${lba_bytes}" skip="${rw_lba}" count=1 status=none | sha256sum | cut -d' ' -f1)" == "${old_sha}" ]] \ + || { echo "STOP: OLD seed not at LBA ${rw_lba}"; exit 2; } + +echo "nvme image: ${img_bytes} bytes, ${bounds_lba} x ${lba_bytes} B LBAs" +echo "sentinel LBA ${sentinel_lba} sha256 ${sentinel_sha}" +echo "rw old LBA ${rw_lba} sha256 ${old_sha}" +echo "rw new LBA ${rw_lba} sha256 ${new_sha}" + +serial_has() { tr -d '\r' 2>/dev/null <"${work}/serial.log" | grep -q -- "$1"; } +qemu_running() { kill -0 "${qemu_pid}" 2>/dev/null; } +wait_for() { # seconds, pattern... + local deadline=$(( $(date +%s) + $1 )); shift + while (( $(date +%s) < deadline )) && qemu_running; do + for p in "$@"; do serial_has "${p}" && return 0; done + sleep 0.2 + done + for p in "$@"; do serial_has "${p}" && return 0; done + return 1 +} +stop_qemu() { + if [[ -n "${qemu_pid}" ]]; then + kill "${qemu_pid}" 2>/dev/null || true + wait "${qemu_pid}" 2>/dev/null || true + fi + qemu_pid="" + exec 3>&- 2>/dev/null || true +} + +# One boot against the shared image. $1 is the terminal marker to wait for. +boot_once() { + cp "${vars_fd}" "${work}/vars.fd" + rm -f "${work}/serial.log" + 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-nvme-rw-test \ + -device ramfb -display none -nic none \ + -serial file:"${work}/serial.log" -no-reboot & + qemu_pid=$! + + if ! wait_for "${boot_timeout}" "report_kind: pre_exit"; then + echo "no AIENOS output within ${boot_timeout} s (firmware hang, issue #61)" + stop_qemu + return 2 + fi + wait_for "${boot_timeout}" "$1" "report_kind: panic" "report_kind: fault" || true + local deadline=$(( $(date +%s) + 20 )) + while qemu_running && (( $(date +%s) < deadline )); do sleep 0.5; done + stop_qemu + return 0 +} + +started=$(date +%s) +if [[ "${mode}" == "smmu" ]]; then + terminal="NVME_WRITE_ERROR_QEMU" +else + terminal="nvme: unavailable (SMMU DMA isolation not active)" +fi +attempt=1 +while :; do + status=0 + boot_once "${terminal}" || status=$? + [[ "${status}" != 2 || "${attempt}" -ge "${attempts}" ]] && break + attempt=$(( attempt + 1 )) +done +elapsed=$(( $(date +%s) - started )) +tr -d '\r' <"${work}/serial.log" >"${work}/serial_boot1.txt" 2>/dev/null || true + +# boot 2: same image, expect persistence across the restart. +if [[ "${mode}" == "smmu" ]]; then + boot_once "NVME_DURABILITY_QEMU" || true + tr -d '\r' <"${work}/serial.log" >"${work}/serial_boot2.txt" 2>/dev/null || true +fi + +[[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial_boot1.txt" "${AIENOS_LOG_DIR}/qemu_nvme_rw_serial.log" 2>/dev/null || true +boot1="${work}/serial_boot1.txt" +failed=0 +check() { if grep -q -- "$2" "${boot1}"; then echo "PASS $1"; else echo "FAIL $1"; failed=1; fi; } +check_absent() { if grep -q -- "$2" "${boot1}"; then echo "FAIL $1"; failed=1; else echo "PASS $1"; fi; } + +if [[ "${mode}" == "smmu" ]]; then + check "ECAM discovery found the NVMe class device" "NVME_DISCOVERY_QEMU: PASS" + check "controller and namespace identify completed" "NVME_IDENTIFY_QEMU: PASS" + check "namespace geometry matches the image" "NVME_GEOMETRY_QEMU: PASS (nsid=1 block_count=${bounds_lba} block_size=${lba_bytes})" + check "read sentinel LBA returned exact bytes and SHA-256" "NVME_READ_QEMU: PASS (lba=${sentinel_lba} blocks=1 bytes=512 sha256=${sentinel_sha})" + check "read past the namespace end is rejected" "NVME_BOUNDS_QEMU: PASS" + check "device-reported read error is surfaced" "NVME_ERROR_QEMU: PASS" + check "write past the namespace end is rejected" "NVME_WRITE_BOUNDS_QEMU: PASS" + check "native write returned exact bytes and SHA-256" "NVME_WRITE_QEMU: PASS (lba=${rw_lba} blocks=1 bytes=512 sha256=${new_sha})" + check "native flush completed" "NVME_FLUSH_QEMU: PASS" + check "write then flush then read-back matched" "NVME_DURABILITY_QEMU: PASS (lba=${rw_lba} blocks=1 bytes=512 sha256=${new_sha})" + check "invalid-namespace write surfaced a device error" "NVME_WRITE_ERROR_QEMU: PASS" + check "IORT stream configured for NVMe DMA" "smmu: enabled" + check "NVMe DMA granted only as confined" "dma_gate: nvme granted (Confined), bus master on" + check "NVMe bus master revoked after the phase" "dma_gate: nvme bus master revoked" + + # Host persistence check: the image file must now hold the written pattern. + host_sha="$(dd if="${image}" bs="${lba_bytes}" skip="${rw_lba}" count=1 status=none | sha256sum | cut -d' ' -f1)" + if [[ "${host_sha}" == "${new_sha}" ]]; then + echo "PASS host read-back after power off equals the written bytes" + else + echo "FAIL host read-back ${host_sha} != written ${new_sha}" + failed=1 + fi + + # Boot 2: the kernel must observe the persisted pattern natively. + if grep -q -- "NVME_DURABILITY_QEMU: PASS (persisted lba=${rw_lba}" "${work}/serial_boot2.txt" 2>/dev/null; then + echo "PASS restart read-back observed the persisted pattern natively" + else + echo "FAIL restart read-back did not observe the persisted pattern" + failed=1 + fi +else + check "discovery found the device before the DMA gate" "NVME_DISCOVERY_QEMU: PASS" + check "NVMe DMA denied without an SMMU" "dma_gate: nvme denied (NoSmmu), bus master stays off" + check "NVMe controller fail-closed without an SMMU" "nvme: unavailable (SMMU DMA isolation not active)" + check_absent "no write marker without DMA" "NVME_WRITE_QEMU: PASS" + check_absent "no flush marker without DMA" "NVME_FLUSH_QEMU: PASS" + check_absent "no durability marker without DMA" "NVME_DURABILITY_QEMU: PASS" +fi +if grep -qE "report_kind: (panic|fault)" "${boot1}"; then + echo "FAIL panic or fault reported (boot 1)" + failed=1 +fi +if [[ -f "${work}/serial_boot2.txt" ]] && grep -qE "report_kind: (panic|fault)" "${work}/serial_boot2.txt"; then + echo "FAIL panic or fault reported (boot 2)" + failed=1 +fi + +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial console (boot 1) ----" + cat "${boot1}" + [[ -f "${work}/serial_boot2.txt" ]] && { echo "---- serial console (boot 2) ----"; cat "${work}/serial_boot2.txt"; } +fi +[[ "${failed}" == 0 ]] && echo "QEMU_NVME_RW: PASS (${mode})" || { echo "QEMU_NVME_RW: FAIL (${mode})"; exit 1; } From d21dd5f0d7158cafb9b8333f319720362cde5be0 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 09:29:23 -0500 Subject: [PATCH 4/4] docs(nvme): write/flush reviews, substrate design, and QEMU evidence - P3_NVME_WRITE_REVIEW.md: write-path correctness review with file:line items, including the MDTS/PRP-list sizing observation. - P3_NVME_FLUSH_REVIEW.md: Flush correctness and durability semantics, including that a no-op flush is prohibited and QEMU reaches the block backend. - P3_NVME_WRITE_DMA_REVIEW.md: read-only confirmation that write DMA is under the same confined authority as read DMA, with no unconstrained bus mastering and no unsafe bypass in hardware-staging. - P3_NVME_WRITE_FLUSH_SUBSTRATE.md: the harness design and marker contract, with a status note on the shipped implementation shape. - evidence/p3_nvme_write_flush_qemu_2026-09-25.md: the QEMU durability qualification (SMMU and fail-closed), the exact markers and hashes, and explicit non-claims (no Machine 1, no Store, no FUA, disposable media). --- docs/P3_NVME_FLUSH_REVIEW.md | 128 ++++++++++ docs/P3_NVME_WRITE_DMA_REVIEW.md | 221 ++++++++++++++++++ docs/P3_NVME_WRITE_FLUSH_SUBSTRATE.md | 197 ++++++++++++++++ docs/P3_NVME_WRITE_REVIEW.md | 152 ++++++++++++ .../p3_nvme_write_flush_qemu_2026-09-25.md | 83 +++++++ 5 files changed, 781 insertions(+) create mode 100644 docs/P3_NVME_FLUSH_REVIEW.md create mode 100644 docs/P3_NVME_WRITE_DMA_REVIEW.md create mode 100644 docs/P3_NVME_WRITE_FLUSH_SUBSTRATE.md create mode 100644 docs/P3_NVME_WRITE_REVIEW.md create mode 100644 evidence/p3_nvme_write_flush_qemu_2026-09-25.md diff --git a/docs/P3_NVME_FLUSH_REVIEW.md b/docs/P3_NVME_FLUSH_REVIEW.md new file mode 100644 index 00000000..21edf764 --- /dev/null +++ b/docs/P3_NVME_FLUSH_REVIEW.md @@ -0,0 +1,128 @@ +# D2 Flush Review - AIENOS P3 NVMe Flush lane + +Base: `aien-dev/aienos` @ `ef359ec` (read-only mirror `/Users/drakestapleton/aienos-nvme-rw`). +Files read in full: `crates/aienos-kernel/src/nvme.rs`, +`crates/aienos-kernel/src/nvme/driver.rs`, `crates/aienos-kernel/src/block.rs`. +Companion tests: `nvme-rw-subagents/d2/nvme_flush.rs` (target `crates/aienos-kernel/tests/nvme_flush.rs`). + +## 1. Is `flush()` a correct NVMe Flush command? + +Implementation (driver.rs:432 - 439) builds a zeroed `Submission`, sets CDW0 opcode = `0` +and CDW1 NSID = `1`, then hands it to `submit_io` (driver.rs:364 - 406). + +- **Opcode** - `0x00` (NVM Flush) in CDW0 bits 7:0. `submit_io` ORs the CID into CDW0 + bits 31:16 (driver.rs:370), leaving opcode/FUSE intact. Correct. +- **NSID** - CDW1 = 1. Correct for the single namespace the driver identifies + (`identify_namespace(1)`), but hardcoded (see NEEDS-FIX 1). +- **CDW10..CDW15** - left zero. Correct; Flush defines no command-specific fields + (no LBA, no NLB, no FUA). +- **Data pointers** - PRP1/PRP2 are zero. Flush is a data-less command; PRPs are + reserved, so requiring none is correct and the tests assert `(prp1, prp2) == (0, 0)`. +- **Queue** - submitted on the polled I/O SQ/CQ (QID 1), which is the correct command + set for an NVM I/O command. +- **CID** - drawn from the shared `next_cid` (driver.rs:368 - 369), so a Flush never + aliases the preceding Write's CID; the test asserts monotonic `+1`. +- **Completion semantics** - `status = c.status() >> 1`; `0 -> Ok(())`, nonzero -> + `BlockError::DeviceError` (driver.rs:392 - 403), and the poll budget is bounded + (1001 iterations) -> `BlockError::Timeout`. This is the honest mapping: durability + is exposed only through a successful completion. + +Verdict: the command layout and completion handling are a correct NVMe Flush. + +## 2. Are `BlockDevice::flush` semantics honest? + +`BlockDevice` (block.rs:11 - 17) declares `flush(&mut self) -> Result<(), BlockError>` +with no documented durability contract. Two implementors differ sharply: + +- `NvmeController::flush` (driver.rs:432) - **honest**: it actually issues the Flush + command and reports backend failure/timeout as an error. It is not a no-op. +- `RamDisk::flush` (block.rs:129 - 131) - **unconditional `Ok(())`**, a literal no-op. + For a purely volatile in-memory disk this is defensible (there is no media to + persist to), but it must be understood as "no durability guarantee", not as a + successful flush. It is the exact pattern that must **not** be copied into a + real-device driver. + +Additional honesty concerns: + +- `write_blocks` never sets the FUA bit (CDW12 bit 14) and never auto-flushes + (driver.rs:428 - 431, 349 - 353). Durability is only obtained if the caller explicitly + calls `flush()`; callers must not assume `write_blocks` is durable. +- The trait does not state whether `flush` is a cache-flush barrier, an ordering + barrier, or both, nor which namespace(s) it covers. The NVMe impl flushes NSID 1 + only. +- All nonzero completion statuses (including DNR, SCT/SC detail) collapse to + `DeviceError`, losing diagnostic detail (acceptable for the coarse `BlockError` + enum, but worth noting). + +## 3. What does QEMU's emulated NVMe do with Flush? + +QEMU does **not** ignore it. In `hw/nvme/ctrl.c` (upstream, v1.4-capable): + +- I/O dispatch routes `NVME_CMD_FLUSH` (opcode `0x00`) to `nvme_flush()` + (`nvme_io_cmd` path, `ctrl.c:4748`). +- `nvme_flush()` validates the NSID (`NVME_INVALID_NSID | NVME_DNR` if invalid, + `NVME_INVALID_FIELD | NVME_DNR` if the namespace is absent), supports + `NVME_NSID_BROADCAST` (`0xFFFFFFFF`) to flush every namespace, then calls + `nvme_do_flush()` (`ctrl.c:3622 - 3659`). +- `nvme_flush_ns_cb()` issues `blk_aio_flush(ns->blkconf.blk, ...)` against the + namespace's `BlockBackend` (`ctrl.c:3582`). If the backend returns an error, + `nvme_flush_ns_cb` sets `req->status = NVME_WRITE_FAULT` (`ctrl.c:3570 - 3573`), + which is returned as a **nonzero completion status** - exactly what our driver + maps to `BlockError::DeviceError`. + +So a successful Flush completion in QEMU means the flush reached the block backend +and the backend reported success. Whether that persists to the host file depends on +the drive's cache mode: + +- `cache=writeback` (QEMU default): `blk_aio_flush` propagates to the format/protocol + driver and typically results in an `fsync`/`fdatasync` of the backing file - the + data reaches the host file. +- `cache=none` / `cache=directsync`: writes are already synchronous, so the flush may + be a no-op at the file layer but still completes successfully. +- `cache=unsafe`: QEMU is explicitly told to ignore flushes / not use `O_DSYNC`; a + successful Flush then does **not** guarantee host persistence. + +Net: emulated Flush is real and reaches the backend; host-level durability is only as +strong as the drive's cache configuration. Our driver correctly treats a nonzero +completion as failure. + +## 4. Flush must not be faked as a no-op + +A silent `flush() -> Ok(())` in a real NVMe driver is a durability bug: it reports +success without ever telling the controller to commit its volatile write cache, so a +power loss can lose acknowledged writes. The current `NvmeController::flush` avoids +this by issuing opcode `0x00` and requiring a zero-status completion. The tests in +`nvme_flush.rs` enforce this directly: they assert an I/O SQ doorbell write occurs, +that the parsed command reaches the simulator, that a nonzero status yields +`DeviceError`, and that a missing completion yields `Timeout` - i.e. flush can never +silently succeed. The `RamDisk` no-op is acceptable only because RAM is inherently +volatile and must never be treated as the pattern for a persistent device. + +## NEEDS-FIX / observations + +1. **Hardcoded NSID 1** (driver.rs:437). `flush()` should target the active + namespace ID (or support `NVME_NSID_BROADCAST` like QEMU) rather than a literal + `1`, or the trait should document the single-namespace restriction. Currently + consistent only because the driver identifies/uses NSID 1 exclusively. +2. **No durability contract on `BlockDevice::flush`** (block.rs:11 - 17). Document that + `flush` is a cache-commit barrier, that `write_blocks` is not implicitly durable, + and that `RamDisk::flush` is a deliberate no-op with no persistence claim. +3. **`write_blocks` has no FUA path** (driver.rs:349 - 353). Either document that + callers must `flush()` for durability or add an FUA option for single-write + durability. +4. **Flush uses the same 1001×1 ms poll budget as data I/O** (driver.rs:379). Real + media flushes can take longer; consider a dedicated (longer) flush budget. +5. **Status detail is lost** (driver.rs:399 - 403). `DeviceError` discards DNR/SCT/SC; + acceptable for the coarse enum but consider preserving it for diagnostics. +6. **No regression test in-repo yet.** `nvme_flush.rs` should be dropped into + `crates/aienos-kernel/tests/` and run with `cargo test -p aienos-kernel` (not run + here per constraints). + +## Test coverage added (`nvme_flush.rs`) + +- `flush_submits_opcode_zero_nsid_one_without_data_pointer` +- `successful_flush_completion_returns_ok` +- `nonzero_flush_completion_status_returns_device_error` +- `flush_timeout_returns_timeout_and_is_bounded` +- `flush_is_not_a_silent_no_op_doorbell_and_command_reach_device` +- `flush_after_write_in_same_session_uses_fresh_cid` diff --git a/docs/P3_NVME_WRITE_DMA_REVIEW.md b/docs/P3_NVME_WRITE_DMA_REVIEW.md new file mode 100644 index 00000000..d57a9194 --- /dev/null +++ b/docs/P3_NVME_WRITE_DMA_REVIEW.md @@ -0,0 +1,221 @@ +# D6 - SMMU / DMA review: P3 Native NVMe Write + Flush lane + +Repo: `aien-dev/aienos`, base `ef359ec` (mirror `/Users/drakestapleton/aienos-nvme-rw`). +Scope: read-only review of the DMA/SMMU authority that a future write+flush lane +would inherit from the existing read substrate. No edits, no cargo, no hardware. + +Verdict up front: the read lane already establishes a single, confined DMA +authority. Because write and read share the same driver `transfer()` and the +same `NativeDma`/`DmaMemory` implementation, a write lane that reuses the +existing module inherits that authority unchanged. There is **no write lane in +this tree yet** (`crates/aienos-kernel/src/nvme/` contains only `driver.rs`; no +`nvme_write.rs`), so the lane must be added without introducing a second window, +a second SMMU policy, or a second BME toggle. + +--- + +## 1. Write DMA uses the SAME confined authority as read DMA + +### 1.1 One static arena window for both directions + +- `ARENA_BYTES = 128 * 1024` and the single `static mut DMA_ARENA: DmaArena` + are defined once - `crates/aienos-boot/src/nvme_read.rs:43`, `:45-48`. +- `NvmeLocation::dma_window()` returns exactly that static, page-aligned: + `nvme_read.rs:75-78` (`base & !0xfff`, `size_of::()`). +- There is no second arena and no per-direction window. `grep` for + `DMA_ARENA`/`dma_window` finds only this one definition plus its users + (`nvme_read.rs:76,271,279,313,331,457`). +- The SMMU Stage-1 policy is built from that same call: + `configure_smmu_for_nvme` takes `nvme.dma_window()` (`handoff.rs:305`) and + passes a **single** `DmaWindow { iova: dma_base, pa: dma_base, length }` to + `build_dma_policy` - `handoff.rs:317-327`. +- `build_dma_policy` requires identity (`window.iova != window.pa.0` → + `InvalidWindow`) and maps only the supplied windows; anything else does not + translate - `crates/aienos-kernel/src/smmu.rs:739-746`. + +### 1.2 Same `dma_gate` decision for the whole phase + +- The gate is evaluated **once**, before any command, in `run`: + `dma_gate::dma_grant(smmu_ready, smmu_base.is_some(), UNSAFE_NVME_DMA_BYPASS)` + - `nvme_read.rs:413-417`. Its result gates the entire run (read today, write + later); there is no second grant call. +- Decision logic is direction-agnostic: confined iff `smmu_ready`, bypass only + when no SMMU exists AND the unsafe feature is compiled, never a fallback after + a failed SMMU - `crates/aienos-kernel/src/dma_gate.rs:68-82`, test + `failed_smmu_never_falls_back_to_bypass` `:279-282`. +- `nvme_read::run` is invoked with `nvme_smmu_result.is_ok()` as `smmu_ready` + (`handoff.rs:2111-2117`), i.e. the grant is tied to the same + `configure_smmu_for_nvme` result (`handoff.rs:1794`). + +### 1.3 Same allocator and same `DmaMemory` path + +- `NativeDma` bump-allocates only inside `DMA_ARENA`, bounds-checked against + `ARENA_BYTES` - `nvme_read.rs:269-283`, `:286-305`. +- Write and read commands both flow through `NvmeController::transfer(write, …)` + (`crates/aienos-kernel/src/nvme/driver.rs:293-362`): writes copy data into + `region.bytes` then `dma.write(...)` (`driver.rs:325-330`); reads call + `dma.read(...)` (`driver.rs:354-357`). Both go through the same + `D: DmaMemory` = `NativeDma`. +- `write_blocks` is a thin wrapper over the same `transfer(true, …)` + (`driver.rs:428-431`); `flush` uses the same `submit_io` + (`driver.rs:432-439`). No separate DMA authority exists for writes. + +**Confirmed:** one window, one SMMU policy, one gate decision, one allocator. +No separate or widened window for writes. + +--- + +## 2. No unconstrained bus mastering + +- Bus Master Enable is cleared on the controller's whole ECAM segment **before** + any SMMU or driver setup: `take_over_dma` → `dma_gate::sweep_bus_master` + (`nvme_read.rs:201-210`), called at `handoff.rs:1790` (and the sweep clears + every endpoint with BME set - `dma_gate.rs:150-218`). +- `run` refuses to proceed if BME did not clear: + `if dma_gate::bus_master_enabled(command) { … return; }` + (`nvme_read.rs:409-412`). +- BME is set **only after** `dma_grant` returns `Ok`: + `ecam.set_command(&at, dma_gate::with_bus_master(command))` at + `nvme_read.rs:460`, which is after the `match dma_gate::dma_grant(...)` at + `:413-429`. On denial it returns with BME still off (`:419-428`). +- BME is revoked after the phase: `revoke_dma` clears BME and re-reads to + confirm (`nvme_read.rs:232-247`), called on every post-grant exit: + init failure `:473`, queue failure `:499`, normal completion `:566`. +- Only one `with_bus_master` call site exists for NVMe + (`nvme_read.rs:460`); the only other is xHCI (`usb_keyboard.rs:341`), and the + two features are documented as mutually exclusive builds + (`handoff.rs:1785-1786`). + +**Confirmed:** BME set only after `dma_grant` `Ok`; revoked after the phase. + +--- + +## 3. Unsafe QEMU bypass cannot enter a hardware-staging image + +- Feature definition: `unsafe-debug-nvme-dma-without-smmu = ["nvme-read"]` + (`crates/aienos-boot/Cargo.toml:42-48`); `hardware-staging = ["handoff"]` + (`:32`). +- Compile guard: `#[cfg(all(feature = "unsafe-debug-nvme-dma-without-smmu", + feature = "hardware-staging"))] compile_error!(...)` - `src/lib.rs:26-33`. + The xHCI bypass has the equivalent guard - `lib.rs:12-19`. +- Banner: `UNSAFE_NVME_BANNER` is printed on every boot of such an image + (`nvme_read.rs:33-36`, `:379-381`), and the active-grant warning is printed + when the bypass actually grants DMA (`nvme_read.rs:443-450`). +- The bypass cannot be requested silently: the QEMU harness requires + `AIENOS_UNSAFE_DMA_BYPASS=1` and refuses the feature otherwise + (`scripts/qemu_nvme_test.sh:49-71`); the SMMU harness forces it off + (`scripts/qemu_smmu_test.sh:3,8`). The hardware staging script builds + `handoff,hardware-staging` with no bypass (`scripts/stage_one_time_boot.sh:32`). +- The harness asserts the confined path: denied without SMMU + (`qemu_nvme_test.sh:246-248`), confined grant + revoke (`:252-261`), and + `check_absent "no unsafe DMA bypass in this image"` on non-bypass runs + (`:263-264`). + +**Confirmed:** unbuildable with `hardware-staging`; banner on every boot; loud +warning when active. + +--- + +## 4. Cache maintenance on the write path + +CPU-writes-cleaned-to-device and device-writes-invalidated-before-CPU-read are +both present, and both are issued with a trailing `dsb`. + +- `clean_dcache_range` = `dc cvac` per line + `dsb` - `arch/aarch64.rs:270-278`, + helper ends with `dsb()` at `:291-301`. +- `clean_invalidate_dcache_range` = `dc civac` per line + `dsb` - + `arch/aarch64.rs:282-289` (clean-first so no CPU write in a shared line is + lost; documented `:279-281`). +- Write direction: `NativeDma::write` copies into the arena then calls + `clean_dcache_range` - `nvme_read.rs:326-339`. In `transfer`, write payloads + reach the device only via `dma.write` (`driver.rs:325-330`). +- Read direction: `NativeDma::read` calls `clean_invalidate_dcache_range` + **before** the CPU copy - `nvme_read.rs:307-324`; used at + `driver.rs:354-357`. +- Queue traffic is on the same discipline: SQ command written via `dma.write` + (clean) before the doorbell (`driver.rs:372-378`); CQ read via `dma.read` + (clean+invalidate) before inspecting phase/status (`driver.rs:380-383`, + admin `:240-243`). +- Host tests exercise the write path end-to-end, including PRP-list and MDTS + chunking (`driver.rs:917-945`) and write-completion-error propagation + (`driver.rs:947-977`). + +**Confirmed:** correct direction of maintenance for write (clean) and read +(clean+invalidate), each fenced with `dsb`. + +--- + +## 5. Gaps / risks specific to the write+flush lane + +1. **No write lane exists.** `nvme_read.rs` is explicitly read-only and claims + no write/flush (`nvme_read.rs:9-11`). The lane must add a new module/feature + (e.g. `nvme-write`) and QEMU harness; it must not simply call + `write_blocks` from the read qualification path without its own evidence + gates. `driver.rs` already implements `write_blocks`/`flush`, so the driver + side is ready. + +2. **Arena exhaustion (functional, fail-closed).** `NativeDma` never frees + (`nvme_read.rs:269-305`), and `transfer`'s MDTS chunk cap is 128 KiB + (`driver.rs:308-316`) - exactly `ARENA_BYTES` (`nvme_read.rs:43`). Admin + queues + identify + I/O queues already consume part of the arena + (`driver.rs:125-127,196-200`), so a maximum-size transfer cannot fit. The + write lane must bound per-command chunk size well below the arena (or add + arena reuse/free), otherwise writes fail with `NvmeError::Dma`. Fail-closed, + but it caps the lane's usefulness and must be an explicit, tested limit. + +3. **BME is not revoked on a panic/fault during the phase.** Revocation happens + only on the enumerated normal/error returns (`nvme_read.rs:473,499,566`). + `fatal_report` resets without clearing BME (`handoff.rs:1571+`), so a fault + mid-write leaves BME set until the cold reset. The write lane should clear + BME in the fault path (or explicitly accept reset as the only containment). + +4. **Flush has no durable evidence yet.** `flush()` submits opcode 0 with + `cdw10=1` through `submit_io` (`driver.rs:432-439`), which only distinguishes + `Ok`/`DeviceError` (`driver.rs:399-403`). The lane must emit a distinct + `NVME_FLUSH_*` evidence line and must only claim durability after a + successful flush completion; it should also record that all prior writes were + submitted serially (they are: each `submit_io` waits for completion - + `driver.rs:379-404`). + +5. **Namespace bounds are enforced before any command** (`driver.rs:301-307`, + `OutOfRange`), so a write cannot escape the namespace. Keep this invariant: + do not add a raw command path that bypasses `transfer`. + +6. **Cache-maintenance caveat.** The maintenance is unconditional. If the arena + mapping were ever Device-nGnRnE rather than Normal memory, `dc cvac`/`civac` + semantics would be wrong. Today the arena is Normal identity-mapped + (`handoff.rs:266-270` comment; `map_plan` identity path). The lane must not + change the arena mapping attributes. + +### Invariants the write+flush lane MUST preserve + +- Reuse `NvmeLocation` / `DMA_ARENA` / `NvmeLocation::dma_window()` unchanged - + no new static arena, no second window. +- Reuse `configure_smmu_for_nvme` and its single `DmaWindow` - no second + `build_dma_policy` call, no widened policy. +- Reuse the single `dma_gate::dma_grant` result - no second grant, and no BME + write anywhere outside `dma_gate::with_bus_master`/`without_bus_master`. +- Keep BME set only between the post-grant point and revocation, including on + fault. +- Keep all data movement through `DmaMemory`/`NativeDma` (clean on write, + clean+invalidate on read) - no direct MMIO or cache-bypassing copies. +- Keep the `unsafe-debug-nvme-dma-without-smmu` compile_error + banner contract + and the `hardware-staging` incompatibility. + +--- + +## Evidence index (file:line) + +| Claim | Evidence | +|---|---| +| Single arena | `nvme_read.rs:43,45-48,75-78` | +| Single SMMU window | `handoff.rs:305,317-327`; `smmu.rs:713-717,739-746` | +| Single gate decision | `nvme_read.rs:413-429`; `dma_gate.rs:68-82,279-282` | +| BME off before setup | `nvme_read.rs:201-210`; `handoff.rs:1790` | +| BME set only after grant | `nvme_read.rs:409-412,460` | +| BME revoked | `nvme_read.rs:232-247,473,499,566` | +| Bypass compile guard | `lib.rs:26-33` (and `:12-19`) | +| Bypass banner | `nvme_read.rs:33-36,379-381,443-450` | +| Cache write/read | `nvme_read.rs:307-324,326-339`; `arch/aarch64.rs:270-289,291-301` | +| Write/flush driver | `driver.rs:293-362,428-439`; tests `:917-977` | +| No write lane yet | `nvme_read.rs:9-11`; `nvme/` contains only `driver.rs` | diff --git a/docs/P3_NVME_WRITE_FLUSH_SUBSTRATE.md b/docs/P3_NVME_WRITE_FLUSH_SUBSTRATE.md new file mode 100644 index 00000000..da931625 --- /dev/null +++ b/docs/P3_NVME_WRITE_FLUSH_SUBSTRATE.md @@ -0,0 +1,197 @@ +# D5 - QEMU native NVMe Write + Flush durability harness (P3) + +> **Status: implemented and passing in QEMU (2026-09-25).** The merged +> implementation keeps the read phase in `crates/aienos-boot/src/nvme_read.rs` +> and adds the write/flush phase there under the `nvme-write` feature (whose +> harness is `scripts/qemu_nvme_rw_test.sh`), rather than a separate +> `nvme_write.rs` module or a mode file. The phase is content-adaptive: on a +> boot where the target LBA already holds the expected pattern it reports +> cross-restart durability; otherwise it writes, flushes, and reads back. See +> [`evidence/p3_nvme_write_flush_qemu_2026-09-25.md`](../evidence/p3_nvme_write_flush_qemu_2026-09-25.md). +> The design below remains the rationale and mode contract. + +Target placement: `scripts/qemu_nvme_rw_test.sh` (this lane authors a candidate +at `nvme-rw-subagents/d5/qemu_nvme_rw_test.sh`). Companion to the merged read +qualification `scripts/qemu_nvme_test.sh` and follows the mode conventions of +`scripts/qemu_keyboard_test.sh`. + +Base: `aien-dev/aienos` @ `ef359ec`. Read-only against the repo; no repo edits, +no `cargo`, no `qemu`, no hardware, no Python. + +## 1. What is being proved + +The read lane (`crates/aienos-boot/src/nvme_read.rs`) deliberately issues only +Identify (`0x06`) and Read (`0x02`) and states that "write and flush are not +claimed, proven, or exercised" (`nvme_read.rs:9-11`, `docs/P3_NVME_READ_SUBSTRATE.md:21-25`). +This lane proves the next two things: + +1. **Write + flush reaches durable media.** The native driver writes a known + pattern to a known LBA and issues an NVM Flush (`BlockDevice::flush`, + `crates/aienos-kernel/src/nvme/driver.rs:432-439`). After QEMU is gone, the + **host image file** at that LBA holds exactly the expected bytes and hash. +2. **Durability across a restart.** A second QEMU run over the same image file + reads that LBA back through the native driver and reports the exact bytes + and SHA-256 (guest hash), which must equal the host's hash. + +The kernel already exposes the primitives this lane needs: +`BlockDevice::write_blocks`/`flush` (`crates/aienos-kernel/src/block.rs:15-16`) +and the NVMe implementation `write_blocks` (`driver.rs:428-431`) and `flush` +(`driver.rs:432-439`). The write module reuses the read module's pre-exit +discovery and post-exit scaffolding: `find_nvme` (`nvme_read.rs:83`), +`take_over_dma` (`nvme_read.rs:203`), the `Ecam` adapter (`nvme_read.rs:170`), +`NativeRegisters`/`NativeDma`/`NativeDelay`, the DMA gate +(`nvme_read.rs:413-461`), and `revoke_dma` (`nvme_read.rs:232`). + +## 2. Image geometry, target LBA and payloads + +Built only with `dd` / `od` / `printf` / `truncate` / `sha256sum`, exactly like +`qemu_nvme_test.sh:94-131`; no Python. + +| Property | Value | +|---|---| +| Image size | 64 MiB = `67108864` bytes | +| LBA size | 512 bytes | +| LBA count / bounds LBA | `131072` (`== block_count`) | +| **Target LBA** | **4096** (offset **2097152**) | +| Read-lane sentinel LBA (untouched here) | 2048 (offset 1048576) | + +Target LBA 4096 is deliberately distinct from the read sentinel LBA 2048 +(`nvme_read.rs:41`, `qemu_nvme_test.sh:107`) so a write can never be confused +with a read-lane sentinel check. + +Payloads are one 512-byte LBA: a 16-byte magic repeated 32 times, no newline +(the read lane uses `AIENOS-NVME-SENT` x32 at `nvme_read.rs:40` and +`qemu_nvme_test.sh:104,113-116`). + +| Name | Magic (x32 = 512 B) | SHA-256 | +|---|---|---| +| **OLD** (host seed, pre-existing bytes) | `AIENOS-NVME-OLD0` | `46fe054d5bfa8bf3b14ce240830da7445b26ebebe273349f9af22e6454244379` | +| **NEW** (guest writes, expected durable bytes) | `AIENOS-NVME-RW01` | `76fa34c132173497a7bcd0c9618ebdcf0629f550934c164adf81cfa05e6a4451` | + +The host seeds OLD at LBA 4096, then `od`-checks the first 16 bytes and +`sha256sum`s the seeded block before boot (`qemu_nvme_rw_test.sh` image build, +mirroring `qemu_nvme_test.sh:118-129`). + +## 3. Restart simulation and per-boot modes + +Restart is **two QEMU runs over the same `nvme.img` file**. The image is built +once and is never rebuilt between boots; `cache=writethrough` on the NVMe +`-drive` keeps the host file coherent with each guest flush. QEMU is asked to +exit cleanly via the HMP monitor (`quit`) before any signal, so block backends +flush to the host file (`qemu_nvme_rw_test.sh` `stop_qemu`). + +The guest reads its mode from an ESP file, because the handoff image has no +runtime environment and `AIENOS_RESTART_SECS` is a **compile-time** env var +(`qemu_nvme_test.sh:78`). Contract: + +- File: `\EFI\AIENOS\NVME_RW_MODE.TXT` on the ESP. +- Exact bytes, no trailing newline: `write` or `verify`. +- Read **before** `ExitBootServices` (boot services still live) and passed into + the post-exit phase; post-exit code cannot use the file protocol. + +| Boot | Mode file | Guest action | Host action | +|---|---|---|---| +| 1 | `write` | Discover, identify, write NEW at LBA 4096, `flush()`, run write bounds + device-error probes | After QEMU exits, read image at LBA 4096; require NEW bytes and `new_sha` | +| 2 | `verify` | Discover, identify, `read_blocks(4096)`; report guest hash and durability | Cross-check guest hash == `new_sha`; require it to match the host hash | + +Each boot copies a fresh `vars.fd` from `AAVMF_VARS`, exactly as +`qemu_nvme_test.sh:157`. A boot with no AIENOS output is retried (firmware hang, +issue #61, `qemu_nvme_test.sh:25-26,185-189`); a failure after AIENOS output +fails immediately. Retrying boot 1 is safe because the mode is explicit +(`write` rewrites NEW idempotently); it does not depend on image state. + +## 4. Exact markers per boot + +Markers follow the read lane's `NVME_*_QEMU: PASS` style +(`nvme_read.rs:392,481,491,516,541,557`). The write module must emit: + +**Boot 1 (`write`), granted-DMA modes (`smmu`, `unsafe-bypass`):** + +- `NVME_DISCOVERY_QEMU: PASS` - ECAM walk found class `0x0108`. +- `NVME_IDENTIFY_QEMU: PASS` - controller + namespace identify completed. +- `NVME_WRITE_QEMU: PASS (lba=4096 blocks=1 bytes=512 sha256=76fa34c1…)` - + `write_blocks(TARGET_LBA, NEW)` returned `Ok`, and the module hashed the NEW + buffer it submitted. +- `NVME_FLUSH_QEMU: PASS (nsid=1)` - `flush()` returned `Ok`. +- `NVME_WRITE_BOUNDS_QEMU: PASS (lba=131072 rejected OutOfRange no_command)` - + `write_blocks(block_count, …)` rejected client-side with no doorbell write, + the write-side analogue of `NVME_BOUNDS_QEMU` (`nvme_read.rs:536-548`). +- `NVME_WRITE_ERROR_QEMU: PASS` - a device-reported error is surfaced, not + swallowed. Normal path: an unallocated namespace identify + (`identify_namespace(0xffff_ffff)` → `NvmeError::CompletionStatus`, as + `nvme_read.rs:552-564`). Error-injection path: see §5. + +In every path where DMA was granted the module must revoke it +(`dma_gate: nvme bus master revoked`, `nvme_read.rs:232-247,566`) - including +when the write itself fails in `write-error` mode - so the host's revoke check +holds in all granted-DMA modes. + +**Boot 2 (`verify`):** + +- `NVME_DISCOVERY_QEMU: PASS`, `NVME_IDENTIFY_QEMU: PASS`. +- `NVME_READ_QEMU: PASS (lba=4096 blocks=1 bytes=512 sha256=76fa34c1…)` - the + guest's own SHA-256 of the block it read natively (**guest hash**); it must + equal `new_sha`. +- `NVME_DURABILITY_QEMU: PASS (lba=4096 restarted guest_sha256=76fa34c1…)` - + guest asserts the readback bytes equal NEW after restart. + +The host emits the final `QEMU_NVME_RW: PASS (${mode})`, mirroring +`QEMU_NVME: PASS` (`qemu_nvme_test.sh:278`). The required marker set is +therefore: `NVME_DISCOVERY_QEMU`, `NVME_IDENTIFY_QEMU`, `NVME_READ_QEMU`, +`NVME_WRITE_QEMU`, `NVME_FLUSH_QEMU`, `NVME_WRITE_BOUNDS_QEMU`, +`NVME_WRITE_ERROR_QEMU`, `NVME_DURABILITY_QEMU`, `QEMU_NVME_RW: PASS`. + +## 5. Modes + +Selected by the same env conventions as `qemu_nvme_test.sh:48-73` / +`qemu_keyboard_test.sh:37-61`. + +- **`smmu` (default)** - `-M virt,…,iommu=smmuv3`; feature `nvme-write`. Full + two-boot write → flush → persist → restart-read proof. Requires + `smmu: enabled`, `smmu_dma_window: nvme only, translation active`, + `dma_gate: nvme granted (Confined), bus master on`, and + `dma_gate: nvme bus master revoked` (`nvme_read.rs:233-247,430-461`). +- **`fail-closed`** - `AIENOS_QEMU_SMMU=0`, no SMMU. The controller must stay + unavailable (`dma_gate: nvme denied (NoSmmu), bus master stays off` and + `nvme: unavailable (SMMU DMA isolation not active)`, `nvme_read.rs:419-428`). + No write/read/flush/durability marker may appear, and the host must still see + OLD at LBA 4096. +- **`write-error`** - `AIENOS_NVME_WRITE_ERROR=1`. SMMU on, but the backend is + attached with `-drive …,readonly=on`. QEMU rejects the media write, so the + driver must surface a device-reported WRITE error: + `NVME_WRITE_ERROR_QEMU: PASS`, with **no** `NVME_WRITE_QEMU: PASS` and no + `NVME_FLUSH_QEMU`, and the host must still see OLD at LBA 4096. This is the + required dedicated error-injection mode. +- **`unsafe-bypass`** - `AIENOS_UNSAFE_DMA_BYPASS=1`. Same as `smmu` but the + unsafe debug build lets NVMe DMA run unconfined; announces + `WARNING: UNSAFE NVME DMA BYPASS BUILD` / `… ACTIVE` + (`nvme_read.rs:34-36,443-450`). QEMU debugging only; never in `verify_all.sh`. + +## 6. Host-vs-guest hash agreement + +- Host builds OLD and NEW, hashing both with `sha256sum` (values in §2). +- After boot 1, host runs + `dd if=nvme.img bs=512 skip=4096 count=1 | sha256sum` and requires it to equal + `new_sha`; this is the power-off persistence check. +- Boot 2's guest prints the SHA-256 of its own native readback in + `NVME_READ_QEMU` and asserts byte equality in `NVME_DURABILITY_QEMU`. The host + greps the exact expected string, so `guest_sha256 == new_sha == host_sha`. + Agreement across all three is the durability proof. + +## 7. Integration prerequisites (owned by the integration lane) + +This harness assumes the write lane adds, mirroring the read lane: + +1. Feature `nvme-write = ["handoff"]` in `crates/aienos-boot/Cargo.toml` (next + to `nvme-read` at `Cargo.toml:23`). +2. Module `nvme_write` gated in `crates/aienos-boot/src/handoff.rs` and a + post-exit `nvme_write::run(...)` call next to the read call + (`handoff.rs:560-561`, `handoff.rs:2110-2119`). +3. The `\EFI\AIENOS\NVME_RW_MODE.TXT` reader described in §3. +4. If `unsafe-bypass` is kept: `unsafe-debug-nvme-dma-without-smmu` currently + depends on `["nvme-read"]` (`Cargo.toml:48`); it must additionally enable + `nvme-write`, or the bypass build will not contain the write module. + +`scripts/verify_all.sh` is **not** edited by this lane. Wiring this harness in +(a two-boot RW QEMU step plus the aarch64 clippy feature loop in step 3b) is a +follow-up, exactly as the read harness notes at `qemu_nvme_test.sh:30-33`. \ No newline at end of file diff --git a/docs/P3_NVME_WRITE_REVIEW.md b/docs/P3_NVME_WRITE_REVIEW.md new file mode 100644 index 00000000..525b9d20 --- /dev/null +++ b/docs/P3_NVME_WRITE_REVIEW.md @@ -0,0 +1,152 @@ +# D1 Write-Path Correctness Review - AIENOS P3 Native NVMe Write + Flush + +Repo: aien-dev/aienos @ `ef359ec` (mirror `/Users/drakestapleton/aienos-nvme-rw`, read-only). +Scope: `crates/aienos-kernel/src/nvme.rs` (`Submission::write`, `io_command`, +`build_prps`, `Completion`) and `crates/aienos-kernel/src/nvme/driver.rs` +(`transfer`, `submit_io`, `write_blocks`/`read_blocks`/`flush`). + +Verdict: the write lane is functionally correct for the read substrate it reuses. +One latent defect is flagged (unreachable under the current MDTS cap) plus one +non-blocking resource observation. + +--- + +## 1. CDW layout (opcode / NSID / PRP / LBA / NLB) + +`io_command` (`nvme.rs:148-160`) writes, for a write (`opcode 0x01`): + +| Field | Dword | Source | Line | +|---|---|---|---| +| OPCODE | CDW0[7:0] | `0x01` | `nvme.rs:150` | +| CID | CDW0[31:16] | overlaid in `submit_io` | `driver.rs:370` | +| NSID | CDW1 | `1` | `nvme.rs:151` | +| PRP1 | CDW6/CDW7 | `p1` lo/hi | `nvme.rs:152-153` | +| PRP2 | CDW8/CDW9 | `p2` lo/hi | `nvme.rs:154-155` | +| LBA | CDW10/CDW11 | `lba` lo/hi | `nvme.rs:156-157` | +| NLB | CDW12[15:0] | `blocks - 1` | `nvme.rs:158` | + +**OK.** Layout matches NVMe Base Spec I/O Write. `Submission::write` +(`nvme.rs:135-137`) only selects opcode `0x01`, so write and read share the +same encoder and CDW12 semantics. + +## 2. Command ID lifecycle + +`submit_io` takes the next CID (monotonic `next_cid`), overlays it into +CDW0[31:16] preserving the opcode low half, and consumes only a completion whose +`command_id()` equals that CID (`driver.rs:368-370`, `389-390`). A mismatch is +reported rather than silently matched. **OK.** Covered by tests +`each_io_command_gets_a_new_cid_and_completion_is_consumed` and +`nonzero_write_completion_maps_to_device_error`. + +## 3. NLB = blocks - 1 + +`set_u32(12, (blocks as u32).wrapping_sub(1))` (`nvme.rs:158`). NVMe NLB is +0-based, so one block -> 0, eight -> 7. `transfer` guarantees `blocks >= 1` +because `data.is_empty()` is rejected and each chunk length is `>= block_size` +(`driver.rs:296-298`, `322-323`), so the `wrapping_sub` cannot underflow on the +write path. **OK.** + +## 4. LBA split across CDW10 / CDW11 + +`set_u32(10, lba as u32)` / `set_u32(11, (lba >> 32) as u32)` +(`nvme.rs:156-157`). Transfer passes `lba + offset/block_size` +(`driver.rs:350`). Because the range check bounds `lba + blocks <= block_count`, +the per-chunk LBA cannot overflow `u64`. **OK.** + +## 5. PRP1 / PRP2 / page-list construction reused from read + +The write path is the read path with an extra DMA pre-fill, so the PRP +construction is genuinely shared: + +- data region allocated at `PAGE_SIZE` alignment (`driver.rs:324`), +- `list_pages = len.div_ceil(PAGE_SIZE)`; a list region is allocated only when + more than two pages are spanned (`driver.rs:331-336`), +- `build_prps(region.physical, len, PAGE_SIZE, list_address, &mut list)` returns + `(p1, p2, used)` and those are passed unchanged to `Submission::write` + (`driver.rs:339-353`). + +Because the data region is page-aligned, `build_prps`' internal page count +(`nvme.rs:272-277`, offset = 0) exactly equals `list_pages`, so the ">2 pages" +test never disagrees with the encoder. PRP1 is the raw buffer address, PRP2 the +second page or the list address, and the list entries are the remaining data +pages - identical to the read path. **OK.** + +## 6. MDTS chunking + +`mdts_limit` is `128 KiB` when `mdts == 0`, else `PAGE_SIZE << mdts` clamped to +`128 KiB` (`driver.rs:308-315`); `chunk_limit` is floored to a whole block +(`driver.rs:316`). This is a deliberate conservative cap: MDTS=0 means +"no limit" in the spec, but capping is always safe. MDTS units are the minimum +page size, and `init` refuses `CAP.MPSMIN != 0` (`driver.rs:118-120`), so the +`PAGE_SIZE` base is correct. `checked_shl` + `unwrap_or(usize::MAX)` avoids the +`mdts = 255` shift panic. **OK.** + +### NEEDS-FIX (latent): the single-page PRP list is only safe because MDTS is capped +- **Where:** `driver.rs:331-337` (one `PAGE_SIZE` list region and a + `PAGE_SIZE / 8 = 512`-entry list buffer). +- **Why:** `build_prps` supports chaining across contiguous list pages + (`nvme.rs:295-316`), but the driver allocates exactly one list page. A chunk + needing more than 511 data-page entries (i.e. `> 2 MiB` at 4 KiB pages) would + fail `build_prps` with `ListTooSmall`, which `transfer` maps to + `BlockError::InvalidInput` (`driver.rs:341`), failing every large transfer. This + is unreachable today only because `mdts_limit` is hard-capped at `128 KiB` + (`driver.rs:314`). The cap is load-bearing and undocumented. +- **Minimal fix:** size the list allocation and buffer from the page count, e.g. + `let entries = (list_pages - 1).max(1); let list_pages_needed = entries.div_ceil(PAGE_SIZE / 8);` + allocate `list_pages_needed * PAGE_SIZE` bytes and + `alloc::vec![0u64; list_pages_needed * (PAGE_SIZE / 8)]`. Alternatively, add a + comment asserting the 128 KiB cap is what keeps the list within one page. + +## 7. Per-chunk commands + +The chunk loop advances by whole blocks and recomputes the LBA from the block +offset (`driver.rs:320-360`), submitting exactly one I/O command per chunk via +`submit_io` (`driver.rs:349-353`). Each chunk gets its own CID and its own +completion (synchronous poll), and the next chunk's DMA is not allocated until +the previous command has completed, so no buffer is freed while the device may +still be reading it. **OK.** Covered by +`mdts_chunking_submits_per_chunk_commands_with_correct_lba_and_nlb` +(300 blocks -> 256 + 44, NLB 255 and 43, LBA 20 and 276). + +## 8. Transfer bounds (no I/O on rejection) + +`lba.checked_add(blocks).filter(|end| *end <= block_count)` rejects overflowing +or past-end ranges with `BlockError::OutOfRange` (`driver.rs:301-307`) *before* +any allocation or `submit_io`. **OK.** Covered by +`write_past_block_count_is_out_of_range_without_io_submission`, which asserts +the command count, I/O doorbell count, and DMA region count are all unchanged. + +## 9. Empty / non-block-multiple input + +`data.is_empty() || !data.len().is_multiple_of(block_size)` -> `InvalidInput` +(`driver.rs:296-298`) before bounds and before I/O. **OK.** Covered by +`empty_and_non_block_multiple_buffers_are_invalid_input`. + +## 10. Write completion status -> DeviceError + +`submit_io` advances the completion head (and phase on wrap), rings the CQ +doorbell, then returns `BlockError::DeviceError` for any nonzero status +(`driver.rs:392-403`). **OK.** Covered by +`nonzero_write_completion_maps_to_device_error`. + +## 11. Flush + +`flush` submits opcode `0x00` with NSID 1 and no PRP (`driver.rs:432-439`); +`submit_io` handles it identically to a payload command and the device replies +with a normal completion. **OK.** + +## 12. Observation (non-blocking): redundant copy in `write_blocks` + +`write_blocks` does `buffer.to_vec()` (`driver.rs:429`) solely to satisfy +`transfer`'s `&mut [u8]` parameter, which the write path never mutates. For a +128 KiB chunk this doubles transient kernel memory. Not a correctness defect; +a write-specific path taking `&[u8]` would remove it. + +--- + +## Required corrections + +- **NEEDS-FIX (latent, §6):** single-page PRP list allocation is correct only + under the 128 KiB MDTS cap; make the list sizing derive from the page count + (or document the invariant). No runtime impact at `ef359ec`. +- All other reviewed items: **OK**. diff --git a/evidence/p3_nvme_write_flush_qemu_2026-09-25.md b/evidence/p3_nvme_write_flush_qemu_2026-09-25.md new file mode 100644 index 00000000..0fefd9c8 --- /dev/null +++ b/evidence/p3_nvme_write_flush_qemu_2026-09-25.md @@ -0,0 +1,83 @@ +# P3 native NVMe write + flush durability qualification (2026-09-25) + +Result: **`QEMU_NVME_RW: PASS`** in SMMU-confined and fail-closed modes. + +Emulator qualification only. It is not Machine 1 evidence and does not touch +Store. QEMU disposable media only; the drive is a fresh raw file rebuilt each +run. + +Base: `aien-dev/aienos` @ `ef359ec` plus this branch. Commands: +`bash scripts/qemu_nvme_rw_test.sh` (SMMU) and +`AIENOS_QEMU_SMMU=0 bash scripts/qemu_nvme_rw_test.sh` (fail-closed). + +## Media and payloads + +- 64 MiB raw image, 131072 LBAs of 512 bytes. +- Read sentinel at LBA 2048: `AIENOS-NVME-SENT` x32, + sha256 `8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1`. +- Write target at LBA 4096, seeded OLD (`AIENOS-NVME-OLD0` x32), written NEW + (`AIENOS-NVME-RW01` x32), + sha256 `76fa34c132173497a7bcd0c9618ebdcf0629f550934c164adf81cfa05e6a4451`. +- Bounds write at LBA 131072 (== block_count); error write at NSID `0xffffffff`. + +## Boot 1 (SMMU confined): write, flush, read-back + +```text +NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x8000004000) +smmu: enabled base=0x9050000 stream_id=0x10 +smmu_dma_window: nvme only, translation active +dma_gate: nvme granted (Confined), bus master on +NVME_IDENTIFY_QEMU: PASS (vid=0x1b36 did=0x0010 nsid=1) +NVME_GEOMETRY_QEMU: PASS (nsid=1 block_count=131072 block_size=512) +NVME_READ_QEMU: PASS (lba=2048 blocks=1 bytes=512 sha256=8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1) +NVME_BOUNDS_QEMU: PASS (lba=131072 rejected OutOfRange no_command) +NVME_ERROR_QEMU: PASS (identify nsid=0xffffffff rejected status=nonzero sct=0 sc=11) +NVME_WRITE_BOUNDS_QEMU: PASS (lba=131072 rejected OutOfRange no_command) +NVME_WRITE_QEMU: PASS (lba=4096 blocks=1 bytes=512 sha256=76fa34c132173497a7bcd0c9618ebdcf0629f550934c164adf81cfa05e6a4451) +NVME_FLUSH_QEMU: PASS (nsid=1) +NVME_DURABILITY_QEMU: PASS (lba=4096 blocks=1 bytes=512 sha256=76fa34c132173497a7bcd0c9618ebdcf0629f550934c164adf81cfa05e6a4451) +NVME_WRITE_ERROR_QEMU: PASS (write nsid=0xffffffff rejected status=nonzero) +dma_gate: nvme bus master revoked +QEMU_NVME_RW: PASS (smmu) +``` + +Host check after the guest stopped: reading LBA 4096 from the image file +returns the written bytes, sha256 +`76fa34c132173497a7bcd0c9618ebdcf0629f550934c164adf81cfa05e6a4451` (power-off +persistence). + +## Boot 2 (same image, restart): persisted read + +```text +NVME_READ_QEMU: PASS (lba=2048 ... sha256=8b688adc...) +NVME_DURABILITY_QEMU: PASS (persisted lba=4096 blocks=1 bytes=512 sha256=76fa34c1...) +dma_gate: nvme bus master revoked +``` + +`persisted` means the phase read the target before writing and found the bytes +an earlier boot wrote, so the data survived the restart and the host-visible +media. The harness requires this marker on boot 2. + +## Fail-closed (no SMMU, normal build) + +```text +NVME_DISCOVERY_QEMU: PASS (...) +dma_gate: nvme denied (NoSmmu), bus master stays off +nvme: unavailable (SMMU DMA isolation not active) +QEMU_NVME_RW: PASS (fail-closed) +``` + +`NVME_WRITE_QEMU`, `NVME_FLUSH_QEMU`, and `NVME_DURABILITY_QEMU` are absent. +No SMMU confinement means no DMA, so no write reaches the device. + +## What this proves and does not prove + +- Proves, in QEMU: native NVMe write command construction and completion, + a real NVMe Flush (opcode 0, no-op prohibited), flush-gated durability, + client-side write bounds, an invalid-namespace write error surfaced as a + device error, host-visible persistence after power off, and native read-back + after restart, all with DMA confined by the SMMU to the driver arena. +- Does not prove: any Machine 1 or GB10 behavior, Store behavior, multi-queue + I/O, FUA, or power-loss atomicity beyond a completed Flush. It makes no + Store v1 dependency and touches no Store file. No media is written outside + the disposable QEMU image.