Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
GitHub aien-dev/aienux#129 (code only)
closed derived 4716a0172420e806 #129
Imported from GitHub aien-dev/aienux#129 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base ff5de9c5af6da27d0e8dc9ddefa3d7b63fbdffd3 · Head 8f2d3cc863e91a31691c8d5c8f85bf8f2db4aab0
github-advanced-security[bot] commented on crates/aienos-boot/src/handoff.rs line 329 on 2026-09-25 13:45 UTC
CodeQL / Access of invalid pointer
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
Show more details
github-advanced-security[bot] commented on crates/aienos-boot/src/handoff.rs line 2106 on 2026-09-25 13:45 UTC
CodeQL / Access of invalid pointer
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
This operation dereferences a pointer that may be invalid .
Show more details
github-advanced-security[bot] reviewed (COMMENTED) on 2026-09-25 13:45 UTC
Apply it
git checkout -b patch-4716a0172420e806 ff5de9c5af6da27d0e8dc9ddefa3d7b63fbdffd3
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/4716a0172420e806 .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aienux
129
8f2d3cc863e91a31691c8d5c8f85bf8f2db4aab0
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":129,"url":"https://github.com/aien-dev/aienux/pull/129","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:35:47Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml
index aa9a8c08 ..3ecca6c3 100644
--- a/crates/aienos-boot/Cargo.toml
+++ b/crates/aienos-boot/Cargo.toml
@@ -18,6 +18,9 @@ handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc"]
# SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012).
# Only the QEMU keyboard test enables it; hardware staging never does.
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"]
# 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
@@ -36,6 +39,13 @@ hardware-staging = ["handoff"]
# `hardware-staging`. Reach it only through AIENOS_UNSAFE_DMA_BYPASS=1 in
# scripts/qemu_keyboard_test.sh.
unsafe-debug-dma-without-smmu = ["usb-keyboard"]
+# UNSAFE. DEBUG ONLY. QEMU ONLY. Same bypass for the NVMe read candidate:
+# it lets the NVMe function DMA to physical memory with NO SMMU confinement
+# when the platform has no SMMU. It never applies when an SMMU exists but
+# failed to initialise, prints a warning on every boot, and is a compile
+# error together with `hardware-staging`. Reach it only through
+# AIENOS_UNSAFE_DMA_BYPASS=1 in scripts/qemu_nvme_test.sh.
+unsafe-debug-nvme-dma-without-smmu = ["nvme-read"]
[dependencies]
uefi = { version = "0.41", default-features = false, optional = true }
diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs
index bac7b94b ..e1377af1 100644
--- a/crates/aienos-boot/src/handoff.rs
+++ b/crates/aienos-boot/src/handoff.rs
@@ -38,7 +38,7 @@ use aienos_kernel::report::ReportBuf;
use aienos_kernel::sync::spinlock::SpinLock;
use core::alloc::{GlobalAlloc, Layout};
use core::fmt::Write;
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams};
@@ -60,7 +60,7 @@ static POST_EXIT_HEAP: AtomicU64 = AtomicU64::new(0);
static POST_EXIT_HEAP_USED: AtomicU64 = AtomicU64::new(0);
static BOOT_SERVICES_LIVE: AtomicBool = AtomicBool::new(true);
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
#[repr(C)]
// Field order keeps every queue aligned to its own size (the SMMU ignores
// low base address bits below the queue size): stream table at 0 (256 KiB),
@@ -73,10 +73,10 @@ struct SmmuTables {
context: [u64; 8],
}
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
const STREAM_ENTRIES: u32 = 4096;
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
const SMMU_QUEUE_ENTRIES: u32 = 16;
// The linear stream table base must be aligned to its size (4096 * 64 bytes =
@@ -84,13 +84,13 @@ const SMMU_QUEUE_ENTRIES: u32 = 16;
// section alignment above 8192, so a 256 KiB-aligned static is unbuildable for
// aarch64-unknown-uefi; allocate the tables at runtime with an over-aligned
// Layout and hand out one shared pointer to every user instead.
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
const SMMU_TABLES_ALIGN: usize = 262144;
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
static SMMU_TABLES_PTR: AtomicUsize = AtomicUsize::new(0);
-#[cfg(feature = "usb-keyboard")]
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
fn smmu_tables() -> *mut SmmuTables {
let existing = SMMU_TABLES_PTR.load(Ordering::Acquire);
if existing != 0 {
@@ -105,6 +105,15 @@ fn smmu_tables() -> *mut SmmuTables {
raw.cast::<SmmuTables>()
}
+/// Pointer to the shared event queue ring, reached by byte offset so no typed
+/// pointer dereference is needed.
+#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
+fn smmu_event_queue_ptr() -> *const [[u64; 4]; SMMU_QUEUE_ENTRIES as usize] {
+ let base = smmu_tables() as *mut u8;
+ base.wrapping_add(core::mem::offset_of!(SmmuTables, event_queue))
+ .cast()
+}
+
struct BootHeap;
unsafe impl GlobalAlloc for BootHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
@@ -281,6 +290,74 @@ fn configure_smmu_for_xhci(
Ok(stream_id)
}
+#[cfg(feature = "nvme-read")]
+fn configure_smmu_for_nvme(
+ iort: Option<&acpi::IortSmmu>,
+ nvme: Option<nvme_read::NvmeLocation>,
+ pool_base: usize,
+ frames_used: usize,
+) -> Result<u32, aienos_kernel::smmu::Error> {
+ let iort = iort.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
+ let nvme = nvme.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
+ let stream_id = nvme
+ .stream_id(iort)
+ .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
+ let (dma_base, dma_length) = nvme.dma_window();
+ let remaining = PT_POOL_PAGES.saturating_sub(frames_used);
+ let next = pool_base
+ .checked_add(
+ frames_used
+ .checked_mul(4096)
+ .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?,
+ )
+ .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
+ let frames = FixedFramePool::new(PhysAddr(next), remaining)
+ .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
+ // Stage-1 table that maps only the NVMe DMA arena (identity).
+ let policy = aienos_kernel::smmu::build_dma_policy(
+ stream_id,
+ 1,
+ &[aienos_kernel::smmu::DmaWindow {
+ iova: dma_base as usize,
+ pa: PhysAddr(dma_base as usize),
+ length: dma_length,
+ }],
+ frames,
+ PhysicalTableMemory,
+ )?;
+ let table_frames = policy.page_table.frames_used().unwrap_or(0);
+ clean_table_pool(next, table_frames * 4096);
+
+ let base = smmu_tables() as *mut u8;
+ assert!(stream_id < STREAM_ENTRIES, "SID outside the stream table");
+ // Field addresses are reached by byte offset from the allocation base, so
+ // no typed pointer dereference happens here.
+ let field = |offset: usize| base.wrapping_add(offset);
+ // Safety: as in configure_smmu_for_xhci, the tables are one live,
+ // identity-mapped, 256 KiB-aligned allocation owned by the SMMU; the
+ // register aperture is identity mapped by enter_kernel_mmu.
+ let linear = unsafe {
+ aienos_kernel::smmu::LinearTables::new(
+ field(core::mem::offset_of!(SmmuTables, stream_table)).cast::<[u64; 8]>(),
+ STREAM_ENTRIES,
+ field(core::mem::offset_of!(SmmuTables, command_queue)).cast::<[u64; 2]>(),
+ SMMU_QUEUE_ENTRIES,
+ field(core::mem::offset_of!(SmmuTables, event_queue)).cast::<[u64; 4]>(),
+ SMMU_QUEUE_ENTRIES,
+ field(core::mem::offset_of!(SmmuTables, context)).cast::<[u64; 8]>(),
+ )?
+ };
+ let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) };
+ aienos_kernel::smmu::configure_linear_stream(
+ &mut regs,
+ &linear,
+ policy.stream_id,
+ &policy.cd,
+ aienos_kernel::smmu::DEFAULT_SPINS,
+ )?;
+ Ok(stream_id)
+}
+
#[allow(clippy::too_many_arguments)]
fn enter_kernel_mmu(
memory_map: &impl MemoryMap,
@@ -294,6 +371,8 @@ fn enter_kernel_mmu(
ecam: Option<AddressRange>,
gic: Option<acpi::GicBases>,
smmu_mmio: Option<u64>,
+ nvme_mmio: Option<u64>,
+ nvme_ecam: Option<AddressRange>,
) -> KernelMmu {
let descriptors: alloc::vec::Vec<_> = memory_map
.entries()
@@ -326,6 +405,15 @@ fn enter_kernel_mmu(
if let Some(range) = ecam {
mmio.push(range);
}
+ if let Some(base) = nvme_mmio {
+ mmio.push(AddressRange {
+ start: base & !4095,
+ length: 0x10000,
+ });
+ }
+ if let Some(range) = nvme_ecam {
+ mmio.push(range);
+ }
if let Some(gic) = gic {
if let Some(base) = gic.distributor {
mmio.push(AddressRange {
@@ -469,6 +557,9 @@ fn current_ttbr0_el1() -> u64 {
#[cfg(feature = "usb-keyboard")]
mod usb_keyboard;
+#[cfg(feature = "nvme-read")]
+mod nvme_read;
+
/// Commit this image was built from; `scripts/stage_one_time_boot.sh` sets it.
const COMMIT: &str = match option_env!("AIENOS_COMMIT") {
Some(commit) => commit,
@@ -945,9 +1036,9 @@ struct AcpiFacts {
cpu: Option<acpi::CpuTopology>,
spcr: Option<acpi::SpcrConsole>,
gic: Option<acpi::GicBases>,
- #[cfg(feature = "usb-keyboard")]
+ #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
mcfg: Option<&'static [u8]>,
- #[cfg(feature = "usb-keyboard")]
+ #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
iort: Option<acpi::IortSmmu>,
}
@@ -986,9 +1077,9 @@ fn discover_acpi(boot_mpidr: u64) -> AcpiFacts {
facts.gic = acpi::madt_gic_bases(table).ok();
}
b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(),
- #[cfg(feature = "usb-keyboard")]
+ #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
b"MCFG" => facts.mcfg = Some(table),
- #[cfg(feature = "usb-keyboard")]
+ #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
b"IORT" => facts.iort = acpi::iort_smmuv3(table).ok().flatten(),
_ => {}
}
@@ -1550,6 +1641,8 @@ fn main() -> Status {
let artifact_candidates = read_artifact_candidates();
#[cfg(feature = "usb-keyboard")]
let xhci = usb_keyboard::find_xhci();
+ #[cfg(feature = "nvme-read")]
+ let nvme = nvme_read::find_nvme();
let mut pre = Report::new();
header(&mut pre, "pre_exit");
@@ -1653,9 +1746,28 @@ fn main() -> Status {
#[cfg(not(feature = "usb-keyboard"))]
None,
acpi_facts.gic,
- #[cfg(feature = "usb-keyboard")]
+ #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
acpi_facts.iort.as_ref().map(|i| i.base),
- #[cfg(not(feature = "usb-keyboard"))]
+ #[cfg(not(any(feature = "usb-keyboard", feature = "nvme-read")))]
+ None,
+ #[cfg(feature = "nvme-read")]
+ nvme.map(|n| n.mmio_base()),
+ #[cfg(not(feature = "nvme-read"))]
+ None,
+ #[cfg(feature = "nvme-read")]
+ nvme.and_then(|n| {
+ let (segment, bus) = n.ecam_location();
+ acpi_facts.mcfg.and_then(|t| {
+ acpi::mcfg_window(t, segment, bus)
+ .ok()
+ .flatten()
+ .map(|w| AddressRange {
+ start: w.base,
+ length: (u64::from(w.end_bus) - u64::from(w.start_bus) + 1) << 20,
+ })
+ })
+ }),
+ #[cfg(not(feature = "nvme-read"))]
None,
);
let pt_frames_used = kernel_mmu.pt_frames_used;
@@ -1671,6 +1783,16 @@ fn main() -> Status {
let smmu_result =
configure_smmu_for_xhci(acpi_facts.iort.as_ref(), xhci, pt_pool, pt_frames_used);
+ // NVMe read candidate: same fail-closed DMA discipline. Enabling both
+ // `usb-keyboard` and `nvme-read` in one image is not a supported build;
+ // each QEMU harness enables exactly one.
+ #[cfg(feature = "nvme-read")]
+ let nvme_takeover = nvme_read::take_over_dma(nvme, acpi_facts.mcfg);
+
+ #[cfg(feature = "nvme-read")]
+ let nvme_smmu_result =
+ configure_smmu_for_nvme(acpi_facts.iort.as_ref(), nvme, pt_pool, pt_frames_used);
+
fatal::set_fault_hook(on_fault);
fatal::install_exception_vectors();
stage(VECTORS_INSTALLED);
@@ -1983,7 +2105,17 @@ fn main() -> Status {
smmu_result.is_ok(),
acpi_facts.iort.as_ref().map(|s| s.base),
smmu_result.ok(),
- unsafe { core::ptr::addr_of_mut!((*smmu_tables()).event_queue).cast_const() },
+ smmu_event_queue_ptr(),
+ );
+ #[cfg(feature = "nvme-read")]
+ nvme_read::run(
+ nvme,
+ nvme_takeover,
+ &mut screen,
+ nvme_smmu_result.is_ok(),
+ acpi_facts.iort.as_ref().map(|s| s.base),
+ nvme_smmu_result.ok(),
+ smmu_event_queue_ptr(),
);
finish(screen)
}
diff --git a/crates/aienos-boot/src/lib.rs b/crates/aienos-boot/src/lib.rs
index 08cd759f ..89309f18 100644
--- a/crates/aienos-boot/src/lib.rs
+++ b/crates/aienos-boot/src/lib.rs
@@ -20,3 +20,17 @@ compile_error!(
/// Whether this build carries the unsafe, QEMU-only DMA bypass.
pub const UNSAFE_DMA_BYPASS: bool = cfg!(feature = "unsafe-debug-dma-without-smmu");
+
+// The same rule for the NVMe read candidate: unconfined DMA must never be
+// part of an image staged on Machine 1.
+#[cfg(all(
+ feature = "unsafe-debug-nvme-dma-without-smmu",
+ feature = "hardware-staging"
+))]
+compile_error!(
+ "feature `unsafe-debug-nvme-dma-without-smmu` (unconfined DMA, QEMU debug only) \
+ cannot be combined with `hardware-staging`: no SMMU confinement means no DMA"
+);
+
+/// Whether this build carries the unsafe, QEMU-only NVMe DMA bypass.
+pub const UNSAFE_NVME_DMA_BYPASS: bool = cfg!(feature = "unsafe-debug-nvme-dma-without-smmu");
diff --git a/crates/aienos-boot/src/nvme_read.rs b/crates/aienos-boot/src/nvme_read.rs
new file mode 100644
index 00000000 ..d509932f
--- /dev/null
+++ b/crates/aienos-boot/src/nvme_read.rs
@@ -0,0 +1,601 @@
+//! P3 native NVMe read substrate (read-only qualification).
+//!
+//! Built only with the `nvme-read` feature, which `scripts/qemu_nvme_test.sh`
+//! enables and hardware staging never does. After firmware exit this module
+//! drives a PCIe NVMe controller with the polled, host-tested
+//! [`aienos_kernel::nvme`] driver over a native MMIO adapter and a static DMA
+//! arena, then reads one sentinel LBA and verifies it natively.
+//!
+//! Read-only: this module issues Identify (admin, 0x06) and Read (I/O, 0x02)
+//! only. It never calls `write_blocks`, `flush`, format, or any mutating
+//! command. Write and flush are not claimed here.
+//!
+//! DMA rule (M3): no SMMU confinement means no DMA. [`take_over_dma`] clears
+//! Bus Master Enable on every endpoint of the controller's PCI segment before
+//! any SMMU or driver setup, and [`run`] sets it again only when
+//! [`dma_gate::dma_grant`] allows it.
+
+use aienos_kernel::acpi::{self, EcamWindow};
+use aienos_kernel::arch::aarch64::{
+ clean_dcache_range, clean_invalidate_dcache_range, counter_frequency_hz, counter_ticks, MmioReg,
+};
+use aienos_kernel::block::BlockDevice;
+use aienos_kernel::console::EarlyConsole;
+use aienos_kernel::display::Screen;
+use aienos_kernel::dma_gate::{self, BusMasterSweep, DmaGrant, PciConfig, PCI_COMMAND};
+use aienos_kernel::nvme::driver::{Delay, DmaMemory, DmaRegion, NvmeController, NvmeError};
+use aienos_kernel::nvme::Registers;
+use core::fmt::Write;
+use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams};
+use uefi::proto::pci::root_bridge::PciRootBridgeIo;
+use uefi::proto::pci::PciIoAddress;
+
+/// Printed on every boot of an image built with the unsafe NVMe DMA bypass.
+const UNSAFE_NVME_BANNER: &str =
+ "\nWARNING: UNSAFE NVME DMA BYPASS BUILD (unsafe-debug-nvme-dma-without-smmu): \
+ NVMe DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n";
+
+/// Sentinel the qualification image holds: 32 repeats of a 16-byte magic in
+/// one 512-byte LBA.
+pub const SENTINEL_MAGIC: &[u8; 16] = b"AIENOS-NVME-SENT";
+pub const SENTINEL_LBA: u64 = 2048;
+
+const ARENA_BYTES: usize = 128 * 1024;
+
+#[repr(C, align(4096))]
+struct DmaArena([u8; ARENA_BYTES]);
+
+static mut DMA_ARENA: DmaArena = DmaArena([0; ARENA_BYTES]);
+
+/// Where the NVMe controller sits, found before firmware exit.
+#[derive(Clone, Copy)]
+pub struct NvmeLocation {
+ segment: u16,
+ bus: u8,
+ device: u8,
+ function: u8,
+ vendor: u16,
+ device_id: u16,
+ mmio: u64,
+}
+
+impl NvmeLocation {
+ pub fn mmio_base(self) -> u64 {
+ self.mmio
+ }
+ pub fn ecam_location(self) -> (u16, u8) {
+ (self.segment, self.bus)
+ }
+ pub fn requester_id(self) -> u32 {
+ (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function)
+ }
+ pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option<u32> {
+ iort.stream_id_for(self.requester_id())
+ }
+ pub fn dma_window(self) -> (u64, usize) {
+ let base = core::ptr::addr_of!(DMA_ARENA) as u64;
+ (base & !0xfff, core::mem::size_of::<DmaArena>())
+ }
+}
+
+/// Walk every root bridge for the first NVMe controller (class base 0x01,
+/// sub-class 0x08). Pre-exit only; read-only config access.
+pub fn find_nvme() -> Option<NvmeLocation> {
+ for handle in uefi::boot::find_handles::<PciRootBridgeIo>().ok()? {
+ let params = OpenProtocolParams {
+ handle,
+ agent: uefi::boot::image_handle(),
+ controller: None,
+ };
+ let Ok(mut root) = (unsafe {
+ uefi::boot::open_protocol::<PciRootBridgeIo>(
+ params,
+ OpenProtocolAttributes::GetProtocol,
+ )
+ }) else {
+ continue;
+ };
+ let (bus_min, bus_max) = crate::bus_ranges(&mut root).unwrap_or((0, 0));
+ for bus in bus_min..=bus_max {
+ for device in 0..32u8 {
+ for function in 0..8u8 {
+ let address = PciIoAddress::new(bus, device, function);
+ let mut read = |offset| {
+ root.pci()
+ .read_one::<u32>(address.with_register(offset))
+ .ok()
+ };
+ let Some(id) = read(0).filter(|id| id & 0xffff != 0xffff) else {
+ if function == 0 {
+ break;
+ }
+ continue;
+ };
+ if let (Some(class), Some(low), Some(high)) =
+ (read(0x08), read(0x10), read(0x14))
+ {
+ // Config dword 0x08 is base<<24 | subclass<<16 | prog_if<<8 | rev.
+ let class_code = class >> 16;
+ // 0x0108: mass storage, NVM. Accept any programming
+ // interface (QEMU reports 0x010802).
+ if class_code == 0x0108 && low & 0x1 == 0 {
+ let is_64 = low & 0x7 == 0x4;
+ let mmio = if is_64 {
+ (u64::from(high) << 32) | u64::from(low & !0xf)
+ } else {
+ u64::from(low & !0xf)
+ };
+ if mmio != 0 {
+ return Some(NvmeLocation {
+ segment: root.segment_nr() as u16,
+ bus,
+ device,
+ function,
+ vendor: (id & 0xffff) as u16,
+ device_id: (id >> 16) as u16,
+ mmio,
+ });
+ }
+ }
+ }
+ let multi = read(0x0c).is_some_and(|v| v & 0x80_0000 != 0);
+ if function == 0 && !multi {
+ break;
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+fn console() -> Option<EarlyConsole> {
+ crate::CONSOLE
+ .try_lock()
+ .and_then(|k| *k)
+ .and_then(EarlyConsole::from_kind)
+}
+
+/// Write `text` to the SPCR console and the screen.
+fn say(screen: &mut Option<Screen>, text: &str) {
+ if let Some(console) = console() {
+ console.write_str(text);
+ }
+ if let Some(s) = screen.as_mut() {
+ let _ = s.write_str(text);
+ }
+}
+
+/// Config space of one ECAM window, reached through the kernel identity map.
+struct Ecam(EcamWindow);
+
+impl PciConfig for Ecam {
+ fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32> {
+ let addr = self.0.config_address(bus, device, function, offset)?;
+ Some(MmioReg::<u32>::new(addr as usize).read())
+ }
+ fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) {
+ if let Some(addr) = self.0.config_address(bus, device, function, offset) {
+ MmioReg::<u16>::new(addr as usize).write(value);
+ }
+ }
+}
+
+impl Ecam {
+ fn command(&mut self, at: &NvmeLocation) -> Option<u16> {
+ self.read32(at.bus, at.device, at.function, PCI_COMMAND)
+ .map(|v| v as u16)
+ }
+ fn set_command(&mut self, at: &NvmeLocation, value: u16) {
+ self.write16(at.bus, at.device, at.function, PCI_COMMAND, value);
+ }
+}
+
+/// What [`take_over_dma`] did to the controller's PCI segment.
+#[derive(Clone, Copy)]
+pub struct DmaTakeover {
+ window: EcamWindow,
+ sweep: BusMasterSweep,
+}
+
+/// Post-exit, before any SMMU or driver setup: clear Bus Master Enable on
+/// every endpoint in the NVMe ECAM window.
+pub fn take_over_dma(nvme: Option<NvmeLocation>, mcfg: Option<&[u8]>) -> Option<DmaTakeover> {
+ let at = nvme?;
+ let window = acpi::mcfg_window(mcfg?, at.segment, at.bus)
+ .ok()
+ .flatten()?;
+ let sweep = dma_gate::sweep_bus_master(&mut Ecam(window), window.start_bus, window.end_bus);
+ Some(DmaTakeover { window, sweep })
+}
+
+fn report_takeover(screen: &mut Option<Screen>, takeover: &DmaTakeover) {
+ let (w, s) = (&takeover.window, &takeover.sweep);
+ let mut line = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(
+ line,
+ "dma_sweep: seg {:04x} bus {:02x}-{:02x} functions={} bridges={} bridges_bme={} \
+ endpoints_bme_found={} still_enabled={}",
+ w.segment,
+ w.start_bus,
+ w.end_bus,
+ s.functions,
+ s.bridges,
+ s.bridges_bus_master,
+ s.endpoints_bus_master,
+ s.still_enabled
+ );
+ say(screen, line.as_str());
+}
+
+/// Clear Bus Master Enable on the controller again (revoke its DMA).
+fn revoke_dma(screen: &mut Option<Screen>, ecam: &mut Ecam, at: &NvmeLocation) {
+ if let Some(command) = ecam.command(at) {
+ ecam.set_command(at, dma_gate::without_bus_master(command));
+ }
+ let off = ecam
+ .command(at)
+ .is_some_and(|c| !dma_gate::bus_master_enabled(c));
+ say(
+ screen,
+ if off {
+ "dma_gate: nvme bus master revoked\n"
+ } else {
+ "dma_gate: nvme bus master revoke FAILED\n"
+ },
+ );
+}
+
+/// Registers adapter over the controller's MMIO BAR.
+struct NativeRegisters {
+ base: usize,
+}
+
+impl Registers for NativeRegisters {
+ fn read32(&mut self, offset: u32) -> u32 {
+ MmioReg::<u32>::new(self.base + offset as usize).read()
+ }
+ fn write32(&mut self, offset: u32, value: u32) {
+ MmioReg::<u32>::new(self.base + offset as usize).write(value);
+ }
+}
+
+/// Bump allocator over the static, identity-mapped, cache-coherent DMA arena.
+struct NativeDma {
+ cursor: usize,
+ end: usize,
+}
+
+impl NativeDma {
+ fn new() -> Self {
+ let base = core::ptr::addr_of!(DMA_ARENA) as usize;
+ Self {
+ cursor: base,
+ end: base + ARENA_BYTES,
+ }
+ }
+
+ fn offset_of(physical: u64) -> Option<usize> {
+ let base = core::ptr::addr_of!(DMA_ARENA) as u64;
+ let offset = physical.checked_sub(base)?;
+ (offset < ARENA_BYTES as u64).then_some(offset as usize)
+ }
+}
+
+impl DmaMemory for NativeDma {
+ fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
+ if alignment == 0 || !alignment.is_power_of_two() {
+ return Err(NvmeError::Dma);
+ }
+ let aligned = self
+ .cursor
+ .checked_add(alignment - 1)
+ .map(|v| v & !(alignment - 1))
+ .ok_or(NvmeError::Dma)?;
+ if aligned.checked_add(size).is_none_or(|end| end > self.end) {
+ return Err(NvmeError::Dma);
+ }
+ self.cursor = aligned + size;
+ // SAFETY: bump-allocated inside the live static arena, never shared.
+ unsafe { core::ptr::write_bytes(aligned as *mut u8, 0, size) };
+ Ok(DmaRegion {
+ physical: aligned as u64,
+ bytes: alloc::vec![0u8; size],
+ })
+ }
+
+ fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
+ let offset = Self::offset_of(physical).ok_or(NvmeError::Dma)?;
+ if offset + output.len() > ARENA_BYTES {
+ return Err(NvmeError::Dma);
+ }
+ // The device wrote this memory; drop stale cache lines before reading.
+ let base = core::ptr::addr_of!(DMA_ARENA) as usize;
+ clean_invalidate_dcache_range(base + offset, output.len());
+ // SAFETY: in-bounds inside the live arena; copy into the caller buffer.
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ (base + offset) as *const u8,
+ output.as_mut_ptr(),
+ output.len(),
+ )
+ };
+ Ok(())
+ }
+
+ fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
+ let offset = Self::offset_of(physical).ok_or(NvmeError::Dma)?;
+ if offset + input.len() > ARENA_BYTES {
+ return Err(NvmeError::Dma);
+ }
+ let base = core::ptr::addr_of!(DMA_ARENA) as usize;
+ // SAFETY: in-bounds inside the live arena; copy from the caller buffer.
+ unsafe {
+ core::ptr::copy_nonoverlapping(input.as_ptr(), (base + offset) as *mut u8, input.len())
+ };
+ // Make the CPU writes visible to the controller before it reads them.
+ clean_dcache_range(base + offset, input.len());
+ Ok(())
+ }
+}
+
+/// Real-time delay bounded by the architectural counter.
+struct NativeDelay;
+
+impl Delay for NativeDelay {
+ fn delay_us(&mut self, us: u32) {
+ let hz = counter_frequency_hz();
+ if hz == 0 {
+ for _ in 0..us {
+ core::hint::spin_loop();
+ }
+ return;
+ }
+ let ticks = hz.saturating_mul(u64::from(us)) / 1_000_000;
+ let start = counter_ticks();
+ while counter_ticks().wrapping_sub(start) < ticks {
+ core::hint::spin_loop();
+ }
+ }
+}
+
+fn hex_digest(out: &mut impl Write, digest: &[u8; 32]) {
+ for byte in digest {
+ let _ = write!(out, "{byte:02x}");
+ }
+}
+
+/// Post-exit: bring up the controller, read the sentinel LBA, and report.
+#[allow(clippy::too_many_arguments)]
+pub fn run(
+ nvme: Option<NvmeLocation>,
+ takeover: Option<DmaTakeover>,
+ screen: &mut Option<Screen>,
+ smmu_ready: bool,
+ smmu_base: Option<u64>,
+ smmu_stream_id: Option<u32>,
+ smmu_events: *const [[u64; 4]; 16],
+) {
+ if aienos_boot::UNSAFE_NVME_DMA_BYPASS {
+ say(screen, UNSAFE_NVME_BANNER);
+ }
+ let Some(at) = nvme else {
+ say(
+ screen,
+ "NVME_DISCOVERY_QEMU: FAIL (no class 0x0108 function)\n",
+ );
+ return;
+ };
+ let mut line = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(
+ line,
+ "NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg={:04x} bus={:02x} device={:02x} function={:02x} bar0={:#x})",
+ at.segment, at.bus, at.device, at.function, at.mmio
+ );
+ say(screen, line.as_str());
+ let Some(takeover) = takeover else {
+ say(
+ screen,
+ "nvme: unavailable (no ECAM window for the controller; DMA not granted)\n",
+ );
+ return;
+ };
+ report_takeover(screen, &takeover);
+ let mut ecam = Ecam(takeover.window);
+ let Some(command) = ecam.command(&at) else {
+ say(screen, "nvme: unavailable (config space unreadable)\n");
+ return;
+ };
+ if dma_gate::bus_master_enabled(command) {
+ say(screen, "nvme: unavailable (bus master would not clear)\n");
+ return;
+ }
+ let grant = match dma_gate::dma_grant(
+ smmu_ready,
+ smmu_base.is_some(),
+ aienos_boot::UNSAFE_NVME_DMA_BYPASS,
+ ) {
+ Ok(grant) => grant,
+ Err(denied) => {
+ let mut msg = aienos_kernel::report::ReportBuf::<200>::new();
+ let _ = writeln!(
+ msg,
+ "dma_gate: nvme denied ({denied:?}), bus master stays off\n\
+ nvme: unavailable (SMMU DMA isolation not active)"
+ );
+ say(screen, msg.as_str());
+ return;
+ }
+ };
+ let dma_mode = match grant {
+ DmaGrant::Confined => {
+ let mut smmu_line = aienos_kernel::report::ReportBuf::<160>::new();
+ let _ = writeln!(
+ smmu_line,
+ "smmu: enabled base={:#x} stream_id={:#x}",
+ smmu_base.unwrap_or(0),
+ smmu_stream_id.unwrap_or(0)
+ );
+ say(screen, smmu_line.as_str());
+ say(screen, "smmu_dma_window: nvme only, translation active\n");
+ "smmu-translated"
+ }
+ DmaGrant::UnsafeBypass => {
+ say(
+ screen,
+ "WARNING: UNSAFE NVME DMA BYPASS ACTIVE: no SMMU on this machine, NVMe DMA \
+ reaches physical memory UNCONFINED (QEMU debug only)\n",
+ );
+ "UNSAFE-identity-no-smmu"
+ }
+ };
+ let mut mode = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(
+ mode,
+ "dma_gate: nvme granted ({grant:?}), bus master on\n\
+ nvme_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}",
+ core::ptr::addr_of!(DMA_ARENA) as usize,
+ ARENA_BYTES
+ );
+ ecam.set_command(&at, dma_gate::with_bus_master(command));
+ say(screen, mode.as_str());
+
+ let registers = NativeRegisters {
+ base: at.mmio as usize,
+ };
+ let dma = NativeDma::new();
+ let mut controller = match NvmeController::init(registers, dma, NativeDelay) {
+ Ok(controller) => controller,
+ Err(error) => {
+ let mut msg = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(msg, "NVME_IDENTIFY_QEMU: FAIL (init {error:?})");
+ say(screen, msg.as_str());
+ revoke_dma(screen, &mut ecam, &at);
+ report_smmu_fault(screen, smmu_base, smmu_stream_id, smmu_events);
+ return;
+ }
+ };
+ let mut identified = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(
+ identified,
+ "NVME_IDENTIFY_QEMU: PASS (vid={:#06x} did={:#06x} nsid=1)",
+ at.vendor, at.device_id
+ );
+ say(screen, identified.as_str());
+
+ let block_count = controller.block_count();
+ let block_size = controller.block_size();
+ let mut geometry = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(
+ geometry,
+ "NVME_GEOMETRY_QEMU: PASS (nsid=1 block_count={block_count} block_size={block_size})"
+ );
+ say(screen, geometry.as_str());
+
+ if let Err(error) = controller.create_io_queues(4) {
+ let mut msg = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(msg, "NVME_READ_QEMU: FAIL (create_io_queues {error:?})");
+ say(screen, msg.as_str());
+ revoke_dma(screen, &mut ecam, &at);
+ return;
+ }
+
+ // Read the sentinel LBA and verify it natively.
+ let mut buffer = [0u8; 512];
+ match controller.read_blocks(SENTINEL_LBA, &mut buffer) {
+ Ok(()) => {
+ let digest = aienos_kernel::crypto::sha256::hash(&buffer);
+ let mut expected = [0u8; 512];
+ for chunk in expected.as_chunks_mut::<16>().0 {
+ chunk.copy_from_slice(SENTINEL_MAGIC);
+ }
+ let mut read_line = aienos_kernel::report::ReportBuf::<320>::new();
+ if buffer == expected {
+ let _ = write!(
+ read_line,
+ "NVME_READ_QEMU: PASS (lba={SENTINEL_LBA} blocks=1 bytes=512 sha256="
+ );
+ hex_digest(&mut read_line, &digest);
+ let _ = writeln!(read_line, ")");
+ } else {
+ let _ = writeln!(
+ read_line,
+ "NVME_READ_QEMU: FAIL (sentinel mismatch at lba {SENTINEL_LBA})"
+ );
+ }
+ say(screen, read_line.as_str());
+ }
+ Err(error) => {
+ let mut msg = aienos_kernel::report::ReportBuf::<256>::new();
+ let _ = writeln!(msg, "NVME_READ_QEMU: FAIL (read {error:?})");
+ say(screen, msg.as_str());
+ }
+ }
+
+ // Bounds: one read past the end must be rejected before any command.
+ let mut bounds = aienos_kernel::report::ReportBuf::<256>::new();
+ match controller.read_blocks(block_count, &mut buffer) {
+ Err(aienos_kernel::block::BlockError::OutOfRange) => {
+ let _ = writeln!(
+ bounds,
+ "NVME_BOUNDS_QEMU: PASS (lba={block_count} rejected OutOfRange no_command)"
+ );
+ }
+ other => {
+ let _ = writeln!(bounds, "NVME_BOUNDS_QEMU: FAIL (got {other:?})");
+ }
+ }
+ say(screen, bounds.as_str());
+
+ // Error path: identify an unallocated namespace must surface a nonzero
+ // completion status rather than being swallowed.
+ let mut error_line = aienos_kernel::report::ReportBuf::<256>::new();
+ match controller.identify_namespace(0xffff_ffff) {
+ Err(NvmeError::CompletionStatus { sct, sc }) => {
+ let _ = writeln!(
+ error_line,
+ "NVME_ERROR_QEMU: PASS (identify nsid=0xffffffff rejected status=nonzero sct={sct} sc={sc})"
+ );
+ }
+ other => {
+ let _ = writeln!(error_line, "NVME_ERROR_QEMU: FAIL (got {other:?})");
+ }
+ }
+ say(screen, error_line.as_str());
+
+ revoke_dma(screen, &mut ecam, &at);
+}
+
+fn report_smmu_fault(
+ screen: &mut Option<Screen>,
+ smmu_base: Option<u64>,
+ smmu_stream_id: Option<u32>,
+ smmu_events: *const [[u64; 4]; 16],
+) {
+ let Some(base) = smmu_base else {
+ return;
+ };
+ let reg = |offset| MmioReg::<u32>::new(base as usize + offset).read();
+ clean_invalidate_dcache_range(smmu_events as usize, core::mem::size_of::<[[u64; 4]; 16]>());
+ let events = unsafe { core::ptr::read_volatile(smmu_events) };
+ let mut fault = aienos_kernel::report::ReportBuf::<512>::new();
+ let _ = writeln!(
+ fault,
+ "smmu_fault: GERROR={:#x} GERRORN={:#x} events={events:016x?}",
+ reg(0x60),
+ reg(0x64)
+ );
+ say(screen, fault.as_str());
+ if let Some(sid) = smmu_stream_id {
+ let table_base = (u64::from(reg(0x84)) << 32 | u64::from(reg(0x80))) & !0x3f;
+ let ste_addr = table_base + u64::from(sid) * 64;
+ let ste0 = unsafe { core::ptr::read_volatile(ste_addr as *const u64) };
+ let ste1 = unsafe { core::ptr::read_volatile((ste_addr + 8) as *const u64) };
+ let mut entry = aienos_kernel::report::ReportBuf::<192>::new();
+ let _ = writeln!(
+ entry,
+ "smmu_ste: base={table_base:#x} sid={sid:#x} addr={ste_addr:#x} words=[{ste0:#x},{ste1:#x}]"
+ );
+ say(screen, entry.as_str());
+ }
+}
diff --git a/crates/aienos-kernel/src/nvme.rs b/crates/aienos-kernel/src/nvme.rs
index 2bd09422 ..7ea33abd 100644
--- a/crates/aienos-kernel/src/nvme.rs
+++ b/crates/aienos-kernel/src/nvme.rs
@@ -40,6 +40,10 @@ impl Cap {
pub const fn timeout_units(self) -> u8 {
((self.0 >> 24) & 0xff) as u8
}
+ /// CAP.MPSMIN: log2 of the minimum memory page size, in 4 KiB units.
+ pub const fn mpsmin(self) -> u8 {
+ ((self.0 >> 48) & 0xf) as u8
+ }
}
pub const fn doorbell_offset(qid: u16, completion: bool, stride: u32) -> u32 {
@@ -274,7 +278,11 @@ pub fn build_prps(
if pages == 1 {
return Ok((address, 0, 0));
}
- let second = (address & !((page_size as u64) - 1)) + page_size as u64;
+ // The second data page starts at the next page boundary after `address`.
+ // A near-`u64::MAX` address must be rejected, not wrapped or panicked.
+ let second = (address & !((page_size as u64) - 1))
+ .checked_add(page_size as u64)
+ .ok_or(PrpError::Invalid)?;
if pages == 2 {
return Ok((address, second, 0));
}
@@ -292,9 +300,15 @@ pub fn build_prps(
let entry = list.get_mut(slot).ok_or(PrpError::ListTooSmall)?;
let last_in_page = slot % per_page == per_page - 1;
if last_in_page && count - data > 1 {
- *entry = list_address + ((slot / per_page + 1) * page_size) as u64;
+ let offset = (slot / per_page + 1)
+ .checked_mul(page_size)
+ .ok_or(PrpError::Invalid)?;
+ *entry = list_address
+ .checked_add(offset as u64)
+ .ok_or(PrpError::Invalid)?;
} else {
- *entry = second + (data * page_size) as u64;
+ let offset = data.checked_mul(page_size).ok_or(PrpError::Invalid)?;
+ *entry = second.checked_add(offset as u64).ok_or(PrpError::Invalid)?;
data += 1;
}
slot += 1;
diff --git a/crates/aienos-kernel/src/nvme/driver.rs b/crates/aienos-kernel/src/nvme/driver.rs
index 55445d47 ..c5894dc0 100644
--- a/crates/aienos-kernel/src/nvme/driver.rs
+++ b/crates/aienos-kernel/src/nvme/driver.rs
@@ -49,9 +49,16 @@ pub enum NvmeError {
Controller(ControllerError),
Dma,
Timeout,
- CompletionStatus { sct: u8, sc: u8 },
+ CompletionStatus {
+ sct: u8,
+ sc: u8,
+ },
InvalidIdentify,
InvalidQueueDepth,
+ /// The controller needs a memory page size larger than the 4 KiB the
+ /// driver programs into CC.MPS (CAP.MPSMIN != 0), or another base
+ /// property this read substrate does not support.
+ UnsupportedController,
}
/// A zeroed, physically contiguous DMA allocation and its CPU byte view.
@@ -105,6 +112,12 @@ impl<R: Registers, D: DmaMemory, T: Delay> NvmeController<R, D, T> {
/// Reset and enable the controller. Ready waits honour CAP.TO (500 ms units).
pub fn init(mut registers: R, mut dma: D, mut delay: T) -> Result<Self, NvmeError> {
let cap = Cap(((registers.read32(4) as u64) << 32) | registers.read32(0) as u64);
+ // The driver programs CC.MPS for a 4 KiB memory page (CC_MPS_4K) and
+ // builds 4 KiB queues, so a controller that demands a larger minimum
+ // page size is refused rather than mis-programmed.
+ if cap.mpsmin() != 0 {
+ return Err(NvmeError::UnsupportedController);
+ }
let timeout_ms = u32::from(cap.timeout_units().max(1)) * 500;
let cc = registers.read32(REG_CC);
registers.write32(REG_CC, cc & !CC_EN);
@@ -159,7 +172,9 @@ impl<R: Registers, D: DmaMemory, T: Delay> NvmeController<R, D, T> {
let lbads = *bytes
.get(descriptor + 2)
.ok_or(NvmeError::InvalidIdentify)?;
- if block_count == 0 || lbads >= 32 {
+ // NVMe LBA sizes are 512 bytes (lbads 9) through 2^31; anything smaller
+ // is not a valid data block size.
+ if block_count == 0 || !(9..=31).contains(&lbads) {
return Err(NvmeError::InvalidIdentify);
}
let info = NamespaceInfo {
@@ -172,7 +187,9 @@ impl<R: Registers, D: DmaMemory, T: Delay> NvmeController<R, D, T> {
/// Create polled I/O completion and submission queues, both with QID 1.
pub fn create_io_queues(&mut self, depth: u16) -> Result<(), NvmeError> {
- if depth < 2 {
+ // NVMe requires at least 2 entries, and the queue may not exceed the
+ // controller's advertised maximum (CAP.MQES + 1).
+ if depth < 2 || depth > self.cap.mqes() {
return Err(NvmeError::InvalidQueueDepth);
}
let size = usize::from(depth).checked_mul(16).ok_or(NvmeError::Dma)?;
@@ -496,12 +513,16 @@ mod tests {
io_cq_tail: usize,
io_sq_tail: usize,
io_phase: bool,
+ /// CAP high dword (offset 4). Bits 16..20 carry CAP.MPSMIN.
+ cap_high: u32,
+ /// LBA data size (lbads) the fake reports for namespace 1.
+ lbads: u8,
}
impl Registers for FakeRegs {
fn read32(&mut self, offset: u32) -> u32 {
match offset {
0 => 0x0100_03ff, // CAP.TO = 1 (500 ms), MQES = 1023
- 4 => 0,
+ 4 => self.cap_high,
REG_CC => self.cc,
REG_CSTS => {
if self.ready_after_reads > 0 && self.cc & CC_EN != 0 {
@@ -577,7 +598,7 @@ mod tests {
if cns == 0 {
data[0..8].copy_from_slice(&self.namespace_size.to_le_bytes());
data[26] = 0;
- data[130] = 9;
+ data[130] = self.lbads;
}
}
0x05 => {
@@ -750,6 +771,8 @@ mod tests {
io_cq_tail: 0,
io_sq_tail: 0,
io_phase: true,
+ cap_high: 0,
+ lbads: 9,
},
FakeDma {
shared,
@@ -974,4 +997,37 @@ mod tests {
Err(NvmeError::CompletionStatus { sc: 1, .. })
));
}
+
+ #[test]
+ fn controller_requiring_larger_pages_is_refused() {
+ let (mut regs, dma) = fixture();
+ // CAP.MPSMIN = 1 means the controller needs 8 KiB pages; the driver
+ // only programs 4 KiB.
+ regs.cap_high = 1 << 16;
+ assert_eq!(
+ NvmeController::init(regs, dma, CountingDelay::default()).err(),
+ Some(NvmeError::UnsupportedController)
+ );
+ }
+
+ #[test]
+ fn io_queue_depth_above_mqes_is_rejected() {
+ let (regs, dma) = fixture();
+ let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
+ // CAP.MQES + 1 = 1024 in the fixture.
+ assert_eq!(
+ controller.create_io_queues(1025),
+ Err(NvmeError::InvalidQueueDepth)
+ );
+ }
+
+ #[test]
+ fn lbads_below_512_is_invalid_identify() {
+ let (mut regs, dma) = fixture();
+ regs.lbads = 8;
+ assert_eq!(
+ NvmeController::init(regs, dma, CountingDelay::default()).err(),
+ Some(NvmeError::InvalidIdentify)
+ );
+ }
}
diff --git a/crates/aienos-kernel/tests/nvme_completion.rs b/crates/aienos-kernel/tests/nvme_completion.rs
new file mode 100644
index 00000000 ..9fd2b3f0
--- /dev/null
+++ b/crates/aienos-kernel/tests/nvme_completion.rs
@@ -0,0 +1,619 @@
+//! External integration tests for the polled NVMe completion/error path.
+//!
+//! Target: `crates/aienos-kernel/tests/nvme_completion.rs`.
+//!
+//! Uses only the public `aienos_kernel::nvme` and
+//! `aienos_kernel::nvme::driver` API plus our own `Registers`, `DmaMemory`
+//! and `Delay` fakes. The device fake is programmable: it can echo a wrong
+//! command id, park a stale-phase completion ahead of the real one, return
+//! crafted status words, never complete, or fault/never-ready the controller.
+
+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, Completion, CompletionQueue, ControllerError, Registers, Submission, CSTS_CFS,
+ 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;
+const POLLS: u64 = 1_001; // driver loops `0..=1000`
+
+type Shared = Rc<RefCell<Device>>;
+
+// ---------------------------------------------------------------------------
+// Programmable device model
+// ---------------------------------------------------------------------------
+
+#[derive(Clone, Default)]
+struct Behavior {
+ /// Raw status bits (SC/SCT/DNR) ORed with the phase bit before delivery.
+ admin_raw_status: Option<u16>,
+ /// Added to the echoed CID; nonzero forces a command-id mismatch.
+ admin_cid_delta: i32,
+ /// Emit this many stale-phase completions before the real one.
+ admin_stale_reads: u32,
+ /// If true, never place an admin completion (driver must bound its poll).
+ admin_never_complete: bool,
+ io_raw_status: Option<u16>,
+ io_cid_delta: i32,
+ io_stale_reads: u32,
+ io_never_complete: bool,
+}
+
+struct Region {
+ base: u64,
+ len: usize,
+ bytes: Vec<u8>,
+}
+
+struct Device {
+ regions: Vec<Region>,
+ next_phys: u64,
+ cc: u32,
+ csts: u32,
+ fatal_on_enable: bool,
+ never_ready: bool,
+ asq: u64,
+ acq: u64,
+ admin_cq_base: Option<u64>,
+ admin_cq_len: usize,
+ io_sq_base: Option<u64>,
+ io_cq_base: Option<u64>,
+ 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]>,
+ admin_commands: u64,
+ io_commands: u64,
+ behavior: Behavior,
+}
+
+impl Device {
+ fn new() -> Self {
+ Self {
+ regions: Vec::new(),
+ next_phys: 0x1000,
+ cc: 0,
+ csts: 0,
+ fatal_on_enable: false,
+ never_ready: false,
+ 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(),
+ admin_commands: 0,
+ io_commands: 0,
+ 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<usize> {
+ 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) {
+ let idx = self.find_region(prp, PAGE);
+ if let Some(i) = idx {
+ let bytes = &mut self.regions[i].bytes;
+ if cns == 1 {
+ bytes[77] = 0; // MDTS = 0
+ } 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 => {
+ self.io_cq_base = Some(p1);
+ self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1;
+ }
+ 0x01 => self.io_sq_base = Some(p1),
+ _ => {}
+ }
+ self.admin_commands += 1;
+ if !self.behavior.admin_never_complete {
+ let echo = if self.behavior.admin_cid_delta == 0 {
+ cid
+ } else {
+ cid.wrapping_add(self.behavior.admin_cid_delta as u16)
+ };
+ let mut stale = self.behavior.admin_stale_reads;
+ while stale > 0 {
+ let phase = !self.admin_phase;
+ self.push_admin(phase, cid, 0);
+ stale -= 1;
+ }
+ let raw = self.behavior.admin_raw_status.unwrap_or(0);
+ let phase = self.admin_phase;
+ self.push_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 cid = u16::from_le_bytes([cmd[2], cmd[3]]);
+ self.io_commands += 1;
+ if !self.behavior.io_never_complete {
+ let echo = if self.behavior.io_cid_delta == 0 {
+ cid
+ } else {
+ cid.wrapping_add(self.behavior.io_cid_delta as u16)
+ };
+ let mut stale = self.behavior.io_stale_reads;
+ while stale > 0 {
+ let phase = !self.io_phase;
+ self.push_io(phase, cid, 0);
+ stale -= 1;
+ }
+ let raw = self.behavior.io_raw_status.unwrap_or(0);
+ let phase = self.io_phase;
+ self.push_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 if self.fatal_on_enable {
+ CSTS_CFS
+ } else if self.never_ready {
+ 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<DmaRegion, NvmeError> {
+ 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<RefCell<u64>>,
+}
+
+impl Delay for CountingDelay {
+ fn delay_us(&mut self, us: u32) {
+ *self.waited_us.borrow_mut() += u64::from(us);
+ }
+}
+
+type Controller = NvmeController<FakeRegs, FakeDma, CountingDelay>;
+
+/// Build a controller that completes its initialization normally.
+fn make_controller() -> (Controller, Shared, Rc<RefCell<u64>>) {
+ 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 admin_command_id_mismatch_reports_invalid_identify() {
+ let (mut controller, shared, _) = make_controller();
+ shared.borrow_mut().behavior.admin_cid_delta = 1;
+ assert_eq!(
+ controller.identify_controller(),
+ Err(NvmeError::InvalidIdentify)
+ );
+}
+
+#[test]
+fn io_command_id_mismatch_reports_device_error() {
+ let (mut controller, shared, _) = make_controller();
+ controller.create_io_queues(4).unwrap();
+ shared.borrow_mut().behavior.io_cid_delta = 1;
+ let mut buffer = [0u8; 512];
+ assert_eq!(
+ controller.read_blocks(0, &mut buffer),
+ Err(BlockError::DeviceError)
+ );
+}
+
+#[test]
+fn stale_phase_completion_is_skipped_and_matching_one_consumed() {
+ let (mut controller, shared, waited) = make_controller();
+ shared.borrow_mut().behavior.admin_stale_reads = 1;
+ let before = *waited.borrow();
+ controller.identify_controller().unwrap();
+ // Exactly one backoff: the stale entry was skipped, the real one consumed.
+ assert_eq!(*waited.borrow() - before, 1_000);
+ let device = shared.borrow();
+ assert!(device.admin_queue.is_empty());
+ assert_eq!(device.admin_commands, 3); // two during init + this one
+ assert!(device.admin_phase);
+}
+
+#[test]
+fn admin_cq_phase_flips_when_head_wraps_at_depth_eight() {
+ let (mut controller, shared, _) = make_controller();
+ for _ in 0..6 {
+ controller.identify_controller().unwrap();
+ }
+ {
+ let device = shared.borrow();
+ assert_eq!(device.admin_commands, 8);
+ assert_eq!(device.admin_cq_tail, 0);
+ assert!(!device.admin_phase, "phase must flip once the head wraps");
+ }
+ // The 9th command only completes if the driver tracked the same flip.
+ controller.identify_controller().unwrap();
+ let device = shared.borrow();
+ assert_eq!(device.admin_commands, 9);
+ assert!(!device.admin_phase);
+}
+
+#[test]
+fn admin_timeout_is_bounded_no_infinite_loop() {
+ let (mut controller, shared, waited) = make_controller();
+ shared.borrow_mut().behavior.admin_never_complete = true;
+ let before = *waited.borrow();
+ assert_eq!(controller.identify_controller(), Err(NvmeError::Timeout));
+ assert_eq!(*waited.borrow() - before, POLLS * 1_000);
+}
+
+#[test]
+fn io_timeout_is_bounded_no_infinite_loop() {
+ let (mut controller, shared, waited) = make_controller();
+ controller.create_io_queues(4).unwrap();
+ shared.borrow_mut().behavior.io_never_complete = true;
+ let before = *waited.borrow();
+ let mut buffer = [0u8; 512];
+ assert_eq!(
+ controller.read_blocks(0, &mut buffer),
+ Err(BlockError::Timeout)
+ );
+ assert_eq!(*waited.borrow() - before, POLLS * 1_000);
+}
+
+#[test]
+fn controller_fatal_status_maps_to_controller_failed() {
+ let shared: Shared = Rc::new(RefCell::new(Device::new()));
+ shared.borrow_mut().fatal_on_enable = true;
+ let regs = FakeRegs {
+ shared: shared.clone(),
+ };
+ let dma = FakeDma {
+ shared: shared.clone(),
+ };
+ let result = NvmeController::init(regs, dma, CountingDelay::default());
+ assert_eq!(
+ result.err(),
+ Some(NvmeError::Controller(ControllerError::Failed))
+ );
+}
+
+#[test]
+fn controller_never_ready_maps_to_controller_timeout() {
+ let shared: Shared = Rc::new(RefCell::new(Device::new()));
+ shared.borrow_mut().never_ready = true;
+ let regs = FakeRegs {
+ shared: shared.clone(),
+ };
+ let dma = FakeDma {
+ shared: shared.clone(),
+ };
+ let result = NvmeController::init(regs, dma, CountingDelay::default());
+ assert_eq!(
+ result.err(),
+ Some(NvmeError::Controller(ControllerError::Timeout))
+ );
+}
+
+#[test]
+fn admin_status_word_decodes_exact_sc_and_sct() {
+ // status word 0x0002 -> status >> 1 = 1 -> sc 1, sct 0.
+ let (mut controller, shared, _) = make_controller();
+ shared.borrow_mut().behavior.admin_raw_status = Some(0x0002);
+ assert_eq!(
+ controller.identify_namespace(1),
+ Err(NvmeError::CompletionStatus { sct: 0, sc: 1 })
+ );
+
+ // 0x2804 style: 0x2804 >> 1 = 0x1402 -> sc 2, sct (0x1402 >> 8) & 7 = 4.
+ let (mut controller, shared, _) = make_controller();
+ shared.borrow_mut().behavior.admin_raw_status = Some(0x2804);
+ assert_eq!(
+ controller.identify_namespace(1),
+ Err(NvmeError::CompletionStatus { sct: 4, sc: 2 })
+ );
+}
+
+#[test]
+fn io_nonzero_status_maps_to_device_error() {
+ let (mut controller, shared, _) = make_controller();
+ controller.create_io_queues(4).unwrap();
+ shared.borrow_mut().behavior.io_raw_status = Some(0x0002);
+ let mut buffer = [0u8; 512];
+ assert_eq!(
+ controller.read_blocks(0, &mut buffer),
+ Err(BlockError::DeviceError)
+ );
+}
+
+#[test]
+fn malformed_completions_do_not_panic() {
+ // Garbage status word: 0xffff -> sc 0xff, sct 7. Must decode, not panic.
+ let (mut controller, shared, _) = make_controller();
+ shared.borrow_mut().behavior.admin_raw_status = Some(0xffff);
+ assert_eq!(
+ controller.identify_namespace(1),
+ Err(NvmeError::CompletionStatus { sct: 7, sc: 0xff })
+ );
+
+ // All-zero CQE has phase 0, which mismatches the live phase, so it is
+ // ignored until the poll budget runs out.
+ let (mut controller, shared, _) = make_controller();
+ shared.borrow_mut().behavior.admin_never_complete = true;
+ assert_eq!(controller.identify_controller(), Err(NvmeError::Timeout));
+}
+
+#[test]
+fn io_cq_wraparound_consumes_completions_in_order() {
+ let (mut controller, shared, _) = make_controller();
+ controller.create_io_queues(4).unwrap();
+ for lba in 0..4u64 {
+ let mut buffer = [0u8; 512];
+ controller.read_blocks(lba, &mut buffer).unwrap();
+ }
+ {
+ let device = shared.borrow();
+ assert_eq!(device.io_cq_tail, 0);
+ assert!(!device.io_phase, "I/O CQ phase must flip at depth 4");
+ assert_eq!(device.io_commands, 4);
+ }
+ // A fifth transfer only succeeds if the driver flipped in lockstep.
+ let mut buffer = [0u8; 512];
+ controller.read_blocks(4, &mut buffer).unwrap();
+ let device = shared.borrow();
+ assert_eq!(device.io_commands, 5);
+ assert!(device.io_queue.is_empty());
+}
+
+#[test]
+fn completion_accessors_decode_little_endian_fields() {
+ let mut raw = [0u8; 16];
+ raw[0..4].copy_from_slice(&0x1122_3344u32.to_le_bytes());
+ raw[8..10].copy_from_slice(&0x5566u16.to_le_bytes());
+ raw[10..12].copy_from_slice(&0x7788u16.to_le_bytes());
+ raw[12..14].copy_from_slice(&0x99aau16.to_le_bytes());
+ raw[14..16].copy_from_slice(&0x0003u16.to_le_bytes());
+ let cqe = Completion(raw);
+ assert_eq!(cqe.result(), 0x1122_3344);
+ assert_eq!(cqe.sq_head(), 0x5566);
+ assert_eq!(cqe.sq_id(), 0x7788);
+ assert_eq!(cqe.command_id(), 0x99aa);
+ assert_eq!(cqe.status(), 0x0003);
+ assert!(cqe.phase());
+}
+
+#[test]
+fn completion_queue_phase_flips_at_depth_eight() {
+ let mut mem = vec![Completion([0u8; 16]); 8];
+ for entry in &mut mem {
+ entry.0[14..16].copy_from_slice(&1u16.to_le_bytes());
+ }
+ let mut queue = CompletionQueue::new(&mem);
+ for _ in 0..8 {
+ assert!(queue.poll().is_some());
+ }
+ assert_eq!(queue.head(), 0);
+ assert!(!queue.phase());
+ assert!(queue.poll().is_none());
+}
+
+// Keep Submission in scope for device-model fidelity and to document the
+// layouts the fake parses (opcode/CID/PRP dwords).
+#[allow(dead_code)]
+fn submission_layout_probe() -> Submission {
+ Submission::identify_controller(0)
+}
diff --git a/crates/aienos-kernel/tests/nvme_identify.rs b/crates/aienos-kernel/tests/nvme_identify.rs
new file mode 100644
index 00000000 ..bff58da5
--- /dev/null
+++ b/crates/aienos-kernel/tests/nvme_identify.rs
@@ -0,0 +1,449 @@
+//! Oracle D2: NVMe Identify (CNS=1 controller, CNS=0 namespace) integration tests.
+//!
+//! Self-contained external test crate. It implements its own `Registers`,
+//! `DmaMemory`, and `Delay` fakes (OracleRegs/OracleDma/OracleDelay) that model
+//! an in-memory controller answering admin Identify commands by writing the
+//! 4096-byte identify payload into the PRP1 buffer. No hardware, no sleeps.
+
+use std::cell::RefCell;
+use std::collections::BTreeMap;
+use std::rc::Rc;
+
+use aienos_kernel::block::BlockDevice;
+use aienos_kernel::nvme::driver::{
+ Delay, DmaMemory, DmaRegion, NamespaceInfo, NvmeController, NvmeError,
+};
+use aienos_kernel::nvme::{Registers, CC_EN, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS};
+
+const ADMIN_DEPTH: usize = 8;
+const IO_DEPTH: usize = 8;
+
+// Doorbell offsets for CAP.DSTRD = 0 (stride 4): doorbell_offset() yields these.
+const ADMIN_SQ_DB: u32 = 0x1000; // qid 0, submission
+const IO_SQ_DB: u32 = 0x1008; // qid 1, submission
+
+type Store = Rc<RefCell<BTreeMap<u64, Vec<u8>>>>;
+
+// ---------------------------------------------------------------------------
+// DMA fake: page-aligned bump allocator over a shared physical->bytes map.
+// ---------------------------------------------------------------------------
+
+struct OracleDma {
+ store: Store,
+ next: u64,
+}
+
+impl DmaMemory for OracleDma {
+ fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
+ let mask = alignment as u64 - 1;
+ let physical = (self.next + mask) & !mask;
+ self.next = physical + size as u64;
+ self.store.borrow_mut().insert(physical, vec![0; size]);
+ Ok(DmaRegion {
+ physical,
+ bytes: vec![0; size],
+ })
+ }
+
+ fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
+ let store = self.store.borrow();
+ let (base, bytes) = store.range(..=physical).next_back().ok_or(NvmeError::Dma)?;
+ let offset = (physical - base) as usize;
+ output.copy_from_slice(
+ bytes
+ .get(offset..offset + output.len())
+ .ok_or(NvmeError::Dma)?,
+ );
+ Ok(())
+ }
+
+ fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
+ let mut store = self.store.borrow_mut();
+ let (base, bytes) = store
+ .range_mut(..=physical)
+ .next_back()
+ .ok_or(NvmeError::Dma)?;
+ let offset = (physical - *base) as usize;
+ bytes
+ .get_mut(offset..offset + input.len())
+ .ok_or(NvmeError::Dma)?
+ .copy_from_slice(input);
+ Ok(())
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Registers fake: executes admin/IO commands when the matching doorbell is rung.
+// ---------------------------------------------------------------------------
+
+struct OracleRegs {
+ store: Store,
+ cc: u32,
+ writes: Vec<(u32, u32)>,
+
+ // Canned Identify responses.
+ namespace_size: u64,
+ flbas: u8,
+ lbads: u8,
+ mdts: u8,
+ nsid_zero_error: bool,
+
+ 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,
+}
+
+impl Registers for OracleRegs {
+ fn read32(&mut self, offset: u32) -> u32 {
+ match offset {
+ 0 => 0x0100_03ff, // CAP.TO = 1 (500 ms units), DSTRD = 0, MQES = 1023
+ 4 => 0,
+ REG_CC => self.cc,
+ REG_CSTS if self.cc & CC_EN != 0 => CSTS_RDY,
+ REG_CSTS => 0,
+ _ => 0,
+ }
+ }
+
+ fn write32(&mut self, offset: u32, value: u32) {
+ self.writes.push((offset, value));
+
+ match offset {
+ REG_CC => self.cc = value,
+ REG_ASQ => self.admin_sq = (self.admin_sq & !0xffff_ffff) | value as u64,
+ x if x == REG_ASQ + 4 => {
+ self.admin_sq = (self.admin_sq & 0xffff_ffff) | ((value as u64) << 32)
+ }
+ REG_ACQ => self.admin_cq = (self.admin_cq & !0xffff_ffff) | value as u64,
+ x if x == REG_ACQ + 4 => {
+ self.admin_cq = (self.admin_cq & 0xffff_ffff) | ((value as u64) << 32)
+ }
+ _ => {}
+ }
+
+ if offset == ADMIN_SQ_DB {
+ self.run_admin();
+ } else if offset == IO_SQ_DB {
+ self.run_io();
+ }
+ }
+}
+
+impl OracleRegs {
+ fn run_admin(&mut self) {
+ let admin_sq = self.admin_sq;
+ let admin_cq = self.admin_cq;
+ let mut memory = self.store.borrow_mut();
+
+ let at = self.admin_sq_tail * 64;
+ let command = memory
+ .get(&admin_sq)
+ .expect("admin SQ allocated")
+ .get(at..at + 64)
+ .expect("admin SQE in range")
+ .to_vec();
+
+ let opcode = command[0];
+ let cid = u16::from_le_bytes(command[2..4].try_into().unwrap());
+ let nsid = u32::from_le_bytes(command[4..8].try_into().unwrap());
+ let prp = u64::from_le_bytes(command[24..32].try_into().unwrap());
+ let cdw10 = u32::from_le_bytes(command[40..44].try_into().unwrap());
+ let cdw11 = u32::from_le_bytes(command[44..48].try_into().unwrap());
+
+ self.command_error = 0;
+
+ match opcode {
+ 0x06 => {
+ // Identify: CNS in cdw10; answer into the PRP1 buffer.
+ let cns = cdw10;
+ let data = memory.get_mut(&prp).expect("identify buffer allocated");
+ data.fill(0);
+ if cns == 1 {
+ data[77] = self.mdts;
+ } else if self.nsid_zero_error && nsid == 0 {
+ self.command_error = 1 << 1;
+ } else {
+ data[0..8].copy_from_slice(&self.namespace_size.to_le_bytes());
+ // Descriptor 0 decoy: must be ignored when FLBAS selects another.
+ data[130] = 9;
+ let flbas = (self.flbas & 0x0f) as usize;
+ data[26] = flbas as u8;
+ let descriptor = 128 + flbas * 4;
+ data[descriptor + 2] = self.lbads;
+ }
+ }
+ 0x05 => {
+ // Create I/O CQ: remember buffer + depth (QID 1).
+ self.io_cq = prp;
+ self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1;
+ }
+ 0x01 if cdw10 & 0xffff == 1 && cdw11 & 0xffff == 1 => {
+ // Create I/O SQ: remember buffer (QID 1).
+ self.io_sq = prp;
+ }
+ _ => {}
+ }
+
+ {
+ let cqe = memory.get_mut(&admin_cq).expect("admin CQ allocated");
+ let at = self.admin_cq_tail * 16;
+ cqe[at + 12..at + 14].copy_from_slice(&cid.to_le_bytes());
+ cqe[at + 14..at + 16]
+ .copy_from_slice(&((self.admin_phase as u16) | self.command_error).to_le_bytes());
+ }
+ 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 io_sq = self.io_sq;
+ let io_cq = self.io_cq;
+ let mut memory = self.store.borrow_mut();
+
+ let at = self.io_sq_tail * 64;
+ let command = memory
+ .get(&io_sq)
+ .expect("I/O SQ allocated")
+ .get(at..at + 64)
+ .expect("I/O SQE in range")
+ .to_vec();
+ let cid = u16::from_le_bytes(command[2..4].try_into().unwrap());
+
+ self.command_error = 0;
+
+ let cqe = memory.get_mut(&io_cq).expect("I/O CQ allocated");
+ let cq_at = self.io_cq_tail * 16;
+ cqe[cq_at + 12..cq_at + 14].copy_from_slice(&cid.to_le_bytes());
+ cqe[cq_at + 14..cq_at + 16]
+ .copy_from_slice(&((self.io_phase as u16) | self.command_error).to_le_bytes());
+
+ self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth;
+ if self.io_cq_tail == 0 {
+ self.io_phase = !self.io_phase;
+ }
+ self.io_sq_tail = (self.io_sq_tail + 1) % self.io_depth;
+ }
+}
+
+#[derive(Default)]
+struct OracleDelay {
+ waited_us: u64,
+}
+
+impl Delay for OracleDelay {
+ fn delay_us(&mut self, us: u32) {
+ self.waited_us += u64::from(us);
+ }
+}
+
+fn oracle(namespace_size: u64) -> (OracleRegs, OracleDma) {
+ let store: Store = Rc::new(RefCell::new(BTreeMap::new()));
+ (
+ OracleRegs {
+ store: store.clone(),
+ cc: 0,
+ writes: Vec::new(),
+ namespace_size,
+ flbas: 0,
+ lbads: 9,
+ mdts: 0,
+ nsid_zero_error: false,
+ 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: IO_DEPTH,
+ },
+ OracleDma {
+ store,
+ next: 0x1000,
+ },
+ )
+}
+
+type Ctrl = NvmeController<OracleRegs, OracleDma, OracleDelay>;
+
+fn io_submissions(c: &Ctrl) -> usize {
+ c.registers
+ .writes
+ .iter()
+ .filter(|(offset, _)| *offset == IO_SQ_DB)
+ .count()
+}
+
+// ---------------------------------------------------------------------------
+// MDTS (Identify Controller, CNS=1): observable via transfer chunk count.
+// MDTS is not publicly readable, so byte 77 is asserted through chunking.
+// ---------------------------------------------------------------------------
+
+#[test]
+fn mdts_byte_77_controls_transfer_chunking() {
+ // MDTS = 0 -> 128 KiB cap -> a 32 KiB write is one command.
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ c.create_io_queues(IO_DEPTH as u16).unwrap();
+ let data = vec![0u8; 32 * 1024];
+ c.write_blocks(0, &data).unwrap();
+ assert_eq!(
+ io_submissions(&c),
+ 1,
+ "MDTS=0 should allow one 32 KiB command"
+ );
+
+ // MDTS = 1 -> PAGE_SIZE << 1 = 8 KiB per command -> four commands.
+ let (mut regs, dma) = oracle(12345);
+ regs.mdts = 1;
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ c.create_io_queues(IO_DEPTH as u16).unwrap();
+ c.write_blocks(0, &data).unwrap();
+ assert_eq!(
+ io_submissions(&c),
+ 4,
+ "MDTS=1 should split 32 KiB into 8 KiB chunks"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Capacity round-trip after init (init runs Identify Controller then Namespace).
+// ---------------------------------------------------------------------------
+
+#[test]
+fn init_identifies_namespace_and_capacity_round_trips() {
+ let (regs, dma) = oracle(4096);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ assert_eq!(
+ c.identify_namespace(1).unwrap(),
+ NamespaceInfo {
+ block_count: 4096,
+ block_size: 512,
+ }
+ );
+ assert_eq!(c.block_count(), 4096, "BlockDevice capacity after init");
+ assert_eq!(c.block_size(), 512);
+}
+
+// ---------------------------------------------------------------------------
+// Invalid namespace geometries.
+// ---------------------------------------------------------------------------
+
+#[test]
+fn zero_block_count_is_invalid_identify() {
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ c.registers.namespace_size = 0;
+ assert_eq!(c.identify_namespace(1), Err(NvmeError::InvalidIdentify));
+}
+
+#[test]
+fn lbads_at_or_above_32_is_invalid_identify() {
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ for bad in [32u8, 33, 64, 255] {
+ c.registers.lbads = bad;
+ assert_eq!(
+ c.identify_namespace(1),
+ Err(NvmeError::InvalidIdentify),
+ "lbads {bad} must be rejected"
+ );
+ }
+}
+
+#[test]
+fn lbads_9_and_12_map_to_block_sizes() {
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+
+ c.registers.lbads = 9;
+ assert_eq!(c.identify_namespace(1).unwrap().block_size, 512);
+
+ c.registers.lbads = 12;
+ assert_eq!(c.identify_namespace(1).unwrap().block_size, 4096);
+}
+
+// ---------------------------------------------------------------------------
+// FLBAS selects a nonzero LBA-format descriptor.
+// ---------------------------------------------------------------------------
+
+#[test]
+fn nonzero_flbas_selects_its_own_descriptor() {
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+
+ // Descriptor 0 is a decoy (lbads 9 -> 512). Selecting index 2 with lbads 12
+ // must yield 4096, proving descriptor 128 + flbas*4 + 2 is read.
+ c.registers.flbas = 2;
+ c.registers.lbads = 12;
+ assert_eq!(
+ c.identify_namespace(1).unwrap(),
+ NamespaceInfo {
+ block_count: 12345,
+ block_size: 4096,
+ }
+ );
+
+ // Back to descriptor 0.
+ c.registers.flbas = 0;
+ c.registers.lbads = 9;
+ assert_eq!(c.identify_namespace(1).unwrap().block_size, 512);
+}
+
+#[test]
+fn maximum_flbas_descriptor_offset_stays_in_bounds() {
+ // FLBAS is masked with 0x0f, so the largest descriptor is 128 + 15*4 + 2 = 190,
+ // always inside the 4096-byte identify buffer. Assert the boundary is safe.
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ c.registers.flbas = 0xff; // low nibble 15
+ c.registers.lbads = 12;
+ assert_eq!(c.identify_namespace(1).unwrap().block_size, 4096);
+}
+
+// ---------------------------------------------------------------------------
+// Unsupported geometry must not panic.
+// ---------------------------------------------------------------------------
+
+#[test]
+fn nsid_zero_identify_does_not_panic() {
+ let (regs, dma) = oracle(12345);
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+
+ // NSID 0 is not a valid target namespace; surface an error, never panic.
+ c.registers.nsid_zero_error = true;
+ assert!(matches!(
+ c.identify_namespace(0),
+ Err(NvmeError::CompletionStatus { sc: 1, .. })
+ ));
+}
+
+#[test]
+fn mdts_255_shift_does_not_panic() {
+ // MDTS = 255 would make PAGE_SIZE.checked_shl(255) overflow; the driver must
+ // fall back (128 KiB) and complete the transfer without panicking.
+ let (mut regs, dma) = oracle(12345);
+ regs.mdts = 255;
+ let mut c: Ctrl = NvmeController::init(regs, dma, OracleDelay::default()).unwrap();
+ c.create_io_queues(IO_DEPTH as u16).unwrap();
+ let mut buffer = vec![0u8; 512];
+ c.read_blocks(0, &mut buffer).unwrap();
+}
diff --git a/crates/aienos-kernel/tests/nvme_prp.rs b/crates/aienos-kernel/tests/nvme_prp.rs
new file mode 100644
index 00000000 ..bea048f5
--- /dev/null
+++ b/crates/aienos-kernel/tests/nvme_prp.rs
@@ -0,0 +1,308 @@
+//! D3 adversarial PRP tests for the AIENOS P3 native NVMe read substrate.
+//!
+//! External integration test crate. Baseline: aien-dev/aienos @ ff5de9c .
+//! Exercises `aienos_kernel::nvme::build_prps` against the documented PRP
+//! contract with exact expected values, including boundary, overflow, list
+//! chaining, and 64 KiB page geometry.
+
+use aienos_kernel::nvme::{build_prps, PrpError};
+
+const P4K: usize = 4096;
+const P64K: usize = 65536;
+
+#[test]
+fn invalid_zero_length_and_page_size() {
+ assert_eq!(
+ build_prps(0x1000, 0, P4K, 0x8000, &mut [0u64; 4]),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0x1000, 100, 0, 0x8000, &mut [0u64; 4]),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0, usize::MAX, 0, 0, &mut [0u64; 4]),
+ Err(PrpError::Invalid)
+ );
+}
+
+#[test]
+fn invalid_non_power_of_two_page_size() {
+ for ps in [3usize, 1000, 3000, 4097, 8191] {
+ let mut list = [0u64; 4];
+ assert_eq!(
+ build_prps(0x1000, 100, ps, 0x8000, &mut list),
+ Err(PrpError::Invalid),
+ "page_size {ps} must be rejected"
+ );
+ }
+}
+
+#[test]
+fn offset_plus_length_overflow_is_invalid() {
+ let mut list = [0u64; 4];
+ assert_eq!(
+ build_prps(usize::MAX as u64, usize::MAX, P4K, 0x8000, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(1, usize::MAX, P4K, 0x8000, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0, usize::MAX, P4K, 0x8000, &mut list),
+ Err(PrpError::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.
+ let outcome = std::panic::catch_unwind(|| {
+ let mut list = [0u64; 0];
+ build_prps(usize::MAX as u64, 2, P4K, 0, &mut list)
+ });
+ match outcome {
+ Ok(result) => assert_eq!(
+ result,
+ Err(PrpError::Invalid),
+ "address=usize::MAX length=2 must be Invalid, got {result:?}"
+ ),
+ Err(_) => {
+ panic!("address=usize::MAX length=2 panicked; expected Err(Invalid) with no panic")
+ }
+ }
+}
+
+#[test]
+fn single_page_aligned_and_unaligned() {
+ let mut list = [0u64; 0];
+ assert_eq!(
+ build_prps(0x1000, P4K, P4K, 0x8000, &mut list).unwrap(),
+ (0x1000, 0, 0)
+ );
+ assert_eq!(
+ build_prps(0x1080, 100, P4K, 0x8000, &mut list).unwrap(),
+ (0x1080, 0, 0)
+ );
+ assert_eq!(
+ build_prps(0x1FFF, 1, P4K, 0, &mut list).unwrap(),
+ (0x1FFF, 0, 0)
+ );
+ assert_eq!(build_prps(0, P4K, P4K, 0, &mut list).unwrap(), (0, 0, 0));
+}
+
+#[test]
+fn one_page_boundary_crossing() {
+ let mut list = [0u64; 0];
+ assert_eq!(
+ build_prps(0x1000, P4K, P4K, 0x8000, &mut list).unwrap(),
+ (0x1000, 0, 0)
+ );
+ assert_eq!(
+ build_prps(0x1080, P4K, P4K, 0x8000, &mut list).unwrap(),
+ (0x1080, 0x2000, 0)
+ );
+}
+
+#[test]
+fn two_pages_use_prp2_with_zero_used() {
+ let mut list = [0u64; 0];
+ assert_eq!(
+ build_prps(0x1000, 2 * P4K, P4K, 0x8000, &mut list).unwrap(),
+ (0x1000, 0x2000, 0)
+ );
+ assert_eq!(
+ build_prps(0x1080, 7680, P4K, 0, &mut list).unwrap(),
+ (0x1080, 0x2000, 0)
+ );
+ // PRP1 is the raw input, unmodified even when unaligned. One page of
+ // length from an unaligned start spans exactly two pages.
+ assert_eq!(
+ build_prps(0x1ABC, P4K, P4K, 0, &mut list).unwrap(),
+ (0x1ABC, 0x2000, 0)
+ );
+}
+
+#[test]
+fn multi_page_requires_aligned_nonzero_list() {
+ let mut list = [0u64; 4];
+ assert_eq!(
+ build_prps(0x1000, 3 * P4K, P4K, 0, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0x1000, 3 * P4K, P4K, 0x8001, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0x1000, 3 * P4K, P4K, 0xFFF, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0x1000, 3 * P4K, P4K, 0x8000, &mut list).unwrap(),
+ (0x1000, 0x8000, 2)
+ );
+ assert_eq!(list[..2], [0x2000, 0x3000]);
+
+ let mut four = [0u64; 3];
+ assert_eq!(
+ build_prps(0x1000, 4 * P4K, P4K, 0x8000, &mut four).unwrap(),
+ (0x1000, 0x8000, 3)
+ );
+ assert_eq!(four, [0x2000, 0x3000, 0x4000]);
+}
+
+#[test]
+fn list_buffer_too_small_is_bounded() {
+ let mut one = [0u64; 1];
+ assert_eq!(
+ build_prps(0x1000, 3 * P4K, P4K, 0x8000, &mut one),
+ Err(PrpError::ListTooSmall)
+ );
+
+ let mut two = [0u64; 2];
+ assert_eq!(
+ build_prps(0x1000, 4 * P4K, P4K, 0x8000, &mut two),
+ Err(PrpError::ListTooSmall)
+ );
+ assert_eq!(two, [0x2000, 0x3000]);
+
+ let mut three = [0u64; 3];
+ assert_eq!(
+ build_prps(0x1000, 5 * P4K, P4K, 0x8000, &mut three),
+ Err(PrpError::ListTooSmall)
+ );
+ assert_eq!(three, [0x2000, 0x3000, 0x4000]);
+}
+
+#[test]
+fn list_page_chaining_4k_exact_used() {
+ const PER: usize = P4K / 8;
+ let list_at = 0x80_0000u64;
+
+ let mut full = vec![0u64; 2 * 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; 2 * PER];
+ 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);
+ 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);
+
+ let mut short = vec![0u64; PER];
+ assert_eq!(
+ build_prps(0x1000, (2 + PER) * P4K, P4K, list_at, &mut short),
+ Err(PrpError::ListTooSmall)
+ );
+}
+
+#[test]
+fn list_page_chaining_64k_exact_used() {
+ const PER: usize = P64K / 8;
+ let list_at = 0x200_0000u64;
+
+ let mut fits = vec![0u64; PER];
+ let (p1, p2, used) = build_prps(0x10000, (1 + PER) * P64K, P64K, list_at, &mut fits).unwrap();
+ assert_eq!((p1, p2, used), (0x10000, list_at, PER));
+ assert_eq!(fits[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);
+ 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);
+
+ let mut small = vec![0u64; 4];
+ assert_eq!(
+ build_prps(
+ 0x10000,
+ (2 + PER) * P64K,
+ P64K,
+ list_at + 0x1000,
+ &mut small
+ ),
+ Err(PrpError::Invalid)
+ );
+}
+
+#[test]
+fn page_boundaries_64k() {
+ let mut list = [0u64; 0];
+ assert_eq!(
+ build_prps(0x10000, P64K, P64K, 0, &mut list).unwrap(),
+ (0x10000, 0, 0)
+ );
+ assert_eq!(
+ build_prps(0x10080, 100, P64K, 0, &mut list).unwrap(),
+ (0x10080, 0, 0)
+ );
+ assert_eq!(
+ build_prps(0x10080, P64K, P64K, 0, &mut list).unwrap(),
+ (0x10080, 0x20000, 0)
+ );
+ assert_eq!(
+ build_prps(0x10000, 2 * P64K, P64K, 0, &mut list).unwrap(),
+ (0x10000, 0x20000, 0)
+ );
+}
+
+#[test]
+fn transfer_limit_arithmetic_is_bounded() {
+ let mut list = [0u64; 8];
+ let huge = (1usize << 40).checked_mul(4096).expect("64-bit host");
+ assert_eq!(
+ build_prps(0, huge, P4K, 0x8000, &mut list),
+ Err(PrpError::ListTooSmall)
+ );
+ assert_eq!(
+ build_prps(0, usize::MAX, P4K, 0x8000, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(0, usize::MAX - 100, P4K, 0x8000, &mut list),
+ Err(PrpError::Invalid)
+ );
+ assert_eq!(
+ build_prps(usize::MAX as u64, usize::MAX, P4K, 0x8000, &mut list),
+ Err(PrpError::Invalid)
+ );
+}
+
+#[test]
+fn prp_values_are_full_physical_addresses() {
+ let high = 0x1_2345_6000u64;
+ assert!(high > u32::MAX as u64);
+ let mut list = [0u64; 4];
+
+ assert_eq!(
+ build_prps(high, P4K, P4K, 0, &mut list).unwrap(),
+ (high, 0, 0)
+ );
+ assert_eq!(
+ build_prps(high, 2 * P4K, P4K, 0, &mut list).unwrap(),
+ (high, high + P4K as u64, 0)
+ );
+
+ let list_at = 0x2_0000_0000u64;
+ assert!(list_at > u32::MAX as u64);
+ let (p1, p2, used) = build_prps(high, 3 * P4K, P4K, list_at, &mut list).unwrap();
+ assert_eq!((p1, p2, used), (high, list_at, 2));
+ assert_eq!(list[..2], [high + P4K as u64, high + 2 * P4K as u64]);
+ assert!(p1 > u32::MAX as u64);
+ assert!(p2 > u32::MAX as u64);
+
+ assert_eq!(
+ build_prps(0x1080, P4K, P4K, 0, &mut list).unwrap().0,
+ 0x1080
+ );
+}
diff --git a/docs/P3_NVME_CONTROLLER_AUDIT.md b/docs/P3_NVME_CONTROLLER_AUDIT.md
new file mode 100644
index 00000000 ..56d5408f
--- /dev/null
+++ b/docs/P3_NVME_CONTROLLER_AUDIT.md
@@ -0,0 +1,65 @@
+# D1 - NVMe Controller-State Audit (AIENOS P3 Native NVMe Read Substrate)
+
+Repo: `aien-dev/aienos` @ baseline `ff5de9c `
+Mirror (read-only): `/Users/drakestapleton/aienos-p3`
+Scope: `crates/aienos-kernel/src/nvme.rs`, `crates/aienos-kernel/src/nvme/driver.rs`, `crates/aienos-kernel/src/block.rs`
+Reference model: NVMe Base Specification (CAP / VS / CC / CSTS / AQA / ASQ / ACQ register layout; Identify Controller/Namespace layouts).
+
+Status legend:
+- **SUPPORTED** - matches the base register model (or is a safe, self-imposed policy).
+- **UNSAFE-IF-DEVIATES** - correct only for the common 4 KiB / single-controller case; breaks (or overflows/under-waits) on a spec-legal controller that deviates.
+- **UNSUPPORTED** - an assumption the code makes that is not derived from or validated against the register model.
+
+## Register / behavior table
+
+| # | Assumption | file:line | What the code does | Spec-correct? | Risk | Recommended minimal fix | Status |
+|---|-----------|-----------|--------------------|---------------|------|-------------------------|--------|
+| 1 | 64-bit CAP assembly | `nvme/driver.rs:107` | `Cap((read32(4) as u64) << 32) \| read32(0) as u64` | Yes - high dword at 0x04, low at 0x00 | None | None | SUPPORTED |
+| 2 | CAP.MQES enforcement | `nvme.rs:37-39`; `driver.rs:115-118`, `174-196` | MQES decoded (`mqes()`) but never compared to `ADMIN_DEPTH` (8) or caller I/O depth; AQA/QSIZE written unconditionally | Only if `depth-1 <= MQES` | A spec-legal controller with small MQES gets an out-of-range AQA/QSIZE → command abort / undefined behavior | Reject at `init` if `ADMIN_DEPTH > cap.mqes()`, and in `create_io_queues` if `depth > cap.mqes()` | UNSAFE-IF-DEVIATES |
+| 3 | CAP.TO units (500 ms) | `nvme.rs:40-42`; `driver.rs:108` | `timeout_ms = cap.timeout_units().max(1) * 500` | Yes - TO is bits 31:24 in 500 ms units; `TO==0` treated as 500 ms default | None material; `TO=0` means "not reported", a host default is reasonable | None | SUPPORTED |
+| 4 | CAP.DSTRD / doorbell math | `nvme.rs:31-36`, `45-47` | `stride = 4 << DSTRD`; `offset = 0x1000 + (2*qid + completion)*stride` | Yes - SQqTDBL at 0x1000+2q·stride, CQqHDBL at +1·stride | `u32` math can overflow only for absurd qid·stride; no real path | Optionally use `u64` in `doorbell_offset` | SUPPORTED |
+| 5 | CAP.MPSMIN / CAP.MPSMAX / MPS | `nvme.rs:27-43`; `driver.rs:12,43,123` | MPSMIN/MPSMAX never read; `CC.MPS=0` (4 KiB) and `PAGE_SIZE=4096` hard-coded | No - if `CAP.MPSMIN>0` the controller requires MPS ≥ `2^(12+MPSMIN)`; programming MPS=0 is illegal | **High**: on a controller with MPSMIN>0 the enable sequence is non-conformant and ASQ/ACQ/PRP alignments are wrong | Extract MPSMIN (`(cap>>48)&0xff`) / MPSMAX; require `MPSMIN==0` else program the correct MPS and align to `2^(12+MPSMIN)` | UNSUPPORTED |
+| 6 | CAP.CSS / CC.CSS | `driver.rs:42,123` | `CC.CSS=0` (NVM) hard-coded; CAP.CSS never checked | Only if NVM command set supported (`CAP.CSS` bit 0) | Low on real NVMe drives; non-conformant on a device not advertising NVM CSS | Read CAP.CSS (bits 52:45); fail init if bit 0 clear | UNSUPPORTED |
+| 7 | CAP.AMS / CC.AMS | `driver.rs:42,123` | `CC.AMS=0` (Round Robin) hard-coded; CAP.AMS never checked | Round Robin is the base mechanism, but not validated | Low | Read CAP.AMS (bits 18:17); assert bit 0 set or select a supported mechanism | UNSAFE-IF-DEVIATES |
+| 8 | VS (0x08) read/validated | `nvme.rs:9` (constant only) | `REG_VS` defined; never read. No version gate | Base register model compatible across 1.x/2.x; reading VS is not required to init | Low / informational; a future major-version incompatibility goes undetected | Optionally read VS, log/reject unsupported major | UNSUPPORTED |
+| 9 | CC reset → configure → enable order | `driver.rs:109-125` | Clear `CC.EN`, wait RDY=0, program AQA/ASQ/ACQ, write CC(EN=1), wait RDY=1 | Yes - admin queues programmed before EN; correct sequencing | None | None | SUPPORTED |
+| 10 | CSTS.CFS handling | `nvme.rs:70-72`; `driver.rs:32-34` | Any poll that sees CFS returns `Failed` immediately | Yes - CFS = fatal controller status | None | None | SUPPORTED |
+| 11 | CSTS.SHST | - | Never read | Not required for bring-up | None | None | SUPPORTED |
+| 12 | Readiness poll bound / off-by-one | `driver.rs:30-39` | `for _ in 0..=timeout_ms { read; if ready return; delay(1ms) }` | Bounded, but delays once after the final read → total `(TO+1)*1ms` | Trivial extra ms past CAP.TO | `for _ in 0..timeout_ms` (or check-after-delay) | UNSAFE-IF-DEVIATES |
+| 13 | AQA field packing | `driver.rs:115-118` | `((DEPTH-1)<<16) \| (DEPTH-1)` = `0x0007_0007` | Yes - ASQS bits 11:0, ACQS bits 27:16 | Field width not masked; only safe because DEPTH=8 | Mask with `0xfff` / `0xfff<<16` if depth ever exceeds 4096 | SUPPORTED (conditional on #2) |
+| 14 | ASQ/ACQ 64-bit writes | `driver.rs:119-122` | Low dword at 0x28/0x30, high dword at +4; before EN | Yes | None | None | SUPPORTED |
+| 15 | ASQ/ACQ alignment | `driver.rs:112-114` | Allocated with alignment `PAGE_SIZE` (4 KiB) | Only if MPSMIN=0; spec requires alignment to min memory page size `2^(12+MPSMIN)` | Tied to finding #5 | Align ASQ/ACQ (and all DMA used in PRPs) to `2^(12+MPSMIN)` | UNSAFE-IF-DEVIATES |
+| 16 | Queue entry sizes 64/16, PAGE=4096 | `nvme.rs:81,159`; `driver.rs:12,44-45,123` | `CC.IOSQES=6`→64 B, `CC.IOCQES=4`→16 B; matching buffers | Yes for SQ/CQ sizes; MPS assumption is #5 | SQ/CQ sizes correct; page size tied to #5 | None beyond #5 | SUPPORTED |
+| 17 | Admin completion poll bound | `driver.rs:15,222,228` | Fixed `ADMIN_TIMEOUT_MS=1000` × 1 ms, independent of CAP.TO | Bounded; CAP.TO governs readiness but not command wait | A slow but conformant admin command could exceed 1 s | Derive from CAP.TO (e.g. `cap.timeout_units()*500`) | SUPPORTED (note) |
+| 18 | I/O completion poll bound | `driver.rs:362,369` | `for _ in 0..=1000` with 1 ms delay | Bounded; fixed policy | Same as #17 | Make configurable / CAP.TO-derived | SUPPORTED (note) |
+| 19 | MDTS handling | `driver.rs:150,291-302` | MDTS byte 77; `limit = (PAGE_SIZE<<MDTS).min(128KiB)`, `MDTS=0` → 128 KiB | Units under-stated if MPSMIN>0 (safe: more splitting); MDTS=0 self-capped (safe) | Conservative in the safe direction; no overflow | Use `2^(12+MPSMIN)` as the MDTS unit; keep the 128 KiB self-cap | SUPPORTED (conservative) |
+| 20 | Identify Controller MDTS offset | `driver.rs:150` | `bytes[77]` | Yes - MDTS at byte 77 | None | None | SUPPORTED |
+| 21 | Identify Namespace block count | `driver.rs:156` | `NSZE = u64 le bytes[0..8]` | Yes - NSZE bytes 0-7 | None (uses NSZE not NCAP; correct as last-address + 1) | None | SUPPORTED |
+| 22 | FLBAS index | `driver.rs:157` | `bytes[26] & 0x0f` | Yes - FLBAS byte 26, low 4 bits = format index | None | None | SUPPORTED |
+| 23 | LBA format descriptor | `driver.rs:158-159` | `descriptor = 128 + flbas*4`; `lbads = bytes[descriptor+2]` | Yes - LBAF array at 128, LBADS at +2 | None | None | SUPPORTED |
+| 24 | LBADS lower bound | `driver.rs:162` | Rejects only `lbads >= 32`; accepts `lbads` 0..8 | No - valid LBA data sizes are `2^9`…`2^31` (LBADS 9..31) | A malformed identify yields a 1-byte block size and a huge block_count; silent miscompute | Require `9 <= lbads < 32` | UNSUPPORTED |
+| 25 | Command layouts | `nvme.rs:96-156` | Identify CDW10=CNS, NSID=CDW1; R/W opcodes 0x02/0x01, NLB-1 in CDW12, LBA in CDW10-11, PRP1/2 in DW6-9 | Yes | None | None | SUPPORTED |
+| 26 | CID handling | `driver.rs:212,353` | CID in CDW0 bits 31:16, low 16 preserved; wrapped modulo 16 bits | Yes | None | None | SUPPORTED |
+| 27 | Completion status decode | `nvme.rs:173-175`; `driver.rs:234-239` | `status>>1`, SCT=(status>>8)&7, SC=status&0xff; phase=bit0 | Yes | None (More/DNR bits not inspected) | Optionally surface More/DNR | SUPPORTED |
+| 28 | Phase tracking | `nvme.rs:219-254`; `driver.rs:136,227,368` | CQ consumer starts phase=1, toggles on ring wrap | Yes | None | None | SUPPORTED |
+| 29 | Hard-coded NSID 1 | `driver.rs:145,150,156`, `184-185`, `333-335`, `419` | All identify/read/write/flush use namespace 1 | Assumes NSID 1 exists and is the target | **Medium**: a controller whose active namespace is not 1 (or multi-namespace) fails or targets the wrong store | Enumerate active NSIDs (Identify CNS=2) and use the discovered NSID | UNSUPPORTED |
+| 30 | Queue-create CDW11 (PC/IEN/CQID) | `nvme.rs:106-127` | CQ: `CDW11=1` (PC=1, IEN=0, IV=0); SQ: `CDW11=1\|(cqid<<16)` | Yes | None | None | SUPPORTED |
+| 31 | CQ head doorbell after consume | `driver.rs:246-249,380-381` | Advances `cq_head`, writes CQqHDBL | Yes | None | None | SUPPORTED |
+| 32 | Completion SQID not checked | `driver.rs:231,372` | Only `command_id` matched; SQID ignored | Spec requires matching SQID+CID | Low robustness; a stale/misrouted completion could be accepted | Also compare `completion.sq_id()` (0 admin / 1 I/O) | UNSAFE-IF-DEVIATES |
+| 33 | Flush command | `driver.rs:415-422` | Opcode 0, NSID 1, via I/O queue | Yes (aside from NSID assumption #29) | Tied to #29 | None | SUPPORTED |
+| 34 | PRP list capacity | `driver.rs:314-331`; `nvme.rs:258-303` | One 4 KiB list page allocated when `len/PAGE > 2`; max chunk 128 KiB ⇒ ≤512 entries | Yes for the self-imposed 128 KiB cap | None | None | SUPPORTED |
+| 35 | DMA 64-bit address width | `driver.rs:119-122`, `nvme.rs:90-91` | Always writes full 64-bit PRP/ASQ/ACQ addresses | Yes for 64-bit-capable controllers; no check | Low; base NVMe ASQ/ACQ are 64-bit by definition | None | SUPPORTED |
+
+## Summary of non-SUPPORTED items
+
+| Finding | Status | Severity |
+|---------|--------|----------|
+| CAP.MPSMIN/MPSMAX ignored; MPS + PAGE_SIZE + ASQ/ACQ alignment hard-coded to 4 KiB | UNSUPPORTED | High |
+| CAP.MQES not enforced for admin/I/O queue depths | UNSAFE-IF-DEVIATES | High |
+| CAP.CSS not validated; CC.CSS hard-coded NVM | UNSUPPORTED | Medium |
+| Hard-coded NSID 1 (no active-namespace enumeration) | UNSUPPORTED | Medium |
+| LBADS lower bound not validated (accepts 0..8) | UNSUPPORTED | Medium |
+| CAP.AMS not validated; CC.AMS hard-coded Round Robin | UNSAFE-IF-DEVIATES | Low |
+| Readiness poll delays once after the final read (off-by-one vs CAP.TO) | UNSAFE-IF-DEVIATES | Low |
+| Completion SQID not verified against expected queue | UNSAFE-IF-DEVIATES | Low |
+| VS (0x08) never read/validated | UNSUPPORTED | Informational |
diff --git a/docs/P3_NVME_READ_SUBSTRATE.md b/docs/P3_NVME_READ_SUBSTRATE.md
new file mode 100644
index 00000000 ..5d338073
--- /dev/null
+++ b/docs/P3_NVME_READ_SUBSTRATE.md
@@ -0,0 +1,352 @@
+# D5 - P3 Native NVMe Read Substrate: adapter and wiring design
+
+Baseline: `aien-dev/aienos` @ `ff5de9c ` (mirror `/Users/drakestapleton/aienos-p3`).
+Lane: P3 Native NVMe Read Substrate. Deliverable: the native adapter/wiring that
+lets the AIENOS handoff image drive an NVMe controller directly after firmware
+exit, plus the QEMU harness `scripts/qemu_nvme_test.sh` (this directory's
+`qemu_nvme_test.sh`). **Read-only qualification.**
+
+> **Status: implemented and passing in QEMU (2026-09-25).** The module
+> `crates/aienos-boot/src/nvme_read.rs`, the `nvme-read` feature, the handoff
+> wiring, and `scripts/qemu_nvme_test.sh` are in this branch. The SMMU-confined
+> run and the fail-closed run both pass; see
+> [`evidence/p3_nvme_read_qemu_2026-09-25.md`](../evidence/p3_nvme_read_qemu_2026-09-25.md).
+> `scripts/verify_all.sh` is intentionally not edited; wiring the harness and
+> the `nvme-read` clippy check into it remains a small follow-up.
+
+## 0. Scope and explicit non-claims
+
+- The substrate issues **only** Identify (admin, opcode 0x06) and Read
+ (I/O, opcode 0x02) commands. The `nvme-read` build never calls
+ `write_blocks`, `flush`, format, namespace management, or set-features with
+ side effects.
+- **Write and flush are NOT claimed, proven, or exercised.** The driver's
+ `BlockDevice` impl (`crates/aienos-kernel/src/nvme/driver.rs:401`) does
+ expose `write_blocks`/`flush`; this lane deliberately leaves them untested.
+ The QEMU harness attaches a disposable raw image and the guest only reads it.
+- **No dependency on Store v1 or any Store file.** The module reads the raw
+ namespace through `aienos_kernel::nvme` only; nothing imports
+ `aienos_kernel::store` (see `crates/aienos-kernel/src/lib.rs:42`).
+- The device is a native PCIe function discovered through ECAM and driven with
+ MMIO + polled queues, mirroring the xHCI keyboard candidate
+ (`crates/aienos-boot/src/usb_keyboard.rs`), not a UEFI Block I/O protocol.
+
+## 1. Feature gating
+
+Mirror the `usb-keyboard` gating exactly
+(`crates/aienos-boot/Cargo.toml:18-38`).
+
+`crates/aienos-boot/Cargo.toml`:
+
+```toml
+# SEED/P3 candidate: polled native NVMe read after firmware exit.
+# Only scripts/qemu_nvme_test.sh enables it; hardware staging never does.
+nvme-read = ["handoff"]
+# UNSAFE. DEBUG ONLY. QEMU ONLY. Lets the NVMe function DMA straight to
+# physical memory with NO SMMU confinement when the platform has no SMMU.
+# Never compiled with hardware-staging; prints a warning on every boot.
+unsafe-debug-nvme-dma-without-smmu = ["nvme-read"]
+```
+
+`crates/aienos-boot/src/lib.rs` adds, next to the existing xHCI guard
+(`crates/aienos-boot/src/lib.rs:12-19`):
+
+```rust
+#[cfg(all(
+ feature = "unsafe-debug-nvme-dma-without-smmu",
+ feature = "hardware-staging"
+))]
+compile_error!(
+ "feature `unsafe-debug-nvme-dma-without-smmu` (unconfined DMA, QEMU debug \
+ only) cannot be combined with `hardware-staging`: no SMMU confinement \
+ means no DMA"
+);
+
+/// Whether this build carries the unsafe, QEMU-only NVMe DMA bypass.
+pub const UNSAFE_NVME_DMA_BYPASS: bool = cfg!(feature = "unsafe-debug-nvme-dma-without-smmu");
+```
+
+The module is declared in the handoff binary next to the keyboard module
+(`crates/aienos-boot/src/handoff.rs:469-470`):
+
+```rust
+#[cfg(feature = "nvme-read")]
+mod nvme_read;
+```
+
+## 2. New module `crates/aienos-boot/src/nvme_read.rs`
+
+The module's shape is a direct sibling of `usb_keyboard.rs`: pre-exit discovery,
+post-exit confinement, then `run()`.
+
+### 2.1 `NvmeLocation` - ECAM discovery of class 0x0108 and BAR0
+
+Pre-exit (`find_nvme()`), walk every `PciRootBridgeIo` handle exactly like
+`find_xhci()` (`usb_keyboard.rs:72-126`):
+
+- Read config dword 0 for the present check (`id & 0xffff != 0xffff`).
+- Read class/revision at offset `0x08`; the class code is bits 8..32.
+ NVMe is base class `0x01` (mass storage), sub-class `0x08` (NVM),
+ programming interface `0x02`. QEMU's `-device nvme` reports `0x010802`,
+ so match `(class_revision >> 8) & 0xffff == 0x0108` (accept any prog-if).
+ (Constants: `crates/aienos-kernel/src/pci.rs:20` defines `REG_CLASS_REVISION`.)
+- Decode a 64-bit memory BAR0 from config offsets `0x10` (low) and `0x14`
+ (high) into the MMIO base, as the xHCI walk reads its BAR pair
+ (`usb_keyboard.rs:104-114`). Reject an I/O-space BAR (low bit 0).
+
+```rust
+#[derive(Clone, Copy)]
+pub struct NvmeLocation {
+ segment: u16, bus: u8, device: u8, function: u8, mmio: u64,
+}
+
+impl NvmeLocation {
+ pub fn mmio_base(self) -> u64 { self.mmio }
+ pub fn ecam_location(self) -> (u16, u8) { (self.segment, self.bus) }
+ pub fn requester_id(self) -> u32 {
+ (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function)
+ }
+ pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option<u32> {
+ iort.stream_id_for(self.requester_id())
+ }
+ pub fn dma_window(self) -> (u64, usize) {
+ let base = core::ptr::addr_of!(DMA_ARENA) as u64;
+ (base & !0xfff, core::mem::size_of::<DmaArena>())
+ }
+}
+```
+
+`requester_id` / `stream_id` / `dma_window` mirror `XhciLocation`
+(`usb_keyboard.rs:59-68`). `requester_id` is exactly `Bdf::requester_id`
+(`crates/aienos-kernel/src/pci.rs:75`); `stream_id` uses
+`IortSmmu::stream_id_for` (`crates/aienos-kernel/src/acpi.rs:286`).
+
+### 2.2 `NativeRegisters` - Registers MMIO adapter
+
+The kernel driver is generic over `Registers`
+(`crates/aienos-kernel/src/nvme.rs:22`), which this adapter implements over
+`MmioReg` (`crates/aienos-kernel/src/arch/aarch64.rs:8-31`):
+
+```rust
+pub struct NativeRegisters { base: usize }
+
+impl aienos_kernel::nvme::Registers for NativeRegisters {
+ fn read32(&mut self, offset: u32) -> u32 {
+ MmioReg::<u32>::new(self.base + offset as usize).read()
+ }
+ fn write32(&mut self, offset: u32, value: u32) {
+ MmioReg::<u32>::new(self.base + offset as usize).write(value);
+ }
+}
+```
+
+### 2.3 `NativeDma` - static DMA arena implementing `DmaMemory`
+
+The driver owns DMA through the `DmaMemory` trait
+(`crates/aienos-kernel/src/nvme/driver.rs:63-67`), whose regions carry a
+physical address and a CPU byte view. The handoff identity-maps conventional
+memory, so the arena's virtual address **is** its physical address (the same
+assumption as `XhciLocation::dma_window`, `usb_keyboard.rs:65-68`).
+
+```rust
+const ARENA_BYTES: usize = 128 * 1024; // admin + I/O queues + transfer pages
+
+#[repr(C, align(4096))]
+struct DmaArena([u8; ARENA_BYTES]);
+
+static mut DMA_ARENA: DmaArena = DmaArena([0; ARENA_BYTES]);
+
+struct NativeDma { next: usize, end: usize }
+
+impl aienos_kernel::nvme::driver::DmaMemory for NativeDma {
+ fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
+ let base = core::ptr::addr_of_mut!(DMA_ARENA) as usize;
+ let aligned = (self.next + alignment - 1) & !(alignment - 1);
+ if aligned.checked_add(size).is_none_or(|e| e > self.end) {
+ return Err(NvmeError::Dma);
+ }
+ self.next = aligned + size;
+ let ptr = aligned as *mut u8;
+ // SAFETY: bump-allocated from the zeroed static arena, page aligned.
+ unsafe { core::ptr::write_bytes(ptr, 0, size) };
+ Ok(DmaRegion { physical: aligned as u64, bytes: unsafe {
+ core::slice::from_raw_parts_mut(ptr, size) }.to_vec() })
+ }
+ fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { /* copy from identity */ }
+ fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { /* copy to identity */ }
+}
+```
+
+`#[repr(C, align(4096))]` on the arena mirrors `DmaPage`
+(`crates/aienos-kernel/src/usb/xhci/controller.rs:38-41`). 128 KiB covers the
+driver's bounded allocations: admin SQ/CQ/Identify 3 x 4096
+(`driver.rs:112-114`), I/O CQ `depth*16` and SQ `depth*64` for `depth = 4`
+(`driver.rs:178-183`), a transfer region plus PRP list for a single 512-byte
+read (`driver.rs:307-324`).
+
+### 2.4 `NativeDelay` - bounded real-time waits
+
+`Delay::delay_us` (`driver.rs:18`) spins on the architectural counter using
+`counter_frequency_hz()` / `counter_ticks()`
+(`crates/aienos-kernel/src/arch/aarch64.rs:130,204`), so every controller wait
+is bounded in real time, matching the kernel's own design note
+(`driver.rs:14-15`).
+
+### 2.5 SMMU + `dma_gate` confinement
+
+Post-exit, in order (mirrors `usb_keyboard.rs:182-345` and
+`handoff.rs:1665-1672`):
+
+1. **Bus-master sweep before anything else.** `take_over_dma(nvme, mcfg)` builds
+ an `Ecam` adapter over the MCFG window
+ (`crates/aienos-kernel/src/acpi.rs:380`, adapter pattern
+ `usb_keyboard.rs:147-169`) and calls
+ `dma_gate::sweep_bus_master` (`dma_gate.rs:150`) so every endpoint's Bus
+ Master Enable starts clear.
+2. **SMMU domain for the NVMe stream.** `configure_smmu_for_nvme` is a
+ parameterized twin of `configure_smmu_for_xhci` (`handoff.rs:206-282`):
+ resolve `stream_id` from IORT (`acpi.rs:286`), build policy with
+ `aienos_kernel::smmu::build_dma_policy` over the **NVMe arena window**
+ (`dma_window()` above) only, then `configure_linear_stream`. The report
+ line is `smmu_dma_window: nvme only, translation active`.
+3. **Gate.** `dma_gate::dma_grant(smmu_ready, smmu_present, UNSAFE_NVME_DMA_BYPASS)`
+ (`dma_gate.rs:68`). Only on `Ok(Confined)` (or `Ok(UnsafeBypass)`) is
+ `dma_gate::with_bus_master(command)` written. On denial the module logs
+ `dma_gate: nvme denied ({denied:?}), bus master stays off` and
+ `nvme: unavailable (SMMU DMA isolation not active)`, then returns with the
+ controller never enabled.
+4. **Revocation.** After the phase, clear Bus Master Enable again and emit
+ `dma_gate: nvme bus master revoked` (pattern `usb_keyboard.rs:226-241`).
+
+Unsafe bypass announcement (QEMU only), mirroring
+`usb_keyboard.rs:35-37,257-259,326-331`:
+
+```rust
+const UNSAFE_NVME_BANNER: &str =
+ "\nWARNING: UNSAFE NVME DMA BYPASS BUILD (unsafe-debug-nvme-dma-without-smmu): \
+ NVMe DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n";
+// on UnsafeBypass grant:
+"WARNING: UNSAFE NVME DMA BYPASS ACTIVE: no SMMU on this machine, NVMe DMA \
+ reaches physical memory UNCONFINED (QEMU debug only)\n"
+```
+
+### 2.6 `run()` - the read phase and the six markers
+
+`run(nvme, takeover, &mut screen, smmu_ready, smmu_base, smmu_stream_id, events)`
+uses the same `say()` console+screen helper as `usb_keyboard.rs:136-143`.
+
+Controller bring-up: `NvmeController::init(NativeRegisters, NativeDma,
+NativeDelay)` (`driver.rs:106`) performs the reset/ready handshake, builds the
+admin queues, and runs Identify Controller + Identify Namespace 1
+(`driver.rs:144-171`). Then `create_io_queues(4)` (`driver.rs:174`) creates the
+polled QID-1 CQ/SQ (`create_io_cq` sets PC=1, IEN=0; `nvme.rs:106`).
+
+Read: `BlockDevice::read_blocks(sentinel_lba, &mut [u8; 512])`
+(`driver.rs:408`) issues a single Read (opcode 0x02, `nvme.rs:128`) over the
+identity-mapped arena. The module then verifies the bytes **natively** against
+the expected 512-byte sentinel and computes the SHA-256 with
+`aienos_kernel::crypto::sha256::hash` (`crypto/mod.rs:9`,
+`aienos-crypto/src/sha256.rs:198`). No host round-trip is trusted.
+
+## 3. Handoff wiring (`crates/aienos-boot/src/handoff.rs`)
+
+- **Pre-exit:** `let nvme = nvme_read::find_nvme();` beside the xHCI discovery
+ (`handoff.rs:1551-1552`). BAR0 must be mapped before post-exit MMIO.
+- **MMU map:** extend `enter_kernel_mmu`'s device list
+ (`handoff.rs:307-348`) with the NVMe BAR0 range (0x10000 bytes, as the xHCI
+ BAR uses) and the NVMe ECAM window, and with the SMMU page when present.
+ Because the current signature has one `xhci_mmio` slot, generalize it to a
+ caller-built `&[AddressRange]` (`extra_mmio`) so `usb-keyboard` and
+ `nvme-read` can coexist; the ECAM window is derived exactly as at
+ `handoff.rs:1640-1652`.
+- **Post-exit:** after `configure_smmu_for_xhci` (`handoff.rs:1670-1672`),
+ run `nvme_read::take_over_dma(nvme, acpi_facts.mcfg)` and
+ `configure_smmu_for_nvme(...)`, then call `nvme_read::run(...)` after the
+ final report and the optional keyboard phase (`handoff.rs:1975-1987`).
+
+Pre-exit facts reused unchanged: MCFG table + ECAM window (`acpi.rs:380`),
+IORT SMMUv3 (`acpi.rs:297`), and `bus_ranges` (`handoff.rs:840`).
+
+## 4. Serial markers (exact strings the kernel emits)
+
+Emitted through `say()` to the SPCR console during the NVMe phase. The six
+required markers, with their detail (PASS shown; on failure the same prefix is
+printed with `FAIL` and the reason):
+
+```text
+NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x10010000)
+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)
+```
+
+Supporting lines (not required, used by the harness for isolation):
+
+```text
+nvme: class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x... # discovery detail
+dma_sweep: seg 0000 bus 00-ff ... # dma_gate::sweep_bus_master
+dma_gate: nvme granted (Confined), bus master on # or UnsafeBypass / denied
+smmu: enabled base=0x... stream_id=0x...
+smmu_dma_window: nvme only, translation active
+dma_gate: nvme bus master revoked
+nvme: unavailable (SMMU DMA isolation not active)
+```
+
+Marker semantics:
+
+| Marker | Kernel action |
+| --- | --- |
+| `NVME_DISCOVERY_QEMU` | ECAM walk found a function whose class code is base/sub `0x0108`; BAR0 decoded. PASS = found + BAR0 mapped. |
+| `NVME_IDENTIFY_QEMU` | `NvmeController::init` reached CSTS.RDY and Identify Controller + Identify Namespace 1 returned status 0 (`driver.rs:144-171`). |
+| `NVME_GEOMETRY_QEMU` | Namespace 1 reports `block_count == 131072`, `block_size == 512`, exactly the image geometry. |
+| `NVME_READ_QEMU` | Read of LBA 2048 returned 512 bytes byte-identical to the sentinel, and `sha256 == 8b688adc …`. |
+| `NVME_BOUNDS_QEMU` | `read_blocks(131072, …)` returned `BlockError::OutOfRange` with **no** I/O doorbell write (client-side bounds, `driver.rs:284-290`). |
+| `NVME_ERROR_QEMU` | Identify Namespace for unallocated NSID `0xffffffff` returned a non-zero completion status (`NvmeError::CompletionStatus`, `driver.rs:236-239`); proves the device error path is surfaced, not swallowed. |
+
+## 5. Exact expected sentinel geometry
+
+| Property | Value |
+| --- | --- |
+| Image size | 64 MiB = 67,108,864 bytes, disposable raw |
+| LBA size | 512 bytes |
+| Total LBAs | 131,072 |
+| Sentinel LBA | 2048 (byte offset 1,048,576 = 1 MiB) |
+| Sentinel length | 1 LBA = 512 bytes |
+| Sentinel payload | 16-byte magic `AIENOS-NVME-SENT` repeated 32 times (no newline) |
+| Sentinel SHA-256 | `8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1 ` |
+| Bounds LBA (out of range) | 131072 (== block_count) |
+| Error NSID | 0xffffffff (unallocated) |
+
+The host harness builds the same payload with `printf` + `truncate` + `dd`,
+hashes it with `sha256sum`, and requires the kernel's `NVME_READ_QEMU` line to
+contain that host-computed hash, so a wrong or stale image cannot pass.
+
+## 6. Harness mapping (`qemu_nvme_test.sh`)
+
+- Builds `-p aienos-boot --target aarch64-unknown-uefi --features nvme-read
+ --bin aienos-handoff --target-dir target/qemu-nvme` with `AIENOS_COMMIT`
+ and `AIENOS_RESTART_SECS=1` (as `qemu_keyboard_test.sh:65-68`).
+- Boots the same AAVMF image and `virt,virtualization=on,gic-version=3`
+ machine, defaulting to `iommu=smmuv3`; attaches the sentinel image as
+ `-device nvme,drive=nvme0,serial=aienos-nvme-test`.
+- Waits for `report_kind: pre_exit`, then for `NVME_ERROR_QEMU: PASS` (or a
+ panic/fault), then checks the six markers plus the SMMU/`dma_gate` lines and
+ prints `QEMU_NVME: PASS`/`FAIL` with a non-zero exit on failure.
+- Fail-closed mode (`AIENOS_QEMU_SMMU=0`, normal build) requires the six
+ markers to be **absent** and the denial lines to be present. Unsafe mode
+ (`AIENOS_UNSAFE_DMA_BYPASS=1`) requires the bypass banners plus the six
+ markers and prints a warning.
+
+## 7. Follow-ups (not done in this lane)
+
+- **`scripts/verify_all.sh` is not edited.** Adding a QEMU step for this
+ harness and `nvme-read` to the aarch64 clippy feature loop
+ (`verify_all.sh:70-73`) is a separate integration change.
+- **Host unit tests:** add `aienos-boot`/kernel tests for the class-0x0108
+ match and the arena bump allocator; the kernel `nvme` module already has a
+ full fake-controller suite (`driver.rs:425-977`) the native adapter must not
+ disturb.
+- **Write/flush stay out of scope** until a separate lane can prove
+ confinement end-to-end for mutating media commands.
diff --git a/docs/P3_NVME_UNSAFE_ASSUMPTIONS.md b/docs/P3_NVME_UNSAFE_ASSUMPTIONS.md
new file mode 100644
index 00000000 ..dcfda46c
--- /dev/null
+++ b/docs/P3_NVME_UNSAFE_ASSUMPTIONS.md
@@ -0,0 +1,61 @@
+# D1 - Unsupported / Unsafe Assumptions (prioritized)
+
+Repo: `aien-dev/aienos` @ `ff5de9c `. Read-only audit; no repo edits, no cargo, no hardware.
+
+Only assumptions that are **UNSUPPORTED** or **UNSAFE-IF-DEVIATES** are listed. Each entry gives the minimal change.
+
+---
+
+## P0 - CAP.MPSMIN / MPSMAX ignored; MPS, PAGE_SIZE and ASQ/ACQ alignment hard-coded to 4 KiB
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:12,43,123`; `crates/aienos-kernel/src/nvme.rs:27-43`
+- **Assumption**: `CC.MPS=0` (4 KiB), `PAGE_SIZE=4096`, and `PAGE_SIZE`-aligned ASQ/ACQ are always valid.
+- **Why unsafe**: `CAP.MPSMIN` (CAP bits 55:48) sets the minimum memory page size `2^(12+MPSMIN)`. A spec-legal controller with `MPSMIN>0` requires `CC.MPS >= MPSMIN` and page-size-aligned admin queues; programming MPS=0 is non-conformant and the ASQ/ACQ/PRP page math is wrong.
+- **Minimal change**: Extract MPSMIN from CAP (`(cap >> 48) & 0xff`) and MPSMAX (`(cap >> 56) & 0xf`). If `MPSMIN != 0`, either fail init loudly or program `CC.MPS = MPSMIN` and use `page_size = 1 << (12 + MPSMIN)` for allocations/alignment/PRP math instead of the `PAGE_SIZE` constant.
+
+## P0 - CAP.MQES not enforced for admin or I/O queue depths
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:115-118` (admin), `174-196` (I/O); decode at `crates/aienos-kernel/src/nvme.rs:37-39`
+- **Assumption**: `ADMIN_DEPTH=8` and any caller I/O `depth >= 2` are accepted without checking the controller's maximum (`CAP.MQES+1`).
+- **Why unsafe**: The controller may support fewer entries; AQA (`0x0007_0007`) or a create-queue QSIZE above `MQES` is out of range and aborts/undefined.
+- **Minimal change**: At the top of `init`, return an error if `ADMIN_DEPTH > cap.mqes()`; in `create_io_queues`, reject `depth > cap.mqes()` before allocating.
+
+## P1 - CAP.CSS not validated; CC.CSS hard-coded to NVM
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:42,123`
+- **Assumption**: The controller supports the NVM command set (`CC.CSS=0`).
+- **Why unsafe**: If `CAP.CSS` bit 0 is clear, selecting CSS 0 is invalid and the enable sequence is non-conformant. Rare but spec-legal.
+- **Minimal change**: Read `CAP.CSS` (`(cap >> 45) & 0xff`); fail init with a dedicated error if bit 0 is 0.
+
+## P1 - Hard-coded NSID 1; no active-namespace enumeration
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:145,150,156`, `184-185`, `333-335`, `419`
+- **Assumption**: Namespace ID 1 always exists and is the intended storage.
+- **Why unsafe**: A controller may expose a different active NSID or multiple namespaces; reads/writes/flush could fail or target the wrong store. (Note: `nsid` is a parameter to `identify_namespace` but every caller passes 1.)
+- **Minimal change**: Enumerate active namespaces with Identify (CNS=2) and use the first active NSID, or thread a caller-supplied NSID through `identify_namespace`, `transfer`, and `flush`.
+
+## P1 - LBADS lower bound not validated
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:162`
+- **Assumption**: Any `lbads < 32` is a usable LBA data size.
+- **Why unsafe**: Valid LBA data sizes are `2^9`..`2^31` (LBADS 9..31). Accepting `lbads` 0..8 yields block sizes below 512 B and a correspondingly inflated `block_count`, silently miscomputing addresses.
+- **Minimal change**: Change the guard to reject `lbads < 9 || lbads >= 32`.
+
+## P2 - CAP.AMS not validated; CC.AMS hard-coded Round Robin
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:42,123`
+- **Assumption**: Round Robin arbitration (`CC.AMS=0`) is always supported.
+- **Why unsafe**: Round Robin is normally supported, but the capability (`CAP.AMS` bit 0) is never checked before selecting it.
+- **Minimal change**: Read `CAP.AMS` (`(cap >> 17) & 0x3`); if bit 0 is clear, fail init or select a supported mechanism.
+
+## P2 - Readiness poll off-by-one vs CAP.TO
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:30-39`
+- **Assumption**: `for _ in 0..=timeout_ms` with a post-read 1 ms delay bounds the wait at `timeout_ms` ms.
+- **Why unsafe**: It delays once after the final read, making the real bound `(timeout_ms+1)` ms - one poll past CAP.TO. Low impact, trivially wrong.
+- **Minimal change**: Use `for _ in 0..timeout_ms` or move `delay_us(1000)` before the last iteration.
+
+## P2 - Completion SQID not verified
+- **file:line**: `crates/aienos-kernel/src/nvme/driver.rs:231,372`
+- **Assumption**: Matching `command_id` alone identifies the completion.
+- **Why unsafe**: The spec keys completion to `(SQID, CID)`. A stale or misrouted CQE with a reused CID could be consumed.
+- **Minimal change**: After `command_id` matches, also assert `completion.sq_id()` equals the expected SQ ID (0 admin / 1 I/O), else treat as error.
+
+## P3 - VS (0x08) never read or validated
+- **file:line**: `crates/aienos-kernel/src/nvme.rs:9`
+- **Assumption**: The controller's major/minor version is irrelevant.
+- **Why unsafe**: The base register layout is stable across NVMe 1.x/2.x, so risk is informational today; there is no version gate for a future incompatible major.
+- **Minimal change** (optional): Read `REG_VS` during `init` and reject unsupported major versions, or log the version for field diagnostics.
diff --git a/evidence/p3_nvme_read_qemu_2026-09-25.md b/evidence/p3_nvme_read_qemu_2026-09-25.md
new file mode 100644
index 00000000 ..f7bc13ac
--- /dev/null
+++ b/evidence/p3_nvme_read_qemu_2026-09-25.md
@@ -0,0 +1,66 @@
+# P3 native NVMe read substrate: QEMU qualification (2026-09-25)
+
+Result: **`QEMU_NVME: PASS`** in both SMMU-confined and fail-closed modes.
+
+This is an emulator qualification only. It is not Machine 1 evidence. The
+substrate issues Identify and Read commands only; write and flush are not
+claimed, implemented, or exercised.
+
+Baseline: `aien-dev/aienos` @ `ff5de9c ` plus this branch. Command:
+`bash scripts/qemu_nvme_test.sh` (SMMU mode) and
+`AIENOS_QEMU_SMMU=0 bash scripts/qemu_nvme_test.sh` (fail-closed mode).
+
+## Disposable media
+
+- 64 MiB raw image, 131072 LBAs of 512 bytes, rebuilt per run.
+- Sentinel at LBA 2048, one 512-byte block: the 16-byte magic
+ `AIENOS-NVME-SENT` repeated 32 times.
+- Sentinel SHA-256:
+ `8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1 `.
+- Attached as `-drive if=none,id=nvme0,... -device nvme,drive=nvme0,serial=aienos-nvme-test`.
+
+## SMMU-confined run (`-M virt,...,iommu=smmuv3`)
+
+```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)
+dma_gate: nvme bus master revoked
+QEMU_NVME: PASS (smmu)
+```
+
+The read SHA-256 the kernel computes natively equals the host-computed
+sentinel SHA-256, so a wrong or stale image cannot pass.
+
+## Fail-closed run (no SMMU, normal build)
+
+```text
+NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x8000004000)
+dma_sweep: seg 0000 bus 00-ff functions=3 bridges=0 bridges_bme=0 endpoints_bme_found=2 still_enabled=0
+dma_gate: nvme denied (NoSmmu), bus master stays off
+nvme: unavailable (SMMU DMA isolation not active)
+QEMU_NVME: PASS (fail-closed)
+```
+
+`NVME_IDENTIFY_QEMU` and `NVME_READ_QEMU` are absent. Discovery runs before the
+DMA gate and is DMA-free; the controller is never enabled and no read happens.
+This proves the M3 rule holds for the NVMe path: no SMMU confinement means no
+DMA.
+
+## What this proves and does not prove
+
+- Proves, in QEMU: ECAM discovery of an NVMe class device, controller reset and
+ ready handshake, Identify Controller and Namespace, polled I/O queues, a
+ one-LBA read over PRPs, client-side bounds rejection, and device error
+ surfacing, all with DMA confined to the driver's arena by the SMMU.
+- Does not prove: any GB10 or Machine 1 behavior, GPU/accelerator behavior,
+ write, flush, namespace management, format, interrupt-driven I/O, or Store
+ interaction. It makes no Store v1 dependency and touches no Store file.
+- The unsafe bypass feature exists for debugging only; no bypass run was needed
+ for this qualification.
diff --git a/scripts/qemu_nvme_test.sh b/scripts/qemu_nvme_test.sh
new file mode 100755
index 00000000 ..41232e6b
--- /dev/null
+++ b/scripts/qemu_nvme_test.sh
@@ -0,0 +1,278 @@
+#!/usr/bin/env bash
+# P3 native NVMe read substrate proof in QEMU (read-only qualification).
+#
+# Boot the handoff image built with the `nvme-read` feature with a raw,
+# disposable NVMe namespace attached as
+# -drive if=none,id=nvme0,... -device nvme,drive=nvme0,serial=aienos-nvme-test
+# and let the native AIENOS driver drive the controller directly after
+# ExitBootServices: ECAM discovery, BAR0 MMIO, polled admin/I/O queues, and a
+# read of a deterministic sentinel LBA. The host builds the same sentinel and
+# checks the exact bytes and SHA-256 the kernel reports.
+#
+# Read-only: the driver only issues Identify and Read commands. No media write,
+# flush, format or namespace-management command is claimed or exercised.
+#
+# DMA rule (M3): no SMMU confinement means no DMA. Mirrors
+# scripts/qemu_keyboard_test.sh:
+# default QEMU SMMUv3 (iommu=smmuv3); the NVMe function
+# gets DMA only through a translated stream.
+# AIENOS_QEMU_SMMU=0 no SMMU, normal build: the controller must stay
+# unavailable with bus mastering off (fail-closed).
+# AIENOS_UNSAFE_DMA_BYPASS=1 no SMMU, UNSAFE debug build that lets the NVMe
+# function DMA to physical memory unconfined.
+# QEMU debugging only; never part of verify_all.sh.
+#
+# A boot that shows no AIENOS output at all is retried (firmware hang before
+# AIENOS runs, issue #61); any failure after AIENOS output fails at once.
+#
+# 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 (a dedicated QEMU step plus the aarch64 clippy
+# feature loop in step 3b) is a follow-up change 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}"
+machine="virt,virtualization=on,gic-version=3"
+
+# DMA mode (M3 rule: no SMMU confinement means no DMA), as in qemu_keyboard_test.sh.
+bypass_feature="unsafe-debug-nvme-dma-without-smmu"
+if [[ "${AIENOS_UNSAFE_DMA_BYPASS:-0}" == "1" ]]; then
+ mode="unsafe-bypass"
+ default_features="nvme-read,${bypass_feature}"
+ target_dir="target/qemu-nvme-unsafe-dma-bypass"
+ echo "################################################################"
+ echo "WARNING: AIENOS_UNSAFE_DMA_BYPASS=1: building ${bypass_feature}."
+ echo "WARNING: NVMe DMA runs WITHOUT SMMU confinement. QEMU debug only."
+ echo "WARNING: this run proves nothing about DMA isolation."
+ echo "################################################################"
+elif [[ "${AIENOS_QEMU_SMMU:-1}" == "1" ]]; then
+ mode="smmu"
+ machine+=",iommu=smmuv3"
+ default_features="nvme-read"
+ target_dir="target/qemu-nvme"
+else
+ mode="fail-closed"
+ default_features="nvme-read"
+ target_dir="target/qemu-nvme"
+fi
+features="${AIENOS_BUILD_FEATURES:-$default_features}"
+if [[ "${mode}" != "unsafe-bypass" && ",${features}," == *",${bypass_feature},"* ]]; then
+ echo "STOP: ${bypass_feature} requested without AIENOS_UNSAFE_DMA_BYPASS=1"
+ exit 2
+fi
+
+# Own target directory: an NVMe-enabled image never lands where hardware
+# staging or the other tests pick up the handoff image.
+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 "${features}" --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"
+
+# ---------------------------------------------------------------------------
+# Deterministic, disposable raw NVMe image (64 MiB), built with the same
+# tools the repo already uses (dd / od / printf / truncate / sha256sum).
+#
+# Geometry:
+# image : 64 MiB = 67108864 bytes = 131072 LBAs of 512 bytes
+# sentinel : LBA 2048 (offset 1048576 ), one 512-byte block
+# payload : the 16-byte magic "AIENOS-NVME-SENT" repeated 32 times
+# bounds LBA : 131072 (== block_count), must be rejected OutOfRange
+# ---------------------------------------------------------------------------
+magic='AIENOS-NVME-SENT'
+img_bytes=67108864
+lba_bytes=512
+sent_lba=2048
+sent_offset=$(( sent_lba * lba_bytes ))
+bounds_lba=$(( img_bytes / lba_bytes ))
+
+image="${work}/nvme.img"
+sentinel="${work}/sentinel.bin"
+# 16 bytes * 32 = 512 bytes, exactly one LBA, no newline.
+: > "${sentinel}"
+for _ in {1..32}; do printf '%s' "${magic}" >> "${sentinel}"; done
+[[ "$(wc -c <"${sentinel}")" == "512" ]] || { echo "STOP: sentinel must be exactly 512 bytes"; exit 2; }
+# Sparse zero image of the exact namespace size, then drop the sentinel block in.
+truncate -s "${img_bytes}" "${image}"
+dd if="${sentinel}" of="${image}" bs="${lba_bytes}" seek="${sent_lba}" conv=notrunc status=none
+[[ "$(wc -c <"${image}")" == "${img_bytes}" ]] || { echo "STOP: NVMe image is not ${img_bytes} bytes"; exit 2; }
+
+sentinel_sha="$(sha256sum "${sentinel}")"
+sentinel_sha="${sentinel_sha%% *}"
+readback_sha="$(dd if="${image}" bs="${lba_bytes}" skip="${sent_lba}" count=1 status=none | sha256sum)"
+readback_sha="${readback_sha%% *}"
+if [[ "${readback_sha}" != "${sentinel_sha}" ]]; then
+ echo "STOP: sentinel block was not written at LBA ${sent_lba} (offset ${sent_offset})"
+ exit 2
+fi
+echo "nvme image: ${img_bytes} bytes, ${bounds_lba} x ${lba_bytes} B LBAs"
+echo "sentinel: LBA ${sent_lba} offset ${sent_offset}, magic '${magic}' x32, sha256 ${sentinel_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 until the serial log contains one of the patterns or QEMU exits.
+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
+}
+
+boot_once() {
+ cp "${vars_fd}" "${work}/vars.fd"
+ rm -f "${work}/serial.log" "${work}/mon.in" "${work}/mon.out"
+ mkfifo "${work}/mon.in" "${work}/mon.out"
+ # Single-threaded TCG: multi-threaded TCG intermittently loses the
+ # firmware's timer wake-up and hangs before AIENOS output (#61).
+ local -a smmu_trace=()
+ if [[ "${AIENOS_QEMU_SMMU_TRACE:-0}" == "1" ]]; then
+ smmu_trace=(-d unimp,guest_errors -trace "smmuv3_*")
+ fi
+ # The NVMe namespace is a fresh image rebuilt above for every run; QEMU
+ # only ever sees reads from the guest driver.
+ qemu-system-aarch64 \
+ "${smmu_trace[@]}" \
+ -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-test \
+ -device ramfb -display none -nic none \
+ -chardev pipe,id=mon,path="${work}/mon" -mon chardev=mon,mode=readline \
+ -serial file:"${work}/serial.log" -no-reboot &
+ qemu_pid=$!
+ # Drain monitor output so QEMU never blocks writing it.
+ cat "${work}/mon.out" >/dev/null &
+ exec 3>"${work}/mon.in"
+
+ if ! wait_for "${boot_timeout}" "report_kind: pre_exit"; then
+ echo "attempt ${attempt}: no AIENOS output within ${boot_timeout} s (firmware hang, issue #61)"
+ stop_qemu
+ return 2
+ fi
+ # The native NVMe phase runs after the final report, so the last marker is
+ # the terminal signal; a panic or fault also ends the phase.
+ wait_for "${boot_timeout}" "NVME_ERROR_QEMU: PASS" "report_kind: panic" "report_kind: fault" || true
+ local deadline=$(( $(date +%s) + 30 ))
+ while qemu_running && (( $(date +%s) < deadline )); do sleep 0.5; done
+ qemu_running && echo "QEMU still running after the NVMe phase"
+ stop_qemu
+ return 0
+}
+
+started=$(date +%s)
+attempt=1
+while :; do
+ status=0
+ boot_once || status=$?
+ [[ "${status}" != 2 || "${attempt}" -ge "${attempts}" ]] && break
+ attempt=$(( attempt + 1 ))
+done
+elapsed=$(( $(date +%s) - started ))
+
+tr -d '\r' <"${work}/serial.log" >"${work}/serial.txt" 2>/dev/null || true
+[[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial.txt" "${AIENOS_LOG_DIR}/qemu_nvme_serial.log" 2>/dev/null || true
+failed=0
+check() { # description, pattern
+ if grep -q -- "$2" "${work}/serial.txt"; then
+ echo "PASS $1"
+ else
+ echo "FAIL $1"
+ failed=1
+ fi
+}
+check_absent() { # description, pattern
+ if grep -q -- "$2" "${work}/serial.txt"; then
+ echo "FAIL $1"
+ failed=1
+ else
+ echo "PASS $1"
+ fi
+}
+echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), dma mode ${mode}"
+
+# The six required native read markers. They must only appear once the
+# NVMe function has been granted DMA; in fail-closed mode they must be absent.
+if [[ "${mode}" != "fail-closed" ]]; 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 "sentinel LBA read back exact bytes and SHA-256" \
+ "NVME_READ_QEMU: PASS (lba=${sent_lba} blocks=1 bytes=512 sha256=${sentinel_sha})"
+ check "read past the namespace end is rejected before any command" "NVME_BOUNDS_QEMU: PASS"
+ check "device-reported command error is surfaced" "NVME_ERROR_QEMU: PASS"
+fi
+
+if [[ "${mode}" == "fail-closed" ]]; then
+ 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 "NVMe controller never granted DMA" "dma_gate: nvme granted"
+ check_absent "NVMe controller never identified" "NVME_IDENTIFY_QEMU"
+ check_absent "NVMe read never ran" "NVME_READ_QEMU"
+else
+ if [[ "${mode}" == "smmu" ]]; then
+ check "IORT stream configured for NVMe DMA" "smmu: enabled"
+ check "NVMe DMA window translated" "smmu_dma_window: nvme only, translation active"
+ check "NVMe DMA granted only as confined" "dma_gate: nvme granted (Confined), bus master on"
+ else
+ check "unsafe bypass build announced on serial" "WARNING: UNSAFE NVME DMA BYPASS BUILD"
+ check "unsafe bypass grant announced on serial" "WARNING: UNSAFE NVME DMA BYPASS ACTIVE"
+ check "NVMe DMA granted through the unsafe bypass" "dma_gate: nvme granted (UnsafeBypass)"
+ fi
+ check "NVMe bus master revoked after the read phase" "dma_gate: nvme bus master revoked"
+fi
+if [[ "${mode}" != "unsafe-bypass" ]]; then
+ check_absent "no unsafe DMA bypass in this image" "UNSAFE NVME DMA BYPASS"
+fi
+if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then
+ echo "FAIL panic or fault reported"
+ failed=1
+fi
+
+if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then
+ echo "---- serial console ----"
+ cat "${work}/serial.txt"
+fi
+if [[ "${mode}" == "unsafe-bypass" ]]; then
+ echo "WARNING: this was an UNSAFE NVME DMA BYPASS run (no SMMU confinement)."
+fi
+[[ "${failed}" == 0 ]] && echo "QEMU_NVME: PASS (${mode})" || { echo "QEMU_NVME: FAIL (${mode})"; exit 1; }