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 / src / nvme / driver.rs

1179 lines · 44783 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//! Polled NVMe admin controller initialization and Identify commands.
17
18use crate::block::BlockError;
19use alloc::vec;
20use alloc::vec::Vec;
21
22use super::{
23 build_prps, doorbell_offset, Cap, Completion, ControllerError, Registers, Submission, CC_EN,
24 CSTS_CFS, CSTS_RDY, REG_ACQ, REG_AQA, REG_ASQ, REG_CC, REG_CSTS,
25};
26
27use super::atomicity::{self, AtomicityFields};
28
29pub const PAGE_SIZE: usize = 4096;
30pub const ADMIN_DEPTH: usize = 8;
31/// Admin commands complete quickly; bound the wait in real time.
32const ADMIN_TIMEOUT_MS: u32 = 1000;
33
34/// Real-time delay used to bound register and completion polling.
35pub trait Delay {
36 fn delay_us(&mut self, us: u32);
37}
38
39/// Wait for CSTS.RDY to equal `want`, polling every 1 ms for up to
40/// `timeout_ms`. CSTS.CFS aborts immediately.
41fn wait_ready<R: Registers, T: Delay>(
42 registers: &mut R,
43 delay: &mut T,
44 want: bool,
45 timeout_ms: u32,
46) -> Result<(), ControllerError> {
47 for _ in 0..=timeout_ms {
48 let status = registers.read32(REG_CSTS);
49 if status & CSTS_CFS != 0 {
50 return Err(ControllerError::Failed);
51 }
52 if (status & CSTS_RDY != 0) == want {
53 return Ok(());
54 }
55 delay.delay_us(1000);
56 }
57 Err(ControllerError::Timeout)
58}
59const CC_NVM: u32 = 0 << 4;
60const CC_MPS_4K: u32 = 0 << 7;
61const CC_IOSQES_64: u32 = 6 << 16;
62const CC_IOCQES_16: u32 = 4 << 20;
63
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub enum NvmeError {
66 Controller(ControllerError),
67 Dma,
68 Timeout,
69 CompletionStatus {
70 sct: u8,
71 sc: u8,
72 },
73 InvalidIdentify,
74 InvalidQueueDepth,
75 /// The controller needs a memory page size larger than the 4 KiB the
76 /// driver programs into CC.MPS (CAP.MPSMIN != 0), or another base
77 /// property this read substrate does not support.
78 UnsupportedController,
79}
80
81/// A zeroed, physically contiguous DMA allocation and its CPU byte view.
82pub struct DmaRegion {
83 pub physical: u64,
84 pub bytes: Vec<u8>,
85}
86
87pub trait DmaMemory {
88 fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError>;
89 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError>;
90 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError>;
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94pub struct NamespaceInfo {
95 pub block_count: u64,
96 pub block_size: u32,
97}
98
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub struct IoQueueState {
101 pub depth: u16,
102 pub submission_tail: usize,
103 pub completion_head: usize,
104 pub phase: bool,
105 pub submission_doorbell: u32,
106 pub completion_doorbell: u32,
107}
108
109pub struct NvmeController<R: Registers, D: DmaMemory, T: Delay> {
110 pub registers: R,
111 pub dma: D,
112 delay: T,
113 cap: Cap,
114 sq: DmaRegion,
115 cq: DmaRegion,
116 identify: DmaRegion,
117 sq_tail: usize,
118 cq_head: usize,
119 phase: bool,
120 next_cid: u16,
121 io_cq: Option<DmaRegion>,
122 io_sq: Option<DmaRegion>,
123 io_queue: Option<IoQueueState>,
124 mdts: u8,
125 namespace: Option<NamespaceInfo>,
126 awupf_raw: Option<u16>,
127 nawupf_raw: Option<u16>,
128 nabspf_raw: Option<u16>,
129 nabo_blocks: u16,
130}
131
132impl<R: Registers, D: DmaMemory, T: Delay> NvmeController<R, D, T> {
133 /// Reset and enable the controller. Ready waits honour CAP.TO (500 ms units).
134 pub fn init(mut registers: R, mut dma: D, mut delay: T) -> Result<Self, NvmeError> {
135 let cap = Cap(((registers.read32(4) as u64) << 32) | registers.read32(0) as u64);
136 // The driver programs CC.MPS for a 4 KiB memory page (CC_MPS_4K) and
137 // builds 4 KiB queues, so a controller that demands a larger minimum
138 // page size is refused rather than mis-programmed.
139 if cap.mpsmin() != 0 {
140 return Err(NvmeError::UnsupportedController);
141 }
142 let timeout_ms = u32::from(cap.timeout_units().max(1)) * 500;
143 let cc = registers.read32(REG_CC);
144 registers.write32(REG_CC, cc & !CC_EN);
145 wait_ready(&mut registers, &mut delay, false, timeout_ms).map_err(NvmeError::Controller)?;
146 let sq = dma.allocate(PAGE_SIZE, PAGE_SIZE)?;
147 let cq = dma.allocate(PAGE_SIZE, PAGE_SIZE)?;
148 let identify = dma.allocate(PAGE_SIZE, PAGE_SIZE)?;
149 registers.write32(
150 REG_AQA,
151 ((ADMIN_DEPTH as u32 - 1) << 16) | (ADMIN_DEPTH as u32 - 1),
152 );
153 registers.write32(REG_ASQ, sq.physical as u32);
154 registers.write32(REG_ASQ + 4, (sq.physical >> 32) as u32);
155 registers.write32(REG_ACQ, cq.physical as u32);
156 registers.write32(REG_ACQ + 4, (cq.physical >> 32) as u32);
157 let cc = CC_NVM | CC_MPS_4K | CC_IOSQES_64 | CC_IOCQES_16 | CC_EN;
158 registers.write32(REG_CC, cc);
159 wait_ready(&mut registers, &mut delay, true, timeout_ms).map_err(NvmeError::Controller)?;
160 let mut controller = Self {
161 registers,
162 dma,
163 delay,
164 cap,
165 sq,
166 cq,
167 identify,
168 sq_tail: 0,
169 cq_head: 0,
170 phase: true,
171 next_cid: 1,
172 io_cq: None,
173 io_sq: None,
174 io_queue: None,
175 mdts: 0,
176 namespace: None,
177 awupf_raw: None,
178 nawupf_raw: None,
179 nabspf_raw: None,
180 nabo_blocks: 0,
181 };
182 controller.identify_controller()?;
183 controller.identify_namespace(1)?;
184 Ok(controller)
185 }
186
187 pub fn identify_controller(&mut self) -> Result<(), NvmeError> {
188 let bytes = self.submit_identify(0, 1)?;
189 self.mdts = bytes[77];
190 // NVMe 1.4 Identify Controller: AWUPF is a 0-based power-fail atomic
191 // write unit in logical blocks.
192 self.awupf_raw = atomicity::read_u16_le(&bytes, atomicity::ID_CTRL_AWUPF_OFFSET);
193 Ok(())
194 }
195
196 pub fn identify_namespace(&mut self, nsid: u32) -> Result<NamespaceInfo, NvmeError> {
197 let bytes = self.submit_identify(nsid, 0)?;
198 let block_count = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
199 let flbas = (bytes[26] & 0x0f) as usize;
200 let descriptor = 128 + flbas * 4;
201 let lbads = *bytes
202 .get(descriptor + 2)
203 .ok_or(NvmeError::InvalidIdentify)?;
204 // NVMe LBA sizes are 512 bytes (lbads 9) through 2^31; anything smaller
205 // is not a valid data block size.
206 if block_count == 0 || !(9..=31).contains(&lbads) {
207 return Err(NvmeError::InvalidIdentify);
208 }
209 let info = NamespaceInfo {
210 block_count,
211 block_size: 1u32 << lbads,
212 };
213 self.namespace = Some(info);
214 // NVMe 1.4 Identify Namespace: NAWUPF/NABO/NABSPF, all little-endian.
215 // NAWUPF 0h means the controller AWUPF applies; NABSPF 0h means no
216 // atomic boundary.
217 self.nawupf_raw = atomicity::read_u16_le(&bytes, atomicity::ID_NS_NAWUPF_OFFSET);
218 self.nabo_blocks =
219 atomicity::read_u16_le(&bytes, atomicity::ID_NS_NABO_OFFSET).unwrap_or(0);
220 self.nabspf_raw = atomicity::read_u16_le(&bytes, atomicity::ID_NS_NABSPF_OFFSET);
221 Ok(info)
222 }
223
224 /// The effective power-fail atomicity contract for the identified
225 /// namespace, or `None` before a namespace has been identified.
226 pub fn atomicity(&self) -> Option<AtomicityFields> {
227 let namespace = self.namespace?;
228 Some(AtomicityFields {
229 lba_bytes: namespace.block_size,
230 awupf_raw: self.awupf_raw,
231 nawupf_raw: self.nawupf_raw,
232 nabspf_raw: self.nabspf_raw,
233 nabo_blocks: self.nabo_blocks,
234 })
235 }
236
237 /// Create polled I/O completion and submission queues, both with QID 1.
238 pub fn create_io_queues(&mut self, depth: u16) -> Result<(), NvmeError> {
239 // NVMe requires at least 2 entries, and the queue may not exceed the
240 // controller's advertised maximum (CAP.MQES + 1).
241 if depth < 2 || depth > self.cap.mqes() {
242 return Err(NvmeError::InvalidQueueDepth);
243 }
244 let size = usize::from(depth).checked_mul(16).ok_or(NvmeError::Dma)?;
245 let cq = self.dma.allocate(size, PAGE_SIZE)?;
246 let sq = self.dma.allocate(
247 usize::from(depth).checked_mul(64).ok_or(NvmeError::Dma)?,
248 PAGE_SIZE,
249 )?;
250 self.submit_admin(Submission::create_io_cq(1, depth, cq.physical))?;
251 self.submit_admin(Submission::create_io_sq(1, depth, sq.physical, 1))?;
252 self.io_cq = Some(cq);
253 self.io_sq = Some(sq);
254 let stride = self.cap.doorbell_stride();
255 self.io_queue = Some(IoQueueState {
256 depth,
257 submission_tail: 0,
258 completion_head: 0,
259 phase: true,
260 submission_doorbell: doorbell_offset(1, false, stride),
261 completion_doorbell: doorbell_offset(1, true, stride),
262 });
263 Ok(())
264 }
265
266 pub fn io_queue(&self) -> Option<IoQueueState> {
267 self.io_queue
268 }
269
270 fn submit_admin(&mut self, command: Submission) -> Result<(), NvmeError> {
271 self.submit_admin_inner(command)?;
272 Ok(())
273 }
274
275 fn submit_admin_inner(&mut self, mut command: Submission) -> Result<Vec<u8>, NvmeError> {
276 let cid = self.next_cid;
277 self.next_cid = self.next_cid.wrapping_add(1);
278 command.set_u32(0, (command.u32_at(0) & 0xffff) | ((cid as u32) << 16));
279 let offset = self.sq_tail * 64;
280 self.sq.bytes[offset..offset + 64].copy_from_slice(&command.0);
281 self.dma
282 .write(self.sq.physical + offset as u64, &command.0)?;
283 self.sq_tail = (self.sq_tail + 1) % ADMIN_DEPTH;
284 self.registers.write32(
285 doorbell_offset(0, false, self.cap.doorbell_stride()),
286 self.sq_tail as u32,
287 );
288 for _ in 0..=ADMIN_TIMEOUT_MS {
289 let mut raw = [0u8; 16];
290 self.dma
291 .read(self.cq.physical + (self.cq_head * 16) as u64, &mut raw)?;
292 let completion = Completion(raw);
293 if completion.phase() != self.phase {
294 self.delay.delay_us(1000);
295 continue;
296 }
297 if completion.command_id() != cid {
298 return Err(NvmeError::InvalidIdentify);
299 }
300 let status = completion.status() >> 1;
301 if status != 0 {
302 return Err(NvmeError::CompletionStatus {
303 sct: ((status >> 8) & 7) as u8,
304 sc: (status & 0xff) as u8,
305 });
306 }
307 self.cq_head += 1;
308 if self.cq_head == ADMIN_DEPTH {
309 self.cq_head = 0;
310 self.phase = !self.phase;
311 }
312 self.registers.write32(
313 doorbell_offset(0, true, self.cap.doorbell_stride()),
314 self.cq_head as u32,
315 );
316 let mut data = vec![0; PAGE_SIZE];
317 self.dma.read(self.identify.physical, &mut data)?;
318 return Ok(data);
319 }
320 Err(NvmeError::Timeout)
321 }
322
323 fn submit_identify(&mut self, nsid: u32, cns: u32) -> Result<Vec<u8>, NvmeError> {
324 self.identify.bytes.fill(0);
325 self.dma
326 .write(self.identify.physical, &self.identify.bytes)?;
327 let command = if cns == 1 {
328 Submission::identify_controller(self.identify.physical)
329 } else {
330 Submission::identify_namespace(nsid, self.identify.physical)
331 };
332 self.submit_admin_inner(command)
333 }
334
335 fn ensure_namespace(&mut self) -> Result<NamespaceInfo, BlockError> {
336 match self.namespace {
337 Some(info) => Ok(info),
338 None => self.identify_namespace(1).map_err(map_error),
339 }
340 }
341
342 fn transfer(
343 &mut self,
344 nsid: u32,
345 write: bool,
346 lba: u64,
347 data: &mut [u8],
348 ) -> Result<(), BlockError> {
349 let info = self.ensure_namespace()?;
350 let block_size = info.block_size as usize;
351 if data.is_empty() || !data.len().is_multiple_of(block_size) {
352 return Err(BlockError::InvalidInput);
353 }
354 let blocks =
355 u64::try_from(data.len() / block_size).map_err(|_| BlockError::InvalidInput)?;
356 if lba
357 .checked_add(blocks)
358 .filter(|end| *end <= info.block_count)
359 .is_none()
360 {
361 return Err(BlockError::OutOfRange);
362 }
363 let mdts_limit = if self.mdts == 0 {
364 128 * 1024
365 } else {
366 (PAGE_SIZE
367 .checked_shl(u32::from(self.mdts))
368 .unwrap_or(usize::MAX))
369 .min(128 * 1024)
370 };
371 let chunk_limit = mdts_limit / block_size * block_size;
372 if chunk_limit == 0 {
373 return Err(BlockError::InvalidInput);
374 }
375 let mut offset = 0usize;
376 while offset < data.len() {
377 let len = (data.len() - offset).min(chunk_limit);
378 let count = len / block_size;
379 let mut region = self.dma.allocate(len, PAGE_SIZE).map_err(map_error)?;
380 if write {
381 region.bytes[..len].copy_from_slice(&data[offset..offset + len]);
382 self.dma
383 .write(region.physical, &region.bytes[..len])
384 .map_err(map_error)?;
385 }
386 let list_pages = len.div_ceil(PAGE_SIZE);
387 let list_region = if list_pages > 2 {
388 Some(self.dma.allocate(PAGE_SIZE, PAGE_SIZE).map_err(map_error)?)
389 } else {
390 None
391 };
392 let mut list = alloc::vec![0u64; PAGE_SIZE / 8];
393 let list_address = list_region.as_ref().map_or(0, |r| r.physical);
394 let (p1, p2, used) =
395 build_prps(region.physical, len, PAGE_SIZE, list_address, &mut list)
396 .map_err(|_| BlockError::InvalidInput)?;
397 if let Some(ref list_mem) = list_region {
398 let bytes =
399 unsafe { core::slice::from_raw_parts(list.as_ptr() as *const u8, used * 8) };
400 self.dma
401 .write(list_mem.physical, bytes)
402 .map_err(map_error)?;
403 }
404 self.submit_io(if write {
405 Submission::write(
406 nsid,
407 lba + (offset / block_size) as u64,
408 count as u16,
409 p1,
410 p2,
411 )
412 } else {
413 Submission::read(
414 nsid,
415 lba + (offset / block_size) as u64,
416 count as u16,
417 p1,
418 p2,
419 )
420 })?;
421 if !write {
422 self.dma
423 .read(region.physical, &mut data[offset..offset + len])
424 .map_err(map_error)?;
425 }
426 offset += len;
427 }
428 Ok(())
429 }
430
431 fn submit_io(&mut self, mut command: Submission) -> Result<(), BlockError> {
432 let q = self.io_queue.as_mut().ok_or(BlockError::DeviceError)?;
433 let sq = self.io_sq.as_mut().ok_or(BlockError::DeviceError)?;
434 let cq = self.io_cq.as_ref().ok_or(BlockError::DeviceError)?;
435 let cid = self.next_cid;
436 self.next_cid = self.next_cid.wrapping_add(1);
437 command.set_u32(0, (command.u32_at(0) & 0xffff) | (u32::from(cid) << 16));
438 let offset = q.submission_tail * 64;
439 sq.bytes[offset..offset + 64].copy_from_slice(&command.0);
440 self.dma
441 .write(sq.physical + offset as u64, &command.0)
442 .map_err(map_error)?;
443 q.submission_tail = (q.submission_tail + 1) % usize::from(q.depth);
444 self.registers
445 .write32(q.submission_doorbell, q.submission_tail as u32);
446 for _ in 0..=1000 {
447 let mut raw = [0u8; 16];
448 self.dma
449 .read(cq.physical + (q.completion_head * 16) as u64, &mut raw)
450 .map_err(map_error)?;
451 let c = Completion(raw);
452 if c.phase() != q.phase {
453 self.delay.delay_us(1000);
454 continue;
455 }
456 if c.command_id() != cid {
457 return Err(BlockError::DeviceError);
458 }
459 let status = c.status() >> 1;
460 q.completion_head = (q.completion_head + 1) % usize::from(q.depth);
461 if q.completion_head == 0 {
462 q.phase = !q.phase;
463 }
464 self.registers
465 .write32(q.completion_doorbell, q.completion_head as u32);
466 return if status == 0 {
467 Ok(())
468 } else {
469 Err(BlockError::DeviceError)
470 };
471 }
472 Err(BlockError::Timeout)
473 }
474}
475
476fn map_error(error: NvmeError) -> BlockError {
477 match error {
478 NvmeError::Timeout => BlockError::Timeout,
479 NvmeError::Dma => BlockError::DeviceError,
480 NvmeError::CompletionStatus { .. } => BlockError::DeviceError,
481 _ => BlockError::DeviceError,
482 }
483}
484
485impl<R: Registers, D: DmaMemory, T: Delay> crate::block::BlockDevice for NvmeController<R, D, T> {
486 fn block_size(&self) -> u32 {
487 self.namespace.map_or(0, |n| n.block_size)
488 }
489 fn block_count(&self) -> u64 {
490 self.namespace.map_or(0, |n| n.block_count)
491 }
492 fn read_blocks(&mut self, lba: u64, buffer: &mut [u8]) -> Result<(), BlockError> {
493 self.transfer(1, false, lba, buffer)
494 }
495 fn write_blocks(&mut self, lba: u64, buffer: &[u8]) -> Result<(), BlockError> {
496 let mut owned = buffer.to_vec();
497 self.transfer(1, true, lba, &mut owned)
498 }
499 fn flush(&mut self) -> Result<(), BlockError> {
500 self.submit_io({
501 let mut c = Submission::zeroed();
502 c.set_u32(0, 0);
503 c.set_u32(1, 1);
504 c
505 })
506 }
507}
508
509impl<R: Registers, D: DmaMemory, T: Delay> NvmeController<R, D, T> {
510 /// Read `buffer` from an explicit namespace id. The `BlockDevice` trait
511 /// path fixes NSID 1; this exists so a caller (and the qualification
512 /// phase) can exercise the invalid-namespace error path and any future
513 /// multi-namespace use without special-casing the driver.
514 pub fn read_blocks_nsid(
515 &mut self,
516 nsid: u32,
517 lba: u64,
518 buffer: &mut [u8],
519 ) -> Result<(), BlockError> {
520 self.transfer(nsid, false, lba, buffer)
521 }
522
523 /// Write `buffer` to an explicit namespace id. See `read_blocks_nsid`.
524 pub fn write_blocks_nsid(
525 &mut self,
526 nsid: u32,
527 lba: u64,
528 buffer: &[u8],
529 ) -> Result<(), BlockError> {
530 let mut owned = buffer.to_vec();
531 self.transfer(nsid, true, lba, &mut owned)
532 }
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538 use alloc::collections::BTreeMap;
539 use alloc::rc::Rc;
540 use core::cell::RefCell;
541 use std::vec;
542
543 type Shared = Rc<RefCell<BTreeMap<u64, Vec<u8>>>>;
544
545 struct FakeDma {
546 shared: Shared,
547 next: u64,
548 }
549 impl DmaMemory for FakeDma {
550 fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
551 assert_eq!(alignment, PAGE_SIZE);
552 let physical = self.next;
553 self.next = (self.next + size as u64 + PAGE_SIZE as u64 - 1) & !(PAGE_SIZE as u64 - 1);
554 self.shared.borrow_mut().insert(physical, vec![0; size]);
555 Ok(DmaRegion {
556 physical,
557 bytes: vec![0; size],
558 })
559 }
560 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
561 let memory = self.shared.borrow();
562 let (base, bytes) = memory
563 .range(..=physical)
564 .next_back()
565 .ok_or(NvmeError::Dma)?;
566 let offset = (physical - base) as usize;
567 output.copy_from_slice(
568 bytes
569 .get(offset..offset + output.len())
570 .ok_or(NvmeError::Dma)?,
571 );
572 Ok(())
573 }
574 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
575 let mut memory = self.shared.borrow_mut();
576 let (base, bytes) = memory
577 .range_mut(..=physical)
578 .next_back()
579 .ok_or(NvmeError::Dma)?;
580 let offset = (physical - *base) as usize;
581 bytes
582 .get_mut(offset..offset + input.len())
583 .ok_or(NvmeError::Dma)?
584 .copy_from_slice(input);
585 Ok(())
586 }
587 }
588
589 struct FakeRegs {
590 shared: Shared,
591 status: u32,
592 cc: u32,
593 writes: Vec<(u32, u32)>,
594 namespace_size: u64,
595 completion_status: u16,
596 never_ready: bool,
597 ready_after_reads: u32,
598 fatal: bool,
599 cq_tail: usize,
600 sq_tail: usize,
601 cq_ids: Vec<u16>,
602 command_error: u16,
603 disk: Vec<u8>,
604 io_sq: Option<u64>,
605 io_cq: Option<u64>,
606 io_cq_tail: usize,
607 io_sq_tail: usize,
608 io_phase: bool,
609 /// CAP high dword (offset 4). Bits 16..20 carry CAP.MPSMIN.
610 cap_high: u32,
611 /// LBA data size (lbads) the fake reports for namespace 1.
612 lbads: u8,
613 awupf: u16,
614 nawupf: u16,
615 nabspf: u16,
616 nabo: u16,
617 }
618 impl Registers for FakeRegs {
619 fn read32(&mut self, offset: u32) -> u32 {
620 match offset {
621 0 => 0x0100_03ff, // CAP.TO = 1 (500 ms), MQES = 1023
622 4 => self.cap_high,
623 REG_CC => self.cc,
624 REG_CSTS => {
625 if self.ready_after_reads > 0 && self.cc & CC_EN != 0 {
626 self.ready_after_reads -= 1;
627 return self.status & !CSTS_RDY;
628 }
629 self.status
630 }
631 _ => 0,
632 }
633 }
634 fn write32(&mut self, offset: u32, value: u32) {
635 self.writes.push((offset, value));
636 if offset == REG_CC {
637 self.cc = value;
638 self.status = if value & CC_EN == 0 {
639 0
640 } else if self.fatal {
641 CSTS_CFS
642 } else if self.never_ready {
643 0
644 } else {
645 CSTS_RDY
646 };
647 }
648 if offset == doorbell_offset(0, false, 4) {
649 let mut memory = self.shared.borrow_mut();
650 let sq = u64::from_le_bytes([
651 self.writes.iter().find(|(r, _)| *r == REG_ASQ).unwrap().1 as u8,
652 (self.writes.iter().find(|(r, _)| *r == REG_ASQ).unwrap().1 >> 8) as u8,
653 (self.writes.iter().find(|(r, _)| *r == REG_ASQ).unwrap().1 >> 16) as u8,
654 (self.writes.iter().find(|(r, _)| *r == REG_ASQ).unwrap().1 >> 24) as u8,
655 self.writes
656 .iter()
657 .find(|(r, _)| *r == REG_ASQ + 4)
658 .unwrap()
659 .1 as u8,
660 (self
661 .writes
662 .iter()
663 .find(|(r, _)| *r == REG_ASQ + 4)
664 .unwrap()
665 .1
666 >> 8) as u8,
667 (self
668 .writes
669 .iter()
670 .find(|(r, _)| *r == REG_ASQ + 4)
671 .unwrap()
672 .1
673 >> 16) as u8,
674 (self
675 .writes
676 .iter()
677 .find(|(r, _)| *r == REG_ASQ + 4)
678 .unwrap()
679 .1
680 >> 24) as u8,
681 ]);
682 let command_offset = self.sq_tail * 64;
683 let command =
684 memory.get(&sq).unwrap()[command_offset..command_offset + 64].to_vec();
685 let cid = u16::from_le_bytes([command[2], command[3]]);
686 let prp = u64::from_le_bytes(command[24..32].try_into().unwrap());
687 let opcode = u32::from_le_bytes(command[0..4].try_into().unwrap()) as u8;
688 let cdw10 = u32::from_le_bytes(command[40..44].try_into().unwrap());
689 let cdw11 = u32::from_le_bytes(command[44..48].try_into().unwrap());
690 self.command_error = 0;
691 match opcode {
692 0x06 => {
693 let cns = cdw10;
694 let data = memory.get_mut(&prp).unwrap();
695 if cns == 0 {
696 data[0..8].copy_from_slice(&self.namespace_size.to_le_bytes());
697 data[26] = 0;
698 data[130] = self.lbads;
699 data[36..38].copy_from_slice(&self.nawupf.to_le_bytes());
700 data[42..44].copy_from_slice(&self.nabo.to_le_bytes());
701 data[44..46].copy_from_slice(&self.nabspf.to_le_bytes());
702 } else if cns == 1 {
703 data[528..530].copy_from_slice(&self.awupf.to_le_bytes());
704 }
705 }
706 0x05 => {
707 assert_eq!(cdw10, 1 | (3 << 16)); // QID 1, depth 4 minus one
708 assert_eq!(cdw11, 1); // PC=1, IEN=0
709 self.cq_ids.push(1);
710 self.io_cq = Some(prp);
711 }
712 0x01 if cdw10 & 0xffff == 1 && cdw11 & 0xffff == 1 => {
713 assert_eq!(cdw10, 1 | (3 << 16));
714 assert_eq!(cdw11, 1 | (1 << 16));
715 if !self.cq_ids.contains(&1) {
716 self.command_error = 1 << 1;
717 }
718 self.io_sq = Some(prp);
719 }
720 _ => panic!("unexpected admin opcode {opcode:#x}"),
721 }
722 let cq = u64::from_le_bytes([
723 self.writes.iter().find(|(r, _)| *r == REG_ACQ).unwrap().1 as u8,
724 (self.writes.iter().find(|(r, _)| *r == REG_ACQ).unwrap().1 >> 8) as u8,
725 (self.writes.iter().find(|(r, _)| *r == REG_ACQ).unwrap().1 >> 16) as u8,
726 (self.writes.iter().find(|(r, _)| *r == REG_ACQ).unwrap().1 >> 24) as u8,
727 self.writes
728 .iter()
729 .find(|(r, _)| *r == REG_ACQ + 4)
730 .unwrap()
731 .1 as u8,
732 (self
733 .writes
734 .iter()
735 .find(|(r, _)| *r == REG_ACQ + 4)
736 .unwrap()
737 .1
738 >> 8) as u8,
739 (self
740 .writes
741 .iter()
742 .find(|(r, _)| *r == REG_ACQ + 4)
743 .unwrap()
744 .1
745 >> 16) as u8,
746 (self
747 .writes
748 .iter()
749 .find(|(r, _)| *r == REG_ACQ + 4)
750 .unwrap()
751 .1
752 >> 24) as u8,
753 ]);
754 let cqe = memory.get_mut(&cq).unwrap();
755 let completion_offset = self.cq_tail * 16;
756 cqe[completion_offset + 12..completion_offset + 14]
757 .copy_from_slice(&cid.to_le_bytes());
758 cqe[completion_offset + 14..completion_offset + 16].copy_from_slice(
759 &(1 | self.completion_status | self.command_error).to_le_bytes(),
760 );
761 self.cq_tail = (self.cq_tail + 1) % ADMIN_DEPTH;
762 self.sq_tail = (self.sq_tail + 1) % ADMIN_DEPTH;
763 }
764 if offset == doorbell_offset(1, false, 4) {
765 let mut memory = self.shared.borrow_mut();
766 let sq = self.io_sq.expect("I/O SQ created");
767 let cq = self.io_cq.expect("I/O CQ created");
768 let command_offset = self.io_sq_tail * 64;
769 let command =
770 memory.get(&sq).unwrap()[command_offset..command_offset + 64].to_vec();
771 let opcode = command[0];
772 let cid = u16::from_le_bytes(command[2..4].try_into().unwrap());
773 let nsid = u32::from_le_bytes(command[4..8].try_into().unwrap());
774 let p1 = u64::from_le_bytes(command[24..32].try_into().unwrap());
775 let p2 = u64::from_le_bytes(command[32..40].try_into().unwrap());
776 let lba = u64::from(u32::from_le_bytes(command[40..44].try_into().unwrap()))
777 | (u64::from(u32::from_le_bytes(command[44..48].try_into().unwrap())) << 32);
778 let len =
779 (u32::from_le_bytes(command[48..52].try_into().unwrap()) as usize + 1) * 512;
780 self.command_error = 0;
781 if nsid != 1 {
782 self.command_error = 1 << 1;
783 }
784 if opcode == 0x01 || opcode == 0x02 {
785 let mut addresses = vec![p1];
786 let first = (PAGE_SIZE - (p1 as usize & (PAGE_SIZE - 1))).min(len);
787 let remaining = len.saturating_sub(first);
788 if remaining > 0 {
789 if p2 != 0 && remaining <= PAGE_SIZE {
790 addresses.push(p2);
791 } else {
792 let mut list_page = p2;
793 let mut left = remaining;
794 while left > 0 {
795 let entries = memory.get(&list_page).unwrap();
796 for i in 0..PAGE_SIZE / 8 {
797 let address = u64::from_le_bytes(
798 entries[i * 8..i * 8 + 8].try_into().unwrap(),
799 );
800 if address == 0 {
801 break;
802 }
803 if i == PAGE_SIZE / 8 - 1 && left > PAGE_SIZE {
804 list_page = address;
805 break;
806 }
807 addresses.push(address);
808 left = left.saturating_sub(PAGE_SIZE);
809 if left == 0 {
810 break;
811 }
812 }
813 }
814 }
815 }
816 let disk_start = lba as usize * 512;
817 let mut done = 0;
818 for address in addresses {
819 if done == len {
820 break;
821 }
822 let n = (len - done).min(PAGE_SIZE - (address as usize & (PAGE_SIZE - 1)));
823 let disk = &mut self.disk[disk_start + done..disk_start + done + n];
824 let data = memory.range_mut(..=address).next_back().unwrap();
825 let off = (address - *data.0) as usize;
826 let dma = &mut data.1[off..off + n];
827 if opcode == 0x01 {
828 disk.copy_from_slice(dma);
829 } else {
830 dma.copy_from_slice(disk);
831 }
832 done += n;
833 }
834 } else if opcode != 0x00 {
835 self.command_error = 1 << 1;
836 }
837 let cqe = memory.get_mut(&cq).unwrap();
838 let at = self.io_cq_tail * 16;
839 cqe[at + 12..at + 14].copy_from_slice(&cid.to_le_bytes());
840 cqe[at + 14..at + 16].copy_from_slice(
841 &((self.io_phase as u16) | self.completion_status | self.command_error)
842 .to_le_bytes(),
843 );
844 self.io_cq_tail = (self.io_cq_tail + 1) % 4;
845 if self.io_cq_tail == 0 {
846 self.io_phase = !self.io_phase;
847 }
848 self.io_sq_tail = (self.io_sq_tail + 1) % 4;
849 }
850 }
851 }
852
853 fn fixture() -> (FakeRegs, FakeDma) {
854 let shared = Rc::new(RefCell::new(BTreeMap::new()));
855 (
856 FakeRegs {
857 shared: shared.clone(),
858 status: 0,
859 cc: 0,
860 writes: Vec::new(),
861 namespace_size: 12345,
862 completion_status: 0,
863 never_ready: false,
864 ready_after_reads: 0,
865 fatal: false,
866 cq_tail: 0,
867 sq_tail: 0,
868 cq_ids: Vec::new(),
869 command_error: 0,
870 disk: vec![0; 12345 * 512],
871 io_sq: None,
872 io_cq: None,
873 io_cq_tail: 0,
874 io_sq_tail: 0,
875 io_phase: true,
876 cap_high: 0,
877 lbads: 9,
878 awupf: 0,
879 nawupf: 0,
880 nabspf: 0,
881 nabo: 0,
882 },
883 FakeDma {
884 shared,
885 next: 0x1000,
886 },
887 )
888 }
889
890 /// Host stand-in for a real-time delay: counts 1 ms waits instead of sleeping.
891 #[derive(Default)]
892 struct CountingDelay {
893 waited_us: u64,
894 }
895 impl Delay for CountingDelay {
896 fn delay_us(&mut self, us: u32) {
897 self.waited_us += u64::from(us);
898 }
899 }
900
901 #[test]
902 fn readiness_wait_honours_cap_timeout() {
903 // CAP.TO = 1 (500 ms). Ready after 200 status reads (~200 ms): must succeed,
904 // where a fixed 100-read poll limit would have reported a timeout.
905 let (mut regs, dma) = fixture();
906 regs.ready_after_reads = 200;
907 let controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
908 let waited = controller.delay.waited_us;
909 assert!((199_000..=201_000).contains(&waited), "waited {waited} us");
910 // Never ready: gives up after about CAP.TO x 500 ms, not sooner.
911 let (mut regs, dma) = fixture();
912 regs.never_ready = true;
913 let mut delay = CountingDelay::default();
914 let mut regs2 = regs;
915 regs2.write32(REG_CC, CC_EN);
916 assert_eq!(
917 wait_ready(&mut regs2, &mut delay, true, 500),
918 Err(ControllerError::Timeout)
919 );
920 assert_eq!(delay.waited_us, 501_000);
921 let _ = dma;
922 }
923
924 #[test]
925 fn parses_power_fail_atomicity_fields() {
926 use super::atomicity::AtomicityDecision;
927 let (mut regs, dma) = fixture();
928 regs.awupf = 7; // 8 blocks
929 regs.nawupf = 3; // 4 blocks: namespace overrides
930 regs.nabspf = 7; // boundary size 8 blocks
931 regs.nabo = 0;
932 let controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
933 let a = controller.atomicity().expect("atomicity after identify");
934 assert_eq!(a.lba_bytes, 512);
935 assert_eq!(a.awupf_raw, Some(7));
936 assert_eq!(a.nawupf_raw, Some(3));
937 assert_eq!(a.nabspf_raw, Some(7));
938 assert_eq!(a.nabo_blocks, 0);
939 assert_eq!(a.effective_power_fail_blocks(), Some(4));
940 assert_eq!(a.store_unit_lba(1), Some((8, 8)));
941 assert!(matches!(
942 a.store_root_decision(0),
943 AtomicityDecision::NotAtomic(_)
944 ));
945 }
946
947 #[test]
948 fn initializes_and_identifies_namespace() {
949 let (regs, dma) = fixture();
950 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
951 assert_eq!(
952 controller
953 .registers
954 .writes
955 .iter()
956 .find(|(r, _)| *r == REG_AQA)
957 .unwrap()
958 .1,
959 0x0007_0007
960 );
961 assert_eq!(
962 controller
963 .registers
964 .writes
965 .iter()
966 .rev()
967 .find(|(r, _)| *r == REG_CC)
968 .unwrap()
969 .1,
970 CC_IOSQES_64 | CC_IOCQES_16 | CC_EN
971 );
972 assert!(controller
973 .registers
974 .writes
975 .iter()
976 .any(|(register, value)| *register == REG_ASQ && *value == 0x1000));
977 assert!(controller
978 .registers
979 .writes
980 .iter()
981 .any(|(register, value)| *register == REG_ACQ && *value == 0x2000));
982 assert_eq!(
983 controller.identify_namespace(1).unwrap(),
984 NamespaceInfo {
985 block_count: 12345,
986 block_size: 512
987 }
988 );
989 }
990
991 #[test]
992 fn creates_polled_io_queues() {
993 let (regs, dma) = fixture();
994 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
995 controller.create_io_queues(4).unwrap();
996 assert_eq!(
997 controller.io_queue(),
998 Some(IoQueueState {
999 depth: 4,
1000 submission_tail: 0,
1001 completion_head: 0,
1002 phase: true,
1003 submission_doorbell: doorbell_offset(1, false, 4),
1004 completion_doorbell: doorbell_offset(1, true, 4),
1005 })
1006 );
1007 assert_eq!(controller.registers.command_error, 0);
1008 }
1009
1010 #[test]
1011 fn simulator_rejects_submission_queue_without_completion_queue() {
1012 let (regs, dma) = fixture();
1013 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1014 assert_eq!(
1015 controller.submit_admin(Submission::create_io_sq(1, 4, 0x5000, 1)),
1016 Err(NvmeError::CompletionStatus { sct: 0, sc: 1 })
1017 );
1018 }
1019
1020 #[test]
1021 fn shallow_io_queue_is_rejected_before_submission() {
1022 let (regs, dma) = fixture();
1023 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1024 let submissions = controller
1025 .registers
1026 .writes
1027 .iter()
1028 .filter(|(offset, _)| *offset == doorbell_offset(0, false, 4))
1029 .count();
1030 assert_eq!(
1031 controller.create_io_queues(1),
1032 Err(NvmeError::InvalidQueueDepth)
1033 );
1034 assert_eq!(
1035 controller
1036 .registers
1037 .writes
1038 .iter()
1039 .filter(|(offset, _)| *offset == doorbell_offset(0, false, 4))
1040 .count(),
1041 submissions
1042 );
1043 }
1044
1045 #[test]
1046 fn block_io_roundtrips_small_and_prp_list_transfers_with_mdts_chunks() {
1047 use crate::block::BlockDevice;
1048 let (regs, dma) = fixture();
1049 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1050 controller.create_io_queues(4).unwrap();
1051 for blocks in [1usize, 8, 300] {
1052 let input: Vec<u8> = (0..blocks * 512).map(|i| (i * 17) as u8).collect();
1053 controller.write_blocks(10, &input).unwrap_or_else(|e| {
1054 panic!(
1055 "write {blocks}: {e:?}, queue {:?}, io {:?}/{:?}, tail {}",
1056 controller.io_queue,
1057 controller.registers.io_cq,
1058 controller.registers.io_sq,
1059 controller.registers.io_cq_tail
1060 )
1061 });
1062 let mut output = vec![0; input.len()];
1063 controller.read_blocks(10, &mut output).unwrap();
1064 assert_eq!(output, input);
1065 }
1066 // The final transfer exceeds the 128 KiB cap and is split into two commands.
1067 let io_doorbells = controller
1068 .registers
1069 .writes
1070 .iter()
1071 .filter(|(r, _)| *r == doorbell_offset(1, false, 4))
1072 .count();
1073 assert!(io_doorbells >= 8);
1074 }
1075
1076 #[test]
1077 fn invalid_range_has_no_io_command_and_write_completion_error_propagates() {
1078 use crate::block::{BlockDevice, BlockError};
1079 let (regs, dma) = fixture();
1080 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1081 controller.create_io_queues(4).unwrap();
1082 let before = controller
1083 .registers
1084 .writes
1085 .iter()
1086 .filter(|(r, _)| *r == doorbell_offset(1, false, 4))
1087 .count();
1088 assert_eq!(
1089 controller.write_blocks(12345, &[0; 512]),
1090 Err(BlockError::OutOfRange)
1091 );
1092 assert_eq!(
1093 controller
1094 .registers
1095 .writes
1096 .iter()
1097 .filter(|(r, _)| *r == doorbell_offset(1, false, 4))
1098 .count(),
1099 before
1100 );
1101 controller.registers.completion_status = 2;
1102 assert_eq!(
1103 controller.write_blocks(0, &[7; 512]),
1104 Err(BlockError::DeviceError)
1105 );
1106 }
1107
1108 #[test]
1109 fn readiness_and_completion_errors_are_bounded() {
1110 let (mut regs, dma) = fixture();
1111 regs.never_ready = true;
1112 assert_eq!(
1113 NvmeController::init(regs, dma, CountingDelay::default()).err(),
1114 Some(NvmeError::Controller(ControllerError::Timeout))
1115 );
1116 let (mut regs, dma) = fixture();
1117 regs.fatal = true;
1118 assert_eq!(
1119 NvmeController::init(regs, dma, CountingDelay::default()).err(),
1120 Some(NvmeError::Controller(ControllerError::Failed))
1121 );
1122 let (mut regs, dma) = fixture();
1123 regs.completion_status = 2;
1124 assert!(matches!(
1125 NvmeController::init(regs, dma, CountingDelay::default()),
1126 Err(NvmeError::CompletionStatus { sc: 1, .. })
1127 ));
1128 }
1129
1130 #[test]
1131 fn controller_requiring_larger_pages_is_refused() {
1132 let (mut regs, dma) = fixture();
1133 // CAP.MPSMIN = 1 means the controller needs 8 KiB pages; the driver
1134 // only programs 4 KiB.
1135 regs.cap_high = 1 << 16;
1136 assert_eq!(
1137 NvmeController::init(regs, dma, CountingDelay::default()).err(),
1138 Some(NvmeError::UnsupportedController)
1139 );
1140 }
1141
1142 #[test]
1143 fn io_queue_depth_above_mqes_is_rejected() {
1144 let (regs, dma) = fixture();
1145 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1146 // CAP.MQES + 1 = 1024 in the fixture.
1147 assert_eq!(
1148 controller.create_io_queues(1025),
1149 Err(NvmeError::InvalidQueueDepth)
1150 );
1151 }
1152
1153 #[test]
1154 fn lbads_below_512_is_invalid_identify() {
1155 let (mut regs, dma) = fixture();
1156 regs.lbads = 8;
1157 assert_eq!(
1158 NvmeController::init(regs, dma, CountingDelay::default()).err(),
1159 Some(NvmeError::InvalidIdentify)
1160 );
1161 }
1162
1163 #[test]
1164 fn explicit_namespace_write_surfaces_device_error() {
1165 let (regs, dma) = fixture();
1166 let mut controller = NvmeController::init(regs, dma, CountingDelay::default()).unwrap();
1167 controller.create_io_queues(4).unwrap();
1168 // The simulator rejects any NSID other than 1 with a completion error.
1169 assert_eq!(
1170 controller.write_blocks_nsid(0xffff_ffff, 0, &[0xAB; 512]),
1171 Err(BlockError::DeviceError)
1172 );
1173 // A valid explicit namespace write still round-trips.
1174 controller.write_blocks_nsid(1, 0, &[0xCD; 512]).unwrap();
1175 let mut out = [0u8; 512];
1176 controller.read_blocks_nsid(1, 0, &mut out).unwrap();
1177 assert_eq!(out, [0xCD; 512]);
1178 }
1179}