Skip to main content

intel_vtd/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Intel VT-d (Virtualization Technology for Directed I/O) IOMMU emulator.
5//!
6//! Provides emulated DMA address translation (IOVA → GPA via root/context
7//! tables and second-level page table walking) and interrupt remapping for
8//! emulated PCI devices.
9//!
10//! Unlike the AMD IOMMU (which is a PCI device), VT-d is a pure MMIO platform
11//! device discovered via the ACPI DMAR table. It has no PCI config space.
12//!
13//! Legacy and scalable second-stage translation support 39/48-bit addresses,
14//! 4KB/2MB/1GB pages, and pass-through. ECAP advertises SMTS, SSTS, SMPWCS,
15//! SSADS and RPS together. Scalable requests use the context's implied RID_PASID;
16//! explicitly PASID-tagged requests, first-stage/nested translation, ATS, PRI,
17//! and supervisor requests are not supported.
18//!
19//! Tracking is optional per PASID entry: SSADE-enabled second-stage walks
20//! atomically set accessed flags and, for accepted writes, the leaf dirty flag
21//! before the DMA operation, even if that operation subsequently fails
22//! (§§3.7.2, 9.8). Updates require PWSNP=1; a required non-snooping update faults
23//! with reason 0x7c, and a failed atomic update faults with 0x7d (§7.1.3).
24//! Legacy translation and pass-through never update A/D flags.
25//!
26//! Walks are uncached, so cleared A/D flags can be set again immediately. This
27//! is an implementation property, not a portable software guarantee: software
28//! must use the invalidation protocol in §6.5.3.3. The state lock drains walks
29//! and DMA operations against invalidation, not guest page-table writes.
30//! Unsynchronized clearing does not provide a race-free dirty snapshot. There
31//! is no migration bitmap API. Interrupt remapping supports MSI and IOAPIC
32//! routes; queued invalidation uses 128/256-bit descriptors in legacy mode and
33//! 256-bit descriptors in scalable mode.
34
35#![forbid(unsafe_code)]
36
37pub mod spec;
38
39use chipset_device::ChipsetDevice;
40use chipset_device::io::IoError;
41use chipset_device::io::IoResult;
42use chipset_device::mmio::MmioIntercept;
43use guestmem::GuestMemory;
44use guestmem::GuestMemoryError;
45use inspect::InspectMut;
46use parking_lot::RwLock;
47use parking_lot::RwLockWriteGuard;
48use pci_core::msi::SignalMsi;
49use spec::invalidation::DescriptorType;
50use spec::invalidation::DescriptorWidth;
51use spec::invalidation::InvalidationDescriptor256;
52use spec::invalidation::InvalidationError;
53use spec::invalidation::InvalidationWaitDw0Dw1;
54use spec::invalidation::InvalidationWaitDw2Dw3;
55use spec::irte::Irte;
56use spec::irte::IrteLo;
57use spec::irte::SourceValidationType;
58use spec::pte::SlPte;
59use spec::registers::CapReg;
60use spec::registers::CcmdReg;
61use spec::registers::EcapReg;
62use spec::registers::FaultReason;
63use spec::registers::FectlReg;
64use spec::registers::FrcdHi;
65use spec::registers::FrcdLo;
66use spec::registers::FstsReg;
67use spec::registers::GcmdReg;
68use spec::registers::GstsReg;
69use spec::registers::IcsReg;
70use spec::registers::IectlReg;
71use spec::registers::IotlbReg;
72use spec::registers::IqaReg;
73use spec::registers::IqhReg;
74use spec::registers::IqtReg;
75use spec::registers::IrtaReg;
76use spec::registers::MmioRegister as Reg;
77use spec::registers::NumDomains;
78use spec::registers::RtaddrReg;
79use spec::registers::TranslationTableMode;
80use spec::registers::VersionReg;
81use spec::root_context::AddressWidth;
82use spec::root_context::ContextEntry;
83use spec::root_context::RootEntry;
84use spec::root_context::TranslationType;
85use spec::scalable::PasidDirectoryEntry;
86use spec::scalable::PasidTableEntry;
87use spec::scalable::PasidTranslationType;
88use spec::scalable::ScalableContextEntry;
89use spec::scalable::ScalableRootEntry;
90use spec::scalable::ScalableValidationError;
91use std::ops::RangeInclusive;
92use std::sync::Arc;
93use zerocopy::FromBytes;
94use zerocopy::FromZeros;
95use zerocopy::Immutable;
96use zerocopy::IntoBytes;
97use zerocopy::KnownLayout;
98
99/// MMIO region size (4KB).
100pub const MMIO_REGION_SIZE: u64 = spec::registers::MMIO_REGION_SIZE;
101
102// =============================================================================
103// Hardcoded Capability Values (1B.3)
104// =============================================================================
105
106/// Value returned by the VT-d version register (major = 1, minor = 0).
107const VER_VALUE: u32 = VersionReg::new().with_max(1).with_min(0).into_bits();
108
109/// Maximum guest address width in bits.
110const MGAW_BITS: u8 = 48;
111
112/// Host width advertised by OpenVMM's IntelVtdDmarConfig, independently of
113/// second-stage input MGAW/AGAW. SlPte can encode up to 52 address bits.
114const HAW_BITS: u8 = 48;
115const HOST_ADDRESS_MASK: u64 = (1 << HAW_BITS) - 1;
116
117/// Bounds the entire walk, including all CAS-conflict restarts (at most 64 PTEs).
118const MAX_AD_WALK_ATTEMPTS: usize = 16;
119
120/// SAGAW bitmask: supported address widths (39-bit + 48-bit).
121const SAGAW_MASK: u8 = (1 << AddressWidth::AW_39BIT.0) | (1 << AddressWidth::AW_48BIT.0);
122
123/// Largest advertised AGAW, which bounds DMA fault information (§11.4.7.6).
124const MAX_AGAW_BITS: u32 = 30 + 9 * SAGAW_MASK.ilog2();
125
126/// Number of fault recording registers.
127const NUM_FAULT_RECORDS: u8 = 1;
128
129/// Capability Register value.
130const CAP_VALUE: u64 = CapReg::new()
131    .with_nd(NumDomains::ND_64K.0)
132    .with_afl(false)
133    .with_rwbf(false)
134    .with_cm(false)
135    .with_sagaw(SAGAW_MASK)
136    .with_mgaw(MGAW_BITS - 1)
137    .with_zlr(true)
138    .with_fro(Reg::FRCD_DW0.0 / 16)
139    .with_sllps(spec::registers::SLLPS_2MB | spec::registers::SLLPS_1GB)
140    .with_psi(true)
141    .with_nfr(NUM_FAULT_RECORDS - 1)
142    .with_mamv(30 - 12) // max invalidation range = 1GB (2^30) / 4KB page (2^12)
143    .with_dwd(true)
144    .with_drd(true)
145    .into_bits();
146
147/// Extended Capability Register value.
148const ECAP_VALUE: u64 = EcapReg::new()
149    .with_c(true)
150    .with_qi(true)
151    .with_ir(true)
152    .with_eim(true)
153    .with_pt(true)
154    .with_sc(true)
155    .with_smts(true)
156    .with_ssts(true)
157    .with_smpwcs(true)
158    .with_ssads(true)
159    .with_rps(true)
160    .with_iro(Reg::IVA.0 / 16)
161    .with_mhmv(15) // max IM field in interrupt cache invalidation (4-bit max)
162    .into_bits();
163
164// =============================================================================
165// Configuration
166// =============================================================================
167
168/// Configuration for constructing an [`IntelVtdDevice`].
169#[derive(Debug, Clone)]
170pub struct IntelVtdConfig {
171    /// MMIO base address for the VT-d register file.
172    pub mmio_base: u64,
173}
174
175// =============================================================================
176// Internal Register State
177// =============================================================================
178
179/// Internal mutable state of the VT-d IOMMU.
180///
181/// All fields are behind `RwLock<VtdState>` in [`VtdSharedState`].
182/// DMA translations take a read lock; MMIO writes take a write lock.
183#[derive(Debug, inspect::Inspect)]
184struct VtdState {
185    // -- Global status (mirrors GCMD operations) --
186    /// Global Status Register value.
187    gsts: GstsReg,
188
189    // -- Root table --
190    /// Root Table Address Register (raw value, written freely).
191    rtaddr: RtaddrReg,
192    /// Latched root table address (set when SRTP is processed).
193    latched_rtaddr: RtaddrReg,
194
195    // -- Interrupt remapping table --
196    /// Interrupt Remapping Table Address Register (raw value).
197    irta: IrtaReg,
198    /// Latched IRTA (set when SIRTP is processed).
199    latched_irta: IrtaReg,
200
201    // -- Context command register (register-based invalidation) --
202    ccmd: CcmdReg,
203
204    // -- Fault recording --
205    /// Fault Status Register (RW1C bits: PFO, IQE, ICE, ITE).
206    fsts: FstsReg,
207    /// Fault Event Control Register.
208    fectl: FectlReg,
209    /// Fault Event Data Register.
210    #[inspect(hex)]
211    fedata: u32,
212    /// Fault Event Address Register.
213    #[inspect(hex)]
214    feaddr: u32,
215    /// Fault Event Upper Address Register.
216    #[inspect(hex)]
217    feuaddr: u32,
218    /// Fault Recording Register — low 64 bits.
219    frcd_lo: FrcdLo,
220    /// Fault Recording Register — high 64 bits.
221    frcd_hi: FrcdHi,
222
223    // -- Invalidation queue --
224    /// Invalidation Queue Address Register.
225    iqa: IqaReg,
226    /// Invalidation Queue Head.
227    iqh: IqhReg,
228    /// Invalidation Queue Tail.
229    iqt: IqtReg,
230    /// Whether the last consumed descriptor was an invalidation wait.
231    invalidation_queue_last_wait: bool,
232    /// Invalidation Completion Status Register (IWC bit).
233    ics: IcsReg,
234    /// Invalidation Event Control Register.
235    iectl: IectlReg,
236    /// Invalidation Event Data Register.
237    #[inspect(hex)]
238    iedata: u32,
239    /// Invalidation Event Address Register.
240    #[inspect(hex)]
241    ieaddr: u32,
242    /// Invalidation Event Upper Address Register.
243    #[inspect(hex)]
244    ieuaddr: u32,
245
246    // -- IOTLB registers (register-based invalidation, pre-QI) --
247    /// Invalidate Address Register (IVA_REG at 0x100).
248    #[inspect(hex)]
249    iva: u64,
250    /// IOTLB Invalidate Register (IOTLB_REG at 0x108).
251    iotlb: IotlbReg,
252}
253
254impl VtdState {
255    fn new() -> Self {
256        Self {
257            // Per VT-d spec §10.4.10 and §10.4.21, FECTL.IM and IECTL.IM
258            // default to 1 (masked) at power-up reset. Without this, the
259            // IOMMU may deliver spurious MSIs with uninitialized FEADDR/IEADDR
260            // registers (address=0, data=0) during early initialization, which
261            // can inject vector 0 (#DE) into the guest and crash it.
262            fectl: FectlReg::new().with_im(true),
263            iectl: IectlReg::new().with_im(true),
264            gsts: GstsReg::new(),
265            rtaddr: RtaddrReg::new(),
266            latched_rtaddr: RtaddrReg::new(),
267            irta: IrtaReg::new(),
268            latched_irta: IrtaReg::new(),
269            ccmd: CcmdReg::new(),
270            fsts: FstsReg::new(),
271            fedata: 0,
272            feaddr: 0,
273            feuaddr: 0,
274            frcd_lo: FrcdLo::new(),
275            frcd_hi: FrcdHi::new(),
276            iqa: IqaReg::new(),
277            iqh: IqhReg::new(),
278            iqt: IqtReg::new(),
279            invalidation_queue_last_wait: false,
280            ics: IcsReg::new(),
281            iedata: 0,
282            ieaddr: 0,
283            ieuaddr: 0,
284            iva: 0,
285            iotlb: IotlbReg::new(),
286        }
287    }
288}
289
290/// Validated queue geometry. Offsets are bytes, not descriptor indices.
291struct InvalidationQueue {
292    base: u64,
293    size: u64,
294    width: DescriptorWidth,
295    head: u64,
296    pending: u64,
297}
298
299impl InvalidationQueue {
300    fn new(state: &VtdState, ecap: EcapReg) -> Result<Self, InvalidationError> {
301        let iqa = state.iqa;
302        let width = DescriptorWidth::checked(
303            iqa.dw(),
304            TranslationTableMode(state.latched_rtaddr.ttm()),
305            ecap,
306        )?;
307        let base = iqa.queue_base_address();
308        let size = iqa.queue_size_bytes();
309        // Check the last byte, allowing a queue ending exactly at u64::MAX.
310        if iqa.into_bits() & 0x7f8 != 0 || base.checked_add(size - 1).is_none() {
311            return Err(InvalidationError::QueueAddress);
312        }
313        let head = state.iqh.into_bits();
314        let tail = state.iqt.into_bits();
315        let stride = width.bytes() as u64;
316        if head >= size || !head.is_multiple_of(stride) {
317            return Err(InvalidationError::QueueHead(head));
318        }
319        if tail >= size || !tail.is_multiple_of(stride) {
320            return Err(InvalidationError::QueueTail(tail));
321        }
322        Ok(Self {
323            base,
324            size,
325            width,
326            head,
327            pending: (tail + size - head) % size / stride,
328        })
329    }
330}
331
332// =============================================================================
333// Shared IOMMU State
334// =============================================================================
335
336/// Original, untagged DMA request and the fault policy accumulated during lookup.
337#[derive(Debug, Clone, Copy)]
338struct TranslationContext {
339    source_id: u16,
340    iova: u64,
341    mode: TranslationTableMode,
342    fpd: bool,
343}
344
345impl TranslationContext {
346    fn ad_fault(self, error: SecondStageAdError) -> VtdFault {
347        VtdFault::AdUpdate {
348            source_id: self.source_id,
349            iova: self.iova,
350            fpd: self.fpd,
351            error,
352        }
353    }
354
355    fn reason(self, legacy: FaultReason, scalable: FaultReason) -> FaultReason {
356        if self.mode == TranslationTableMode::LEGACY {
357            legacy
358        } else {
359            scalable
360        }
361    }
362
363    fn fault(self, reason: FaultReason) -> VtdFault {
364        let Self {
365            source_id,
366            iova,
367            fpd,
368            ..
369        } = self;
370        match reason {
371            FaultReason::ROOT_NOT_PRESENT => VtdFault::RootNotPresent { source_id, iova },
372            FaultReason::CONTEXT_NOT_PRESENT => VtdFault::ContextNotPresent {
373                source_id,
374                iova,
375                fpd,
376            },
377            FaultReason::INVALID_CONTEXT_ENTRY => VtdFault::InvalidContextEntry {
378                source_id,
379                iova,
380                fpd,
381            },
382            FaultReason::ADDRESS_BEYOND_MGAW => VtdFault::AddressBeyondMgaw {
383                source_id,
384                iova,
385                fpd,
386            },
387            FaultReason::WRITE_ACCESS_DENIED | FaultReason::READ_ACCESS_DENIED => {
388                VtdFault::AccessDenied {
389                    source_id,
390                    iova,
391                    fpd,
392                    write: reason == FaultReason::WRITE_ACCESS_DENIED,
393                }
394            }
395            FaultReason::ROOT_ENTRY_ACCESS_ERROR => {
396                VtdFault::RootEntryAccessError { source_id, iova }
397            }
398            FaultReason::CONTEXT_ENTRY_ACCESS_ERROR => {
399                VtdFault::ContextEntryAccessError { source_id, iova }
400            }
401            FaultReason::SL_PTE_ACCESS_ERROR => VtdFault::PageTableAccessError {
402                source_id,
403                iova,
404                fpd,
405            },
406            _ => VtdFault::Dma {
407                source_id,
408                iova,
409                reason,
410                fpd,
411            },
412        }
413    }
414}
415
416/// Validated lookup result; pass-through has no paging/A-D configuration.
417#[derive(Debug)]
418enum TranslationDescriptor {
419    PassThrough {
420        context: TranslationContext,
421        domain_id: u16,
422    },
423    SecondStage(SecondStageTranslation),
424}
425
426#[derive(Debug)]
427struct SecondStageTranslation {
428    context: TranslationContext,
429    root: u64,
430    levels: u8,
431    domain_id: u16,
432    ssade: bool,
433    pwsnp: bool,
434}
435
436/// Shared VT-d IOMMU state accessible by per-device wrappers.
437///
438/// This struct holds the MMIO register state and guest memory reference
439/// behind a `RwLock`, allowing concurrent reads from per-device translation
440/// wrappers while the `IntelVtdDevice` performs exclusive writes via MMIO.
441pub struct VtdSharedState {
442    /// Guest memory for reading root/context/page tables and IRT.
443    guest_memory: GuestMemory,
444    /// MMIO register state, protected by a RwLock.
445    state: RwLock<VtdState>,
446    /// MSI delivery handle for the IOMMU's own interrupts (fault events
447    /// and invalidation completion events). VT-d is a platform device
448    /// with no PCI MSI capability — it programs MSI address/data directly
449    /// into MMIO registers (FEADDR/FEDATA, IEADDR/IEDATA).
450    signal_msi: Arc<dyn SignalMsi>,
451    /// Registered interrupt routes for invalidation callbacks.
452    retranslate_interrupts: iommu_common::RetranslateInterruptsList,
453}
454
455impl VtdSharedState {
456    /// Create new shared state.
457    fn new(guest_memory: GuestMemory, signal_msi: Arc<dyn SignalMsi>) -> Self {
458        Self {
459            guest_memory,
460            state: RwLock::new(VtdState::new()),
461            signal_msi,
462            retranslate_interrupts: iommu_common::RetranslateInterruptsList::new(),
463        }
464    }
465
466    /// Returns whether translation is currently enabled (GSTS.TES).
467    pub fn is_enabled(&self) -> bool {
468        let state = self.state.read();
469        state.gsts.tes()
470    }
471
472    /// Returns whether interrupt remapping is currently enabled (GSTS.IRES).
473    pub fn is_ir_enabled(&self) -> bool {
474        let state = self.state.read();
475        state.gsts.ires()
476    }
477
478    /// Create a per-device IOVA→GPA translator.
479    pub fn translator(self: &Arc<Self>) -> VtdTranslator {
480        VtdTranslator {
481            shared: self.clone(),
482        }
483    }
484
485    /// Create a per-device MSI remapping wrapper.
486    pub fn wrap_signal_msi(self: &Arc<Self>, inner: Arc<dyn SignalMsi>) -> Arc<VtdSignalMsi> {
487        Arc::new(VtdSignalMsi {
488            shared: self.clone(),
489            inner,
490        })
491    }
492
493    /// Deliver the IOMMU's own fault event MSI.
494    ///
495    /// VT-d delivers its own MSIs directly (not through its own interrupt
496    /// remapping). Uses `signal_msi(None, ...)` — the `None` devid means
497    /// if this MSI were to pass through a VtdSignalMsi wrapper it would be
498    /// dropped, which is correct (IOMMU MSIs must not loop through IR).
499    fn deliver_fault_interrupt(&self, state: &VtdState) {
500        let fectl = state.fectl;
501        if fectl.im() {
502            // Masked — don't deliver, IP will be set by caller.
503            return;
504        }
505        let addr = (state.feuaddr as u64) << 32 | (state.feaddr as u64);
506        let data = state.fedata;
507        self.signal_msi.signal_msi(None, addr, data);
508    }
509
510    /// Deliver the IOMMU's own invalidation completion event MSI.
511    fn deliver_invalidation_interrupt(&self, state: &VtdState) {
512        let iectl = state.iectl;
513        if iectl.im() {
514            return;
515        }
516        let addr = (state.ieuaddr as u64) << 32 | (state.ieaddr as u64);
517        let data = state.iedata;
518        self.signal_msi.signal_msi(None, addr, data);
519    }
520
521    // =========================================================================
522    // Fault Recording (1D)
523    // =========================================================================
524
525    /// Record a translation fault in the Fault Recording Register.
526    ///
527    /// Must be called under a **write lock** on `self.state`.
528    /// `fpd` must already account for the fault's qualification (Table 26).
529    fn record_fault_locked(
530        &self,
531        state: &mut VtdState,
532        source_id: u16,
533        fault_reason: FaultReason,
534        fault_addr: u64,
535        is_read: bool,
536        fpd: bool,
537    ) {
538        if fpd {
539            return;
540        }
541
542        // Check if FRCD[0].F is already set (fault record occupied).
543        if state.frcd_hi.f() {
544            // Overflow — set PFO, discard new fault.
545            let mut fsts = state.fsts;
546            fsts.set_pfo(true);
547            state.fsts = fsts;
548            return;
549        }
550
551        // Write fault recording register.
552        let frcd_lo = FrcdLo::new().with_fi((fault_addr & ((1 << MAX_AGAW_BITS) - 1)) >> 12);
553        let frcd_hi = FrcdHi::new()
554            .with_sid(source_id)
555            .with_fr(fault_reason.0)
556            .with_t(is_read)
557            .with_f(true);
558
559        state.frcd_lo = frcd_lo;
560        state.frcd_hi = frcd_hi;
561
562        // Signal fault event MSI if unmasked.
563        // PPF transitions 0→1 since we just set F=1 and it was 0 before.
564        let fectl = state.fectl;
565        if !fectl.im() {
566            self.deliver_fault_interrupt(state);
567        } else {
568            // Masked — set IP (interrupt pending).
569            state.fectl = state.fectl.with_ip(true);
570        }
571    }
572
573    // =========================================================================
574    // DMA Translation (1E)
575    // =========================================================================
576
577    /// Translate an IOVA to a GPA while holding the read lock.
578    ///
579    /// Production callers use ECAP_VALUE; tests also exercise reduced profiles.
580    /// Returns `Ok(gpa)` on success or `Err(VtdFault)` on failure.
581    fn translate_locked(
582        &self,
583        state: &VtdState,
584        bus: u8,
585        devfn: u8,
586        iova: u64,
587        write: bool,
588        ecap: EcapReg,
589    ) -> Result<u64, VtdFault> {
590        if !state.gsts.tes() {
591            return Ok(iova);
592        }
593
594        let context = TranslationContext {
595            source_id: bdf(bus, devfn),
596            iova,
597            mode: TranslationTableMode(state.latched_rtaddr.ttm()),
598            fpd: false,
599        };
600        let root = state.latched_rtaddr.root_table_address();
601        let translation = match context.mode {
602            TranslationTableMode::LEGACY => self.resolve_legacy(root, context, ecap)?,
603            TranslationTableMode::SCALABLE if ecap.smts() => {
604                self.resolve_scalable(root, context, ecap)?
605            }
606            _ => return Err(context.fault(FaultReason::INVALID_ROOT_TABLE_MODE)),
607        };
608        match translation {
609            TranslationDescriptor::PassThrough { context, domain_id } => {
610                tracing::trace!(domain_id, "vtd: pass-through DMA");
611                if iova > HOST_ADDRESS_MASK {
612                    return Err(context.fault(context.reason(
613                        FaultReason::ADDRESS_BEYOND_MGAW,
614                        FaultReason::SCALABLE_ADDRESS_BEYOND_HAW,
615                    )));
616                }
617                Self::check_dma_output(context, iova)
618            }
619            TranslationDescriptor::SecondStage(translation) => {
620                self.walk_sl_page_table(&translation, write, ecap)
621            }
622        }
623    }
624
625    fn resolve_legacy(
626        &self,
627        root: u64,
628        mut context: TranslationContext,
629        ecap: EcapReg,
630    ) -> Result<TranslationDescriptor, VtdFault> {
631        let entry: RootEntry = self.read_translation_entry(
632            root,
633            u64::from(context.source_id >> 8),
634            context,
635            FaultReason::ROOT_ENTRY_ACCESS_ERROR,
636        )?;
637        if !entry.lo.p() {
638            return Err(context.fault(FaultReason::ROOT_NOT_PRESENT));
639        }
640        if entry.lo.into_bits() & (0xffe | !HOST_ADDRESS_MASK) != 0 || entry.hi != 0 {
641            return Err(context.fault(FaultReason::ROOT_ENTRY_RESERVED_BIT));
642        }
643        let entry: ContextEntry = self.read_translation_entry(
644            entry.lo.context_table_address(),
645            u64::from(context.source_id & 0xff),
646            context,
647            FaultReason::CONTEXT_ENTRY_ACCESS_ERROR,
648        )?;
649        context.fpd = entry.lo.fpd();
650        if !entry.lo.p() {
651            return Err(context.fault(FaultReason::CONTEXT_NOT_PRESENT));
652        }
653        // Context bits 70:67 are ignored, not reserved (§9.3).
654        if entry.lo.into_bits() & 0xff0 != 0 || entry.hi.into_bits() & 0xffff_ffff_ff00_0080 != 0 {
655            return Err(context.fault(FaultReason::CONTEXT_ENTRY_RESERVED_BIT));
656        }
657        let aw = AddressWidth(entry.hi.aw());
658        let domain_id = entry.hi.did();
659        match TranslationType(entry.lo.tt()) {
660            TranslationType::PASS_THROUGH if ecap.pt() => {
661                // §9.3 requires the largest supported AW. For compatibility,
662                // tolerate any supported AW, but not invalid encodings.
663                // Identity addresses still use HAW (§3.9), not paging AGAW.
664                if Self::supported_levels(aw).is_none() {
665                    return Err(context.fault(FaultReason::INVALID_CONTEXT_ENTRY));
666                }
667                Ok(TranslationDescriptor::PassThrough { context, domain_id })
668            }
669            TranslationType::UNTRANSLATED_ONLY | TranslationType::ALL => {
670                if entry.lo.page_table_address() > HOST_ADDRESS_MASK {
671                    return Err(context.fault(FaultReason::CONTEXT_ENTRY_RESERVED_BIT));
672                }
673                let levels = Self::supported_levels(aw)
674                    .ok_or_else(|| context.fault(FaultReason::INVALID_CONTEXT_ENTRY))?;
675                Ok(TranslationDescriptor::SecondStage(SecondStageTranslation {
676                    context,
677                    root: entry.lo.page_table_address(),
678                    levels,
679                    domain_id,
680                    ssade: false,
681                    pwsnp: ecap.c(),
682                }))
683            }
684            _ => Err(context.fault(FaultReason::INVALID_CONTEXT_ENTRY)),
685        }
686    }
687
688    /// Resolve an untagged RID through the scalable tables (§§3.4.3, 9.2, 9.4-9.6).
689    fn resolve_scalable(
690        &self,
691        root: u64,
692        mut context: TranslationContext,
693        ecap: EcapReg,
694    ) -> Result<TranslationDescriptor, VtdFault> {
695        let devfn = context.source_id as u8;
696        let entry: ScalableRootEntry = self.read_translation_entry(
697            root,
698            u64::from(context.source_id >> 8),
699            context,
700            FaultReason::SCALABLE_ROOT_ACCESS_ERROR,
701        )?;
702        let half = entry.half(devfn);
703        half.validate(HAW_BITS).map_err(|error| {
704            context.fault(match error {
705                ScalableValidationError::NotPresent => FaultReason::SCALABLE_ROOT_NOT_PRESENT,
706                _ => FaultReason::SCALABLE_ROOT_RESERVED_BIT,
707            })
708        })?;
709
710        let entry: ScalableContextEntry = self.read_translation_entry(
711            half.context_table_address(),
712            ScalableContextEntry::table_index(devfn) as u64,
713            context,
714            FaultReason::SCALABLE_CONTEXT_ACCESS_ERROR,
715        )?;
716        context.fpd |= entry.lo.fpd();
717        // Apply capability-dependent reserved-zero rules before profile validation,
718        // but ignore all fields except FPD when P=0 (§9.4).
719        if entry.lo.p() && !ecap.rps() && entry.hi.rid_pasid() != 0 {
720            return Err(context.fault(FaultReason::SCALABLE_CONTEXT_RESERVED_BIT));
721        }
722        entry.validate(HAW_BITS).map_err(|error| {
723            context.fault(match error {
724                ScalableValidationError::NotPresent => FaultReason::SCALABLE_CONTEXT_NOT_PRESENT,
725                ScalableValidationError::PasidOutOfRange { .. } => {
726                    FaultReason::SCALABLE_INVALID_CONTEXT
727                }
728                _ => FaultReason::SCALABLE_CONTEXT_RESERVED_BIT,
729            })
730        })?;
731        let (directory_index, table_index) = entry
732            .pasid_indices(entry.hi.rid_pasid())
733            .map_err(|_| context.fault(FaultReason::SCALABLE_INVALID_CONTEXT))?;
734
735        let entry: PasidDirectoryEntry = self.read_translation_entry(
736            entry.directory_address(),
737            u64::from(directory_index),
738            context,
739            FaultReason::PASID_DIRECTORY_ACCESS_ERROR,
740        )?;
741        context.fpd |= entry.fpd();
742        entry.validate(HAW_BITS).map_err(|error| {
743            context.fault(match error {
744                ScalableValidationError::NotPresent => FaultReason::PASID_DIRECTORY_NOT_PRESENT,
745                _ => FaultReason::PASID_DIRECTORY_RESERVED_BIT,
746            })
747        })?;
748
749        let entry: PasidTableEntry = self.read_translation_entry(
750            entry.table_address(),
751            u64::from(table_index),
752            context,
753            FaultReason::PASID_TABLE_ACCESS_ERROR,
754        )?;
755        context.fpd |= entry.lo.fpd();
756        // Capability-dependent reserved fields must not reach PGTT/AW validation;
757        // not-present entries still ignore everything except FPD (§9.6).
758        if entry.lo.p()
759            && ((!ecap.ssts()
760                && (entry.lo.aw() != 0 || entry.lo.ssptptr() != 0 || entry.lo.ssade()))
761                || (!ecap.ssads() && entry.lo.ssade())
762                || (!ecap.smpwcs() && entry.hi.pwsnp())
763                || (!ecap.sc() && entry.hi.pgsnp()))
764        {
765            return Err(context.fault(FaultReason::PASID_TABLE_RESERVED_BIT));
766        }
767        entry.validate(HAW_BITS).map_err(|error| {
768            context.fault(match error {
769                ScalableValidationError::NotPresent => FaultReason::PASID_TABLE_NOT_PRESENT,
770                ScalableValidationError::UnsupportedTranslationType(_)
771                | ScalableValidationError::UnsupportedAddressWidth(_) => {
772                    FaultReason::PASID_TABLE_INVALID_ENTRY
773                }
774                _ => FaultReason::PASID_TABLE_RESERVED_BIT,
775            })
776        })?;
777        let domain_id = entry.hi.did();
778        match PasidTranslationType(entry.lo.pgtt()) {
779            PasidTranslationType::PASS_THROUGH if ecap.pt() => {
780                Ok(TranslationDescriptor::PassThrough { context, domain_id })
781            }
782            PasidTranslationType::SECOND_STAGE if ecap.ssts() => {
783                let levels = Self::supported_levels(AddressWidth(entry.lo.aw()))
784                    .ok_or_else(|| context.fault(FaultReason::PASID_TABLE_INVALID_ENTRY))?;
785                Ok(TranslationDescriptor::SecondStage(SecondStageTranslation {
786                    context,
787                    root: entry.page_table_address(),
788                    levels,
789                    domain_id,
790                    ssade: entry.lo.ssade(),
791                    pwsnp: entry.hi.pwsnp(),
792                }))
793            }
794            _ => Err(context.fault(FaultReason::PASID_TABLE_INVALID_ENTRY)),
795        }
796    }
797
798    fn supported_levels(aw: AddressWidth) -> Option<u8> {
799        match aw {
800            AddressWidth::AW_39BIT => Some(3),
801            AddressWidth::AW_48BIT => Some(4),
802            _ => None,
803        }
804    }
805
806    fn read_translation_entry<T: FromBytes + KnownLayout + Immutable>(
807        &self,
808        base: u64,
809        index: u64,
810        context: TranslationContext,
811        reason: FaultReason,
812    ) -> Result<T, VtdFault> {
813        let address = Self::translation_entry_address::<T>(base, index)
814            .ok_or_else(|| context.fault(reason))?;
815        self.guest_memory
816            .read_plain(address)
817            .map_err(|_| context.fault(reason))
818    }
819
820    fn translation_entry_address<T>(base: u64, index: u64) -> Option<u64> {
821        let size = size_of::<T>() as u64;
822        index
823            .checked_mul(size)
824            .and_then(|offset| base.checked_add(offset))
825            .filter(|address| {
826                address
827                    .checked_add(size - 1)
828                    .is_some_and(|end| end <= HOST_ADDRESS_MASK)
829            })
830    }
831
832    fn check_dma_output(context: TranslationContext, gpa: u64) -> Result<u64, VtdFault> {
833        if gpa & !0xf_ffff == 0xfee0_0000 {
834            return Err(context.fault(context.reason(
835                FaultReason::OUTPUT_ADDR_IN_INTR_RANGE,
836                FaultReason::SCALABLE_OUTPUT_ADDR_IN_INTR_RANGE,
837            )));
838        }
839        Ok(gpa)
840    }
841
842    /// Shared second-stage walk (§§3.7, 3.7.1, 3.7.2, 9.8).
843    fn walk_sl_page_table(
844        &self,
845        translation: &SecondStageTranslation,
846        write: bool,
847        ecap: EcapReg,
848    ) -> Result<u64, VtdFault> {
849        self.walk_sl_page_table_with_cas(translation, write, ecap, |address, current, new| {
850            self.guest_memory
851                .compare_exchange::<u64>(address, current.to_le(), new.to_le())
852                .map(|result| result.is_ok())
853        })
854    }
855
856    /// The callable operates on decoded little-endian words and reports whether
857    /// the CAS succeeded. A conflict always requires a fresh, validated walk.
858    fn walk_sl_page_table_with_cas(
859        &self,
860        translation: &SecondStageTranslation,
861        write: bool,
862        ecap: EcapReg,
863        mut compare_exchange: impl FnMut(u64, u64, u64) -> Result<bool, GuestMemoryError>,
864    ) -> Result<u64, VtdFault> {
865        let &SecondStageTranslation {
866            context,
867            root,
868            levels,
869            domain_id,
870            ssade,
871            pwsnp,
872        } = translation;
873        tracing::trace!(domain_id, ssade, pwsnp, "vtd: second-stage DMA");
874        if !matches!(levels, 3 | 4) {
875            return Err(context.fault(context.reason(
876                FaultReason::INVALID_CONTEXT_ENTRY,
877                FaultReason::PASID_TABLE_INVALID_ENTRY,
878            )));
879        }
880        let iova = context.iova;
881        if iova >> MGAW_BITS.min(12 + 9 * levels) != 0 {
882            return Err(context.fault(context.reason(
883                FaultReason::ADDRESS_BEYOND_MGAW,
884                FaultReason::SCALABLE_ADDRESS_BEYOND_AGAW,
885            )));
886        }
887        let track_ad = ssade && context.mode == TranslationTableMode::SCALABLE;
888
889        'walk: for _ in 0..MAX_AD_WALK_ATTEMPTS {
890            let mut table_addr = root;
891            let mut can_read = true;
892            let mut can_write = true;
893            for level in (1..=levels).rev() {
894                // Table 26 distinguishes SSPTPTR access (LCT.4.3/SSS.4) from
895                // access through a preceding paging entry's ADDR (LSS.1/SSS.1).
896                let reason = if level == levels {
897                    context.reason(
898                        FaultReason::INVALID_CONTEXT_ENTRY,
899                        FaultReason::SCALABLE_SL_ROOT_ACCESS_ERROR,
900                    )
901                } else {
902                    context.reason(
903                        FaultReason::SL_PTE_ACCESS_ERROR,
904                        FaultReason::SCALABLE_SL_PTE_ACCESS_ERROR,
905                    )
906                };
907                let address = Self::translation_entry_address::<u64>(
908                    table_addr,
909                    SlPte::iova_index(iova, level) as u64,
910                )
911                .ok_or_else(|| context.fault(reason))?;
912                let raw = self
913                    .guest_memory
914                    .read_plain::<u64>(address)
915                    .map(u64::from_le)
916                    .map_err(|_| context.fault(reason))?;
917                let pte = SlPte::from(raw);
918                can_read &= pte.r();
919                can_write &= pte.w();
920                let denied = context.reason(
921                    if write {
922                        FaultReason::WRITE_ACCESS_DENIED
923                    } else {
924                        FaultReason::READ_ACCESS_DENIED
925                    },
926                    if write {
927                        FaultReason::SCALABLE_WRITE_ACCESS_DENIED
928                    } else {
929                        FaultReason::SCALABLE_READ_ACCESS_DENIED
930                    },
931                );
932                if !pte.is_present() || (!can_read && !can_write) {
933                    return Err(context
934                        .fault(context.reason(denied, FaultReason::SCALABLE_SL_PTE_NOT_PRESENT)));
935                }
936
937                let leaf = level == 1 || (pte.ps() && matches!(level, 2 | 3));
938                let offset_mask = SlPte::page_size_at_level(level) - 1;
939                let reserved = (1 << 62)
940                    | (((1u64 << 52) - 1) & !HOST_ADDRESS_MASK)
941                    | if !leaf || !ecap.sc() { 1 << 11 } else { 0 }
942                    | if level == 4 { 1 << 7 } else { 0 }
943                    | if leaf { offset_mask & !0xfff } else { 0 };
944                if raw & reserved != 0 {
945                    return Err(context.fault(context.reason(
946                        FaultReason::SL_PTE_RESERVED_BIT,
947                        FaultReason::SCALABLE_SL_PTE_RESERVED_BIT,
948                    )));
949                }
950                let output = if leaf {
951                    if (write && !can_write) || (!write && !can_read) {
952                        return Err(context.fault(denied));
953                    }
954                    Some(Self::check_dma_output(
955                        context,
956                        pte.phys_address() | (iova & offset_mask),
957                    )?)
958                } else {
959                    None
960                };
961                // Only validated entries acquire A; D additionally requires an
962                // accepted write translation, including the output-range check.
963                let updated = pte
964                    .with_a(true)
965                    .with_d(pte.d() || (leaf && write))
966                    .into_bits();
967                if track_ad && updated != raw {
968                    if !ecap.smpwcs() || !pwsnp {
969                        return Err(context.ad_fault(SecondStageAdError::NonSnooping));
970                    }
971                    if !compare_exchange(address, raw, updated)
972                        .map_err(|error| context.ad_fault(SecondStageAdError::Memory(error)))?
973                    {
974                        // Restart permissions and geometry from the root, even
975                        // for A/D-only conflicts. Never OR into a stale mapping.
976                        // The attempt budget is shared across every level.
977                        continue 'walk;
978                    }
979                }
980                if let Some(gpa) = output {
981                    return Ok(gpa);
982                }
983                table_addr = pte.phys_address();
984            }
985        }
986        Err(context.ad_fault(SecondStageAdError::RetryExhausted))
987    }
988
989    // =========================================================================
990    // Interrupt Remapping (1F)
991    // =========================================================================
992
993    /// Remap an MSI using the Interrupt Remapping Table.
994    ///
995    /// Called under the read lock. On fault, returns `Err(VtdFault)`.
996    fn remap_msi_locked(
997        &self,
998        state: &VtdState,
999        source_id: u16,
1000        address: u64,
1001        data: u32,
1002    ) -> Result<(u64, u32), VtdFault> {
1003        let gsts = state.gsts;
1004        if !gsts.ires() {
1005            // IR disabled — pass through.
1006            return Ok((address, data));
1007        }
1008
1009        // Check for compatibility-format MSI (bit 4 of address = 0).
1010        let is_remappable = (address >> 4) & 1 != 0;
1011        if !is_remappable {
1012            return self.handle_compat_format(state, source_id, address, data);
1013        }
1014
1015        // Extract IRTE index from remappable-format MSI.
1016        let irte_index = Self::extract_irte_index(address, data);
1017
1018        // Validate index against IRT size.
1019        let irta = state.latched_irta;
1020        let max_entries = irta.entry_count();
1021        if irte_index as u32 >= max_entries {
1022            return Err(VtdFault::IrteIndexExceedsSize {
1023                source_id,
1024                irte_index,
1025            });
1026        }
1027
1028        // Look up IRTE.
1029        let irt_base = irta.irt_base_address();
1030        let irte = self.lookup_irte(irt_base, irte_index, source_id)?;
1031
1032        // Validate source ID.
1033        self.validate_irte_source(source_id, &irte, irte_index)?;
1034
1035        // Check IRTE mode (IM=0 for remapped, IM=1 for posted — not supported).
1036        let irte_lo = irte.lo;
1037        if irte_lo.im() {
1038            return Err(VtdFault::IrteReservedField {
1039                source_id,
1040                irte_index,
1041                fpd: irte_lo.fpd(),
1042            });
1043        }
1044
1045        // Construct remapped MSI address and data.
1046        let eime = irta.eime();
1047        let (new_address, new_data) = Self::construct_remapped_msi(irte_lo, eime);
1048
1049        Ok((new_address, new_data))
1050    }
1051
1052    /// Handle compatibility-format MSI when IR is enabled.
1053    fn handle_compat_format(
1054        &self,
1055        state: &VtdState,
1056        source_id: u16,
1057        address: u64,
1058        data: u32,
1059    ) -> Result<(u64, u32), VtdFault> {
1060        let irta = state.latched_irta;
1061        let gsts = state.gsts;
1062
1063        // EIME=1 → always block compatibility-format interrupts.
1064        if irta.eime() {
1065            return Err(VtdFault::CompatibilityFormatBlocked { source_id });
1066        }
1067
1068        // CFIS=1 → pass through.
1069        if gsts.cfis() {
1070            return Ok((address, data));
1071        }
1072
1073        // CFIS=0 → block.
1074        Err(VtdFault::CompatibilityFormatBlocked { source_id })
1075    }
1076
1077    /// Extract the IRTE index from remappable-format MSI address/data.
1078    ///
1079    /// Handle = {address[2], address[19:5]} (16-bit).
1080    /// SHV = address[3].
1081    /// If SHV=0: index = handle.
1082    /// If SHV=1: index = handle + data[15:0].
1083    fn extract_irte_index(address: u64, data: u32) -> u16 {
1084        let handle_lo = ((address >> 5) & 0x7FFF) as u16; // address[19:5] = 15 bits
1085        let handle_hi = ((address >> 2) & 1) as u16; // address[2] = 1 bit
1086        let handle = (handle_hi << 15) | handle_lo;
1087
1088        let shv = (address >> 3) & 1 != 0;
1089        if shv {
1090            handle.wrapping_add(data as u16)
1091        } else {
1092            handle
1093        }
1094    }
1095
1096    /// Look up an IRTE by index.
1097    fn lookup_irte(
1098        &self,
1099        irt_base: u64,
1100        irte_index: u16,
1101        source_id: u16,
1102    ) -> Result<Irte, VtdFault> {
1103        let entry_addr = irt_base + (irte_index as u64) * 16;
1104        let irte: Irte =
1105            self.guest_memory
1106                .read_plain(entry_addr)
1107                .map_err(|_| VtdFault::IrteAccessError {
1108                    source_id,
1109                    irte_index,
1110                })?;
1111
1112        if !irte.lo.p() {
1113            return Err(VtdFault::IrteNotPresent {
1114                source_id,
1115                irte_index,
1116                fpd: irte.lo.fpd(),
1117            });
1118        }
1119
1120        Ok(irte)
1121    }
1122
1123    /// Validate the interrupt source against the IRTE's SVT/SID/SQ fields.
1124    fn validate_irte_source(
1125        &self,
1126        source_id: u16,
1127        irte: &Irte,
1128        irte_index: u16,
1129    ) -> Result<(), VtdFault> {
1130        let svt = SourceValidationType(irte.hi.svt());
1131        let irte_sid = irte.hi.sid();
1132        let sq = irte.hi.sq();
1133        let fpd = irte.lo.fpd();
1134
1135        match svt {
1136            SourceValidationType::NONE => Ok(()),
1137            SourceValidationType::VERIFY_SID => {
1138                // Mask based on SQ: SQ=00 all 16 bits, SQ=01 ignore bit 2,
1139                // SQ=10 ignore bits 2:1, SQ=11 ignore bits 2:0.
1140                let mask: u16 = match sq {
1141                    0b00 => 0xFFFF,
1142                    0b01 => !0x04,
1143                    0b10 => !0x06,
1144                    0b11 => !0x07,
1145                    _ => 0xFFFF,
1146                };
1147                if (source_id & mask) != (irte_sid & mask) {
1148                    Err(VtdFault::SourceValidationFailed {
1149                        source_id,
1150                        irte_index,
1151                        fpd,
1152                    })
1153                } else {
1154                    Ok(())
1155                }
1156            }
1157            SourceValidationType::VERIFY_BUS_RANGE => {
1158                // SID[7:0] = start bus, SID[15:8] = end bus.
1159                let start_bus = (irte_sid & 0xFF) as u8;
1160                let end_bus = ((irte_sid >> 8) & 0xFF) as u8;
1161                let source_bus = ((source_id >> 8) & 0xFF) as u8;
1162                if source_bus < start_bus || source_bus > end_bus {
1163                    Err(VtdFault::SourceValidationFailed {
1164                        source_id,
1165                        irte_index,
1166                        fpd,
1167                    })
1168                } else {
1169                    Ok(())
1170                }
1171            }
1172            _ => {
1173                // Unknown SVT — treat as no validation.
1174                Ok(())
1175            }
1176        }
1177    }
1178
1179    /// Construct remapped MSI address and data from an IRTE.
1180    fn construct_remapped_msi(irte_lo: IrteLo, eime: bool) -> (u64, u32) {
1181        let dst = if eime {
1182            // x2APIC: full 32-bit destination.
1183            irte_lo.dst()
1184        } else {
1185            // xAPIC: 8-bit destination from bits 15:8 of DST field.
1186            irte_lo.xapic_destination() as u32
1187        };
1188
1189        let new_address = x86defs::msi::MsiAddress::new()
1190            .with_address(x86defs::msi::MSI_ADDRESS)
1191            .with_virt_destination(dst as u16)
1192            .with_destination_mode_logical(irte_lo.dm())
1193            .with_redirection_hint(irte_lo.rh());
1194
1195        let new_data = x86defs::msi::MsiData::new()
1196            .with_vector(irte_lo.vector())
1197            .with_delivery_mode(irte_lo.dlm())
1198            .with_trigger_mode_level(irte_lo.tm());
1199
1200        (new_address.into_bits() as u64, new_data.into_bits())
1201    }
1202}
1203
1204// =============================================================================
1205// VtdFault — IOMMU-specific translation/remapping error
1206// =============================================================================
1207
1208/// Failure to atomically mark a second-stage paging entry (§7.1.3, SSS.5/6).
1209#[derive(Debug, thiserror::Error)]
1210pub enum SecondStageAdError {
1211    /// A required update cannot be performed without page-walk snooping.
1212    #[error("second-stage A/D update requires page-walk snooping")]
1213    NonSnooping,
1214    /// Guest memory rejected the atomic access.
1215    #[error("second-stage A/D atomic memory access failed")]
1216    Memory(#[source] GuestMemoryError),
1217    /// Conflicting page-table changes exhausted the per-translation budget.
1218    #[error("second-stage A/D walk retry budget exhausted")]
1219    RetryExhausted,
1220}
1221
1222/// VT-d translation or interrupt remapping fault.
1223///
1224/// Each variant carries the source ID and faulting address/index,
1225/// and maps to a specific VT-d fault reason code.
1226#[derive(Debug, thiserror::Error)]
1227#[expect(missing_docs)]
1228pub enum VtdFault {
1229    #[error("{error} (source_id={source_id:#06x}, iova={iova:#x})")]
1230    AdUpdate {
1231        source_id: u16,
1232        iova: u64,
1233        fpd: bool,
1234        #[source]
1235        error: SecondStageAdError,
1236    },
1237
1238    #[error("DMA fault {reason:?} (source_id={source_id:#06x}, iova={iova:#x})")]
1239    Dma {
1240        source_id: u16,
1241        iova: u64,
1242        reason: FaultReason,
1243        fpd: bool,
1244    },
1245
1246    #[error("root entry not present (source_id={source_id:#06x})")]
1247    RootNotPresent { source_id: u16, iova: u64 },
1248
1249    #[error("context entry not present (source_id={source_id:#06x})")]
1250    ContextNotPresent {
1251        source_id: u16,
1252        iova: u64,
1253        fpd: bool,
1254    },
1255
1256    #[error("invalid context entry (source_id={source_id:#06x}, iova={iova:#x})")]
1257    InvalidContextEntry {
1258        source_id: u16,
1259        iova: u64,
1260        fpd: bool,
1261    },
1262
1263    #[error("IOVA beyond MGAW (source_id={source_id:#06x}, iova={iova:#x})")]
1264    AddressBeyondMgaw {
1265        source_id: u16,
1266        iova: u64,
1267        fpd: bool,
1268    },
1269
1270    #[error("{} access denied (source_id={source_id:#06x}, iova={iova:#x})", if *write { "write" } else { "read" })]
1271    AccessDenied {
1272        source_id: u16,
1273        iova: u64,
1274        fpd: bool,
1275        write: bool,
1276    },
1277
1278    #[error("root entry access error (source_id={source_id:#06x})")]
1279    RootEntryAccessError { source_id: u16, iova: u64 },
1280
1281    #[error("context entry access error (source_id={source_id:#06x})")]
1282    ContextEntryAccessError { source_id: u16, iova: u64 },
1283
1284    #[error("page table access error (source_id={source_id:#06x}, iova={iova:#x})")]
1285    PageTableAccessError {
1286        source_id: u16,
1287        iova: u64,
1288        fpd: bool,
1289    },
1290
1291    #[error("IRTE not present (source_id={source_id:#06x}, index={irte_index})")]
1292    IrteNotPresent {
1293        source_id: u16,
1294        irte_index: u16,
1295        fpd: bool,
1296    },
1297
1298    #[error("IRTE access error (source_id={source_id:#06x}, index={irte_index})")]
1299    IrteAccessError { source_id: u16, irte_index: u16 },
1300
1301    #[error("IRTE index exceeds IRT size (source_id={source_id:#06x}, index={irte_index})")]
1302    IrteIndexExceedsSize { source_id: u16, irte_index: u16 },
1303
1304    #[error("IRTE reserved field set (source_id={source_id:#06x}, index={irte_index})")]
1305    IrteReservedField {
1306        source_id: u16,
1307        irte_index: u16,
1308        fpd: bool,
1309    },
1310
1311    #[error("source validation failed (source_id={source_id:#06x})")]
1312    SourceValidationFailed {
1313        source_id: u16,
1314        irte_index: u16,
1315        fpd: bool,
1316    },
1317
1318    #[error("compatibility-format interrupt blocked (source_id={source_id:#06x})")]
1319    CompatibilityFormatBlocked { source_id: u16 },
1320}
1321
1322impl VtdFault {
1323    /// Get the fault reason code for this fault.
1324    fn fault_reason(&self) -> FaultReason {
1325        match self {
1326            Self::AdUpdate { error, .. } => match error {
1327                SecondStageAdError::NonSnooping => FaultReason::SL_AD_UPDATE_NON_SNOOP,
1328                SecondStageAdError::Memory(_) | SecondStageAdError::RetryExhausted => {
1329                    FaultReason::SL_AD_UPDATE_FAILED
1330                }
1331            },
1332            Self::Dma { reason, .. } => *reason,
1333            Self::RootNotPresent { .. } => FaultReason::ROOT_NOT_PRESENT,
1334            Self::ContextNotPresent { .. } => FaultReason::CONTEXT_NOT_PRESENT,
1335            Self::InvalidContextEntry { .. } => FaultReason::INVALID_CONTEXT_ENTRY,
1336            Self::AddressBeyondMgaw { .. } => FaultReason::ADDRESS_BEYOND_MGAW,
1337            Self::AccessDenied { write: true, .. } => FaultReason::WRITE_ACCESS_DENIED,
1338            Self::AccessDenied { write: false, .. } => FaultReason::READ_ACCESS_DENIED,
1339            Self::RootEntryAccessError { .. } => FaultReason::ROOT_ENTRY_ACCESS_ERROR,
1340            Self::ContextEntryAccessError { .. } => FaultReason::CONTEXT_ENTRY_ACCESS_ERROR,
1341            Self::PageTableAccessError { .. } => FaultReason::SL_PTE_ACCESS_ERROR,
1342            Self::IrteNotPresent { .. } => FaultReason::IRTE_NOT_PRESENT,
1343            Self::IrteAccessError { .. } => FaultReason::IRTE_ACCESS_ERROR,
1344            Self::IrteIndexExceedsSize { .. } => FaultReason::IR_INDEX_EXCEEDS_SIZE,
1345            Self::IrteReservedField { .. } => FaultReason::IRTE_RESERVED_FIELD,
1346            Self::SourceValidationFailed { .. } => FaultReason::SOURCE_ID_VERIFICATION_FAIL,
1347            Self::CompatibilityFormatBlocked { .. } => FaultReason::COMPAT_FORMAT_BLOCKED,
1348        }
1349    }
1350
1351    /// Get the source ID from this fault.
1352    fn source_id(&self) -> u16 {
1353        match self {
1354            Self::AdUpdate { source_id, .. }
1355            | Self::Dma { source_id, .. }
1356            | Self::RootNotPresent { source_id, .. }
1357            | Self::ContextNotPresent { source_id, .. }
1358            | Self::InvalidContextEntry { source_id, .. }
1359            | Self::AddressBeyondMgaw { source_id, .. }
1360            | Self::AccessDenied { source_id, .. }
1361            | Self::RootEntryAccessError { source_id, .. }
1362            | Self::ContextEntryAccessError { source_id, .. }
1363            | Self::PageTableAccessError { source_id, .. }
1364            | Self::IrteNotPresent { source_id, .. }
1365            | Self::IrteAccessError { source_id, .. }
1366            | Self::IrteIndexExceedsSize { source_id, .. }
1367            | Self::IrteReservedField { source_id, .. }
1368            | Self::SourceValidationFailed { source_id, .. }
1369            | Self::CompatibilityFormatBlocked { source_id, .. } => *source_id,
1370        }
1371    }
1372
1373    /// Get the faulting address (IOVA for DMA, 0 for IR faults).
1374    fn fault_address(&self) -> u64 {
1375        match self {
1376            Self::AdUpdate { iova, .. }
1377            | Self::Dma { iova, .. }
1378            | Self::RootNotPresent { iova, .. }
1379            | Self::ContextNotPresent { iova, .. }
1380            | Self::InvalidContextEntry { iova, .. }
1381            | Self::AddressBeyondMgaw { iova, .. }
1382            | Self::AccessDenied { iova, .. }
1383            | Self::RootEntryAccessError { iova, .. }
1384            | Self::ContextEntryAccessError { iova, .. }
1385            | Self::PageTableAccessError { iova, .. } => *iova,
1386            // Interrupt remapping faults don't have an IOVA.
1387            Self::IrteNotPresent { .. }
1388            | Self::IrteAccessError { .. }
1389            | Self::IrteIndexExceedsSize { .. }
1390            | Self::IrteReservedField { .. }
1391            | Self::SourceValidationFailed { .. }
1392            | Self::CompatibilityFormatBlocked { .. } => 0,
1393        }
1394    }
1395
1396    /// Whether fault processing is disabled for this fault.
1397    fn fpd(&self) -> bool {
1398        match self {
1399            // Table 26: lookup access errors are unqualified even after a
1400            // parent FPD has been observed. Page-walk faults are qualified.
1401            Self::Dma { reason, fpd, .. } => {
1402                *fpd && !matches!(
1403                    *reason,
1404                    FaultReason::INVALID_ROOT_TABLE_MODE
1405                        | FaultReason::SCALABLE_ROOT_ACCESS_ERROR
1406                        | FaultReason::SCALABLE_ROOT_NOT_PRESENT
1407                        | FaultReason::SCALABLE_ROOT_RESERVED_BIT
1408                        | FaultReason::SCALABLE_CONTEXT_ACCESS_ERROR
1409                        | FaultReason::PASID_DIRECTORY_ACCESS_ERROR
1410                        | FaultReason::PASID_TABLE_ACCESS_ERROR
1411                )
1412            }
1413            Self::AdUpdate { fpd, .. }
1414            | Self::ContextNotPresent { fpd, .. }
1415            | Self::AddressBeyondMgaw { fpd, .. }
1416            | Self::InvalidContextEntry { fpd, .. }
1417            | Self::AccessDenied { fpd, .. }
1418            | Self::PageTableAccessError { fpd, .. }
1419            | Self::IrteNotPresent { fpd, .. }
1420            | Self::IrteReservedField { fpd, .. }
1421            | Self::SourceValidationFailed { fpd, .. } => *fpd,
1422            // Faults without FPD context are always recorded.
1423            Self::RootNotPresent { .. }
1424            | Self::RootEntryAccessError { .. }
1425            | Self::ContextEntryAccessError { .. }
1426            | Self::IrteAccessError { .. }
1427            | Self::IrteIndexExceedsSize { .. }
1428            | Self::CompatibilityFormatBlocked { .. } => false,
1429        }
1430    }
1431
1432    /// Record this fault in the IOMMU's fault recording registers.
1433    ///
1434    /// `is_write` is the access type of the faulting request. This sets
1435    /// FRCD.T (0=write, 1=read/non-write) per §7.1. The access type is a
1436    /// property of the DMA/interrupt request, not of the fault itself.
1437    ///
1438    /// Takes a write lock on the shared state.
1439    fn record(&self, shared: &VtdSharedState, is_write: bool) {
1440        let mut state = shared.state.write();
1441        shared.record_fault_locked(
1442            &mut state,
1443            self.source_id(),
1444            self.fault_reason(),
1445            self.fault_address(),
1446            !is_write, // FRCD.T: 1=read, 0=write
1447            self.fpd(),
1448        );
1449    }
1450}
1451
1452/// Combine bus and devfn into a 16-bit BDF source ID.
1453fn bdf(bus: u8, devfn: u8) -> u16 {
1454    ((bus as u16) << 8) | devfn as u16
1455}
1456
1457// =============================================================================
1458// VtdTranslator — IommuTranslator implementation (1G.2)
1459// =============================================================================
1460
1461/// Per-device IOVA→GPA translator for Intel VT-d.
1462///
1463/// Implements [`iommu_common::IommuTranslator`] using the closure-based API
1464/// that holds the read lock across translation and the memory access operation.
1465#[derive(Clone)]
1466pub struct VtdTranslator {
1467    shared: Arc<VtdSharedState>,
1468}
1469
1470impl iommu_common::IommuTranslator for VtdTranslator {
1471    type Error = VtdFault;
1472
1473    fn max_iova(&self) -> u64 {
1474        // 48-bit address space.
1475        (1u64 << 48) - 1
1476    }
1477
1478    fn translate<R>(
1479        &self,
1480        rid: u16,
1481        iova: u64,
1482        write: bool,
1483        op: impl FnOnce(u64) -> R,
1484    ) -> Result<R, iommu_common::TranslationFault<VtdFault>> {
1485        self.translate_with_capabilities(rid, iova, write, EcapReg::from(ECAP_VALUE), op)
1486    }
1487}
1488
1489impl VtdTranslator {
1490    fn translate_with_capabilities<R>(
1491        &self,
1492        rid: u16,
1493        iova: u64,
1494        write: bool,
1495        ecap: EcapReg,
1496        op: impl FnOnce(u64) -> R,
1497    ) -> Result<R, iommu_common::TranslationFault<VtdFault>> {
1498        let bus = (rid >> 8) as u8;
1499        let devfn = rid as u8;
1500        self.translate_with(
1501            iova,
1502            write,
1503            |state| {
1504                self.shared
1505                    .translate_locked(state, bus, devfn, iova, write, ecap)
1506            },
1507            op,
1508        )
1509    }
1510
1511    fn translate_with<R>(
1512        &self,
1513        iova: u64,
1514        write: bool,
1515        translate: impl FnOnce(&VtdState) -> Result<u64, VtdFault>,
1516        op: impl FnOnce(u64) -> R,
1517    ) -> Result<R, iommu_common::TranslationFault<VtdFault>> {
1518        // Serialize translate + op against invalidation, not guest PTE writes.
1519        let state = self.shared.state.read();
1520        let gpa = match translate(&state) {
1521            Ok(gpa) => gpa,
1522            Err(fault) => {
1523                // Drop the read lock before acquiring write lock for fault recording.
1524                drop(state);
1525                fault.record(&self.shared, write);
1526                return Err(iommu_common::TranslationFault { iova, error: fault });
1527            }
1528        };
1529
1530        let result = op(gpa);
1531        drop(state);
1532        Ok(result)
1533    }
1534}
1535
1536// =============================================================================
1537// VtdSignalMsi — MSI remapping wrapper (1G.3)
1538// =============================================================================
1539
1540/// MSI remapping wrapper for Intel VT-d interrupt remapping.
1541///
1542/// Wraps an inner `SignalMsi` and intercepts MSI writes to remap them
1543/// through the Interrupt Remapping Table.
1544pub struct VtdSignalMsi {
1545    shared: Arc<VtdSharedState>,
1546    inner: Arc<dyn SignalMsi>,
1547}
1548
1549impl SignalMsi for VtdSignalMsi {
1550    fn signal_msi(&self, devid: Option<u32>, address: u64, data: u32) {
1551        let Some(device_id) = devid else {
1552            // No source ID — drop the MSI. Without a BDF, source validation
1553            // and IRTE lookup are impossible.
1554            return;
1555        };
1556        let source_id = device_id as u16;
1557
1558        let state = self.shared.state.read();
1559        match self
1560            .shared
1561            .remap_msi_locked(&state, source_id, address, data)
1562        {
1563            Ok((new_address, new_data)) => {
1564                drop(state);
1565                self.inner.signal_msi(devid, new_address, new_data);
1566            }
1567            Err(fault) => {
1568                drop(state);
1569                tracelimit::warn_ratelimited!(
1570                    source_id,
1571                    address,
1572                    data,
1573                    error = &fault as &dyn std::error::Error,
1574                    "vtd: MSI remapping fault, interrupt dropped"
1575                );
1576                // MSI is a posted write transaction, so is_write=true.
1577                fault.record(&self.shared, true);
1578            }
1579        }
1580    }
1581}
1582
1583impl iommu_common::InterruptRemapper for VtdSharedState {
1584    fn remap_msi(&self, device_id: u16, address: u64, data: u32) -> Option<(u64, u32)> {
1585        let state = self.state.read();
1586        match self.remap_msi_locked(&state, device_id, address, data) {
1587            Ok(result) => Some(result),
1588            Err(fault) => {
1589                drop(state);
1590                // This runs at interrupt delivery time (the IOAPIC wiring
1591                // translates its routes lazily, on assertion), so a fault here
1592                // corresponds to an interrupt actually firing through a bad
1593                // entry. Record it, matching hardware which performs the IRTE
1594                // lookup and records faults at delivery time.
1595                tracelimit::warn_ratelimited!(
1596                    device_id,
1597                    address,
1598                    data,
1599                    error = &fault as &dyn std::error::Error,
1600                    "vtd: interrupt remapping fault on registered-route delivery, dropping interrupt"
1601                );
1602                fault.record(self, true);
1603                None
1604            }
1605        }
1606    }
1607
1608    fn register_route(&self, route: &Arc<dyn iommu_common::RetranslateInterrupts>) {
1609        self.retranslate_interrupts.register(route);
1610    }
1611
1612    fn unregister_route(&self, route: &Arc<dyn iommu_common::RetranslateInterrupts>) {
1613        self.retranslate_interrupts.unregister(route);
1614    }
1615}
1616
1617// =============================================================================
1618// IntelVtdDevice
1619// =============================================================================
1620
1621/// Intel VT-d IOMMU emulator device.
1622///
1623/// A pure MMIO platform device (no PCI config space) discovered via the ACPI
1624/// DMAR table. Implements the VT-d register file for IOMMU control, DMA
1625/// translation, interrupt remapping, invalidation queue, and fault recording.
1626pub struct IntelVtdDevice {
1627    /// Fixed MMIO base address.
1628    mmio_base: u64,
1629    /// Static region descriptor for MmioIntercept.
1630    mmio_region: (&'static str, RangeInclusive<u64>),
1631    /// Shared IOMMU state (accessible by per-device wrappers).
1632    shared: Arc<VtdSharedState>,
1633}
1634
1635impl IntelVtdDevice {
1636    /// Create a new Intel VT-d IOMMU device.
1637    ///
1638    /// `guest_memory` is used for reading root/context/page tables and IRT.
1639    /// `signal_msi` is the partition's MSI delivery handle — used for the
1640    /// IOMMU's own fault event and invalidation completion interrupts.
1641    pub fn new(
1642        guest_memory: GuestMemory,
1643        config: IntelVtdConfig,
1644        signal_msi: Arc<dyn SignalMsi>,
1645    ) -> (Self, Arc<VtdSharedState>) {
1646        let mmio_base = config.mmio_base;
1647        let shared = Arc::new(VtdSharedState::new(guest_memory, signal_msi));
1648
1649        let device = Self {
1650            mmio_base,
1651            mmio_region: (
1652                "intel-vtd-mmio",
1653                mmio_base..=mmio_base + MMIO_REGION_SIZE - 1,
1654            ),
1655            shared: shared.clone(),
1656        };
1657
1658        (device, shared)
1659    }
1660
1661    /// Returns the shared IOMMU state for creating per-device wrappers.
1662    pub fn shared_state(&self) -> &Arc<VtdSharedState> {
1663        &self.shared
1664    }
1665
1666    // =========================================================================
1667    // MMIO Register Read (DWORD granularity)
1668    // =========================================================================
1669
1670    /// Read a 32-bit register value at a DWORD-aligned MMIO offset.
1671    ///
1672    /// All register reads go through this function. 64-bit reads are composed
1673    /// from two DWORD reads. This avoids alignment issues with 32-bit registers
1674    /// at non-8-byte-aligned offsets (e.g. GSTS at 0x01C, FSTS at 0x034).
1675    fn read_register_dword(&self, offset: u16) -> u32 {
1676        let state = self.shared.state.read();
1677        self.read_register_dword_locked(&state, offset)
1678    }
1679
1680    /// Read a DWORD register while already holding the state lock.
1681    fn read_register_dword_locked(&self, state: &VtdState, offset: u16) -> u32 {
1682        /// Extract the lo DWORD from a 64-bit value.
1683        fn lo(val: u64) -> u32 {
1684            val as u32
1685        }
1686        /// Extract the hi DWORD from a 64-bit value.
1687        fn hi(val: u64) -> u32 {
1688            (val >> 32) as u32
1689        }
1690
1691        match Reg(offset) {
1692            Reg::VER => VER_VALUE,
1693            Reg::CAP => lo(CAP_VALUE),
1694            Reg::CAP_HI => hi(CAP_VALUE),
1695            Reg::ECAP => lo(ECAP_VALUE),
1696            Reg::ECAP_HI => hi(ECAP_VALUE),
1697            Reg::GCMD => 0, // write-only
1698            Reg::GSTS => state.gsts.into_bits(),
1699            Reg::RTADDR => lo(state.rtaddr.into_bits()),
1700            Reg::RTADDR_HI => hi(state.rtaddr.into_bits()),
1701            Reg::CCMD => lo(state.ccmd.into_bits()),
1702            Reg::CCMD_HI => hi(state.ccmd.into_bits()),
1703            Reg::FSTS => self.read_fsts(state),
1704            Reg::FECTL => state.fectl.into_bits(),
1705            Reg::FEDATA => state.fedata,
1706            Reg::FEADDR => state.feaddr,
1707            Reg::FEUADDR => state.feuaddr,
1708            Reg::IQH => lo(state.iqh.into_bits()),
1709            Reg::IQH_HI => hi(state.iqh.into_bits()),
1710            Reg::IQT => lo(state.iqt.into_bits()),
1711            Reg::IQT_HI => hi(state.iqt.into_bits()),
1712            Reg::IQA => lo(state.iqa.into_bits()),
1713            Reg::IQA_HI => hi(state.iqa.into_bits()),
1714            Reg::ICS => state.ics.into_bits(),
1715            Reg::IECTL => state.iectl.into_bits(),
1716            Reg::IEDATA => state.iedata,
1717            Reg::IEADDR => state.ieaddr,
1718            Reg::IEUADDR => state.ieuaddr,
1719            Reg::IRTA => lo(state.irta.into_bits()),
1720            Reg::IRTA_HI => hi(state.irta.into_bits()),
1721            Reg::IVA => lo(state.iva),
1722            Reg::IVA_HI => hi(state.iva),
1723            Reg::IOTLB => lo(state.iotlb.into_bits()),
1724            Reg::IOTLB_HI => hi(state.iotlb.into_bits()),
1725            Reg::FRCD_DW0 => lo(state.frcd_lo.into_bits()),
1726            Reg::FRCD_DW1 => hi(state.frcd_lo.into_bits()),
1727            Reg::FRCD_DW2 => lo(state.frcd_hi.into_bits()),
1728            Reg::FRCD_DW3 => hi(state.frcd_hi.into_bits()),
1729            _ => 0,
1730        }
1731    }
1732
1733    /// Read FSTS with PPF dynamically computed as OR of FRCD[n].F bits.
1734    fn read_fsts(&self, state: &VtdState) -> u32 {
1735        let mut fsts = state.fsts;
1736        // PPF = OR of all FRCD[n].F bits. With NFR=0 (1 record), this
1737        // is just FRCD[0].F.
1738        fsts.set_ppf(state.frcd_hi.f());
1739        fsts.into_bits()
1740    }
1741
1742    /// Cancel an undelivered fault interrupt once all sources are serviced
1743    /// (§§7.3 and 11.4.7.2). Residual status must not re-latch a delivered event.
1744    fn reconcile_fault_interrupt(&self, state: &mut VtdState) {
1745        let fsts = FstsReg::from(self.read_fsts(state));
1746        if !fsts.ppf() && !fsts.pfo() && !fsts.iqe() && !fsts.ice() && !fsts.ite() {
1747            state.fectl.set_ip(false);
1748        }
1749    }
1750
1751    // =========================================================================
1752    // MMIO Register Write (DWORD granularity)
1753    // =========================================================================
1754
1755    /// Write a 32-bit value at a DWORD-aligned MMIO offset.
1756    ///
1757    /// Acquires the write lock, performs the register write, and releases it.
1758    /// 64-bit MMIO writes other than IQT call this twice. Command registers
1759    /// trigger on one DWORD and configuration registers are separately latched.
1760    /// IQT is handled atomically so an invalid upper half cannot be overlooked.
1761    fn write_register_dword(&mut self, offset: u16, value: u32) {
1762        let mut state = self.shared.state.write();
1763        let mut process_queue = false;
1764        tracing::trace!(offset, value, "vtd mmio_write_dword");
1765
1766        /// Merge a DWORD write into the lo or hi half of a 64-bit value.
1767        fn write_lo(old: u64, value: u32) -> u64 {
1768            (old & !0xFFFF_FFFF) | value as u64
1769        }
1770        fn write_hi(old: u64, value: u32) -> u64 {
1771            (old & 0xFFFF_FFFF) | ((value as u64) << 32)
1772        }
1773
1774        match Reg(offset) {
1775            // Read-only registers.
1776            Reg::VER
1777            | Reg::CAP
1778            | Reg::CAP_HI
1779            | Reg::ECAP
1780            | Reg::ECAP_HI
1781            | Reg::GSTS
1782            | Reg::IQH
1783            | Reg::IQH_HI
1784            | Reg::FRCD_DW0
1785            | Reg::FRCD_DW1
1786            | Reg::FRCD_DW2 => {}
1787
1788            Reg::GCMD => {
1789                self.process_gcmd(&mut state, value);
1790                process_queue = true;
1791            }
1792
1793            Reg::RTADDR => {
1794                state.rtaddr = RtaddrReg::from(write_lo(state.rtaddr.into_bits(), value));
1795            }
1796            Reg::RTADDR_HI => {
1797                state.rtaddr = RtaddrReg::from(write_hi(state.rtaddr.into_bits(), value));
1798            }
1799
1800            Reg::CCMD => {
1801                state.ccmd = CcmdReg::from(write_lo(state.ccmd.into_bits(), value));
1802            }
1803            Reg::CCMD_HI => {
1804                // ICC is bit 63 — process on hi DWORD write.
1805                let full = write_hi(state.ccmd.into_bits(), value);
1806                self.process_ccmd(&mut state, full);
1807            }
1808
1809            Reg::FSTS => {
1810                let write_val = FstsReg::from(value);
1811                let mut fsts = state.fsts;
1812                if write_val.pfo() {
1813                    fsts.set_pfo(false);
1814                }
1815                if write_val.iqe() {
1816                    fsts.set_iqe(false);
1817                }
1818                if write_val.ice() {
1819                    fsts.set_ice(false);
1820                }
1821                if write_val.ite() {
1822                    fsts.set_ite(false);
1823                }
1824                state.fsts = fsts;
1825                self.reconcile_fault_interrupt(&mut state);
1826                process_queue = write_val.iqe() || write_val.ite();
1827            }
1828
1829            Reg::FECTL => {
1830                let new = FectlReg::from(value);
1831                let old = state.fectl;
1832                state.fectl = FectlReg::new().with_im(new.im()).with_ip(old.ip());
1833                if old.im() && !new.im() && old.ip() {
1834                    state.fectl = state.fectl.with_ip(false);
1835                    self.shared.deliver_fault_interrupt(&state);
1836                }
1837            }
1838
1839            Reg::FEDATA => state.fedata = value,
1840            Reg::FEADDR => state.feaddr = value,
1841            Reg::FEUADDR => state.feuaddr = value,
1842
1843            Reg::IQT => {
1844                state.iqt = IqtReg::from(write_lo(state.iqt.into_bits(), value));
1845                process_queue = true;
1846            }
1847            Reg::IQT_HI => {
1848                state.iqt = IqtReg::from(write_hi(state.iqt.into_bits(), value));
1849                process_queue = true;
1850            }
1851
1852            Reg::IQA => {
1853                if !state.gsts.qies() {
1854                    state.iqa = IqaReg::from(write_lo(state.iqa.into_bits(), value));
1855                } else {
1856                    tracelimit::warn_ratelimited!("vtd: write to IQA while QIE=1, ignored");
1857                }
1858            }
1859            Reg::IQA_HI => {
1860                if !state.gsts.qies() {
1861                    state.iqa = IqaReg::from(write_hi(state.iqa.into_bits(), value));
1862                } else {
1863                    tracelimit::warn_ratelimited!("vtd: write to IQA while QIE=1, ignored");
1864                }
1865            }
1866
1867            Reg::ICS => {
1868                let write_val = IcsReg::from(value);
1869                let mut ics = state.ics;
1870                if write_val.iwc() {
1871                    ics.set_iwc(false);
1872                    state.iectl.set_ip(false);
1873                }
1874                state.ics = ics;
1875            }
1876
1877            Reg::IECTL => {
1878                let new = IectlReg::from(value);
1879                let old = state.iectl;
1880                state.iectl = IectlReg::new().with_im(new.im()).with_ip(old.ip());
1881                if old.im() && !new.im() && old.ip() {
1882                    state.iectl = state.iectl.with_ip(false);
1883                    self.shared.deliver_invalidation_interrupt(&state);
1884                }
1885            }
1886
1887            Reg::IEDATA => state.iedata = value,
1888            Reg::IEADDR => state.ieaddr = value,
1889            Reg::IEUADDR => state.ieuaddr = value,
1890
1891            Reg::IRTA => {
1892                if !state.gsts.ires() {
1893                    state.irta = IrtaReg::from(write_lo(state.irta.into_bits(), value));
1894                } else {
1895                    tracelimit::warn_ratelimited!("vtd: write to IRTA while IRE=1, ignored");
1896                }
1897            }
1898            Reg::IRTA_HI => {
1899                if !state.gsts.ires() {
1900                    state.irta = IrtaReg::from(write_hi(state.irta.into_bits(), value));
1901                } else {
1902                    tracelimit::warn_ratelimited!("vtd: write to IRTA while IRE=1, ignored");
1903                }
1904            }
1905
1906            Reg::IVA => state.iva = write_lo(state.iva, value),
1907            Reg::IVA_HI => state.iva = write_hi(state.iva, value),
1908
1909            Reg::IOTLB => {
1910                state.iotlb = IotlbReg::from(write_lo(state.iotlb.into_bits(), value));
1911            }
1912            Reg::IOTLB_HI => {
1913                // IVT is bit 63 — process on hi DWORD write.
1914                let full = write_hi(state.iotlb.into_bits(), value);
1915                self.process_iotlb_reg(&mut state, full);
1916            }
1917
1918            Reg::FRCD_DW3 => {
1919                // F bit (bit 31 of this DWORD = bit 63 of FRCD_HI) is RW1C.
1920                if (value >> 31) & 1 != 0 {
1921                    state.frcd_hi = state.frcd_hi.with_f(false);
1922                    self.reconcile_fault_interrupt(&mut state);
1923                }
1924            }
1925
1926            _ => {} // Unmapped offsets: silently ignored.
1927        }
1928
1929        drop(state);
1930        if process_queue {
1931            self.process_invalidation_queue();
1932        }
1933    }
1934
1935    // =========================================================================
1936    // GCMD Processing (1B.2)
1937    // =========================================================================
1938
1939    /// Process a write to the Global Command Register (GCMD).
1940    ///
1941    /// GCMD is write-only. Each bit triggers an action; status is reflected
1942    /// in GSTS. Toggle bits (TE, QIE, IRE, CFI) compare against current GSTS.
1943    /// One-shot bits (SRTP, SIRTP, WBF) fire if set.
1944    fn process_gcmd(&self, state: &mut VtdState, value: u32) {
1945        let gcmd = GcmdReg::from(value);
1946        let mut gsts = state.gsts;
1947
1948        // -- One-shot: Set Root Table Pointer (SRTP) --
1949        if gcmd.srtp() {
1950            state.latched_rtaddr = state.rtaddr;
1951            gsts.set_rtps(true);
1952        }
1953
1954        // -- One-shot: Set Interrupt Remapping Table Pointer (SIRTP) --
1955        if gcmd.sirtp() {
1956            state.latched_irta = state.irta;
1957            gsts.set_irtps(true);
1958        }
1959
1960        // -- One-shot: Write Buffer Flush (WBF) --
1961        if gcmd.wbf() {
1962            // No write buffer in emulator — set status immediately.
1963            gsts.set_wbfs(true);
1964        }
1965
1966        // -- One-shot: Set Fault Log / Enable Advanced Fault Logging --
1967        // AFL=0 in CAP, so these are no-ops, but set status for compatibility.
1968        if gcmd.sfl() {
1969            gsts.set_fls(true);
1970        }
1971        if gcmd.eafl() {
1972            gsts.set_afls(true);
1973        }
1974
1975        // -- Toggle: Queued Invalidation Enable (QIE) --
1976        if gcmd.qie() != gsts.qies() {
1977            if gcmd.qie() {
1978                // Enable QI.
1979                gsts.set_qies(true);
1980                // Reset head on enable.
1981                state.iqh = IqhReg::new();
1982                state.invalidation_queue_last_wait = false;
1983            } else {
1984                // VT-d 6.5.2 requires a drained queue ending in a wait, not TE/IRE off.
1985                if state.iqh.head_offset() != state.iqt.tail_offset()
1986                    || !state.invalidation_queue_last_wait
1987                    || state.fsts.iqe()
1988                {
1989                    tracelimit::warn_ratelimited!(
1990                        head = state.iqh.head_offset(),
1991                        tail = state.iqt.tail_offset(),
1992                        last_wait = state.invalidation_queue_last_wait,
1993                        iqe = state.fsts.iqe(),
1994                        "vtd: cannot disable QIE before invalidation queue is quiescent"
1995                    );
1996                } else {
1997                    tracelimit::info_ratelimited!(
1998                        te = gsts.tes(),
1999                        ire = gsts.ires(),
2000                        head = state.iqh.head_offset(),
2001                        tail = state.iqt.tail_offset(),
2002                        "vtd: disabling QIE after completed invalidation wait"
2003                    );
2004                    gsts.set_qies(false);
2005                    state.iqh = IqhReg::new();
2006                }
2007            }
2008        }
2009
2010        // -- Toggle: Translation Enable (TE) --
2011        if gcmd.te() != gsts.tes() {
2012            if gcmd.te() {
2013                // Enable TE — reject if RTPS=0.
2014                if !gsts.rtps() {
2015                    tracelimit::warn_ratelimited!(
2016                        "vtd: cannot enable TE without root table pointer set (RTPS=0)"
2017                    );
2018                } else {
2019                    gsts.set_tes(true);
2020                }
2021            } else {
2022                gsts.set_tes(false);
2023            }
2024        }
2025
2026        // -- Toggle: Interrupt Remapping Enable (IRE) --
2027        if gcmd.ire() != gsts.ires() {
2028            if gcmd.ire() {
2029                // Enable IRE — reject if IRTPS=0.
2030                if !gsts.irtps() {
2031                    tracelimit::warn_ratelimited!(
2032                        "vtd: cannot enable IRE without IRT pointer set (IRTPS=0)"
2033                    );
2034                } else {
2035                    gsts.set_ires(true);
2036                }
2037            } else {
2038                gsts.set_ires(false);
2039            }
2040        }
2041
2042        // -- Toggle: Compatibility Format Interrupt (CFI) --
2043        if gcmd.cfi() != gsts.cfis() {
2044            gsts.set_cfis(gcmd.cfi());
2045        }
2046
2047        state.gsts = gsts;
2048    }
2049
2050    // =========================================================================
2051    // Register-based invalidation (pre-QI)
2052    // =========================================================================
2053
2054    /// Process a write to the Context Command Register (CCMD).
2055    ///
2056    /// Register-based context-cache invalidation. Linux writes this during
2057    /// early init before QI is enabled. No-op since we don't cache.
2058    fn process_ccmd(&self, state: &mut VtdState, value: u64) {
2059        let ccmd = CcmdReg::from(value);
2060        if ccmd.icc() {
2061            // Clear ICC, set CAIG = CIRG (echo back granularity).
2062            state.ccmd = ccmd.with_icc(false).with_caig(ccmd.cirg());
2063        } else {
2064            state.ccmd = CcmdReg::from(value);
2065        }
2066    }
2067
2068    /// Process a write to the IOTLB Invalidate Register (0x108).
2069    ///
2070    /// Register-based IOTLB invalidation. No-op since we don't cache.
2071    fn process_iotlb_reg(&self, state: &mut VtdState, value: u64) {
2072        let reg = IotlbReg::from(value);
2073        if reg.ivt() {
2074            // Clear IVT and echo IAIG = IIRG.
2075            state.iotlb = reg.with_ivt(false).with_iaig(reg.iirg());
2076        } else {
2077            state.iotlb = IotlbReg::from(value);
2078        }
2079    }
2080
2081    // =========================================================================
2082    // Invalidation Queue Processing (1C)
2083    // =========================================================================
2084
2085    /// Process the invalidation queue.
2086    ///
2087    /// Queue execution is serialized by exclusive access to the device. The
2088    /// state lock is also a DMA drain point: translators hold it across the
2089    /// translation and the entire memory operation.
2090    fn process_invalidation_queue(&mut self) {
2091        let cap = CapReg::from(CAP_VALUE);
2092        let ecap = EcapReg::from(ECAP_VALUE);
2093        let mut state = self.shared.state.write();
2094        if !state.gsts.qies() || state.fsts.iqe() || state.fsts.ite() {
2095            return;
2096        }
2097        let mut queue = match InvalidationQueue::new(&state, ecap) {
2098            Ok(queue) => queue,
2099            Err(err) => {
2100                tracelimit::warn_ratelimited!(
2101                    error = &err as &dyn std::error::Error,
2102                    "vtd: invalid queue"
2103                );
2104                self.invalidation_queue_error(&mut state);
2105                return;
2106            }
2107        };
2108        let mode = TranslationTableMode(state.latched_rtaddr.ttm());
2109        // Both offsets have been checked against the size and stride. Bound
2110        // the work explicitly rather than chasing an unchecked guest tail.
2111        for _ in 0..queue.pending {
2112            let entry_addr = queue.base + queue.head;
2113            let mut desc = InvalidationDescriptor256::new_zeroed();
2114            if let Err(err) = self
2115                .shared
2116                .guest_memory
2117                .read_at(entry_addr, &mut desc.as_mut_bytes()[..queue.width.bytes()])
2118            {
2119                tracelimit::warn_ratelimited!(
2120                    error = &err as &dyn std::error::Error,
2121                    addr = entry_addr,
2122                    "vtd: failed to read invalidation queue descriptor"
2123                );
2124                self.invalidation_queue_error(&mut state);
2125                break;
2126            }
2127            if let Err(err) = desc.validate(queue.width, mode, cap, ecap) {
2128                tracelimit::warn_ratelimited!(
2129                    error = &err as &dyn std::error::Error,
2130                    addr = entry_addr,
2131                    "vtd: invalid invalidation descriptor"
2132                );
2133                self.invalidation_queue_error(&mut state);
2134                break;
2135            }
2136            match desc.lower.descriptor_type() {
2137                DescriptorType::CONTEXT_CACHE_INVALIDATE
2138                | DescriptorType::IOTLB_INVALIDATE
2139                | DescriptorType::PASID_CACHE_INVALIDATE
2140                | DescriptorType::PASID_IOTLB_INVALIDATE => {
2141                    // No translation caches. Acquiring the exclusive state
2142                    // lock drains all earlier DMA reads and writes.
2143                }
2144                DescriptorType::INTERRUPT_ENTRY_CACHE_INVALIDATE => {
2145                    let desc = spec::invalidation::parse_interrupt_cache_invalidate(&desc.lower);
2146                    tracing::trace!(
2147                        granularity = desc.granularity(),
2148                        im = desc.im(),
2149                        iidx = desc.iidx(),
2150                        "vtd: interrupt entry cache invalidate"
2151                    );
2152                    // Callbacks may read translation state or record faults.
2153                    // Finish them before advancing to a wait, without holding
2154                    // the state lock they may reacquire. &mut self prevents a
2155                    // second MMIO writer/queue executor from overtaking us.
2156                    RwLockWriteGuard::unlocked(&mut state, || {
2157                        self.shared.retranslate_interrupts.invalidate(None);
2158                    });
2159                }
2160                DescriptorType::INVALIDATION_WAIT => {
2161                    let (lo, hi) = spec::invalidation::parse_invalidation_wait(&desc.lower);
2162                    if !self.process_invalidation_wait(&mut state, lo, hi) {
2163                        break;
2164                    }
2165                }
2166                dt => {
2167                    tracelimit::warn_ratelimited!(?dt, "vtd: unknown invalidation descriptor type");
2168                    self.invalidation_queue_error(&mut state);
2169                    break;
2170                }
2171            }
2172
2173            state.invalidation_queue_last_wait =
2174                desc.lower.descriptor_type() == DescriptorType::INVALIDATION_WAIT;
2175
2176            // Advance head with wrap-around.
2177            queue.head = (queue.head + queue.width.bytes() as u64) % queue.size;
2178            state.iqh = IqhReg::from(queue.head);
2179        }
2180    }
2181
2182    fn invalidation_queue_error(&self, state: &mut VtdState) {
2183        state.fsts.set_iqe(true);
2184        if state.fectl.im() {
2185            state.fectl.set_ip(true);
2186        } else {
2187            self.shared.deliver_fault_interrupt(state);
2188        }
2189    }
2190
2191    /// Process an INVALIDATION_WAIT descriptor (type 0x05).
2192    fn process_invalidation_wait(
2193        &self,
2194        state: &mut VtdState,
2195        lo: InvalidationWaitDw0Dw1,
2196        hi: InvalidationWaitDw2Dw3,
2197    ) -> bool {
2198        if lo.sw() {
2199            let status_address = hi.status_address();
2200
2201            if let Err(e) = self
2202                .shared
2203                .guest_memory
2204                .write_at(status_address, &lo.status_data().to_le_bytes())
2205            {
2206                tracelimit::warn_ratelimited!(
2207                    error = &e as &dyn std::error::Error,
2208                    addr = status_address,
2209                    "vtd: failed to write invalidation wait status"
2210                );
2211                // Do not manufacture a completion when its status write failed.
2212                self.invalidation_queue_error(state);
2213                return false;
2214            }
2215        }
2216
2217        if lo.iflag() && !state.ics.iwc() {
2218            // Set IWC in ICS.
2219            let mut ics = state.ics;
2220            ics.set_iwc(true);
2221            state.ics = ics;
2222
2223            // Signal invalidation completion interrupt.
2224            let iectl = state.iectl;
2225            if !iectl.im() {
2226                self.shared.deliver_invalidation_interrupt(state);
2227            } else {
2228                // Masked — set IP.
2229                state.iectl = state.iectl.with_ip(true);
2230            }
2231        }
2232        // Sequential execution is stronger than FN=0 requires, and satisfies
2233        // FN=1 without letting later descriptors pass this completion.
2234        true
2235    }
2236}
2237
2238// =============================================================================
2239// ChipsetDevice trait implementation
2240// =============================================================================
2241
2242impl ChipsetDevice for IntelVtdDevice {
2243    fn supports_mmio(&mut self) -> Option<&mut dyn MmioIntercept> {
2244        Some(self)
2245    }
2246}
2247
2248// =============================================================================
2249// MMIO Register Access
2250// =============================================================================
2251
2252impl MmioIntercept for IntelVtdDevice {
2253    fn mmio_read(&mut self, addr: u64, data: &mut [u8]) -> IoResult {
2254        let offset = addr - self.mmio_base;
2255
2256        // VT-d supports 4-byte and 8-byte naturally aligned accesses.
2257        match data.len() {
2258            8 => {
2259                // Acquire the read lock once for both DWORD reads to avoid
2260                // a torn read if a writer intervenes between the two halves.
2261                let state = self.shared.state.read();
2262                let lo = self.read_register_dword_locked(&state, offset as u16);
2263                let hi = self.read_register_dword_locked(&state, (offset + 4) as u16);
2264                let val = lo as u64 | ((hi as u64) << 32);
2265                data.copy_from_slice(&val.to_le_bytes());
2266            }
2267            4 => {
2268                let val = self.read_register_dword(offset as u16);
2269                data.copy_from_slice(&val.to_le_bytes());
2270            }
2271            _ => {
2272                tracelimit::warn_ratelimited!(
2273                    addr,
2274                    len = data.len(),
2275                    "vtd: unsupported MMIO read size"
2276                );
2277                data.fill(0xff);
2278                return IoResult::Err(IoError::InvalidAccessSize);
2279            }
2280        }
2281
2282        IoResult::Ok
2283    }
2284
2285    fn mmio_write(&mut self, addr: u64, data: &[u8]) -> IoResult {
2286        let offset = addr - self.mmio_base;
2287
2288        match data.len() {
2289            8 => {
2290                let val = u64::from_le_bytes(data.try_into().unwrap());
2291                if offset == u64::from(Reg::IQT.0) {
2292                    // Validate the complete tail before fetching anything.
2293                    self.shared.state.write().iqt = IqtReg::from(val);
2294                    self.process_invalidation_queue();
2295                } else {
2296                    self.write_register_dword(offset as u16, val as u32);
2297                    self.write_register_dword((offset + 4) as u16, (val >> 32) as u32);
2298                }
2299            }
2300            4 => {
2301                let val = u32::from_le_bytes(data.try_into().unwrap());
2302                self.write_register_dword(offset as u16, val);
2303            }
2304            _ => {
2305                tracelimit::warn_ratelimited!(
2306                    addr,
2307                    len = data.len(),
2308                    "vtd: unsupported MMIO write size"
2309                );
2310                return IoResult::Err(IoError::InvalidAccessSize);
2311            }
2312        }
2313
2314        IoResult::Ok
2315    }
2316
2317    fn get_static_regions(&mut self) -> &[(&str, RangeInclusive<u64>)] {
2318        std::slice::from_ref(&self.mmio_region)
2319    }
2320}
2321
2322// =============================================================================
2323// ChangeDeviceState
2324// =============================================================================
2325
2326impl vmcore::device_state::ChangeDeviceState for IntelVtdDevice {
2327    fn start(&mut self) {}
2328
2329    async fn stop(&mut self) {}
2330
2331    async fn reset(&mut self) {
2332        let mut state = self.shared.state.write();
2333        *state = VtdState::new();
2334    }
2335}
2336
2337// =============================================================================
2338// SaveRestore (stub)
2339// =============================================================================
2340
2341impl vmcore::save_restore::SaveRestore for IntelVtdDevice {
2342    type SavedState = vmcore::save_restore::SavedStateNotSupported;
2343
2344    fn save(&mut self) -> Result<Self::SavedState, vmcore::save_restore::SaveError> {
2345        Err(vmcore::save_restore::SaveError::NotSupported)
2346    }
2347
2348    fn restore(
2349        &mut self,
2350        state: Self::SavedState,
2351    ) -> Result<(), vmcore::save_restore::RestoreError> {
2352        match state {}
2353    }
2354}
2355
2356// =============================================================================
2357// InspectMut
2358// =============================================================================
2359
2360impl InspectMut for IntelVtdDevice {
2361    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
2362        let state = self.shared.state.read();
2363        let gsts = state.gsts;
2364        req.respond()
2365            .hex("mmio_base", self.mmio_base)
2366            .field("translation_enabled", gsts.tes())
2367            .field("ir_enabled", gsts.ires())
2368            .field("qi_enabled", gsts.qies())
2369            .field("fault_status", self.read_fsts(&state))
2370            .field("translation_table_mode", state.latched_rtaddr.ttm())
2371            .field(
2372                "queue_descriptor_bits",
2373                if state.iqa.dw() { 256u16 } else { 128 },
2374            )
2375            .hex("root_table_addr", state.latched_rtaddr.root_table_address())
2376            .hex("irt_addr", state.latched_irta.irt_base_address())
2377            .field("state", &*state);
2378    }
2379}
2380
2381// =============================================================================
2382// Tests
2383// =============================================================================
2384
2385#[cfg(test)]
2386mod tests {
2387    mod accessed_dirty;
2388    mod queued_invalidation;
2389    mod scalable_fixture;
2390    mod scalable_translation;
2391
2392    use super::*;
2393    use guestmem::GuestMemory;
2394    use std::sync::atomic::AtomicU32;
2395    use std::sync::atomic::Ordering;
2396    use test_with_tracing::test;
2397
2398    const TEST_MMIO_BASE: u64 = 0xFED9_0000;
2399
2400    struct TestSignalMsi;
2401    impl SignalMsi for TestSignalMsi {
2402        fn signal_msi(&self, _devid: Option<u32>, _address: u64, _data: u32) {}
2403    }
2404
2405    fn create_test_device() -> IntelVtdDevice {
2406        let gm = GuestMemory::empty();
2407        let signal_msi = Arc::new(TestSignalMsi);
2408        let (device, _shared) = IntelVtdDevice::new(
2409            gm,
2410            IntelVtdConfig {
2411                mmio_base: TEST_MMIO_BASE,
2412            },
2413            signal_msi,
2414        );
2415        device
2416    }
2417
2418    /// Helper to read a 32-bit register.
2419    fn read32(dev: &mut IntelVtdDevice, reg_offset: u16) -> u32 {
2420        let mut data = [0u8; 4];
2421        let result = dev.mmio_read(TEST_MMIO_BASE + reg_offset as u64, &mut data);
2422        assert!(matches!(result, IoResult::Ok));
2423        u32::from_le_bytes(data)
2424    }
2425
2426    /// Helper to write a 32-bit register.
2427    fn write32(dev: &mut IntelVtdDevice, reg_offset: u16, value: u32) {
2428        let data = value.to_le_bytes();
2429        let result = dev.mmio_write(TEST_MMIO_BASE + reg_offset as u64, &data);
2430        assert!(matches!(result, IoResult::Ok));
2431    }
2432
2433    /// Helper to read a 64-bit register.
2434    fn read64(dev: &mut IntelVtdDevice, reg_offset: u16) -> u64 {
2435        let mut data = [0u8; 8];
2436        let result = dev.mmio_read(TEST_MMIO_BASE + reg_offset as u64, &mut data);
2437        assert!(matches!(result, IoResult::Ok));
2438        u64::from_le_bytes(data)
2439    }
2440
2441    /// Helper to write a 64-bit register.
2442    fn write64(dev: &mut IntelVtdDevice, reg_offset: u16, value: u64) {
2443        let data = value.to_le_bytes();
2444        let result = dev.mmio_write(TEST_MMIO_BASE + reg_offset as u64, &data);
2445        assert!(matches!(result, IoResult::Ok));
2446    }
2447
2448    #[test]
2449    fn test_ver_register() {
2450        let mut dev = create_test_device();
2451        let ver = read32(&mut dev, 0x000);
2452        let ver_reg = VersionReg::from(ver);
2453        assert_eq!(ver_reg.max(), 1);
2454        assert_eq!(ver_reg.min(), 0);
2455    }
2456
2457    #[test]
2458    fn test_inspect_reports_latched_mode_not_pending_rtaddr() {
2459        let mut dev = create_test_device();
2460        let mode = |dev: &mut IntelVtdDevice| {
2461            inspect::inspect("translation_table_mode", dev)
2462                .results()
2463                .to_string()
2464        };
2465        assert_eq!(mode(&mut dev), "0");
2466        write64(&mut dev, 0x020, 0x1000 | (1 << 10));
2467        assert_eq!(mode(&mut dev), "0");
2468        write32(&mut dev, 0x018, 1 << 30);
2469        assert_eq!(mode(&mut dev), "1");
2470        write64(&mut dev, 0x020, 0x2000);
2471        assert_eq!(mode(&mut dev), "1");
2472        write32(&mut dev, 0x018, 1 << 30);
2473        assert_eq!(mode(&mut dev), "0");
2474    }
2475
2476    #[test]
2477    fn test_cap_register() {
2478        let mut dev = create_test_device();
2479        let cap = read64(&mut dev, 0x008);
2480        let cap_reg = CapReg::from(cap);
2481        assert_eq!(cap_reg.mgaw(), 47); // 48-bit
2482        assert_eq!(cap_reg.sagaw(), 0x6); // 39-bit + 48-bit
2483        assert_eq!(cap_reg.nfr(), 0); // 1 fault record
2484        assert_eq!(cap_reg.fro(), 0x12); // 0x120
2485        assert_eq!(cap_reg.sllps(), 0x3); // 2MB + 1GB
2486        assert!(cap_reg.dwd());
2487        assert!(cap_reg.drd());
2488        assert!(!cap_reg.cm());
2489        assert_eq!(cap_reg.nd(), 6);
2490    }
2491
2492    #[test]
2493    fn test_ecap_register() {
2494        let mut dev = create_test_device();
2495        let ecap = read64(&mut dev, 0x010);
2496        let ecap_reg = EcapReg::from(ecap);
2497        assert!(ecap_reg.c());
2498        assert!(ecap_reg.qi());
2499        assert!(ecap_reg.ir());
2500        assert!(ecap_reg.eim());
2501        assert_eq!(ecap_reg.iro(), 0x10); // 0x100
2502        assert_eq!(ecap_reg.mhmv(), 0xF);
2503        assert!(ecap_reg.smts());
2504        assert!(ecap_reg.ssts());
2505        assert!(ecap_reg.ssads());
2506        assert!(ecap_reg.smpwcs());
2507        assert!(ecap_reg.rps());
2508        assert!(!ecap_reg.flts());
2509        assert!(!ecap_reg.eafs());
2510        assert!(!ecap_reg.nest());
2511        assert!(!ecap_reg.pasid());
2512        assert!(!ecap_reg.dt());
2513        assert!(!ecap_reg.prs());
2514        assert!(!ecap_reg.srs());
2515        assert_eq!(ecap, 0x0003_6800_00f0_10db);
2516    }
2517
2518    #[test]
2519    fn test_gcmd_read_returns_zero() {
2520        let mut dev = create_test_device();
2521        assert_eq!(read32(&mut dev, 0x018), 0);
2522    }
2523
2524    #[test]
2525    fn test_gsts_initial() {
2526        let mut dev = create_test_device();
2527        let gsts = read32(&mut dev, 0x01C);
2528        assert_eq!(gsts, 0); // All disabled initially
2529    }
2530
2531    #[test]
2532    fn test_srtp_and_te_enable() {
2533        let mut dev = create_test_device();
2534
2535        // Write RTADDR.
2536        let root_table_addr = 0x1000_0000u64;
2537        write64(&mut dev, 0x020, root_table_addr);
2538        assert_eq!(read64(&mut dev, 0x020), root_table_addr);
2539
2540        // GCMD: SRTP (bit 30).
2541        write32(&mut dev, 0x018, GcmdReg::new().with_srtp(true).into_bits());
2542        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2543        assert!(gsts.rtps());
2544
2545        // GCMD: TE (bit 31).
2546        write32(&mut dev, 0x018, GcmdReg::new().with_te(true).into_bits());
2547        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2548        assert!(gsts.tes());
2549    }
2550
2551    #[test]
2552    fn test_te_rejected_without_rtps() {
2553        let mut dev = create_test_device();
2554
2555        // Try to enable TE without setting root table pointer.
2556        write32(&mut dev, 0x018, GcmdReg::new().with_te(true).into_bits());
2557        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2558        assert!(!gsts.tes()); // Should be rejected
2559    }
2560
2561    #[test]
2562    fn test_ire_rejected_without_irtps() {
2563        let mut dev = create_test_device();
2564
2565        // Try to enable IRE without setting IRT pointer.
2566        write32(&mut dev, 0x018, GcmdReg::new().with_ire(true).into_bits());
2567        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2568        assert!(!gsts.ires()); // Should be rejected
2569    }
2570
2571    #[test]
2572    fn test_sirtp_and_ire_enable() {
2573        let mut dev = create_test_device();
2574
2575        // Write IRTA.
2576        let irt_addr = 0x2000_0000u64;
2577        write64(&mut dev, 0x0B8, irt_addr);
2578        assert_eq!(read64(&mut dev, 0x0B8), irt_addr);
2579
2580        // GCMD: SIRTP.
2581        write32(&mut dev, 0x018, GcmdReg::new().with_sirtp(true).into_bits());
2582        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2583        assert!(gsts.irtps());
2584
2585        // GCMD: IRE.
2586        write32(&mut dev, 0x018, GcmdReg::new().with_ire(true).into_bits());
2587        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2588        assert!(gsts.ires());
2589    }
2590
2591    #[test]
2592    fn test_wbf() {
2593        let mut dev = create_test_device();
2594
2595        // GCMD: WBF (bit 27).
2596        write32(&mut dev, 0x018, GcmdReg::new().with_wbf(true).into_bits());
2597        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2598        assert!(gsts.wbfs());
2599    }
2600
2601    #[test]
2602    fn test_qie_enable_disable() {
2603        for (te, ire) in [(true, true), (true, false), (false, true), (false, false)] {
2604            let gm = GuestMemory::allocate(0x4000);
2605            let (mut dev, _) = IntelVtdDevice::new(
2606                gm.clone(),
2607                IntelVtdConfig {
2608                    mmio_base: TEST_MMIO_BASE,
2609                },
2610                Arc::new(TestSignalMsi),
2611            );
2612            write64(&mut dev, 0x090, 0x1000);
2613            let enabled = GcmdReg::new().with_qie(true).with_te(te).with_ire(ire);
2614            write32(
2615                &mut dev,
2616                0x018,
2617                enabled.with_srtp(true).with_sirtp(true).into_bits(),
2618            );
2619            assert!(GstsReg::from(read32(&mut dev, 0x01C)).qies());
2620
2621            let wait = spec::invalidation::InvalidationDescriptor {
2622                dw0: DescriptorType::INVALIDATION_WAIT.0 as u32,
2623                dw1: 0,
2624                dw2: 0,
2625                dw3: 0,
2626            };
2627            gm.write_at(0x1000, wait.as_bytes()).unwrap();
2628            write64(&mut dev, 0x088, IqtReg::new().with_qt(1).into_bits());
2629            assert_eq!(IqhReg::from(read64(&mut dev, 0x080)).head_offset(), 16);
2630            write32(&mut dev, 0x018, enabled.with_qie(false).into_bits());
2631            let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2632            assert!(!gsts.qies(), "QI disable rejected with TE={te}, IRE={ire}");
2633            assert_eq!(gsts.tes(), te);
2634            assert_eq!(gsts.ires(), ire);
2635            assert_eq!(read64(&mut dev, 0x080), 0);
2636        }
2637    }
2638
2639    #[test]
2640    fn test_qie_disable_requires_quiescent_queue() {
2641        let gm = GuestMemory::allocate(0x4000);
2642        let (mut dev, _) = IntelVtdDevice::new(
2643            gm.clone(),
2644            IntelVtdConfig {
2645                mmio_base: TEST_MMIO_BASE,
2646            },
2647            Arc::new(TestSignalMsi),
2648        );
2649        write64(&mut dev, 0x090, 0x1000);
2650        let enabled = GcmdReg::new().with_qie(true).into_bits();
2651        write32(&mut dev, 0x018, enabled);
2652        write32(&mut dev, 0x018, 0);
2653        assert!(GstsReg::from(read32(&mut dev, 0x01C)).qies());
2654
2655        for (index, kind) in [
2656            DescriptorType::INVALIDATION_WAIT,
2657            DescriptorType::IOTLB_INVALIDATE,
2658            DescriptorType::INVALIDATION_WAIT,
2659        ]
2660        .into_iter()
2661        .enumerate()
2662        {
2663            let descriptor = spec::invalidation::InvalidationDescriptor {
2664                dw0: kind.0 as u32
2665                    | if kind == DescriptorType::IOTLB_INVALIDATE {
2666                        1 << 4
2667                    } else {
2668                        0
2669                    },
2670                dw1: 0,
2671                dw2: 0,
2672                dw3: 0,
2673            };
2674            gm.write_at(0x1000 + index as u64 * 16, descriptor.as_bytes())
2675                .unwrap();
2676        }
2677        write64(&mut dev, 0x088, IqtReg::new().with_qt(2).into_bits());
2678        assert_eq!(IqhReg::from(read64(&mut dev, 0x080)).head_offset(), 32);
2679        assert!(!FstsReg::from(read32(&mut dev, 0x034)).iqe());
2680        write32(&mut dev, 0x018, 0);
2681        assert!(GstsReg::from(read32(&mut dev, 0x01C)).qies());
2682
2683        write64(&mut dev, 0x088, IqtReg::new().with_qt(3).into_bits());
2684        for (head, iqe) in [(2, false), (3, true)] {
2685            {
2686                let mut state = dev.shared.state.write();
2687                state.iqh = IqhReg::new().with_qh(head);
2688                state.fsts.set_iqe(iqe);
2689            }
2690            write32(&mut dev, 0x018, 0);
2691            assert!(GstsReg::from(read32(&mut dev, 0x01C)).qies());
2692        }
2693        {
2694            let mut state = dev.shared.state.write();
2695            state.fsts.set_iqe(false);
2696        }
2697        write32(&mut dev, 0x018, 0);
2698        assert!(!GstsReg::from(read32(&mut dev, 0x01C)).qies());
2699        assert_eq!(read64(&mut dev, 0x080), 0);
2700
2701        // Empty the queue before enabling so replay or a queue error cannot
2702        // mask a failure to reset completion tracking.
2703        write64(&mut dev, 0x088, 0);
2704        write32(&mut dev, 0x018, enabled);
2705        assert_eq!(read64(&mut dev, 0x080), 0);
2706        assert_eq!(read64(&mut dev, 0x088), 0);
2707        assert!(!FstsReg::from(read32(&mut dev, 0x034)).iqe());
2708        write32(&mut dev, 0x018, 0);
2709        assert!(GstsReg::from(read32(&mut dev, 0x01C)).qies());
2710        assert!(!FstsReg::from(read32(&mut dev, 0x034)).iqe());
2711    }
2712
2713    #[test]
2714    fn test_ccmd_register_invalidation() {
2715        let mut dev = create_test_device();
2716
2717        // Write CCMD with ICC=1, CIRG=01 (global).
2718        let ccmd = CcmdReg::new().with_icc(true).with_cirg(1);
2719        write64(&mut dev, 0x028, ccmd.into_bits());
2720
2721        // Read back — ICC should be cleared, CAIG should equal CIRG.
2722        let result = CcmdReg::from(read64(&mut dev, 0x028));
2723        assert!(!result.icc());
2724        assert_eq!(result.caig(), 1);
2725    }
2726
2727    #[test]
2728    fn test_fsts_rw1c() {
2729        let mut dev = create_test_device();
2730
2731        // Manually set fault status bits via shared state.
2732        {
2733            let mut state = dev.shared.state.write();
2734            state.fsts = FstsReg::new().with_pfo(true).with_iqe(true);
2735        }
2736
2737        let fsts = FstsReg::from(read32(&mut dev, 0x034));
2738        assert!(fsts.pfo());
2739        assert!(fsts.iqe());
2740
2741        // Clear PFO by writing 1.
2742        write32(&mut dev, 0x034, FstsReg::new().with_pfo(true).into_bits());
2743        let fsts = FstsReg::from(read32(&mut dev, 0x034));
2744        assert!(!fsts.pfo());
2745        assert!(fsts.iqe()); // IQE should still be set
2746    }
2747
2748    #[test]
2749    fn test_ppf_dynamic_computation() {
2750        let mut dev = create_test_device();
2751
2752        // Initially PPF should be 0.
2753        let fsts = FstsReg::from(read32(&mut dev, 0x034));
2754        assert!(!fsts.ppf());
2755
2756        // Set FRCD[0].F (bit 63 of frcd_hi).
2757        {
2758            let mut state = dev.shared.state.write();
2759            state.frcd_hi = FrcdHi::new().with_f(true);
2760        }
2761
2762        // Now PPF should be 1.
2763        let fsts = FstsReg::from(read32(&mut dev, 0x034));
2764        assert!(fsts.ppf());
2765
2766        // Clear F bit via RW1C on FRCD_HI.
2767        write64(&mut dev, Reg::FRCD_DW2.0, 1u64 << 63);
2768
2769        // PPF should be 0 again.
2770        let fsts = FstsReg::from(read32(&mut dev, 0x034));
2771        assert!(!fsts.ppf());
2772    }
2773
2774    #[test]
2775    fn test_ics_rw1c() {
2776        let mut dev = create_test_device();
2777
2778        // Set IWC.
2779        {
2780            let mut state = dev.shared.state.write();
2781            state.ics = IcsReg::new().with_iwc(true);
2782        }
2783
2784        let ics = IcsReg::from(read32(&mut dev, 0x09C));
2785        assert!(ics.iwc());
2786
2787        // Clear IWC.
2788        write32(&mut dev, 0x09C, IcsReg::new().with_iwc(true).into_bits());
2789        let ics = IcsReg::from(read32(&mut dev, 0x09C));
2790        assert!(!ics.iwc());
2791    }
2792
2793    #[test]
2794    fn test_iqa_write_guard() {
2795        let mut dev = create_test_device();
2796
2797        // Write IQA before QIE is enabled — should succeed.
2798        write64(&mut dev, 0x090, 0x5000_0000u64);
2799        assert_eq!(read64(&mut dev, 0x090), 0x5000_0000u64);
2800
2801        // Enable QIE.
2802        write32(&mut dev, 0x018, GcmdReg::new().with_qie(true).into_bits());
2803
2804        // Write IQA while QIE=1 — should be ignored.
2805        write64(&mut dev, 0x090, 0x6000_0000u64);
2806        assert_eq!(read64(&mut dev, 0x090), 0x5000_0000u64);
2807    }
2808
2809    #[test]
2810    fn test_irta_write_guard() {
2811        let mut dev = create_test_device();
2812
2813        // Write IRTA before IRE is enabled — should succeed.
2814        write64(&mut dev, 0x0B8, 0x7000_0000u64);
2815        assert_eq!(read64(&mut dev, 0x0B8), 0x7000_0000u64);
2816
2817        // Enable IRE (need SIRTP first).
2818        write32(&mut dev, 0x018, GcmdReg::new().with_sirtp(true).into_bits());
2819        write32(&mut dev, 0x018, GcmdReg::new().with_ire(true).into_bits());
2820
2821        // Write IRTA while IRE=1 — should be ignored.
2822        write64(&mut dev, 0x0B8, 0x8000_0000u64);
2823        assert_eq!(read64(&mut dev, 0x0B8), 0x7000_0000u64);
2824    }
2825
2826    #[test]
2827    fn test_unmapped_offset_returns_zero() {
2828        let mut dev = create_test_device();
2829        // Read an offset that doesn't correspond to any register.
2830        assert_eq!(read32(&mut dev, 0x050), 0);
2831        assert_eq!(read64(&mut dev, 0x060), 0);
2832    }
2833
2834    #[test]
2835    fn test_unsupported_access_size() {
2836        let mut dev = create_test_device();
2837        let mut data = [0u8; 2];
2838        let result = dev.mmio_read(TEST_MMIO_BASE, &mut data);
2839        assert!(matches!(result, IoResult::Err(IoError::InvalidAccessSize)));
2840    }
2841
2842    #[test]
2843    fn test_32bit_access_to_64bit_register() {
2844        let mut dev = create_test_device();
2845
2846        // CAP is 64-bit at offset 0x008.
2847        let cap_lo = read32(&mut dev, 0x008);
2848        let cap_hi = read32(&mut dev, 0x00C);
2849        let cap_full = read64(&mut dev, 0x008);
2850
2851        assert_eq!(cap_full as u32, cap_lo);
2852        assert_eq!((cap_full >> 32) as u32, cap_hi);
2853    }
2854
2855    #[test]
2856    fn test_iotlb_register_invalidation() {
2857        let mut dev = create_test_device();
2858
2859        // Write IOTLB_REG with IVT=1, IIRG=01 (global).
2860        let iotlb_val = IotlbReg::new().with_ivt(true).with_iirg(1).into_bits();
2861        write64(&mut dev, Reg::IOTLB.0, iotlb_val);
2862
2863        // Read back — IVT should be cleared, IAIG should match IIRG.
2864        let result = IotlbReg::from(read64(&mut dev, Reg::IOTLB.0));
2865        assert!(!result.ivt()); // IVT cleared
2866        assert_eq!(result.iaig(), 1); // IAIG = IIRG = 01
2867    }
2868
2869    #[test]
2870    fn test_cfi_toggle() {
2871        let mut dev = create_test_device();
2872
2873        // Enable CFI.
2874        write32(&mut dev, 0x018, GcmdReg::new().with_cfi(true).into_bits());
2875        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2876        assert!(gsts.cfis());
2877
2878        // Disable CFI.
2879        write32(&mut dev, 0x018, GcmdReg::new().with_cfi(false).into_bits());
2880        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
2881        assert!(!gsts.cfis());
2882    }
2883
2884    #[test]
2885    fn test_frcd_hi_rw1c() {
2886        let mut dev = create_test_device();
2887
2888        // Set F bit (bit 63) in FRCD_HI.
2889        {
2890            let mut state = dev.shared.state.write();
2891            state.frcd_hi = FrcdHi::new().with_f(true);
2892        }
2893
2894        // Verify it reads back.
2895        let frcd_hi = read64(&mut dev, Reg::FRCD_DW2.0);
2896        assert_eq!((frcd_hi >> 63) & 1, 1);
2897
2898        // Clear F via RW1C.
2899        write64(&mut dev, Reg::FRCD_DW2.0, 1u64 << 63);
2900        let frcd_hi = read64(&mut dev, Reg::FRCD_DW2.0);
2901        assert_eq!((frcd_hi >> 63) & 1, 0);
2902    }
2903
2904    // =========================================================================
2905    // Translation tests (1E)
2906    // =========================================================================
2907
2908    use spec::pte::SlPte;
2909    use spec::root_context::AddressWidth;
2910    use spec::root_context::ContextEntry;
2911    use spec::root_context::ContextEntryHi;
2912    use spec::root_context::ContextEntryLo;
2913    use spec::root_context::RootEntry;
2914    use spec::root_context::RootEntryLo;
2915    use zerocopy::IntoBytes;
2916
2917    const ROOT_TABLE_ADDR: u64 = 0x10_0000; // 1 MiB
2918    const CONTEXT_TABLE_ADDR: u64 = 0x11_0000;
2919    const PAGE_TABLE_L4_ADDR: u64 = 0x12_0000;
2920    const PAGE_TABLE_L3_ADDR: u64 = 0x13_0000;
2921    const PAGE_TABLE_L2_ADDR: u64 = 0x14_0000;
2922    const PAGE_TABLE_L1_ADDR: u64 = 0x15_0000;
2923    const TARGET_GPA: u64 = 0x20_0000; // Where IOVA 0 maps to
2924
2925    /// Create a device with guest memory and pre-populate page tables
2926    /// for a 4-level walk mapping IOVA 0 → TARGET_GPA.
2927    fn create_test_device_with_translation() -> (IntelVtdDevice, Arc<VtdSharedState>) {
2928        // 4 MiB of guest memory.
2929        let gm = GuestMemory::allocate(0x40_0000);
2930        let signal_msi = Arc::new(TestSignalMsi);
2931
2932        // Set up root entry: bus 0 → CONTEXT_TABLE_ADDR.
2933        let root_entry = RootEntry {
2934            lo: RootEntryLo::new()
2935                .with_p(true)
2936                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
2937            hi: 0,
2938        };
2939        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
2940
2941        // Set up context entry: devfn 0 → page table at L4, AW=2 (48-bit/4-level).
2942        let context_entry = ContextEntry {
2943            lo: ContextEntryLo::new()
2944                .with_p(true)
2945                .with_tt(TranslationType::UNTRANSLATED_ONLY.0)
2946                .with_ssptptr(PAGE_TABLE_L4_ADDR >> 12),
2947            hi: ContextEntryHi::new()
2948                .with_aw(AddressWidth::AW_48BIT.0)
2949                .with_did(1), // 48-bit / 4-level
2950        };
2951        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
2952            .unwrap();
2953
2954        // Build 4-level page tables: L4 → L3 → L2 → L1 → TARGET_GPA.
2955        // Level 4 entry 0 → L3
2956        let pte_l4 = SlPte::new()
2957            .with_r(true)
2958            .with_w(true)
2959            .with_address(PAGE_TABLE_L3_ADDR >> 12);
2960        gm.write_at(PAGE_TABLE_L4_ADDR, pte_l4.into_bits().as_bytes())
2961            .unwrap();
2962
2963        // Level 3 entry 0 → L2
2964        let pte_l3 = SlPte::new()
2965            .with_r(true)
2966            .with_w(true)
2967            .with_address(PAGE_TABLE_L2_ADDR >> 12);
2968        gm.write_at(PAGE_TABLE_L3_ADDR, pte_l3.into_bits().as_bytes())
2969            .unwrap();
2970
2971        // Level 2 entry 0 → L1
2972        let pte_l2 = SlPte::new()
2973            .with_r(true)
2974            .with_w(true)
2975            .with_address(PAGE_TABLE_L1_ADDR >> 12);
2976        gm.write_at(PAGE_TABLE_L2_ADDR, pte_l2.into_bits().as_bytes())
2977            .unwrap();
2978
2979        // Level 1 entry 0 → TARGET_GPA (4KB page)
2980        let pte_l1 = SlPte::new()
2981            .with_r(true)
2982            .with_w(true)
2983            .with_address(TARGET_GPA >> 12);
2984        gm.write_at(PAGE_TABLE_L1_ADDR, pte_l1.into_bits().as_bytes())
2985            .unwrap();
2986
2987        let (dev, shared) = IntelVtdDevice::new(
2988            gm,
2989            IntelVtdConfig {
2990                mmio_base: TEST_MMIO_BASE,
2991            },
2992            signal_msi,
2993        );
2994
2995        // Enable translation: set root table, SRTP, TE.
2996        {
2997            let mut state = shared.state.write();
2998            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
2999            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3000            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3001        }
3002
3003        (dev, shared)
3004    }
3005
3006    #[test]
3007    fn test_translate_4level_4kb() {
3008        let (_dev, shared) = create_test_device_with_translation();
3009        let state = shared.state.read();
3010        let gpa = shared
3011            .translate_locked(&state, 0, 0, 0x0000, false, EcapReg::from(ECAP_VALUE))
3012            .unwrap();
3013        assert_eq!(gpa, TARGET_GPA);
3014    }
3015
3016    #[test]
3017    fn test_translate_4level_4kb_with_offset() {
3018        let (_dev, shared) = create_test_device_with_translation();
3019        let state = shared.state.read();
3020        // IOVA 0x123 → TARGET_GPA + 0x123
3021        let gpa = shared
3022            .translate_locked(&state, 0, 0, 0x0123, false, EcapReg::from(ECAP_VALUE))
3023            .unwrap();
3024        assert_eq!(gpa, TARGET_GPA + 0x123);
3025    }
3026
3027    #[test]
3028    fn test_translate_disabled_is_identity() {
3029        let (_dev, shared) = create_test_device_with_translation();
3030        // Disable translation.
3031        {
3032            let mut state = shared.state.write();
3033            state.gsts = GstsReg::new().with_rtps(true);
3034        }
3035        let state = shared.state.read();
3036        let gpa = shared
3037            .translate_locked(&state, 0, 0, 0xDEAD_BEEF, false, EcapReg::from(ECAP_VALUE))
3038            .unwrap();
3039        assert_eq!(gpa, 0xDEAD_BEEF);
3040    }
3041
3042    #[test]
3043    fn test_translate_3level() {
3044        let gm = GuestMemory::allocate(0x40_0000);
3045        let signal_msi = Arc::new(TestSignalMsi);
3046
3047        // Set up root entry and context entry with AW=001 (39-bit/3-level).
3048        let root_entry = RootEntry {
3049            lo: RootEntryLo::new()
3050                .with_p(true)
3051                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
3052            hi: 0,
3053        };
3054        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3055
3056        let context_entry = ContextEntry {
3057            lo: ContextEntryLo::new()
3058                .with_p(true)
3059                .with_tt(TranslationType::UNTRANSLATED_ONLY.0)
3060                .with_ssptptr(PAGE_TABLE_L3_ADDR >> 12),
3061            hi: ContextEntryHi::new()
3062                .with_aw(AddressWidth::AW_39BIT.0)
3063                .with_did(1), // 39-bit / 3-level
3064        };
3065        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
3066            .unwrap();
3067
3068        // 3-level walk: L3 → L2 → L1 → TARGET_GPA.
3069        let pte_l3 = SlPte::new()
3070            .with_r(true)
3071            .with_w(true)
3072            .with_address(PAGE_TABLE_L2_ADDR >> 12);
3073        gm.write_at(PAGE_TABLE_L3_ADDR, pte_l3.into_bits().as_bytes())
3074            .unwrap();
3075
3076        let pte_l2 = SlPte::new()
3077            .with_r(true)
3078            .with_w(true)
3079            .with_address(PAGE_TABLE_L1_ADDR >> 12);
3080        gm.write_at(PAGE_TABLE_L2_ADDR, pte_l2.into_bits().as_bytes())
3081            .unwrap();
3082
3083        let pte_l1 = SlPte::new()
3084            .with_r(true)
3085            .with_w(true)
3086            .with_address(TARGET_GPA >> 12);
3087        gm.write_at(PAGE_TABLE_L1_ADDR, pte_l1.into_bits().as_bytes())
3088            .unwrap();
3089
3090        let (_dev, shared) = IntelVtdDevice::new(
3091            gm,
3092            IntelVtdConfig {
3093                mmio_base: TEST_MMIO_BASE,
3094            },
3095            signal_msi,
3096        );
3097        {
3098            let mut state = shared.state.write();
3099            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3100            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3101            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3102        }
3103
3104        let state = shared.state.read();
3105        let gpa = shared
3106            .translate_locked(&state, 0, 0, 0x0000, false, EcapReg::from(ECAP_VALUE))
3107            .unwrap();
3108        assert_eq!(gpa, TARGET_GPA);
3109    }
3110
3111    #[test]
3112    fn test_translate_2mb_large_page() {
3113        let gm = GuestMemory::allocate(0x40_0000);
3114        let signal_msi = Arc::new(TestSignalMsi);
3115
3116        let root_entry = RootEntry {
3117            lo: RootEntryLo::new()
3118                .with_p(true)
3119                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
3120            hi: 0,
3121        };
3122        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3123
3124        let context_entry = ContextEntry {
3125            lo: ContextEntryLo::new()
3126                .with_p(true)
3127                .with_tt(TranslationType::UNTRANSLATED_ONLY.0)
3128                .with_ssptptr(PAGE_TABLE_L4_ADDR >> 12),
3129            hi: ContextEntryHi::new()
3130                .with_aw(AddressWidth::AW_48BIT.0)
3131                .with_did(1),
3132        };
3133        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
3134            .unwrap();
3135
3136        // L4 → L3 → L2 (PS=1, 2MB page)
3137        let pte_l4 = SlPte::new()
3138            .with_r(true)
3139            .with_w(true)
3140            .with_address(PAGE_TABLE_L3_ADDR >> 12);
3141        gm.write_at(PAGE_TABLE_L4_ADDR, pte_l4.into_bits().as_bytes())
3142            .unwrap();
3143
3144        let pte_l3 = SlPte::new()
3145            .with_r(true)
3146            .with_w(true)
3147            .with_address(PAGE_TABLE_L2_ADDR >> 12);
3148        gm.write_at(PAGE_TABLE_L3_ADDR, pte_l3.into_bits().as_bytes())
3149            .unwrap();
3150
3151        // 2MB page at 0x200000
3152        let pte_l2 = SlPte::new()
3153            .with_r(true)
3154            .with_w(true)
3155            .with_ps(true)
3156            .with_address(0x20_0000 >> 12); // Base GPA = 0x200000
3157        gm.write_at(PAGE_TABLE_L2_ADDR, pte_l2.into_bits().as_bytes())
3158            .unwrap();
3159
3160        let (_dev, shared) = IntelVtdDevice::new(
3161            gm,
3162            IntelVtdConfig {
3163                mmio_base: TEST_MMIO_BASE,
3164            },
3165            signal_msi,
3166        );
3167        {
3168            let mut state = shared.state.write();
3169            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3170            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3171            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3172        }
3173
3174        let state = shared.state.read();
3175        // IOVA 0x1234 within the 2MB page → GPA 0x201234.
3176        let gpa = shared
3177            .translate_locked(&state, 0, 0, 0x1234, false, EcapReg::from(ECAP_VALUE))
3178            .unwrap();
3179        assert_eq!(gpa, 0x20_1234);
3180    }
3181
3182    #[test]
3183    fn test_translate_passthrough() {
3184        let gm = GuestMemory::allocate(0x40_0000);
3185        let signal_msi = Arc::new(TestSignalMsi);
3186
3187        let root_entry = RootEntry {
3188            lo: RootEntryLo::new()
3189                .with_p(true)
3190                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
3191            hi: 0,
3192        };
3193        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3194
3195        // Context entry with TT=10 (pass-through).
3196        let context_entry = ContextEntry {
3197            lo: ContextEntryLo::new()
3198                .with_p(true)
3199                .with_tt(TranslationType::PASS_THROUGH.0)
3200                .with_ssptptr(0),
3201            hi: ContextEntryHi::new()
3202                .with_aw(AddressWidth::AW_48BIT.0)
3203                .with_did(1),
3204        };
3205        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
3206            .unwrap();
3207
3208        let (_dev, shared) = IntelVtdDevice::new(
3209            gm,
3210            IntelVtdConfig {
3211                mmio_base: TEST_MMIO_BASE,
3212            },
3213            signal_msi,
3214        );
3215        {
3216            let mut state = shared.state.write();
3217            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3218            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3219            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3220        }
3221
3222        let state = shared.state.read();
3223        let gpa = shared
3224            .translate_locked(&state, 0, 0, 0xABCD_0000, false, EcapReg::from(ECAP_VALUE))
3225            .unwrap();
3226        assert_eq!(gpa, 0xABCD_0000);
3227    }
3228
3229    #[test]
3230    fn test_translate_root_not_present() {
3231        let gm = GuestMemory::allocate(0x40_0000);
3232        let signal_msi = Arc::new(TestSignalMsi);
3233
3234        // Root entry with P=0.
3235        let root_entry = RootEntry {
3236            lo: RootEntryLo::new().with_p(false),
3237            hi: 0,
3238        };
3239        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3240
3241        let (_dev, shared) = IntelVtdDevice::new(
3242            gm,
3243            IntelVtdConfig {
3244                mmio_base: TEST_MMIO_BASE,
3245            },
3246            signal_msi,
3247        );
3248        {
3249            let mut state = shared.state.write();
3250            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3251            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3252            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3253        }
3254
3255        let state = shared.state.read();
3256        let err = shared
3257            .translate_locked(&state, 0, 0, 0x1000, false, EcapReg::from(ECAP_VALUE))
3258            .unwrap_err();
3259        assert!(matches!(err, VtdFault::RootNotPresent { .. }));
3260    }
3261
3262    #[test]
3263    fn test_translate_context_not_present() {
3264        let gm = GuestMemory::allocate(0x40_0000);
3265        let signal_msi = Arc::new(TestSignalMsi);
3266
3267        let root_entry = RootEntry {
3268            lo: RootEntryLo::new()
3269                .with_p(true)
3270                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
3271            hi: 0,
3272        };
3273        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3274
3275        // Context entry with P=0.
3276        let context_entry = ContextEntry {
3277            lo: ContextEntryLo::new().with_p(false),
3278            hi: ContextEntryHi::new(),
3279        };
3280        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
3281            .unwrap();
3282
3283        let (_dev, shared) = IntelVtdDevice::new(
3284            gm,
3285            IntelVtdConfig {
3286                mmio_base: TEST_MMIO_BASE,
3287            },
3288            signal_msi,
3289        );
3290        {
3291            let mut state = shared.state.write();
3292            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3293            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3294            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3295        }
3296
3297        let state = shared.state.read();
3298        let err = shared
3299            .translate_locked(&state, 0, 0, 0x1000, false, EcapReg::from(ECAP_VALUE))
3300            .unwrap_err();
3301        assert!(matches!(err, VtdFault::ContextNotPresent { .. }));
3302    }
3303
3304    #[test]
3305    fn test_translate_pte_not_present() {
3306        let (_dev, shared) = create_test_device_with_translation();
3307
3308        // Write a non-present PTE at L1 entry 1 (IOVA 0x1000).
3309        let pte = SlPte::new(); // R=W=0
3310        shared
3311            .guest_memory
3312            .write_at(PAGE_TABLE_L1_ADDR + 8, pte.into_bits().as_bytes())
3313            .unwrap();
3314
3315        let state = shared.state.read();
3316        let err = shared
3317            .translate_locked(&state, 0, 0, 0x1000, false, EcapReg::from(ECAP_VALUE))
3318            .unwrap_err();
3319        // Non-present PTE (R=W=0) on a read → AccessDenied with write=false (fault 0x06).
3320        assert!(matches!(err, VtdFault::AccessDenied { write: false, .. }));
3321    }
3322
3323    #[test]
3324    fn test_translate_write_to_readonly() {
3325        let (_dev, shared) = create_test_device_with_translation();
3326
3327        // Write a read-only PTE at L1 entry 0 (R=1, W=0).
3328        let pte = SlPte::new().with_r(true).with_w(false);
3329        shared
3330            .guest_memory
3331            .write_at(PAGE_TABLE_L1_ADDR, pte.into_bits().as_bytes())
3332            .unwrap();
3333
3334        let state = shared.state.read();
3335        // Read should succeed.
3336        let gpa = shared
3337            .translate_locked(&state, 0, 0, 0x0000, false, EcapReg::from(ECAP_VALUE))
3338            .unwrap();
3339        assert_eq!(gpa, 0); // PTE address field is 0
3340        // Write should fail.
3341        let err = shared
3342            .translate_locked(&state, 0, 0, 0x0000, true, EcapReg::from(ECAP_VALUE))
3343            .unwrap_err();
3344        assert!(matches!(err, VtdFault::AccessDenied { write: true, .. }));
3345    }
3346
3347    #[test]
3348    fn test_translate_pde_permission_restricts() {
3349        let (_dev, shared) = create_test_device_with_translation();
3350
3351        // Make L2 entry 0 read-only (R=1, W=0), L1 entry 0 has W=1.
3352        // AND-accumulation means write should fail.
3353        let pte_l2 = SlPte::new()
3354            .with_r(true)
3355            .with_w(false) // No write at L2
3356            .with_address(PAGE_TABLE_L1_ADDR >> 12);
3357        shared
3358            .guest_memory
3359            .write_at(PAGE_TABLE_L2_ADDR, pte_l2.into_bits().as_bytes())
3360            .unwrap();
3361
3362        let state = shared.state.read();
3363        let err = shared
3364            .translate_locked(&state, 0, 0, 0x0000, true, EcapReg::from(ECAP_VALUE))
3365            .unwrap_err();
3366        assert!(matches!(err, VtdFault::AccessDenied { write: true, .. }));
3367    }
3368
3369    #[test]
3370    fn test_translate_fpd_suppresses_fault() {
3371        let gm = GuestMemory::allocate(0x40_0000);
3372        let signal_msi = Arc::new(TestSignalMsi);
3373
3374        let root_entry = RootEntry {
3375            lo: RootEntryLo::new()
3376                .with_p(true)
3377                .with_ctp(CONTEXT_TABLE_ADDR >> 12),
3378            hi: 0,
3379        };
3380        gm.write_at(ROOT_TABLE_ADDR, root_entry.as_bytes()).unwrap();
3381
3382        // Context entry with FPD=1, pointing to a non-existent page table.
3383        let context_entry = ContextEntry {
3384            lo: ContextEntryLo::new()
3385                .with_p(true)
3386                .with_fpd(true)
3387                .with_tt(TranslationType::UNTRANSLATED_ONLY.0)
3388                .with_ssptptr(0x30_0000 >> 12), // Points to zeroed memory
3389            hi: ContextEntryHi::new()
3390                .with_aw(AddressWidth::AW_48BIT.0)
3391                .with_did(1),
3392        };
3393        gm.write_at(CONTEXT_TABLE_ADDR, context_entry.as_bytes())
3394            .unwrap();
3395
3396        let (_dev, shared) = IntelVtdDevice::new(
3397            gm,
3398            IntelVtdConfig {
3399                mmio_base: TEST_MMIO_BASE,
3400            },
3401            signal_msi,
3402        );
3403        {
3404            let mut state = shared.state.write();
3405            state.rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3406            state.latched_rtaddr = RtaddrReg::from(ROOT_TABLE_ADDR);
3407            state.gsts = GstsReg::new().with_rtps(true).with_tes(true);
3408        }
3409
3410        // Translation should fail (PTE not present in zeroed memory).
3411        let state = shared.state.read();
3412        let err = shared
3413            .translate_locked(&state, 0, 0, 0x0000, false, EcapReg::from(ECAP_VALUE))
3414            .unwrap_err();
3415        assert!(err.fpd()); // FPD should be true
3416
3417        // Record the fault — it should be suppressed by FPD.
3418        drop(state);
3419        err.record(&shared, false); // read access
3420
3421        // FRCD.F should NOT be set (fault suppressed).
3422        let state = shared.state.read();
3423        assert!(!state.frcd_hi.f());
3424    }
3425
3426    // =========================================================================
3427    // Interrupt remapping tests (1F)
3428    // =========================================================================
3429
3430    use spec::irte::Irte;
3431    use spec::irte::IrteHi;
3432    use spec::irte::IrteLo;
3433
3434    const IRT_BASE_ADDR: u64 = 0x18_0000;
3435
3436    #[test]
3437    fn test_extract_irte_index_no_shv() {
3438        // Handle = {addr[2], addr[19:5]}. SHV = addr[3] = 0.
3439        // addr = 0xFEE0_0010 (bit 4=1, remappable format, handle=0x0000).
3440        let index = VtdSharedState::extract_irte_index(0xFEE0_0010, 0);
3441        assert_eq!(index, 0);
3442
3443        // addr[19:5] = 0x7 (handle[14:0] = 7), addr[2] = 0 (handle[15]=0).
3444        // addr = 0xFEE0_00F0 (bits 7:5 = 111).
3445        let addr = 0xFEE0_0010 | (0x7 << 5);
3446        let index = VtdSharedState::extract_irte_index(addr, 0);
3447        assert_eq!(index, 7);
3448    }
3449
3450    #[test]
3451    fn test_extract_irte_index_with_shv() {
3452        // SHV = addr[3] = 1. handle = {addr[2], addr[19:5]}.
3453        // index = handle + data[15:0].
3454        let addr = 0xFEE0_0018 | (0x5 << 5); // handle=5, SHV=1
3455        let index = VtdSharedState::extract_irte_index(addr, 3);
3456        assert_eq!(index, 8); // 5 + 3
3457    }
3458
3459    fn setup_ir_state(shared: &Arc<VtdSharedState>, eime: bool) {
3460        let mut state = shared.state.write();
3461        // Set up IRT: base at IRT_BASE_ADDR, size=0xF (65536 entries).
3462        state.irta = IrtaReg::new()
3463            .with_irta(IRT_BASE_ADDR >> 12)
3464            .with_s(0xF)
3465            .with_eime(eime);
3466        state.latched_irta = state.irta;
3467        // Enable IR.
3468        let mut gsts = state.gsts;
3469        gsts.set_ires(true);
3470        gsts.set_irtps(true);
3471        state.gsts = gsts;
3472    }
3473
3474    struct CountingRoute {
3475        device_id: u16,
3476        retranslate_count: AtomicU32,
3477    }
3478
3479    impl iommu_common::RetranslateInterrupts for CountingRoute {
3480        fn device_id(&self) -> u16 {
3481            self.device_id
3482        }
3483
3484        fn retranslate(&self) {
3485            self.retranslate_count.fetch_add(1, Ordering::SeqCst);
3486        }
3487    }
3488
3489    #[test]
3490    fn test_remap_msi_basic() {
3491        let gm = GuestMemory::allocate(0x40_0000);
3492        let signal_msi = Arc::new(TestSignalMsi);
3493        let (_dev, shared) = IntelVtdDevice::new(
3494            gm.clone(),
3495            IntelVtdConfig {
3496                mmio_base: TEST_MMIO_BASE,
3497            },
3498            signal_msi,
3499        );
3500
3501        setup_ir_state(&shared, false);
3502
3503        // Write IRTE at index 0: vector=0x42, DST xAPIC ID=3, fixed delivery.
3504        let irte = Irte {
3505            lo: IrteLo::new()
3506                .with_p(true)
3507                .with_vector(0x42)
3508                .with_dst(0x0300) // xAPIC: APIC ID in bits 15:8
3509                .with_dlm(0) // Fixed
3510                .with_dm(false), // Physical
3511            hi: IrteHi::new().with_svt(0), // No source validation
3512        };
3513        gm.write_at(IRT_BASE_ADDR, irte.as_bytes()).unwrap();
3514
3515        // Remappable MSI: addr bit4=1, handle=0, SHV=0 → IRTE index 0.
3516        let addr = 0xFEE0_0010u64;
3517        let data = 0u32;
3518        let state = shared.state.read();
3519        let (new_addr, new_data) = shared.remap_msi_locked(&state, 0x0000, addr, data).unwrap();
3520
3521        // Expected: addr = 0xFEE03000 (DST=3 in bits 19:12).
3522        assert_eq!(new_addr & 0xFFF0_0000, 0xFEE0_0000);
3523        assert_eq!((new_addr >> 12) & 0xFF, 3); // APIC ID = 3
3524        assert_eq!(new_data & 0xFF, 0x42); // Vector = 0x42
3525    }
3526
3527    #[test]
3528    fn test_remap_msi_x2apic_destination() {
3529        let gm = GuestMemory::allocate(0x40_0000);
3530        let signal_msi = Arc::new(TestSignalMsi);
3531        let (_dev, shared) = IntelVtdDevice::new(
3532            gm.clone(),
3533            IntelVtdConfig {
3534                mmio_base: TEST_MMIO_BASE,
3535            },
3536            signal_msi,
3537        );
3538
3539        // Enable IR with EIME=1 (x2APIC mode).
3540        setup_ir_state(&shared, true);
3541
3542        // Write IRTE with destination APIC ID = 300 (> 255).
3543        let apic_id: u32 = 300;
3544        let irte = Irte {
3545            lo: IrteLo::new()
3546                .with_p(true)
3547                .with_vector(0x50)
3548                .with_dst(apic_id)
3549                .with_dlm(0)
3550                .with_dm(false),
3551            hi: IrteHi::new().with_svt(0),
3552        };
3553        gm.write_at(IRT_BASE_ADDR, irte.as_bytes()).unwrap();
3554
3555        let addr = 0xFEE0_0010u64;
3556        let state = shared.state.read();
3557        let (new_addr, new_data) = shared.remap_msi_locked(&state, 0x0000, addr, 0).unwrap();
3558
3559        // Verify the destination is preserved via virt_destination encoding.
3560        let msi_addr = x86defs::msi::MsiAddress::from(new_addr as u32);
3561        assert_eq!(msi_addr.virt_destination(), apic_id as u16);
3562        assert_eq!(new_data & 0xFF, 0x50);
3563    }
3564
3565    #[test]
3566    fn test_remap_msi_ir_disabled_passthrough() {
3567        let gm = GuestMemory::allocate(0x40_0000);
3568        let signal_msi = Arc::new(TestSignalMsi);
3569        let (_dev, shared) = IntelVtdDevice::new(
3570            gm,
3571            IntelVtdConfig {
3572                mmio_base: TEST_MMIO_BASE,
3573            },
3574            signal_msi,
3575        );
3576        // IR not enabled — pass through.
3577        let state = shared.state.read();
3578        let (a, d) = shared
3579            .remap_msi_locked(&state, 0, 0xFEE0_1234, 0x42)
3580            .unwrap();
3581        assert_eq!(a, 0xFEE0_1234);
3582        assert_eq!(d, 0x42);
3583    }
3584
3585    #[test]
3586    fn test_interrupt_remapper_transitions_from_passthrough_to_remap() {
3587        let gm = GuestMemory::allocate(0x40_0000);
3588        let signal_msi = Arc::new(TestSignalMsi);
3589        let (_dev, shared) = IntelVtdDevice::new(
3590            gm.clone(),
3591            IntelVtdConfig {
3592                mmio_base: TEST_MMIO_BASE,
3593            },
3594            signal_msi,
3595        );
3596
3597        let compat_addr = 0xFEE0_0000u64;
3598        assert_eq!(
3599            iommu_common::InterruptRemapper::remap_msi(&*shared, 0x00A0, compat_addr, 0x31),
3600            Some((compat_addr, 0x31))
3601        );
3602
3603        setup_ir_state(&shared, false);
3604        let irte = Irte {
3605            lo: IrteLo::new()
3606                .with_p(true)
3607                .with_vector(0x45)
3608                .with_dst(0x0200)
3609                .with_dlm(0)
3610                .with_dm(false),
3611            hi: IrteHi::new().with_svt(0b01).with_sq(0).with_sid(0x00A0),
3612        };
3613        gm.write_at(IRT_BASE_ADDR, irte.as_bytes()).unwrap();
3614
3615        let (new_addr, new_data) =
3616            iommu_common::InterruptRemapper::remap_msi(&*shared, 0x00A0, 0xFEE0_0010, 0).unwrap();
3617        assert_eq!((new_addr >> 12) & 0xFF, 2);
3618        assert_eq!(new_data & 0xFF, 0x45);
3619    }
3620
3621    #[test]
3622    fn test_remap_msi_irte_not_present() {
3623        let gm = GuestMemory::allocate(0x40_0000);
3624        let signal_msi = Arc::new(TestSignalMsi);
3625        let (_dev, shared) = IntelVtdDevice::new(
3626            gm.clone(),
3627            IntelVtdConfig {
3628                mmio_base: TEST_MMIO_BASE,
3629            },
3630            signal_msi,
3631        );
3632
3633        setup_ir_state(&shared, false);
3634
3635        // IRTE at index 0 is all zeros (P=0).
3636        let addr = 0xFEE0_0010u64;
3637        let state = shared.state.read();
3638        let err = shared
3639            .remap_msi_locked(&state, 0x0000, addr, 0)
3640            .unwrap_err();
3641        assert!(matches!(err, VtdFault::IrteNotPresent { .. }));
3642    }
3643
3644    #[test]
3645    fn test_remap_msi_posted_irte_rejected() {
3646        let gm = GuestMemory::allocate(0x40_0000);
3647        let signal_msi = Arc::new(TestSignalMsi);
3648        let (_dev, shared) = IntelVtdDevice::new(
3649            gm.clone(),
3650            IntelVtdConfig {
3651                mmio_base: TEST_MMIO_BASE,
3652            },
3653            signal_msi,
3654        );
3655
3656        setup_ir_state(&shared, false);
3657
3658        let irte = Irte {
3659            lo: IrteLo::new().with_p(true).with_im(true).with_vector(0x40),
3660            hi: IrteHi::new().with_svt(0),
3661        };
3662        gm.write_at(IRT_BASE_ADDR, irte.as_bytes()).unwrap();
3663
3664        let state = shared.state.read();
3665        let err = shared
3666            .remap_msi_locked(&state, 0x0000, 0xFEE0_0010, 0)
3667            .unwrap_err();
3668        assert!(matches!(err, VtdFault::IrteReservedField { .. }));
3669    }
3670
3671    #[test]
3672    fn test_interrupt_entry_cache_invalidate_retranslates_routes() {
3673        const IQ_BASE: u64 = 0x20_0000;
3674
3675        let gm = GuestMemory::allocate(0x40_0000);
3676        let signal_msi = Arc::new(TestSignalMsi);
3677        let (mut dev, shared) = IntelVtdDevice::new(
3678            gm.clone(),
3679            IntelVtdConfig {
3680                mmio_base: TEST_MMIO_BASE,
3681            },
3682            signal_msi,
3683        );
3684
3685        let route = Arc::new(CountingRoute {
3686            device_id: 0x00A0,
3687            retranslate_count: AtomicU32::new(0),
3688        });
3689        let route_dyn: Arc<dyn iommu_common::RetranslateInterrupts> = route.clone();
3690        iommu_common::InterruptRemapper::register_route(&*shared, &route_dyn);
3691
3692        let iqa = IqaReg::new().with_qs(0).with_iqa(IQ_BASE >> 12);
3693        write64(&mut dev, Reg::IQA.0, iqa.into_bits());
3694        write32(
3695            &mut dev,
3696            Reg::GCMD.0,
3697            GcmdReg::new().with_qie(true).into_bits(),
3698        );
3699
3700        let desc = spec::invalidation::InvalidationDescriptor {
3701            dw0: DescriptorType::INTERRUPT_ENTRY_CACHE_INVALIDATE.0 as u32,
3702            dw1: 0,
3703            dw2: 0,
3704            dw3: 0,
3705        };
3706        gm.write_at(IQ_BASE, desc.as_bytes()).unwrap();
3707
3708        write64(&mut dev, Reg::IQT.0, IqtReg::new().with_qt(1).into_bits());
3709
3710        assert_eq!(route.retranslate_count.load(Ordering::SeqCst), 1);
3711        assert_eq!(IqhReg::from(read64(&mut dev, Reg::IQH.0)).head_offset(), 16);
3712    }
3713
3714    #[test]
3715    fn test_remap_msi_compat_format_blocked() {
3716        let gm = GuestMemory::allocate(0x40_0000);
3717        let signal_msi = Arc::new(TestSignalMsi);
3718        let (_dev, shared) = IntelVtdDevice::new(
3719            gm,
3720            IntelVtdConfig {
3721                mmio_base: TEST_MMIO_BASE,
3722            },
3723            signal_msi,
3724        );
3725
3726        setup_ir_state(&shared, false);
3727        // CFIS=0 (default) → compat-format blocked.
3728
3729        // Compatibility format: bit 4 = 0.
3730        let addr = 0xFEE0_0000u64; // bit 4 = 0
3731        let state = shared.state.read();
3732        let err = shared
3733            .remap_msi_locked(&state, 0x0000, addr, 0)
3734            .unwrap_err();
3735        assert!(matches!(err, VtdFault::CompatibilityFormatBlocked { .. }));
3736    }
3737
3738    #[test]
3739    fn test_remap_msi_compat_format_passthrough_cfis() {
3740        let gm = GuestMemory::allocate(0x40_0000);
3741        let signal_msi = Arc::new(TestSignalMsi);
3742        let (_dev, shared) = IntelVtdDevice::new(
3743            gm,
3744            IntelVtdConfig {
3745                mmio_base: TEST_MMIO_BASE,
3746            },
3747            signal_msi,
3748        );
3749
3750        setup_ir_state(&shared, false);
3751
3752        // Set CFIS=1 → pass-through for compat-format.
3753        {
3754            let mut state = shared.state.write();
3755            let mut gsts = state.gsts;
3756            gsts.set_cfis(true);
3757            state.gsts = gsts;
3758        }
3759
3760        let addr = 0xFEE0_0000u64; // bit 4 = 0
3761        let state = shared.state.read();
3762        let (a, d) = shared.remap_msi_locked(&state, 0x0000, addr, 0x42).unwrap();
3763        assert_eq!(a, addr);
3764        assert_eq!(d, 0x42);
3765    }
3766
3767    #[test]
3768    fn test_remap_msi_source_validation_verify_sid() {
3769        let gm = GuestMemory::allocate(0x40_0000);
3770        let signal_msi = Arc::new(TestSignalMsi);
3771        let (_dev, shared) = IntelVtdDevice::new(
3772            gm.clone(),
3773            IntelVtdConfig {
3774                mmio_base: TEST_MMIO_BASE,
3775            },
3776            signal_msi,
3777        );
3778
3779        setup_ir_state(&shared, false);
3780
3781        // IRTE with SVT=01 (verify SID), SQ=00 (exact match), SID=0x0100.
3782        let irte = Irte {
3783            lo: IrteLo::new()
3784                .with_p(true)
3785                .with_vector(0x30)
3786                .with_dst(0x0100)
3787                .with_dlm(0)
3788                .with_dm(false),
3789            hi: IrteHi::new().with_svt(0b01).with_sq(0b00).with_sid(0x0100),
3790        };
3791        gm.write_at(IRT_BASE_ADDR, irte.as_bytes()).unwrap();
3792
3793        let addr = 0xFEE0_0010u64;
3794        let state = shared.state.read();
3795
3796        // Matching SID should succeed.
3797        assert!(shared.remap_msi_locked(&state, 0x0100, addr, 0).is_ok());
3798
3799        // Non-matching SID should fail.
3800        let err = shared
3801            .remap_msi_locked(&state, 0x0200, addr, 0)
3802            .unwrap_err();
3803        assert!(matches!(err, VtdFault::SourceValidationFailed { .. }));
3804    }
3805
3806    #[test]
3807    fn test_record_fault() {
3808        let gm = GuestMemory::allocate(0x40_0000);
3809        let signal_msi = Arc::new(TestSignalMsi);
3810        let (_dev, shared) = IntelVtdDevice::new(
3811            gm,
3812            IntelVtdConfig {
3813                mmio_base: TEST_MMIO_BASE,
3814            },
3815            signal_msi,
3816        );
3817
3818        let fault = VtdFault::RootNotPresent {
3819            source_id: 0x0100,
3820            iova: 0x1000,
3821        };
3822        fault.record(&shared, false); // simulate a read fault
3823
3824        let state = shared.state.read();
3825        let frcd_hi = state.frcd_hi;
3826        assert!(frcd_hi.f());
3827        assert_eq!(frcd_hi.sid(), 0x0100);
3828        assert_eq!(frcd_hi.fr(), FaultReason::ROOT_NOT_PRESENT.0);
3829        assert!(frcd_hi.t()); // T=1 for read
3830
3831        let frcd_lo = state.frcd_lo;
3832        assert_eq!(frcd_lo.fault_address(), 0x1000);
3833    }
3834
3835    #[test]
3836    fn test_frcd_raw_mmio_reason_position() {
3837        let mut dev = create_test_device();
3838        for reason in 0..=u8::MAX {
3839            for is_read in [false, true] {
3840                {
3841                    let mut state = dev.shared.state.write();
3842                    dev.shared.record_fault_locked(
3843                        &mut state,
3844                        0xabcd,
3845                        FaultReason(reason),
3846                        0x1234_5678_abcd,
3847                        is_read,
3848                        false,
3849                    );
3850                }
3851                // §11.4.7.6: FR is full-register bits 103:96, hence the
3852                // low byte of DWORD 3, not bits 23:16 of that DWORD.
3853                let dw3 = 0x8000_0000 | ((is_read as u32) << 30) | u32::from(reason);
3854                assert_eq!(read32(&mut dev, 0x120), 0x5678_a000);
3855                assert_eq!(read32(&mut dev, 0x124), 0x1234);
3856                assert_eq!(read32(&mut dev, 0x128), 0xabcd);
3857                assert_eq!(read32(&mut dev, 0x12c), dw3);
3858                assert_eq!(read64(&mut dev, 0x128), (u64::from(dw3) << 32) | 0xabcd);
3859                // RW1C clears F without changing the reason or request metadata.
3860                write32(&mut dev, 0x12c, 1 << 31);
3861                assert_eq!(read32(&mut dev, 0x12c), dw3 & !(1 << 31));
3862            }
3863        }
3864    }
3865
3866    #[test]
3867    fn test_iqa_raw_mmio_layout() {
3868        let mut dev = create_test_device();
3869        for qs in 0..=7 {
3870            for dw in [0, 1] {
3871                let raw = 0x1234_5678_9000 | (dw << 11) | qs;
3872                write64(&mut dev, 0x090, raw);
3873                assert_eq!(read64(&mut dev, 0x090), raw);
3874                let state = dev.shared.state.read();
3875                assert_eq!(state.iqa.dw(), dw != 0);
3876                assert_eq!(state.iqa.qs(), qs as u8);
3877                assert_eq!(state.iqa.queue_size_bytes(), 4096 << qs);
3878            }
3879        }
3880    }
3881
3882    #[test]
3883    fn test_record_fault_overflow() {
3884        let gm = GuestMemory::allocate(0x40_0000);
3885        let signal_msi = Arc::new(TestSignalMsi);
3886        let (_dev, shared) = IntelVtdDevice::new(
3887            gm,
3888            IntelVtdConfig {
3889                mmio_base: TEST_MMIO_BASE,
3890            },
3891            signal_msi,
3892        );
3893
3894        // Record first fault.
3895        let fault1 = VtdFault::RootNotPresent {
3896            source_id: 0x0100,
3897            iova: 0x1000,
3898        };
3899        fault1.record(&shared, true); // write fault
3900
3901        // Record second fault — should overflow.
3902        let fault2 = VtdFault::ContextNotPresent {
3903            source_id: 0x0200,
3904            iova: 0x2000,
3905            fpd: false,
3906        };
3907        fault2.record(&shared, false);
3908
3909        let state = shared.state.read();
3910        // PFO should be set.
3911        let fsts = state.fsts;
3912        assert!(fsts.pfo());
3913        // FRCD should still have first fault.
3914        let frcd_hi = state.frcd_hi;
3915        assert_eq!(frcd_hi.sid(), 0x0100);
3916    }
3917
3918    #[test]
3919    fn test_vtd_translator() {
3920        let (_dev, shared) = create_test_device_with_translation();
3921        let translator = shared.translator();
3922
3923        // Test via IommuTranslator trait.
3924        let result = iommu_common::IommuTranslator::translate(
3925            &translator,
3926            0x0000, // RID: bus=0, devfn=0
3927            0x0000, // IOVA
3928            false,
3929            |gpa| gpa,
3930        )
3931        .unwrap();
3932        assert_eq!(result, TARGET_GPA);
3933    }
3934
3935    #[test]
3936    fn test_vtd_signal_msi() {
3937        use std::sync::atomic::{AtomicU64, Ordering};
3938
3939        struct RecordingMsi {
3940            last_addr: AtomicU64,
3941        }
3942        impl SignalMsi for RecordingMsi {
3943            fn signal_msi(&self, _devid: Option<u32>, address: u64, _data: u32) {
3944                self.last_addr.store(address, Ordering::SeqCst);
3945            }
3946        }
3947
3948        let gm = GuestMemory::allocate(0x40_0000);
3949        let inner_msi = Arc::new(RecordingMsi {
3950            last_addr: AtomicU64::new(0),
3951        });
3952        let signal_msi = Arc::new(TestSignalMsi);
3953
3954        let (_dev, shared) = IntelVtdDevice::new(
3955            gm.clone(),
3956            IntelVtdConfig {
3957                mmio_base: TEST_MMIO_BASE,
3958            },
3959            signal_msi,
3960        );
3961
3962        // No IR enabled → pass-through.
3963        let wrapper = shared.wrap_signal_msi(inner_msi.clone());
3964        wrapper.signal_msi(Some(0x0100), 0xFEE0_1234, 0x42);
3965        assert_eq!(inner_msi.last_addr.load(Ordering::SeqCst), 0xFEE0_1234);
3966    }
3967
3968    #[test]
3969    fn test_vtd_signal_msi_no_devid_dropped() {
3970        use std::sync::atomic::{AtomicU32, Ordering};
3971
3972        struct CountingMsi {
3973            count: AtomicU32,
3974        }
3975        impl SignalMsi for CountingMsi {
3976            fn signal_msi(&self, _devid: Option<u32>, _address: u64, _data: u32) {
3977                self.count.fetch_add(1, Ordering::SeqCst);
3978            }
3979        }
3980
3981        let gm = GuestMemory::allocate(0x40_0000);
3982        let inner_msi = Arc::new(CountingMsi {
3983            count: AtomicU32::new(0),
3984        });
3985        let signal_msi = Arc::new(TestSignalMsi);
3986
3987        let (_dev, shared) = IntelVtdDevice::new(
3988            gm,
3989            IntelVtdConfig {
3990                mmio_base: TEST_MMIO_BASE,
3991            },
3992            signal_msi,
3993        );
3994
3995        let wrapper = shared.wrap_signal_msi(inner_msi.clone());
3996
3997        // devid=None should be silently dropped.
3998        wrapper.signal_msi(None, 0xFEE0_1234, 0x42);
3999        assert_eq!(inner_msi.count.load(Ordering::SeqCst), 0);
4000    }
4001
4002    // =========================================================================
4003    // End-to-end integration test (1J.1)
4004    // =========================================================================
4005    //
4006    // This test constructs the full VT-d stack and programs it via MMIO,
4007    // mimicking a Linux `intel-iommu` driver init sequence.
4008
4009    use spec::invalidation::InvalidationWaitDw0Dw1;
4010    use spec::invalidation::InvalidationWaitDw2Dw3;
4011
4012    /// Guest memory layout for the end-to-end test.
4013    ///
4014    /// 8 MiB of guest memory. Addresses chosen to be well-separated.
4015    const E2E_MEM_SIZE: usize = 0x80_0000;
4016    const E2E_ROOT_TABLE: u64 = 0x10_0000; // 1 MiB
4017    const E2E_CONTEXT_TABLE: u64 = 0x11_0000; // 1 MiB + 64 KiB
4018    const E2E_PT_L4: u64 = 0x12_0000;
4019    const E2E_PT_L3: u64 = 0x13_0000;
4020    const E2E_PT_L2: u64 = 0x14_0000;
4021    const E2E_PT_L1: u64 = 0x15_0000;
4022    const E2E_TARGET_GPA: u64 = 0x20_0000; // 2 MiB — where IOVA 0 maps to
4023    const E2E_IQ_BASE: u64 = 0x30_0000; // Invalidation queue
4024    const E2E_IQ_STATUS: u64 = 0x31_0000; // Status write address for INVALIDATION_WAIT
4025    const E2E_IRT_BASE: u64 = 0x40_0000; // Interrupt remapping table
4026    /// Test device BDF: bus=1, dev=0, fn=0 → devfn=0x00, RID=0x0100.
4027    const E2E_TEST_BUS: u8 = 1;
4028    const E2E_TEST_DEVFN: u8 = 0x00;
4029    const E2E_TEST_RID: u16 = 0x0100;
4030
4031    /// End-to-end test mimicking a Linux intel-iommu driver init sequence.
4032    ///
4033    /// Steps:
4034    ///  1. Read CAP/ECAP, verify capabilities.
4035    ///  2. Allocate root table, context tables, page tables in guest memory.
4036    ///  3. Write RTADDR with root table GPA.
4037    ///  4. Write GCMD with SRTP=1, verify RTPS in GSTS.
4038    ///  5. Register-based invalidation (CCMD, IOTLB) before QI.
4039    ///  6. Allocate invalidation queue, write IQA.
4040    ///  7. Write GCMD with QIE=1, verify QIES.
4041    ///  8. Program context entries for test devices.
4042    ///  9. Build 4-level page table mapping IOVA 0x0 → E2E_TARGET_GPA.
4043    /// 10. Write GCMD with TE=1, verify TES.
4044    /// 11. Submit invalidation queue descriptors (context + IOTLB + wait).
4045    /// 12. DMA read/write via VtdTranslator, verify translation.
4046    /// 13. Allocate IRT, program IRTE entries.
4047    /// 14. Write IRTA with IRT base, GCMD with SIRTP=1 then IRE=1.
4048    /// 15. MSI via VtdSignalMsi, verify remapping.
4049    /// 16. Access unmapped IOVA, verify fault recording.
4050    #[test]
4051    fn test_end_to_end_linux_init_sequence() {
4052        for (scalable, dw) in [(false, false), (false, true), (true, true)] {
4053            linux_init_sequence(scalable, dw);
4054        }
4055    }
4056
4057    fn linux_init_sequence(scalable: bool, dw: bool) {
4058        use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
4059
4060        // -- Recording MSI sink to verify interrupt delivery --
4061        struct RecordingMsi {
4062            last_addr: AtomicU64,
4063            last_data: AtomicU32,
4064            count: AtomicU32,
4065        }
4066        impl RecordingMsi {
4067            fn new() -> Self {
4068                Self {
4069                    last_addr: AtomicU64::new(0),
4070                    last_data: AtomicU32::new(0),
4071                    count: AtomicU32::new(0),
4072                }
4073            }
4074        }
4075        impl SignalMsi for RecordingMsi {
4076            fn signal_msi(&self, _devid: Option<u32>, address: u64, data: u32) {
4077                self.last_addr.store(address, Ordering::SeqCst);
4078                self.last_data.store(data, Ordering::SeqCst);
4079                self.count.fetch_add(1, Ordering::SeqCst);
4080            }
4081        }
4082
4083        let gm = GuestMemory::allocate(E2E_MEM_SIZE);
4084        let iommu_msi = Arc::new(RecordingMsi::new());
4085        let (mut dev, shared) = IntelVtdDevice::new(
4086            gm.clone(),
4087            IntelVtdConfig {
4088                mmio_base: TEST_MMIO_BASE,
4089            },
4090            iommu_msi.clone(),
4091        );
4092
4093        // =====================================================================
4094        // Step 1: Read and verify capabilities
4095        // =====================================================================
4096        let ver = read32(&mut dev, 0x000);
4097        assert_eq!(VersionReg::from(ver).max(), 1);
4098        assert_eq!(VersionReg::from(ver).min(), 0);
4099
4100        let cap = read64(&mut dev, 0x008);
4101        let cap_reg = CapReg::from(cap);
4102        assert_eq!(cap_reg.mgaw(), 47); // 48-bit
4103        assert!(cap_reg.sagaw() & 0x4 != 0); // 48-bit/4-level supported
4104        assert!(cap_reg.sagaw() & 0x2 != 0); // 39-bit/3-level supported
4105        assert_eq!(cap_reg.nfr(), 0); // 1 fault record
4106
4107        let ecap = read64(&mut dev, 0x010);
4108        assert_eq!(ecap, 0x0003_6800_00f0_10db);
4109        let ecap_reg = EcapReg::from(ecap);
4110        assert!(ecap_reg.qi()); // Queued invalidation
4111        assert!(ecap_reg.ir()); // Interrupt remapping
4112        assert!(ecap_reg.eim()); // x2APIC
4113        assert!(ecap_reg.c()); // Page-walk coherency
4114
4115        // Initial GSTS should be all zeros.
4116        assert_eq!(read32(&mut dev, 0x01C), 0);
4117
4118        // =====================================================================
4119        // Step 2–4: Set root table pointer
4120        // =====================================================================
4121
4122        // Write root table, context table entries, and page tables into guest
4123        // memory for bus 1, devfn 0.
4124
4125        // Root table entry for bus 1 → context table.
4126        let root_entry = RootEntry {
4127            lo: RootEntryLo::new()
4128                .with_p(true)
4129                .with_ctp(E2E_CONTEXT_TABLE >> 12),
4130            hi: 0,
4131        };
4132        gm.write_at(
4133            E2E_ROOT_TABLE + (E2E_TEST_BUS as u64) * 16,
4134            root_entry.as_bytes(),
4135        )
4136        .unwrap();
4137
4138        // Context entry for devfn 0 → 4-level page table.
4139        let context_entry = ContextEntry {
4140            lo: ContextEntryLo::new()
4141                .with_p(true)
4142                .with_tt(TranslationType::UNTRANSLATED_ONLY.0)
4143                .with_ssptptr(E2E_PT_L4 >> 12),
4144            hi: ContextEntryHi::new()
4145                .with_aw(AddressWidth::AW_48BIT.0)
4146                .with_did(1), // 48-bit/4-level
4147        };
4148        gm.write_at(
4149            E2E_CONTEXT_TABLE + (E2E_TEST_DEVFN as u64) * 16,
4150            context_entry.as_bytes(),
4151        )
4152        .unwrap();
4153        if scalable {
4154            // RID_PASID=65 resolves directory entry 1 and PASID-table entry 1.
4155            let directory = 0x16_0000u64;
4156            let pasid_table = 0x17_0000u64;
4157            for (address, words) in [
4158                (E2E_CONTEXT_TABLE, vec![directory | 1, 65, 0, 0]),
4159                (directory + 8, vec![pasid_table | 1]),
4160                (
4161                    pasid_table + 64,
4162                    vec![
4163                        E2E_PT_L4 | 1 | (2 << 2) | (2 << 6) | (1 << 9),
4164                        1 | (1 << 23),
4165                        0,
4166                        0,
4167                        0,
4168                        0,
4169                        0,
4170                        0,
4171                    ],
4172                ),
4173            ] {
4174                for (index, word) in words.into_iter().enumerate() {
4175                    gm.write_at(address + index as u64 * 8, &word.to_le_bytes())
4176                        .unwrap();
4177                }
4178            }
4179        }
4180
4181        // Build 4-level page tables: L4 → L3 → L2 → L1 → TARGET_GPA.
4182        let pte_l4 = SlPte::new()
4183            .with_r(true)
4184            .with_w(true)
4185            .with_address(E2E_PT_L3 >> 12);
4186        gm.write_at(E2E_PT_L4, pte_l4.into_bits().as_bytes())
4187            .unwrap();
4188
4189        let pte_l3 = SlPte::new()
4190            .with_r(true)
4191            .with_w(true)
4192            .with_address(E2E_PT_L2 >> 12);
4193        gm.write_at(E2E_PT_L3, pte_l3.into_bits().as_bytes())
4194            .unwrap();
4195
4196        let pte_l2 = SlPte::new()
4197            .with_r(true)
4198            .with_w(true)
4199            .with_address(E2E_PT_L1 >> 12);
4200        gm.write_at(E2E_PT_L2, pte_l2.into_bits().as_bytes())
4201            .unwrap();
4202
4203        let pte_l1 = SlPte::new()
4204            .with_r(true)
4205            .with_w(true)
4206            .with_address(E2E_TARGET_GPA >> 12);
4207        gm.write_at(E2E_PT_L1, pte_l1.into_bits().as_bytes())
4208            .unwrap();
4209
4210        // Write RTADDR register.
4211        let rtaddr = E2E_ROOT_TABLE | (u64::from(scalable) << 10);
4212        write64(&mut dev, 0x020, rtaddr);
4213        assert_eq!(read64(&mut dev, 0x020), rtaddr);
4214
4215        // GCMD: SRTP (set root table pointer).
4216        write32(&mut dev, 0x018, GcmdReg::new().with_srtp(true).into_bits());
4217        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4218        assert!(gsts.rtps(), "RTPS must be set after SRTP");
4219
4220        // =====================================================================
4221        // Step 5: Register-based invalidation (legacy only)
4222        // =====================================================================
4223
4224        if !scalable {
4225            // Context-cache invalidation: global.
4226            let ccmd = CcmdReg::new().with_icc(true).with_cirg(1); // global
4227            write64(&mut dev, 0x028, ccmd.into_bits());
4228            let ccmd_result = CcmdReg::from(read64(&mut dev, 0x028));
4229            assert!(!ccmd_result.icc(), "ICC must be cleared after invalidation");
4230            assert_eq!(ccmd_result.caig(), 1, "CAIG must echo CIRG");
4231
4232            // IOTLB invalidation: global.
4233            let iotlb_val = IotlbReg::new().with_ivt(true).with_iirg(1).into_bits();
4234            write64(&mut dev, Reg::IOTLB.0, iotlb_val);
4235            let iotlb_result = IotlbReg::from(read64(&mut dev, Reg::IOTLB.0));
4236            assert!(!iotlb_result.ivt(), "IVT must be cleared");
4237            assert_eq!(iotlb_result.iaig(), 1, "IAIG must echo IIRG");
4238        }
4239
4240        // =====================================================================
4241        // Step 6–7: Enable queued invalidation
4242        // =====================================================================
4243
4244        // QS=0: 4KB, with 256 narrow or 128 wide descriptors.
4245        let stride = if dw { 32 } else { 16 };
4246        let iqa = IqaReg::new()
4247            .with_qs(0)
4248            .with_dw(dw)
4249            .with_iqa(E2E_IQ_BASE >> 12);
4250        write64(&mut dev, 0x090, iqa.into_bits());
4251        assert_eq!(read64(&mut dev, 0x090), iqa.into_bits());
4252
4253        // Enable QI.
4254        write32(&mut dev, 0x018, GcmdReg::new().with_qie(true).into_bits());
4255        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4256        assert!(gsts.qies(), "QIES must be set after QIE");
4257
4258        // Verify IQH starts at 0.
4259        assert_eq!(read64(&mut dev, 0x080), 0, "IQH must start at 0");
4260
4261        // =====================================================================
4262        // Step 10: Enable translation
4263        // =====================================================================
4264
4265        // GCMD is a write-only register where toggle bits are compared against
4266        // GSTS. Must include the current state of all toggle bits (QIE=1) plus
4267        // the new bit (TE=1) to avoid inadvertently disabling QI.
4268        write32(
4269            &mut dev,
4270            0x018,
4271            GcmdReg::new().with_te(true).with_qie(true).into_bits(),
4272        );
4273        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4274        assert!(gsts.tes(), "TES must be set after TE");
4275        assert!(gsts.qies(), "QIES must remain set");
4276
4277        // =====================================================================
4278        // Step 11: Submit invalidation queue descriptors
4279        // =====================================================================
4280
4281        // Write 3 descriptors: context-cache invalidate, IOTLB invalidate,
4282        // invalidation-wait with status write.
4283
4284        // Descriptor 0: context-cache invalidation (global, type=0x01).
4285        let desc0 = spec::invalidation::InvalidationDescriptor {
4286            dw0: DescriptorType::CONTEXT_CACHE_INVALIDATE.0 as u32 | (1u32 << 4), // global granularity
4287            dw1: 0,
4288            dw2: 0,
4289            dw3: 0,
4290        };
4291        gm.write_at(E2E_IQ_BASE, desc0.as_bytes()).unwrap();
4292
4293        // Descriptor 1: IOTLB invalidation (global, type=0x02).
4294        let desc1 = spec::invalidation::InvalidationDescriptor {
4295            dw0: DescriptorType::IOTLB_INVALIDATE.0 as u32 | (1u32 << 4), // global
4296            dw1: 0,
4297            dw2: 0,
4298            dw3: 0,
4299        };
4300        gm.write_at(E2E_IQ_BASE + stride, desc1.as_bytes()).unwrap();
4301
4302        // Descriptor 2: invalidation-wait with status write (type=0x05).
4303        let iw_lo = InvalidationWaitDw0Dw1::new()
4304            .with_desc_type(DescriptorType::INVALIDATION_WAIT.0)
4305            .with_sw(true)
4306            .with_status_data(0xDEAD_BEEF);
4307        let iw_hi = InvalidationWaitDw2Dw3::new().with_sal(E2E_IQ_STATUS >> 2);
4308        let desc2 = spec::invalidation::InvalidationDescriptor {
4309            dw0: iw_lo.into_bits() as u32,
4310            dw1: (iw_lo.into_bits() >> 32) as u32,
4311            dw2: iw_hi.into_bits() as u32,
4312            dw3: (iw_hi.into_bits() >> 32) as u32,
4313        };
4314        gm.write_at(E2E_IQ_BASE + 2 * stride, desc2.as_bytes())
4315            .unwrap();
4316
4317        // Clear status location.
4318        gm.write_at(E2E_IQ_STATUS, &0u32.to_le_bytes()).unwrap();
4319
4320        write64(&mut dev, 0x088, 3 * stride);
4321
4322        // Verify head advanced to tail.
4323        let iqh = IqhReg::from(read64(&mut dev, 0x080));
4324        assert_eq!(
4325            iqh.head_offset(),
4326            3 * stride,
4327            "IQH must advance to tail after processing"
4328        );
4329
4330        // Verify status data was written by INVALIDATION_WAIT.
4331        let status: u32 = gm.read_plain(E2E_IQ_STATUS).unwrap();
4332        assert_eq!(
4333            status, 0xDEAD_BEEF,
4334            "INVALIDATION_WAIT must write status data"
4335        );
4336
4337        // =====================================================================
4338        // Step 12: DMA translation via VtdTranslator
4339        // =====================================================================
4340        let translator = shared.translator();
4341
4342        // Translate IOVA 0x0 → should map to E2E_TARGET_GPA.
4343        let gpa = iommu_common::IommuTranslator::translate(
4344            &translator,
4345            E2E_TEST_RID,
4346            0x0000,
4347            false, // read
4348            |gpa| {
4349                assert_eq!(gm.read_plain::<[u8; 2]>(gpa).unwrap(), [0, 0]);
4350                gpa
4351            },
4352        )
4353        .unwrap();
4354        assert_eq!(gpa, E2E_TARGET_GPA, "IOVA 0x0 must map to target GPA");
4355        assert_eq!(
4356            u64::from_le(gm.read_plain::<u64>(E2E_PT_L1).unwrap()),
4357            pte_l1.into_bits() | if scalable { 1 << 8 } else { 0 },
4358        );
4359
4360        // Translate IOVA 0x0 with write.
4361        let gpa = iommu_common::IommuTranslator::translate(
4362            &translator,
4363            E2E_TEST_RID,
4364            0x0000,
4365            true, // write
4366            |gpa| {
4367                gm.write_at(gpa, &[0x5a, 0xa5]).unwrap();
4368                gpa
4369            },
4370        )
4371        .unwrap();
4372        assert_eq!(gpa, E2E_TARGET_GPA, "IOVA 0x0 write must map to target GPA");
4373        let payload =
4374            iommu_common::IommuTranslator::translate(&translator, E2E_TEST_RID, 0, false, |gpa| {
4375                gm.read_plain::<[u8; 2]>(gpa).unwrap()
4376            })
4377            .unwrap();
4378        assert_eq!(payload, [0x5a, 0xa5]);
4379        for (address, original, leaf) in [
4380            (E2E_PT_L4, pte_l4, false),
4381            (E2E_PT_L3, pte_l3, false),
4382            (E2E_PT_L2, pte_l2, false),
4383            (E2E_PT_L1, pte_l1, true),
4384        ] {
4385            assert_eq!(
4386                u64::from_le(gm.read_plain::<u64>(address).unwrap()),
4387                original.into_bits()
4388                    | if scalable {
4389                        (1 << 8) | if leaf { 1 << 9 } else { 0 }
4390                    } else {
4391                        0
4392                    },
4393            );
4394        }
4395
4396        // Translate with page offset.
4397        let gpa = iommu_common::IommuTranslator::translate(
4398            &translator,
4399            E2E_TEST_RID,
4400            0x0ABC,
4401            false,
4402            |gpa| gpa,
4403        )
4404        .unwrap();
4405        assert_eq!(
4406            gpa,
4407            E2E_TARGET_GPA + 0xABC,
4408            "IOVA page offset must be preserved"
4409        );
4410
4411        // =====================================================================
4412        // Step 13–14: Set up interrupt remapping
4413        // =====================================================================
4414
4415        // Program IRTE at index 0: vector=0x42, DST=5 (xAPIC), fixed delivery.
4416        let irte = Irte {
4417            lo: IrteLo::new()
4418                .with_p(true)
4419                .with_vector(0x42)
4420                .with_dst(0x0500) // xAPIC: APIC ID in bits 15:8
4421                .with_dlm(0) // Fixed delivery
4422                .with_dm(false), // Physical
4423            hi: IrteHi::new()
4424                .with_svt(0b01) // Verify SID
4425                .with_sq(0b00) // Exact match
4426                .with_sid(E2E_TEST_RID),
4427        };
4428        gm.write_at(E2E_IRT_BASE, irte.as_bytes()).unwrap();
4429
4430        // Write IRTA: base at E2E_IRT_BASE, S=0 (2 entries), EIME=0.
4431        let irta = IrtaReg::new()
4432            .with_irta(E2E_IRT_BASE >> 12)
4433            .with_s(0) // 2 entries
4434            .with_eime(false);
4435        write64(&mut dev, 0x0B8, irta.into_bits());
4436
4437        // GCMD: SIRTP (set IRT pointer). Must preserve toggle bits.
4438        write32(
4439            &mut dev,
4440            0x018,
4441            GcmdReg::new()
4442                .with_sirtp(true)
4443                .with_te(true)
4444                .with_qie(true)
4445                .into_bits(),
4446        );
4447        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4448        assert!(gsts.irtps(), "IRTPS must be set after SIRTP");
4449
4450        // GCMD: IRE (enable interrupt remapping). Must preserve toggle bits.
4451        write32(
4452            &mut dev,
4453            0x018,
4454            GcmdReg::new()
4455                .with_ire(true)
4456                .with_te(true)
4457                .with_qie(true)
4458                .into_bits(),
4459        );
4460        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4461        assert!(gsts.ires(), "IRES must be set after IRE");
4462
4463        // =====================================================================
4464        // Step 15: MSI remapping via VtdSignalMsi
4465        // =====================================================================
4466        let inner_msi = Arc::new(RecordingMsi::new());
4467        let wrapper = shared.wrap_signal_msi(inner_msi.clone());
4468
4469        // Send remappable-format MSI: addr bit4=1, handle=0, SHV=0 → IRTE index 0.
4470        let msi_addr = 0xFEE0_0010u64;
4471        let msi_data = 0u32;
4472        wrapper.signal_msi(Some(E2E_TEST_RID as u32), msi_addr, msi_data);
4473
4474        // Verify remapped MSI was delivered.
4475        assert_eq!(
4476            inner_msi.count.load(Ordering::SeqCst),
4477            1,
4478            "Remapped MSI must be delivered"
4479        );
4480        let delivered_addr = inner_msi.last_addr.load(Ordering::SeqCst);
4481        let delivered_data = inner_msi.last_data.load(Ordering::SeqCst);
4482        // Destination should be APIC ID 5 in bits 19:12.
4483        assert_eq!(
4484            (delivered_addr >> 12) & 0xFF,
4485            5,
4486            "Remapped MSI dest must be APIC ID 5"
4487        );
4488        // Vector should be 0x42.
4489        assert_eq!(
4490            delivered_data & 0xFF,
4491            0x42,
4492            "Remapped MSI vector must be 0x42"
4493        );
4494
4495        // =====================================================================
4496        // Step 16: Fault recording — unmapped IOVA
4497        // =====================================================================
4498
4499        // IOVA 0x1000 maps to L1 entry index 1, which is not populated (zeros).
4500        let fault_result = iommu_common::IommuTranslator::translate(
4501            &translator,
4502            E2E_TEST_RID,
4503            0x1000,
4504            false,
4505            |gpa| gpa,
4506        );
4507        assert!(
4508            fault_result.is_err(),
4509            "Unmapped IOVA must produce a translation fault"
4510        );
4511
4512        // Verify fault was recorded in FRCD.
4513        let frcd_hi = read64(&mut dev, Reg::FRCD_DW2.0);
4514        let frcd = FrcdHi::from(frcd_hi);
4515        assert!(frcd.f(), "Fault must be recorded (F=1)");
4516        assert_eq!(
4517            frcd.sid(),
4518            E2E_TEST_RID,
4519            "Fault source ID must match test device"
4520        );
4521
4522        // Verify FSTS.PPF is set.
4523        let fsts = FstsReg::from(read32(&mut dev, 0x034));
4524        assert!(fsts.ppf(), "PPF must be set when fault is pending");
4525
4526        // Clear fault by writing 1 to F bit (RW1C).
4527        write64(&mut dev, Reg::FRCD_DW2.0, 1u64 << 63);
4528        let fsts = FstsReg::from(read32(&mut dev, 0x034));
4529        assert!(!fsts.ppf(), "PPF must clear when F is cleared");
4530
4531        // =====================================================================
4532        // Verify source validation: wrong BDF should be rejected
4533        // =====================================================================
4534        let wrong_rid_wrapper = shared.wrap_signal_msi(inner_msi.clone());
4535        let pre_count = inner_msi.count.load(Ordering::SeqCst);
4536        wrong_rid_wrapper.signal_msi(Some(0x0200), msi_addr, msi_data); // Wrong BDF
4537        assert_eq!(
4538            inner_msi.count.load(Ordering::SeqCst),
4539            pre_count,
4540            "MSI with wrong source ID must be dropped"
4541        );
4542
4543        // =====================================================================
4544        // Verify disable: turn off translation, check identity mapping
4545        // =====================================================================
4546        // Write GCMD with TE=0, preserving QIE and IRE.
4547        write32(
4548            &mut dev,
4549            0x018,
4550            GcmdReg::new()
4551                .with_te(false)
4552                .with_qie(true)
4553                .with_ire(true)
4554                .into_bits(),
4555        );
4556        let gsts = GstsReg::from(read32(&mut dev, 0x01C));
4557        assert!(!gsts.tes(), "TES must clear when TE=0");
4558        assert!(gsts.qies(), "QIES must remain set");
4559        assert!(gsts.ires(), "IRES must remain set");
4560
4561        // With translation disabled, IOVA = GPA (identity mapping).
4562        let gpa = iommu_common::IommuTranslator::translate(
4563            &translator,
4564            E2E_TEST_RID,
4565            0xDEAD_0000,
4566            false,
4567            |gpa| gpa,
4568        )
4569        .unwrap();
4570        assert_eq!(
4571            gpa, 0xDEAD_0000,
4572            "Disabled translation must return identity mapping"
4573        );
4574    }
4575}