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 / crates / aienos-kernel / tests / nvme_completion.rs

634 lines · 21424 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//! External integration tests for the polled NVMe completion/error path.
17//!
18//! Target: `crates/aienos-kernel/tests/nvme_completion.rs`.
19//!
20//! Uses only the public `aienos_kernel::nvme` and
21//! `aienos_kernel::nvme::driver` API plus our own `Registers`, `DmaMemory`
22//! and `Delay` fakes. The device fake is programmable: it can echo a wrong
23//! command id, park a stale-phase completion ahead of the real one, return
24//! crafted status words, never complete, or fault/never-ready the controller.
25
26use std::cell::RefCell;
27use std::collections::VecDeque;
28use std::rc::Rc;
29
30use aienos_kernel::block::{BlockDevice, BlockError};
31use aienos_kernel::nvme::driver::{
32 Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH,
33};
34use aienos_kernel::nvme::{
35 doorbell_offset, Completion, CompletionQueue, ControllerError, Registers, Submission, CSTS_CFS,
36 CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS,
37};
38
39const PAGE: usize = 4096;
40/// CAP.DSTRD = 0 -> 4-byte doorbell stride. CAP.TO = 1 -> 500 ms ready budget.
41const CAP_LOW: u32 = 0x0100_03ff;
42const STRIDE: u32 = 4;
43const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE);
44const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE);
45const NS_BLOCKS: u64 = 12_345;
46const POLLS: u64 = 1_001; // driver loops `0..=1000`
47
48type Shared = Rc<RefCell<Device>>;
49
50// ---------------------------------------------------------------------------
51// Programmable device model
52// ---------------------------------------------------------------------------
53
54#[derive(Clone, Default)]
55struct Behavior {
56 /// Raw status bits (SC/SCT/DNR) ORed with the phase bit before delivery.
57 admin_raw_status: Option<u16>,
58 /// Added to the echoed CID; nonzero forces a command-id mismatch.
59 admin_cid_delta: i32,
60 /// Emit this many stale-phase completions before the real one.
61 admin_stale_reads: u32,
62 /// If true, never place an admin completion (driver must bound its poll).
63 admin_never_complete: bool,
64 io_raw_status: Option<u16>,
65 io_cid_delta: i32,
66 io_stale_reads: u32,
67 io_never_complete: bool,
68}
69
70struct Region {
71 base: u64,
72 len: usize,
73 bytes: Vec<u8>,
74}
75
76struct Device {
77 regions: Vec<Region>,
78 next_phys: u64,
79 cc: u32,
80 csts: u32,
81 fatal_on_enable: bool,
82 never_ready: bool,
83 asq: u64,
84 acq: u64,
85 admin_cq_base: Option<u64>,
86 admin_cq_len: usize,
87 io_sq_base: Option<u64>,
88 io_cq_base: Option<u64>,
89 io_depth: usize,
90 admin_sq_tail: usize,
91 admin_cq_tail: usize,
92 admin_phase: bool,
93 io_sq_tail: usize,
94 io_cq_tail: usize,
95 io_phase: bool,
96 admin_queue: VecDeque<[u8; 16]>,
97 io_queue: VecDeque<[u8; 16]>,
98 admin_commands: u64,
99 io_commands: u64,
100 behavior: Behavior,
101}
102
103impl Device {
104 fn new() -> Self {
105 Self {
106 regions: Vec::new(),
107 next_phys: 0x1000,
108 cc: 0,
109 csts: 0,
110 fatal_on_enable: false,
111 never_ready: false,
112 asq: 0,
113 acq: 0,
114 admin_cq_base: None,
115 admin_cq_len: 0,
116 io_sq_base: None,
117 io_cq_base: None,
118 io_depth: 0,
119 admin_sq_tail: 0,
120 admin_cq_tail: 0,
121 admin_phase: true,
122 io_sq_tail: 0,
123 io_cq_tail: 0,
124 io_phase: true,
125 admin_queue: VecDeque::new(),
126 io_queue: VecDeque::new(),
127 admin_commands: 0,
128 io_commands: 0,
129 behavior: Behavior::default(),
130 }
131 }
132
133 fn alloc(&mut self, size: usize, alignment: usize) -> u64 {
134 let align = alignment.max(1) as u64;
135 let base = (self.next_phys + align - 1) & !(align - 1);
136 self.next_phys = base + size as u64;
137 self.regions.push(Region {
138 base,
139 len: size,
140 bytes: vec![0; size],
141 });
142 base
143 }
144
145 fn find_region(&self, physical: u64, len: usize) -> Option<usize> {
146 self.regions
147 .iter()
148 .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64)
149 }
150
151 fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
152 if output.len() == 16 {
153 if let Some(base) = self.admin_cq_base {
154 if physical >= base && physical + 16 <= base + self.admin_cq_len as u64 {
155 match self.admin_queue.pop_front() {
156 Some(cqe) => output.copy_from_slice(&cqe),
157 None => output.fill(0),
158 }
159 return Ok(());
160 }
161 }
162 if let Some(base) = self.io_cq_base {
163 let len = (self.io_depth * 16) as u64;
164 if physical >= base && physical + 16 <= base + len {
165 match self.io_queue.pop_front() {
166 Some(cqe) => output.copy_from_slice(&cqe),
167 None => output.fill(0),
168 }
169 return Ok(());
170 }
171 }
172 }
173 match self.find_region(physical, output.len()) {
174 Some(i) => {
175 output.copy_from_slice(&self.regions[i].bytes[..output.len()]);
176 Ok(())
177 }
178 None => Err(NvmeError::Dma),
179 }
180 }
181
182 fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
183 match self.find_region(physical, input.len()) {
184 Some(i) => {
185 self.regions[i].bytes[..input.len()].copy_from_slice(input);
186 Ok(())
187 }
188 None => Err(NvmeError::Dma),
189 }
190 }
191
192 fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] {
193 let addr = base + (slot * 64) as u64;
194 let mut out = [0u8; 64];
195 if let Some(i) = self.find_region(addr, 64) {
196 out.copy_from_slice(&self.regions[i].bytes[..64]);
197 }
198 out
199 }
200
201 fn fill_identify(&mut self, prp: u64, cns: u32) {
202 let idx = self.find_region(prp, PAGE);
203 if let Some(i) = idx {
204 let bytes = &mut self.regions[i].bytes;
205 if cns == 1 {
206 bytes[77] = 0; // MDTS = 0
207 } else {
208 bytes[0..8].copy_from_slice(&NS_BLOCKS.to_le_bytes());
209 bytes[26] = 0; // FLBAS -> format 0
210 bytes[128 + 2] = 9; // LBADS -> 512-byte blocks
211 }
212 }
213 }
214
215 fn push_admin(&mut self, phase: bool, cid: u16, raw: u16) {
216 let mut cqe = [0u8; 16];
217 cqe[12..14].copy_from_slice(&cid.to_le_bytes());
218 cqe[14..16].copy_from_slice(&(raw | u16::from(phase)).to_le_bytes());
219 self.admin_queue.push_back(cqe);
220 }
221
222 fn push_io(&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.io_queue.push_back(cqe);
227 }
228
229 fn on_admin_doorbell(&mut self) {
230 let slot = self.admin_sq_tail;
231 let cmd = self.peek_command(self.asq, slot);
232 let opcode = cmd[0];
233 let cid = u16::from_le_bytes([cmd[2], cmd[3]]);
234 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap());
235 let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap());
236 match opcode {
237 0x06 => self.fill_identify(p1, cdw10),
238 0x05 => {
239 self.io_cq_base = Some(p1);
240 self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1;
241 }
242 0x01 => self.io_sq_base = Some(p1),
243 _ => {}
244 }
245 self.admin_commands += 1;
246 if !self.behavior.admin_never_complete {
247 let echo = if self.behavior.admin_cid_delta == 0 {
248 cid
249 } else {
250 cid.wrapping_add(self.behavior.admin_cid_delta as u16)
251 };
252 let mut stale = self.behavior.admin_stale_reads;
253 while stale > 0 {
254 let phase = !self.admin_phase;
255 self.push_admin(phase, cid, 0);
256 stale -= 1;
257 }
258 let raw = self.behavior.admin_raw_status.unwrap_or(0);
259 let phase = self.admin_phase;
260 self.push_admin(phase, echo, raw);
261 }
262 self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH;
263 self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH;
264 if self.admin_cq_tail == 0 {
265 self.admin_phase = !self.admin_phase;
266 }
267 }
268
269 fn on_io_doorbell(&mut self) {
270 let Some(sq) = self.io_sq_base else {
271 return;
272 };
273 if self.io_depth == 0 {
274 return;
275 }
276 let slot = self.io_sq_tail;
277 let cmd = self.peek_command(sq, slot);
278 let cid = u16::from_le_bytes([cmd[2], cmd[3]]);
279 self.io_commands += 1;
280 if !self.behavior.io_never_complete {
281 let echo = if self.behavior.io_cid_delta == 0 {
282 cid
283 } else {
284 cid.wrapping_add(self.behavior.io_cid_delta as u16)
285 };
286 let mut stale = self.behavior.io_stale_reads;
287 while stale > 0 {
288 let phase = !self.io_phase;
289 self.push_io(phase, cid, 0);
290 stale -= 1;
291 }
292 let raw = self.behavior.io_raw_status.unwrap_or(0);
293 let phase = self.io_phase;
294 self.push_io(phase, echo, raw);
295 }
296 self.io_sq_tail = (slot + 1) % self.io_depth;
297 self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth;
298 if self.io_cq_tail == 0 {
299 self.io_phase = !self.io_phase;
300 }
301 }
302
303 fn reg_read(&mut self, offset: u32) -> u32 {
304 match offset {
305 0 => CAP_LOW,
306 4 => 0,
307 REG_CC => self.cc,
308 REG_CSTS => self.csts,
309 _ => 0,
310 }
311 }
312
313 fn reg_write(&mut self, offset: u32, value: u32) {
314 match offset {
315 REG_CC => {
316 self.cc = value;
317 self.csts = if value & 1 == 0 {
318 0
319 } else if self.fatal_on_enable {
320 CSTS_CFS
321 } else if self.never_ready {
322 0
323 } else {
324 CSTS_RDY
325 };
326 }
327 REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value),
328 x if x == REG_ASQ + 4 => self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32),
329 REG_ACQ => {
330 self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value);
331 self.admin_cq_base = Some(self.acq);
332 self.admin_cq_len = PAGE;
333 }
334 x if x == REG_ACQ + 4 => {
335 self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32);
336 self.admin_cq_base = Some(self.acq);
337 self.admin_cq_len = PAGE;
338 }
339 ADMIN_DOORBELL => self.on_admin_doorbell(),
340 IO_SQ_DOORBELL => self.on_io_doorbell(),
341 _ => {}
342 }
343 }
344}
345
346// ---------------------------------------------------------------------------
347// Fakes implementing the public driver traits
348// ---------------------------------------------------------------------------
349
350struct FakeRegs {
351 shared: Shared,
352}
353
354impl Registers for FakeRegs {
355 fn read32(&mut self, offset: u32) -> u32 {
356 self.shared.borrow_mut().reg_read(offset)
357 }
358 fn write32(&mut self, offset: u32, value: u32) {
359 self.shared.borrow_mut().reg_write(offset, value);
360 }
361}
362
363struct FakeDma {
364 shared: Shared,
365}
366
367impl DmaMemory for FakeDma {
368 fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
369 let physical = self.shared.borrow_mut().alloc(size, alignment);
370 Ok(DmaRegion {
371 physical,
372 bytes: vec![0; size],
373 })
374 }
375 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
376 self.shared.borrow_mut().read_mem(physical, output)
377 }
378 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
379 self.shared.borrow_mut().write_mem(physical, input)
380 }
381}
382
383#[derive(Default)]
384struct CountingDelay {
385 waited_us: Rc<RefCell<u64>>,
386}
387
388impl Delay for CountingDelay {
389 fn delay_us(&mut self, us: u32) {
390 *self.waited_us.borrow_mut() += u64::from(us);
391 }
392}
393
394type Controller = NvmeController<FakeRegs, FakeDma, CountingDelay>;
395
396/// Build a controller that completes its initialization normally.
397fn make_controller() -> (Controller, Shared, Rc<RefCell<u64>>) {
398 let shared: Shared = Rc::new(RefCell::new(Device::new()));
399 let regs = FakeRegs {
400 shared: shared.clone(),
401 };
402 let dma = FakeDma {
403 shared: shared.clone(),
404 };
405 let delay = CountingDelay::default();
406 let waited = delay.waited_us.clone();
407 let controller = NvmeController::init(regs, dma, delay).expect("init should succeed");
408 (controller, shared, waited)
409}
410
411// ---------------------------------------------------------------------------
412// Tests
413// ---------------------------------------------------------------------------
414
415#[test]
416fn admin_command_id_mismatch_reports_invalid_identify() {
417 let (mut controller, shared, _) = make_controller();
418 shared.borrow_mut().behavior.admin_cid_delta = 1;
419 assert_eq!(
420 controller.identify_controller(),
421 Err(NvmeError::InvalidIdentify)
422 );
423}
424
425#[test]
426fn io_command_id_mismatch_reports_device_error() {
427 let (mut controller, shared, _) = make_controller();
428 controller.create_io_queues(4).unwrap();
429 shared.borrow_mut().behavior.io_cid_delta = 1;
430 let mut buffer = [0u8; 512];
431 assert_eq!(
432 controller.read_blocks(0, &mut buffer),
433 Err(BlockError::DeviceError)
434 );
435}
436
437#[test]
438fn stale_phase_completion_is_skipped_and_matching_one_consumed() {
439 let (mut controller, shared, waited) = make_controller();
440 shared.borrow_mut().behavior.admin_stale_reads = 1;
441 let before = *waited.borrow();
442 controller.identify_controller().unwrap();
443 // Exactly one backoff: the stale entry was skipped, the real one consumed.
444 assert_eq!(*waited.borrow() - before, 1_000);
445 let device = shared.borrow();
446 assert!(device.admin_queue.is_empty());
447 assert_eq!(device.admin_commands, 3); // two during init + this one
448 assert!(device.admin_phase);
449}
450
451#[test]
452fn admin_cq_phase_flips_when_head_wraps_at_depth_eight() {
453 let (mut controller, shared, _) = make_controller();
454 for _ in 0..6 {
455 controller.identify_controller().unwrap();
456 }
457 {
458 let device = shared.borrow();
459 assert_eq!(device.admin_commands, 8);
460 assert_eq!(device.admin_cq_tail, 0);
461 assert!(!device.admin_phase, "phase must flip once the head wraps");
462 }
463 // The 9th command only completes if the driver tracked the same flip.
464 controller.identify_controller().unwrap();
465 let device = shared.borrow();
466 assert_eq!(device.admin_commands, 9);
467 assert!(!device.admin_phase);
468}
469
470#[test]
471fn admin_timeout_is_bounded_no_infinite_loop() {
472 let (mut controller, shared, waited) = make_controller();
473 shared.borrow_mut().behavior.admin_never_complete = true;
474 let before = *waited.borrow();
475 assert_eq!(controller.identify_controller(), Err(NvmeError::Timeout));
476 assert_eq!(*waited.borrow() - before, POLLS * 1_000);
477}
478
479#[test]
480fn io_timeout_is_bounded_no_infinite_loop() {
481 let (mut controller, shared, waited) = make_controller();
482 controller.create_io_queues(4).unwrap();
483 shared.borrow_mut().behavior.io_never_complete = true;
484 let before = *waited.borrow();
485 let mut buffer = [0u8; 512];
486 assert_eq!(
487 controller.read_blocks(0, &mut buffer),
488 Err(BlockError::Timeout)
489 );
490 assert_eq!(*waited.borrow() - before, POLLS * 1_000);
491}
492
493#[test]
494fn controller_fatal_status_maps_to_controller_failed() {
495 let shared: Shared = Rc::new(RefCell::new(Device::new()));
496 shared.borrow_mut().fatal_on_enable = true;
497 let regs = FakeRegs {
498 shared: shared.clone(),
499 };
500 let dma = FakeDma {
501 shared: shared.clone(),
502 };
503 let result = NvmeController::init(regs, dma, CountingDelay::default());
504 assert_eq!(
505 result.err(),
506 Some(NvmeError::Controller(ControllerError::Failed))
507 );
508}
509
510#[test]
511fn controller_never_ready_maps_to_controller_timeout() {
512 let shared: Shared = Rc::new(RefCell::new(Device::new()));
513 shared.borrow_mut().never_ready = true;
514 let regs = FakeRegs {
515 shared: shared.clone(),
516 };
517 let dma = FakeDma {
518 shared: shared.clone(),
519 };
520 let result = NvmeController::init(regs, dma, CountingDelay::default());
521 assert_eq!(
522 result.err(),
523 Some(NvmeError::Controller(ControllerError::Timeout))
524 );
525}
526
527#[test]
528fn admin_status_word_decodes_exact_sc_and_sct() {
529 // status word 0x0002 -> status >> 1 = 1 -> sc 1, sct 0.
530 let (mut controller, shared, _) = make_controller();
531 shared.borrow_mut().behavior.admin_raw_status = Some(0x0002);
532 assert_eq!(
533 controller.identify_namespace(1),
534 Err(NvmeError::CompletionStatus { sct: 0, sc: 1 })
535 );
536
537 // 0x2804 style: 0x2804 >> 1 = 0x1402 -> sc 2, sct (0x1402 >> 8) & 7 = 4.
538 let (mut controller, shared, _) = make_controller();
539 shared.borrow_mut().behavior.admin_raw_status = Some(0x2804);
540 assert_eq!(
541 controller.identify_namespace(1),
542 Err(NvmeError::CompletionStatus { sct: 4, sc: 2 })
543 );
544}
545
546#[test]
547fn io_nonzero_status_maps_to_device_error() {
548 let (mut controller, shared, _) = make_controller();
549 controller.create_io_queues(4).unwrap();
550 shared.borrow_mut().behavior.io_raw_status = Some(0x0002);
551 let mut buffer = [0u8; 512];
552 assert_eq!(
553 controller.read_blocks(0, &mut buffer),
554 Err(BlockError::DeviceError)
555 );
556}
557
558#[test]
559fn malformed_completions_do_not_panic() {
560 // Garbage status word: 0xffff -> sc 0xff, sct 7. Must decode, not panic.
561 let (mut controller, shared, _) = make_controller();
562 shared.borrow_mut().behavior.admin_raw_status = Some(0xffff);
563 assert_eq!(
564 controller.identify_namespace(1),
565 Err(NvmeError::CompletionStatus { sct: 7, sc: 0xff })
566 );
567
568 // All-zero CQE has phase 0, which mismatches the live phase, so it is
569 // ignored until the poll budget runs out.
570 let (mut controller, shared, _) = make_controller();
571 shared.borrow_mut().behavior.admin_never_complete = true;
572 assert_eq!(controller.identify_controller(), Err(NvmeError::Timeout));
573}
574
575#[test]
576fn io_cq_wraparound_consumes_completions_in_order() {
577 let (mut controller, shared, _) = make_controller();
578 controller.create_io_queues(4).unwrap();
579 for lba in 0..4u64 {
580 let mut buffer = [0u8; 512];
581 controller.read_blocks(lba, &mut buffer).unwrap();
582 }
583 {
584 let device = shared.borrow();
585 assert_eq!(device.io_cq_tail, 0);
586 assert!(!device.io_phase, "I/O CQ phase must flip at depth 4");
587 assert_eq!(device.io_commands, 4);
588 }
589 // A fifth transfer only succeeds if the driver flipped in lockstep.
590 let mut buffer = [0u8; 512];
591 controller.read_blocks(4, &mut buffer).unwrap();
592 let device = shared.borrow();
593 assert_eq!(device.io_commands, 5);
594 assert!(device.io_queue.is_empty());
595}
596
597#[test]
598fn completion_accessors_decode_little_endian_fields() {
599 let mut raw = [0u8; 16];
600 raw[0..4].copy_from_slice(&0x1122_3344u32.to_le_bytes());
601 raw[8..10].copy_from_slice(&0x5566u16.to_le_bytes());
602 raw[10..12].copy_from_slice(&0x7788u16.to_le_bytes());
603 raw[12..14].copy_from_slice(&0x99aau16.to_le_bytes());
604 raw[14..16].copy_from_slice(&0x0003u16.to_le_bytes());
605 let cqe = Completion(raw);
606 assert_eq!(cqe.result(), 0x1122_3344);
607 assert_eq!(cqe.sq_head(), 0x5566);
608 assert_eq!(cqe.sq_id(), 0x7788);
609 assert_eq!(cqe.command_id(), 0x99aa);
610 assert_eq!(cqe.status(), 0x0003);
611 assert!(cqe.phase());
612}
613
614#[test]
615fn completion_queue_phase_flips_at_depth_eight() {
616 let mut mem = vec![Completion([0u8; 16]); 8];
617 for entry in &mut mem {
618 entry.0[14..16].copy_from_slice(&1u16.to_le_bytes());
619 }
620 let mut queue = CompletionQueue::new(&mem);
621 for _ in 0..8 {
622 assert!(queue.poll().is_some());
623 }
624 assert_eq!(queue.head(), 0);
625 assert!(!queue.phase());
626 assert!(queue.poll().is_none());
627}
628
629// Keep Submission in scope for device-model fidelity and to document the
630// layouts the fake parses (opcode/CID/PRP dwords).
631#[allow(dead_code)]
632fn submission_layout_probe() -> Submission {
633 Submission::identify_controller(0)
634}