Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/tests/nvme_flush.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / tests / nvme_flush.rs` 525 lines ยท 17558 bytes Raw Blame History 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 //! D2 integration tests: NVMe Flush (opcode 0x00) on the polled I/O queue. 17 //! 18 //! Target: `crates/aienos-kernel/tests/nvme_flush.rs`. 19 //! 20 //! Self-contained: this file uses only the public `aienos_kernel::nvme` and 21 //! `aienos_kernel::nvme::driver` API plus local `Registers`, `DmaMemory`, and 22 //! `Delay` fakes. The fake controller records every I/O command and every I/O 23 //! submission-doorbell write, so the tests can prove that `flush()` issues a 24 //! real Flush command that reaches the device instead of being a silent no-op. 25 //! 26 //! Base: aien-dev/aienux @ `ef359ec`. 27 28 use std::cell::RefCell; 29 use std::collections::VecDeque; 30 use std::rc::Rc; 31 32 use aienos_kernel::block::{BlockDevice, BlockError}; 33 use aienos_kernel::nvme::driver::{ 34 Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, 35 }; 36 use aienos_kernel::nvme::{ 37 doorbell_offset, Registers, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS, 38 }; 39 40 const PAGE: usize = 4096; 41 /// CAP.DSTRD = 0 -> 4-byte doorbell stride. CAP.TO = 1 -> 500 ms ready budget. 42 const CAP_LOW: u32 = 0x0100_03ff; 43 const STRIDE: u32 = 4; 44 const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE); 45 const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE); 46 const NS_BLOCKS: u64 = 12_345; 47 /// The driver loops `for _ in 0..=1000`, i.e. 1001 polls, each backing off 1 ms. 48 const POLLS: u64 = 1_001; 49 const FLUSH_OPCODE: u8 = 0x00; 50 const WRITE_OPCODE: u8 = 0x01; 51 const IO_DEPTH: u16 = 4; 52 53 type Shared = Rc>; 54 55 // --------------------------------------------------------------------------- 56 // Device model 57 // --------------------------------------------------------------------------- 58 59 /// Knobs the tests flip to shape I/O completion behaviour. 60 #[derive(Clone, Default)] 61 struct Behavior { 62 /// Raw status bits (SC/SCT/DNR) ORed with the phase bit before delivery. 63 io_raw_status: Option, 64 /// If true, never place an I/O completion (driver must bound its poll). 65 io_never_complete: bool, 66 } 67 68 struct Region { 69 base: u64, 70 len: usize, 71 bytes: Vec, 72 } 73 74 /// Every I/O command the device observed, parsed from its SQ entry. 75 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 76 struct RecordedIo { 77 opcode: u8, 78 nsid: u32, 79 cid: u16, 80 cdw10: u32, 81 cdw11: u32, 82 prp1: u64, 83 prp2: u64, 84 } 85 86 struct Device { 87 regions: Vec, 88 next_phys: u64, 89 cc: u32, 90 csts: u32, 91 asq: u64, 92 acq: u64, 93 admin_cq_base: Option, 94 admin_cq_len: usize, 95 io_sq_base: Option, 96 io_cq_base: Option, 97 io_depth: usize, 98 admin_sq_tail: usize, 99 admin_cq_tail: usize, 100 admin_phase: bool, 101 io_sq_tail: usize, 102 io_cq_tail: usize, 103 io_phase: bool, 104 admin_queue: VecDeque<[u8; 16]>, 105 io_queue: VecDeque<[u8; 16]>, 106 io_commands: u64, 107 io_sq_doorbells: u64, 108 io_log: Vec, 109 behavior: Behavior, 110 } 111 112 impl Device { 113 fn new() -> Self { 114 Self { 115 regions: Vec::new(), 116 next_phys: 0x1000, 117 cc: 0, 118 csts: 0, 119 asq: 0, 120 acq: 0, 121 admin_cq_base: None, 122 admin_cq_len: 0, 123 io_sq_base: None, 124 io_cq_base: None, 125 io_depth: 0, 126 admin_sq_tail: 0, 127 admin_cq_tail: 0, 128 admin_phase: true, 129 io_sq_tail: 0, 130 io_cq_tail: 0, 131 io_phase: true, 132 admin_queue: VecDeque::new(), 133 io_queue: VecDeque::new(), 134 io_commands: 0, 135 io_sq_doorbells: 0, 136 io_log: Vec::new(), 137 behavior: Behavior::default(), 138 } 139 } 140 141 fn alloc(&mut self, size: usize, alignment: usize) -> u64 { 142 let align = alignment.max(1) as u64; 143 let base = (self.next_phys + align - 1) & !(align - 1); 144 self.next_phys = base + size as u64; 145 self.regions.push(Region { 146 base, 147 len: size, 148 bytes: vec![0; size], 149 }); 150 base 151 } 152 153 fn find_region(&self, physical: u64, len: usize) -> Option { 154 self.regions 155 .iter() 156 .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64) 157 } 158 159 fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { 160 if output.len() == 16 { 161 if let Some(base) = self.admin_cq_base { 162 if physical >= base && physical + 16 <= base + self.admin_cq_len as u64 { 163 match self.admin_queue.pop_front() { 164 Some(cqe) => output.copy_from_slice(&cqe), 165 None => output.fill(0), 166 } 167 return Ok(()); 168 } 169 } 170 if let Some(base) = self.io_cq_base { 171 let len = (self.io_depth * 16) as u64; 172 if physical >= base && physical + 16 <= base + len { 173 match self.io_queue.pop_front() { 174 Some(cqe) => output.copy_from_slice(&cqe), 175 None => output.fill(0), 176 } 177 return Ok(()); 178 } 179 } 180 } 181 match self.find_region(physical, output.len()) { 182 Some(i) => { 183 output.copy_from_slice(&self.regions[i].bytes[..output.len()]); 184 Ok(()) 185 } 186 None => Err(NvmeError::Dma), 187 } 188 } 189 190 fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { 191 match self.find_region(physical, input.len()) { 192 Some(i) => { 193 self.regions[i].bytes[..input.len()].copy_from_slice(input); 194 Ok(()) 195 } 196 None => Err(NvmeError::Dma), 197 } 198 } 199 200 fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] { 201 let addr = base + (slot * 64) as u64; 202 let mut out = [0u8; 64]; 203 if let Some(i) = self.find_region(addr, 64) { 204 out.copy_from_slice(&self.regions[i].bytes[..64]); 205 } 206 out 207 } 208 209 fn fill_identify(&mut self, prp: u64, cns: u32) { 210 if let Some(i) = self.find_region(prp, PAGE) { 211 let bytes = &mut self.regions[i].bytes; 212 if cns == 1 { 213 bytes[77] = 0; // MDTS = 0 -> 128 KiB chunk cap 214 } else { 215 bytes[0..8].copy_from_slice(&NS_BLOCKS.to_le_bytes()); 216 bytes[26] = 0; // FLBAS -> format 0 217 bytes[128 + 2] = 9; // LBADS -> 512-byte blocks 218 } 219 } 220 } 221 222 fn push_admin(&mut self, phase: bool, cid: u16, raw: u16) { 223 let mut cqe = [0u8; 16]; 224 cqe[12..14].copy_from_slice(&cid.to_le_bytes()); 225 cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); 226 self.admin_queue.push_back(cqe); 227 } 228 229 fn push_io(&mut self, phase: bool, cid: u16, raw: u16) { 230 let mut cqe = [0u8; 16]; 231 cqe[12..14].copy_from_slice(&cid.to_le_bytes()); 232 cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes()); 233 self.io_queue.push_back(cqe); 234 } 235 236 fn on_admin_doorbell(&mut self) { 237 let slot = self.admin_sq_tail; 238 let cmd = self.peek_command(self.asq, slot); 239 let opcode = cmd[0]; 240 let cid = u16::from_le_bytes([cmd[2], cmd[3]]); 241 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); 242 let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); 243 match opcode { 244 0x06 => self.fill_identify(p1, cdw10), 245 0x05 => { 246 // Create I/O CQ (QID 1): remember buffer and depth. 247 self.io_cq_base = Some(p1); 248 self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1; 249 } 250 0x01 => self.io_sq_base = Some(p1), // Create I/O SQ (QID 1) 251 _ => {} 252 } 253 self.push_admin(self.admin_phase, cid, 0); 254 self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH; 255 self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH; 256 if self.admin_cq_tail == 0 { 257 self.admin_phase = !self.admin_phase; 258 } 259 } 260 261 fn on_io_doorbell(&mut self) { 262 self.io_sq_doorbells += 1; 263 let Some(sq) = self.io_sq_base else { 264 return; 265 }; 266 if self.io_depth == 0 { 267 return; 268 } 269 let slot = self.io_sq_tail; 270 let cmd = self.peek_command(sq, slot); 271 let opcode = cmd[0]; 272 let cid = u16::from_le_bytes([cmd[2], cmd[3]]); 273 let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap()); 274 let prp1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap()); 275 let prp2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap()); 276 let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap()); 277 let cdw11 = u32::from_le_bytes(cmd[44..48].try_into().unwrap()); 278 self.io_commands += 1; 279 self.io_log.push(RecordedIo { 280 opcode, 281 nsid, 282 cid, 283 cdw10, 284 cdw11, 285 prp1, 286 prp2, 287 }); 288 if !self.behavior.io_never_complete { 289 let raw = self.behavior.io_raw_status.unwrap_or(0); 290 self.push_io(self.io_phase, cid, raw); 291 } 292 self.io_sq_tail = (slot + 1) % self.io_depth; 293 self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth; 294 if self.io_cq_tail == 0 { 295 self.io_phase = !self.io_phase; 296 } 297 } 298 299 fn reg_read(&mut self, offset: u32) -> u32 { 300 match offset { 301 0 => CAP_LOW, 302 4 => 0, 303 REG_CC => self.cc, 304 REG_CSTS => self.csts, 305 _ => 0, 306 } 307 } 308 309 fn reg_write(&mut self, offset: u32, value: u32) { 310 match offset { 311 REG_CC => { 312 self.cc = value; 313 self.csts = if value & 1 == 0 { 0 } else { CSTS_RDY }; 314 } 315 REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value), 316 x if x == REG_ASQ + 4 => self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32), 317 REG_ACQ => { 318 self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value); 319 self.admin_cq_base = Some(self.acq); 320 self.admin_cq_len = PAGE; 321 } 322 x if x == REG_ACQ + 4 => { 323 self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32); 324 self.admin_cq_base = Some(self.acq); 325 self.admin_cq_len = PAGE; 326 } 327 ADMIN_DOORBELL => self.on_admin_doorbell(), 328 IO_SQ_DOORBELL => self.on_io_doorbell(), 329 _ => {} 330 } 331 } 332 } 333 334 // --------------------------------------------------------------------------- 335 // Fakes implementing the public driver traits 336 // --------------------------------------------------------------------------- 337 338 struct FakeRegs { 339 shared: Shared, 340 } 341 342 impl Registers for FakeRegs { 343 fn read32(&mut self, offset: u32) -> u32 { 344 self.shared.borrow_mut().reg_read(offset) 345 } 346 fn write32(&mut self, offset: u32, value: u32) { 347 self.shared.borrow_mut().reg_write(offset, value); 348 } 349 } 350 351 struct FakeDma { 352 shared: Shared, 353 } 354 355 impl DmaMemory for FakeDma { 356 fn allocate(&mut self, size: usize, alignment: usize) -> Result { 357 let physical = self.shared.borrow_mut().alloc(size, alignment); 358 Ok(DmaRegion { 359 physical, 360 bytes: vec![0; size], 361 }) 362 } 363 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> { 364 self.shared.borrow_mut().read_mem(physical, output) 365 } 366 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> { 367 self.shared.borrow_mut().write_mem(physical, input) 368 } 369 } 370 371 #[derive(Default)] 372 struct CountingDelay { 373 waited_us: Rc>, 374 } 375 376 impl Delay for CountingDelay { 377 fn delay_us(&mut self, us: u32) { 378 *self.waited_us.borrow_mut() += u64::from(us); 379 } 380 } 381 382 type Controller = NvmeController; 383 384 fn make_controller() -> (Controller, Shared, Rc>) { 385 let shared: Shared = Rc::new(RefCell::new(Device::new())); 386 let regs = FakeRegs { 387 shared: shared.clone(), 388 }; 389 let dma = FakeDma { 390 shared: shared.clone(), 391 }; 392 let delay = CountingDelay::default(); 393 let waited = delay.waited_us.clone(); 394 let controller = NvmeController::init(regs, dma, delay).expect("init should succeed"); 395 (controller, shared, waited) 396 } 397 398 fn recorded_io(shared: &Shared) -> Vec { 399 shared.borrow().io_log.clone() 400 } 401 402 // --------------------------------------------------------------------------- 403 // Tests 404 // --------------------------------------------------------------------------- 405 406 /// Flush is opcode 0x00, addressed to NSID 1, with no PRP data pointer. 407 #[test] 408 fn flush_submits_opcode_zero_nsid_one_without_data_pointer() { 409 let (mut controller, shared, _) = make_controller(); 410 controller.create_io_queues(IO_DEPTH).unwrap(); 411 controller.flush().unwrap(); 412 413 let log = recorded_io(&shared); 414 assert_eq!(log.len(), 1, "exactly one I/O command: the Flush"); 415 let flush = log[0]; 416 assert_eq!(flush.opcode, FLUSH_OPCODE, "Flush is opcode 0x00"); 417 assert_eq!(flush.nsid, 1, "Flush targets NSID 1"); 418 assert_eq!( 419 (flush.prp1, flush.prp2), 420 (0, 0), 421 "Flush is data-less: PRP1/PRP2 must stay zero" 422 ); 423 assert_eq!( 424 (flush.cdw10, flush.cdw11), 425 (0, 0), 426 "reserved CDW10/CDW11 must stay zero" 427 ); 428 } 429 430 /// A zero-status completion means the controller reported the cache durable. 431 #[test] 432 fn successful_flush_completion_returns_ok() { 433 let (mut controller, shared, _) = make_controller(); 434 controller.create_io_queues(IO_DEPTH).unwrap(); 435 436 assert_eq!(controller.flush(), Ok(())); 437 438 let device = shared.borrow(); 439 assert_eq!(device.io_commands, 1, "the Flush reached the device"); 440 assert_eq!(device.io_log[0].opcode, FLUSH_OPCODE); 441 } 442 443 /// Durability is exposed only through successful completion: any nonzero status 444 /// is a failure, never an assumed success. 445 #[test] 446 fn nonzero_flush_completion_status_returns_device_error() { 447 let (mut controller, shared, _) = make_controller(); 448 controller.create_io_queues(IO_DEPTH).unwrap(); 449 // status word 0x0002 -> status >> 1 == 1 (nonzero). 450 shared.borrow_mut().behavior.io_raw_status = Some(0x0002); 451 452 assert_eq!(controller.flush(), Err(BlockError::DeviceError)); 453 } 454 455 /// A missing completion is bounded and surfaced as a timeout, not an infinite 456 /// loop and not a fake success. 457 #[test] 458 fn flush_timeout_returns_timeout_and_is_bounded() { 459 let (mut controller, shared, waited) = make_controller(); 460 controller.create_io_queues(IO_DEPTH).unwrap(); 461 shared.borrow_mut().behavior.io_never_complete = true; 462 463 let before = *waited.borrow(); 464 assert_eq!(controller.flush(), Err(BlockError::Timeout)); 465 assert_eq!( 466 *waited.borrow() - before, 467 POLLS * 1_000, 468 "the poll budget must be bounded" 469 ); 470 } 471 472 /// Flush must not be a silent no-op: it must ring the I/O submission doorbell 473 /// and the command must actually reach the device simulator. 474 #[test] 475 fn flush_is_not_a_silent_no_op_doorbell_and_command_reach_device() { 476 let (mut controller, shared, _) = make_controller(); 477 controller.create_io_queues(IO_DEPTH).unwrap(); 478 let (doorbells_before, commands_before) = { 479 let device = shared.borrow(); 480 (device.io_sq_doorbells, device.io_commands) 481 }; 482 483 controller.flush().unwrap(); 484 485 let device = shared.borrow(); 486 assert_eq!( 487 device.io_sq_doorbells, 488 doorbells_before + 1, 489 "a Flush must ring the I/O submission-queue doorbell" 490 ); 491 assert_eq!( 492 device.io_commands, 493 commands_before + 1, 494 "the Flush command must reach the device" 495 ); 496 assert_eq!( 497 device.io_log.last().unwrap().opcode, 498 FLUSH_OPCODE, 499 "the delivered command is a Flush" 500 ); 501 } 502 503 /// Flush after a write in the same session must use a fresh command id, never 504 /// reuse the write's CID. 505 #[test] 506 fn flush_after_write_in_same_session_uses_fresh_cid() { 507 let (mut controller, shared, _) = make_controller(); 508 controller.create_io_queues(IO_DEPTH).unwrap(); 509 510 controller.write_blocks(0, &[0xAB; 512]).unwrap(); 511 controller.flush().unwrap(); 512 513 let log = recorded_io(&shared); 514 assert_eq!(log.len(), 2, "one Write then one Flush"); 515 let write = log[0]; 516 let flush = log[1]; 517 assert_eq!(write.opcode, WRITE_OPCODE, "first command is a Write"); 518 assert_eq!(flush.opcode, FLUSH_OPCODE, "second command is a Flush"); 519 assert_ne!(flush.cid, write.cid, "Flush must not reuse the Write CID"); 520 assert_eq!( 521 flush.cid, 522 write.cid.wrapping_add(1), 523 "the CID must advance monotonically" 524 ); 525 }