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

690 lines · 23857 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 AIENOS P3 native NVMe write + flush lane.
17//!
18//! Target: `crates/aienos-kernel/tests/nvme_write.rs`.
19//! Repo mirror (read-only): aien-dev/aienux @ ef359ec.
20//!
21//! Uses only the public `aienos_kernel::nvme` and
22//! `aienos_kernel::nvme::driver` API plus our own `Registers`, `DmaMemory`
23//! and `Delay` fakes. Unlike the completion fake, this device model is
24//! *persistent*: `opcode 0x01` copies the DMA payload into a per-LBA disk map
25//! and `opcode 0x02` copies it back, so a written buffer can be read back.
26//!
27//! Covered deterministically:
28//! * one-block write command encoding (opcode/NSID/LBA/NLB/PRP1),
29//! * 8-block single command within MDTS,
30//! * starting LBA split across CDW10/CDW11 for an offset write,
31//! * out-of-range writes rejected with no I/O doorbell / no DMA / no command,
32//! * empty and non-block-multiple buffers -> InvalidInput,
33//! * fresh command id per I/O command and CID-matched completion consumption,
34//! * nonzero completion status -> DeviceError,
35//! * 300-block MDTS chunking with correct per-chunk LBA and NLB,
36//! * exact byte round-trip through `read_blocks`.
37
38use std::cell::RefCell;
39use std::collections::BTreeMap;
40use std::rc::Rc;
41
42use aienos_kernel::block::{BlockDevice, BlockError};
43use aienos_kernel::nvme::driver::{
44 Delay, DmaMemory, DmaRegion, NvmeController, NvmeError, ADMIN_DEPTH, PAGE_SIZE,
45};
46use aienos_kernel::nvme::{
47 doorbell_offset, Registers, CC_EN, CSTS_RDY, REG_ACQ, REG_ASQ, REG_CC, REG_CSTS,
48};
49
50const CAP_LOW: u32 = 0x0100_03ff; // CAP.MQES = 1023, CAP.TO = 1 (500 ms), CAP.DSTRD = 0
51const STRIDE: u32 = 4;
52const ADMIN_DOORBELL: u32 = doorbell_offset(0, false, STRIDE);
53const IO_SQ_DOORBELL: u32 = doorbell_offset(1, false, STRIDE);
54
55const NS_BLOCKS: u64 = 12_345;
56const BLOCK_SIZE: usize = 512;
57
58type Shared = Rc<RefCell<Device>>;
59
60// ---------------------------------------------------------------------------
61// Persistent device model
62// ---------------------------------------------------------------------------
63
64struct Region {
65 base: u64,
66 len: usize,
67 bytes: Vec<u8>,
68}
69
70struct Device {
71 regions: Vec<Region>,
72 next_phys: u64,
73 cc: u32,
74 csts: u32,
75 asq: u64,
76 acq: u64,
77 io_sq_base: Option<u64>,
78 io_cq_base: Option<u64>,
79 io_depth: usize,
80 admin_sq_tail: usize,
81 admin_cq_tail: usize,
82 admin_phase: bool,
83 io_sq_tail: usize,
84 io_cq_tail: usize,
85 io_phase: bool,
86 /// I/O commands actually processed (one per I/O SQ doorbell that had a queue).
87 io_commands: u64,
88 /// I/O SQ doorbell register writes seen, including ones with no queue yet.
89 io_doorbell_writes: u64,
90 io_cids: Vec<u16>,
91 io_completed: Vec<u16>,
92 io_log: Vec<[u8; 64]>,
93 /// Persistent block store: LBA -> block payload.
94 disk: BTreeMap<u64, Vec<u8>>,
95 namespace_blocks: u64,
96 lbads: u8,
97 mdts: u8,
98 completion_status: u16,
99 command_error: u16,
100}
101
102impl Device {
103 fn new() -> Self {
104 Self {
105 regions: Vec::new(),
106 next_phys: 0x1000,
107 cc: 0,
108 csts: 0,
109 asq: 0,
110 acq: 0,
111 io_sq_base: None,
112 io_cq_base: None,
113 io_depth: 0,
114 admin_sq_tail: 0,
115 admin_cq_tail: 0,
116 admin_phase: true,
117 io_sq_tail: 0,
118 io_cq_tail: 0,
119 io_phase: true,
120 io_commands: 0,
121 io_doorbell_writes: 0,
122 io_cids: Vec::new(),
123 io_completed: Vec::new(),
124 io_log: Vec::new(),
125 disk: BTreeMap::new(),
126 namespace_blocks: NS_BLOCKS,
127 lbads: 9,
128 mdts: 0,
129 completion_status: 0,
130 command_error: 0,
131 }
132 }
133
134 fn block_size(&self) -> usize {
135 1usize << u32::from(self.lbads)
136 }
137
138 fn alloc(&mut self, size: usize, alignment: usize) -> u64 {
139 let align = alignment.max(1) as u64;
140 let base = (self.next_phys + align - 1) & !(align - 1);
141 self.next_phys = base + size as u64;
142 self.regions.push(Region {
143 base,
144 len: size,
145 bytes: vec![0; size],
146 });
147 base
148 }
149
150 fn find_region(&self, physical: u64, len: usize) -> Option<usize> {
151 self.regions
152 .iter()
153 .position(|r| physical >= r.base && physical + len as u64 <= r.base + r.len as u64)
154 }
155
156 fn read_mem(&mut self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
157 let i = self
158 .find_region(physical, output.len())
159 .ok_or(NvmeError::Dma)?;
160 let off = (physical - self.regions[i].base) as usize;
161 output.copy_from_slice(&self.regions[i].bytes[off..off + output.len()]);
162 Ok(())
163 }
164
165 fn write_mem(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
166 let i = self
167 .find_region(physical, input.len())
168 .ok_or(NvmeError::Dma)?;
169 let off = (physical - self.regions[i].base) as usize;
170 self.regions[i].bytes[off..off + input.len()].copy_from_slice(input);
171 Ok(())
172 }
173
174 fn region_vec(&self, physical: u64, len: usize) -> Option<Vec<u8>> {
175 let i = self.find_region(physical, len)?;
176 let off = (physical - self.regions[i].base) as usize;
177 Some(self.regions[i].bytes[off..off + len].to_vec())
178 }
179
180 fn peek_command(&self, base: u64, slot: usize) -> [u8; 64] {
181 let addr = base + (slot * 64) as u64;
182 let mut out = [0u8; 64];
183 if let Some(bytes) = self.region_vec(addr, 64) {
184 out.copy_from_slice(&bytes);
185 }
186 out
187 }
188
189 fn fill_identify(&mut self, prp: u64, cns: u32) {
190 if let Some(i) = self.find_region(prp, PAGE_SIZE) {
191 let bytes = &mut self.regions[i].bytes;
192 bytes.fill(0);
193 if cns == 1 {
194 bytes[77] = self.mdts; // MDTS
195 } else {
196 bytes[0..8].copy_from_slice(&self.namespace_blocks.to_le_bytes());
197 bytes[26] = 0; // FLBAS -> format 0
198 bytes[128 + 2] = self.lbads; // LBADS in descriptor 0
199 }
200 }
201 }
202
203 fn on_admin_doorbell(&mut self) {
204 let slot = self.admin_sq_tail;
205 let cmd = self.peek_command(self.asq, slot);
206 let opcode = cmd[0];
207 let cid = u16::from_le_bytes([cmd[2], cmd[3]]);
208 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap());
209 let cdw10 = u32::from_le_bytes(cmd[40..44].try_into().unwrap());
210 match opcode {
211 0x06 => self.fill_identify(p1, cdw10),
212 0x05 => {
213 self.io_cq_base = Some(p1);
214 self.io_depth = ((cdw10 >> 16) & 0xffff) as usize + 1;
215 }
216 0x01 => self.io_sq_base = Some(p1),
217 _ => {}
218 }
219 let at = self.acq + (self.admin_cq_tail * 16) as u64;
220 let mut raw = [0u8; 16];
221 raw[12..14].copy_from_slice(&cid.to_le_bytes());
222 raw[14..16].copy_from_slice(&u16::from(self.admin_phase).to_le_bytes());
223 self.write_mem(at, &raw).ok();
224 self.admin_sq_tail = (slot + 1) % ADMIN_DEPTH;
225 self.admin_cq_tail = (self.admin_cq_tail + 1) % ADMIN_DEPTH;
226 if self.admin_cq_tail == 0 {
227 self.admin_phase = !self.admin_phase;
228 }
229 }
230
231 /// Decompose a transfer into (address, len) segments, mirroring the PRP
232 /// shapes `build_prps` produces: PRP1, optional PRP2, or a page list.
233 fn collect_segments(&self, p1: u64, p2: u64, len: usize) -> Vec<(u64, usize)> {
234 let mut segs = Vec::new();
235 if len == 0 {
236 return segs;
237 }
238 let first = (PAGE_SIZE - (p1 as usize & (PAGE_SIZE - 1))).min(len);
239 segs.push((p1, first));
240 let mut left = len - first;
241 if left == 0 {
242 return segs;
243 }
244 if p2 != 0 && left <= PAGE_SIZE {
245 segs.push((p2, left));
246 return segs;
247 }
248 let per = PAGE_SIZE / 8;
249 let mut list_page = p2;
250 'outer: while left > 0 {
251 let entries = match self.region_vec(list_page, PAGE_SIZE) {
252 Some(bytes) => bytes,
253 None => break,
254 };
255 for i in 0..per {
256 let address = u64::from_le_bytes(entries[i * 8..i * 8 + 8].try_into().unwrap());
257 if address == 0 {
258 break 'outer;
259 }
260 if i == per - 1 && left > PAGE_SIZE {
261 list_page = address; // chain pointer to the next list page
262 continue 'outer;
263 }
264 let n = left.min(PAGE_SIZE - (address as usize & (PAGE_SIZE - 1)));
265 segs.push((address, n));
266 left -= n;
267 if left == 0 {
268 break 'outer;
269 }
270 }
271 }
272 segs
273 }
274
275 fn on_io_doorbell(&mut self) {
276 let Some(sq) = self.io_sq_base else { return };
277 if self.io_depth == 0 {
278 return;
279 }
280 let slot = self.io_sq_tail;
281 let cmd = self.peek_command(sq, slot);
282 self.io_commands += 1;
283 self.io_log.push(cmd);
284 let cid = u16::from_le_bytes([cmd[2], cmd[3]]);
285 self.io_cids.push(cid);
286
287 let opcode = cmd[0];
288 let nsid = u32::from_le_bytes(cmd[4..8].try_into().unwrap());
289 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap());
290 let p2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap());
291 let lba = u64::from(u32::from_le_bytes(cmd[40..44].try_into().unwrap()))
292 | (u64::from(u32::from_le_bytes(cmd[44..48].try_into().unwrap())) << 32);
293 let nlb = u32::from_le_bytes(cmd[48..52].try_into().unwrap()) as usize;
294 let len = nlb.saturating_add(1) * self.block_size();
295 let bs = self.block_size();
296
297 let mut err = 0u16;
298 if nsid != 1 {
299 err = 1 << 1;
300 }
301 match opcode {
302 0x01 | 0x02 => {
303 let segs = self.collect_segments(p1, p2, len);
304 if opcode == 0x01 {
305 let mut flat = vec![0u8; len];
306 let mut done = 0usize;
307 for (address, n) in segs {
308 if done + n > len {
309 break;
310 }
311 let bytes = self.region_vec(address, n).unwrap_or_else(|| vec![0; n]);
312 flat[done..done + n].copy_from_slice(&bytes);
313 done += n;
314 }
315 for b in 0..(len / bs) {
316 self.disk
317 .insert(lba + b as u64, flat[b * bs..(b + 1) * bs].to_vec());
318 }
319 } else {
320 let mut flat = vec![0u8; len];
321 for b in 0..(len / bs) {
322 if let Some(block) = self.disk.get(&(lba + b as u64)) {
323 flat[b * bs..(b + 1) * bs].copy_from_slice(block);
324 }
325 }
326 let mut done = 0usize;
327 for (address, n) in segs {
328 if done + n > len {
329 break;
330 }
331 self.write_mem(address, &flat[done..done + n]).ok();
332 done += n;
333 }
334 }
335 }
336 0x00 => {} // Flush: no payload.
337 _ => err = 1 << 1,
338 }
339 self.command_error = err;
340 self.push_io_completion(cid);
341 self.io_sq_tail = (slot + 1) % self.io_depth;
342 self.io_cq_tail = (self.io_cq_tail + 1) % self.io_depth;
343 if self.io_cq_tail == 0 {
344 self.io_phase = !self.io_phase;
345 }
346 }
347
348 fn push_io_completion(&mut self, cid: u16) {
349 if let Some(base) = self.io_cq_base {
350 let at = base + (self.io_cq_tail * 16) as u64;
351 let mut raw = [0u8; 16];
352 raw[12..14].copy_from_slice(&cid.to_le_bytes());
353 let status = u16::from(self.io_phase) | self.completion_status | self.command_error;
354 raw[14..16].copy_from_slice(&status.to_le_bytes());
355 self.write_mem(at, &raw).ok();
356 }
357 self.io_completed.push(cid);
358 }
359
360 fn reg_read(&mut self, offset: u32) -> u32 {
361 match offset {
362 0 => CAP_LOW,
363 4 => 0,
364 REG_CC => self.cc,
365 REG_CSTS => self.csts,
366 _ => 0,
367 }
368 }
369
370 fn reg_write(&mut self, offset: u32, value: u32) {
371 match offset {
372 REG_CC => {
373 self.cc = value;
374 self.csts = if value & CC_EN == 0 { 0 } else { CSTS_RDY };
375 }
376 REG_ASQ => self.asq = (self.asq & 0xffff_ffff_0000_0000) | u64::from(value),
377 x if x == REG_ASQ + 4 => {
378 self.asq = (self.asq & 0xffff_ffff) | (u64::from(value) << 32);
379 }
380 REG_ACQ => self.acq = (self.acq & 0xffff_ffff_0000_0000) | u64::from(value),
381 x if x == REG_ACQ + 4 => {
382 self.acq = (self.acq & 0xffff_ffff) | (u64::from(value) << 32);
383 }
384 ADMIN_DOORBELL => self.on_admin_doorbell(),
385 IO_SQ_DOORBELL => {
386 self.io_doorbell_writes += 1;
387 self.on_io_doorbell();
388 }
389 _ => {}
390 }
391 }
392}
393
394// ---------------------------------------------------------------------------
395// Fakes implementing the public driver traits
396// ---------------------------------------------------------------------------
397
398struct FakeRegs {
399 shared: Shared,
400}
401
402impl Registers for FakeRegs {
403 fn read32(&mut self, offset: u32) -> u32 {
404 self.shared.borrow_mut().reg_read(offset)
405 }
406 fn write32(&mut self, offset: u32, value: u32) {
407 self.shared.borrow_mut().reg_write(offset, value);
408 }
409}
410
411struct FakeDma {
412 shared: Shared,
413}
414
415impl DmaMemory for FakeDma {
416 fn allocate(&mut self, size: usize, alignment: usize) -> Result<DmaRegion, NvmeError> {
417 let physical = self.shared.borrow_mut().alloc(size, alignment);
418 Ok(DmaRegion {
419 physical,
420 bytes: vec![0; size],
421 })
422 }
423 fn read(&self, physical: u64, output: &mut [u8]) -> Result<(), NvmeError> {
424 self.shared.borrow_mut().read_mem(physical, output)
425 }
426 fn write(&mut self, physical: u64, input: &[u8]) -> Result<(), NvmeError> {
427 self.shared.borrow_mut().write_mem(physical, input)
428 }
429}
430
431struct CountingDelay;
432
433impl Delay for CountingDelay {
434 fn delay_us(&mut self, _us: u32) {}
435}
436
437type Controller = NvmeController<FakeRegs, FakeDma, CountingDelay>;
438
439fn controller_with(namespace_blocks: u64, lbads: u8, mdts: u8) -> (Controller, Shared) {
440 let mut dev = Device::new();
441 dev.namespace_blocks = namespace_blocks;
442 dev.lbads = lbads;
443 dev.mdts = mdts;
444 let shared: Shared = Rc::new(RefCell::new(dev));
445 let regs = FakeRegs {
446 shared: shared.clone(),
447 };
448 let dma = FakeDma {
449 shared: shared.clone(),
450 };
451 let controller =
452 NvmeController::init(regs, dma, CountingDelay).expect("controller init should succeed");
453 (controller, shared)
454}
455
456fn controller() -> (Controller, Shared) {
457 controller_with(NS_BLOCKS, 9, 0)
458}
459
460fn cdw(cmd: &[u8; 64], dword: usize) -> u32 {
461 u32::from_le_bytes(cmd[dword * 4..dword * 4 + 4].try_into().unwrap())
462}
463
464// ---------------------------------------------------------------------------
465// Tests
466// ---------------------------------------------------------------------------
467
468#[test]
469fn write_one_block_encodes_opcode_nsid_lba_nlb_and_prp1() {
470 let (mut c, shared) = controller();
471 c.create_io_queues(4).unwrap();
472
473 let before = shared.borrow().regions.len();
474 c.write_blocks(5, &[0xab; BLOCK_SIZE]).unwrap();
475
476 let dev = shared.borrow();
477 assert_eq!(dev.io_commands, 1, "one block -> one I/O command");
478 let cmd = *dev.io_log.last().unwrap();
479 assert_eq!(cmd[0] & 0x7f, 0x01, "NVM Write opcode");
480 assert_eq!(cdw(&cmd, 1), 1, "NSID = 1");
481 assert_eq!(cdw(&cmd, 10), 5, "CDW10 = LBA low");
482 assert_eq!(cdw(&cmd, 11), 0, "CDW11 = LBA high");
483 assert_eq!(cdw(&cmd, 12), 0, "CDW12 = NLB = blocks - 1");
484 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap());
485 let p2 = u64::from_le_bytes(cmd[32..40].try_into().unwrap());
486 assert_eq!(p2, 0, "single page transfer has no PRP2");
487 assert_eq!(p1 & (PAGE_SIZE as u64 - 1), 0, "PRP1 is page aligned");
488 assert_eq!(
489 dev.regions[before].base, p1,
490 "PRP1 points at the write buffer"
491 );
492 assert_eq!(dev.regions[before].len, BLOCK_SIZE);
493 assert_eq!(dev.io_cids.len(), 1);
494}
495
496#[test]
497fn write_eight_blocks_is_one_command_with_nlb_seven() {
498 let (mut c, shared) = controller();
499 c.create_io_queues(4).unwrap();
500
501 let before = shared.borrow().regions.len();
502 let data: Vec<u8> = (0..8 * BLOCK_SIZE).map(|i| i as u8).collect();
503 c.write_blocks(100, &data).unwrap();
504
505 let dev = shared.borrow();
506 assert_eq!(dev.io_commands, 1, "8 blocks fit in one MDTS chunk");
507 let cmd = *dev.io_log.last().unwrap();
508 assert_eq!(cdw(&cmd, 12), 7, "NLB = 8 - 1");
509 assert_eq!(cdw(&cmd, 10), 100, "starting LBA");
510 assert_eq!(cdw(&cmd, 1), 1, "NSID = 1");
511 let p1 = u64::from_le_bytes(cmd[24..32].try_into().unwrap());
512 assert_eq!(dev.regions[before].base, p1);
513 assert_eq!(dev.regions[before].len, 8 * BLOCK_SIZE);
514}
515
516#[test]
517fn offset_write_splits_lba_across_cdw10_and_cdw11() {
518 let (mut c, shared) = controller_with(0x1_0000_0010, 9, 0);
519 c.create_io_queues(4).unwrap();
520
521 let lba = 0x1_0000_0003u64;
522 c.write_blocks(lba, &[0x5a; 2 * BLOCK_SIZE]).unwrap();
523
524 let dev = shared.borrow();
525 let cmd = *dev.io_log.last().unwrap();
526 let lo = cdw(&cmd, 10);
527 let hi = cdw(&cmd, 11);
528 assert_eq!(lo, 3, "CDW10 = low 32 bits of LBA");
529 assert_eq!(hi, 1, "CDW11 = high 32 bits of LBA");
530 assert_eq!(u64::from(lo) | (u64::from(hi) << 32), lba);
531 assert_eq!(cdw(&cmd, 12), 1, "NLB for 2 blocks");
532}
533
534#[test]
535fn write_past_block_count_is_out_of_range_without_io_submission() {
536 let (mut c, shared) = controller_with(16, 9, 0);
537 c.create_io_queues(4).unwrap();
538
539 let (cmds, doors, allocs) = {
540 let dev = shared.borrow();
541 (dev.io_commands, dev.io_doorbell_writes, dev.regions.len())
542 };
543
544 assert_eq!(
545 c.write_blocks(16, &[0u8; BLOCK_SIZE]),
546 Err(BlockError::OutOfRange)
547 );
548 assert_eq!(
549 c.write_blocks(15, &[0u8; 2 * BLOCK_SIZE]),
550 Err(BlockError::OutOfRange)
551 );
552 assert_eq!(
553 c.write_blocks(u64::MAX, &[0u8; BLOCK_SIZE]),
554 Err(BlockError::OutOfRange)
555 );
556
557 let dev = shared.borrow();
558 assert_eq!(dev.io_commands, cmds, "no I/O command submitted");
559 assert_eq!(dev.io_doorbell_writes, doors, "no I/O doorbell rung");
560 assert_eq!(
561 dev.regions.len(),
562 allocs,
563 "no DMA allocated for a rejected write"
564 );
565}
566
567#[test]
568fn empty_and_non_block_multiple_buffers_are_invalid_input() {
569 let (mut c, shared) = controller();
570 c.create_io_queues(4).unwrap();
571
572 let doors = shared.borrow().io_doorbell_writes;
573 assert_eq!(c.write_blocks(0, &[]), Err(BlockError::InvalidInput));
574 assert_eq!(
575 c.write_blocks(0, &[0u8; BLOCK_SIZE + 1]),
576 Err(BlockError::InvalidInput)
577 );
578 assert_eq!(
579 c.write_blocks(7, &[0u8; BLOCK_SIZE - 1]),
580 Err(BlockError::InvalidInput)
581 );
582 assert_eq!(
583 shared.borrow().io_doorbell_writes,
584 doors,
585 "invalid input must not reach the doorbell"
586 );
587 assert_eq!(shared.borrow().io_commands, 0);
588}
589
590#[test]
591fn each_io_command_gets_a_new_cid_and_completion_is_consumed() {
592 let (mut c, shared) = controller();
593 c.create_io_queues(4).unwrap();
594
595 c.write_blocks(0, &[1u8; BLOCK_SIZE]).unwrap();
596 c.write_blocks(1, &[2u8; 2 * BLOCK_SIZE]).unwrap();
597 c.write_blocks(10, &[3u8; BLOCK_SIZE]).unwrap();
598
599 let dev = shared.borrow();
600 assert_eq!(dev.io_commands, 3);
601 assert_eq!(dev.io_cids.len(), 3, "one CID per submitted command");
602 assert_eq!(
603 dev.io_completed, dev.io_cids,
604 "each completion echoed the submitted CID, so submit_io consumed it"
605 );
606 for pair in dev.io_cids.windows(2) {
607 assert!(pair[0] < pair[1], "CIDs must be fresh and increasing");
608 }
609 let mut unique = dev.io_cids.clone();
610 unique.sort_unstable();
611 unique.dedup();
612 assert_eq!(unique.len(), dev.io_cids.len(), "CIDs must never be reused");
613}
614
615#[test]
616fn nonzero_write_completion_maps_to_device_error() {
617 let (mut c, shared) = controller();
618 c.create_io_queues(4).unwrap();
619 shared.borrow_mut().completion_status = 2; // status >> 1 == 1 -> nonzero
620
621 assert_eq!(
622 c.write_blocks(0, &[7u8; BLOCK_SIZE]),
623 Err(BlockError::DeviceError)
624 );
625}
626
627#[test]
628fn mdts_chunking_submits_per_chunk_commands_with_correct_lba_and_nlb() {
629 let (mut c, shared) = controller();
630 c.create_io_queues(4).unwrap();
631
632 let before = shared.borrow().regions.len();
633 let blocks = 300usize;
634 let data: Vec<u8> = (0..blocks * BLOCK_SIZE).map(|i| (i % 251) as u8).collect();
635 c.write_blocks(20, &data).unwrap();
636
637 let dev = shared.borrow();
638 assert_eq!(
639 dev.io_commands, 2,
640 "300 blocks split at the 128 KiB MDTS cap -> 256 + 44"
641 );
642 let c0 = dev.io_log[0];
643 let c1 = dev.io_log[1];
644 assert_eq!(cdw(&c0, 12), 255, "first chunk NLB = 256 - 1");
645 assert_eq!(cdw(&c1, 12), 43, "second chunk NLB = 44 - 1");
646 assert_eq!(cdw(&c0, 10), 20, "first chunk starting LBA");
647 assert_eq!(
648 cdw(&c1, 10),
649 20 + 256,
650 "second chunk advances by 256 blocks"
651 );
652 assert_eq!(
653 dev.regions[before].base,
654 u64::from_le_bytes(c0[24..32].try_into().unwrap()),
655 "first chunk PRP1 points at its own data region"
656 );
657 let c1_p1 = u64::from_le_bytes(c1[24..32].try_into().unwrap());
658 assert!(
659 dev.regions.iter().any(|r| r.base == c1_p1),
660 "second chunk PRP1 points at its own data region"
661 );
662 drop(dev);
663
664 let mut out = vec![0u8; data.len()];
665 c.read_blocks(20, &mut out).unwrap();
666 assert_eq!(out, data, "chunked write round-trips exactly");
667}
668
669#[test]
670fn written_bytes_read_back_exactly() {
671 let (mut c, _shared) = controller();
672 c.create_io_queues(4).unwrap();
673
674 let data: Vec<u8> = (0..8 * BLOCK_SIZE).map(|i| (i * 31 + 7) as u8).collect();
675 c.write_blocks(1234, &data).unwrap();
676
677 let mut out = vec![0u8; data.len()];
678 c.read_blocks(1234, &mut out).unwrap();
679 assert_eq!(out, data, "read-back must match the written bytes exactly");
680
681 // A never-written region reads back as zeros.
682 let mut zero = [0xffu8; BLOCK_SIZE];
683 c.read_blocks(9999, &mut zero).unwrap();
684 assert_eq!(zero, [0u8; BLOCK_SIZE]);
685
686 // An offset read returns exactly the bytes written at that offset.
687 let mut tail = [0u8; BLOCK_SIZE];
688 c.read_blocks(1234 + 7, &mut tail).unwrap();
689 assert_eq!(tail, data[7 * BLOCK_SIZE..8 * BLOCK_SIZE]);
690}