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

602 lines · 22068 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//! Driver for QEMU's `edu` educational PCI device (1234:11e8).
17//!
18//! The device exists to prove DMA confinement without risking a real
19//! controller: it copies up to 4 KiB between its internal buffer and a bus
20//! address we choose, so a test can aim a transfer at memory the SMMU must
21//! refuse and then check that nothing moved.
22//!
23//! Register map (QEMU `docs/specs/edu.rst` and `hw/misc/edu.c`, checked
24//! against QEMU 8.2.2): BAR0 is 1 MiB of MMIO. Offsets below 0x80 take only
25//! 4-byte accesses; offsets from 0x80 take 4 or 8 bytes, and this driver uses
26//! 8 for all of them.
27//!
28//! Things the device does that the driver must respect:
29//! - A transfer whose device side falls outside the 4 KiB buffer at 0x40000
30//! makes QEMU abort (`hw_error`), so the driver checks lengths first.
31//! - The RAM side address is silently masked with the device's `dma_mask`
32//! (28 bits unless `-device edu,dma_mask=...` says otherwise). An address
33//! above the mask would wrap to a different address, so the driver refuses
34//! it instead.
35//! - A transfer runs from a timer 100 ms of guest time after the command is
36//! written, so completion polling needs a generous budget.
37//! - Completion only means the command bit cleared. The device ignores DMA
38//! errors, so a transfer the SMMU blocked also "completes"; proof of a
39//! block is the memory contents and the SMMU event queue, not this status.
40//!
41//! Register access goes through [`Registers`], so the driver is host-tested
42//! against a fake that simulates the DMA command state machine. [`EduMmio`]
43//! is the real adapter over a mapped BAR0.
44
45use crate::arch::aarch64::dsb;
46
47/// PCI vendor id of the `edu` device.
48pub const VENDOR_ID: u16 = 0x1234;
49/// PCI device id of the `edu` device.
50pub const DEVICE_ID: u16 = 0x11e8;
51/// Size of BAR0, the MMIO register window.
52pub const BAR0_SIZE: u64 = 1 << 20;
53
54/// Identification, `0xRRrr00ed` for version RR.rr (read only).
55pub const REG_ID: usize = 0x00;
56/// Liveness check: reads back the bitwise inverse of the last value written.
57pub const REG_LIVENESS: usize = 0x04;
58/// Factorial computation input and result.
59pub const REG_FACTORIAL: usize = 0x08;
60/// Status: bit 0 computing factorial, bit 7 raise interrupt when done.
61pub const REG_STATUS: usize = 0x20;
62/// Interrupt status (read only): OR of values that raised an interrupt.
63pub const REG_IRQ_STATUS: usize = 0x24;
64/// Interrupt raise (write only): value is ORed into the interrupt status.
65pub const REG_IRQ_RAISE: usize = 0x60;
66/// Interrupt acknowledge (write only): value is cleared from the interrupt status.
67pub const REG_IRQ_ACK: usize = 0x64;
68/// DMA source address (u64).
69pub const REG_DMA_SRC: usize = 0x80;
70/// DMA destination address (u64).
71pub const REG_DMA_DST: usize = 0x88;
72/// DMA transfer length in bytes (u64).
73pub const REG_DMA_COUNT: usize = 0x90;
74/// DMA command (u64), see the `DMA_CMD_*` bits.
75pub const REG_DMA_CMD: usize = 0x98;
76
77/// DMA command bit: start the transfer. The device clears it when done.
78pub const DMA_CMD_START: u64 = 1 << 0;
79/// DMA command bit: direction. Clear copies RAM to the device buffer, set
80/// copies the device buffer to RAM.
81pub const DMA_CMD_TO_RAM: u64 = 1 << 1;
82/// DMA command bit: raise interrupt [`DMA_IRQ`] when the transfer finishes.
83pub const DMA_CMD_IRQ: u64 = 1 << 2;
84/// Interrupt status value a finished DMA raises when [`DMA_CMD_IRQ`] was set.
85pub const DMA_IRQ: u32 = 0x100;
86
87/// Device address of the internal DMA buffer.
88pub const DMA_BUFFER_ADDR: u64 = 0x40000;
89/// Size of the internal DMA buffer in bytes.
90pub const DMA_BUFFER_SIZE: u64 = 4096;
91/// The device's default DMA address mask: 28 bits, so bus addresses below 256 MiB.
92pub const DEFAULT_DMA_MASK: u64 = (1 << 28) - 1;
93/// Low 16 bits of the identification register on every `edu` version.
94const ID_SIGNATURE: u32 = 0x00ed;
95/// Default number of command register reads before giving up on a transfer.
96pub const DEFAULT_SPIN_LIMIT: u32 = 50_000_000;
97
98/// MMIO access to the device's BAR0, by byte offset.
99pub trait Registers {
100 fn read32(&mut self, offset: usize) -> u32;
101 fn write32(&mut self, offset: usize, value: u32);
102 fn read64(&mut self, offset: usize) -> u64;
103 fn write64(&mut self, offset: usize, value: u64);
104}
105
106/// Device version from the identification register.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct EduVersion {
109 pub major: u8,
110 pub minor: u8,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum EduError {
115 /// The identification register does not carry the `edu` signature.
116 NotEdu { id: u32 },
117 /// The liveness register did not return the inverse of what was written.
118 LivenessFailed { wrote: u32, read: u32 },
119 /// A zero length transfer was requested.
120 EmptyTransfer,
121 /// The length exceeds the 4 KiB device buffer.
122 TooLong { len: u64 },
123 /// Part of the RAM side range lies above the device's DMA mask.
124 IovaOutOfRange { iova: u64, len: u64, mask: u64 },
125 /// A transfer is already in flight; the device would ignore a new command.
126 Busy,
127 /// The start bit did not clear within the spin budget. The transfer may
128 /// still run later, so the RAM range stays owned by the device.
129 Timeout,
130}
131
132/// Driver state: the register window, the DMA mask the device was created
133/// with and the completion polling budget.
134pub struct Edu<R: Registers> {
135 regs: R,
136 dma_mask: u64,
137 spin_limit: u32,
138}
139
140impl<R: Registers> Edu<R> {
141 /// Driver for a device with the default 28-bit DMA mask.
142 pub fn new(regs: R) -> Self {
143 Self {
144 regs,
145 dma_mask: DEFAULT_DMA_MASK,
146 spin_limit: DEFAULT_SPIN_LIMIT,
147 }
148 }
149
150 /// Use the mask the device was created with (`-device edu,dma_mask=`).
151 pub fn with_dma_mask(mut self, mask: u64) -> Self {
152 self.dma_mask = mask;
153 self
154 }
155
156 /// Number of command register reads to wait for a transfer.
157 pub fn with_spin_limit(mut self, spins: u32) -> Self {
158 self.spin_limit = spins;
159 self
160 }
161
162 pub fn dma_mask(&self) -> u64 {
163 self.dma_mask
164 }
165
166 pub fn registers(&mut self) -> &mut R {
167 &mut self.regs
168 }
169
170 pub fn into_registers(self) -> R {
171 self.regs
172 }
173
174 /// Checks the identification signature and the liveness register.
175 /// Touches no DMA state.
176 pub fn probe(&mut self) -> Result<EduVersion, EduError> {
177 let id = self.regs.read32(REG_ID);
178 if id & 0xffff != ID_SIGNATURE {
179 return Err(EduError::NotEdu { id });
180 }
181 for wrote in [0x5a5a_a5a5u32, 0x0123_4567] {
182 self.regs.write32(REG_LIVENESS, wrote);
183 let read = self.regs.read32(REG_LIVENESS);
184 if read != !wrote {
185 return Err(EduError::LivenessFailed { wrote, read });
186 }
187 }
188 Ok(EduVersion {
189 major: (id >> 24) as u8,
190 minor: (id >> 16) as u8,
191 })
192 }
193
194 /// Whether a transfer is in flight.
195 pub fn dma_busy(&mut self) -> bool {
196 self.regs.read64(REG_DMA_CMD) & DMA_CMD_START != 0
197 }
198
199 /// Copies `len` bytes from bus address `src_iova` into the start of the
200 /// device buffer and waits for the command to finish.
201 pub fn dma_to_device(&mut self, src_iova: u64, len: u64) -> Result<(), EduError> {
202 self.transfer(src_iova, len, false)
203 }
204
205 /// Copies `len` bytes from the start of the device buffer to bus address
206 /// `dst_iova` and waits for the command to finish.
207 pub fn dma_from_device(&mut self, dst_iova: u64, len: u64) -> Result<(), EduError> {
208 self.transfer(dst_iova, len, true)
209 }
210
211 /// Interrupt status bits currently raised.
212 pub fn irq_status(&mut self) -> u32 {
213 self.regs.read32(REG_IRQ_STATUS)
214 }
215
216 /// Clears `bits` from the interrupt status.
217 pub fn ack_irq(&mut self, bits: u32) {
218 self.regs.write32(REG_IRQ_ACK, bits);
219 }
220
221 /// Validates, programs and starts one transfer, then polls for completion.
222 fn transfer(&mut self, iova: u64, len: u64, to_ram: bool) -> Result<(), EduError> {
223 self.check(iova, len)?;
224 if self.dma_busy() {
225 return Err(EduError::Busy);
226 }
227 let (src, dst, command) = if to_ram {
228 (DMA_BUFFER_ADDR, iova, DMA_CMD_START | DMA_CMD_TO_RAM)
229 } else {
230 (iova, DMA_BUFFER_ADDR, DMA_CMD_START)
231 };
232 self.regs.write64(REG_DMA_SRC, src);
233 self.regs.write64(REG_DMA_DST, dst);
234 self.regs.write64(REG_DMA_COUNT, len);
235 self.regs.write64(REG_DMA_CMD, command);
236 for _ in 0..self.spin_limit {
237 if !self.dma_busy() {
238 return Ok(());
239 }
240 core::hint::spin_loop();
241 }
242 Err(EduError::Timeout)
243 }
244
245 /// Length fits the device buffer and the whole RAM range sits under the mask.
246 fn check(&self, iova: u64, len: u64) -> Result<(), EduError> {
247 if len == 0 {
248 return Err(EduError::EmptyTransfer);
249 }
250 if len > DMA_BUFFER_SIZE {
251 return Err(EduError::TooLong { len });
252 }
253 let out_of_range = EduError::IovaOutOfRange {
254 iova,
255 len,
256 mask: self.dma_mask,
257 };
258 let last = iova.checked_add(len - 1).ok_or(out_of_range)?;
259 if iova & !self.dma_mask != 0 || last & !self.dma_mask != 0 {
260 return Err(out_of_range);
261 }
262 Ok(())
263 }
264}
265
266/// BAR0 of a real device through volatile MMIO. Every write is preceded by a
267/// full data synchronization barrier and every read followed by one, so
268/// buffer writes in RAM are visible to the device before a transfer starts
269/// and device writes are visible to the CPU after completion is seen.
270pub struct EduMmio {
271 base: usize,
272}
273
274impl EduMmio {
275 /// # Safety
276 /// `base` must be the virtual address of the device's BAR0, mapped as
277 /// device memory for [`BAR0_SIZE`] bytes for as long as this value is
278 /// used, with memory decode enabled, and not driven by anything else.
279 pub const unsafe fn new(base: usize) -> Self {
280 Self { base }
281 }
282}
283
284impl Registers for EduMmio {
285 fn read32(&mut self, offset: usize) -> u32 {
286 // SAFETY: inside the BAR that `new` requires to be mapped.
287 let value = unsafe { core::ptr::read_volatile((self.base + offset) as *const u32) };
288 dsb();
289 value
290 }
291
292 fn write32(&mut self, offset: usize, value: u32) {
293 dsb();
294 // SAFETY: as for `read32`.
295 unsafe { core::ptr::write_volatile((self.base + offset) as *mut u32, value) }
296 }
297
298 fn read64(&mut self, offset: usize) -> u64 {
299 // SAFETY: as for `read32`.
300 let value = unsafe { core::ptr::read_volatile((self.base + offset) as *const u64) };
301 dsb();
302 value
303 }
304
305 fn write64(&mut self, offset: usize, value: u64) {
306 dsb();
307 // SAFETY: as for `read32`.
308 unsafe { core::ptr::write_volatile((self.base + offset) as *mut u64, value) }
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 /// Simulated `edu` register file and bus. RAM is a small window of bus
317 /// addresses from `ram_base`; addresses in `blocked` model an SMMU that
318 /// refuses the access (the device still reports completion, as QEMU's
319 /// does). Panics where real QEMU would abort or misbehave, so a test
320 /// fails if the driver ever programs such a transfer.
321 struct FakeEdu {
322 id: u32,
323 liveness: u32,
324 irq_status: u32,
325 src: u64,
326 dst: u64,
327 count: u64,
328 cmd: u64,
329 dma_mask: u64,
330 buffer: [u8; DMA_BUFFER_SIZE as usize],
331 ram_base: u64,
332 ram: std::vec::Vec<u8>,
333 blocked: core::ops::Range<u64>,
334 /// Command reads before a started transfer runs; `None` never runs.
335 delay: Option<u32>,
336 polls_left: u32,
337 transfers: u32,
338 invert_liveness: bool,
339 }
340
341 impl FakeEdu {
342 fn new() -> Self {
343 Self {
344 id: 0x0100_00ed,
345 liveness: 0,
346 irq_status: 0,
347 src: 0,
348 dst: 0,
349 count: 0,
350 cmd: 0,
351 dma_mask: DEFAULT_DMA_MASK,
352 buffer: [0; DMA_BUFFER_SIZE as usize],
353 ram_base: 0x10_0000,
354 ram: std::vec![0; 0x4000],
355 blocked: 0..0,
356 delay: Some(3),
357 polls_left: 0,
358 transfers: 0,
359 invert_liveness: true,
360 }
361 }
362
363 fn ram_index(&self, addr: u64) -> usize {
364 usize::try_from(addr - self.ram_base).unwrap()
365 }
366
367 fn run_dma(&mut self) {
368 let len = self.count;
369 let to_ram = self.cmd & DMA_CMD_TO_RAM != 0;
370 let (device, ram) = if to_ram {
371 (self.src, self.dst)
372 } else {
373 (self.dst, self.src)
374 };
375 // QEMU aborts on a device side range outside the buffer.
376 assert!(
377 device >= DMA_BUFFER_ADDR && device + len <= DMA_BUFFER_ADDR + DMA_BUFFER_SIZE,
378 "edu would abort: device range {device:#x}+{len:#x}"
379 );
380 // QEMU masks the RAM side; the driver must never rely on that.
381 assert_eq!(ram & self.dma_mask, ram, "edu would clamp {ram:#x}");
382 let off = (device - DMA_BUFFER_ADDR) as usize;
383 let n = len as usize;
384 if !self.blocked.contains(&ram) {
385 let at = self.ram_index(ram);
386 if to_ram {
387 self.ram[at..at + n].copy_from_slice(&self.buffer[off..off + n]);
388 } else {
389 self.buffer[off..off + n].copy_from_slice(&self.ram[at..at + n]);
390 }
391 }
392 self.transfers += 1;
393 self.cmd &= !DMA_CMD_START;
394 if self.cmd & DMA_CMD_IRQ != 0 {
395 self.irq_status |= DMA_IRQ;
396 }
397 }
398 }
399
400 impl Registers for FakeEdu {
401 fn read32(&mut self, offset: usize) -> u32 {
402 match offset {
403 REG_ID => self.id,
404 REG_LIVENESS => self.liveness,
405 REG_IRQ_STATUS => self.irq_status,
406 _ => panic!("unexpected 32-bit read at {offset:#x}"),
407 }
408 }
409
410 fn write32(&mut self, offset: usize, value: u32) {
411 match offset {
412 REG_LIVENESS if self.invert_liveness => self.liveness = !value,
413 REG_LIVENESS => self.liveness = value,
414 REG_IRQ_ACK => self.irq_status &= !value,
415 _ => panic!("unexpected 32-bit write at {offset:#x}"),
416 }
417 }
418
419 fn read64(&mut self, offset: usize) -> u64 {
420 match offset {
421 REG_DMA_CMD => {
422 if self.cmd & DMA_CMD_START != 0 {
423 if let Some(delay) = self.delay {
424 if self.polls_left >= delay {
425 self.run_dma();
426 } else {
427 self.polls_left += 1;
428 }
429 }
430 }
431 self.cmd
432 }
433 _ => panic!("unexpected 64-bit read at {offset:#x}"),
434 }
435 }
436
437 fn write64(&mut self, offset: usize, value: u64) {
438 match offset {
439 REG_DMA_SRC => self.src = value,
440 REG_DMA_DST => self.dst = value,
441 REG_DMA_COUNT => self.count = value,
442 // QEMU ignores a new command while a transfer runs.
443 REG_DMA_CMD if self.cmd & DMA_CMD_START == 0 => {
444 self.cmd = value;
445 self.polls_left = 0;
446 }
447 REG_DMA_CMD => {}
448 _ => panic!("unexpected 64-bit write at {offset:#x}"),
449 }
450 }
451 }
452
453 #[test]
454 fn probe_reads_version_and_checks_liveness() {
455 let mut edu = Edu::new(FakeEdu::new());
456 assert_eq!(edu.probe(), Ok(EduVersion { major: 1, minor: 0 }));
457
458 let mut fake = FakeEdu::new();
459 fake.id = 0x1af4_1000;
460 assert_eq!(
461 Edu::new(fake).probe(),
462 Err(EduError::NotEdu { id: 0x1af4_1000 })
463 );
464
465 let mut fake = FakeEdu::new();
466 fake.invert_liveness = false;
467 assert_eq!(
468 Edu::new(fake).probe(),
469 Err(EduError::LivenessFailed {
470 wrote: 0x5a5a_a5a5,
471 read: 0x5a5a_a5a5
472 })
473 );
474 }
475
476 #[test]
477 fn round_trips_bytes_through_the_device_buffer() {
478 let mut fake = FakeEdu::new();
479 let src = fake.ram_base + 0x100;
480 let dst = fake.ram_base + 0x2000;
481 for (i, b) in fake.ram[0x100..0x100 + 200].iter_mut().enumerate() {
482 *b = i as u8 ^ 0xa5;
483 }
484 let mut edu = Edu::new(fake);
485 edu.dma_to_device(src, 200).unwrap();
486 edu.dma_from_device(dst, 200).unwrap();
487 let fake = edu.into_registers();
488 assert_eq!(fake.ram[0x2000..0x2000 + 200], fake.ram[0x100..0x100 + 200]);
489 assert_eq!(fake.transfers, 2);
490 assert_eq!(fake.src, DMA_BUFFER_ADDR);
491 assert_eq!(fake.dst, dst);
492 assert_eq!(fake.cmd, DMA_CMD_TO_RAM);
493 assert_eq!(fake.irq_status, 0, "no interrupt was requested");
494 }
495
496 #[test]
497 fn full_buffer_transfer_is_allowed() {
498 let fake = FakeEdu::new();
499 let at = fake.ram_base;
500 let mut edu = Edu::new(fake);
501 edu.dma_to_device(at, DMA_BUFFER_SIZE).unwrap();
502 edu.dma_from_device(at + DMA_BUFFER_SIZE, DMA_BUFFER_SIZE)
503 .unwrap();
504 }
505
506 #[test]
507 fn blocked_transfer_completes_but_leaves_ram_untouched() {
508 let mut fake = FakeEdu::new();
509 fake.buffer.fill(0x77);
510 let forbidden = fake.ram_base + 0x3000;
511 fake.blocked = forbidden..forbidden + 0x1000;
512 let mut edu = Edu::new(fake);
513 // The device reports success: completion is not proof of access.
514 assert_eq!(edu.dma_from_device(forbidden, 64), Ok(()));
515 let fake = edu.into_registers();
516 assert!(fake.ram[0x3000..0x3040].iter().all(|b| *b == 0));
517 }
518
519 #[test]
520 fn rejects_bad_lengths_and_addresses_before_touching_the_device() {
521 let mut edu = Edu::new(FakeEdu::new());
522 let top = DEFAULT_DMA_MASK + 1;
523 assert_eq!(edu.dma_to_device(0x1000, 0), Err(EduError::EmptyTransfer));
524 assert_eq!(
525 edu.dma_to_device(0x1000, DMA_BUFFER_SIZE + 1),
526 Err(EduError::TooLong {
527 len: DMA_BUFFER_SIZE + 1
528 })
529 );
530 let err = |iova, len| EduError::IovaOutOfRange {
531 iova,
532 len,
533 mask: DEFAULT_DMA_MASK,
534 };
535 assert_eq!(edu.dma_from_device(top, 16), Err(err(top, 16)));
536 // Starts below 256 MiB but runs past it.
537 assert_eq!(edu.dma_from_device(top - 8, 16), Err(err(top - 8, 16)));
538 assert_eq!(
539 edu.dma_from_device(u64::MAX - 3, 16),
540 Err(err(u64::MAX - 3, 16))
541 );
542 let fake = edu.into_registers();
543 assert_eq!((fake.src, fake.dst, fake.count, fake.cmd), (0, 0, 0, 0));
544 }
545
546 #[test]
547 fn last_byte_below_the_mask_is_accepted() {
548 let mut fake = FakeEdu::new();
549 fake.ram_base = DEFAULT_DMA_MASK + 1 - 0x2000;
550 let at = DEFAULT_DMA_MASK + 1 - 16;
551 let mut edu = Edu::new(fake);
552 assert_eq!(edu.dma_from_device(at, 16), Ok(()));
553 }
554
555 #[test]
556 fn wider_dma_mask_accepts_higher_addresses() {
557 let mut fake = FakeEdu::new();
558 fake.dma_mask = u64::MAX;
559 fake.ram_base = 0x8000_0000;
560 let mut edu = Edu::new(fake).with_dma_mask(u64::MAX);
561 assert_eq!(edu.dma_mask(), u64::MAX);
562 assert_eq!(edu.dma_from_device(0x8000_0000, 16), Ok(()));
563 }
564
565 #[test]
566 fn times_out_when_the_transfer_never_finishes() {
567 let mut fake = FakeEdu::new();
568 fake.delay = None;
569 let at = fake.ram_base;
570 let mut edu = Edu::new(fake).with_spin_limit(100);
571 assert_eq!(edu.dma_to_device(at, 16), Err(EduError::Timeout));
572 assert!(edu.dma_busy());
573 // The stuck transfer blocks the next one instead of being overwritten.
574 assert_eq!(edu.dma_from_device(at, 16), Err(EduError::Busy));
575 let fake = edu.into_registers();
576 assert_eq!(fake.cmd, DMA_CMD_START, "first command still pending");
577 assert_eq!(fake.transfers, 0);
578 }
579
580 #[test]
581 fn spin_budget_covers_a_slow_transfer() {
582 let mut fake = FakeEdu::new();
583 fake.delay = Some(1000);
584 let at = fake.ram_base;
585 let mut edu = Edu::new(fake).with_spin_limit(1001);
586 assert_eq!(edu.dma_to_device(at, 16), Ok(()));
587 let mut fake = edu.into_registers();
588 fake.delay = Some(1000);
589 let mut edu = Edu::new(fake).with_spin_limit(1000);
590 assert_eq!(edu.dma_to_device(at, 16), Err(EduError::Timeout));
591 }
592
593 #[test]
594 fn interrupt_status_and_acknowledge() {
595 let mut fake = FakeEdu::new();
596 fake.irq_status = DMA_IRQ | 0x1;
597 let mut edu = Edu::new(fake);
598 assert_eq!(edu.irq_status(), DMA_IRQ | 0x1);
599 edu.ack_irq(DMA_IRQ);
600 assert_eq!(edu.irq_status(), 0x1);
601 }
602}