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.rs

503 lines · 16597 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//! Host-testable NVMe register, queue, command, and PRP primitives.
17//! This module performs no MMIO and owns no DMA memory.
18
19use core::convert::TryInto;
20
21pub mod atomicity;
22pub mod driver;
23
24pub const REG_CAP: u32 = 0x00;
25pub const REG_VS: u32 = 0x08;
26pub const REG_INTMS: u32 = 0x0c;
27pub const REG_CC: u32 = 0x14;
28pub const REG_CSTS: u32 = 0x1c;
29pub const REG_AQA: u32 = 0x24;
30pub const REG_ASQ: u32 = 0x28;
31pub const REG_ACQ: u32 = 0x30;
32pub const REG_DOORBELL: u32 = 0x1000;
33pub const CC_EN: u32 = 1;
34pub const CSTS_RDY: u32 = 1;
35pub const CSTS_CFS: u32 = 1 << 1;
36
37/// Abstracts 32-bit controller register accesses for a host fake or a later MMIO adapter.
38pub trait Registers {
39 fn read32(&mut self, offset: u32) -> u32;
40 fn write32(&mut self, offset: u32, value: u32);
41}
42
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct Cap(pub u64);
45
46impl Cap {
47 pub const fn dstrd(self) -> u8 {
48 ((self.0 >> 32) & 0xf) as u8
49 }
50 pub const fn doorbell_stride(self) -> u32 {
51 4 << self.dstrd()
52 }
53 pub const fn mqes(self) -> u16 {
54 (self.0 as u16).wrapping_add(1)
55 }
56 pub const fn timeout_units(self) -> u8 {
57 ((self.0 >> 24) & 0xff) as u8
58 }
59 /// CAP.MPSMIN: log2 of the minimum memory page size, in 4 KiB units.
60 pub const fn mpsmin(self) -> u8 {
61 ((self.0 >> 48) & 0xf) as u8
62 }
63}
64
65pub const fn doorbell_offset(qid: u16, completion: bool, stride: u32) -> u32 {
66 REG_DOORBELL + (2 * qid as u32 + completion as u32) * stride
67}
68
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub enum ControllerError {
71 Failed,
72 Timeout,
73}
74
75/// Bounded state transitions. `polls` is the maximum number of CSTS reads per transition.
76pub fn set_enabled<R: Registers>(
77 r: &mut R,
78 enable: bool,
79 polls: usize,
80) -> Result<(), ControllerError> {
81 let mut cc = r.read32(REG_CC);
82 if enable {
83 cc |= CC_EN;
84 } else {
85 cc &= !CC_EN;
86 }
87 r.write32(REG_CC, cc);
88 for _ in 0..polls {
89 let status = r.read32(REG_CSTS);
90 if status & CSTS_CFS != 0 {
91 return Err(ControllerError::Failed);
92 }
93 if (status & CSTS_RDY != 0) == enable {
94 return Ok(());
95 }
96 }
97 Err(ControllerError::Timeout)
98}
99
100#[derive(Clone, Copy, Debug, Eq, PartialEq)]
101pub struct Submission(pub [u8; 64]);
102
103impl Submission {
104 pub const fn zeroed() -> Self {
105 Self([0; 64])
106 }
107 pub fn set_u32(&mut self, dword: usize, value: u32) {
108 self.0[dword * 4..dword * 4 + 4].copy_from_slice(&value.to_le_bytes());
109 }
110 pub fn set_u64(&mut self, dword: usize, value: u64) {
111 self.0[dword * 4..dword * 4 + 8].copy_from_slice(&value.to_le_bytes());
112 }
113 pub fn u32_at(&self, dword: usize) -> u32 {
114 u32::from_le_bytes(self.0[dword * 4..dword * 4 + 4].try_into().unwrap())
115 }
116 pub fn identify_controller(prp1: u64) -> Self {
117 identify(prp1, 1)
118 }
119 pub fn identify_namespace(nsid: u32, prp1: u64) -> Self {
120 let mut c = identify(prp1, 0);
121 c.set_u32(1, nsid);
122 c
123 }
124 /// Create I/O Completion Queue (opcode 0x05). Polled: PC=1, IEN=0 (ADR 0009).
125 /// `depth` is the entry count; NVMe requires at least 2.
126 pub fn create_io_cq(qid: u16, depth: u16, prp1: u64) -> Self {
127 assert!(depth >= 2, "NVMe queues need at least 2 entries");
128 let mut c = Self::zeroed();
129 c.set_u32(0, 0x05);
130 c.set_u32(6, prp1 as u32);
131 c.set_u32(7, (prp1 >> 32) as u32);
132 c.set_u32(10, qid as u32 | ((depth as u32 - 1) << 16));
133 c.set_u32(11, 1);
134 c
135 }
136 /// Create I/O Submission Queue (opcode 0x01). CDW11: PC (bit 0), QPRIO
137 /// (bits 2:1, 0 = urgent/unused), CQID (bits 31:16).
138 pub fn create_io_sq(qid: u16, depth: u16, prp1: u64, cqid: u16) -> Self {
139 assert!(depth >= 2, "NVMe queues need at least 2 entries");
140 let mut c = Self::zeroed();
141 c.set_u32(0, 0x01);
142 c.set_u32(6, prp1 as u32);
143 c.set_u32(7, (prp1 >> 32) as u32);
144 c.set_u32(10, qid as u32 | ((depth as u32 - 1) << 16));
145 c.set_u32(11, 1 | ((cqid as u32) << 16));
146 c
147 }
148 pub fn read(nsid: u32, lba: u64, blocks: u16, prp1: u64, prp2: u64) -> Self {
149 io_command(0x02, nsid, lba, blocks, prp1, prp2)
150 }
151 pub fn write(nsid: u32, lba: u64, blocks: u16, prp1: u64, prp2: u64) -> Self {
152 io_command(0x01, nsid, lba, blocks, prp1, prp2)
153 }
154}
155
156fn identify(prp1: u64, cns: u32) -> Submission {
157 let mut c = Submission::zeroed();
158 c.set_u32(0, 0x06);
159 c.set_u32(6, prp1 as u32);
160 c.set_u32(7, (prp1 >> 32) as u32);
161 c.set_u32(10, cns);
162 c
163}
164fn io_command(op: u32, nsid: u32, lba: u64, blocks: u16, p1: u64, p2: u64) -> Submission {
165 let mut c = Submission::zeroed();
166 c.set_u32(0, op);
167 c.set_u32(1, nsid);
168 c.set_u32(6, p1 as u32);
169 c.set_u32(7, (p1 >> 32) as u32);
170 c.set_u32(8, p2 as u32);
171 c.set_u32(9, (p2 >> 32) as u32);
172 c.set_u32(10, lba as u32);
173 c.set_u32(11, (lba >> 32) as u32);
174 c.set_u32(12, (blocks as u32).wrapping_sub(1));
175 c
176}
177
178#[derive(Clone, Copy, Debug, Eq, PartialEq)]
179pub struct Completion(pub [u8; 16]);
180impl Completion {
181 pub fn result(&self) -> u32 {
182 u32::from_le_bytes(self.0[0..4].try_into().unwrap())
183 }
184 pub fn sq_head(&self) -> u16 {
185 u16::from_le_bytes(self.0[8..10].try_into().unwrap())
186 }
187 pub fn sq_id(&self) -> u16 {
188 u16::from_le_bytes(self.0[10..12].try_into().unwrap())
189 }
190 pub fn command_id(&self) -> u16 {
191 u16::from_le_bytes(self.0[12..14].try_into().unwrap())
192 }
193 pub fn status(&self) -> u16 {
194 u16::from_le_bytes(self.0[14..16].try_into().unwrap())
195 }
196 pub fn phase(&self) -> bool {
197 self.status() & 1 != 0
198 }
199}
200
201/// Single-producer submission ring. One slot stays unused to distinguish full from empty.
202pub struct SubmissionQueue<'a> {
203 entries: &'a mut [Submission],
204 tail: usize,
205 head: usize,
206}
207impl<'a> SubmissionQueue<'a> {
208 pub fn new(entries: &'a mut [Submission]) -> Self {
209 Self {
210 entries,
211 tail: 0,
212 head: 0,
213 }
214 }
215 pub fn push(&mut self, entry: Submission) -> Result<usize, Submission> {
216 if self.entries.len() < 2 {
217 return Err(entry);
218 }
219 let next = (self.tail + 1) % self.entries.len();
220 if next == self.head {
221 return Err(entry);
222 }
223 let slot = self.tail;
224 self.entries[slot] = entry;
225 self.tail = next;
226 Ok(slot)
227 }
228 pub fn head(&self) -> usize {
229 self.head
230 }
231 pub fn tail(&self) -> usize {
232 self.tail
233 }
234 pub fn set_head(&mut self, head: usize) {
235 self.head = head % self.entries.len();
236 }
237}
238
239/// Completion ring consumer, initialized to the inverted phase as required by NVMe.
240pub struct CompletionQueue<'a> {
241 entries: &'a [Completion],
242 head: usize,
243 phase: bool,
244}
245impl<'a> CompletionQueue<'a> {
246 pub fn new(entries: &'a [Completion]) -> Self {
247 Self {
248 entries,
249 head: 0,
250 phase: true,
251 }
252 }
253 pub fn poll(&mut self) -> Option<Completion> {
254 if self.entries.is_empty() {
255 return None;
256 }
257 let c = self.entries[self.head];
258 if c.phase() != self.phase {
259 return None;
260 }
261 self.head += 1;
262 if self.head == self.entries.len() {
263 self.head = 0;
264 self.phase = !self.phase;
265 }
266 Some(c)
267 }
268 pub fn head(&self) -> usize {
269 self.head
270 }
271 pub fn phase(&self) -> bool {
272 self.phase
273 }
274}
275
276/// Build PRP1/PRP2 and optional page-list entries for a transfer buffer.
277/// `list` is caller-owned and must itself be DMA-addressable when used by a real adapter.
278pub fn build_prps(
279 address: u64,
280 length: usize,
281 page_size: usize,
282 list_address: u64,
283 list: &mut [u64],
284) -> Result<(u64, u64, usize), PrpError> {
285 if length == 0 || page_size == 0 || !page_size.is_power_of_two() {
286 return Err(PrpError::Invalid);
287 }
288 let offset = address as usize & (page_size - 1);
289 let covered = offset.checked_add(length).ok_or(PrpError::Invalid)?;
290 let pages = covered
291 .checked_add(page_size - 1)
292 .ok_or(PrpError::Invalid)?
293 / page_size;
294 if pages == 1 {
295 return Ok((address, 0, 0));
296 }
297 // The second data page starts at the next page boundary after `address`.
298 // A near-`u64::MAX` address must be rejected, not wrapped or panicked.
299 let second = (address & !((page_size as u64) - 1))
300 .checked_add(page_size as u64)
301 .ok_or(PrpError::Invalid)?;
302 if pages == 2 {
303 return Ok((address, second, 0));
304 }
305 if list_address == 0 || list_address & (page_size as u64 - 1) != 0 {
306 return Err(PrpError::Invalid);
307 }
308 // `list` is contiguous, page-aligned list pages starting at `list_address`.
309 // Each list page holds page_size / 8 entries; when more data pages remain
310 // than fit, the last entry of a full list page points to the next list page.
311 let per_page = page_size / 8;
312 let count = pages - 1;
313 let mut data = 0;
314 let mut slot = 0;
315 while data < count {
316 let entry = list.get_mut(slot).ok_or(PrpError::ListTooSmall)?;
317 let last_in_page = slot % per_page == per_page - 1;
318 if last_in_page && count - data > 1 {
319 let offset = (slot / per_page + 1)
320 .checked_mul(page_size)
321 .ok_or(PrpError::Invalid)?;
322 *entry = list_address
323 .checked_add(offset as u64)
324 .ok_or(PrpError::Invalid)?;
325 } else {
326 let offset = data.checked_mul(page_size).ok_or(PrpError::Invalid)?;
327 *entry = second.checked_add(offset as u64).ok_or(PrpError::Invalid)?;
328 data += 1;
329 }
330 slot += 1;
331 }
332 Ok((address, list_address, slot))
333}
334#[derive(Clone, Copy, Debug, Eq, PartialEq)]
335pub enum PrpError {
336 Invalid,
337 ListTooSmall,
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343 use std::vec;
344
345 #[derive(Default)]
346 struct Fake {
347 cc: u32,
348 statuses: std::vec::Vec<u32>,
349 writes: std::vec::Vec<(u32, u32)>,
350 }
351 impl Registers for Fake {
352 fn read32(&mut self, off: u32) -> u32 {
353 if off == REG_CC {
354 self.cc
355 } else {
356 self.statuses.remove(0)
357 }
358 }
359 fn write32(&mut self, off: u32, value: u32) {
360 self.writes.push((off, value));
361 if off == REG_CC {
362 self.cc = value;
363 }
364 }
365 }
366
367 #[test]
368 fn registers_and_doorbells() {
369 let cap = Cap((3u64 << 32) | 0xff);
370 assert_eq!(cap.dstrd(), 3);
371 assert_eq!(cap.doorbell_stride(), 32);
372 assert_eq!(cap.mqes(), 256);
373 assert_eq!(doorbell_offset(2, true, cap.doorbell_stride()), 0x10a0);
374 }
375 #[test]
376 fn command_layouts() {
377 let c = Submission::identify_controller(0x1122_3344_5566_7788);
378 assert_eq!(c.u32_at(0), 6);
379 assert_eq!(c.u32_at(6), 0x5566_7788);
380 assert_eq!(c.u32_at(7), 0x1122_3344);
381 let r = Submission::read(7, 0x1234_5678_9abc_def0, 2, 0x1000, 0x2000);
382 assert_eq!(r.u32_at(0), 2);
383 assert_eq!(r.u32_at(1), 7);
384 assert_eq!(r.u32_at(10), 0x9abc_def0);
385 assert_eq!(r.u32_at(11), 0x1234_5678);
386 assert_eq!(r.u32_at(12), 1);
387 assert_eq!(Submission::write(1, 0, 1, 0, 0).u32_at(0), 1);
388 assert_eq!(
389 Submission::create_io_cq(3, 8, 0x4000).u32_at(10),
390 3 | (7 << 16)
391 );
392 // Polled completion queue: physically contiguous, interrupts disabled.
393 assert_eq!(Submission::create_io_cq(3, 8, 0x4000).u32_at(11), 1);
394 // SQ CDW11: PC=1 in bit 0, the target CQID in bits 31:16.
395 let sq = Submission::create_io_sq(4, 16, 0x5000, 3);
396 assert_eq!(sq.u32_at(10), 4 | (15 << 16));
397 assert_eq!(sq.u32_at(11), 1 | (3 << 16));
398 assert_eq!(
399 Submission::create_io_sq(1, 2, 0, 0x1234).u32_at(11) >> 16,
400 0x1234
401 );
402 }
403 #[test]
404 fn submission_full_and_wrap() {
405 let mut mem = vec![Submission::zeroed(); 3];
406 let mut q = SubmissionQueue::new(&mut mem);
407 assert_eq!(q.push(Submission::zeroed()), Ok(0));
408 assert_eq!(q.push(Submission::zeroed()), Ok(1));
409 assert!(q.push(Submission::zeroed()).is_err());
410 q.set_head(1);
411 assert_eq!(q.push(Submission::zeroed()), Ok(2));
412 assert_eq!(q.tail(), 0);
413 }
414 #[test]
415 fn completion_phase_wrap_and_empty() {
416 let mut mem = vec![Completion([0; 16]); 2];
417 mem[0].0[14..16].copy_from_slice(&1u16.to_le_bytes());
418 mem[1].0[14..16].copy_from_slice(&1u16.to_le_bytes());
419 let mut q = CompletionQueue::new(&mem);
420 assert!(q.poll().is_some());
421 assert!(q.poll().is_some());
422 assert!(!q.phase());
423 assert!(q.poll().is_none());
424 }
425 #[test]
426 fn prp_spans() {
427 let mut list = [0; 4];
428 assert_eq!(
429 build_prps(0x1080, 100, 4096, 0x8000, &mut list).unwrap(),
430 (0x1080, 0, 0)
431 );
432 assert_eq!(
433 build_prps(0x1080, 4096, 4096, 0x8000, &mut list).unwrap(),
434 (0x1080, 0x2000, 0)
435 );
436 let (p1, lp, n) = build_prps(0x1080, 9000, 4096, 0x8000, &mut list).unwrap();
437 assert_eq!((p1, n), (0x1080, 2));
438 assert_eq!(lp, 0x8000);
439 assert_eq!(list[..2], [0x2000, 0x3000]);
440 assert_eq!(
441 build_prps(0x1000, 12000, 4096, 0x8000, &mut [0; 1]),
442 Err(PrpError::ListTooSmall)
443 );
444 }
445 #[test]
446 fn controller_ready_failure_and_timeout() {
447 let mut ok = Fake {
448 statuses: vec![0, CSTS_RDY],
449 ..Fake::default()
450 };
451 assert_eq!(set_enabled(&mut ok, true, 2), Ok(()));
452 assert_eq!(ok.writes[0], (REG_CC, CC_EN));
453 let mut fail = Fake {
454 statuses: vec![CSTS_CFS],
455 ..Fake::default()
456 };
457 assert_eq!(
458 set_enabled(&mut fail, true, 3),
459 Err(ControllerError::Failed)
460 );
461 let mut timeout = Fake {
462 statuses: vec![0, 0],
463 ..Fake::default()
464 };
465 assert_eq!(
466 set_enabled(&mut timeout, true, 2),
467 Err(ControllerError::Timeout)
468 );
469 }
470 #[test]
471 fn prp_list_chains_across_list_pages() {
472 const PAGE: usize = 4096;
473 let per = PAGE / 8; // 512 entries per list page
474 let list_at = 0x80_0000u64;
475 let mut list = std::vec![0u64; 2 * per];
476 // 1 + 512 data pages after PRP1: 512 list entries fit in one page exactly.
477 let (p1, p2, used) =
478 build_prps(0x1000, (1 + per) * PAGE, PAGE, list_at, &mut list).unwrap();
479 assert_eq!((p1, p2, used), (0x1000, list_at, per));
480 assert_eq!(
481 list[per - 1],
482 0x2000 + ((per - 1) * PAGE) as u64,
483 "last slot is data, no chain"
484 );
485 // One more page: the last slot of page 0 must point at list page 1.
486 let (_, _, used) = build_prps(0x1000, (2 + per) * PAGE, PAGE, list_at, &mut list).unwrap();
487 assert_eq!(used, per + 2);
488 assert_eq!(list[per - 1], list_at + PAGE as u64, "chain pointer");
489 assert_eq!(list[per - 2], 0x2000 + ((per - 2) * PAGE) as u64);
490 assert_eq!(
491 list[per],
492 0x2000 + ((per - 1) * PAGE) as u64,
493 "data resumes in page 1"
494 );
495 assert_eq!(list[per + 1], 0x2000 + (per * PAGE) as u64);
496 // A list buffer too small for the chain is rejected, not overrun.
497 let mut short = std::vec![0u64; per];
498 assert_eq!(
499 build_prps(0x1000, (2 + per) * PAGE, PAGE, list_at, &mut short),
500 Err(PrpError::ListTooSmall)
501 );
502 }
503}