aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-boot / src / nvme_read.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! P3 native NVMe read substrate (read-only qualification). |
| 17 | //! |
| 18 | //! Built only with the `nvme-read` feature, which `scripts/qemu_nvme_test.sh` |
| 19 | //! enables and hardware staging never does. After firmware exit this module |
| 20 | //! drives a PCIe NVMe controller with the polled, host-tested |
| 21 | //! [`aienos_kernel::nvme`] driver over a native MMIO adapter and a static DMA |
| 22 | //! arena, then reads one sentinel LBA and verifies it natively. |
| 23 | //! |
| 24 | //! Read-only: this module issues Identify (admin, 0x06) and Read (I/O, 0x02) |
| 25 | //! only. It never calls `write_blocks`, `flush`, format, or any mutating |
| 26 | //! command. Write and flush are not claimed here. |
| 27 | //! |
| 28 | //! DMA rule (M3): no SMMU confinement means no DMA. [`take_over_dma`] clears |
| 29 | //! Bus Master Enable on every endpoint of the controller's PCI segment before |
| 30 | //! any SMMU or driver setup, and [`run`] sets it again only when |
| 31 | //! [`dma_gate::dma_grant`] allows it. |
| 32 | |
| 33 | #[cfg(feature = "store-qual")] |
| 34 | use crate::store_qual::{ |
| 35 | genesis_units, BoundedNvme, CONFIG_LBA, CONFIG_LBA_512, MODE_RUN_512B, MODE_VERIFY, |
| 36 | MODE_VERIFY_512B, STORE_BASE_LBA, STORE_BASE_LBA_512, STORE_REGION_BLOCKS, |
| 37 | STORE_REGION_BLOCKS_512, |
| 38 | }; |
| 39 | use aienos_kernel::acpi::{self, EcamWindow}; |
| 40 | use aienos_kernel::arch::aarch64::{ |
| 41 | clean_dcache_range, clean_invalidate_dcache_range, counter_frequency_hz, counter_ticks, MmioReg, |
| 42 | }; |
| 43 | use aienos_kernel::block::BlockDevice; |
| 44 | use aienos_kernel::console::EarlyConsole; |
| 45 | use aienos_kernel::display::Screen; |
| 46 | use aienos_kernel::dma_gate::{self, BusMasterSweep, DmaGrant, PciConfig, PCI_COMMAND}; |
| 47 | use aienos_kernel::nvme::atomicity::AtomicityDecision; |
| 48 | use aienos_kernel::nvme::driver::{Delay, DmaMemory, DmaRegion, NvmeController, NvmeError}; |
| 49 | use aienos_kernel::nvme::Registers; |
| 50 | use core::fmt::Write; |
| 51 | use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; |
| 52 | use uefi::proto::pci::root_bridge::PciRootBridgeIo; |
| 53 | use uefi::proto::pci::PciIoAddress; |
| 54 | |
| 55 | /// Printed on every boot of an image built with the unsafe NVMe DMA bypass. |
| 56 | const UNSAFE_NVME_BANNER: &str = |
| 57 | "\nWARNING: UNSAFE NVME DMA BYPASS BUILD (unsafe-debug-nvme-dma-without-smmu): \ |
| 58 | NVMe DMA may run WITHOUT SMMU confinement. Debug only, QEMU only.\n"; |
| 59 | |
| 60 | /// Sentinel the qualification image holds: 32 repeats of a 16-byte magic in |
| 61 | /// one 512-byte LBA. |
| 62 | pub const SENTINEL_MAGIC: &[u8; 16] = b"AIENOS-NVME-SENT"; |
| 63 | pub const SENTINEL_LBA: u64 = 2048; |
| 64 | |
| 65 | /// Write/durability target: a deterministic read-write LBA distinct from the |
| 66 | /// read-only sentinel, and the 512-byte pattern written and verified there. |
| 67 | #[cfg(feature = "nvme-write")] |
| 68 | const RW_LBA: u64 = 4096; |
| 69 | #[cfg(feature = "nvme-write")] |
| 70 | const RW_MAGIC: &[u8; 16] = b"AIENOS-NVME-RW01"; |
| 71 | |
| 72 | const ARENA_BYTES: usize = 512 * 1024; |
| 73 | |
| 74 | #[repr(C, align(4096))] |
| 75 | struct DmaArena([u8; ARENA_BYTES]); |
| 76 | |
| 77 | static mut DMA_ARENA: DmaArena = DmaArena([0; ARENA_BYTES]); |
| 78 | |
| 79 | /// Where the NVMe controller sits, found before firmware exit. |
| 80 | #[derive(Clone, Copy)] |
| 81 | pub struct NvmeLocation { |
| 82 | segment: u16, |
| 83 | bus: u8, |
| 84 | device: u8, |
| 85 | function: u8, |
| 86 | vendor: u16, |
| 87 | device_id: u16, |
| 88 | mmio: u64, |
| 89 | } |
| 90 | |
| 91 | impl NvmeLocation { |
| 92 | pub fn mmio_base(self) -> u64 { |
| 93 | self.mmio |
| 94 | } |
| 95 | pub fn ecam_location(self) -> (u16, u8) { |
| 96 | (self.segment, self.bus) |
| 97 | } |
| 98 | pub fn requester_id(self) -> u32 { |
| 99 | (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function) |
| 100 | } |
| 101 | pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option<u32> { |
| 102 | iort.stream_id_for(self.requester_id()) |
| 103 | } |
| 104 | pub fn dma_window(self) -> (u64, usize) { |
| 105 | let base = core::ptr::addr_of!(DMA_ARENA) as u64; |
| 106 | (base & !0xfff, core::mem::size_of::<DmaArena>()) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// Walk every root bridge for the first NVMe controller (class base 0x01, |
| 111 | /// sub-class 0x08). Pre-exit only; read-only config access. |
| 112 | pub fn find_nvme() -> Option<NvmeLocation> { |
| 113 | for handle in uefi::boot::find_handles::<PciRootBridgeIo>().ok()? { |
| 114 | let params = OpenProtocolParams { |
| 115 | handle, |
| 116 | agent: uefi::boot::image_handle(), |
| 117 | controller: None, |
| 118 | }; |
| 119 | let Ok(mut root) = (unsafe { |
| 120 | uefi::boot::open_protocol::<PciRootBridgeIo>( |
| 121 | params, |
| 122 | OpenProtocolAttributes::GetProtocol, |
| 123 | ) |
| 124 | }) else { |
| 125 | continue; |
| 126 | }; |
| 127 | let (bus_min, bus_max) = crate::bus_ranges(&mut root).unwrap_or((0, 0)); |
| 128 | for bus in bus_min..=bus_max { |
| 129 | for device in 0..32u8 { |
| 130 | for function in 0..8u8 { |
| 131 | let address = PciIoAddress::new(bus, device, function); |
| 132 | let mut read = |offset| { |
| 133 | root.pci() |
| 134 | .read_one::<u32>(address.with_register(offset)) |
| 135 | .ok() |
| 136 | }; |
| 137 | let Some(id) = read(0).filter(|id| id & 0xffff != 0xffff) else { |
| 138 | if function == 0 { |
| 139 | break; |
| 140 | } |
| 141 | continue; |
| 142 | }; |
| 143 | if let (Some(class), Some(low), Some(high)) = |
| 144 | (read(0x08), read(0x10), read(0x14)) |
| 145 | { |
| 146 | // Config dword 0x08 is base<<24 | subclass<<16 | prog_if<<8 | rev. |
| 147 | let class_code = class >> 16; |
| 148 | // 0x0108: mass storage, NVM. Accept any programming |
| 149 | // interface (QEMU reports 0x010802). |
| 150 | if class_code == 0x0108 && low & 0x1 == 0 { |
| 151 | let is_64 = low & 0x7 == 0x4; |
| 152 | let mmio = if is_64 { |
| 153 | (u64::from(high) << 32) | u64::from(low & !0xf) |
| 154 | } else { |
| 155 | u64::from(low & !0xf) |
| 156 | }; |
| 157 | if mmio != 0 { |
| 158 | return Some(NvmeLocation { |
| 159 | segment: root.segment_nr() as u16, |
| 160 | bus, |
| 161 | device, |
| 162 | function, |
| 163 | vendor: (id & 0xffff) as u16, |
| 164 | device_id: (id >> 16) as u16, |
| 165 | mmio, |
| 166 | }); |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | let multi = read(0x0c).is_some_and(|v| v & 0x80_0000 != 0); |
| 171 | if function == 0 && !multi { |
| 172 | break; |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | None |
| 179 | } |
| 180 | |
| 181 | fn console() -> Option<EarlyConsole> { |
| 182 | crate::CONSOLE |
| 183 | .try_lock() |
| 184 | .and_then(|k| *k) |
| 185 | .and_then(EarlyConsole::from_kind) |
| 186 | } |
| 187 | |
| 188 | /// Write `text` to the SPCR console and the screen. |
| 189 | fn say(screen: &mut Option<Screen>, text: &str) { |
| 190 | if let Some(console) = console() { |
| 191 | console.write_str(text); |
| 192 | } |
| 193 | if let Some(s) = screen.as_mut() { |
| 194 | let _ = s.write_str(text); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Config space of one ECAM window, reached through the kernel identity map. |
| 199 | struct Ecam(EcamWindow); |
| 200 | |
| 201 | impl PciConfig for Ecam { |
| 202 | fn read32(&mut self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u32> { |
| 203 | let addr = self.0.config_address(bus, device, function, offset)?; |
| 204 | // SAFETY: `config_address` returned an address inside this ECAM window, |
| 205 | // which the kernel identity map covers as device memory. |
| 206 | Some(unsafe { MmioReg::<u32>::new(addr as usize) }.read()) |
| 207 | } |
| 208 | fn write16(&mut self, bus: u8, device: u8, function: u8, offset: u16, value: u16) { |
| 209 | if let Some(addr) = self.0.config_address(bus, device, function, offset) { |
| 210 | // SAFETY: as in `read32`. |
| 211 | unsafe { MmioReg::<u16>::new(addr as usize) }.write(value); |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | impl Ecam { |
| 217 | fn command(&mut self, at: &NvmeLocation) -> Option<u16> { |
| 218 | self.read32(at.bus, at.device, at.function, PCI_COMMAND) |
| 219 | .map(|v| v as u16) |
| 220 | } |
| 221 | fn set_command(&mut self, at: &NvmeLocation, value: u16) { |
| 222 | self.write16(at.bus, at.device, at.function, PCI_COMMAND, value); |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /// What [`take_over_dma`] did to the controller's PCI segment. |
| 227 | #[derive(Clone, Copy)] |
| 228 | pub struct DmaTakeover { |
| 229 | window: EcamWindow, |
| 230 | sweep: BusMasterSweep, |
| 231 | } |
| 232 | |
| 233 | /// Post-exit, before any SMMU or driver setup: clear Bus Master Enable on |
| 234 | /// every endpoint in the NVMe ECAM window. |
| 235 | pub fn take_over_dma(nvme: Option<NvmeLocation>, mcfg: Option<&[u8]>) -> Option<DmaTakeover> { |
| 236 | let at = nvme?; |
| 237 | let window = acpi::mcfg_window(mcfg?, at.segment, at.bus) |
| 238 | .ok() |
| 239 | .flatten()?; |
| 240 | let sweep = dma_gate::sweep_bus_master(&mut Ecam(window), window.start_bus, window.end_bus); |
| 241 | Some(DmaTakeover { window, sweep }) |
| 242 | } |
| 243 | |
| 244 | fn report_takeover(screen: &mut Option<Screen>, takeover: &DmaTakeover) { |
| 245 | let (w, s) = (&takeover.window, &takeover.sweep); |
| 246 | let mut line = aienos_kernel::report::ReportBuf::<256>::new(); |
| 247 | let _ = writeln!( |
| 248 | line, |
| 249 | "dma_sweep: seg {:04x} bus {:02x}-{:02x} functions={} bridges={} bridges_bme={} \ |
| 250 | endpoints_bme_found={} still_enabled={}", |
| 251 | w.segment, |
| 252 | w.start_bus, |
| 253 | w.end_bus, |
| 254 | s.functions, |
| 255 | s.bridges, |
| 256 | s.bridges_bus_master, |
| 257 | s.endpoints_bus_master, |
| 258 | s.still_enabled |
| 259 | ); |
| 260 | say(screen, line.as_str()); |
| 261 | } |
| 262 | |
| 263 | /// Clear Bus Master Enable on the controller again (revoke its DMA). |
| 264 | fn revoke_dma(screen: &mut Option<Screen>, ecam: &mut Ecam, at: &NvmeLocation) { |
| 265 | if let Some(command) = ecam.command(at) { |
| 266 | ecam.set_command(at, dma_gate::without_bus_master(command)); |
| 267 | } |
| 268 | let off = ecam |
| 269 | .command(at) |
| 270 | .is_some_and(|c| !dma_gate::bus_master_enabled(c)); |
| 271 | say( |
| 272 | screen, |
| 273 | if off { |
| 274 | "dma_gate: nvme bus master revoked\n" |
| 275 | } else { |
| 276 | "dma_gate: nvme bus master revoke FAILED\n" |
| 277 | }, |
| 278 | ); |
| 279 | } |
| 280 | |
| 281 | /// Registers adapter over the controller's MMIO BAR. |
| 282 | struct NativeRegisters { |
| 283 | base: usize, |
| 284 | } |
| 285 | |
| 286 | impl Registers for NativeRegisters { |
| 287 | fn read32(&mut self, offset: u32) -> u32 { |
| 288 | // SAFETY: `base` is the NVMe BAR the PCI takeover assigned, covered by |
| 289 | // the identity map, and the driver passes only NVMe register offsets. |
| 290 | unsafe { MmioReg::<u32>::new(self.base + offset as usize) }.read() |
| 291 | } |
| 292 | fn write32(&mut self, offset: u32, value: u32) { |
| 293 | // SAFETY: as in `read32`. |
| 294 | unsafe { MmioReg::<u32>::new(self.base + offset as usize) }.write(value); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | /// Bump allocator over the static, identity-mapped, cache-coherent DMA arena. |
| 299 | struct NativeDma { |
| 300 | cursor: usize, |
| 301 | end: usize, |
| 302 | } |
| 303 | |
| 304 | impl NativeDma { |
| 305 | fn new() -> Self { |
| 306 | let base = core::ptr::addr_of!(DMA_ARENA) as usize; |
| 307 | Self { |
| 308 | cursor: base, |
| 309 | end: base + ARENA_BYTES, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | fn offset_of(physical: u64) -> Option<usize> { |
| 314 | let base = core::ptr::addr_of!(DMA_ARENA) as u64; |
| 315 | let offset = physical.checked_sub(base)?; |
| 316 | (offset < ARENA_BYTES as u64).then_some(offset as usize) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | impl DmaMemory for NativeDma { |
| 321 | fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> { |
| 322 | if alignment == 0 || !alignment.is_power_of_two() { |
| 323 | return Err(NvmeError::Dma); |
| 324 | } |
| 325 | let aligned = self |
| 326 | .cursor |
| 327 | .checked_add(alignment - 1) |
| 328 | .map(|v| v & !(alignment - 1)) |
| 329 | .ok_or(NvmeError::Dma)?; |
| 330 | if aligned.checked_add(size).is_none_or(|end| end > self.end) { |
| 331 | return Err(NvmeError::Dma); |
| 332 | } |
| 333 | self.cursor = aligned + size; |
| 334 | // SAFETY: bump-allocated inside the live static arena, never shared. |
| 335 | unsafe { core::ptr::write_bytes(aligned as *mut u8, 0, size) }; |
| 336 | Ok(DmaRegion { |
| 337 | physical: aligned as u64, |
| 338 | bytes: alloc::vec![0u8; size], |
| 339 | }) |
| 340 | } |
| 341 | |
| 342 | fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { |
| 343 | let offset = Self::offset_of(physical).ok_or(NvmeError::Dma)?; |
| 344 | if offset + output.len() > ARENA_BYTES { |
| 345 | return Err(NvmeError::Dma); |
| 346 | } |
| 347 | // The device wrote this memory; drop stale cache lines before reading. |
| 348 | let base = core::ptr::addr_of!(DMA_ARENA) as usize; |
| 349 | clean_invalidate_dcache_range(base + offset, output.len()); |
| 350 | // SAFETY: in-bounds inside the live arena; copy into the caller buffer. |
| 351 | unsafe { |
| 352 | core::ptr::copy_nonoverlapping( |
| 353 | (base + offset) as *const u8, |
| 354 | output.as_mut_ptr(), |
| 355 | output.len(), |
| 356 | ) |
| 357 | }; |
| 358 | Ok(()) |
| 359 | } |
| 360 | |
| 361 | fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { |
| 362 | let offset = Self::offset_of(physical).ok_or(NvmeError::Dma)?; |
| 363 | if offset + input.len() > ARENA_BYTES { |
| 364 | return Err(NvmeError::Dma); |
| 365 | } |
| 366 | let base = core::ptr::addr_of!(DMA_ARENA) as usize; |
| 367 | // SAFETY: in-bounds inside the live arena; copy from the caller buffer. |
| 368 | unsafe { |
| 369 | core::ptr::copy_nonoverlapping(input.as_ptr(), (base + offset) as *mut u8, input.len()) |
| 370 | }; |
| 371 | // Make the CPU writes visible to the controller before it reads them. |
| 372 | clean_dcache_range(base + offset, input.len()); |
| 373 | Ok(()) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// Real-time delay bounded by the architectural counter. |
| 378 | struct NativeDelay; |
| 379 | |
| 380 | impl Delay for NativeDelay { |
| 381 | fn delay_us(&mut self, us: u32) { |
| 382 | let hz = counter_frequency_hz(); |
| 383 | if hz == 0 { |
| 384 | for _ in 0..us { |
| 385 | core::hint::spin_loop(); |
| 386 | } |
| 387 | return; |
| 388 | } |
| 389 | let ticks = hz.saturating_mul(u64::from(us)) / 1_000_000; |
| 390 | let start = counter_ticks(); |
| 391 | while counter_ticks().wrapping_sub(start) < ticks { |
| 392 | core::hint::spin_loop(); |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | fn hex_digest(out: &mut impl Write, digest: &[u8; 32]) { |
| 398 | for byte in digest { |
| 399 | let _ = write!(out, "{byte:02x}"); |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// Post-exit: bring up the controller, read the sentinel LBA, and report. |
| 404 | #[allow(clippy::too_many_arguments)] |
| 405 | /// Render a power-fail atomicity decision into a report line. |
| 406 | fn describe_atomicity(buf: &mut aienos_kernel::report::ReportBuf<512>, d: AtomicityDecision) { |
| 407 | match d { |
| 408 | AtomicityDecision::Atomic { effective_blocks } => { |
| 409 | let _ = write!(buf, "atomic(effective={effective_blocks})"); |
| 410 | } |
| 411 | AtomicityDecision::NotAtomic(reason) => { |
| 412 | let _ = write!(buf, "not_atomic({reason:?})"); |
| 413 | } |
| 414 | AtomicityDecision::Unknown(reason) => { |
| 415 | let _ = write!(buf, "unknown({reason:?})"); |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | pub fn run( |
| 421 | nvme: Option<NvmeLocation>, |
| 422 | takeover: Option<DmaTakeover>, |
| 423 | screen: &mut Option<Screen>, |
| 424 | smmu_ready: bool, |
| 425 | smmu_base: Option<u64>, |
| 426 | smmu_stream_id: Option<u32>, |
| 427 | smmu_events: *const [[u64; 4]; 16], |
| 428 | ) { |
| 429 | if aienos_boot::UNSAFE_NVME_DMA_BYPASS { |
| 430 | say(screen, UNSAFE_NVME_BANNER); |
| 431 | } |
| 432 | let Some(at) = nvme else { |
| 433 | say( |
| 434 | screen, |
| 435 | "NVME_DISCOVERY_QEMU: FAIL (no class 0x0108 function)\n", |
| 436 | ); |
| 437 | return; |
| 438 | }; |
| 439 | let mut line = aienos_kernel::report::ReportBuf::<256>::new(); |
| 440 | let _ = writeln!( |
| 441 | line, |
| 442 | "NVME_DISCOVERY_QEMU: PASS (class=0x0108 seg={:04x} bus={:02x} device={:02x} function={:02x} bar0={:#x})", |
| 443 | at.segment, at.bus, at.device, at.function, at.mmio |
| 444 | ); |
| 445 | say(screen, line.as_str()); |
| 446 | let Some(takeover) = takeover else { |
| 447 | say( |
| 448 | screen, |
| 449 | "nvme: unavailable (no ECAM window for the controller; DMA not granted)\n", |
| 450 | ); |
| 451 | return; |
| 452 | }; |
| 453 | report_takeover(screen, &takeover); |
| 454 | let mut ecam = Ecam(takeover.window); |
| 455 | let Some(command) = ecam.command(&at) else { |
| 456 | say(screen, "nvme: unavailable (config space unreadable)\n"); |
| 457 | return; |
| 458 | }; |
| 459 | if dma_gate::bus_master_enabled(command) { |
| 460 | say(screen, "nvme: unavailable (bus master would not clear)\n"); |
| 461 | return; |
| 462 | } |
| 463 | let grant = match dma_gate::dma_grant( |
| 464 | smmu_ready, |
| 465 | smmu_base.is_some(), |
| 466 | aienos_boot::UNSAFE_NVME_DMA_BYPASS, |
| 467 | ) { |
| 468 | Ok(grant) => grant, |
| 469 | Err(denied) => { |
| 470 | let mut msg = aienos_kernel::report::ReportBuf::<200>::new(); |
| 471 | let _ = writeln!( |
| 472 | msg, |
| 473 | "dma_gate: nvme denied ({denied:?}), bus master stays off\n\ |
| 474 | nvme: unavailable (SMMU DMA isolation not active)" |
| 475 | ); |
| 476 | say(screen, msg.as_str()); |
| 477 | return; |
| 478 | } |
| 479 | }; |
| 480 | let dma_mode = match grant { |
| 481 | DmaGrant::Confined => { |
| 482 | let mut smmu_line = aienos_kernel::report::ReportBuf::<160>::new(); |
| 483 | let _ = writeln!( |
| 484 | smmu_line, |
| 485 | "smmu: enabled base={:#x} stream_id={:#x}", |
| 486 | smmu_base.unwrap_or(0), |
| 487 | smmu_stream_id.unwrap_or(0) |
| 488 | ); |
| 489 | say(screen, smmu_line.as_str()); |
| 490 | say(screen, "smmu_dma_window: nvme only, translation active\n"); |
| 491 | "smmu-translated" |
| 492 | } |
| 493 | DmaGrant::UnsafeBypass => { |
| 494 | say( |
| 495 | screen, |
| 496 | "WARNING: UNSAFE NVME DMA BYPASS ACTIVE: no SMMU on this machine, NVMe DMA \ |
| 497 | reaches physical memory UNCONFINED (QEMU debug only)\n", |
| 498 | ); |
| 499 | "UNSAFE-identity-no-smmu" |
| 500 | } |
| 501 | }; |
| 502 | let mut mode = aienos_kernel::report::ReportBuf::<256>::new(); |
| 503 | let _ = writeln!( |
| 504 | mode, |
| 505 | "dma_gate: nvme granted ({grant:?}), bus master on\n\ |
| 506 | nvme_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}", |
| 507 | core::ptr::addr_of!(DMA_ARENA) as usize, |
| 508 | ARENA_BYTES |
| 509 | ); |
| 510 | ecam.set_command(&at, dma_gate::with_bus_master(command)); |
| 511 | say(screen, mode.as_str()); |
| 512 | |
| 513 | let registers = NativeRegisters { |
| 514 | base: at.mmio as usize, |
| 515 | }; |
| 516 | let dma = NativeDma::new(); |
| 517 | let mut controller = match NvmeController::init(registers, dma, NativeDelay) { |
| 518 | Ok(controller) => controller, |
| 519 | Err(error) => { |
| 520 | let mut msg = aienos_kernel::report::ReportBuf::<256>::new(); |
| 521 | let _ = writeln!(msg, "NVME_IDENTIFY_QEMU: FAIL (init {error:?})"); |
| 522 | say(screen, msg.as_str()); |
| 523 | revoke_dma(screen, &mut ecam, &at); |
| 524 | report_smmu_fault(screen, smmu_base, smmu_stream_id, smmu_events); |
| 525 | return; |
| 526 | } |
| 527 | }; |
| 528 | let mut identified = aienos_kernel::report::ReportBuf::<256>::new(); |
| 529 | let _ = writeln!( |
| 530 | identified, |
| 531 | "NVME_IDENTIFY_QEMU: PASS (vid={:#06x} did={:#06x} nsid=1)", |
| 532 | at.vendor, at.device_id |
| 533 | ); |
| 534 | say(screen, identified.as_str()); |
| 535 | |
| 536 | let block_count = controller.block_count(); |
| 537 | let block_size = controller.block_size(); |
| 538 | let mut geometry = aienos_kernel::report::ReportBuf::<256>::new(); |
| 539 | let _ = writeln!( |
| 540 | geometry, |
| 541 | "NVME_GEOMETRY_QEMU: PASS (nsid=1 block_count={block_count} block_size={block_size})" |
| 542 | ); |
| 543 | say(screen, geometry.as_str()); |
| 544 | |
| 545 | // NVMe 1.4 power-fail atomicity observation and System Store root-write |
| 546 | // eligibility. The acceptance marker is emitted only when both Store |
| 547 | // superblock slots satisfy the complete predicate. |
| 548 | if let Some(a) = controller.atomicity() { |
| 549 | let mut fields = aienos_kernel::report::ReportBuf::<512>::new(); |
| 550 | let _ = writeln!( |
| 551 | fields, |
| 552 | "NVME_ATOMICITY_IDENTIFY_QEMU: block_size={} lbads={} awupf_raw={} nawupf_raw={} nabspf_raw={} nabo_blocks={} effective_pf_blocks={} boundary_blocks={}", |
| 553 | a.lba_bytes, |
| 554 | a.lba_bytes.trailing_zeros(), |
| 555 | a.awupf_raw.map_or(-1, i32::from), |
| 556 | a.nawupf_raw.map_or(-1, i32::from), |
| 557 | a.nabspf_raw.map_or(-1, i32::from), |
| 558 | a.nabo_blocks, |
| 559 | a.effective_power_fail_blocks().map_or(-1, |v| v as i64), |
| 560 | a.boundary_blocks().map_or(-1, |v| v as i64), |
| 561 | ); |
| 562 | say(screen, fields.as_str()); |
| 563 | |
| 564 | let slot0 = a.store_root_decision(0); |
| 565 | let slot1 = a.store_root_decision(1); |
| 566 | let both_atomic = matches!(slot0, AtomicityDecision::Atomic { .. }) |
| 567 | && matches!(slot1, AtomicityDecision::Atomic { .. }); |
| 568 | let mut decision = aienos_kernel::report::ReportBuf::<512>::new(); |
| 569 | let _ = write!( |
| 570 | decision, |
| 571 | "NVME_STORE_ROOT_ATOMICITY_QEMU: {} (slot0=", |
| 572 | if both_atomic { "PASS" } else { "FAIL" } |
| 573 | ); |
| 574 | describe_atomicity(&mut decision, slot0); |
| 575 | let _ = write!(decision, " slot1="); |
| 576 | describe_atomicity(&mut decision, slot1); |
| 577 | let _ = writeln!(decision, ")"); |
| 578 | say(screen, decision.as_str()); |
| 579 | } |
| 580 | |
| 581 | if let Err(error) = controller.create_io_queues(4) { |
| 582 | let mut msg = aienos_kernel::report::ReportBuf::<256>::new(); |
| 583 | let _ = writeln!(msg, "NVME_READ_QEMU: FAIL (create_io_queues {error:?})"); |
| 584 | say(screen, msg.as_str()); |
| 585 | revoke_dma(screen, &mut ecam, &at); |
| 586 | return; |
| 587 | } |
| 588 | |
| 589 | // Read the sentinel LBA and verify it natively. |
| 590 | let mut buffer = [0u8; 512]; |
| 591 | match controller.read_blocks(SENTINEL_LBA, &mut buffer) { |
| 592 | Ok(()) => { |
| 593 | let digest = aienos_kernel::crypto::sha256::hash(&buffer); |
| 594 | let mut expected = [0u8; 512]; |
| 595 | for chunk in expected.as_chunks_mut::<16>().0 { |
| 596 | chunk.copy_from_slice(SENTINEL_MAGIC); |
| 597 | } |
| 598 | let mut read_line = aienos_kernel::report::ReportBuf::<320>::new(); |
| 599 | if buffer == expected { |
| 600 | let _ = write!( |
| 601 | read_line, |
| 602 | "NVME_READ_QEMU: PASS (lba={SENTINEL_LBA} blocks=1 bytes=512 sha256=" |
| 603 | ); |
| 604 | hex_digest(&mut read_line, &digest); |
| 605 | let _ = writeln!(read_line, ")"); |
| 606 | } else { |
| 607 | let _ = writeln!( |
| 608 | read_line, |
| 609 | "NVME_READ_QEMU: FAIL (sentinel mismatch at lba {SENTINEL_LBA})" |
| 610 | ); |
| 611 | } |
| 612 | say(screen, read_line.as_str()); |
| 613 | } |
| 614 | Err(error) => { |
| 615 | let mut msg = aienos_kernel::report::ReportBuf::<256>::new(); |
| 616 | let _ = writeln!(msg, "NVME_READ_QEMU: FAIL (read {error:?})"); |
| 617 | say(screen, msg.as_str()); |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | // Bounds: one read past the end must be rejected before any command. |
| 622 | let mut bounds = aienos_kernel::report::ReportBuf::<256>::new(); |
| 623 | match controller.read_blocks(block_count, &mut buffer) { |
| 624 | Err(aienos_kernel::block::BlockError::OutOfRange) => { |
| 625 | let _ = writeln!( |
| 626 | bounds, |
| 627 | "NVME_BOUNDS_QEMU: PASS (lba={block_count} rejected OutOfRange no_command)" |
| 628 | ); |
| 629 | } |
| 630 | other => { |
| 631 | let _ = writeln!(bounds, "NVME_BOUNDS_QEMU: FAIL (got {other:?})"); |
| 632 | } |
| 633 | } |
| 634 | say(screen, bounds.as_str()); |
| 635 | |
| 636 | // Error path: identify an unallocated namespace must surface a nonzero |
| 637 | // completion status rather than being swallowed. |
| 638 | let mut error_line = aienos_kernel::report::ReportBuf::<256>::new(); |
| 639 | match controller.identify_namespace(0xffff_ffff) { |
| 640 | Err(NvmeError::CompletionStatus { sct, sc }) => { |
| 641 | let _ = writeln!( |
| 642 | error_line, |
| 643 | "NVME_ERROR_QEMU: PASS (identify nsid=0xffffffff rejected status=nonzero sct={sct} sc={sc})" |
| 644 | ); |
| 645 | } |
| 646 | other => { |
| 647 | let _ = writeln!(error_line, "NVME_ERROR_QEMU: FAIL (got {other:?})"); |
| 648 | } |
| 649 | } |
| 650 | say(screen, error_line.as_str()); |
| 651 | |
| 652 | #[cfg(feature = "nvme-write")] |
| 653 | run_write_phase(screen, &mut controller, block_count); |
| 654 | |
| 655 | #[cfg(feature = "store-qual")] |
| 656 | run_store_phase(screen, controller, block_count); |
| 657 | |
| 658 | revoke_dma(screen, &mut ecam, &at); |
| 659 | } |
| 660 | |
| 661 | /// Write + flush qualification, exercised only in `nvme-write` builds. |
| 662 | /// |
| 663 | /// Read-only callers never reach this. The phase proves: a write past the end |
| 664 | /// is rejected before any command; a known pattern is written, flushed, and |
| 665 | /// read back byte-for-byte; a later boot that already holds the pattern |
| 666 | /// reports cross-restart durability; and an explicit invalid-namespace write |
| 667 | /// surfaces a device error rather than being swallowed. |
| 668 | #[cfg(feature = "nvme-write")] |
| 669 | fn run_write_phase<R: Registers, D: DmaMemory, T: Delay>( |
| 670 | screen: &mut Option<Screen>, |
| 671 | controller: &mut NvmeController<R, D, T>, |
| 672 | block_count: u64, |
| 673 | ) { |
| 674 | use aienos_kernel::block::BlockError; |
| 675 | |
| 676 | let mut new = [0u8; 512]; |
| 677 | for chunk in new.as_chunks_mut::<16>().0 { |
| 678 | chunk.copy_from_slice(RW_MAGIC); |
| 679 | } |
| 680 | let new_digest = aienos_kernel::crypto::sha256::hash(&new); |
| 681 | |
| 682 | // A write past the namespace end must be rejected before any command. |
| 683 | let mut bounds = aienos_kernel::report::ReportBuf::<256>::new(); |
| 684 | match controller.write_blocks(block_count, &new) { |
| 685 | Err(BlockError::OutOfRange) => { |
| 686 | let _ = writeln!( |
| 687 | bounds, |
| 688 | "NVME_WRITE_BOUNDS_QEMU: PASS (lba={block_count} rejected OutOfRange no_command)" |
| 689 | ); |
| 690 | } |
| 691 | other => { |
| 692 | let _ = writeln!(bounds, "NVME_WRITE_BOUNDS_QEMU: FAIL (got {other:?})"); |
| 693 | } |
| 694 | } |
| 695 | say(screen, bounds.as_str()); |
| 696 | |
| 697 | // If the target already holds the expected bytes, this boot is a restart |
| 698 | // after a prior successful write: report durability across the restart. |
| 699 | let mut readback = [0u8; 512]; |
| 700 | let persisted = controller.read_blocks(RW_LBA, &mut readback).is_ok() && readback == new; |
| 701 | if persisted { |
| 702 | let mut line = aienos_kernel::report::ReportBuf::<320>::new(); |
| 703 | let _ = write!( |
| 704 | line, |
| 705 | "NVME_DURABILITY_QEMU: PASS (persisted lba={RW_LBA} blocks=1 bytes=512 sha256=" |
| 706 | ); |
| 707 | hex_digest(&mut line, &new_digest); |
| 708 | let _ = writeln!(line, ")"); |
| 709 | say(screen, line.as_str()); |
| 710 | } else { |
| 711 | let mut write_line = aienos_kernel::report::ReportBuf::<320>::new(); |
| 712 | match controller.write_blocks(RW_LBA, &new) { |
| 713 | Ok(()) => { |
| 714 | let _ = write!( |
| 715 | write_line, |
| 716 | "NVME_WRITE_QEMU: PASS (lba={RW_LBA} blocks=1 bytes=512 sha256=" |
| 717 | ); |
| 718 | hex_digest(&mut write_line, &new_digest); |
| 719 | let _ = writeln!(write_line, ")"); |
| 720 | } |
| 721 | Err(error) => { |
| 722 | let _ = writeln!(write_line, "NVME_WRITE_QEMU: FAIL (write {error:?})"); |
| 723 | } |
| 724 | } |
| 725 | say(screen, write_line.as_str()); |
| 726 | |
| 727 | let mut flush_line = aienos_kernel::report::ReportBuf::<160>::new(); |
| 728 | match controller.flush() { |
| 729 | Ok(()) => { |
| 730 | let _ = writeln!(flush_line, "NVME_FLUSH_QEMU: PASS (nsid=1)"); |
| 731 | } |
| 732 | Err(error) => { |
| 733 | let _ = writeln!(flush_line, "NVME_FLUSH_QEMU: FAIL (flush {error:?})"); |
| 734 | } |
| 735 | } |
| 736 | say(screen, flush_line.as_str()); |
| 737 | |
| 738 | let mut durability = aienos_kernel::report::ReportBuf::<320>::new(); |
| 739 | let mut readback = [0u8; 512]; |
| 740 | match controller.read_blocks(RW_LBA, &mut readback) { |
| 741 | Ok(()) if readback == new => { |
| 742 | let _ = write!( |
| 743 | durability, |
| 744 | "NVME_DURABILITY_QEMU: PASS (lba={RW_LBA} blocks=1 bytes=512 sha256=" |
| 745 | ); |
| 746 | hex_digest(&mut durability, &new_digest); |
| 747 | let _ = writeln!(durability, ")"); |
| 748 | } |
| 749 | Ok(()) => { |
| 750 | let _ = writeln!(durability, "NVME_DURABILITY_QEMU: FAIL (readback mismatch)"); |
| 751 | } |
| 752 | Err(error) => { |
| 753 | let _ = writeln!(durability, "NVME_DURABILITY_QEMU: FAIL (read {error:?})"); |
| 754 | } |
| 755 | } |
| 756 | say(screen, durability.as_str()); |
| 757 | } |
| 758 | |
| 759 | // An explicit invalid namespace write must surface a device error. |
| 760 | let mut error_line = aienos_kernel::report::ReportBuf::<256>::new(); |
| 761 | match controller.write_blocks_nsid(0xffff_ffff, RW_LBA, &new) { |
| 762 | Err(BlockError::DeviceError) => { |
| 763 | let _ = writeln!( |
| 764 | error_line, |
| 765 | "NVME_WRITE_ERROR_QEMU: PASS (write nsid=0xffffffff rejected status=nonzero)" |
| 766 | ); |
| 767 | } |
| 768 | other => { |
| 769 | let _ = writeln!(error_line, "NVME_WRITE_ERROR_QEMU: FAIL (got {other:?})"); |
| 770 | } |
| 771 | } |
| 772 | say(screen, error_line.as_str()); |
| 773 | } |
| 774 | |
| 775 | fn report_smmu_fault( |
| 776 | screen: &mut Option<Screen>, |
| 777 | smmu_base: Option<u64>, |
| 778 | smmu_stream_id: Option<u32>, |
| 779 | smmu_events: *const [[u64; 4]; 16], |
| 780 | ) { |
| 781 | let Some(base) = smmu_base else { |
| 782 | return; |
| 783 | }; |
| 784 | // SAFETY: `base` is the identity-mapped SMMUv3 register aperture from the |
| 785 | // IORT, and the fault report reads only register offsets inside it. |
| 786 | let reg = |offset| unsafe { MmioReg::<u32>::new(base as usize + offset) }.read(); |
| 787 | clean_invalidate_dcache_range(smmu_events as usize, core::mem::size_of::<[[u64; 4]; 16]>()); |
| 788 | let events = unsafe { core::ptr::read_volatile(smmu_events) }; |
| 789 | let mut fault = aienos_kernel::report::ReportBuf::<512>::new(); |
| 790 | let _ = writeln!( |
| 791 | fault, |
| 792 | "smmu_fault: GERROR={:#x} GERRORN={:#x} events={events:016x?}", |
| 793 | reg(0x60), |
| 794 | reg(0x64) |
| 795 | ); |
| 796 | say(screen, fault.as_str()); |
| 797 | if let Some(sid) = smmu_stream_id { |
| 798 | let table_base = (u64::from(reg(0x84)) << 32 | u64::from(reg(0x80))) & !0x3f; |
| 799 | let ste_addr = table_base + u64::from(sid) * 64; |
| 800 | let ste0 = unsafe { core::ptr::read_volatile(ste_addr as *const u64) }; |
| 801 | let ste1 = unsafe { core::ptr::read_volatile((ste_addr + 8) as *const u64) }; |
| 802 | let mut entry = aienos_kernel::report::ReportBuf::<192>::new(); |
| 803 | let _ = writeln!( |
| 804 | entry, |
| 805 | "smmu_ste: base={table_base:#x} sid={sid:#x} addr={ste_addr:#x} words=[{ste0:#x},{ste1:#x}]" |
| 806 | ); |
| 807 | say(screen, entry.as_str()); |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | // --------------------------------------------------------------------------- |
| 812 | // Store-over-NVMe qualification (test-only, `store-qual`). |
| 813 | // |
| 814 | // Chain: NvmeController -> BoundedNvme -> StoreDeviceAdapter -> Store. |
| 815 | // Requires the atomic-root predicate to PASS for the 4096-byte geometry. |
| 816 | // Mode is selected by a control block at STORE region CONFIG_LBA. |
| 817 | // --------------------------------------------------------------------------- |
| 818 | |
| 819 | #[cfg(feature = "store-qual")] |
| 820 | type QualController = NvmeController<NativeRegisters, NativeDma, NativeDelay>; |
| 821 | |
| 822 | #[cfg(feature = "store-qual")] |
| 823 | type QualAdapter = aienos_kernel::store::device::StoreDeviceAdapter< |
| 824 | BoundedNvme<NativeRegisters, NativeDma, NativeDelay>, |
| 825 | >; |
| 826 | |
| 827 | #[cfg(feature = "store-qual")] |
| 828 | fn qualify_fail(screen: &mut Option<Screen>, reason: &str) { |
| 829 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 830 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL ({reason})"); |
| 831 | say(screen, l.as_str()); |
| 832 | } |
| 833 | |
| 834 | #[cfg(feature = "store-qual")] |
| 835 | fn run_store_phase(screen: &mut Option<Screen>, mut controller: QualController, block_count: u64) { |
| 836 | use aienos_kernel::nvme::atomicity::AtomicityDecision; |
| 837 | use aienos_kernel::store::checkpoint::Checkpoint; |
| 838 | use aienos_kernel::store::engine::{ObjectInput, Store}; |
| 839 | |
| 840 | let block_size = controller.block_size(); |
| 841 | if block_size != 512 && block_size != 4096 { |
| 842 | qualify_fail(screen, "unsupported block size"); |
| 843 | return; |
| 844 | } |
| 845 | |
| 846 | let cfg_lba = if block_size == 512 { |
| 847 | CONFIG_LBA_512 |
| 848 | } else { |
| 849 | CONFIG_LBA |
| 850 | }; |
| 851 | |
| 852 | // Control block. |
| 853 | let mut cfg = [0u8; 4096]; |
| 854 | if controller.read_blocks(cfg_lba, &mut cfg).is_err() { |
| 855 | qualify_fail(screen, "control block read"); |
| 856 | return; |
| 857 | } |
| 858 | let mode = cfg[0]; |
| 859 | let settle = cfg[1]; |
| 860 | |
| 861 | let is_512_qual = mode == MODE_RUN_512B || mode == MODE_VERIFY_512B; |
| 862 | if is_512_qual { |
| 863 | if block_size != 512 { |
| 864 | qualify_fail(screen, "512b qual requires 512-byte LBA"); |
| 865 | return; |
| 866 | } |
| 867 | say(screen, "STORE_512B_NONATOMIC_QUALIFICATION: ACTIVE\n"); |
| 868 | } else { |
| 869 | if block_size != 4096 { |
| 870 | qualify_fail(screen, "geometry is not 4096-byte LBA"); |
| 871 | return; |
| 872 | } |
| 873 | // Atomic-root predicate must PASS, else fail closed. |
| 874 | let atomic = |d| matches!(d, AtomicityDecision::Atomic { .. }); |
| 875 | let ok = controller |
| 876 | .atomicity() |
| 877 | .map(|a| atomic(a.store_root_decision(0)) && atomic(a.store_root_decision(1))) |
| 878 | .unwrap_or(false); |
| 879 | if !ok { |
| 880 | qualify_fail(screen, "atomic-root predicate"); |
| 881 | return; |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | let (base_lba, region_blocks) = if is_512_qual { |
| 886 | (STORE_BASE_LBA_512, STORE_REGION_BLOCKS_512) |
| 887 | } else { |
| 888 | (STORE_BASE_LBA, STORE_REGION_BLOCKS) |
| 889 | }; |
| 890 | |
| 891 | if base_lba |
| 892 | .checked_add(region_blocks) |
| 893 | .is_none_or(|end| end > block_count) |
| 894 | { |
| 895 | qualify_fail(screen, "region outside namespace"); |
| 896 | return; |
| 897 | } |
| 898 | |
| 899 | let bounded = BoundedNvme::new(controller, base_lba, region_blocks); |
| 900 | let mut adapter = match aienos_kernel::store::device::StoreDeviceAdapter::new(bounded) { |
| 901 | Ok(a) => a, |
| 902 | Err(e) => { |
| 903 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 904 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL (adapter {e:?})"); |
| 905 | say(screen, l.as_str()); |
| 906 | return; |
| 907 | } |
| 908 | }; |
| 909 | let region_units = adapter.region_units(); |
| 910 | |
| 911 | #[cfg(feature = "continuity-qual")] |
| 912 | if crate::store_qual::is_continuity_mode(mode) { |
| 913 | if is_512_qual { |
| 914 | qualify_fail(screen, "continuity qualification runs at 4096-byte LBA"); |
| 915 | return; |
| 916 | } |
| 917 | continuity_phase(screen, adapter, mode); |
| 918 | return; |
| 919 | } |
| 920 | |
| 921 | #[cfg(feature = "recovery-qual")] |
| 922 | if crate::store_qual::is_recovery_mode(mode) { |
| 923 | if is_512_qual { |
| 924 | qualify_fail(screen, "recovery qualification runs at 4096-byte LBA"); |
| 925 | return; |
| 926 | } |
| 927 | let mut response = [0u8; 32]; |
| 928 | response.copy_from_slice(&cfg[16..48]); |
| 929 | recovery_phase(screen, adapter, mode, &response); |
| 930 | return; |
| 931 | } |
| 932 | |
| 933 | if mode == MODE_VERIFY || mode == MODE_VERIFY_512B { |
| 934 | verify_reopen(screen, adapter, settle, is_512_qual); |
| 935 | return; |
| 936 | } |
| 937 | |
| 938 | // Provision canonical genesis if the region is unformatted. |
| 939 | let mut probe = [0u8; 4096]; |
| 940 | let provisioned = adapter.read_unit(0, &mut probe).is_ok() && probe.iter().any(|b| *b != 0); |
| 941 | if !provisioned { |
| 942 | let units = genesis_units(region_units); |
| 943 | for (i, unit) in units.iter().enumerate() { |
| 944 | if let Err(e) = adapter.write_unit(i as u64, unit) { |
| 945 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 946 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL (genesis write {e:?})"); |
| 947 | say(screen, l.as_str()); |
| 948 | return; |
| 949 | } |
| 950 | } |
| 951 | if let Err(e) = adapter.flush() { |
| 952 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 953 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL (genesis flush {e:?})"); |
| 954 | say(screen, l.as_str()); |
| 955 | return; |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | let mut store = match Store::open(adapter) { |
| 960 | Ok(s) => s, |
| 961 | Err(e) => { |
| 962 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 963 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL (open {e:?})"); |
| 964 | say(screen, l.as_str()); |
| 965 | return; |
| 966 | } |
| 967 | }; |
| 968 | |
| 969 | let mut integration = aienos_kernel::report::ReportBuf::<256>::new(); |
| 970 | let _ = writeln!( |
| 971 | integration, |
| 972 | "STORE_NVME_INTEGRATION_QEMU: PASS (generation={} state={:?} region_units={})", |
| 973 | store.generation(), |
| 974 | store.mount_state(), |
| 975 | region_units |
| 976 | ); |
| 977 | say(screen, integration.as_str()); |
| 978 | |
| 979 | // Settle transactions to advance committed generations (slot reuse). |
| 980 | for _ in 0..settle { |
| 981 | let bytes = (store.generation() + 1).to_le_bytes(); |
| 982 | let obj = ObjectInput { |
| 983 | kind: 3, |
| 984 | version: 1, |
| 985 | bytes: &bytes, |
| 986 | }; |
| 987 | if let Err(e) = store.transact(&[obj]) { |
| 988 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 989 | let _ = writeln!(l, "STORE_NVME_INTEGRATION_QEMU: FAIL (settle {e:?})"); |
| 990 | say(screen, l.as_str()); |
| 991 | return; |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | // Target transaction: emit CHECKPOINT lines; the host may kill us at one. |
| 996 | let bytes = (store.generation() + 1).to_le_bytes(); |
| 997 | let obj = ObjectInput { |
| 998 | kind: 3, |
| 999 | version: 1, |
| 1000 | bytes: &bytes, |
| 1001 | }; |
| 1002 | let hook = |cp: Checkpoint| { |
| 1003 | let mut l = aienos_kernel::report::ReportBuf::<64>::new(); |
| 1004 | let _ = writeln!(l, "CHECKPOINT: {}", cp.as_str()); |
| 1005 | say(screen, l.as_str()); |
| 1006 | // Observation hold only: give the host crash controller time to see the |
| 1007 | // marker and kill the VM at this exact checkpoint. No flush, no write, |
| 1008 | // no ordering change. |
| 1009 | let hz = counter_frequency_hz(); |
| 1010 | if hz > 0 { |
| 1011 | let start = counter_ticks(); |
| 1012 | while counter_ticks().wrapping_sub(start) < hz / 2 { |
| 1013 | core::hint::spin_loop(); |
| 1014 | } |
| 1015 | } |
| 1016 | }; |
| 1017 | match store.transact_with_hook(&[obj], hook) { |
| 1018 | Ok(()) => { |
| 1019 | let mut l = aienos_kernel::report::ReportBuf::<128>::new(); |
| 1020 | let _ = writeln!( |
| 1021 | l, |
| 1022 | "STORE_CHECKPOINT_QEMU: PASS (generation={})", |
| 1023 | store.generation() |
| 1024 | ); |
| 1025 | say(screen, l.as_str()); |
| 1026 | } |
| 1027 | Err(e) => { |
| 1028 | let mut l = aienos_kernel::report::ReportBuf::<128>::new(); |
| 1029 | let _ = writeln!(l, "STORE_CHECKPOINT_QEMU: FAIL ({e:?})"); |
| 1030 | say(screen, l.as_str()); |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | #[cfg(feature = "store-qual")] |
| 1036 | fn verify_reopen(screen: &mut Option<Screen>, adapter: QualAdapter, settle: u8, is_512: bool) { |
| 1037 | use aienos_kernel::store::engine::{MountState, ObjectInput, Store, StoreError}; |
| 1038 | use aienos_kernel::store::v1::ObjectId; |
| 1039 | |
| 1040 | let upper = u64::from(settle) + 2; |
| 1041 | |
| 1042 | let mut store = match Store::open(adapter) { |
| 1043 | Ok(s) => s, |
| 1044 | Err(e) => { |
| 1045 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 1046 | let _ = writeln!(l, "STORE_REOPEN_QEMU: FAIL (open {e:?})"); |
| 1047 | say(screen, l.as_str()); |
| 1048 | if is_512 { |
| 1049 | let mut l2 = aienos_kernel::report::ReportBuf::<192>::new(); |
| 1050 | let _ = writeln!(l2, "STORE_REOPEN_512B_QEMU: FAIL (open {e:?})"); |
| 1051 | say(screen, l2.as_str()); |
| 1052 | } |
| 1053 | return; |
| 1054 | } |
| 1055 | }; |
| 1056 | let generation = store.generation(); |
| 1057 | let state = store.mount_state(); |
| 1058 | |
| 1059 | if is_512 { |
| 1060 | // Peer classification is the engine's own decision at open, not a |
| 1061 | // re-derivation here. |
| 1062 | let peer_class = store.peer_condition(); |
| 1063 | let mut l512 = aienos_kernel::report::ReportBuf::<192>::new(); |
| 1064 | let _ = writeln!( |
| 1065 | l512, |
| 1066 | "STORE_REOPEN_512B_QEMU: generation={} state={:?} peer_classification={:?}", |
| 1067 | generation, state, peer_class |
| 1068 | ); |
| 1069 | say(screen, l512.as_str()); |
| 1070 | |
| 1071 | if state == MountState::DegradedRecovery { |
| 1072 | let dummy = [0u8; 8]; |
| 1073 | let obj = ObjectInput { |
| 1074 | kind: 3, |
| 1075 | version: 1, |
| 1076 | bytes: &dummy, |
| 1077 | }; |
| 1078 | let mut r = aienos_kernel::report::ReportBuf::<128>::new(); |
| 1079 | match store.transact(&[obj]) { |
| 1080 | Err(StoreError::ReadOnlyDegraded) => { |
| 1081 | let _ = writeln!(r, "STORE_DEGRADED_READONLY_QEMU: PASS"); |
| 1082 | } |
| 1083 | other => { |
| 1084 | let _ = writeln!(r, "STORE_DEGRADED_READONLY_QEMU: FAIL ({other:?})"); |
| 1085 | } |
| 1086 | } |
| 1087 | say(screen, r.as_str()); |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | let mut l = aienos_kernel::report::ReportBuf::<192>::new(); |
| 1092 | let _ = writeln!( |
| 1093 | l, |
| 1094 | "STORE_REOPEN_QEMU: generation={} state={:?} upper={}", |
| 1095 | generation, state, upper |
| 1096 | ); |
| 1097 | say(screen, l.as_str()); |
| 1098 | |
| 1099 | let mut valid = (1..=upper).contains(&generation); |
| 1100 | if valid && generation >= 2 { |
| 1101 | let bytes = generation.to_le_bytes(); |
| 1102 | valid = match ObjectId::calculate(3, 1, &bytes) { |
| 1103 | Ok(oid) => store.read_object(oid).map(|v| v == bytes).unwrap_or(false), |
| 1104 | Err(_) => false, |
| 1105 | }; |
| 1106 | } |
| 1107 | if valid && settle >= 3 && generation >= 4 { |
| 1108 | let mut r = aienos_kernel::report::ReportBuf::<96>::new(); |
| 1109 | let _ = writeln!(r, "STORE_SLOT_REUSE_QEMU: PASS (generation={generation})"); |
| 1110 | say(screen, r.as_str()); |
| 1111 | } |
| 1112 | let mut done = aienos_kernel::report::ReportBuf::<160>::new(); |
| 1113 | let _ = writeln!( |
| 1114 | done, |
| 1115 | "STORE_REOPEN_QEMU: {} (generation={generation})", |
| 1116 | if valid { "PASS" } else { "FAIL" } |
| 1117 | ); |
| 1118 | say(screen, done.as_str()); |
| 1119 | } |
| 1120 | |
| 1121 | /// M4 continuity qualification (ADR 0016). One summary line per boot: |
| 1122 | /// `CONTINUITY: <WORD> agent=<64 hex> incarnation=N sequence=S cortex=K |
| 1123 | /// branches=B memory=<16 hex>` or `CONTINUITY: <STOP-WORD> ...`. Every STOP |
| 1124 | /// path returns before any Store write. |
| 1125 | #[cfg(feature = "continuity-qual")] |
| 1126 | fn continuity_phase(screen: &mut Option<Screen>, mut adapter: QualAdapter, mode: u8) { |
| 1127 | use crate::store_qual::{ |
| 1128 | genesis_units, MODE_CONT_CRASH, MODE_CONT_PROVISION, MODE_CONT_REMEMBER, QUAL_STORE_UUID, |
| 1129 | }; |
| 1130 | use aienos_kernel::continuity::{ |
| 1131 | self, Continuity, ContinuityError, CortexRecord, Epistemic, ProvisionSource, Update, |
| 1132 | }; |
| 1133 | use aienos_kernel::store::engine::Store; |
| 1134 | |
| 1135 | fn line(screen: &mut Option<Screen>, args: core::fmt::Arguments<'_>) { |
| 1136 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1137 | let _ = l.write_fmt(args); |
| 1138 | let _ = writeln!(l); |
| 1139 | say(screen, l.as_str()); |
| 1140 | } |
| 1141 | fn summary(screen: &mut Option<Screen>, word: &str, c: &Continuity) { |
| 1142 | let mut memory = aienos_kernel::crypto::sha256::Sha256::new(); |
| 1143 | for rec in &c.cortex { |
| 1144 | memory.update(&(rec.statement.len() as u32).to_le_bytes()); |
| 1145 | memory.update(&rec.statement); |
| 1146 | } |
| 1147 | let memory = memory.finalize(); |
| 1148 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1149 | let _ = write!(l, "CONTINUITY: {word} agent="); |
| 1150 | for b in &c.root.agent_id { |
| 1151 | let _ = write!(l, "{b:02x}"); |
| 1152 | } |
| 1153 | let _ = write!( |
| 1154 | l, |
| 1155 | " incarnation={} sequence={} cortex={} branches={} memory=", |
| 1156 | c.manifest.incarnation, |
| 1157 | c.manifest.sequence, |
| 1158 | c.cortex.len(), |
| 1159 | c.state.branches.len() |
| 1160 | ); |
| 1161 | for b in &memory[..8] { |
| 1162 | let _ = write!(l, "{b:02x}"); |
| 1163 | } |
| 1164 | let _ = writeln!(l); |
| 1165 | say(screen, l.as_str()); |
| 1166 | } |
| 1167 | fn stop(screen: &mut Option<Screen>, e: ContinuityError) { |
| 1168 | match e { |
| 1169 | ContinuityError::Unprovisioned => { |
| 1170 | line(screen, format_args!("CONTINUITY: UNPROVISIONED")) |
| 1171 | } |
| 1172 | ContinuityError::Conflict => line(screen, format_args!("CONTINUITY: CONFLICT")), |
| 1173 | ContinuityError::Corrupt(why) => { |
| 1174 | line(screen, format_args!("CONTINUITY: CORRUPT ({why})")) |
| 1175 | } |
| 1176 | other => line(screen, format_args!("CONTINUITY: STOP ({other:?})")), |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | if mode == MODE_CONT_PROVISION { |
| 1181 | let mut probe = [0u8; 4096]; |
| 1182 | let blank = adapter.read_unit(0, &mut probe).is_ok() && probe.iter().all(|b| *b == 0); |
| 1183 | if blank { |
| 1184 | let units = genesis_units(adapter.region_units()); |
| 1185 | for (i, unit) in units.iter().enumerate() { |
| 1186 | if adapter.write_unit(i as u64, unit).is_err() { |
| 1187 | line(screen, format_args!("CONTINUITY: STOP (genesis write)")); |
| 1188 | return; |
| 1189 | } |
| 1190 | } |
| 1191 | if adapter.flush().is_err() { |
| 1192 | line(screen, format_args!("CONTINUITY: STOP (genesis flush)")); |
| 1193 | return; |
| 1194 | } |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | let mut store = match Store::open(adapter) { |
| 1199 | Ok(s) => s, |
| 1200 | Err(e) => { |
| 1201 | line(screen, format_args!("CONTINUITY: STOP (store {e:?})")); |
| 1202 | return; |
| 1203 | } |
| 1204 | }; |
| 1205 | |
| 1206 | if mode == MODE_CONT_PROVISION { |
| 1207 | let mut agent = [0u8; 32]; |
| 1208 | for chunk in agent.as_chunks_mut::<8>().0 { |
| 1209 | match aienos_kernel::arch::aarch64::rndr() { |
| 1210 | Some(v) => chunk.copy_from_slice(&v.to_le_bytes()), |
| 1211 | None => { |
| 1212 | line(screen, format_args!("CONTINUITY: NO_ENTROPY")); |
| 1213 | return; |
| 1214 | } |
| 1215 | } |
| 1216 | } |
| 1217 | match continuity::provision( |
| 1218 | &mut store, |
| 1219 | agent, |
| 1220 | QUAL_STORE_UUID, |
| 1221 | ProvisionSource::Qualification, |
| 1222 | ) { |
| 1223 | Ok(c) => summary(screen, "PROVISIONED", &c), |
| 1224 | Err(e) => stop(screen, e), |
| 1225 | } |
| 1226 | return; |
| 1227 | } |
| 1228 | |
| 1229 | let current = match continuity::resume(&mut store) { |
| 1230 | Ok((c, true)) => { |
| 1231 | summary(screen, "RESUMED", &c); |
| 1232 | c |
| 1233 | } |
| 1234 | Ok((c, false)) => { |
| 1235 | summary(screen, "RESUMED_READONLY", &c); |
| 1236 | return; |
| 1237 | } |
| 1238 | Err(e) => { |
| 1239 | stop(screen, e); |
| 1240 | return; |
| 1241 | } |
| 1242 | }; |
| 1243 | |
| 1244 | let fact = |text: &[u8]| CortexRecord { |
| 1245 | status: Epistemic::DirectObservation, |
| 1246 | evidence_hash: [0; 32], |
| 1247 | statement: text.to_vec(), |
| 1248 | }; |
| 1249 | if mode == MODE_CONT_REMEMBER { |
| 1250 | let mut state = current.state.clone(); |
| 1251 | if state.fork(¤t.root.root_branch).is_err() { |
| 1252 | line(screen, format_args!("CONTINUITY: STOP (fork)")); |
| 1253 | return; |
| 1254 | } |
| 1255 | let update = Update { |
| 1256 | state: Some(state), |
| 1257 | cortex: alloc::vec![fact(b"qemu: the operator asked AIEN to remember this")], |
| 1258 | }; |
| 1259 | match continuity::commit(&mut store, ¤t, update, false) { |
| 1260 | Ok(c) => summary(screen, "REMEMBERED", &c), |
| 1261 | Err(e) => stop(screen, e), |
| 1262 | } |
| 1263 | } else if mode == MODE_CONT_CRASH { |
| 1264 | let hook = |cp: aienos_kernel::store::checkpoint::Checkpoint| { |
| 1265 | let mut l = aienos_kernel::report::ReportBuf::<64>::new(); |
| 1266 | let _ = writeln!(l, "CHECKPOINT: {}", cp.as_str()); |
| 1267 | say(screen, l.as_str()); |
| 1268 | // Observation hold only: no flush, no write, no ordering change. |
| 1269 | let hz = counter_frequency_hz(); |
| 1270 | if hz > 0 { |
| 1271 | let start = counter_ticks(); |
| 1272 | while counter_ticks().wrapping_sub(start) < hz / 2 { |
| 1273 | core::hint::spin_loop(); |
| 1274 | } |
| 1275 | } |
| 1276 | }; |
| 1277 | let update = Update { |
| 1278 | state: None, |
| 1279 | cortex: alloc::vec![fact(b"qemu: committed across a crash")], |
| 1280 | }; |
| 1281 | match continuity::commit_with_hook(&mut store, ¤t, update, false, hook) { |
| 1282 | Ok(c) => summary(screen, "COMMITTED", &c), |
| 1283 | Err(e) => stop(screen, e), |
| 1284 | } |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | /// Recovery Core qualification (ADR 0006) with the TEST ONLY operator key. |
| 1289 | /// Mode 9 inspects and prints the challenge for the applicable action; |
| 1290 | /// modes 10/11 verify the operator response in control-block bytes 16..48 |
| 1291 | /// and perform the action only if it verifies for exactly this state. |
| 1292 | #[cfg(feature = "recovery-qual")] |
| 1293 | fn recovery_phase( |
| 1294 | screen: &mut Option<Screen>, |
| 1295 | mut adapter: QualAdapter, |
| 1296 | mode: u8, |
| 1297 | response: &[u8; 32], |
| 1298 | ) { |
| 1299 | use crate::store_qual::{ |
| 1300 | MODE_RECOVERY_PROVISION, MODE_RECOVERY_REPAIR, TEST_ONLY_OPERATOR_KEY, |
| 1301 | }; |
| 1302 | use aienos_kernel::recovery_core::{self, Action, SlotView}; |
| 1303 | |
| 1304 | fn hex_into(l: &mut aienos_kernel::report::ReportBuf<256>, bytes: &[u8]) { |
| 1305 | for b in bytes { |
| 1306 | let _ = write!(l, "{b:02x}"); |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | say(screen, "RECOVERY_OPERATOR_KEY: TEST-ONLY\n"); |
| 1311 | let record = recovery_core::inspect(&mut adapter); |
| 1312 | |
| 1313 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1314 | let _ = write!(l, "RECOVERY_RECORD:"); |
| 1315 | for (i, slot) in record.slots.iter().enumerate() { |
| 1316 | match slot { |
| 1317 | SlotView::Zero => { |
| 1318 | let _ = write!(l, " slot{i}=zero"); |
| 1319 | } |
| 1320 | SlotView::Superblock { generation } => { |
| 1321 | let _ = write!(l, " slot{i}=gen{generation}"); |
| 1322 | } |
| 1323 | SlotView::Undecodable(e) => { |
| 1324 | let _ = write!(l, " slot{i}=undecodable({e:?})"); |
| 1325 | } |
| 1326 | SlotView::ReadError => { |
| 1327 | let _ = write!(l, " slot{i}=read-error"); |
| 1328 | } |
| 1329 | } |
| 1330 | } |
| 1331 | if let Some((m, p, g)) = record.mount { |
| 1332 | let _ = write!(l, " mount={m:?} peer={p:?} generation={g}"); |
| 1333 | } |
| 1334 | if let Some((roots, manifests, other)) = record.catalog { |
| 1335 | let _ = write!(l, " roots={roots} manifests={manifests} other={other}"); |
| 1336 | } |
| 1337 | let _ = write!(l, " agent="); |
| 1338 | match &record.continuity { |
| 1339 | Some(c) => hex_into(&mut l, &c.root.agent_id), |
| 1340 | None => { |
| 1341 | let _ = write!(l, "none"); |
| 1342 | } |
| 1343 | } |
| 1344 | let _ = writeln!(l); |
| 1345 | say(screen, l.as_str()); |
| 1346 | |
| 1347 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1348 | match record.reason { |
| 1349 | Some(reason) => { |
| 1350 | let _ = writeln!(l, "RECOVERY_CORE: ENTERED reason={reason:?}"); |
| 1351 | } |
| 1352 | None => { |
| 1353 | let _ = writeln!(l, "RECOVERY_CORE: NOT_NEEDED"); |
| 1354 | } |
| 1355 | } |
| 1356 | say(screen, l.as_str()); |
| 1357 | |
| 1358 | if let Some(action) = record.applicable() { |
| 1359 | if let Some(challenge) = record.challenge(action) { |
| 1360 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1361 | let _ = write!(l, "RECOVERY_CHALLENGE: action={} challenge=", action.name()); |
| 1362 | hex_into(&mut l, &challenge); |
| 1363 | let _ = writeln!(l); |
| 1364 | say(screen, l.as_str()); |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | let outcome = if mode == MODE_RECOVERY_REPAIR { |
| 1369 | Some( |
| 1370 | recovery_core::repair_degraded_peer(&mut adapter, &TEST_ONLY_OPERATOR_KEY, response) |
| 1371 | .map(|_| (Action::RepairDegradedPeer, None)), |
| 1372 | ) |
| 1373 | } else if mode == MODE_RECOVERY_PROVISION { |
| 1374 | let mut agent = [0u8; 32]; |
| 1375 | for chunk in agent.as_chunks_mut::<8>().0 { |
| 1376 | match aienos_kernel::arch::aarch64::rndr() { |
| 1377 | Some(v) => chunk.copy_from_slice(&v.to_le_bytes()), |
| 1378 | None => { |
| 1379 | say(screen, "RECOVERY_REFUSED (NoEntropy)\n"); |
| 1380 | return; |
| 1381 | } |
| 1382 | } |
| 1383 | } |
| 1384 | Some( |
| 1385 | recovery_core::provision_identity( |
| 1386 | &mut adapter, |
| 1387 | &TEST_ONLY_OPERATOR_KEY, |
| 1388 | response, |
| 1389 | agent, |
| 1390 | ) |
| 1391 | .map(|c| (Action::ProvisionIdentity, Some(c.root.agent_id))), |
| 1392 | ) |
| 1393 | } else { |
| 1394 | None |
| 1395 | }; |
| 1396 | |
| 1397 | let Some(outcome) = outcome else { |
| 1398 | return; |
| 1399 | }; |
| 1400 | let mut l = aienos_kernel::report::ReportBuf::<256>::new(); |
| 1401 | match outcome { |
| 1402 | Ok((action, agent)) => { |
| 1403 | let _ = write!(l, "RECOVERY_ACTION: {} DONE", action.name()); |
| 1404 | if let Some(agent) = agent { |
| 1405 | let _ = write!(l, " agent="); |
| 1406 | hex_into(&mut l, &agent); |
| 1407 | } |
| 1408 | let _ = writeln!(l); |
| 1409 | } |
| 1410 | Err(e) => { |
| 1411 | let _ = writeln!(l, "RECOVERY_REFUSED ({e:?})"); |
| 1412 | } |
| 1413 | } |
| 1414 | say(screen, l.as_str()); |
| 1415 | } |