interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / docs / P3_NVME_READ_SUBSTRATE.md

352 lines · 16771 bytes Raw Blame History Rendered
1# D5 - P3 Native NVMe Read Substrate: adapter and wiring design
2
3Baseline: `aien-dev/aienux` @ `ff5de9c` (mirror `~/aienos-p3`).
4Lane: P3 Native NVMe Read Substrate. Deliverable: the native adapter/wiring that
5lets the AIENOS handoff image drive an NVMe controller directly after firmware
6exit, plus the QEMU harness `scripts/qemu_nvme_test.sh` (this directory's
7`qemu_nvme_test.sh`). **Read-only qualification.**
8
9> **Status: implemented and passing in QEMU (2026-09-25).** The module
10> `crates/aienos-boot/src/nvme_read.rs`, the `nvme-read` feature, the handoff
11> wiring, and `scripts/qemu_nvme_test.sh` are in this branch. The SMMU-confined
12> run and the fail-closed run both pass; see
13> [`evidence/p3_nvme_read_qemu_2026-09-25.md`](../evidence/p3_nvme_read_qemu_2026-09-25.md).
14> `scripts/verify_all.sh` is intentionally not edited; wiring the harness and
15> the `nvme-read` clippy check into it remains a small follow-up.
16
17## 0. Scope and explicit non-claims
18
19- The substrate issues **only** Identify (admin, opcode 0x06) and Read
20 (I/O, opcode 0x02) commands. The `nvme-read` build never calls
21 `write_blocks`, `flush`, format, namespace management, or set-features with
22 side effects.
23- **Write and flush are NOT claimed, proven, or exercised.** The driver's
24 `BlockDevice` impl (`crates/aienos-kernel/src/nvme/driver.rs:401`) does
25 expose `write_blocks`/`flush`; this lane deliberately leaves them untested.
26 The QEMU harness attaches a disposable raw image and the guest only reads it.
27- **No dependency on Store v1 or any Store file.** The module reads the raw
28 namespace through `aienos_kernel::nvme` only; nothing imports
29 `aienos_kernel::store` (see `crates/aienos-kernel/src/lib.rs:42`).
30- The device is a native PCIe function discovered through ECAM and driven with
31 MMIO + polled queues, mirroring the xHCI keyboard candidate
32 (`crates/aienos-boot/src/usb_keyboard.rs`), not a UEFI Block I/O protocol.
33
34## 1. Feature gating
35
36Mirror the `usb-keyboard` gating exactly
37(`crates/aienos-boot/Cargo.toml:18-38`).
38
39`crates/aienos-boot/Cargo.toml`:
40
41```toml
42# SEED/P3 candidate: polled native NVMe read after firmware exit.
43# Only scripts/qemu_nvme_test.sh enables it; hardware staging never does.
44nvme-read = ["handoff"]
45# UNSAFE. DEBUG ONLY. QEMU ONLY. Lets the NVMe function DMA straight to
46# physical memory with NO SMMU confinement when the platform has no SMMU.
47# Never compiled with hardware-staging; prints a warning on every boot.
48unsafe-debug-nvme-dma-without-smmu = ["nvme-read"]
49```
50
51`crates/aienos-boot/src/lib.rs` adds, next to the existing xHCI guard
52(`crates/aienos-boot/src/lib.rs:12-19`):
53
54```rust
55#[cfg(all(
56 feature = "unsafe-debug-nvme-dma-without-smmu",
57 feature = "hardware-staging"
58))]
59compile_error!(
60 "feature `unsafe-debug-nvme-dma-without-smmu` (unconfined DMA, QEMU debug \
61 only) cannot be combined with `hardware-staging`: no SMMU confinement \
62 means no DMA"
63);
64
65/// Whether this build carries the unsafe, QEMU-only NVMe DMA bypass.
66pub const UNSAFE_NVME_DMA_BYPASS: bool = cfg!(feature = "unsafe-debug-nvme-dma-without-smmu");
67```
68
69The module is declared in the handoff binary next to the keyboard module
70(`crates/aienos-boot/src/handoff.rs:469-470`):
71
72```rust
73#[cfg(feature = "nvme-read")]
74mod nvme_read;
75```
76
77## 2. New module `crates/aienos-boot/src/nvme_read.rs`
78
79The module's shape is a direct sibling of `usb_keyboard.rs`: pre-exit discovery,
80post-exit confinement, then `run()`.
81
82### 2.1 `NvmeLocation` - ECAM discovery of class 0x0108 and BAR0
83
84Pre-exit (`find_nvme()`), walk every `PciRootBridgeIo` handle exactly like
85`find_xhci()` (`usb_keyboard.rs:72-126`):
86
87- Read config dword 0 for the present check (`id & 0xffff != 0xffff`).
88- Read class/revision at offset `0x08`; the class code is bits 8..32.
89 NVMe is base class `0x01` (mass storage), sub-class `0x08` (NVM),
90 programming interface `0x02`. QEMU's `-device nvme` reports `0x010802`,
91 so match `(class_revision >> 8) & 0xffff == 0x0108` (accept any prog-if).
92 (Constants: `crates/aienos-kernel/src/pci.rs:20` defines `REG_CLASS_REVISION`.)
93- Decode a 64-bit memory BAR0 from config offsets `0x10` (low) and `0x14`
94 (high) into the MMIO base, as the xHCI walk reads its BAR pair
95 (`usb_keyboard.rs:104-114`). Reject an I/O-space BAR (low bit 0).
96
97```rust
98#[derive(Clone, Copy)]
99pub struct NvmeLocation {
100 segment: u16, bus: u8, device: u8, function: u8, mmio: u64,
101}
102
103impl NvmeLocation {
104 pub fn mmio_base(self) -> u64 { self.mmio }
105 pub fn ecam_location(self) -> (u16, u8) { (self.segment, self.bus) }
106 pub fn requester_id(self) -> u32 {
107 (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function)
108 }
109 pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option<u32> {
110 iort.stream_id_for(self.requester_id())
111 }
112 pub fn dma_window(self) -> (u64, usize) {
113 let base = core::ptr::addr_of!(DMA_ARENA) as u64;
114 (base & !0xfff, core::mem::size_of::<DmaArena>())
115 }
116}
117```
118
119`requester_id` / `stream_id` / `dma_window` mirror `XhciLocation`
120(`usb_keyboard.rs:59-68`). `requester_id` is exactly `Bdf::requester_id`
121(`crates/aienos-kernel/src/pci.rs:75`); `stream_id` uses
122`IortSmmu::stream_id_for` (`crates/aienos-kernel/src/acpi.rs:286`).
123
124### 2.2 `NativeRegisters` - Registers MMIO adapter
125
126The kernel driver is generic over `Registers`
127(`crates/aienos-kernel/src/nvme.rs:22`), which this adapter implements over
128`MmioReg` (`crates/aienos-kernel/src/arch/aarch64.rs:8-31`):
129
130```rust
131pub struct NativeRegisters { base: usize }
132
133impl aienos_kernel::nvme::Registers for NativeRegisters {
134 fn read32(&mut self, offset: u32) -> u32 {
135 MmioReg::<u32>::new(self.base + offset as usize).read()
136 }
137 fn write32(&mut self, offset: u32, value: u32) {
138 MmioReg::<u32>::new(self.base + offset as usize).write(value);
139 }
140}
141```
142
143### 2.3 `NativeDma` - static DMA arena implementing `DmaMemory`
144
145The driver owns DMA through the `DmaMemory` trait
146(`crates/aienos-kernel/src/nvme/driver.rs:63-67`), whose regions carry a
147physical address and a CPU byte view. The handoff identity-maps conventional
148memory, so the arena's virtual address **is** its physical address (the same
149assumption as `XhciLocation::dma_window`, `usb_keyboard.rs:65-68`).
150
151```rust
152const ARENA_BYTES: usize = 128 * 1024; // admin + I/O queues + transfer pages
153
154#[repr(C, align(4096))]
155struct DmaArena([u8; ARENA_BYTES]);
156
157static mut DMA_ARENA: DmaArena = DmaArena([0; ARENA_BYTES]);
158
159struct NativeDma { next: usize, end: usize }
160
161impl aienos_kernel::nvme::driver::DmaMemory for NativeDma {
162 fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
163 let base = core::ptr::addr_of_mut!(DMA_ARENA) as usize;
164 let aligned = (self.next + alignment - 1) & !(alignment - 1);
165 if aligned.checked_add(size).is_none_or(|e| e > self.end) {
166 return Err(NvmeError::Dma);
167 }
168 self.next = aligned + size;
169 let ptr = aligned as *mut u8;
170 // SAFETY: bump-allocated from the zeroed static arena, page aligned.
171 unsafe { core::ptr::write_bytes(ptr, 0, size) };
172 Ok(DmaRegion { physical: aligned as u64, bytes: unsafe {
173 core::slice::from_raw_parts_mut(ptr, size) }.to_vec() })
174 }
175 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { /* copy from identity */ }
176 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { /* copy to identity */ }
177}
178```
179
180`#[repr(C, align(4096))]` on the arena mirrors `DmaPage`
181(`crates/aienos-kernel/src/usb/xhci/controller.rs:38-41`). 128 KiB covers the
182driver's bounded allocations: admin SQ/CQ/Identify 3 x 4096
183(`driver.rs:112-114`), I/O CQ `depth*16` and SQ `depth*64` for `depth = 4`
184(`driver.rs:178-183`), a transfer region plus PRP list for a single 512-byte
185read (`driver.rs:307-324`).
186
187### 2.4 `NativeDelay` - bounded real-time waits
188
189`Delay::delay_us` (`driver.rs:18`) spins on the architectural counter using
190`counter_frequency_hz()` / `counter_ticks()`
191(`crates/aienos-kernel/src/arch/aarch64.rs:130,204`), so every controller wait
192is bounded in real time, matching the kernel's own design note
193(`driver.rs:14-15`).
194
195### 2.5 SMMU + `dma_gate` confinement
196
197Post-exit, in order (mirrors `usb_keyboard.rs:182-345` and
198`handoff.rs:1665-1672`):
199
2001. **Bus-master sweep before anything else.** `take_over_dma(nvme, mcfg)` builds
201 an `Ecam` adapter over the MCFG window
202 (`crates/aienos-kernel/src/acpi.rs:380`, adapter pattern
203 `usb_keyboard.rs:147-169`) and calls
204 `dma_gate::sweep_bus_master` (`dma_gate.rs:150`) so every endpoint's Bus
205 Master Enable starts clear.
2062. **SMMU domain for the NVMe stream.** `configure_smmu_for_nvme` is a
207 parameterized twin of `configure_smmu_for_xhci` (`handoff.rs:206-282`):
208 resolve `stream_id` from IORT (`acpi.rs:286`), build policy with
209 `aienos_kernel::smmu::build_dma_policy` over the **NVMe arena window**
210 (`dma_window()` above) only, then `configure_linear_stream`. The report
211 line is `smmu_dma_window: nvme only, translation active`.
2123. **Gate.** `dma_gate::dma_grant(smmu_ready, smmu_present, UNSAFE_NVME_DMA_BYPASS)`
213 (`dma_gate.rs:68`). Only on `Ok(Confined)` (or `Ok(UnsafeBypass)`) is
214 `dma_gate::with_bus_master(command)` written. On denial the module logs
215 `dma_gate: nvme denied ({denied:?}), bus master stays off` and
216 `nvme: unavailable (SMMU DMA isolation not active)`, then returns with the
217 controller never enabled.
2184. **Revocation.** After the phase, clear Bus Master Enable again and emit
219 `dma_gate: nvme bus master revoked` (pattern `usb_keyboard.rs:226-241`).
220
221Unsafe bypass announcement (QEMU only), mirroring
222`usb_keyboard.rs:35-37,257-259,326-331`:
223
224```rust
225const UNSAFE_NVME_BANNER: &str =
226 "\nWARNING: UNSAFE NVME DMA BYPASS BUILD (unsafe-debug-nvme-dma-without-smmu): \
227 NVMe DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n";
228// on UnsafeBypass grant:
229"WARNING: UNSAFE NVME DMA BYPASS ACTIVE: no SMMU on this machine, NVMe DMA \
230 reaches physical memory UNCONFINED (QEMU debug only)\n"
231```
232
233### 2.6 `run()` - the read phase and the six markers
234
235`run(nvme, takeover, &mut screen, smmu_ready, smmu_base, smmu_stream_id, events)`
236uses the same `say()` console+screen helper as `usb_keyboard.rs:136-143`.
237
238Controller bring-up: `NvmeController::init(NativeRegisters, NativeDma,
239NativeDelay)` (`driver.rs:106`) performs the reset/ready handshake, builds the
240admin queues, and runs Identify Controller + Identify Namespace 1
241(`driver.rs:144-171`). Then `create_io_queues(4)` (`driver.rs:174`) creates the
242polled QID-1 CQ/SQ (`create_io_cq` sets PC=1, IEN=0; `nvme.rs:106`).
243
244Read: `BlockDevice::read_blocks(sentinel_lba, &mut [u8; 512])`
245(`driver.rs:408`) issues a single Read (opcode 0x02, `nvme.rs:128`) over the
246identity-mapped arena. The module then verifies the bytes **natively** against
247the expected 512-byte sentinel and computes the SHA-256 with
248`aienos_kernel::crypto::sha256::hash` (`crypto/mod.rs:9`,
249`aienos-crypto/src/sha256.rs:198`). No host round-trip is trusted.
250
251## 3. Handoff wiring (`crates/aienos-boot/src/handoff.rs`)
252
253- **Pre-exit:** `let nvme = nvme_read::find_nvme();` beside the xHCI discovery
254 (`handoff.rs:1551-1552`). BAR0 must be mapped before post-exit MMIO.
255- **MMU map:** extend `enter_kernel_mmu`'s device list
256 (`handoff.rs:307-348`) with the NVMe BAR0 range (0x10000 bytes, as the xHCI
257 BAR uses) and the NVMe ECAM window, and with the SMMU page when present.
258 Because the current signature has one `xhci_mmio` slot, generalize it to a
259 caller-built `&[AddressRange]` (`extra_mmio`) so `usb-keyboard` and
260 `nvme-read` can coexist; the ECAM window is derived exactly as at
261 `handoff.rs:1640-1652`.
262- **Post-exit:** after `configure_smmu_for_xhci` (`handoff.rs:1670-1672`),
263 run `nvme_read::take_over_dma(nvme, acpi_facts.mcfg)` and
264 `configure_smmu_for_nvme(...)`, then call `nvme_read::run(...)` after the
265 final report and the optional keyboard phase (`handoff.rs:1975-1987`).
266
267Pre-exit facts reused unchanged: MCFG table + ECAM window (`acpi.rs:380`),
268IORT SMMUv3 (`acpi.rs:297`), and `bus_ranges` (`handoff.rs:840`).
269
270## 4. Serial markers (exact strings the kernel emits)
271
272Emitted through `say()` to the SPCR console during the NVMe phase. The six
273required markers, with their detail (PASS shown; on failure the same prefix is
274printed with `FAIL` and the reason):
275
276```text
277NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x10010000)
278NVME_IDENTIFY_QEMU: PASS (vid=0x1b36 did=0x0010 nsid=1)
279NVME_GEOMETRY_QEMU: PASS (nsid=1 block_count=131072 block_size=512)
280NVME_READ_QEMU: PASS (lba=2048 blocks=1 bytes=512 sha256=8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1)
281NVME_BOUNDS_QEMU: PASS (lba=131072 rejected OutOfRange no_command)
282NVME_ERROR_QEMU: PASS (identify nsid=0xffffffff rejected status=nonzero)
283```
284
285Supporting lines (not required, used by the harness for isolation):
286
287```text
288nvme: class=0x0108 seg=0000 bus=00 device=02 function=00 bar0=0x... # discovery detail
289dma_sweep: seg 0000 bus 00-ff ... # dma_gate::sweep_bus_master
290dma_gate: nvme granted (Confined), bus master on # or UnsafeBypass / denied
291smmu: enabled base=0x... stream_id=0x...
292smmu_dma_window: nvme only, translation active
293dma_gate: nvme bus master revoked
294nvme: unavailable (SMMU DMA isolation not active)
295```
296
297Marker semantics:
298
299| Marker | Kernel action |
300| --- | --- |
301| `NVME_DISCOVERY_QEMU` | ECAM walk found a function whose class code is base/sub `0x0108`; BAR0 decoded. PASS = found + BAR0 mapped. |
302| `NVME_IDENTIFY_QEMU` | `NvmeController::init` reached CSTS.RDY and Identify Controller + Identify Namespace 1 returned status 0 (`driver.rs:144-171`). |
303| `NVME_GEOMETRY_QEMU` | Namespace 1 reports `block_count == 131072`, `block_size == 512`, exactly the image geometry. |
304| `NVME_READ_QEMU` | Read of LBA 2048 returned 512 bytes byte-identical to the sentinel, and `sha256 == 8b688adc…`. |
305| `NVME_BOUNDS_QEMU` | `read_blocks(131072, …)` returned `BlockError::OutOfRange` with **no** I/O doorbell write (client-side bounds, `driver.rs:284-290`). |
306| `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. |
307
308## 5. Exact expected sentinel geometry
309
310| Property | Value |
311| --- | --- |
312| Image size | 64 MiB = 67,108,864 bytes, disposable raw |
313| LBA size | 512 bytes |
314| Total LBAs | 131,072 |
315| Sentinel LBA | 2048 (byte offset 1,048,576 = 1 MiB) |
316| Sentinel length | 1 LBA = 512 bytes |
317| Sentinel payload | 16-byte magic `AIENOS-NVME-SENT` repeated 32 times (no newline) |
318| Sentinel SHA-256 | `8b688adcb13bef657e868313fb149e7e92e664b5f09fbd32f99d9cabf756fdf1` |
319| Bounds LBA (out of range) | 131072 (== block_count) |
320| Error NSID | 0xffffffff (unallocated) |
321
322The host harness builds the same payload with `printf` + `truncate` + `dd`,
323hashes it with `sha256sum`, and requires the kernel's `NVME_READ_QEMU` line to
324contain that host-computed hash, so a wrong or stale image cannot pass.
325
326## 6. Harness mapping (`qemu_nvme_test.sh`)
327
328- Builds `-p aienos-boot --target aarch64-unknown-uefi --features nvme-read
329 --bin aienos-handoff --target-dir target/qemu-nvme` with `AIENOS_COMMIT`
330 and `AIENOS_RESTART_SECS=1` (as `qemu_keyboard_test.sh:65-68`).
331- Boots the same AAVMF image and `virt,virtualization=on,gic-version=3`
332 machine, defaulting to `iommu=smmuv3`; attaches the sentinel image as
333 `-device nvme,drive=nvme0,serial=aienos-nvme-test`.
334- Waits for `report_kind: pre_exit`, then for `NVME_ERROR_QEMU: PASS` (or a
335 panic/fault), then checks the six markers plus the SMMU/`dma_gate` lines and
336 prints `QEMU_NVME: PASS`/`FAIL` with a non-zero exit on failure.
337- Fail-closed mode (`AIENOS_QEMU_SMMU=0`, normal build) requires the six
338 markers to be **absent** and the denial lines to be present. Unsafe mode
339 (`AIENOS_UNSAFE_DMA_BYPASS=1`) requires the bypass banners plus the six
340 markers and prints a warning.
341
342## 7. Follow-ups (not done in this lane)
343
344- **`scripts/verify_all.sh` is not edited.** Adding a QEMU step for this
345 harness and `nvme-read` to the aarch64 clippy feature loop
346 (`verify_all.sh:70-73`) is a separate integration change.
347- **Host unit tests:** add `aienos-boot`/kernel tests for the class-0x0108
348 match and the arena bump allocator; the kernel `nvme` module already has a
349 full fake-controller suite (`driver.rs:425-977`) the native adapter must not
350 disturb.
351- **Write/flush stay out of scope** until a separate lane can prove
352 confinement end-to-end for mutating media commands.