Skip to main content

strat9_kernel/hardware/
iommu.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! IOMMU domain and IOVA management.
24//!
25//! This module is the architecture-neutral bookkeeping layer between a PCI
26//! function and the DMA allocator:
27//!
28//! * a [`Domain`] is bound to one [`Sbdf`] and owns a sparse IOVA space;
29//! * mappings are kept in a `BTreeMap` keyed by IOVA start, so `map`, `unmap`
30//!   and `translate` are O(log n) and overlap checks never scan the whole
31//!   table;
32//! * domains are allocated from a 16-bit bitmap (the VT-d domain-id width) and
33//!   handed out as `Arc<Domain>` with an explicit logical reference count so
34//!   hot-unplug can revoke DMA in one place;
35//! * hardware programming lives in `crate::arch::iommu` behind a [`Backend`].
36//!
37//! Ordering invariant: the global `DOMAINS` registry lock is always taken
38//! before the `DOMAIN_BITMAP` lock.  A [`Domain`] state lock is never taken
39//! while holding the registry lock.
40
41use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
42use core::{
43    fmt,
44    ops::{BitAnd, BitOr},
45    sync::atomic::{AtomicBool, AtomicU64, Ordering},
46};
47
48use crate::sync::{FixedQueue, SpinLock};
49
50/// First address handed out to drivers in a domain IOVA space.
51///
52/// The low 4 GiB are left alone so that a 32-bit-only device can still be
53/// given a valid address without extra bounce buffering.
54pub const IOVA_BASE: u64 = 0x1_0000_0000;
55
56/// Page granularity of every IOMMU mapping.
57pub const IOMMU_PAGE_SIZE: u64 = 4096;
58
59/// Large-page granularities supported by the second-level page tables.
60pub const IOMMU_SUPERPAGE_2M: u64 = 2 * 1024 * 1024;
61/// 1 GiB leaf entries.
62pub const IOMMU_SUPERPAGE_1G: u64 = 1024 * 1024 * 1024;
63
64/// Granularity of one mapping.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MappingKind {
67    /// 4 KiB leaf.
68    Page4K,
69    /// 2 MiB leaf (second-level PS bit at level 2).
70    Page2M,
71    /// 1 GiB leaf (second-level PS bit at level 3).
72    Page1G,
73}
74
75impl MappingKind {
76    /// Size represented by one leaf entry.
77    pub const fn size(self) -> u64 {
78        match self {
79            MappingKind::Page4K => IOMMU_PAGE_SIZE,
80            MappingKind::Page2M => IOMMU_SUPERPAGE_2M,
81            MappingKind::Page1G => IOMMU_SUPERPAGE_1G,
82        }
83    }
84
85    /// Smallest kind that can cover `len` with the given base alignment.
86    ///
87    /// Returns `None` when `len` is zero or not a multiple of 4 KiB.
88    pub fn best_for(iova: u64, len: u64) -> Option<Self> {
89        if len == 0 || len & (IOMMU_PAGE_SIZE - 1) != 0 {
90            return None;
91        }
92        if len >= IOMMU_SUPERPAGE_1G
93            && iova & (IOMMU_SUPERPAGE_1G - 1) == 0
94            && len & (IOMMU_SUPERPAGE_1G - 1) == 0
95        {
96            Some(MappingKind::Page1G)
97        } else if len >= IOMMU_SUPERPAGE_2M
98            && iova & (IOMMU_SUPERPAGE_2M - 1) == 0
99            && len & (IOMMU_SUPERPAGE_2M - 1) == 0
100        {
101            Some(MappingKind::Page2M)
102        } else {
103            Some(MappingKind::Page4K)
104        }
105    }
106}
107
108/// Highest domain id the VT-d context entry can encode.
109pub const MAX_DOMAIN_ID: u16 = u16::MAX;
110
111const BITMAP_WORDS: usize = (MAX_DOMAIN_ID as usize + 1) / 64;
112
113// =============================================================================
114// Sbdf : segment / bus / device / function
115// =============================================================================
116
117/// A PCI function identity, including its PCI segment group.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
119pub struct Sbdf {
120    pub segment: u16,
121    pub bus: u8,
122    pub device: u8,
123    pub function: u8,
124}
125
126impl Sbdf {
127    /// Build a new segment-qualified PCI identity.
128    pub const fn new(segment: u16, bus: u8, device: u8, function: u8) -> Self {
129        Self {
130            segment,
131            bus,
132            device,
133            function,
134        }
135    }
136
137    /// Identity of a device seen on segment 0 (the common case).
138    pub const fn from_pci(bus: u8, device: u8, function: u8) -> Self {
139        Self::new(0, bus, device, function)
140    }
141
142    /// Packed 32-bit representation: `segment:16 | bus:8 | dev:5 | fn:3`.
143    pub const fn to_u32(self) -> u32 {
144        ((self.segment as u32) << 16)
145            | ((self.bus as u32) << 8)
146            | ((self.device as u32 & 0x1f) << 3)
147            | (self.function as u32 & 0x7)
148    }
149
150    /// Unpack a value previously produced by [`Sbdf::to_u32`].
151    pub const fn from_u32(raw: u32) -> Self {
152        Self {
153            segment: (raw >> 16) as u16,
154            bus: (raw >> 8) as u8,
155            device: ((raw >> 3) & 0x1f) as u8,
156            function: (raw & 0x7) as u8,
157        }
158    }
159}
160
161impl fmt::Display for Sbdf {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        write!(
164            f,
165            "{:04x}:{:02x}:{:02x}.{:x}",
166            self.segment, self.bus, self.device, self.function
167        )
168    }
169}
170
171// =============================================================================
172// DmaProt : access rights of a mapping
173// =============================================================================
174
175/// DMA access rights for a mapping.
176///
177/// For a device:
178/// * `READ` means the device may read memory (the DMA buffer is a write for
179///   the CPU);
180/// * `WRITE` means the device may write memory.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
182pub struct DmaProt(u8);
183
184impl DmaProt {
185    /// No access.
186    pub const NONE: Self = Self(0);
187    /// Device may read memory.
188    pub const READ: Self = Self(0b01);
189    /// Device may write memory.
190    pub const WRITE: Self = Self(0b10);
191    /// Device may read and write memory.
192    pub const READ_WRITE: Self = Self(0b11);
193
194    /// Raw bits, as used by the syscall ABI.
195    pub const fn bits(self) -> u8 {
196        self.0
197    }
198
199    /// Rebuild rights from raw ABI bits, rejecting unknown bits.
200    pub const fn from_bits(bits: u8) -> Option<Self> {
201        if bits & !0b11 != 0 {
202            None
203        } else {
204            Some(Self(bits))
205        }
206    }
207
208    /// True when every right in `other` is present.
209    pub const fn contains(self, other: Self) -> bool {
210        self.0 & other.0 == other.0
211    }
212
213    /// True when no access is granted.
214    pub const fn is_empty(self) -> bool {
215        self.0 == 0
216    }
217
218    /// Device-readable mapping.
219    pub const fn readable(self) -> bool {
220        self.0 & Self::READ.0 != 0
221    }
222
223    /// Device-writable mapping.
224    pub const fn writable(self) -> bool {
225        self.0 & Self::WRITE.0 != 0
226    }
227}
228
229impl BitOr for DmaProt {
230    type Output = Self;
231
232    fn bitor(self, rhs: Self) -> Self {
233        Self(self.0 | rhs.0)
234    }
235}
236
237impl BitAnd for DmaProt {
238    type Output = Self;
239
240    fn bitand(self, rhs: Self) -> Self {
241        Self(self.0 & rhs.0)
242    }
243}
244
245// =============================================================================
246// Errors
247// =============================================================================
248
249/// Errors returned by the IOMMU bookkeeping layer.
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum IommuError {
252    /// No IOMMU is described by the firmware.
253    NotPresent,
254    /// A backend exists but has not been validated for activation.
255    BackendNotReady,
256    /// All 16-bit domain ids are in use.
257    NoDomainSpace,
258    /// The domain id does not belong to a live delegation.
259    UnknownDomain,
260    /// Zero-length, unaligned or overflowing range.
261    InvalidRange,
262    /// The range overlaps an existing mapping.
263    Overlap,
264    /// The IOVA range is not fully mapped.
265    NotMapped,
266    /// The buffer already belongs to a domain.
267    AlreadyMapped,
268    /// The physical range is reserved by the firmware (RMRR/IVMD).
269    Reserved,
270    /// The domain is quiesced and refuses new mappings.
271    Quiesced,
272    /// The backend does not implement the requested feature.
273    Unsupported,
274    /// The hardware backend refused the operation.
275    Hardware,
276}
277
278impl IommuError {
279    /// Stable short description, used in logs.
280    pub const fn as_str(self) -> &'static str {
281        match self {
282            IommuError::NotPresent => "no IOMMU firmware present",
283            IommuError::BackendNotReady => "IOMMU backend not ready",
284            IommuError::NoDomainSpace => "no free IOMMU domain id",
285            IommuError::UnknownDomain => "unknown IOMMU domain",
286            IommuError::InvalidRange => "invalid IOVA range",
287            IommuError::Overlap => "overlapping IOVA range",
288            IommuError::NotMapped => "IOVA range not mapped",
289            IommuError::AlreadyMapped => "buffer already mapped to a domain",
290            IommuError::Reserved => "physical range is firmware-reserved",
291            IommuError::Quiesced => "IOMMU domain is quiesced",
292            IommuError::Unsupported => "operation not supported by the IOMMU backend",
293            IommuError::Hardware => "IOMMU hardware refused the operation",
294        }
295    }
296}
297
298/// Opaque domain identifier (VT-d uses 16 bits).
299#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
300pub struct DomainId(pub u16);
301
302impl DomainId {
303    /// Raw numeric identifier.
304    pub const fn raw(self) -> u16 {
305        self.0
306    }
307
308    /// Rebuild an id from the raw ABI value.
309    pub const fn from_raw(raw: u16) -> Self {
310        Self(raw)
311    }
312}
313
314// =============================================================================
315// Mappings
316// =============================================================================
317
318/// One IOVA -> physical mapping.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub struct Mapping {
321    pub iova: u64,
322    pub phys: u64,
323    pub len: u64,
324    pub prot: DmaProt,
325    pub kind: MappingKind,
326}
327
328impl Mapping {
329    /// Exclusive end of the IOVA range.
330    pub const fn end(&self) -> u64 {
331        self.iova.saturating_add(self.len)
332    }
333
334    /// True when `iova` falls inside this mapping.
335    pub const fn contains(&self, iova: u64) -> bool {
336        iova >= self.iova && iova < self.end()
337    }
338}
339
340/// Result of a software translation.
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
342pub struct Translation {
343    pub phys: u64,
344    pub prot: DmaProt,
345    /// Bytes between `iova` and the end of the mapping.
346    pub remaining: u64,
347}
348
349// =============================================================================
350// Faults
351// =============================================================================
352
353/// What the kernel should do when a device faults.
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum FaultPolicy {
356    /// Queue the record and keep going.
357    Log,
358    /// Queue the record and signal the owning strate.
359    Notify,
360    /// Destroy every domain owned by the faulting silo.
361    KillOwner,
362    /// Stop the kernel (critical devices only).
363    Panic,
364}
365
366impl FaultPolicy {
367    /// Decode the ABI representation (0=log, 1=notify, 2=kill, 3=panic).
368    pub const fn from_raw(raw: u8) -> Self {
369        match raw {
370            1 => FaultPolicy::Notify,
371            2 => FaultPolicy::KillOwner,
372            3 => FaultPolicy::Panic,
373            _ => FaultPolicy::Log,
374        }
375    }
376
377    /// Stable numeric representation.
378    pub const fn as_raw(self) -> u8 {
379        match self {
380            FaultPolicy::Log => 0,
381            FaultPolicy::Notify => 1,
382            FaultPolicy::KillOwner => 2,
383            FaultPolicy::Panic => 3,
384        }
385    }
386
387    /// Action actually taken for this policy.
388    pub const fn action(self) -> FaultAction {
389        match self {
390            FaultPolicy::Log => FaultAction::Logged,
391            FaultPolicy::Notify => FaultAction::Notified,
392            FaultPolicy::KillOwner => FaultAction::OwnerRevoked,
393            FaultPolicy::Panic => FaultAction::Panicked,
394        }
395    }
396}
397
398/// Outcome attached to a queued fault record.
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub enum FaultAction {
401    Logged,
402    Notified,
403    OwnerRevoked,
404    Panicked,
405}
406
407impl FaultAction {
408    /// Stable numeric representation for the ABI.
409    pub const fn as_raw(self) -> u8 {
410        match self {
411            FaultAction::Logged => 0,
412            FaultAction::Notified => 1,
413            FaultAction::OwnerRevoked => 2,
414            FaultAction::Panicked => 3,
415        }
416    }
417}
418
419/// Reason reported by the hardware (or by a debug injection).
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub enum FaultReason {
422    /// The device attempted a read with no valid translation.
423    Read,
424    /// The device attempted a write with no valid translation.
425    Write,
426    /// The translation existed but the access rights denied it.
427    Permission,
428    /// The IOVA was outside the domain's declared range.
429    OutOfRange,
430}
431
432impl FaultReason {
433    /// Stable numeric representation for the ABI.
434    pub const fn as_raw(self) -> u8 {
435        match self {
436            FaultReason::Read => 0,
437            FaultReason::Write => 1,
438            FaultReason::Permission => 2,
439            FaultReason::OutOfRange => 3,
440        }
441    }
442}
443
444/// One bounded fault record.
445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446pub struct FaultRecord {
447    pub seq: u64,
448    pub timestamp_ns: u64,
449    pub domain: DomainId,
450    pub sbdf: Sbdf,
451    pub iova: u64,
452    pub reason: FaultReason,
453    pub access: DmaProt,
454    pub owner: Option<u32>,
455    pub action: FaultAction,
456}
457
458/// Maximum number of fault records kept globally.
459pub const FAULT_QUEUE_CAPACITY: usize = 256;
460/// Per-domain burst before records are dropped (rate limit).
461pub const FAULT_BURST: u32 = 32;
462
463static FAULTS: SpinLock<FixedQueue<FaultRecord, FAULT_QUEUE_CAPACITY>> =
464    SpinLock::new(FixedQueue::new());
465static FAULT_SEQ: AtomicU64 = AtomicU64::new(1);
466static FAULT_DROPPED: AtomicU64 = AtomicU64::new(0);
467
468// =============================================================================
469// Reserved regions (RMRR / IVMD)
470// =============================================================================
471
472/// A physical range reserved for a device by the firmware.
473///
474/// The IOMMU must identity-map it for the listed devices, and the DMA
475/// allocator must never hand those pages to another domain.
476#[derive(Debug, Clone, PartialEq, Eq)]
477pub struct ReservedRegion {
478    pub segment: u16,
479    /// Inclusive start.
480    pub base: u64,
481    /// Inclusive end.
482    pub limit: u64,
483    /// Explicit endpoint list; empty means `all_bus_from` applies.
484    pub devices: Vec<Sbdf>,
485    /// When set, every bus `>=` this value in `segment` is covered.
486    pub all_bus_from: Option<u8>,
487    /// True when the region was identity-mapped during discovery.
488    pub identity_mapped: bool,
489}
490
491impl ReservedRegion {
492    /// True when `phys` falls inside the reserved range.
493    pub const fn contains(&self, phys: u64) -> bool {
494        phys >= self.base && phys <= self.limit
495    }
496
497    /// True when the region overlaps `[start, start + len)`.
498    pub const fn overlaps(&self, start: u64, len: u64) -> bool {
499        match start.checked_add(len) {
500            Some(end) => start <= self.limit && end > self.base,
501            None => true,
502        }
503    }
504
505    /// True when this region applies to `sbdf`.
506    pub fn covers(&self, sbdf: Sbdf) -> bool {
507        if self.segment != sbdf.segment {
508            return false;
509        }
510        if self.devices.iter().any(|d| *d == sbdf) {
511            return true;
512        }
513        self.all_bus_from
514            .map(|bus| sbdf.bus >= bus)
515            .unwrap_or(false)
516    }
517}
518
519static RESERVED: SpinLock<Vec<ReservedRegion>> = SpinLock::new(Vec::new());
520static PANIC_ON_INVALID_RMRR: AtomicBool = AtomicBool::new(false);
521
522/// Replace the reserved-region set with the firmware description.
523pub fn set_reserved_regions(regions: Vec<ReservedRegion>, panic_on_invalid: bool) {
524    PANIC_ON_INVALID_RMRR.store(panic_on_invalid, Ordering::Release);
525    for region in &regions {
526        if region.base > region.limit {
527            if panic_on_invalid {
528                panic!(
529                    "IOMMU: invalid RMRR {}..{} for segment {}",
530                    region.base, region.limit, region.segment
531                );
532            }
533            log::warn!(
534                "[IOMMU] ignoring inverted RMRR {:#x}..{:#x} seg={}",
535                region.base,
536                region.limit,
537                region.segment
538            );
539        }
540    }
541    *RESERVED.lock() = regions;
542}
543
544/// Snapshot of the reserved regions, for diagnostics and `/srv/iommu`.
545pub fn reserved_regions() -> Vec<ReservedRegion> {
546    RESERVED.lock().clone()
547}
548
549/// Find the reserved region, if any, covering `[start, start + len)` for `sbdf`.
550pub fn reserved_conflict(sbdf: Sbdf, start: u64, len: u64) -> Option<ReservedRegion> {
551    RESERVED
552        .lock()
553        .iter()
554        .find(|r| r.covers(sbdf) && r.overlaps(start, len))
555        .cloned()
556}
557
558// =============================================================================
559// Statistics
560// =============================================================================
561
562/// Per-domain counters exported through `/srv/iommu`.
563#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
564pub struct DomainStats {
565    pub maps: u64,
566    pub unmaps: u64,
567    pub bytes_mapped: u64,
568    pub faults: u64,
569    pub dropped_faults: u64,
570}
571
572/// Global counters.
573#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
574pub struct IommuStats {
575    pub domains_created: u64,
576    pub domains_destroyed: u64,
577    pub maps: u64,
578    pub unmaps: u64,
579    pub faults: u64,
580    pub dropped_faults: u64,
581    pub activations: u64,
582}
583
584static STATS: SpinLock<IommuStats> = SpinLock::new(IommuStats {
585    domains_created: 0,
586    domains_destroyed: 0,
587    maps: 0,
588    unmaps: 0,
589    faults: 0,
590    dropped_faults: 0,
591    activations: 0,
592});
593
594/// Snapshot of the global counters.
595pub fn stats() -> IommuStats {
596    *STATS.lock()
597}
598
599#[derive(Debug)]
600struct DomainState {
601    refs: usize,
602    generation: u64,
603    quiesced: bool,
604    owner: Option<u32>,
605    policy: FaultPolicy,
606    fault_budget: u32,
607    stats: DomainStats,
608    mappings: BTreeMap<u64, Mapping>,
609}
610
611impl DomainState {
612    fn new(owner: Option<u32>, policy: FaultPolicy) -> Self {
613        Self {
614            refs: 1,
615            generation: 0,
616            quiesced: false,
617            owner,
618            policy,
619            fault_budget: FAULT_BURST,
620            stats: DomainStats::default(),
621            mappings: BTreeMap::new(),
622        }
623    }
624
625    /// Find the first hole at or after [`IOVA_BASE`] that fits `len`.
626    fn alloc_iova(&self, len: u64) -> Result<u64, IommuError> {
627        let mut candidate = IOVA_BASE;
628        for mapping in self.mappings.values() {
629            if mapping.end() <= candidate {
630                continue;
631            }
632            let fits = candidate
633                .checked_add(len)
634                .map(|end| end <= mapping.iova)
635                .unwrap_or(false);
636            if fits {
637                return Ok(candidate);
638            }
639            candidate = candidate.max(mapping.end());
640        }
641        candidate.checked_add(len).ok_or(IommuError::InvalidRange)?;
642        Ok(candidate)
643    }
644}
645
646// =============================================================================
647// Domain
648// =============================================================================
649
650/// A DMA domain attached to one PCI function.
651pub struct Domain {
652    id: DomainId,
653    sbdf: Sbdf,
654    state: SpinLock<DomainState>,
655}
656
657impl fmt::Debug for Domain {
658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659        let state = self.state.lock();
660        f.debug_struct("Domain")
661            .field("id", &self.id)
662            .field("sbdf", &self.sbdf)
663            .field("refs", &state.refs)
664            .field("generation", &state.generation)
665            .field("mappings", &state.mappings.len())
666            .finish()
667    }
668}
669
670impl Domain {
671    /// Constructor for tests and kernel-internal domains without an owner.
672    #[allow(dead_code)]
673    fn new(id: DomainId, sbdf: Sbdf) -> Self {
674        Self::new_owned(id, sbdf, None, FaultPolicy::Log)
675    }
676
677    fn new_owned(id: DomainId, sbdf: Sbdf, owner: Option<u32>, policy: FaultPolicy) -> Self {
678        Self {
679            id,
680            sbdf,
681            state: SpinLock::new(DomainState::new(owner, policy)),
682        }
683    }
684
685    /// Domain identifier.
686    pub const fn id(&self) -> DomainId {
687        self.id
688    }
689
690    /// PCI function this domain is bound to.
691    pub const fn sbdf(&self) -> Sbdf {
692        self.sbdf
693    }
694
695    /// Owning silo SID, when the domain was created for a userspace driver.
696    pub fn owner(&self) -> Option<u32> {
697        self.state.lock().owner
698    }
699
700    /// Fault policy attached to this domain.
701    pub fn fault_policy(&self) -> FaultPolicy {
702        self.state.lock().policy
703    }
704
705    /// Change the fault policy.
706    pub fn set_fault_policy(&self, policy: FaultPolicy) {
707        self.state.lock().policy = policy;
708    }
709
710    /// True when new mappings are refused.
711    pub fn is_quiesced(&self) -> bool {
712        self.state.lock().quiesced
713    }
714
715    /// Stop accepting new mappings (hot-unplug prep).
716    pub fn quiesce(&self) {
717        let mut state = self.state.lock();
718        state.quiesced = true;
719        state.generation = state.generation.wrapping_add(1);
720    }
721
722    /// Accept new mappings again.
723    pub fn resume(&self) {
724        let mut state = self.state.lock();
725        state.quiesced = false;
726        state.generation = state.generation.wrapping_add(1);
727    }
728
729    /// Per-domain statistics.
730    pub fn stats(&self) -> DomainStats {
731        self.state.lock().stats
732    }
733
734    /// Number of bytes currently mapped.
735    pub fn mapped_bytes(&self) -> u64 {
736        self.state
737            .lock()
738            .mappings
739            .values()
740            .map(|mapping| mapping.len)
741            .sum()
742    }
743
744    /// Logical reference count (one per outstanding delegation).
745    pub fn refs(&self) -> usize {
746        self.state.lock().refs
747    }
748
749    /// Take one more logical reference.
750    pub fn acquire(&self) -> usize {
751        let mut state = self.state.lock();
752        state.refs = state.refs.saturating_add(1);
753        state.refs
754    }
755
756    /// Drop one logical reference, returning the new count.
757    pub fn release(&self) -> usize {
758        let mut state = self.state.lock();
759        state.refs = state.refs.saturating_sub(1);
760        state.refs
761    }
762
763    /// Monotonic generation, bumped on every map/unmap.
764    pub fn generation(&self) -> u64 {
765        self.state.lock().generation
766    }
767
768    /// Number of live mappings.
769    pub fn mapping_count(&self) -> usize {
770        self.state.lock().mappings.len()
771    }
772
773    /// Snapshot of the mappings, sorted by IOVA.
774    pub fn mappings(&self) -> Vec<Mapping> {
775        self.state.lock().mappings.values().copied().collect()
776    }
777
778    /// True when the domain has at least one mapping.
779    pub fn is_active(&self) -> bool {
780        !self.state.lock().mappings.is_empty()
781    }
782
783    /// Map `len` bytes of physical memory at `iova`.
784    ///
785    /// The range must be page-aligned, non-empty and must not overlap an
786    /// existing mapping.  The overlap check is O(log n).
787    pub fn map(&self, iova: u64, phys: u64, len: u64, prot: DmaProt) -> Result<(), IommuError> {
788        let kind = MappingKind::best_for(iova, len)
789            .filter(|kind| phys & (kind.size() - 1) == 0)
790            .unwrap_or(MappingKind::Page4K);
791        self.map_kind(iova, phys, len, prot, kind)
792    }
793
794    /// Map `len` bytes using an explicit page granularity.
795    pub fn map_kind(
796        &self,
797        iova: u64,
798        phys: u64,
799        len: u64,
800        prot: DmaProt,
801        kind: MappingKind,
802    ) -> Result<(), IommuError> {
803        self.map_impl(iova, phys, len, prot, kind, false)
804    }
805
806    /// Identity-map a firmware-reserved range (RMRR/IVMD) into this domain.
807    ///
808    /// This bypasses the reserved-region conflict check: it is the one path
809    /// allowed to touch those pages, and only for their owning device.
810    pub fn map_reserved(
811        &self,
812        iova: u64,
813        phys: u64,
814        len: u64,
815        prot: DmaProt,
816    ) -> Result<(), IommuError> {
817        let kind = MappingKind::best_for(iova, len)
818            .filter(|kind| phys & (kind.size() - 1) == 0)
819            .unwrap_or(MappingKind::Page4K);
820        self.map_impl(iova, phys, len, prot, kind, true)
821    }
822
823    fn map_impl(
824        &self,
825        iova: u64,
826        phys: u64,
827        len: u64,
828        prot: DmaProt,
829        kind: MappingKind,
830        allow_reserved: bool,
831    ) -> Result<(), IommuError> {
832        validate_range(iova, len)?;
833        let leaf = kind.size();
834        if iova & (leaf - 1) != 0 || len & (leaf - 1) != 0 {
835            return Err(IommuError::InvalidRange);
836        }
837        if phys & (IOMMU_PAGE_SIZE - 1) != 0 {
838            return Err(IommuError::InvalidRange);
839        }
840        phys.checked_add(len).ok_or(IommuError::InvalidRange)?;
841
842        // Firmware-reserved regions (RMRR/IVMD) must not be handed to a
843        // domain unless the device is their intended owner.
844        if !allow_reserved && reserved_conflict(self.sbdf, phys, len).is_some() {
845            return Err(IommuError::Reserved);
846        }
847
848        let mut state = self.state.lock();
849        if state.quiesced {
850            return Err(IommuError::Quiesced);
851        }
852
853        // Previous mapping (largest start <= iova) may straddle `iova`.
854        if let Some((_, prev)) = state.mappings.range(..=iova).next_back() {
855            if prev.end() > iova {
856                return Err(IommuError::Overlap);
857            }
858        }
859        // Next mapping starting inside [iova, iova + len).
860        if let Some((&next_start, _)) = state.mappings.range(iova..iova + len).next() {
861            debug_assert!(next_start >= iova);
862            return Err(IommuError::Overlap);
863        }
864
865        // Program the backend first: a hardware refusal must leave the
866        // software table unchanged.
867        crate::arch::iommu::map_domain(self.id, self.sbdf, iova, phys, len, prot, kind)
868            .map_err(backend_error)?;
869
870        state.mappings.insert(
871            iova,
872            Mapping {
873                iova,
874                phys,
875                len,
876                prot,
877                kind,
878            },
879        );
880        state.generation = state.generation.wrapping_add(1);
881        state.stats.maps = state.stats.maps.wrapping_add(1);
882        state.stats.bytes_mapped = state.stats.bytes_mapped.wrapping_add(len);
883        drop(state);
884        let mut global = STATS.lock();
885        global.maps = global.maps.wrapping_add(1);
886        Ok(())
887    }
888
889    /// Allocate a free IOVA range and map `phys` into it.
890    pub fn map_auto(&self, phys: u64, len: u64, prot: DmaProt) -> Result<u64, IommuError> {
891        validate_range(0, len)?;
892        let iova = {
893            let state = self.state.lock();
894            state.alloc_iova(len)?
895        };
896        self.map(iova, phys, len, prot)?;
897        Ok(iova)
898    }
899
900    /// Remove every mapping fully contained in `[iova, iova + len)`.
901    ///
902    /// Returns how many mappings were removed.  A partial overlap is an error:
903    /// callers must unmap on the granularity they mapped.
904    pub fn unmap(&self, iova: u64, len: u64) -> Result<usize, IommuError> {
905        validate_range(iova, len)?;
906        let end = iova + len;
907        let mut state = self.state.lock();
908
909        let mut keys: Vec<u64> = Vec::new();
910        if let Some((&start, prev)) = state.mappings.range(..end).next_back() {
911            if prev.end() > iova {
912                keys.push(start);
913            }
914        }
915        for &start in state.mappings.range(iova..end).map(|(k, _)| k) {
916            if !keys.contains(&start) {
917                keys.push(start);
918            }
919        }
920        if keys.is_empty() {
921            return Err(IommuError::NotMapped);
922        }
923        for key in &keys {
924            let Some(mapping) = state.mappings.get(key) else {
925                continue;
926            };
927            if mapping.iova < iova || mapping.end() > end {
928                return Err(IommuError::InvalidRange);
929            }
930        }
931
932        // Tear down hardware shadows before forgetting the mappings.
933        for key in &keys {
934            if let Some(mapping) = state.mappings.get(key).copied() {
935                crate::arch::iommu::unmap_domain(
936                    self.id,
937                    self.sbdf,
938                    mapping.iova,
939                    mapping.len,
940                    mapping.kind,
941                )
942                .map_err(backend_error)?;
943            }
944        }
945
946        let mut removed_bytes = 0u64;
947        for key in &keys {
948            if let Some(mapping) = state.mappings.remove(key) {
949                removed_bytes = removed_bytes.wrapping_add(mapping.len);
950            }
951        }
952        state.generation = state.generation.wrapping_add(1);
953        state.stats.unmaps = state.stats.unmaps.wrapping_add(keys.len() as u64);
954        state.stats.bytes_mapped = state.stats.bytes_mapped.saturating_sub(removed_bytes);
955        let removed = keys.len();
956        drop(state);
957        let mut global = STATS.lock();
958        global.unmaps = global.unmaps.wrapping_add(removed as u64);
959        Ok(removed)
960    }
961
962    /// Remove exactly one mapping that starts at `iova`.
963    pub fn unmap_exact(&self, iova: u64) -> Result<Mapping, IommuError> {
964        let mut state = self.state.lock();
965        let mapping = *state.mappings.get(&iova).ok_or(IommuError::NotMapped)?;
966        crate::arch::iommu::unmap_domain(
967            self.id,
968            self.sbdf,
969            mapping.iova,
970            mapping.len,
971            mapping.kind,
972        )
973        .map_err(backend_error)?;
974        state.mappings.remove(&iova);
975        state.generation = state.generation.wrapping_add(1);
976        state.stats.unmaps = state.stats.unmaps.wrapping_add(1);
977        state.stats.bytes_mapped = state.stats.bytes_mapped.saturating_sub(mapping.len);
978        Ok(mapping)
979    }
980
981    /// Translate an IOVA with the software table.
982    ///
983    /// This is the source of truth while hardware translation is disabled, and
984    /// a verification aid afterwards.
985    pub fn translate(&self, iova: u64) -> Option<Translation> {
986        let state = self.state.lock();
987        let (_, mapping) = state.mappings.range(..=iova).next_back()?;
988        if !mapping.contains(iova) {
989            return None;
990        }
991        Some(Translation {
992            phys: mapping.phys + (iova - mapping.iova),
993            prot: mapping.prot,
994            remaining: mapping.end() - iova,
995        })
996    }
997
998    /// Remove every mapping, keeping the domain alive.
999    pub fn reset(&self) {
1000        let mappings: Vec<Mapping> = self.state.lock().mappings.values().copied().collect();
1001        for mapping in mappings {
1002            let _ = crate::arch::iommu::unmap_domain(
1003                self.id,
1004                self.sbdf,
1005                mapping.iova,
1006                mapping.len,
1007                mapping.kind,
1008            );
1009        }
1010        let mut state = self.state.lock();
1011        if !state.mappings.is_empty() {
1012            state.mappings.clear();
1013            state.stats.bytes_mapped = 0;
1014            state.generation = state.generation.wrapping_add(1);
1015        }
1016    }
1017
1018    /// Record a fault for this domain and apply its policy.
1019    ///
1020    /// Returns the queued record (with the action that was taken).  The
1021    /// per-domain burst budget bounds the work done by a misbehaving device;
1022    /// excess records are counted and dropped.
1023    pub fn report_fault(
1024        &self,
1025        iova: u64,
1026        reason: FaultReason,
1027        access: DmaProt,
1028    ) -> Option<FaultRecord> {
1029        let (owner, action, seq) = {
1030            let mut state = self.state.lock();
1031            state.stats.faults = state.stats.faults.wrapping_add(1);
1032            let policy = state.policy;
1033            let action = policy.action();
1034            let seq = FAULT_SEQ.fetch_add(1, Ordering::Relaxed);
1035            if state.fault_budget == 0 {
1036                state.stats.dropped_faults = state.stats.dropped_faults.wrapping_add(1);
1037                drop(state);
1038                FAULT_DROPPED.fetch_add(1, Ordering::Relaxed);
1039                let mut global = STATS.lock();
1040                global.dropped_faults = global.dropped_faults.wrapping_add(1);
1041                drop(global);
1042                if policy == FaultPolicy::Panic {
1043                    panic!("IOMMU fault (rate-limited) domain={:?}", self.id);
1044                }
1045                return None;
1046            }
1047            state.fault_budget -= 1;
1048            (state.owner, action, seq)
1049        };
1050
1051        let record = FaultRecord {
1052            seq,
1053            timestamp_ns: crate::syscall::time::current_time_ns(),
1054            domain: self.id,
1055            sbdf: self.sbdf,
1056            iova,
1057            reason,
1058            access,
1059            owner,
1060            action,
1061        };
1062
1063        {
1064            let mut global = STATS.lock();
1065            global.faults = global.faults.wrapping_add(1);
1066        }
1067        if FAULTS.lock().push_back(record).is_err() {
1068            FAULT_DROPPED.fetch_add(1, Ordering::Relaxed);
1069            let mut global = STATS.lock();
1070            global.dropped_faults = global.dropped_faults.wrapping_add(1);
1071        }
1072
1073        match action {
1074            FaultAction::OwnerRevoked => {
1075                if let Some(sid) = owner {
1076                    revoke_owner(sid);
1077                }
1078            }
1079            FaultAction::Panicked => {
1080                panic!(
1081                    "IOMMU fault: sbdf={} iova={:#x} domain={:?}",
1082                    self.sbdf, iova, self.id
1083                );
1084            }
1085            _ => {}
1086        }
1087        Some(record)
1088    }
1089}
1090
1091fn validate_range(iova: u64, len: u64) -> Result<(), IommuError> {
1092    if len == 0 || iova & (IOMMU_PAGE_SIZE - 1) != 0 || len & (IOMMU_PAGE_SIZE - 1) != 0 {
1093        return Err(IommuError::InvalidRange);
1094    }
1095    iova.checked_add(len).ok_or(IommuError::InvalidRange)?;
1096    Ok(())
1097}
1098
1099fn backend_error(error: crate::arch::iommu::IommuError) -> IommuError {
1100    use crate::arch::iommu::IommuError as Backend;
1101    match error {
1102        Backend::NotPresent => IommuError::NotPresent,
1103        Backend::NotReady => IommuError::BackendNotReady,
1104        Backend::Unsupported => IommuError::Unsupported,
1105        Backend::Hardware => IommuError::Hardware,
1106        Backend::InvalidDomain => IommuError::UnknownDomain,
1107    }
1108}
1109
1110// =============================================================================
1111// Global registry
1112// =============================================================================
1113
1114static DOMAINS: SpinLock<BTreeMap<DomainId, Arc<Domain>>> = SpinLock::new(BTreeMap::new());
1115static DOMAIN_BITMAP: SpinLock<[u64; BITMAP_WORDS]> = SpinLock::new([0u64; BITMAP_WORDS]);
1116static HARDWARE_ENABLED: AtomicBool = AtomicBool::new(false);
1117
1118fn allocate_domain_id() -> Result<DomainId, IommuError> {
1119    let mut bitmap = DOMAIN_BITMAP.lock();
1120    // Id 0 is reserved: VTD uses it for the "no translation" context.
1121    for word in 0..BITMAP_WORDS {
1122        let mut free = !bitmap[word];
1123        if word == 0 {
1124            free &= !1u64; // keep bit 0 clear
1125        }
1126        if free == 0 {
1127            continue;
1128        }
1129        let bit = free.trailing_zeros() as usize;
1130        bitmap[word] |= 1u64 << bit;
1131        return Ok(DomainId((word * 64 + bit) as u16));
1132    }
1133    Err(IommuError::NoDomainSpace)
1134}
1135
1136fn free_domain_id(id: DomainId) {
1137    let index = id.0 as usize;
1138    if index == 0 || index > MAX_DOMAIN_ID as usize {
1139        return;
1140    }
1141    let mut bitmap = DOMAIN_BITMAP.lock();
1142    bitmap[index / 64] &= !(1u64 << (index % 64));
1143}
1144
1145/// True when the firmware advertised an IOMMU (DMAR or IVRS).
1146pub fn firmware_present() -> bool {
1147    crate::acpi::get_dmar().is_some() || crate::acpi::get_ivrs().is_some()
1148}
1149
1150/// True when translation is actually programmed.
1151pub fn enabled() -> bool {
1152    HARDWARE_ENABLED.load(Ordering::Acquire)
1153}
1154
1155/// Return the domain bound to `sbdf`, creating it on first use.
1156///
1157/// Each successful call takes one logical reference; release it with
1158/// [`release_domain`] once the caller no longer needs the domain.
1159pub fn domain_for(sbdf: Sbdf) -> Result<Arc<Domain>, IommuError> {
1160    domain_for_owned(sbdf, None, FaultPolicy::Log)
1161}
1162
1163/// Same as [`domain_for`], but records the owning silo and its fault policy.
1164///
1165/// When the domain is created, firmware-reserved ranges (RMRR/IVMD) that
1166/// apply to `sbdf` are identity-mapped so the device keeps working on its
1167/// reserved buffers.
1168pub fn domain_for_owned(
1169    sbdf: Sbdf,
1170    owner: Option<u32>,
1171    policy: FaultPolicy,
1172) -> Result<Arc<Domain>, IommuError> {
1173    let mut domains = DOMAINS.lock();
1174    if let Some(existing) = domains.values().find(|domain| domain.sbdf() == sbdf) {
1175        existing.acquire();
1176        return Ok(existing.clone());
1177    }
1178    let id = allocate_domain_id()?;
1179    let domain = Arc::new(Domain::new_owned(id, sbdf, owner, policy));
1180    domains.insert(id, domain.clone());
1181    {
1182        let mut global = STATS.lock();
1183        global.domains_created = global.domains_created.wrapping_add(1);
1184    }
1185
1186    // Identity-map the firmware-reserved regions this device owns.
1187    for region in RESERVED.lock().iter().filter(|r| r.covers(sbdf)) {
1188        let start = region.base & !(IOMMU_PAGE_SIZE - 1);
1189        let Some(end) = region
1190            .limit
1191            .checked_add(IOMMU_PAGE_SIZE)
1192            .map(|limit| limit & !(IOMMU_PAGE_SIZE - 1))
1193        else {
1194            continue;
1195        };
1196        if end <= start {
1197            continue;
1198        }
1199        if let Err(err) = domain.map_reserved(start, start, end - start, DmaProt::READ_WRITE) {
1200            log::warn!(
1201                "[IOMMU] cannot identity-map RMRR {:#x}..{:#x} for {}: {:?}",
1202                start,
1203                end - 1,
1204                sbdf,
1205                err
1206            );
1207        }
1208    }
1209
1210    Ok(domain)
1211}
1212
1213/// Convenience wrapper for segment 0.
1214pub fn create_domain(bus: u8, device: u8, function: u8) -> Result<Arc<Domain>, IommuError> {
1215    domain_for(Sbdf::from_pci(bus, device, function))
1216}
1217
1218/// Look up a live domain by id.
1219///
1220/// The returned `Arc` keeps the object alive but does **not** take a logical
1221/// reference: logical references model delegations, not transient lookups.
1222pub fn get_domain(id: DomainId) -> Option<Arc<Domain>> {
1223    DOMAINS.lock().get(&id).cloned()
1224}
1225
1226/// Find the live domain bound to `sbdf`, without taking a logical reference.
1227pub fn find_domain(sbdf: Sbdf) -> Option<Arc<Domain>> {
1228    DOMAINS
1229        .lock()
1230        .values()
1231        .find(|domain| domain.sbdf() == sbdf)
1232        .cloned()
1233}
1234
1235/// Drop one logical reference, tearing down the domain when it reaches zero.
1236pub fn release_domain(domain: &Arc<Domain>) -> bool {
1237    if domain.release() > 0 {
1238        return false;
1239    }
1240    let id = domain.id();
1241    domain.reset();
1242    let mut domains = DOMAINS.lock();
1243    // Only remove the registry entry if it is still the same object.
1244    let same = domains
1245        .get(&id)
1246        .map(|entry| Arc::ptr_eq(entry, domain))
1247        .unwrap_or(false);
1248    if same {
1249        domains.remove(&id);
1250        free_domain_id(id);
1251        let mut global = STATS.lock();
1252        global.domains_destroyed = global.domains_destroyed.wrapping_add(1);
1253        true
1254    } else {
1255        false
1256    }
1257}
1258
1259/// Destroy a domain unconditionally (hot-unplug, forced teardown).
1260pub fn teardown(id: DomainId) -> bool {
1261    let mut domains = DOMAINS.lock();
1262    let Some(domain) = domains.remove(&id) else {
1263        return false;
1264    };
1265    domain.reset();
1266    free_domain_id(id);
1267    let mut global = STATS.lock();
1268    global.domains_destroyed = global.domains_destroyed.wrapping_add(1);
1269    true
1270}
1271
1272/// Map an IOVA range into an existing domain, by id.
1273pub fn map(
1274    domain: DomainId,
1275    iova: u64,
1276    phys: u64,
1277    len: u64,
1278    prot: DmaProt,
1279) -> Result<(), IommuError> {
1280    let domain = lookup(domain)?;
1281    domain.map(iova, phys, len, prot)
1282}
1283
1284/// Remove mappings from an existing domain, by id.
1285pub fn unmap(domain: DomainId, iova: u64, len: u64) -> Result<usize, IommuError> {
1286    let domain = lookup(domain)?;
1287    domain.unmap(iova, len)
1288}
1289
1290/// Translate an IOVA through an existing domain, by id.
1291pub fn translate(domain: DomainId, iova: u64) -> Option<Translation> {
1292    lookup(domain).ok()?.translate(iova)
1293}
1294
1295fn lookup(id: DomainId) -> Result<Arc<Domain>, IommuError> {
1296    DOMAINS
1297        .lock()
1298        .get(&id)
1299        .cloned()
1300        .ok_or(IommuError::UnknownDomain)
1301}
1302
1303/// Number of live domains, for diagnostics.
1304pub fn domain_count() -> usize {
1305    DOMAINS.lock().len()
1306}
1307
1308/// Number of live domains and mapped bytes owned by a silo.
1309pub fn owner_usage(sid: u32) -> (usize, u64) {
1310    let domains = DOMAINS.lock();
1311    let owned: Vec<Arc<Domain>> = domains
1312        .values()
1313        .filter(|domain| domain.owner() == Some(sid))
1314        .cloned()
1315        .collect();
1316    drop(domains);
1317    let mut bytes = 0u64;
1318    for domain in &owned {
1319        bytes = bytes.saturating_add(domain.mapped_bytes());
1320    }
1321    (owned.len(), bytes)
1322}
1323
1324/// Destroy every domain owned by `sid` (silo death, hot-unplug, fault).
1325pub fn revoke_owner(sid: u32) -> usize {
1326    let ids: Vec<DomainId> = {
1327        let domains = DOMAINS.lock();
1328        domains
1329            .values()
1330            .filter(|domain| domain.owner() == Some(sid))
1331            .map(|domain| domain.id())
1332            .collect()
1333    };
1334    let mut revoked = 0;
1335    for id in ids {
1336        if teardown(id) {
1337            revoked += 1;
1338        }
1339    }
1340    if revoked > 0 {
1341        log::warn!("[IOMMU] revoked {} domain(s) for silo {}", revoked, sid);
1342    }
1343    revoked
1344}
1345
1346/// Stop accepting new mappings for a domain (hot-unplug preparation).
1347pub fn quiesce(id: DomainId) -> Result<(), IommuError> {
1348    lookup(id)?.quiesce();
1349    Ok(())
1350}
1351
1352/// Allow new mappings again.
1353pub fn resume(id: DomainId) -> Result<(), IommuError> {
1354    lookup(id)?.resume();
1355    Ok(())
1356}
1357
1358/// Detach a domain from its device: quiesce, then tear it down.
1359pub fn detach(id: DomainId) -> bool {
1360    if let Ok(domain) = lookup(id) {
1361        domain.quiesce();
1362    }
1363    teardown(id)
1364}
1365
1366/// Detach every domain bound to `sbdf` (device hot-removal).
1367pub fn detach_device(sbdf: Sbdf) -> usize {
1368    let ids: Vec<DomainId> = DOMAINS
1369        .lock()
1370        .values()
1371        .filter(|domain| domain.sbdf() == sbdf)
1372        .map(|domain| domain.id())
1373        .collect();
1374    let mut detached = 0;
1375    for id in ids {
1376        if detach(id) {
1377            detached += 1;
1378        }
1379    }
1380    if detached > 0 {
1381        log::info!("[IOMMU] detached {} domain(s) from {}", detached, sbdf);
1382    }
1383    detached
1384}
1385
1386/// Map a range with automatic 2 MiB/1 GiB superpage selection.
1387pub fn map_super(
1388    domain: DomainId,
1389    iova: u64,
1390    phys: u64,
1391    len: u64,
1392    prot: DmaProt,
1393) -> Result<MappingKind, IommuError> {
1394    let domain = lookup(domain)?;
1395    let kind = MappingKind::best_for(iova, len)
1396        .filter(|kind| phys & (kind.size() - 1) == 0)
1397        .ok_or(IommuError::InvalidRange)?;
1398    domain.map_kind(iova, phys, len, prot, kind)?;
1399    Ok(kind)
1400}
1401
1402// =============================================================================
1403// Fault queue API
1404// =============================================================================
1405
1406/// Pop the oldest fault record.
1407pub fn next_fault() -> Option<FaultRecord> {
1408    FAULTS.lock().pop_front()
1409}
1410
1411/// Number of fault records dropped by the rate limiter or a full queue.
1412pub fn faults_dropped() -> u64 {
1413    FAULT_DROPPED.load(Ordering::Relaxed)
1414}
1415
1416/// Refill the per-domain fault burst budget.
1417pub fn refill_fault_budget(domain: DomainId, burst: u32) {
1418    if let Ok(domain) = lookup(domain) {
1419        domain.state.lock().fault_budget = burst;
1420    }
1421}
1422
1423/// Inject a synthetic fault (debug builds and fault-policy tests).
1424pub fn inject_fault(
1425    domain: DomainId,
1426    iova: u64,
1427    reason: FaultReason,
1428    access: DmaProt,
1429) -> Option<FaultRecord> {
1430    lookup(domain).ok()?.report_fault(iova, reason, access)
1431}
1432
1433/// Coarse IOMMU groups derived from the DMAR DRHD scopes.
1434///
1435/// This is not a full PCIe ACS analysis: devices sharing a DRHD and a bus are
1436/// reported together, which is enough to warn a caller that two functions
1437/// cannot be isolated from each other.
1438#[derive(Debug, Clone, PartialEq, Eq)]
1439pub struct IommuGroup {
1440    pub id: u32,
1441    pub segment: u16,
1442    pub bus: u8,
1443    pub devices: Vec<Sbdf>,
1444}
1445
1446/// Return the coarse IOMMU groups advertised by the firmware.
1447pub fn groups() -> Vec<IommuGroup> {
1448    let Some(dmar) = crate::acpi::get_dmar() else {
1449        return Vec::new();
1450    };
1451    let Ok(units) = dmar.drhds() else {
1452        return Vec::new();
1453    };
1454    let mut groups: Vec<IommuGroup> = Vec::new();
1455    for unit in units {
1456        for scope in unit.scopes {
1457            let e = match scope.endpoint() {
1458                Some(endpoint) => endpoint,
1459                None => continue,
1460            };
1461            let sbdf = Sbdf::new(unit.segment, e.0, e.1, e.2);
1462            if let Some(group) = groups
1463                .iter_mut()
1464                .find(|g| g.segment == sbdf.segment && g.bus == sbdf.bus)
1465            {
1466                if !group.devices.contains(&sbdf) {
1467                    group.devices.push(sbdf);
1468                }
1469            } else {
1470                groups.push(IommuGroup {
1471                    id: groups.len() as u32,
1472                    segment: sbdf.segment,
1473                    bus: sbdf.bus,
1474                    devices: alloc::vec![sbdf],
1475                });
1476            }
1477        }
1478    }
1479    groups
1480}
1481
1482/// Parse the firmware tables and log a short IOMMU summary.
1483///
1484/// This never touches hardware: activation is a separate, explicit step.
1485pub fn init() {
1486    // `serial_println!` rather than `log::info!`: the IOMMU banner must be
1487    // visible even if the log gate (EXTENSIONS_READY) or quiet mode is active.
1488    crate::serial_println!("[IOMMU] init: probing firmware tables");
1489    let discovery = crate::arch::iommu::init();
1490    load_reserved_regions();
1491    if discovery.present {
1492        crate::serial_println!(
1493            "[IOMMU] {} backend, {} DRHD unit(s), {} RMRR, {} ATSR, {} bit host width, \
1494             intr-remap={}, x2apic-opt-out={}, ready={}",
1495            discovery.backend,
1496            discovery.units,
1497            discovery.rmrrs,
1498            discovery.atsrs,
1499            discovery.host_address_width,
1500            discovery.intr_remap,
1501            discovery.x2apic_opt_out,
1502            discovery.ready
1503        );
1504        log::info!(
1505            "[IOMMU] {} backend, {} unit(s), ready={}",
1506            discovery.backend,
1507            discovery.units,
1508            discovery.ready
1509        );
1510    } else {
1511        crate::serial_println!("[IOMMU] no IOMMU firmware table found (DMA is untranslated)");
1512    }
1513}
1514
1515/// Enable hardware translation.
1516///
1517/// Returns `false` unless a backend reports itself ready and successfully
1518/// programs the root/context tables.  P0 deliberately keeps this false until
1519/// the VT-d backend has been validated on real hardware.
1520pub fn activate() -> bool {
1521    if HARDWARE_ENABLED.load(Ordering::Acquire) {
1522        return true;
1523    }
1524    let backend = crate::arch::iommu::backend();
1525    if !backend.is_ready() {
1526        return false;
1527    }
1528    if backend.activate().is_err() {
1529        return false;
1530    }
1531    HARDWARE_ENABLED.store(true, Ordering::Release);
1532    let mut global = STATS.lock();
1533    global.activations = global.activations.wrapping_add(1);
1534    true
1535}
1536
1537/// Translate the DMAR RMRR structures into [`ReservedRegion`]s.
1538fn load_reserved_regions() {
1539    use crate::acpi::dmar::ScopeKind;
1540
1541    let Some(dmar) = crate::acpi::get_dmar() else {
1542        return;
1543    };
1544    let Ok(rmrrs) = dmar.rmrrs() else {
1545        return;
1546    };
1547
1548    let mut regions = Vec::new();
1549    for rmrr in rmrrs {
1550        let mut devices = Vec::new();
1551        let mut all_bus_from: Option<u8> = None;
1552        for scope in &rmrr.scopes {
1553            match scope.kind {
1554                ScopeKind::PciEndpoint => {
1555                    if let Some((bus, device, function)) = scope.endpoint() {
1556                        devices.push(Sbdf::new(rmrr.segment, bus, device, function));
1557                    }
1558                }
1559                ScopeKind::PciSubHierarchy => {
1560                    if scope.path.is_empty() {
1561                        all_bus_from = Some(
1562                            all_bus_from
1563                                .map(|bus| bus.min(scope.start_bus))
1564                                .unwrap_or(scope.start_bus),
1565                        );
1566                    } else if let Some(path) = scope.path.last() {
1567                        devices.push(Sbdf::new(
1568                            rmrr.segment,
1569                            scope.start_bus,
1570                            path.device,
1571                            path.function,
1572                        ));
1573                    }
1574                }
1575                _ => {}
1576            }
1577        }
1578        if devices.is_empty() && all_bus_from.is_none() {
1579            let panic_on_invalid = PANIC_ON_INVALID_RMRR.load(Ordering::Acquire);
1580            if panic_on_invalid {
1581                panic!(
1582                    "IOMMU: RMRR {:#x}..{:#x} has no device scope",
1583                    rmrr.base, rmrr.limit
1584                );
1585            }
1586            log::warn!(
1587                "[IOMMU] ignoring RMRR {:#x}..{:#x} without a usable device scope",
1588                rmrr.base,
1589                rmrr.limit
1590            );
1591            continue;
1592        }
1593        regions.push(ReservedRegion {
1594            segment: rmrr.segment,
1595            base: rmrr.base,
1596            limit: rmrr.limit,
1597            devices,
1598            all_bus_from,
1599            identity_mapped: false,
1600        });
1601    }
1602
1603    if !regions.is_empty() {
1604        log::info!("[IOMMU] {} reserved region(s) from RMRR", regions.len());
1605    }
1606
1607    // AMD IVMD: 0x20 = reserved, 0x22 = non-translated (also reserved).
1608    if let Some(ivrs) = crate::acpi::get_ivrs() {
1609        for md in ivrs.ivmd_blocks() {
1610            if md.typ != 0x20 && md.typ != 0x22 {
1611                continue;
1612            }
1613            let Some(end) = md.start_addr.checked_add(md.length_bytes) else {
1614                continue;
1615            };
1616            if end <= md.start_addr {
1617                continue;
1618            }
1619            let mut devices = Vec::new();
1620            let mut all_bus_from = None;
1621            if md.device_id == 0xffff {
1622                all_bus_from = Some(0);
1623            } else {
1624                let devfn = md.device_id;
1625                devices.push(Sbdf::new(
1626                    md.pci_segment,
1627                    (devfn >> 8) as u8,
1628                    ((devfn >> 3) & 0x1f) as u8,
1629                    (devfn & 0x7) as u8,
1630                ));
1631            }
1632            regions.push(ReservedRegion {
1633                segment: md.pci_segment,
1634                base: md.start_addr,
1635                limit: end - 1,
1636                devices,
1637                all_bus_from,
1638                identity_mapped: false,
1639            });
1640        }
1641    }
1642
1643    set_reserved_regions(regions, false);
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648    use super::*;
1649
1650    #[test]
1651    fn sbdf_roundtrip() {
1652        let sbdf = Sbdf::new(2, 0x1f, 3, 5);
1653        assert_eq!(Sbdf::from_u32(sbdf.to_u32()), sbdf);
1654    }
1655
1656    #[test]
1657    fn map_translate_unmap() {
1658        let domain = Domain::new(DomainId(7), Sbdf::from_pci(0, 2, 0));
1659        domain
1660            .map(IOVA_BASE, 0x1000, 0x2000, DmaProt::READ_WRITE)
1661            .unwrap();
1662        let t = domain.translate(IOVA_BASE + 0x1800).unwrap();
1663        assert_eq!(t.phys, 0x2800);
1664        assert_eq!(t.remaining, 0x800);
1665        assert_eq!(domain.generation(), 1);
1666
1667        assert!(domain
1668            .map(IOVA_BASE, 0x9000, 0x1000, DmaProt::READ)
1669            .is_err());
1670        assert!(domain
1671            .map(IOVA_BASE - 0x1000, 0x9000, 0x3000, DmaProt::READ)
1672            .is_err());
1673
1674        assert_eq!(domain.unmap(IOVA_BASE, 0x2000).unwrap(), 1);
1675        assert!(domain.translate(IOVA_BASE).is_none());
1676        assert_eq!(domain.unmap(IOVA_BASE, 0x2000), Err(IommuError::NotMapped));
1677    }
1678
1679    #[test]
1680    fn auto_iova_skips_holes() {
1681        let domain = Domain::new(DomainId(9), Sbdf::from_pci(0, 3, 0));
1682        let a = domain.map_auto(0x10_0000, 0x1000, DmaProt::READ).unwrap();
1683        let b = domain.map_auto(0x20_0000, 0x1000, DmaProt::READ).unwrap();
1684        assert_eq!(a, IOVA_BASE);
1685        assert_eq!(b, IOVA_BASE + 0x1000);
1686        domain.unmap_exact(a).unwrap();
1687        let c = domain.map_auto(0x30_0000, 0x1000, DmaProt::READ).unwrap();
1688        assert_eq!(c, IOVA_BASE);
1689    }
1690
1691    #[test]
1692    fn dma_prot_bits() {
1693        assert!(DmaProt::READ_WRITE.contains(DmaProt::READ));
1694        assert!(DmaProt::READ_WRITE.contains(DmaProt::WRITE));
1695        assert!(!DmaProt::READ.contains(DmaProt::WRITE));
1696        assert!(DmaProt::READ.readable() && !DmaProt::READ.writable());
1697        assert_eq!(DmaProt::from_bits(0b100), None);
1698        assert_eq!(DmaProt::from_bits(0b11), Some(DmaProt::READ_WRITE));
1699    }
1700
1701    #[test]
1702    fn superpage_selection() {
1703        assert_eq!(
1704            MappingKind::best_for(IOVA_BASE, IOMMU_SUPERPAGE_2M),
1705            Some(MappingKind::Page2M)
1706        );
1707        assert_eq!(
1708            MappingKind::best_for(IOVA_BASE, IOMMU_SUPERPAGE_1G),
1709            Some(MappingKind::Page1G)
1710        );
1711        // Misaligned base must fall back to 4 KiB leaves.
1712        assert_eq!(
1713            MappingKind::best_for(IOVA_BASE + IOMMU_PAGE_SIZE, IOMMU_SUPERPAGE_2M),
1714            Some(MappingKind::Page4K)
1715        );
1716        assert_eq!(MappingKind::best_for(IOVA_BASE, 0), None);
1717    }
1718
1719    #[test]
1720    fn quiesce_refuses_new_mappings() {
1721        let domain = Domain::new(DomainId(21), Sbdf::from_pci(0, 5, 0));
1722        domain.quiesce();
1723        assert_eq!(
1724            domain.map(IOVA_BASE, 0x1000, 0x1000, DmaProt::READ),
1725            Err(IommuError::Quiesced)
1726        );
1727        domain.resume();
1728        assert!(domain.map(IOVA_BASE, 0x1000, 0x1000, DmaProt::READ).is_ok());
1729    }
1730
1731    #[test]
1732    fn reserved_regions_are_rejected() {
1733        let sbdf = Sbdf::from_pci(0, 6, 0);
1734        set_reserved_regions(
1735            alloc::vec![ReservedRegion {
1736                segment: 0,
1737                base: 0x8000,
1738                limit: 0x8fff,
1739                devices: alloc::vec![sbdf],
1740                all_bus_from: None,
1741                identity_mapped: false,
1742            }],
1743            false,
1744        );
1745        let domain = Domain::new(DomainId(22), sbdf);
1746        assert_eq!(
1747            domain.map(IOVA_BASE, 0x8000, 0x1000, DmaProt::READ),
1748            Err(IommuError::Reserved)
1749        );
1750        // The reserved identity mapping path is the only way in.
1751        assert!(domain
1752            .map_reserved(0x8000, 0x8000, 0x1000, DmaProt::READ_WRITE)
1753            .is_ok());
1754        set_reserved_regions(alloc::vec![], false);
1755    }
1756
1757    #[test]
1758    fn fault_policy_kill_owner_records_the_action() {
1759        let domain = Domain::new_owned(
1760            DomainId(23),
1761            Sbdf::from_pci(0, 7, 0),
1762            Some(42),
1763            FaultPolicy::KillOwner,
1764        );
1765        let record = domain
1766            .report_fault(IOVA_BASE, FaultReason::Write, DmaProt::WRITE)
1767            .expect("fault queued");
1768        assert_eq!(record.owner, Some(42));
1769        assert_eq!(record.action, FaultAction::OwnerRevoked);
1770        assert_eq!(domain.stats().faults, 1);
1771    }
1772
1773    #[test]
1774    fn rejects_unaligned_and_empty() {
1775        let domain = Domain::new(DomainId(11), Sbdf::from_pci(0, 4, 0));
1776        assert_eq!(
1777            domain.map(IOVA_BASE + 1, 0x1000, 0x1000, DmaProt::READ),
1778            Err(IommuError::InvalidRange)
1779        );
1780        assert_eq!(
1781            domain.map(IOVA_BASE, 0x1000, 0, DmaProt::READ),
1782            Err(IommuError::InvalidRange)
1783        );
1784    }
1785}