Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/smmu.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / smmu.rs` 1407 lines ยท 50421 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 SMMUv3 descriptors, queues, and register sequencing. 17 //! 18 //! This module does not map MMIO. Register access and the cache maintenance 19 //! that makes CPU-written tables visible to the SMMU both go through the 20 //! [`Registers`] trait, so the whole bring-up runs against a fake in host 21 //! tests. 22 //! 23 //! Governing rule: no SMMU confinement means no DMA. The bring-up sets 24 //! GBPA.ABORT before anything else and never clears it, so a disabled SMMU 25 //! (SMMUEN = 0) aborts every transaction instead of bypassing. Once SMMUEN is 26 //! acknowledged, each stream follows its own STE, and every STE this module 27 //! does not configure is an abort STE. 28 29 use crate::mem::frame_allocator::PhysAddr; 30 use crate::mem::pagetable::{FrameSource, MapFlags, PageTableBuilder, PageTableError, TableMemory}; 31 32 pub const STE_BYTES: usize = 64; 33 pub const CD_BYTES: usize = 64; 34 pub const COMMAND_BYTES: usize = 16; 35 pub const EVENT_BYTES: usize = 32; 36 pub const CR0: u32 = 0x20; 37 pub const CR0ACK: u32 = 0x24; 38 pub const CR1: u32 = 0x28; 39 pub const CR2: u32 = 0x2c; 40 pub const IDR0: u32 = 0x00; 41 pub const IDR1: u32 = 0x04; 42 pub const IDR2: u32 = 0x08; 43 pub const IDR3: u32 = 0x0c; 44 pub const IDR4: u32 = 0x10; 45 pub const IDR5: u32 = 0x14; 46 pub const GBPA: u32 = 0x44; 47 pub const STRTAB_BASE: u32 = 0x80; 48 pub const STRTAB_BASE_CFG: u32 = 0x88; 49 pub const CMDQ_BASE: u32 = 0x90; 50 pub const CMDQ_PROD: u32 = 0x98; 51 pub const CMDQ_CONS: u32 = 0x9c; 52 pub const EVENTQ_BASE: u32 = 0xa0; 53 /// The event queue indexes live in register page 1 (base + 64 KiB). 54 pub const EVENTQ_PROD: u32 = 0x1_00a8; 55 pub const EVENTQ_CONS: u32 = 0x1_00ac; 56 57 pub const IDR0_S1P: u32 = 1 << 1; 58 pub const IDR1_SIDSIZE_MASK: u32 = 0x3f; 59 const IDR1_EVENTQS_SHIFT: u32 = 16; 60 const IDR1_CMDQS_SHIFT: u32 = 21; 61 const IDR1_QS_MASK: u32 = 0x1f; 62 63 /// GBPA.ABORT: with SMMUEN clear, abort every incoming transaction. 64 pub const GBPA_ABORT: u32 = 1 << 20; 65 /// GBPA.UPDATE: set by software to request an update, cleared by the SMMU 66 /// once the new GBPA value is in effect. 67 pub const GBPA_UPDATE: u32 = 1 << 31; 68 69 pub const CR0_SMMUEN: u32 = 1 << 0; 70 pub const CR0_EVENTQEN: u32 = 1 << 2; 71 pub const CR0_CMDQEN: u32 = 1 << 3; 72 const CR0_ACK_MASK: u32 = 0x0f; 73 74 /// CMDQ_CONS.ERR: non-zero when the SMMU stopped on a bad command. 75 const CMDQ_CONS_ERR_MASK: u32 = 0x7f << 24; 76 /// EVENTQ_PROD.OVFLG and EVENTQ_CONS.OVACKFLG. 77 const EVENTQ_OVERFLOW: u32 = 1 << 31; 78 79 /// Default poll bound for every SMMU handshake. 80 pub const DEFAULT_SPINS: usize = 1_000_000; 81 82 /// Platform seam for one SMMUv3 instance: 32-bit register access plus the 83 /// cache maintenance for memory the SMMU reads or writes. 84 pub trait Registers { 85 fn read(&mut self, offset: u32) -> u32; 86 fn write(&mut self, offset: u32, value: u32); 87 88 /// Write a 64-bit register as two 32-bit halves, low half first. 89 fn write64(&mut self, offset: u32, value: u64) { 90 self.write(offset, value as u32); 91 self.write(offset + 4, (value >> 32) as u32); 92 } 93 94 /// Make CPU writes to `[address, address + bytes)` visible to the SMMU 95 /// before the next register write. There is no default: an implementor 96 /// that forgets this on a non-coherent system would hand the SMMU stale 97 /// tables. 98 fn clean_dma(&mut self, address: usize, bytes: usize); 99 100 /// Drop CPU cache lines over `[address, address + bytes)` so the next CPU 101 /// read sees what the SMMU wrote. 102 fn invalidate_dma(&mut self, address: usize, bytes: usize); 103 } 104 105 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 106 pub enum Error { 107 /// A poll ran out of spins. 108 Timeout, 109 /// CMDQ_CONS.ERR reported a command error. 110 CommandQueue, 111 /// A table, queue, stream id or window failed validation. 112 InvalidWindow, 113 /// The SMMU lacks a feature this bring-up needs (IDR checks). 114 Unsupported, 115 /// GBPA did not read back with ABORT set after the update completed. 116 AbortNotLatched, 117 PageTable(PageTableError), 118 } 119 120 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 121 pub struct Ste(pub [u64; 8]); 122 123 impl Ste { 124 /// V = 1, Config = 0b000: abort every transaction from the stream. 125 /// There is deliberately no bypass constructor. 126 pub const fn abort() -> Self { 127 Self([1, 0, 0, 0, 0, 0, 0, 0]) 128 } 129 /// Stage-1 translate, stage-2 bypass. STE word 0 holds V (bit 0), 130 /// Config (bits 3:1, 0b101 = S1 translate / S2 bypass), S1Fmt (bits 5:4, 131 /// 0 = linear, one CD) and S1ContextPtr (bits 51:6, 64-byte aligned). 132 pub const fn stage1(cd_address: u64) -> Self { 133 Self([ 134 1 | (0b101 << 1) | (cd_address & 0x000f_ffff_ffff_ffc0), 135 0, 136 0, 137 0, 138 0, 139 0, 140 0, 141 0, 142 ]) 143 } 144 } 145 146 /// Linear-format, 64-byte context descriptor (eight little-endian words). 147 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 148 pub struct ContextDescriptor(pub [u64; 8]); 149 150 impl ContextDescriptor { 151 pub fn stage1(ttb0: u64, asid: u16, mair: u64, t0sz: u8) -> Result { 152 if t0sz > 39 || ttb0 & 0xfff != 0 { 153 return Err(Error::InvalidWindow); 154 } 155 // CD word 0 carries the TTBR0/TTBR1 configuration and every control 156 // bit: T0SZ, TG0, IRGN0, ORGN0, SH0, EPD0, EPD1, V, IPS, AA64, R, A 157 // and ASID. EPD0 stays clear so the TTBR0 stage-1 walk runs; EPD1 158 // disables the unused TTBR1 walk. 159 let word0 = u64::from(t0sz) 160 | (0b01 << 8) // IRGN0: write-back 161 | (0b01 << 10) // ORGN0: write-back 162 | (0b11 << 12) // SH0: inner shareable 163 | (1 << 30) // EPD1: TTBR1 walk disabled 164 | (1 << 31) // V: descriptor valid 165 | (0b101 << 32) // IPS: 5 (48-bit) 166 | (1 << 41) // AA64 167 | (1 << 45) // R: record faults as events 168 | (1 << 46) // A: abort faulting transactions (not RAZ/WI) 169 | (u64::from(asid) << 48); 170 // CD word 1 is the 4 KiB-aligned TTBR0 (48-bit physical address). 171 let word1 = ttb0 & 0x0000_ffff_ffff_fff0; 172 // CD word 2 is TTBR1, unused because EPD1 is set. 173 let word2 = 0; 174 // CD word 3 is MAIR. 175 let word3 = mair & 0x0000_0000_0000_ffff; 176 Ok(Self([word0, word1, word2, word3, 0, 0, 0, 0])) 177 } 178 } 179 180 pub const CMD_CFGI_STE: u8 = 0x03; 181 pub const CMD_CFGI_ALL: u8 = 0x04; 182 pub const CMD_TLBI_NSNH_ALL: u8 = 0x30; 183 pub const CMD_SYNC: u8 = 0x46; 184 185 pub const fn command(opcode: u8, sid: u32, leaf: bool) -> [u64; 2] { 186 let word0 = opcode as u64 | ((sid as u64) << 32); 187 let word1 = if opcode == CMD_CFGI_ALL { 188 31 189 } else { 190 leaf as u64 191 }; 192 [word0, word1] 193 } 194 195 /// SMMUv3 queue index: for a queue of 2^n entries the register holds the 196 /// index in bits n-1:0 and the wrap flag in bit n. 197 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 198 pub struct QueueCursor { 199 pub index: u32, 200 pub wrap: bool, 201 } 202 203 impl QueueCursor { 204 /// `entries` must be a power of two. 205 pub fn encode(self, entries: u32) -> u32 { 206 (self.index & (entries - 1)) | ((self.wrap as u32) << entries.trailing_zeros()) 207 } 208 209 /// `entries` must be a power of two. 210 pub fn decode(value: u32, entries: u32) -> Self { 211 Self { 212 index: value & (entries - 1), 213 wrap: value & entries != 0, 214 } 215 } 216 217 pub fn advance(&mut self, entries: u32) { 218 self.index += 1; 219 if self.index == entries { 220 self.index = 0; 221 self.wrap = !self.wrap; 222 } 223 } 224 } 225 226 /// Register mapping for an identity-mapped SMMUv3 register aperture 227 /// (both 64 KiB register pages). 228 pub struct MmioRegisters { 229 base: usize, 230 } 231 232 impl MmioRegisters { 233 /// # Safety 234 /// `base` must address a mapped SMMUv3 register aperture of 128 KiB. 235 pub const unsafe fn new(base: usize) -> Self { 236 Self { base } 237 } 238 } 239 240 impl Registers for MmioRegisters { 241 fn read(&mut self, offset: u32) -> u32 { 242 unsafe { core::ptr::read_volatile((self.base + offset as usize) as *const u32) } 243 } 244 245 fn write(&mut self, offset: u32, value: u32) { 246 unsafe { core::ptr::write_volatile((self.base + offset as usize) as *mut u32, value) } 247 } 248 249 fn clean_dma(&mut self, address: usize, bytes: usize) { 250 // Ends with DSB, which also orders the clean before the next MMIO write. 251 crate::arch::aarch64::clean_dcache_range(address, bytes); 252 } 253 254 fn invalidate_dma(&mut self, address: usize, bytes: usize) { 255 crate::arch::aarch64::clean_invalidate_dcache_range(address, bytes); 256 } 257 } 258 259 /// The memory one SMMU reads and writes in linear stream table mode: the 260 /// stream table, the command queue, the event queue and one context 261 /// descriptor. Addresses are identity mapped (virtual == physical). 262 #[derive(Debug)] 263 pub struct LinearTables { 264 stream_table: *mut [u64; 8], 265 stream_entries: u32, 266 command_queue: *mut [u64; 2], 267 command_entries: u32, 268 event_queue: *mut [u64; 4], 269 event_entries: u32, 270 context: *mut [u64; 8], 271 } 272 273 fn aligned(address: usize, bytes: usize) -> bool { 274 address != 0 && address & (bytes.max(32) - 1) == 0 275 } 276 277 impl LinearTables { 278 /// Validate the table geometry: every entry count is a power of two, each 279 /// queue has at least two entries, and every base is aligned to its own 280 /// size (the SMMU ignores low address bits below the size, so a 281 /// misaligned queue would overlap its neighbour). 282 /// 283 /// # Safety 284 /// Each pointer must address live, physically contiguous, identity 285 /// mapped RAM visible to the SMMU with room for the stated number of 286 /// entries, and nothing else may use that memory while this value (or 287 /// the SMMU programmed from it) is in use. 288 pub unsafe fn new( 289 stream_table: *mut [u64; 8], 290 stream_entries: u32, 291 command_queue: *mut [u64; 2], 292 command_entries: u32, 293 event_queue: *mut [u64; 4], 294 event_entries: u32, 295 context: *mut [u64; 8], 296 ) -> Result { 297 let pow2 = |n: u32, min: u32| n >= min && n.is_power_of_two(); 298 if !pow2(stream_entries, 1) 299 || !pow2(command_entries, 2) 300 || !pow2(event_entries, 2) 301 || !aligned(stream_table as usize, stream_entries as usize * STE_BYTES) 302 || !aligned( 303 command_queue as usize, 304 command_entries as usize * COMMAND_BYTES, 305 ) 306 || !aligned(event_queue as usize, event_entries as usize * EVENT_BYTES) 307 || !aligned(context as usize, CD_BYTES) 308 { 309 return Err(Error::InvalidWindow); 310 } 311 Ok(Self { 312 stream_table, 313 stream_entries, 314 command_queue, 315 command_entries, 316 event_queue, 317 event_entries, 318 context, 319 }) 320 } 321 322 pub fn stream_entries(&self) -> u32 { 323 self.stream_entries 324 } 325 326 pub fn context_address(&self) -> u64 { 327 self.context as u64 328 } 329 330 fn write_ste_word(&self, sid: u32, word: usize, value: u64) { 331 // Safety: `new` established that the table holds `stream_entries` 332 // STEs; callers check `sid` first. A 64-bit aligned store is single 333 // copy atomic, so the SMMU never sees a torn word 0. 334 unsafe { 335 core::ptr::write_volatile( 336 (self.stream_table.add(sid as usize) as *mut u64).add(word), 337 value, 338 ) 339 } 340 } 341 342 fn ste_address(&self, sid: u32) -> usize { 343 self.stream_table as usize + sid as usize * STE_BYTES 344 } 345 } 346 347 /// Wait for any GBPA update in flight, then request `value` and wait for the 348 /// SMMU to clear GBPA.UPDATE. 349 fn update_gbpa(regs: &mut R, value: u32, spins: usize) -> Result { 350 let mut current = poll_gbpa_idle(regs, spins)?; 351 current = (current & !GBPA_UPDATE) | value; 352 regs.write(GBPA, current | GBPA_UPDATE); 353 poll_gbpa_idle(regs, spins) 354 } 355 356 fn poll_gbpa_idle(regs: &mut R, spins: usize) -> Result { 357 for _ in 0..spins { 358 let gbpa = regs.read(GBPA); 359 if gbpa & GBPA_UPDATE == 0 { 360 return Ok(gbpa); 361 } 362 } 363 Err(Error::Timeout) 364 } 365 366 /// Set GBPA.ABORT so that whenever SMMUEN is clear every transaction aborts. 367 pub fn set_global_abort(regs: &mut R, spins: usize) -> Result<(), Error> { 368 let gbpa = update_gbpa(regs, GBPA_ABORT, spins)?; 369 if gbpa & GBPA_ABORT == 0 { 370 return Err(Error::AbortNotLatched); 371 } 372 Ok(()) 373 } 374 375 fn wait_cr0(regs: &mut R, expected: u32, spins: usize) -> Result<(), Error> { 376 for _ in 0..spins { 377 // CR0ACK mirrors the enabled queue and SMMU bits from CR0. 378 if regs.read(CR0ACK) & CR0_ACK_MASK == expected & CR0_ACK_MASK { 379 return Ok(()); 380 } 381 } 382 Err(Error::Timeout) 383 } 384 385 fn cmdq_cons(regs: &mut R, entries: u32) -> Result { 386 let cons = regs.read(CMDQ_CONS); 387 if cons & CMDQ_CONS_ERR_MASK != 0 { 388 return Err(Error::CommandQueue); 389 } 390 Ok(QueueCursor::decode(cons, entries)) 391 } 392 393 /// Append `commands` to the command queue and wait until the SMMU has 394 /// consumed all of them. Each poll is bounded by `spins`; a stuck queue 395 /// returns `Error::Timeout` and a command error returns 396 /// `Error::CommandQueue`. End the batch with `CMD_SYNC` when the caller 397 /// needs every earlier command to have taken effect. 398 pub fn submit_commands( 399 regs: &mut R, 400 tables: &LinearTables, 401 commands: &[[u64; 2]], 402 spins: usize, 403 ) -> Result<(), Error> { 404 let entries = tables.command_entries; 405 let mut prod = QueueCursor::decode(regs.read(CMDQ_PROD), entries); 406 for &words in commands { 407 // Wait for a free slot: the queue is full when the indexes match and 408 // the wrap flags differ. 409 let mut has_space = false; 410 for _ in 0..spins { 411 let cons = cmdq_cons(regs, entries)?; 412 if !(cons.index == prod.index && cons.wrap != prod.wrap) { 413 has_space = true; 414 break; 415 } 416 } 417 if !has_space { 418 return Err(Error::Timeout); 419 } 420 // Safety: `new` established that the queue holds `entries` slots and 421 // `prod.index < entries`. 422 let slot = unsafe { tables.command_queue.add(prod.index as usize) }; 423 unsafe { core::ptr::write_volatile(slot, words) }; 424 regs.clean_dma(slot as usize, COMMAND_BYTES); 425 prod.advance(entries); 426 regs.write(CMDQ_PROD, prod.encode(entries)); 427 } 428 for _ in 0..spins { 429 if cmdq_cons(regs, entries)? == prod { 430 return Ok(()); 431 } 432 } 433 Err(Error::Timeout) 434 } 435 436 /// Point stream `sid` at `ste` and make the SMMU forget any cached copy. 437 /// 438 /// The old entry is first replaced by an abort STE (one atomic store of word 439 /// 0) and invalidated, so the SMMU never sees a half-written entry: the new 440 /// words 1..7 are written behind that abort, then word 0 last. Finally 441 /// `CMD_CFGI_STE(sid)`, `CMD_TLBI_NSNH_ALL` and `CMD_SYNC` are issued and 442 /// waited for. 443 pub fn install_ste( 444 regs: &mut R, 445 tables: &LinearTables, 446 sid: u32, 447 ste: Ste, 448 spins: usize, 449 ) -> Result<(), Error> { 450 if sid >= tables.stream_entries { 451 return Err(Error::InvalidWindow); 452 } 453 abort_ste(regs, tables, sid, spins)?; 454 for (word, value) in ste.0.iter().enumerate().skip(1) { 455 tables.write_ste_word(sid, word, *value); 456 } 457 // Clean (and, through its DSB, order) words 1..7 before word 0 makes the 458 // entry live, so a coherent SMMU cannot fetch the new word 0 with stale 459 // words behind it. 460 regs.clean_dma(tables.ste_address(sid), STE_BYTES); 461 tables.write_ste_word(sid, 0, ste.0[0]); 462 invalidate_ste(regs, tables, sid, spins) 463 } 464 465 /// Return stream `sid` to abort: write an abort STE, then issue 466 /// `CMD_CFGI_STE(sid)`, `CMD_TLBI_NSNH_ALL` and `CMD_SYNC` and wait for them. 467 /// On `Ok` no further DMA from `sid` can translate. 468 pub fn abort_ste( 469 regs: &mut R, 470 tables: &LinearTables, 471 sid: u32, 472 spins: usize, 473 ) -> Result<(), Error> { 474 if sid >= tables.stream_entries { 475 return Err(Error::InvalidWindow); 476 } 477 let abort = Ste::abort(); 478 // Word 0 first: once V=1 and Config=abort, the other words are ignored. 479 tables.write_ste_word(sid, 0, abort.0[0]); 480 for (word, value) in abort.0.iter().enumerate().skip(1) { 481 tables.write_ste_word(sid, word, *value); 482 } 483 invalidate_ste(regs, tables, sid, spins) 484 } 485 486 fn invalidate_ste( 487 regs: &mut R, 488 tables: &LinearTables, 489 sid: u32, 490 spins: usize, 491 ) -> Result<(), Error> { 492 regs.clean_dma(tables.ste_address(sid), STE_BYTES); 493 submit_commands( 494 regs, 495 tables, 496 &[ 497 command(CMD_CFGI_STE, sid, true), 498 command(CMD_TLBI_NSNH_ALL, 0, false), 499 command(CMD_SYNC, 0, false), 500 ], 501 spins, 502 ) 503 } 504 505 pub const EVENT_F_UUT: u8 = 0x01; 506 pub const EVENT_C_BAD_STREAMID: u8 = 0x02; 507 pub const EVENT_F_STE_FETCH: u8 = 0x03; 508 pub const EVENT_C_BAD_STE: u8 = 0x04; 509 pub const EVENT_F_STREAM_DISABLED: u8 = 0x06; 510 pub const EVENT_F_TRANSL_FORBIDDEN: u8 = 0x07; 511 pub const EVENT_F_CD_FETCH: u8 = 0x09; 512 pub const EVENT_C_BAD_CD: u8 = 0x0a; 513 pub const EVENT_F_WALK_EABT: u8 = 0x0b; 514 pub const EVENT_F_TRANSLATION: u8 = 0x10; 515 pub const EVENT_F_ADDR_SIZE: u8 = 0x11; 516 pub const EVENT_F_ACCESS: u8 = 0x12; 517 pub const EVENT_F_PERMISSION: u8 = 0x13; 518 519 /// One decoded 32-byte event queue record. 520 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 521 pub struct EventRecord { 522 /// Word 0 bits 7:0 (see the `EVENT_*` constants). 523 pub event_type: u8, 524 /// Word 0 bits 63:32. 525 pub stream_id: u32, 526 /// Word 2: the faulting input address for translation-class events 527 /// (`EVENT_F_TRANSLATION` through `EVENT_F_PERMISSION`, and walk faults). 528 pub input_address: u64, 529 pub raw: [u64; 4], 530 } 531 532 impl EventRecord { 533 pub fn decode(raw: [u64; 4]) -> Self { 534 Self { 535 event_type: raw[0] as u8, 536 stream_id: (raw[0] >> 32) as u32, 537 input_address: raw[2], 538 raw, 539 } 540 } 541 } 542 543 /// Result of one [`read_events`] call. 544 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 545 pub struct EventDrain { 546 /// Records written to the front of the output slice. 547 pub count: usize, 548 /// The SMMU reported an event queue overflow since the last 549 /// acknowledgement (some events were lost). It is acknowledged here. 550 pub overflowed: bool, 551 } 552 553 /// Consume event records between EVENTQ_CONS and EVENTQ_PROD, oldest first, 554 /// up to `out.len()`, then publish the new EVENTQ_CONS. Records left over 555 /// stay queued for the next call. 556 pub fn read_events( 557 regs: &mut R, 558 tables: &LinearTables, 559 out: &mut [EventRecord], 560 ) -> EventDrain { 561 let entries = tables.event_entries; 562 let prod_raw = regs.read(EVENTQ_PROD); 563 let cons_raw = regs.read(EVENTQ_CONS); 564 let prod = QueueCursor::decode(prod_raw, entries); 565 let mut cons = QueueCursor::decode(cons_raw, entries); 566 let overflow_flag = prod_raw & EVENTQ_OVERFLOW; 567 let mut count = 0; 568 while cons != prod && count < out.len() { 569 // Safety: `new` established that the queue holds `entries` records 570 // and `cons.index < entries`. 571 let slot = unsafe { tables.event_queue.add(cons.index as usize) }; 572 regs.invalidate_dma(slot as usize, EVENT_BYTES); 573 let raw = unsafe { core::ptr::read_volatile(slot) }; 574 out[count] = EventRecord::decode(raw); 575 count += 1; 576 cons.advance(entries); 577 } 578 // Copying OVFLG into OVACKFLG acknowledges an overflow. 579 regs.write(EVENTQ_CONS, cons.encode(entries) | overflow_flag); 580 EventDrain { 581 count, 582 overflowed: overflow_flag != cons_raw & EVENTQ_OVERFLOW, 583 } 584 } 585 586 /// Bring the SMMU up with every stream in abort except `stream_id`, which 587 /// translates through `cd` (stage 1 only). 588 /// 589 /// Order, fail closed at every step: 590 /// 1. Set GBPA.ABORT and wait for the update. From here on a disabled SMMU 591 /// aborts all DMA. GBPA.ABORT is never cleared. 592 /// 2. Check the stream id and that IDR0/IDR1 support the geometry. 593 /// 3. Write the tables (all abort STEs, the CD, then the one live STE) and 594 /// clean them to the SMMU. 595 /// 4. Disable the SMMU, program queues and the stream table, enable the 596 /// queues, invalidate all cached config and TLBs, then set SMMUEN and wait 597 /// for CR0ACK. 598 /// 599 /// If step 1 fails the error is returned without touching CR0 (GBPA may 600 /// not have latched, so the caller must treat the SMMU as unusable). Any 601 /// later error writes CR0 = 0, which leaves the SMMU disabled behind 602 /// GBPA.ABORT (and so aborting every stream), and returns the error. 603 pub fn configure_linear_stream( 604 regs: &mut R, 605 tables: &LinearTables, 606 stream_id: u32, 607 cd: &ContextDescriptor, 608 spins: usize, 609 ) -> Result<(), Error> { 610 set_global_abort(regs, spins)?; 611 let result = check_and_program(regs, tables, stream_id, cd, spins); 612 if result.is_err() { 613 // Disable translation so that GBPA.ABORT governs every stream. The 614 // acknowledgement wait is best effort: the original error is the 615 // one reported, and ABORT stays set either way. 616 regs.write(CR0, 0); 617 let _ = wait_cr0(regs, 0, spins); 618 } 619 result 620 } 621 622 fn check_and_program( 623 regs: &mut R, 624 tables: &LinearTables, 625 stream_id: u32, 626 cd: &ContextDescriptor, 627 spins: usize, 628 ) -> Result<(), Error> { 629 if stream_id >= tables.stream_entries { 630 return Err(Error::InvalidWindow); 631 } 632 let sid_bits = tables.stream_entries.trailing_zeros(); 633 if regs.read(IDR0) & IDR0_S1P == 0 { 634 return Err(Error::Unsupported); 635 } 636 let idr1 = regs.read(IDR1); 637 if idr1 & IDR1_SIDSIZE_MASK < sid_bits 638 || (idr1 >> IDR1_CMDQS_SHIFT) & IDR1_QS_MASK < tables.command_entries.trailing_zeros() 639 || (idr1 >> IDR1_EVENTQS_SHIFT) & IDR1_QS_MASK < tables.event_entries.trailing_zeros() 640 { 641 return Err(Error::Unsupported); 642 } 643 program_linear_stream(regs, tables, stream_id, cd, sid_bits, spins) 644 } 645 646 fn program_linear_stream( 647 regs: &mut R, 648 tables: &LinearTables, 649 stream_id: u32, 650 cd: &ContextDescriptor, 651 sid_bits: u32, 652 spins: usize, 653 ) -> Result<(), Error> { 654 for sid in 0..tables.stream_entries { 655 for (word, value) in Ste::abort().0.iter().enumerate() { 656 tables.write_ste_word(sid, word, *value); 657 } 658 } 659 // Safety: `LinearTables::new` established the CD and queue geometry. 660 unsafe { 661 core::ptr::write_volatile(tables.context, cd.0); 662 for i in 0..tables.command_entries as usize { 663 core::ptr::write_volatile(tables.command_queue.add(i), [0; 2]); 664 } 665 for i in 0..tables.event_entries as usize { 666 core::ptr::write_volatile(tables.event_queue.add(i), [0; 4]); 667 } 668 } 669 let ste = Ste::stage1(tables.context_address()); 670 for (word, value) in ste.0.iter().enumerate().skip(1) { 671 tables.write_ste_word(stream_id, word, *value); 672 } 673 tables.write_ste_word(stream_id, 0, ste.0[0]); 674 675 // Everything the SMMU will fetch is written; clean it before any 676 // register points the SMMU at it. 677 regs.clean_dma( 678 tables.stream_table as usize, 679 tables.stream_entries as usize * STE_BYTES, 680 ); 681 regs.clean_dma(tables.context as usize, CD_BYTES); 682 regs.clean_dma( 683 tables.command_queue as usize, 684 tables.command_entries as usize * COMMAND_BYTES, 685 ); 686 // Clean and invalidate: no dirty CPU line may later overwrite an event. 687 regs.invalidate_dma( 688 tables.event_queue as usize, 689 tables.event_entries as usize * EVENT_BYTES, 690 ); 691 692 regs.write(CR0, 0); 693 wait_cr0(regs, 0, spins)?; 694 regs.write(CR1, 0x0d75); 695 regs.write64( 696 CMDQ_BASE, 697 tables.command_queue as u64 | u64::from(tables.command_entries.trailing_zeros()), 698 ); 699 regs.write(CMDQ_CONS, 0); 700 regs.write(CMDQ_PROD, 0); 701 regs.write64( 702 EVENTQ_BASE, 703 tables.event_queue as u64 | u64::from(tables.event_entries.trailing_zeros()), 704 ); 705 regs.write(EVENTQ_CONS, 0); 706 regs.write(EVENTQ_PROD, 0); 707 regs.write(STRTAB_BASE_CFG, sid_bits); 708 regs.write64(STRTAB_BASE, tables.stream_table as u64); 709 regs.write(CR0, CR0_CMDQEN | CR0_EVENTQEN); 710 wait_cr0(regs, CR0_CMDQEN | CR0_EVENTQEN, spins)?; 711 712 submit_commands( 713 regs, 714 tables, 715 &[ 716 command(CMD_CFGI_ALL, 0, false), 717 command(CMD_TLBI_NSNH_ALL, 0, false), 718 command(CMD_SYNC, 0, false), 719 ], 720 spins, 721 )?; 722 let enable = CR0_SMMUEN | CR0_CMDQEN | CR0_EVENTQEN; 723 regs.write(CR0, enable); 724 wait_cr0(regs, enable, spins) 725 } 726 727 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 728 pub struct DmaWindow { 729 pub iova: usize, 730 pub pa: PhysAddr, 731 pub length: usize, 732 } 733 734 /// The stage-1 translation for one stream: a page table that maps only the 735 /// allowed windows and the context descriptor that points at it. 736 pub struct DmaPolicy { 737 pub stream_id: u32, 738 pub cd: ContextDescriptor, 739 pub page_table: PageTableBuilder, 740 } 741 742 /// Build an identity-policy stage-1 table: only the supplied windows translate. 743 /// Hand `policy.cd` to [`configure_linear_stream`] after cleaning the page 744 /// table frames to the SMMU. 745 pub fn build_dma_policy( 746 stream_id: u32, 747 asid: u16, 748 windows: &[DmaWindow], 749 frames: F, 750 memory: M, 751 ) -> Result, Error> { 752 let mut table = PageTableBuilder::new(frames, memory).map_err(Error::PageTable)?; 753 for window in windows { 754 if window.iova != window.pa.0 { 755 return Err(Error::InvalidWindow); 756 } 757 table 758 .map(window.iova, window.pa, window.length, MapFlags::KERNEL_DATA) 759 .map_err(Error::PageTable)?; 760 } 761 let cd = ContextDescriptor::stage1(table.root().0 as u64, asid, 0x00ff, 16)?; 762 Ok(DmaPolicy { 763 stream_id, 764 cd, 765 page_table: table, 766 }) 767 } 768 769 #[cfg(test)] 770 mod tests { 771 use super::*; 772 use std::{boxed::Box, cell::RefCell, collections::BTreeMap, vec::Vec}; 773 774 const SIDS: u32 = 16; 775 const QUEUE: u32 = 16; 776 777 #[repr(C, align(1024))] 778 struct TestTables { 779 stream: [[u64; 8]; SIDS as usize], 780 events: [[u64; 4]; QUEUE as usize], 781 commands: [[u64; 2]; QUEUE as usize], 782 context: [u64; 8], 783 } 784 785 fn test_tables() -> (Box, LinearTables) { 786 let mut memory = Box::new(TestTables { 787 stream: [[0xdead; 8]; SIDS as usize], 788 events: [[0; 4]; QUEUE as usize], 789 commands: [[0; 2]; QUEUE as usize], 790 context: [0; 8], 791 }); 792 let tables = unsafe { 793 LinearTables::new( 794 memory.stream.as_mut_ptr(), 795 SIDS, 796 memory.commands.as_mut_ptr(), 797 QUEUE, 798 memory.events.as_mut_ptr(), 799 QUEUE, 800 &mut memory.context, 801 ) 802 } 803 .unwrap(); 804 (memory, tables) 805 } 806 807 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 808 enum Op { 809 /// Offset, value, and whether GBPA.ABORT was in effect after it. 810 Write(u32, u32, bool), 811 Clean(usize, usize), 812 Invalidate(usize, usize), 813 } 814 815 /// Register model: GBPA.UPDATE clears when the update completes (unless 816 /// `gbpa_stuck`), CR0ACK follows CR0 except for `ack_never` bits, and the 817 /// command queue consumes everything up to CMDQ_PROD (unless 818 /// `cmdq_stuck`), recording the commands it read. 819 struct Fake { 820 values: BTreeMap, 821 log: Vec, 822 gbpa_stuck: bool, 823 ack_never: u32, 824 cmdq_stuck: bool, 825 cmdq_error: bool, 826 consumed: Vec<[u64; 2]>, 827 } 828 829 impl Fake { 830 fn new() -> Self { 831 let mut values = BTreeMap::new(); 832 values.insert(IDR0, IDR0_S1P); 833 values.insert( 834 IDR1, 835 16 | (19 << IDR1_EVENTQS_SHIFT) | (19 << IDR1_CMDQS_SHIFT), 836 ); 837 // Reset GBPA: bypass (ABORT clear). 838 values.insert(GBPA, 0x1000); 839 Self { 840 values, 841 log: Vec::new(), 842 gbpa_stuck: false, 843 ack_never: 0, 844 cmdq_stuck: false, 845 cmdq_error: false, 846 consumed: Vec::new(), 847 } 848 } 849 fn get(&self, offset: u32) -> u32 { 850 *self.values.get(&offset).unwrap_or(&0) 851 } 852 fn abort_in_effect(&self) -> bool { 853 let gbpa = self.get(GBPA); 854 gbpa & GBPA_UPDATE == 0 && gbpa & GBPA_ABORT != 0 855 } 856 fn writes(&self) -> Vec<(u32, u32, bool)> { 857 self.log 858 .iter() 859 .filter_map(|op| match *op { 860 Op::Write(o, v, a) => Some((o, v, a)), 861 _ => None, 862 }) 863 .collect() 864 } 865 fn position(&self, pred: impl Fn(&Op) -> bool) -> Option { 866 self.log.iter().position(pred) 867 } 868 fn consume_commands(&mut self, prod: u32) { 869 let base = u64::from(self.get(CMDQ_BASE)) | (u64::from(self.get(CMDQ_BASE + 4)) << 32); 870 let entries = 1u32 << (base & 0x1f); 871 let queue = (base & !0x1f) as *const [u64; 2]; 872 let mut cons = QueueCursor::decode(self.get(CMDQ_CONS), entries); 873 let prod = QueueCursor::decode(prod, entries); 874 while cons != prod { 875 self.consumed 876 .push(unsafe { core::ptr::read_volatile(queue.add(cons.index as usize)) }); 877 cons.advance(entries); 878 } 879 self.values.insert(CMDQ_CONS, cons.encode(entries)); 880 } 881 } 882 883 impl Registers for Fake { 884 fn read(&mut self, offset: u32) -> u32 { 885 self.get(offset) 886 } 887 fn write(&mut self, offset: u32, value: u32) { 888 let mut stored = value; 889 if offset == GBPA && !self.gbpa_stuck { 890 stored &= !GBPA_UPDATE; 891 } 892 self.values.insert(offset, stored); 893 match offset { 894 CR0 => { 895 self.values.insert(CR0ACK, value & !self.ack_never); 896 } 897 CMDQ_PROD if self.get(CR0ACK) & CR0_CMDQEN != 0 => { 898 if self.cmdq_error { 899 self.values.insert(CMDQ_CONS, 0x01 << 24); 900 } else if !self.cmdq_stuck { 901 self.consume_commands(value); 902 } 903 } 904 _ => {} 905 } 906 let abort = self.abort_in_effect(); 907 self.log.push(Op::Write(offset, value, abort)); 908 } 909 fn clean_dma(&mut self, address: usize, bytes: usize) { 910 self.log.push(Op::Clean(address, bytes)); 911 } 912 fn invalidate_dma(&mut self, address: usize, bytes: usize) { 913 self.log.push(Op::Invalidate(address, bytes)); 914 } 915 } 916 917 fn cd() -> ContextDescriptor { 918 ContextDescriptor::stage1(0x4000, 1, 0x00ff, 16).unwrap() 919 } 920 921 fn smmuen_write(regs: &Fake) -> Option { 922 regs.position(|op| matches!(op, Op::Write(CR0, v, _) if v & CR0_SMMUEN != 0)) 923 } 924 925 #[test] 926 fn descriptor_layouts() { 927 assert_eq!(Ste::abort().0[0], 1); 928 // Review fix: Config 0b101 (S1 translate) and S1ContextPtr in word 0. 929 let ste = Ste::stage1(0x1_2345_6780); 930 assert_eq!(ste.0[0] & 1, 1, "V"); 931 assert_eq!( 932 (ste.0[0] >> 1) & 0b111, 933 0b101, 934 "Config = S1 translate, S2 bypass" 935 ); 936 assert_eq!((ste.0[0] >> 4) & 0b11, 0, "S1Fmt linear"); 937 assert_eq!( 938 ste.0[0] & 0x000f_ffff_ffff_ffc0, 939 0x1_2345_6780, 940 "S1ContextPtr" 941 ); 942 assert_eq!(&ste.0[1..], &[0; 7]); 943 let cd = ContextDescriptor::stage1(0x4000, 0x1234, 0xff00, 16).unwrap(); 944 assert_eq!( 945 cd.0[0], 946 16 | (1 << 8) 947 | (1 << 10) 948 | (3 << 12) 949 | (1 << 30) 950 | (1 << 31) 951 | (0b101_u64 << 32) 952 | (1 << 41) 953 | (1 << 45) 954 | (1 << 46) 955 | (0x1234_u64 << 48) 956 ); 957 assert_eq!(cd.0[1], 0x4000, "TTBR0"); 958 assert_eq!(cd.0[2], 0, "TTBR1 unused (EPD1 set)"); 959 assert_eq!(cd.0[3], 0xff00, "MAIR"); 960 } 961 962 #[test] 963 fn command_words_and_queue_wrap() { 964 assert_eq!( 965 command(CMD_CFGI_STE, 7, true), 966 [CMD_CFGI_STE as u64 | (7 << 32), 1] 967 ); 968 assert_eq!(command(CMD_CFGI_ALL, 0, false), [4, 31]); 969 assert_eq!(command(CMD_TLBI_NSNH_ALL, 0, false)[0], 0x30); 970 assert_eq!(command(CMD_SYNC, 0, false)[0], 0x46); 971 let mut c = QueueCursor { 972 index: 1, 973 wrap: false, 974 }; 975 c.advance(2); 976 assert_eq!( 977 c, 978 QueueCursor { 979 index: 0, 980 wrap: true 981 } 982 ); 983 // The wrap flag sits just above the index bits, not in bit 31. 984 assert_eq!(c.encode(2), 0b10); 985 let c = QueueCursor { 986 index: 5, 987 wrap: true, 988 }; 989 assert_eq!(c.encode(16), 0x15); 990 assert_eq!(QueueCursor::decode(0x15, 16), c); 991 assert!(!QueueCursor::decode(0x8000_0005, 16).wrap); 992 } 993 994 #[test] 995 fn tables_reject_misaligned_or_bad_geometry() { 996 let (mut memory, _) = test_tables(); 997 let stream = memory.stream.as_mut_ptr(); 998 let commands = memory.commands.as_mut_ptr(); 999 let events = memory.events.as_mut_ptr(); 1000 let context: *mut [u64; 8] = &mut memory.context; 1001 let new = |s, se, c, ce, e, ee, cd| unsafe { LinearTables::new(s, se, c, ce, e, ee, cd) }; 1002 assert!(new(stream, SIDS, commands, QUEUE, events, QUEUE, context).is_ok()); 1003 assert!(new(stream, 12, commands, QUEUE, events, QUEUE, context).is_err()); 1004 assert!(new(stream, SIDS, commands, 1, events, QUEUE, context).is_err()); 1005 // The event queue base must be aligned to its 512-byte size. 1006 let shifted = unsafe { (commands as *mut u8).sub(256) }.cast::<[u64; 4]>(); 1007 assert!(new(stream, SIDS, commands, QUEUE, shifted, QUEUE, context).is_err()); 1008 let cd = unsafe { (context as *mut u8).add(8) }.cast::<[u64; 8]>(); 1009 assert!(new(stream, SIDS, commands, QUEUE, events, QUEUE, cd).is_err()); 1010 } 1011 1012 #[test] 1013 fn bring_up_keeps_global_abort_through_smmuen() { 1014 let (memory, tables) = test_tables(); 1015 let mut regs = Fake::new(); 1016 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1017 1018 // The first register write sets GBPA.ABORT, and ABORT is in effect 1019 // after every register write up to and including SMMUEN. 1020 let writes = regs.writes(); 1021 assert_eq!(writes[0].0, GBPA); 1022 assert!(writes.iter().all(|&(_, _, abort)| abort), "{writes:x?}"); 1023 assert!(writes 1024 .iter() 1025 .filter(|w| w.0 == GBPA) 1026 .all(|w| w.1 & GBPA_ABORT != 0)); 1027 let last = *writes.last().unwrap(); 1028 assert_eq!((last.0, last.1), (CR0, 0x0d), "SMMUEN is the final write"); 1029 assert_eq!(regs.get(CR0ACK), 0x0d, "SMMUEN acknowledged"); 1030 assert!(regs.abort_in_effect(), "GBPA still aborts if SMMUEN drops"); 1031 1032 // Only stream 3 translates, through the CD this call wrote. 1033 for (sid, ste) in memory.stream.iter().enumerate() { 1034 if sid == 3 { 1035 assert_eq!(*ste, Ste::stage1(tables.context_address()).0); 1036 } else { 1037 assert_eq!(*ste, Ste::abort().0, "sid {sid}"); 1038 } 1039 } 1040 assert_eq!(memory.context, cd().0); 1041 assert_eq!( 1042 regs.consumed, 1043 [ 1044 command(CMD_CFGI_ALL, 0, false), 1045 command(CMD_TLBI_NSNH_ALL, 0, false), 1046 command(CMD_SYNC, 0, false) 1047 ] 1048 ); 1049 assert_eq!(regs.get(STRTAB_BASE_CFG), 4); 1050 } 1051 1052 #[test] 1053 fn bring_up_cleans_tables_after_writing_before_programming() { 1054 let (memory, tables) = test_tables(); 1055 let mut regs = Fake::new(); 1056 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1057 let stream = memory.stream.as_ptr() as usize; 1058 let context = &memory.context as *const _ as usize; 1059 let commands = memory.commands.as_ptr() as usize; 1060 let events = memory.events.as_ptr() as usize; 1061 let cleans = [ 1062 regs.position(|op| *op == Op::Clean(stream, SIDS as usize * STE_BYTES)), 1063 regs.position(|op| *op == Op::Clean(context, CD_BYTES)), 1064 regs.position(|op| *op == Op::Clean(commands, QUEUE as usize * COMMAND_BYTES)), 1065 regs.position(|op| *op == Op::Invalidate(events, QUEUE as usize * EVENT_BYTES)), 1066 ]; 1067 let first_cr0 = regs 1068 .position(|op| matches!(op, Op::Write(CR0, _, _))) 1069 .unwrap(); 1070 let first_strtab = regs 1071 .position(|op| matches!(op, Op::Write(STRTAB_BASE, _, _))) 1072 .unwrap(); 1073 for clean in cleans { 1074 let clean = clean.expect("table region cleaned"); 1075 assert!(clean < first_cr0 && clean < first_strtab); 1076 } 1077 // Tables are cleaned after GBPA.ABORT, so the cleans cover the final 1078 // contents (this function writes tables only after that point). 1079 assert!(regs.position(|op| matches!(op, Op::Write(GBPA, _, _))) < cleans[0]); 1080 } 1081 1082 #[test] 1083 fn gbpa_update_timeout_fails_closed() { 1084 let (_memory, tables) = test_tables(); 1085 let mut regs = Fake::new(); 1086 regs.gbpa_stuck = true; 1087 assert_eq!( 1088 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4), 1089 Err(Error::Timeout) 1090 ); 1091 assert_eq!(regs.get(GBPA) & GBPA_ABORT, GBPA_ABORT, "ABORT requested"); 1092 assert!(regs.writes().iter().all(|w| w.0 == GBPA), "nothing else"); 1093 } 1094 1095 #[test] 1096 fn smmuen_ack_failure_fails_closed() { 1097 let (_memory, tables) = test_tables(); 1098 let mut regs = Fake::new(); 1099 regs.ack_never = CR0_SMMUEN; 1100 assert_eq!( 1101 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4), 1102 Err(Error::Timeout) 1103 ); 1104 assert!(regs.abort_in_effect()); 1105 let last = *regs.writes().last().unwrap(); 1106 assert_eq!((last.0, last.1), (CR0, 0), "SMMU left disabled"); 1107 assert!(regs.writes().iter().all(|&(_, _, abort)| abort)); 1108 } 1109 1110 #[test] 1111 fn command_timeout_and_error_fail_closed() { 1112 for error in [false, true] { 1113 let (_memory, tables) = test_tables(); 1114 let mut regs = Fake::new(); 1115 regs.cmdq_stuck = !error; 1116 regs.cmdq_error = error; 1117 let expected = if error { 1118 Error::CommandQueue 1119 } else { 1120 Error::Timeout 1121 }; 1122 assert_eq!( 1123 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4), 1124 Err(expected) 1125 ); 1126 assert!(smmuen_write(®s).is_none(), "SMMUEN never requested"); 1127 assert!(regs.abort_in_effect()); 1128 assert_eq!(regs.get(CR0), 0); 1129 } 1130 } 1131 1132 #[test] 1133 #[allow(clippy::type_complexity)] 1134 fn unsupported_hardware_or_bad_sid_fails_closed() { 1135 let cases: [(Box, u32, Error); 3] = [ 1136 ( 1137 Box::new(|r| { 1138 let _ = r.values.insert(IDR1, 2); 1139 }), 1140 3, 1141 Error::Unsupported, 1142 ), 1143 ( 1144 Box::new(|r| { 1145 let _ = r.values.insert(IDR0, 0); 1146 }), 1147 3, 1148 Error::Unsupported, 1149 ), 1150 (Box::new(|_| {}), SIDS, Error::InvalidWindow), 1151 ]; 1152 for (setup, sid, expected) in cases { 1153 let (memory, tables) = test_tables(); 1154 let mut regs = Fake::new(); 1155 // Firmware left the SMMU enabled: the error path must disable it 1156 // so that GBPA.ABORT governs every stream. 1157 regs.write(CR0, CR0_SMMUEN | CR0_CMDQEN); 1158 regs.log.clear(); 1159 setup(&mut regs); 1160 assert_eq!( 1161 configure_linear_stream(&mut regs, &tables, sid, &cd(), 4), 1162 Err(expected) 1163 ); 1164 let writes = regs.writes(); 1165 assert_eq!(writes[0].0, GBPA, "ABORT is requested first"); 1166 assert_eq!(*writes.last().unwrap(), (CR0, 0, true), "{writes:x?}"); 1167 assert!(writes.iter().all(|w| w.0 == GBPA || w.0 == CR0)); 1168 assert!(regs.abort_in_effect()); 1169 assert_eq!(regs.get(CR0ACK), 0, "SMMU disabled"); 1170 assert!(smmuen_write(®s).is_none()); 1171 // No table was written. 1172 assert!(memory.stream.iter().all(|ste| *ste == [0xdead; 8])); 1173 } 1174 } 1175 1176 #[test] 1177 fn gbpa_that_will_not_abort_is_an_error() { 1178 struct NoAbort(Fake); 1179 impl Registers for NoAbort { 1180 fn read(&mut self, offset: u32) -> u32 { 1181 self.0.read(offset) 1182 } 1183 fn write(&mut self, offset: u32, value: u32) { 1184 let value = if offset == GBPA { 1185 value & !GBPA_ABORT 1186 } else { 1187 value 1188 }; 1189 self.0.write(offset, value) 1190 } 1191 fn clean_dma(&mut self, a: usize, b: usize) { 1192 self.0.clean_dma(a, b) 1193 } 1194 fn invalidate_dma(&mut self, a: usize, b: usize) { 1195 self.0.invalidate_dma(a, b) 1196 } 1197 } 1198 let (_memory, tables) = test_tables(); 1199 let mut regs = NoAbort(Fake::new()); 1200 assert_eq!( 1201 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4), 1202 Err(Error::AbortNotLatched) 1203 ); 1204 assert!(regs.0.writes().iter().all(|w| w.0 == GBPA)); 1205 } 1206 1207 #[test] 1208 fn install_and_abort_ste_invalidate_that_stream() { 1209 let (memory, tables) = test_tables(); 1210 let mut regs = Fake::new(); 1211 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1212 regs.consumed.clear(); 1213 regs.log.clear(); 1214 1215 let ste = Ste::stage1(tables.context_address()); 1216 install_ste(&mut regs, &tables, 7, ste, 4).unwrap(); 1217 assert_eq!(memory.stream[7], ste.0); 1218 let invalidate = [ 1219 command(CMD_CFGI_STE, 7, true), 1220 command(CMD_TLBI_NSNH_ALL, 0, false), 1221 command(CMD_SYNC, 0, false), 1222 ]; 1223 // Abort first, then the new entry, each invalidated and synced. 1224 assert_eq!(regs.consumed[..3], invalidate); 1225 assert_eq!(regs.consumed[3..], invalidate); 1226 let ste7 = memory.stream.as_ptr() as usize + 7 * STE_BYTES; 1227 let clean = regs 1228 .position(|op| *op == Op::Clean(ste7, STE_BYTES)) 1229 .unwrap(); 1230 let prod = regs 1231 .position(|op| matches!(op, Op::Write(CMDQ_PROD, _, _))) 1232 .unwrap(); 1233 assert!(clean < prod, "STE cleaned before the SMMU is told"); 1234 1235 regs.consumed.clear(); 1236 abort_ste(&mut regs, &tables, 7, 4).unwrap(); 1237 assert_eq!(memory.stream[7], Ste::abort().0); 1238 assert_eq!(regs.consumed, invalidate); 1239 1240 assert_eq!( 1241 install_ste(&mut regs, &tables, SIDS, ste, 4), 1242 Err(Error::InvalidWindow) 1243 ); 1244 assert_eq!( 1245 abort_ste(&mut regs, &tables, SIDS, 4), 1246 Err(Error::InvalidWindow) 1247 ); 1248 } 1249 1250 #[test] 1251 fn command_queue_wraps_and_times_out() { 1252 let (_memory, tables) = test_tables(); 1253 let mut regs = Fake::new(); 1254 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1255 // 3 + 11 * 3 = 36 commands: the 16-entry queue wraps twice. 1256 for _ in 0..11 { 1257 abort_ste(&mut regs, &tables, 5, 4).unwrap(); 1258 } 1259 assert_eq!(regs.consumed.len(), 36); 1260 assert_eq!(regs.get(CMDQ_PROD), 36 % 16, "two wraps: flag clear"); 1261 for _ in 0..4 { 1262 abort_ste(&mut regs, &tables, 5, 4).unwrap(); 1263 } 1264 assert_eq!( 1265 regs.get(CMDQ_PROD), 1266 0x10, 1267 "48 commands, three wraps: flag set" 1268 ); 1269 1270 regs.cmdq_stuck = true; 1271 assert_eq!(abort_ste(&mut regs, &tables, 5, 4), Err(Error::Timeout)); 1272 } 1273 1274 #[test] 1275 fn submit_refuses_to_overwrite_a_full_queue() { 1276 let (_memory, tables) = test_tables(); 1277 let mut regs = Fake::new(); 1278 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1279 regs.cmdq_stuck = true; 1280 let sync = [command(CMD_SYNC, 0, false); QUEUE as usize + 1]; 1281 assert_eq!( 1282 submit_commands(&mut regs, &tables, &sync, 4), 1283 Err(Error::Timeout) 1284 ); 1285 // 16 slots were used from index 3; the 17th would have overwritten 1286 // an unconsumed command, so it was never published. 1287 let prod = QueueCursor::decode(regs.get(CMDQ_PROD), QUEUE); 1288 let cons = QueueCursor::decode(regs.get(CMDQ_CONS), QUEUE); 1289 assert_eq!(prod.index, cons.index); 1290 assert_ne!(prod.wrap, cons.wrap); 1291 } 1292 1293 fn event(kind: u8, sid: u32, address: u64) -> [u64; 4] { 1294 [u64::from(kind) | (u64::from(sid) << 32), 0, address, 0] 1295 } 1296 1297 #[test] 1298 fn event_reader_decodes_and_consumes_records() { 1299 let (mut memory, tables) = test_tables(); 1300 let mut regs = Fake::new(); 1301 configure_linear_stream(&mut regs, &tables, 3, &cd(), 4).unwrap(); 1302 1303 assert_eq!( 1304 read_events(&mut regs, &tables, &mut []), 1305 EventDrain::default() 1306 ); 1307 // Records at 14, 15, 0 (wrapped): PROD index 1 with wrap set. 1308 memory.events[14] = event(EVENT_F_TRANSLATION, 3, 0x1234_5000); 1309 memory.events[15] = event(EVENT_C_BAD_STE, 9, 0); 1310 memory.events[0] = event(EVENT_F_PERMISSION, 3, 0xdead_b000); 1311 regs.values.insert(EVENTQ_CONS, 14); 1312 regs.values.insert(EVENTQ_PROD, 0x10 | 1); 1313 1314 let mut out = [EventRecord::default(); 2]; 1315 let drain = read_events(&mut regs, &tables, &mut out); 1316 assert_eq!( 1317 drain, 1318 EventDrain { 1319 count: 2, 1320 overflowed: false 1321 } 1322 ); 1323 assert_eq!(out[0].event_type, EVENT_F_TRANSLATION); 1324 assert_eq!(out[0].stream_id, 3); 1325 assert_eq!(out[0].input_address, 0x1234_5000); 1326 assert_eq!(out[1].event_type, EVENT_C_BAD_STE); 1327 assert_eq!(out[1].stream_id, 9); 1328 assert_eq!(regs.get(EVENTQ_CONS), 0x10, "index 0, wrapped"); 1329 let slot14 = memory.events.as_ptr() as usize + 14 * EVENT_BYTES; 1330 assert!(regs 1331 .position(|op| *op == Op::Invalidate(slot14, EVENT_BYTES)) 1332 .is_some()); 1333 1334 let drain = read_events(&mut regs, &tables, &mut out); 1335 assert_eq!(drain.count, 1); 1336 assert_eq!(out[0].event_type, EVENT_F_PERMISSION); 1337 assert_eq!(out[0].input_address, 0xdead_b000); 1338 assert_eq!(regs.get(EVENTQ_CONS), 0x11); 1339 assert_eq!(read_events(&mut regs, &tables, &mut out).count, 0); 1340 } 1341 1342 #[test] 1343 fn event_reader_acknowledges_overflow() { 1344 let (_memory, tables) = test_tables(); 1345 let mut regs = Fake::new(); 1346 regs.values.insert(EVENTQ_PROD, EVENTQ_OVERFLOW); 1347 let mut out = [EventRecord::default(); 1]; 1348 assert!(read_events(&mut regs, &tables, &mut out).overflowed); 1349 assert_eq!(regs.get(EVENTQ_CONS), EVENTQ_OVERFLOW, "OVACKFLG copied"); 1350 assert!(!read_events(&mut regs, &tables, &mut out).overflowed); 1351 } 1352 1353 #[test] 1354 fn policy_maps_only_allowed_windows() { 1355 struct Frames(usize); 1356 impl FrameSource for Frames { 1357 fn allocate_frame(&mut self) -> Option { 1358 let p = PhysAddr(self.0); 1359 self.0 += 4096; 1360 Some(p) 1361 } 1362 fn deallocate_frame(&mut self, _: PhysAddr) -> bool { 1363 true 1364 } 1365 } 1366 #[derive(Clone, Default)] 1367 struct Mem(RefCell>); 1368 impl TableMemory for Mem { 1369 fn read_entry(&self, t: PhysAddr, i: usize) -> Option { 1370 Some(*self.0.borrow().get(&(t.0, i)).unwrap_or(&0)) 1371 } 1372 fn write_entry(&mut self, t: PhysAddr, i: usize, v: u64) -> bool { 1373 self.0.borrow_mut().insert((t.0, i), v); 1374 true 1375 } 1376 } 1377 let window = DmaWindow { 1378 iova: 0x1000, 1379 pa: PhysAddr(0x1000), 1380 length: 4096, 1381 }; 1382 let policy = build_dma_policy(9, 1, &[window], Frames(0x100000), Mem::default()).unwrap(); 1383 assert_eq!(policy.stream_id, 9); 1384 assert_eq!( 1385 policy.cd, 1386 ContextDescriptor::stage1(0x100000, 1, 0x00ff, 16).unwrap() 1387 ); 1388 assert_eq!( 1389 policy 1390 .page_table 1391 .translate(0x1000) 1392 .unwrap() 1393 .unwrap() 1394 .physical_address, 1395 PhysAddr(0x1000) 1396 ); 1397 assert!(policy.page_table.translate(0x2000).unwrap().is_none()); 1398 let skewed = DmaWindow { 1399 iova: 0x2000, 1400 ..window 1401 }; 1402 assert!(matches!( 1403 build_dma_policy(9, 1, &[skewed], Frames(0x100000), Mem::default()), 1404 Err(Error::InvalidWindow) 1405 )); 1406 } 1407 }