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/device.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 / device.rs` 1122 lines ยท 41767 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 //! Device authority: a device may only move memory (DMA) while a capability 17 //! says it may. 18 //! 19 //! # The security invariant 20 //! 21 //! Device authority and capability authority are the same boundary. A device 22 //! can reach memory only through two gates that the kernel controls: 23 //! 24 //! 1. The IOMMU (SMMU) stream table entry for the device's stream. Until the 25 //! kernel installs a translation window there, every DMA the device issues 26 //! is aborted by the IOMMU. 27 //! 2. The PCI bus master enable (BME) bit. While it is clear, the device 28 //! cannot start DMA at all. 29 //! 30 //! This module is the only code that opens those gates, and it opens them only 31 //! when a capability that names the device and carries the `MAP` right is 32 //! presented. It opens the IOMMU gate first and the BME gate second, so there 33 //! is never a moment where the device can issue DMA that the IOMMU would not 34 //! confine. 35 //! 36 //! Revocation closes the gates in the reverse order: stop handing the device 37 //! new work, clear BME, quiesce or reset the device, set the stream to ABORT, 38 //! invalidate any cached translations, and only then remove the capability 39 //! and everything derived from it. Taking authority away never depends on the 40 //! device cooperating: if a hardware step fails, the remaining steps still 41 //! run, so BME ends clear and the stream ends aborted wherever the hardware 42 //! allows, and the error is reported. 43 //! 44 //! Every authority check happens before any hardware effect. A missing, 45 //! stale, or under-privileged capability causes no hardware effect at all. 46 //! 47 //! An active device remembers which capability activated it. If that 48 //! capability disappears by any route other than [`revoke_device`] (the 49 //! holder removes it, an ancestor is revoked with plain [`CapTable::revoke`], 50 //! or the holder's table is destroyed), the kernel calls 51 //! [`DeviceTable::sweep`], which tears down every device whose activating 52 //! capability no longer resolves with `MAP`. So a device never keeps DMA 53 //! access that no live capability grants. 54 //! 55 //! Every teardown also forgets the device's DMA window, so the next 56 //! activation only reaches memory the kernel hands out afresh, never the 57 //! previous holder's buffers. 58 //! 59 //! Hardware is reached through the small traits [`DmaTranslation`], 60 //! [`PciCommand`], and [`Quiesce`], so this logic is host-tested with a fake 61 //! recorder and does not depend on a particular SMMU or PCI driver. 62 //! 63 //! Two notes on scope: 64 //! 65 //! - `REVOKE` on a device capability is the power to stop that device for 66 //! every holder, because there is only one device. Derive `REVOKE` only to 67 //! a task trusted with that power. 68 //! - Revocation removes the presented capability and its descendants. A 69 //! capability to the same device that was never derived from it (for 70 //! example an independent root, or a copy made by `transfer`) is a separate 71 //! grant of authority and survives, although the device is left quiesced 72 //! and must be activated again, with a fresh window, by whoever holds `MAP`. 73 74 use crate::caps::{CapError, CapTable, Handle, Rights}; 75 use crate::mem::frame_allocator::PAGE_SIZE; 76 77 /// Kernel-assigned identity of a device, stable for the life of the table. 78 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 79 pub struct DeviceId(pub u32); 80 81 /// Where a device stands with respect to DMA. 82 /// 83 /// The discriminants are fixed so the state can be reported or stored in a 84 /// stable form. 85 #[repr(u8)] 86 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 87 pub enum DmaState { 88 /// BME clear and the stream aborted (or never opened). No DMA possible. 89 /// This is the only state from which a device may be activated. 90 Quiesced = 0, 91 /// The IOMMU translation is installed but BME is still clear. Transient: 92 /// it exists only between the two activation steps, and is kept as a 93 /// named state so a later split of activation (for example waiting on a 94 /// driver between the steps) has a correct place to stop. 95 TranslationInstalled = 1, 96 /// BME set and the translation installed: the device may DMA inside its 97 /// window. 98 Active = 2, 99 /// Teardown started but did not complete cleanly. The device is not 100 /// trusted again until a teardown succeeds (see 101 /// [`DeviceTable::force_quiesce`]). 102 Revoking = 3, 103 } 104 105 /// The IOVA range a device may reach once its translation is installed: 106 /// `pages` pages of `PAGE_SIZE` bytes starting at `iova`. How the range maps 107 /// to physical memory is the `DmaTranslation` implementation's business. 108 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 109 pub struct DmaWindow { 110 pub iova: u64, 111 pub pages: u32, 112 } 113 114 impl DmaWindow { 115 /// Non-empty, page aligned, and not wrapping past the top of the address 116 /// space. 117 pub const fn is_valid(self) -> bool { 118 let page = PAGE_SIZE as u64; 119 self.pages != 0 120 && self.iova.is_multiple_of(page) 121 && self.iova.checked_add(self.pages as u64 * page).is_some() 122 } 123 } 124 125 /// Names one capability slot: the table it lives in and its handle. 126 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 127 pub struct CapRef { 128 pub table: u32, 129 pub handle: Handle, 130 } 131 132 /// One DMA-capable device known to the kernel. 133 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 134 pub struct Device { 135 pub id: DeviceId, 136 /// PCI requester ID (bus, device, function). 137 pub requester_id: u16, 138 /// IOMMU stream ID for this device's DMA. 139 pub stream_id: u32, 140 pub state: DmaState, 141 /// The window to install on activation. `None` means the kernel has not 142 /// given the device any memory yet, so it cannot be activated. Cleared by 143 /// every teardown. 144 pub window: Option, 145 /// The capability that activated the device, while it is active. 146 pub authority: Option, 147 } 148 149 impl Device { 150 /// A new device in the safe starting state: quiesced, no window. 151 pub const fn new(id: DeviceId, requester_id: u16, stream_id: u32) -> Self { 152 Self { 153 id, 154 requester_id, 155 stream_id, 156 state: DmaState::Quiesced, 157 window: None, 158 authority: None, 159 } 160 } 161 } 162 163 /// A hardware operation failed. The code is driver specific and opaque here. 164 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 165 pub struct HwFault(pub u32); 166 167 /// Which hardware step an error came from. 168 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 169 pub enum HwStep { 170 InstallTranslation, 171 EnableBusMaster, 172 DisableBusMaster, 173 Quiesce, 174 AbortStream, 175 Invalidate, 176 } 177 178 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 179 pub enum DeviceError { 180 /// The capability was missing, stale, or lacked the needed right. 181 Cap(CapError), 182 /// The capability is valid but does not name a registered device. 183 NotADevice, 184 /// The device is not in a state that allows the operation. 185 WrongState(DmaState), 186 /// Activation was requested before the kernel set a DMA window. 187 NoWindow, 188 /// The window is empty, unaligned, or wraps the address space. 189 BadWindow, 190 /// The device table has no free slot. 191 Full, 192 /// Registration clashes with an existing resource, device ID, requester 193 /// ID, or stream ID. 194 Duplicate, 195 /// A hardware step failed. For activation the device was torn down again; 196 /// for revocation the capability was still revoked. If the device state 197 /// is [`DmaState::Revoking`] afterwards, the teardown itself also failed 198 /// and [`DeviceTable::force_quiesce`] should be retried. 199 Hardware { step: HwStep, fault: HwFault }, 200 /// Hardware teardown succeeded but `CapTable::revoke` then refused (for 201 /// example malformed derivation data). DMA is stopped and the window is 202 /// forgotten, but no capability was removed. 203 Revoke(CapError), 204 } 205 206 impl From for DeviceError { 207 fn from(error: CapError) -> Self { 208 Self::Cap(error) 209 } 210 } 211 212 /// IOMMU control for one stream. Implemented over the SMMU driver. 213 pub trait DmaTranslation { 214 /// Make `window` the only memory the stream may reach. Must be visible to 215 /// the IOMMU (synchronized) before returning `Ok`. 216 fn install_translation(&mut self, stream_id: u32, window: DmaWindow) -> Result<(), HwFault>; 217 /// Point the stream at an ABORT entry so every DMA from it faults. 218 fn abort_stream(&mut self, stream_id: u32) -> Result<(), HwFault>; 219 /// Drop any translations the IOMMU may have cached for the stream. 220 fn invalidate(&mut self, stream_id: u32) -> Result<(), HwFault>; 221 } 222 223 /// PCI command register control. Implemented over the PCI config space. 224 pub trait PciCommand { 225 /// Set or clear the bus master enable bit for `requester_id`. 226 fn set_bus_master(&mut self, requester_id: u16, enabled: bool) -> Result<(), HwFault>; 227 } 228 229 /// The device driver's part of teardown. 230 pub trait Quiesce { 231 /// Stop handing the device new work (close submission queues). 232 fn stop_work(&mut self, device: &Device); 233 /// Wait for in-flight work to finish, or reset the device. 234 fn quiesce(&mut self, device: &Device) -> Result<(), HwFault>; 235 } 236 237 #[derive(Clone, Copy)] 238 struct Entry { 239 resource: u32, 240 device: Device, 241 } 242 243 /// Fixed-capacity map from a capability resource ID to a device. No 244 /// allocation. The resource IDs share the opaque space used by `CapTable`, so 245 /// the kernel must pick device resource IDs that do not collide with other 246 /// resources. 247 pub struct DeviceTable { 248 entries: [Option; N], 249 } 250 251 impl Default for DeviceTable { 252 fn default() -> Self { 253 Self::new() 254 } 255 } 256 257 impl DeviceTable { 258 pub const fn new() -> Self { 259 Self { entries: [None; N] } 260 } 261 262 /// Add a device reachable through capabilities naming `resource`. The 263 /// device must start quiesced with no authority. Resource, device ID, 264 /// requester ID, and stream ID must all be unique: two devices sharing a 265 /// stream or a bus master bit could not be revoked apart. 266 pub fn register(&mut self, resource: u32, device: Device) -> Result<(), DeviceError> { 267 if device.state != DmaState::Quiesced || device.authority.is_some() { 268 return Err(DeviceError::WrongState(device.state)); 269 } 270 if let Some(window) = device.window { 271 if !window.is_valid() { 272 return Err(DeviceError::BadWindow); 273 } 274 } 275 let clash = self.entries.iter().flatten().any(|entry| { 276 entry.resource == resource 277 || entry.device.id == device.id 278 || entry.device.requester_id == device.requester_id 279 || entry.device.stream_id == device.stream_id 280 }); 281 if clash { 282 return Err(DeviceError::Duplicate); 283 } 284 let slot = self 285 .entries 286 .iter_mut() 287 .find(|entry| entry.is_none()) 288 .ok_or(DeviceError::Full)?; 289 *slot = Some(Entry { resource, device }); 290 Ok(()) 291 } 292 293 pub fn get(&self, resource: u32) -> Option<&Device> { 294 self.entries 295 .iter() 296 .flatten() 297 .find(|entry| entry.resource == resource) 298 .map(|entry| &entry.device) 299 } 300 301 fn get_mut(&mut self, resource: u32) -> Option<&mut Device> { 302 self.entries 303 .iter_mut() 304 .flatten() 305 .find(|entry| entry.resource == resource) 306 .map(|entry| &mut entry.device) 307 } 308 309 /// Set the window a later activation will install. Only allowed while the 310 /// device is quiesced, so a live device's reach never changes underneath 311 /// it. This is a kernel decision, not a capability holder's. 312 pub fn set_window(&mut self, resource: u32, window: DmaWindow) -> Result<(), DeviceError> { 313 let device = self.get_mut(resource).ok_or(DeviceError::NotADevice)?; 314 if device.state != DmaState::Quiesced { 315 return Err(DeviceError::WrongState(device.state)); 316 } 317 if !window.is_valid() { 318 return Err(DeviceError::BadWindow); 319 } 320 device.window = Some(window); 321 Ok(()) 322 } 323 324 /// Tear down every device that is not quiesced and whose activating 325 /// capability no longer resolves, with `MAP`, to that device. A table 326 /// missing from `tables` counts as gone, so the caller must pass every 327 /// live table. Call this after any capability removal that did not go 328 /// through [`revoke_device`]. Devices left in [`DmaState::Revoking`] by 329 /// an earlier failed teardown are retried too. Every device is processed; 330 /// the first hardware error is returned. 331 pub fn sweep( 332 &mut self, 333 tables: &[&CapTable], 334 hw: &mut H, 335 ) -> Result<(), DeviceError> 336 where 337 H: DmaTranslation + PciCommand + Quiesce, 338 { 339 let mut first = Ok(()); 340 for entry in self.entries.iter_mut().flatten() { 341 if entry.device.state == DmaState::Quiesced { 342 continue; 343 } 344 let live = entry.device.authority.is_some_and(|auth| { 345 let mut owners = tables.iter().filter(|table| table.id() == auth.table); 346 match (owners.next(), owners.next()) { 347 (Some(table), None) => { 348 table.lookup(auth.handle, Rights::MAP) == Ok(entry.resource) 349 } 350 _ => false, 351 } 352 }); 353 if !live { 354 let result = teardown(&mut entry.device, hw); 355 if first.is_ok() { 356 first = result; 357 } 358 } 359 } 360 first 361 } 362 363 /// Run the teardown sequence on a device without a capability. Removing 364 /// authority never needs authority, so the kernel may call this at any 365 /// time (for example to retry after a failed teardown left the device in 366 /// [`DmaState::Revoking`]). Returns the first hardware error, if any. 367 pub fn force_quiesce(&mut self, resource: u32, hw: &mut H) -> Result<(), DeviceError> 368 where 369 H: DmaTranslation + PciCommand + Quiesce, 370 { 371 let device = self.get_mut(resource).ok_or(DeviceError::NotADevice)?; 372 teardown(device, hw) 373 } 374 } 375 376 /// Resolve `handle` in `caps` with `rights` to a registered device. 377 fn resolve<'d, const N: usize, const M: usize>( 378 caps: &CapTable, 379 handle: Handle, 380 rights: Rights, 381 devices: &'d mut DeviceTable, 382 ) -> Result<&'d mut Device, DeviceError> { 383 let resource = caps.lookup(handle, rights)?; 384 devices.get_mut(resource).ok_or(DeviceError::NotADevice) 385 } 386 387 /// Give the device named by `handle` DMA access to its window. 388 /// 389 /// Requires a capability with `MAP` that names a registered, quiesced device 390 /// with a window. Every check runs before any hardware effect, so a refused 391 /// request touches no hardware. On success the order is: install the IOMMU 392 /// translation, then set BME; the device ends [`DmaState::Active`] and 393 /// records `handle` in `caps` as its authority. 394 /// 395 /// If a hardware step fails, the full teardown runs so BME ends clear and the 396 /// stream ends aborted, and the failing step is reported. The teardown also 397 /// forgets the window, so the kernel must set one again before a retry. 398 pub fn activate( 399 caps: &CapTable, 400 handle: Handle, 401 devices: &mut DeviceTable, 402 hw: &mut H, 403 ) -> Result<(), DeviceError> 404 where 405 H: DmaTranslation + PciCommand + Quiesce, 406 { 407 let device = resolve(caps, handle, Rights::MAP, devices)?; 408 if device.state != DmaState::Quiesced { 409 return Err(DeviceError::WrongState(device.state)); 410 } 411 let window = device.window.ok_or(DeviceError::NoWindow)?; 412 413 if let Err(fault) = hw.install_translation(device.stream_id, window) { 414 // The activation error is the one returned. A failed teardown is 415 // still visible to the caller: the state stays Revoking. 416 let _ = teardown(device, hw); 417 return Err(DeviceError::Hardware { 418 step: HwStep::InstallTranslation, 419 fault, 420 }); 421 } 422 device.state = DmaState::TranslationInstalled; 423 424 if let Err(fault) = hw.set_bus_master(device.requester_id, true) { 425 let _ = teardown(device, hw); 426 return Err(DeviceError::Hardware { 427 step: HwStep::EnableBusMaster, 428 fault, 429 }); 430 } 431 device.state = DmaState::Active; 432 device.authority = Some(CapRef { 433 table: caps.id(), 434 handle, 435 }); 436 Ok(()) 437 } 438 439 /// Take DMA access away from the device named by `handle` and revoke the 440 /// capability and everything derived from it. 441 /// 442 /// `table_id` names the table in `tables` that holds `handle`, which must 443 /// carry `REVOKE` and name a registered device. `tables` must include every 444 /// table that may hold descendants, exactly as for [`CapTable::revoke`]. 445 /// These checks run before any hardware effect. 446 /// 447 /// Order: stop new work, clear BME, quiesce or reset, abort the stream, 448 /// invalidate translations, then revoke the capability tree. The device ends 449 /// [`DmaState::Quiesced`] with no window and no authority. If a hardware step 450 /// fails, the remaining steps still run, the capability is still revoked, the 451 /// device is left in [`DmaState::Revoking`] so it cannot be activated, and 452 /// the first hardware error is returned. 453 /// 454 /// `CapTable::revoke` checks the derivation tree itself and can still refuse 455 /// after the hardware is down (only on malformed derivation data). Then DMA 456 /// stays stopped and [`DeviceError::Revoke`] is returned. Stopping DMA first 457 /// is the safe direction to fail in. 458 pub fn revoke_device( 459 table_id: u32, 460 handle: Handle, 461 tables: &mut [&mut CapTable], 462 devices: &mut DeviceTable, 463 hw: &mut H, 464 ) -> Result<(), DeviceError> 465 where 466 H: DmaTranslation + PciCommand + Quiesce, 467 { 468 let mut matching = tables.iter().filter(|table| table.id() == table_id); 469 let caps = match (matching.next(), matching.next()) { 470 (Some(table), None) => table, 471 _ => return Err(DeviceError::Cap(CapError::DuplicateTable)), 472 }; 473 let device = resolve(caps, handle, Rights::REVOKE, devices)?; 474 475 let hardware = teardown(device, hw); 476 // Authority is removed even if the hardware misbehaved: a faulty device 477 // must not be able to keep its capability alive. 478 let revoked = CapTable::::revoke(table_id, handle, tables); 479 hardware?; 480 revoked.map_err(DeviceError::Revoke) 481 } 482 483 /// Close both DMA gates. Runs every step even after a failure and returns the 484 /// first failure. The device is `Quiesced` only if every step succeeded. The 485 /// window and authority are forgotten either way. 486 fn teardown(device: &mut Device, hw: &mut H) -> Result<(), DeviceError> 487 where 488 H: DmaTranslation + PciCommand + Quiesce, 489 { 490 device.state = DmaState::Revoking; 491 device.window = None; 492 device.authority = None; 493 let mut first: Option = None; 494 let mut note = |step: HwStep, result: Result<(), HwFault>| { 495 if let (Err(fault), None) = (result, first) { 496 first = Some(DeviceError::Hardware { step, fault }); 497 } 498 }; 499 500 hw.stop_work(device); 501 note( 502 HwStep::DisableBusMaster, 503 hw.set_bus_master(device.requester_id, false), 504 ); 505 note(HwStep::Quiesce, hw.quiesce(device)); 506 note(HwStep::AbortStream, hw.abort_stream(device.stream_id)); 507 note(HwStep::Invalidate, hw.invalidate(device.stream_id)); 508 509 match first { 510 None => { 511 device.state = DmaState::Quiesced; 512 Ok(()) 513 } 514 Some(error) => Err(error), 515 } 516 } 517 518 #[cfg(test)] 519 mod tests { 520 use super::*; 521 use std::vec::Vec; 522 523 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 524 enum Effect { 525 Install(u32, DmaWindow), 526 Bme(u16, bool), 527 StopWork(DeviceId), 528 Quiesce(DeviceId), 529 Abort(u32), 530 Invalidate(u32), 531 } 532 533 /// Records every hardware effect and can fail one chosen step. 534 #[derive(Default)] 535 struct Recorder { 536 effects: Vec, 537 fail: Option, 538 /// Hardware view of BME and the stream, to check the final state. 539 bme: bool, 540 aborted: bool, 541 } 542 543 impl Recorder { 544 fn failing(step: HwStep) -> Self { 545 Self { 546 fail: Some(step), 547 ..Self::default() 548 } 549 } 550 fn result(&self, step: HwStep) -> Result<(), HwFault> { 551 if self.fail == Some(step) { 552 Err(HwFault(0xdead)) 553 } else { 554 Ok(()) 555 } 556 } 557 } 558 559 impl DmaTranslation for Recorder { 560 fn install_translation( 561 &mut self, 562 stream_id: u32, 563 window: DmaWindow, 564 ) -> Result<(), HwFault> { 565 self.effects.push(Effect::Install(stream_id, window)); 566 self.result(HwStep::InstallTranslation)?; 567 self.aborted = false; 568 Ok(()) 569 } 570 fn abort_stream(&mut self, stream_id: u32) -> Result<(), HwFault> { 571 self.effects.push(Effect::Abort(stream_id)); 572 self.result(HwStep::AbortStream)?; 573 self.aborted = true; 574 Ok(()) 575 } 576 fn invalidate(&mut self, stream_id: u32) -> Result<(), HwFault> { 577 self.effects.push(Effect::Invalidate(stream_id)); 578 self.result(HwStep::Invalidate) 579 } 580 } 581 582 impl PciCommand for Recorder { 583 fn set_bus_master(&mut self, requester_id: u16, enabled: bool) -> Result<(), HwFault> { 584 self.effects.push(Effect::Bme(requester_id, enabled)); 585 let step = if enabled { 586 HwStep::EnableBusMaster 587 } else { 588 HwStep::DisableBusMaster 589 }; 590 self.result(step)?; 591 self.bme = enabled; 592 Ok(()) 593 } 594 } 595 596 impl Quiesce for Recorder { 597 fn stop_work(&mut self, device: &Device) { 598 self.effects.push(Effect::StopWork(device.id)); 599 } 600 fn quiesce(&mut self, device: &Device) -> Result<(), HwFault> { 601 self.effects.push(Effect::Quiesce(device.id)); 602 self.result(HwStep::Quiesce) 603 } 604 } 605 606 const RES: u32 = 0x100; 607 const DEV: DeviceId = DeviceId(3); 608 const RID: u16 = 0x0010; 609 const SID: u32 = 0x10; 610 const WINDOW: DmaWindow = DmaWindow { 611 iova: 0x4000_0000, 612 pages: 4, 613 }; 614 const ALL: Rights = Rights::from_bits(0x3f).unwrap(); 615 616 fn devices() -> DeviceTable<4> { 617 let mut table = DeviceTable::new(); 618 table.register(RES, Device::new(DEV, RID, SID)).unwrap(); 619 table.set_window(RES, WINDOW).unwrap(); 620 table 621 } 622 623 fn teardown_effects() -> [Effect; 5] { 624 [ 625 Effect::StopWork(DEV), 626 Effect::Bme(RID, false), 627 Effect::Quiesce(DEV), 628 Effect::Abort(SID), 629 Effect::Invalidate(SID), 630 ] 631 } 632 633 fn state(devices: &DeviceTable<4>) -> DmaState { 634 devices.get(RES).unwrap().state 635 } 636 637 #[test] 638 fn activate_installs_translation_before_bus_master() { 639 let mut caps = CapTable::<4>::new(1); 640 let handle = caps.insert(RES, Rights::MAP).unwrap(); 641 let mut devices = devices(); 642 let mut hw = Recorder::default(); 643 644 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 645 646 assert_eq!( 647 hw.effects, 648 [Effect::Install(SID, WINDOW), Effect::Bme(RID, true)] 649 ); 650 assert_eq!(state(&devices), DmaState::Active); 651 } 652 653 #[test] 654 fn revoke_runs_exact_teardown_then_removes_capability_tree() { 655 let mut owner = CapTable::<4>::new(1); 656 let mut user = CapTable::<4>::new(2); 657 let root = owner.insert(RES, ALL).unwrap(); 658 let child = CapTable::derive_into(&mut owner, root, &mut user, Rights::MAP).unwrap(); 659 let mut devices = devices(); 660 let mut hw = Recorder::default(); 661 activate(&user, child, &mut devices, &mut hw).unwrap(); 662 hw.effects.clear(); 663 664 revoke_device(1, root, &mut [&mut owner, &mut user], &mut devices, &mut hw).unwrap(); 665 666 assert_eq!(hw.effects, teardown_effects()); 667 assert_eq!(state(&devices), DmaState::Quiesced); 668 assert_eq!( 669 owner.lookup(root, Rights::NONE), 670 Err(CapError::InvalidHandle) 671 ); 672 assert_eq!( 673 user.lookup(child, Rights::NONE), 674 Err(CapError::InvalidHandle) 675 ); 676 } 677 678 #[test] 679 fn activate_with_revoked_handle_fails_without_effects() { 680 let mut caps = CapTable::<4>::new(1); 681 let handle = caps.insert(RES, ALL).unwrap(); 682 let mut devices = devices(); 683 let mut hw = Recorder::default(); 684 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 685 revoke_device(1, handle, &mut [&mut caps], &mut devices, &mut hw).unwrap(); 686 hw.effects.clear(); 687 688 assert_eq!( 689 activate(&caps, handle, &mut devices, &mut hw), 690 Err(DeviceError::Cap(CapError::InvalidHandle)) 691 ); 692 assert!(hw.effects.is_empty()); 693 } 694 695 #[test] 696 fn missing_capability_causes_no_effects() { 697 let caps = CapTable::<4>::new(1); 698 let mut devices = devices(); 699 let mut hw = Recorder::default(); 700 let bogus = Handle { 701 index: 0, 702 generation: 1, 703 }; 704 assert_eq!( 705 activate(&caps, bogus, &mut devices, &mut hw), 706 Err(DeviceError::Cap(CapError::InvalidHandle)) 707 ); 708 let mut caps = caps; 709 assert_eq!( 710 revoke_device(1, bogus, &mut [&mut caps], &mut devices, &mut hw), 711 Err(DeviceError::Cap(CapError::InvalidHandle)) 712 ); 713 assert!(hw.effects.is_empty()); 714 assert_eq!(state(&devices), DmaState::Quiesced); 715 } 716 717 #[test] 718 fn read_only_capability_causes_no_effects() { 719 let mut caps = CapTable::<4>::new(1); 720 let handle = caps.insert(RES, Rights::READ).unwrap(); 721 let mut devices = devices(); 722 let mut hw = Recorder::default(); 723 assert_eq!( 724 activate(&caps, handle, &mut devices, &mut hw), 725 Err(DeviceError::Cap(CapError::MissingRights)) 726 ); 727 assert_eq!( 728 revoke_device(1, handle, &mut [&mut caps], &mut devices, &mut hw), 729 Err(DeviceError::Cap(CapError::MissingRights)) 730 ); 731 assert!(hw.effects.is_empty()); 732 assert_eq!(caps.lookup(handle, Rights::READ), Ok(RES)); 733 } 734 735 #[test] 736 fn map_without_revoke_cannot_tear_down_an_active_device() { 737 let mut caps = CapTable::<4>::new(1); 738 let handle = caps.insert(RES, Rights::MAP).unwrap(); 739 let mut devices = devices(); 740 let mut hw = Recorder::default(); 741 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 742 hw.effects.clear(); 743 assert_eq!( 744 revoke_device(1, handle, &mut [&mut caps], &mut devices, &mut hw), 745 Err(DeviceError::Cap(CapError::MissingRights)) 746 ); 747 assert!(hw.effects.is_empty()); 748 assert_eq!(state(&devices), DmaState::Active); 749 } 750 751 #[test] 752 fn attenuated_capability_without_map_cannot_activate() { 753 let mut caps = CapTable::<4>::new(1); 754 let root = caps.insert(RES, ALL).unwrap(); 755 let weak = caps 756 .derive(root, Rights::READ | Rights::WRITE | Rights::REVOKE) 757 .unwrap(); 758 let mut devices = devices(); 759 let mut hw = Recorder::default(); 760 assert_eq!( 761 activate(&caps, weak, &mut devices, &mut hw), 762 Err(DeviceError::Cap(CapError::MissingRights)) 763 ); 764 assert!(hw.effects.is_empty()); 765 assert_eq!(state(&devices), DmaState::Quiesced); 766 } 767 768 #[test] 769 fn capability_for_other_resource_is_not_a_device() { 770 let mut caps = CapTable::<4>::new(1); 771 let console = caps.insert(1, ALL).unwrap(); 772 let mut devices = devices(); 773 let mut hw = Recorder::default(); 774 assert_eq!( 775 activate(&caps, console, &mut devices, &mut hw), 776 Err(DeviceError::NotADevice) 777 ); 778 assert_eq!( 779 revoke_device(1, console, &mut [&mut caps], &mut devices, &mut hw), 780 Err(DeviceError::NotADevice) 781 ); 782 assert!(hw.effects.is_empty()); 783 assert_eq!(caps.lookup(console, Rights::READ), Ok(1)); 784 } 785 786 #[test] 787 fn activation_refused_without_window_or_when_already_active() { 788 let mut caps = CapTable::<4>::new(1); 789 let handle = caps.insert(RES, Rights::MAP).unwrap(); 790 let mut devices = DeviceTable::<4>::new(); 791 devices.register(RES, Device::new(DEV, RID, SID)).unwrap(); 792 let mut hw = Recorder::default(); 793 assert_eq!( 794 activate(&caps, handle, &mut devices, &mut hw), 795 Err(DeviceError::NoWindow) 796 ); 797 assert!(hw.effects.is_empty()); 798 799 devices.set_window(RES, WINDOW).unwrap(); 800 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 801 hw.effects.clear(); 802 assert_eq!( 803 activate(&caps, handle, &mut devices, &mut hw), 804 Err(DeviceError::WrongState(DmaState::Active)) 805 ); 806 assert_eq!( 807 devices.set_window(RES, WINDOW), 808 Err(DeviceError::WrongState(DmaState::Active)) 809 ); 810 assert!(hw.effects.is_empty()); 811 } 812 813 #[test] 814 fn activation_failure_at_each_step_leaves_bus_master_clear_and_stream_aborted() { 815 for step in [HwStep::InstallTranslation, HwStep::EnableBusMaster] { 816 let mut caps = CapTable::<4>::new(1); 817 let handle = caps.insert(RES, Rights::MAP).unwrap(); 818 let mut devices = devices(); 819 let mut hw = Recorder::failing(step); 820 821 let result = activate(&caps, handle, &mut devices, &mut hw); 822 823 assert_eq!( 824 result, 825 Err(DeviceError::Hardware { 826 step, 827 fault: HwFault(0xdead) 828 }) 829 ); 830 let mut expected = Vec::from([Effect::Install(SID, WINDOW)]); 831 if step == HwStep::EnableBusMaster { 832 expected.push(Effect::Bme(RID, true)); 833 } 834 expected.extend(teardown_effects()); 835 assert_eq!(hw.effects, expected, "{step:?}"); 836 assert!(!hw.bme, "{step:?}"); 837 assert!(hw.aborted, "{step:?}"); 838 assert_eq!(state(&devices), DmaState::Quiesced, "{step:?}"); 839 } 840 } 841 842 #[test] 843 fn failed_teardown_blocks_activation_until_a_clean_retry() { 844 // Quiescing fails during revocation, so teardown is incomplete. 845 let mut caps = CapTable::<4>::new(1); 846 let handle = caps.insert(RES, ALL).unwrap(); 847 let mut devices = devices(); 848 let mut hw = Recorder::failing(HwStep::Quiesce); 849 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 850 851 assert!(revoke_device(1, handle, &mut [&mut caps], &mut devices, &mut hw).is_err()); 852 assert_eq!(state(&devices), DmaState::Revoking); 853 854 // A fresh capability to the same device still cannot activate it. 855 let again = caps.insert(RES, Rights::MAP).unwrap(); 856 hw.effects.clear(); 857 assert_eq!( 858 activate(&caps, again, &mut devices, &mut hw), 859 Err(DeviceError::WrongState(DmaState::Revoking)) 860 ); 861 assert!(hw.effects.is_empty()); 862 863 // A clean retry without a capability returns it to Quiesced. 864 hw.fail = None; 865 devices.force_quiesce(RES, &mut hw).unwrap(); 866 assert_eq!(hw.effects, teardown_effects()); 867 assert_eq!(state(&devices), DmaState::Quiesced); 868 } 869 870 #[test] 871 fn revoke_failure_at_each_step_still_closes_gates_and_revokes() { 872 for step in [ 873 HwStep::DisableBusMaster, 874 HwStep::Quiesce, 875 HwStep::AbortStream, 876 HwStep::Invalidate, 877 ] { 878 let mut owner = CapTable::<4>::new(1); 879 let mut user = CapTable::<4>::new(2); 880 let root = owner.insert(RES, ALL).unwrap(); 881 let child = CapTable::derive_into(&mut owner, root, &mut user, Rights::MAP).unwrap(); 882 let mut devices = devices(); 883 let mut hw = Recorder::default(); 884 activate(&user, child, &mut devices, &mut hw).unwrap(); 885 hw.effects.clear(); 886 hw.fail = Some(step); 887 888 let result = 889 revoke_device(1, root, &mut [&mut owner, &mut user], &mut devices, &mut hw); 890 891 assert_eq!( 892 result, 893 Err(DeviceError::Hardware { 894 step, 895 fault: HwFault(0xdead) 896 }), 897 "{step:?}" 898 ); 899 // Every step still ran, in order. 900 assert_eq!(hw.effects, teardown_effects(), "{step:?}"); 901 // BME is clear unless clearing it is the step that failed, and 902 // the stream is aborted unless aborting is the step that failed. 903 assert_eq!(hw.bme, step == HwStep::DisableBusMaster, "{step:?}"); 904 assert_eq!(hw.aborted, step != HwStep::AbortStream, "{step:?}"); 905 assert_eq!(state(&devices), DmaState::Revoking, "{step:?}"); 906 // Authority is gone regardless. 907 assert_eq!( 908 owner.lookup(root, Rights::NONE), 909 Err(CapError::InvalidHandle) 910 ); 911 assert_eq!( 912 user.lookup(child, Rights::NONE), 913 Err(CapError::InvalidHandle) 914 ); 915 } 916 } 917 918 #[test] 919 fn duplicate_or_missing_table_in_revoke_set_causes_no_effects() { 920 let mut caps = CapTable::<4>::new(1); 921 let handle = caps.insert(RES, ALL).unwrap(); 922 let mut devices = devices(); 923 let mut hw = Recorder::default(); 924 let mut other = CapTable::<4>::new(2); 925 assert_eq!( 926 revoke_device(1, handle, &mut [&mut other], &mut devices, &mut hw), 927 Err(DeviceError::Cap(CapError::DuplicateTable)) 928 ); 929 let mut twin = CapTable::<4>::new(1); 930 assert_eq!( 931 revoke_device( 932 1, 933 handle, 934 &mut [&mut caps, &mut twin], 935 &mut devices, 936 &mut hw 937 ), 938 Err(DeviceError::Cap(CapError::DuplicateTable)) 939 ); 940 assert!(hw.effects.is_empty()); 941 assert_eq!(caps.lookup(handle, Rights::MAP), Ok(RES)); 942 } 943 944 #[test] 945 fn register_rejects_clashes_and_live_devices() { 946 let mut devices = DeviceTable::<2>::new(); 947 devices.register(RES, Device::new(DEV, RID, SID)).unwrap(); 948 for (resource, id, rid, sid) in [ 949 (RES, DeviceId(9), 1, 99), 950 (7, DEV, 1, 99), 951 (7, DeviceId(9), RID, 99), 952 (7, DeviceId(9), 1, SID), 953 ] { 954 assert_eq!( 955 devices.register(resource, Device::new(id, rid, sid)), 956 Err(DeviceError::Duplicate) 957 ); 958 } 959 let mut bad = Device::new(DeviceId(9), 1, 99); 960 bad.window = Some(DmaWindow { iova: 1, pages: 1 }); 961 assert_eq!(devices.register(7, bad), Err(DeviceError::BadWindow)); 962 let mut live = Device::new(DeviceId(9), 1, 99); 963 live.state = DmaState::Active; 964 assert_eq!( 965 devices.register(7, live), 966 Err(DeviceError::WrongState(DmaState::Active)) 967 ); 968 devices 969 .register(7, Device::new(DeviceId(9), 1, 99)) 970 .unwrap(); 971 assert_eq!( 972 devices.register(8, Device::new(DeviceId(10), 2, 100)), 973 Err(DeviceError::Full) 974 ); 975 } 976 977 #[test] 978 fn window_validation() { 979 let mut devices = devices(); 980 for window in [ 981 DmaWindow { 982 iova: 0x1000, 983 pages: 0, 984 }, 985 DmaWindow { 986 iova: 0x1001, 987 pages: 1, 988 }, 989 DmaWindow { 990 iova: !0xfff, 991 pages: 2, 992 }, 993 ] { 994 assert_eq!(devices.set_window(RES, window), Err(DeviceError::BadWindow)); 995 } 996 assert_eq!(devices.get(RES).unwrap().window, Some(WINDOW)); 997 assert_eq!( 998 devices.set_window(0x999, WINDOW), 999 Err(DeviceError::NotADevice) 1000 ); 1001 } 1002 1003 #[test] 1004 fn revoke_forgets_window_so_next_holder_cannot_reuse_it() { 1005 let mut caps = CapTable::<4>::new(1); 1006 let first = caps.insert(RES, ALL).unwrap(); 1007 let mut devices = devices(); 1008 let mut hw = Recorder::default(); 1009 activate(&caps, first, &mut devices, &mut hw).unwrap(); 1010 revoke_device(1, first, &mut [&mut caps], &mut devices, &mut hw).unwrap(); 1011 assert_eq!(devices.get(RES).unwrap().window, None); 1012 assert_eq!(devices.get(RES).unwrap().authority, None); 1013 1014 let next = caps.insert(RES, Rights::MAP).unwrap(); 1015 hw.effects.clear(); 1016 assert_eq!( 1017 activate(&caps, next, &mut devices, &mut hw), 1018 Err(DeviceError::NoWindow) 1019 ); 1020 assert!(hw.effects.is_empty()); 1021 } 1022 1023 #[test] 1024 fn activation_records_its_authority() { 1025 let mut caps = CapTable::<4>::new(7); 1026 let handle = caps.insert(RES, Rights::MAP).unwrap(); 1027 let mut devices = devices(); 1028 let mut hw = Recorder::default(); 1029 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 1030 assert_eq!( 1031 devices.get(RES).unwrap().authority, 1032 Some(CapRef { table: 7, handle }) 1033 ); 1034 } 1035 1036 #[test] 1037 fn sweep_leaves_devices_with_live_authority_alone() { 1038 let mut caps = CapTable::<4>::new(1); 1039 let handle = caps.insert(RES, Rights::MAP).unwrap(); 1040 let mut devices = devices(); 1041 let mut hw = Recorder::default(); 1042 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 1043 hw.effects.clear(); 1044 1045 devices.sweep(&[&caps], &mut hw).unwrap(); 1046 1047 assert!(hw.effects.is_empty()); 1048 assert_eq!(state(&devices), DmaState::Active); 1049 } 1050 1051 #[test] 1052 fn sweep_tears_down_when_ancestor_revoked_through_plain_cap_path() { 1053 let mut owner = CapTable::<4>::new(1); 1054 let mut user = CapTable::<4>::new(2); 1055 let root = owner.insert(RES, ALL).unwrap(); 1056 let child = CapTable::derive_into(&mut owner, root, &mut user, Rights::MAP).unwrap(); 1057 let mut devices = devices(); 1058 let mut hw = Recorder::default(); 1059 activate(&user, child, &mut devices, &mut hw).unwrap(); 1060 hw.effects.clear(); 1061 1062 CapTable::<4>::revoke(1, root, &mut [&mut owner, &mut user]).unwrap(); 1063 devices.sweep(&[&owner, &user], &mut hw).unwrap(); 1064 1065 assert_eq!(hw.effects, teardown_effects()); 1066 assert_eq!(state(&devices), DmaState::Quiesced); 1067 assert!(!hw.bme && hw.aborted); 1068 } 1069 1070 #[test] 1071 fn sweep_tears_down_after_holder_removes_or_table_is_gone() { 1072 // The holder drops its handle, and the slot is reused by an unrelated 1073 // capability: the generation check keeps it from counting. 1074 let mut caps = CapTable::<1>::new(1); 1075 let handle = caps.insert(RES, Rights::MAP).unwrap(); 1076 let mut devices = devices(); 1077 let mut hw = Recorder::default(); 1078 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 1079 caps.remove(handle).unwrap(); 1080 let reused = caps.insert(RES, Rights::MAP).unwrap(); 1081 assert_eq!(reused.index, handle.index); 1082 hw.effects.clear(); 1083 devices.sweep(&[&caps], &mut hw).unwrap(); 1084 assert_eq!(hw.effects, teardown_effects()); 1085 assert_eq!(state(&devices), DmaState::Quiesced); 1086 1087 // The holder's whole table is gone. 1088 devices.set_window(RES, WINDOW).unwrap(); 1089 activate(&caps, reused, &mut devices, &mut hw).unwrap(); 1090 hw.effects.clear(); 1091 devices.sweep::<1, _>(&[], &mut hw).unwrap(); 1092 assert_eq!(hw.effects, teardown_effects()); 1093 assert_eq!(state(&devices), DmaState::Quiesced); 1094 } 1095 1096 #[test] 1097 fn sweep_retries_a_failed_teardown() { 1098 let mut caps = CapTable::<4>::new(1); 1099 let handle = caps.insert(RES, ALL).unwrap(); 1100 let mut devices = devices(); 1101 let mut hw = Recorder::failing(HwStep::AbortStream); 1102 activate(&caps, handle, &mut devices, &mut hw).unwrap(); 1103 assert!(revoke_device(1, handle, &mut [&mut caps], &mut devices, &mut hw).is_err()); 1104 assert_eq!(state(&devices), DmaState::Revoking); 1105 assert!(!hw.aborted); 1106 1107 hw.fail = None; 1108 hw.effects.clear(); 1109 devices.sweep(&[&caps], &mut hw).unwrap(); 1110 assert_eq!(hw.effects, teardown_effects()); 1111 assert!(hw.aborted); 1112 assert_eq!(state(&devices), DmaState::Quiesced); 1113 } 1114 1115 #[test] 1116 fn state_discriminants_are_stable() { 1117 assert_eq!(DmaState::Quiesced as u8, 0); 1118 assert_eq!(DmaState::TranslationInstalled as u8, 1); 1119 assert_eq!(DmaState::Active as u8, 2); 1120 assert_eq!(DmaState::Revoking as u8, 3); 1121 } 1122 }