Skip to main content

strat9_kernel/arch/x86_64/
iommu.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Intel VT-d backend (x86_64).
24//!
25//! Implements the legacy (non-scalable) translation path:
26//! * DMAR/DRHD discovery and CAP/ECAP probing;
27//! * shadow root/context/second-level tables (4 KiB, 2 MiB, 1 GiB leaves);
28//! * queued invalidation (QI) with WAIT completion;
29//! * interrupt-remapping table (IRTA/IRTE) and MSI doorbell allocation.
30//!
31//! Context entries follow the legacy format observed in ESXi
32//! (`IOMMU-ANALYSE.md` §3.4): `TT = 00` (second-level translation), AGAW in
33//! bits 6:4, domain id in the high qword bits 23:8.  QI descriptor types and
34//! the IR doorbell formula follow §3.6/§3.7 of the same document.
35//!
36//! Activation remains gated by [`HARDWARE_ACTIVATION_ENABLED`]: the code is
37//! complete but must be validated under QEMU `intel-iommu` before a boot path
38//! may enable it.  Until then `is_ready()` is false, `SYS_IOMMU_ACTIVATE`
39//! returns 0 and MSI stays on the physical path.
40
41use alloc::{collections::BTreeMap, vec::Vec};
42use core::sync::atomic::{AtomicBool, AtomicU16, Ordering};
43
44use super::super::iommu::{Backend, Discovery, IommuError, MsiAllocation};
45use crate::{
46    hardware::iommu::{DmaProt, DomainId, MappingKind, Sbdf},
47    memory,
48    sync::SpinLock,
49};
50
51/// Flip only after QEMU/hardware validation of the activation path.
52///
53/// Enabled by the kernel feature `iommu-activate`, so a normal build keeps
54/// translation disabled and the boot path unchanged.
55pub const HARDWARE_ACTIVATION_ENABLED: bool = cfg!(feature = "iommu-activate");
56
57/// Interrupt remapping is not enabled yet: MSI messages are still physical.
58/// Enabling IRE without programming every device's IRTE would drop MSI.
59pub const INTERRUPT_REMAPPING_ENABLED: bool = false;
60
61// Register offsets from the DRHD register base.
62const VTD_CAP: usize = 0x08;
63const VTD_ECAP: usize = 0x10;
64const VTD_GCMD: usize = 0x18;
65const VTD_GSTS: usize = 0x1c;
66const VTD_RTADDR: usize = 0x20;
67const VTD_IQH: usize = 0x80;
68const VTD_IQT: usize = 0x88;
69const VTD_IQA: usize = 0x90;
70const VTD_IRTA: usize = 0xb8;
71
72const GCMD_SIRTP: u32 = 1 << 24;
73const GCMD_IRE: u32 = 1 << 25;
74const GCMD_QI: u32 = 1 << 26;
75const GCMD_SRTP: u32 = 1 << 30;
76const GCMD_TE: u32 = 1 << 31;
77
78const GSTS_SIRTPS: u32 = 1 << 24;
79const GSTS_IRES: u32 = 1 << 25;
80const GSTS_QIES: u32 = 1 << 26;
81const GSTS_RTPS: u32 = 1 << 30;
82const GSTS_TES: u32 = 1 << 31;
83
84const ECAP_QI: u64 = 1 << 1;
85const ECAP_IR: u64 = 1 << 3;
86const ECAP_PT: u64 = 1 << 5;
87
88const CAP_CM: u64 = 1 << 7;
89
90/// Second-level page-table flags.
91const SL_PRESENT: u64 = 1 << 0;
92const SL_WRITE: u64 = 1 << 1;
93const SL_SUPERPAGE: u64 = 1 << 7;
94const SL_ADDR_MASK: u64 = 0x000f_ffff_ffff_f000;
95
96/// QI descriptor types (ESXi `IOMMU-ANALYSE.md` §3.6).
97const QI_CONTEXT: u64 = 1;
98const QI_IOTLB: u64 = 2;
99const QI_IRTE: u64 = 4;
100const QI_WAIT: u64 = 5;
101
102const QI_ENTRIES: usize = 256;
103const QI_SIZE_BYTES: usize = QI_ENTRIES * 16;
104
105/// Number of 128-bit IRTEs (one 4 KiB page).
106const IRTE_COUNT: usize = 256;
107
108struct Qi {
109    /// Physical address of the 4 KiB descriptor ring.
110    queue: u64,
111    /// Physical address of the WAIT status word.
112    status: u64,
113    /// MMIO base of the owning unit.
114    register_base: u64,
115    index: AtomicU16,
116}
117
118impl Qi {
119    fn submit(&self, qw0: u64, qw1: u64) {
120        let index = self.index.load(Ordering::Acquire) as usize;
121        // SAFETY: the ring is a 4 KiB page owned by this unit and `index`
122        // is always < QI_ENTRIES.
123        unsafe {
124            let base = memory::phys_to_virt(self.queue) as *mut u64;
125            core::ptr::write_volatile(base.add(index * 2), qw0);
126            core::ptr::write_volatile(base.add(index * 2 + 1), qw1);
127        }
128        core::sync::atomic::fence(Ordering::Release);
129        let next = (index + 1) % QI_ENTRIES;
130        self.index.store(next as u16, Ordering::Release);
131        // Tail is a byte offset; it wraps to 0 after the last descriptor.
132        let tail = ((next * 16) & (QI_SIZE_BYTES - 1)) as u64;
133        // SAFETY: MMIO write to this unit's IQT register.
134        unsafe {
135            core::ptr::write_volatile((self.register_base as usize + VTD_IQT) as *mut u64, tail);
136        }
137    }
138
139    fn wait(&self) {
140        // Status word: set to ~0, ask the unit to write 0 on completion.
141        // SAFETY: `status` is a 4 KiB page owned by this unit.
142        unsafe {
143            core::ptr::write_volatile(memory::phys_to_virt(self.status) as *mut u32, u32::MAX);
144        }
145        core::sync::atomic::fence(Ordering::SeqCst);
146        // WAIT descriptor: type 5, SW=1, status data 0, status address.
147        self.submit(QI_WAIT | (1 << 4), self.status);
148        for _ in 0..20_000_000 {
149            // SAFETY: as above.
150            let value = unsafe {
151                core::ptr::read_volatile(memory::phys_to_virt(self.status) as *const u32)
152            };
153            if value == 0 {
154                return;
155            }
156            core::hint::spin_loop();
157        }
158        log::warn!("[IOMMU] QI WAIT timeout");
159    }
160}
161
162struct Unit {
163    segment: u16,
164    #[allow(dead_code)]
165    register_base: u64,
166    virt: u64,
167    cap: u64,
168    ecap: u64,
169    qi: Option<Qi>,
170}
171
172struct DomainShadow {
173    slpt: u64,
174}
175
176struct IrTable {
177    phys: u64,
178    used: [u64; 4],
179}
180
181impl IrTable {
182    fn alloc(&mut self) -> Option<usize> {
183        for word in 0..self.used.len() {
184            let free = !self.used[word];
185            if free != 0 {
186                let bit = free.trailing_zeros() as usize;
187                self.used[word] |= 1u64 << bit;
188                return Some(word * 64 + bit);
189            }
190        }
191        None
192    }
193
194    fn free(&mut self, index: usize) {
195        if index < IRTE_COUNT {
196            self.used[index / 64] &= !(1u64 << (index % 64));
197        }
198    }
199}
200
201struct VtdState {
202    root: u64,
203    context_tables: BTreeMap<u8, u64>,
204    domains: BTreeMap<DomainId, DomainShadow>,
205    units: Vec<Unit>,
206    ir: Option<IrTable>,
207}
208
209static STATE: SpinLock<Option<VtdState>> = SpinLock::new(None);
210static ACTIVE: AtomicBool = AtomicBool::new(false);
211static IR_ACTIVE: AtomicBool = AtomicBool::new(false);
212static DISCOVERY: SpinLock<Option<Discovery>> = SpinLock::new(None);
213
214struct VtdBackend;
215
216static VTD: VtdBackend = VtdBackend;
217
218impl Backend for VtdBackend {
219    fn name(&self) -> &'static str {
220        "vt-d"
221    }
222
223    fn is_ready(&self) -> bool {
224        HARDWARE_ACTIVATION_ENABLED && STATE.lock().is_some()
225    }
226
227    fn activate(&self) -> Result<(), IommuError> {
228        if ACTIVE.load(Ordering::Acquire) {
229            return Ok(());
230        }
231        if !HARDWARE_ACTIVATION_ENABLED {
232            return Err(IommuError::NotReady);
233        }
234
235        let mut guard = STATE.lock();
236        let state = guard.as_mut().ok_or(IommuError::NotPresent)?;
237        if state.units.is_empty() {
238            return Err(IommuError::NotPresent);
239        }
240
241        // Clear residual state (ESXi `VTDIommuPrecheckAndCleanup`).
242        for unit in &mut state.units {
243            mmio_write32(unit.virt, VTD_GCMD, 0);
244            if !wait_gsts_clear(unit.virt) {
245                return Err(IommuError::Hardware);
246            }
247            // Queued invalidation is mandatory when CM=1.
248            if unit.ecap & ECAP_QI != 0 {
249                qi_setup(unit)?;
250            } else if unit.cap & CAP_CM != 0 {
251                log::warn!(
252                    "[IOMMU] unit seg={} requires QI (CM=1) but ECAP.QI is absent",
253                    unit.segment
254                );
255                return Err(IommuError::Unsupported);
256            }
257        }
258
259        // Root table, then context-entry translation.
260        // Devices that are not migrated yet get a pass-through context entry
261        // so GPU/USB/virtio keep using physical DMA instead of faulting.
262        install_passthrough_contexts(state)?;
263        for unit in &mut state.units {
264            mmio_write64(unit.virt, VTD_RTADDR, state.root);
265            mmio_write32(
266                unit.virt,
267                VTD_GCMD,
268                mmio_read32(unit.virt, VTD_GCMD) | GCMD_SRTP,
269            );
270            if !wait_bits(unit.virt, VTD_GSTS, GSTS_RTPS) {
271                return Err(IommuError::Hardware);
272            }
273        }
274
275        // Optional interrupt remapping (kept off until every MSI is an IRTE).
276        if INTERRUPT_REMAPPING_ENABLED && state.units.iter().any(|unit| unit.ecap & ECAP_IR != 0) {
277            match ir_enable(state) {
278                Ok(()) => IR_ACTIVE.store(true, Ordering::Release),
279                Err(err) => log::warn!("[IOMMU] interrupt remapping unavailable: {:?}", err),
280            }
281        }
282
283        // Finally enable DMA translation.
284        for unit in &mut state.units {
285            mmio_write32(
286                unit.virt,
287                VTD_GCMD,
288                mmio_read32(unit.virt, VTD_GCMD) | GCMD_TE,
289            );
290            if !wait_bits(unit.virt, VTD_GSTS, GSTS_TES) {
291                log::error!("[IOMMU] unit seg={} refused TE", unit.segment);
292                return Err(IommuError::Hardware);
293            }
294            flush_unit(unit, true, true);
295        }
296
297        ACTIVE.store(true, Ordering::Release);
298        log::info!(
299            "[IOMMU] VT-d translation enabled on {} unit(s), IR={}",
300            state.units.len(),
301            IR_ACTIVE.load(Ordering::Acquire)
302        );
303        Ok(())
304    }
305
306    fn invalidate_domain(&self, domain: DomainId) {
307        if !ACTIVE.load(Ordering::Acquire) {
308            return;
309        }
310        if let Some(state) = STATE.lock().as_ref() {
311            if state.domains.contains_key(&domain) {
312                for unit in &state.units {
313                    flush_unit(unit, false, true);
314                }
315            }
316        }
317    }
318
319    fn map(
320        &self,
321        domain: DomainId,
322        sbdf: Sbdf,
323        iova: u64,
324        phys: u64,
325        len: u64,
326        prot: DmaProt,
327        kind: MappingKind,
328    ) -> Result<(), IommuError> {
329        let mut guard = STATE.lock();
330        let state = guard.as_mut().ok_or(IommuError::NotPresent)?;
331
332        let context = match state.context_tables.get(&sbdf.bus) {
333            Some(context) => *context,
334            None => {
335                let context = alloc_zeroed_table()?;
336                state.context_tables.insert(sbdf.bus, context);
337                install_root_entry(state.root, sbdf.bus, context)?;
338                context
339            }
340        };
341
342        let slpt = match state.domains.get(&domain) {
343            Some(shadow) => shadow.slpt,
344            None => {
345                let slpt = alloc_zeroed_table()?;
346                state.domains.insert(domain, DomainShadow { slpt });
347                slpt
348            }
349        };
350
351        install_context_entry(context, sbdf, domain, slpt)?;
352
353        let mut offset = 0u64;
354        while offset < len {
355            if let Err(err) = install_leaf(slpt, iova + offset, phys + offset, kind, prot) {
356                let mut done = 0u64;
357                while done < offset {
358                    let _ = clear_leaf(slpt, iova + done, kind);
359                    done += kind.size();
360                }
361                return Err(err);
362            }
363            offset += kind.size();
364        }
365
366        if ACTIVE.load(Ordering::Acquire) {
367            for unit in &state.units {
368                flush_unit(unit, true, true);
369            }
370        }
371        Ok(())
372    }
373
374    fn unmap(
375        &self,
376        domain: DomainId,
377        _sbdf: Sbdf,
378        iova: u64,
379        len: u64,
380        kind: MappingKind,
381    ) -> Result<(), IommuError> {
382        let guard = STATE.lock();
383        let state = guard.as_ref().ok_or(IommuError::NotPresent)?;
384        let shadow = state
385            .domains
386            .get(&domain)
387            .ok_or(IommuError::InvalidDomain)?;
388
389        let mut offset = 0u64;
390        while offset < len {
391            clear_leaf(shadow.slpt, iova + offset, kind)?;
392            offset += kind.size();
393        }
394
395        drop(guard);
396        if ACTIVE.load(Ordering::Acquire) {
397            if let Some(state) = STATE.lock().as_ref() {
398                for unit in &state.units {
399                    flush_unit(unit, false, true);
400                }
401            }
402        }
403        Ok(())
404    }
405
406    fn interrupt_remapping(&self) -> bool {
407        STATE
408            .lock()
409            .as_ref()
410            .map(|state| state.units.iter().any(|unit| unit.ecap & ECAP_IR != 0))
411            .unwrap_or(false)
412    }
413
414    fn interrupt_remapping_active(&self) -> bool {
415        IR_ACTIVE.load(Ordering::Acquire)
416    }
417
418    fn allocate_msi(&self, sbdf: Sbdf, vector: u8) -> Result<MsiAllocation, IommuError> {
419        if !IR_ACTIVE.load(Ordering::Acquire) {
420            return Err(IommuError::NotReady);
421        }
422        let mut guard = STATE.lock();
423        let state = guard.as_mut().ok_or(IommuError::NotPresent)?;
424        let ir = state.ir.as_mut().ok_or(IommuError::NotReady)?;
425        let index = ir.alloc().ok_or(IommuError::Hardware)?;
426        let lapic = crate::arch::x86_64::apic::lapic_id();
427        write_irte(ir, index, sbdf, vector, lapic);
428        for unit in &state.units {
429            if unit.ecap & ECAP_IR != 0 {
430                flush_unit(unit, false, false);
431                qi_flush_ir(unit);
432            }
433        }
434        // ESXi doorbell: 0xFEE00018 | ((index * 32) & 0xFFFE0), data = 0.
435        let address = 0xFEE0_0018u64 | (((index as u64) * 32) & 0xFFFE0);
436        Ok(MsiAllocation {
437            cookie: index as u32 + 1,
438            address,
439            data: 0,
440        })
441    }
442
443    fn free_msi(&self, cookie: u32) -> Result<(), IommuError> {
444        if cookie == 0 {
445            return Err(IommuError::InvalidDomain);
446        }
447        let index = (cookie - 1) as usize;
448        let mut guard = STATE.lock();
449        let state = guard.as_mut().ok_or(IommuError::NotPresent)?;
450        let phys = state.ir.as_ref().ok_or(IommuError::NotReady)?.phys;
451        if index >= IRTE_COUNT {
452            return Err(IommuError::InvalidDomain);
453        }
454        // Clear the IRTE first, then flush the IR caches.
455        // SAFETY: the IR table is a 4 KiB page and index < IRTE_COUNT.
456        unsafe {
457            let base = memory::phys_to_virt(phys) as *mut u64;
458            core::ptr::write_volatile(base.add(index * 2), 0);
459            core::ptr::write_volatile(base.add(index * 2 + 1), 0);
460        }
461        for unit in &state.units {
462            if unit.ecap & ECAP_IR != 0 {
463                qi_flush_ir(unit);
464            }
465        }
466        if let Some(ir) = state.ir.as_mut() {
467            ir.free(index);
468        }
469        Ok(())
470    }
471}
472
473// =============================================================================
474// Discovery
475// =============================================================================
476
477/// Parse the DMAR, probe the units and build the shadow root table.
478pub fn init() -> Discovery {
479    let Some(dmar) = crate::acpi::get_dmar() else {
480        *DISCOVERY.lock() = Some(Discovery::absent());
481        return Discovery::absent();
482    };
483
484    let units = match dmar.drhds() {
485        Ok(units) => units,
486        Err(err) => {
487            log::warn!("[IOMMU] DMAR DRHD parse error: {:?}", err);
488            Vec::new()
489        }
490    };
491
492    let mut probed = Vec::new();
493    for unit in &units {
494        let virt = match map_mmio(unit.register_base) {
495            Some(virt) => virt,
496            None => continue,
497        };
498        let cap = mmio_read64(virt, VTD_CAP);
499        let ecap = mmio_read64(virt, VTD_ECAP);
500        log::info!(
501            "[IOMMU] DRHD seg={} base={:#x} include_all={} scopes={} cap={:#x} ecap={:#x}",
502            unit.segment,
503            unit.register_base,
504            unit.include_pci_all(),
505            unit.scopes.len(),
506            cap,
507            ecap
508        );
509        probed.push(Unit {
510            segment: unit.segment,
511            register_base: unit.register_base,
512            virt,
513            cap,
514            ecap,
515            qi: None,
516        });
517    }
518
519    let mut ready = false;
520    match alloc_zeroed_table() {
521        Ok(root) => {
522            let state = VtdState {
523                root,
524                context_tables: BTreeMap::new(),
525                domains: BTreeMap::new(),
526                units: probed,
527                ir: None,
528            };
529            ready = !state.units.is_empty();
530            *STATE.lock() = Some(state);
531            log::info!(
532                "[IOMMU] VT-d shadow root at {:#x} ({} unit(s), activation {})",
533                root,
534                ready as u8,
535                if HARDWARE_ACTIVATION_ENABLED {
536                    "enabled"
537                } else {
538                    "locked"
539                }
540            );
541        }
542        Err(err) => {
543            log::warn!("[IOMMU] cannot allocate VT-d root table: {:?}", err);
544            *STATE.lock() = None;
545        }
546    }
547
548    let discovery = Discovery {
549        present: true,
550        ready: ready && HARDWARE_ACTIVATION_ENABLED,
551        backend: "vt-d",
552        units: units.len() as u32,
553        rmrrs: dmar.rmrrs().map(|v| v.len()).unwrap_or(0) as u32,
554        atsrs: dmar.atsrs().map(|v| v.len()).unwrap_or(0) as u32,
555        host_address_width: dmar.host_address_width(),
556        intr_remap: dmar.intr_remap_supported(),
557        x2apic_opt_out: dmar.x2apic_opt_out(),
558    };
559    *DISCOVERY.lock() = Some(discovery);
560    discovery
561}
562
563/// Summary recorded by [`init`].
564pub fn discovery() -> Discovery {
565    DISCOVERY
566        .lock()
567        .as_ref()
568        .copied()
569        .unwrap_or_else(Discovery::absent)
570}
571
572/// Backend handle, available only when a DMAR was found.
573pub fn backend() -> Option<&'static dyn Backend> {
574    let present = DISCOVERY
575        .lock()
576        .as_ref()
577        .map(|discovery| discovery.present)
578        .unwrap_or(false);
579    if present {
580        Some(&VTD)
581    } else {
582        None
583    }
584}
585
586// =============================================================================
587// QI
588// =============================================================================
589
590fn qi_setup(unit: &mut Unit) -> Result<(), IommuError> {
591    let queue = alloc_zeroed_table()?;
592    let status = alloc_zeroed_table()?;
593    let qi = Qi {
594        queue,
595        status,
596        register_base: unit.virt,
597        index: AtomicU16::new(0),
598    };
599    mmio_write64(unit.virt, VTD_IQA, queue);
600    mmio_write64(unit.virt, VTD_IQT, 0);
601    if mmio_read64(unit.virt, VTD_IQH) != 0 {
602        return Err(IommuError::Hardware);
603    }
604    unit.qi = Some(qi);
605    mmio_write32(
606        unit.virt,
607        VTD_GCMD,
608        mmio_read32(unit.virt, VTD_GCMD) | GCMD_QI,
609    );
610    if !wait_bits(unit.virt, VTD_GSTS, GSTS_QIES) {
611        return Err(IommuError::Hardware);
612    }
613    Ok(())
614}
615
616fn wait_gsts_clear(virt: u64) -> bool {
617    for _ in 0..1_000_000 {
618        let gsts = mmio_read32(virt, VTD_GSTS);
619        if gsts & (GSTS_TES | GSTS_RTPS | GSTS_IRES | GSTS_QIES | GSTS_SIRTPS) == 0 {
620            return true;
621        }
622        core::hint::spin_loop();
623    }
624    false
625}
626
627fn qi_flush_ir(unit: &Unit) {
628    if let Some(qi) = &unit.qi {
629        qi.submit(QI_IRTE, 0);
630        qi.wait();
631    }
632}
633
634fn flush_unit(unit: &Unit, context: bool, iotlb: bool) {
635    if let Some(qi) = &unit.qi {
636        if context {
637            qi.submit(QI_CONTEXT, 0);
638        }
639        if iotlb {
640            qi.submit(QI_IOTLB, 0);
641        }
642        if context || iotlb {
643            qi.wait();
644        }
645        return;
646    }
647    // Register-based fallback (only valid when CAP.CM=0).
648    if context {
649        mmio_write64(unit.virt, 0x28, (1u64 << 63) | (1u64 << 61));
650    }
651    if iotlb {
652        let gcmd = mmio_read64(unit.virt, VTD_GCMD);
653        mmio_write64(unit.virt, VTD_GCMD, gcmd | (1u64 << 61));
654    }
655}
656
657// =============================================================================
658// IR
659// =============================================================================
660
661fn ir_enable(state: &mut VtdState) -> Result<(), IommuError> {
662    let phys = alloc_zeroed_table()?;
663    let x2apic = crate::arch::x86_64::apic::lapic_id() > 0xff;
664    state.ir = Some(IrTable { phys, used: [0; 4] });
665
666    for unit in &mut state.units {
667        if unit.ecap & ECAP_IR == 0 {
668            continue;
669        }
670        // One page = 256 IRTEs, so the size field is 0.
671        let irta = phys | if x2apic { 0x800 } else { 0 };
672        mmio_write64(unit.virt, VTD_IRTA, irta);
673        mmio_write32(
674            unit.virt,
675            VTD_GCMD,
676            mmio_read32(unit.virt, VTD_GCMD) | GCMD_SIRTP,
677        );
678        if !wait_bits(unit.virt, VTD_GSTS, GSTS_SIRTPS) {
679            return Err(IommuError::Hardware);
680        }
681        qi_flush_ir(unit);
682        mmio_write32(
683            unit.virt,
684            VTD_GCMD,
685            mmio_read32(unit.virt, VTD_GCMD) | GCMD_IRE,
686        );
687        if !wait_bits(unit.virt, VTD_GSTS, GSTS_IRES) {
688            return Err(IommuError::Hardware);
689        }
690    }
691    Ok(())
692}
693
694fn write_irte(ir: &IrTable, index: usize, sbdf: Sbdf, vector: u8, lapic: u32) {
695    let sid = ((sbdf.bus as u64) << 8) | ((sbdf.device as u64) << 3) | (sbdf.function as u64 & 0x7);
696    let destination = lapic as u64;
697    // Extended IRTE: P | SID | SQ | SVT=01 | vector | destination low.
698    let qw0 = SL_PRESENT
699        | (sid << 16)
700        | (1u64 << 32)
701        | (1u64 << 33)
702        | ((vector as u64) << 40)
703        | ((destination & 0xffff) << 48);
704    let qw1 = (destination >> 16) & 0xffff_ffff;
705    // SAFETY: the IR table is a zeroed 4 KiB page, index < 256.
706    unsafe {
707        let base = memory::phys_to_virt(ir.phys) as *mut u64;
708        core::ptr::write_volatile(base.add(index * 2), qw0);
709        core::ptr::write_volatile(base.add(index * 2 + 1), qw1);
710    }
711}
712
713// =============================================================================
714// Table helpers
715// =============================================================================
716
717fn alloc_zeroed_table() -> Result<u64, IommuError> {
718    let frame = crate::sync::with_irqs_disabled(|token| memory::allocate_phys_contiguous(token, 0))
719        .map_err(|_| IommuError::Hardware)?;
720    let phys = frame.start_address.as_u64();
721    let virt = memory::phys_to_virt(phys) as *mut u8;
722    // SAFETY: the buddy allocator returned a full 4 KiB frame owned by us.
723    unsafe {
724        core::ptr::write_bytes(virt, 0, 4096);
725    }
726    Ok(phys)
727}
728
729fn map_mmio(base: u64) -> Option<u64> {
730    if base == 0 {
731        return None;
732    }
733    memory::paging::ensure_identity_map_range(base, 0x1000);
734    Some(memory::phys_to_virt(base))
735}
736
737fn mmio_read32(virt: u64, offset: usize) -> u32 {
738    // SAFETY: `virt` maps a full 4 KiB register page.
739    unsafe { core::ptr::read_volatile((virt as usize + offset) as *const u32) }
740}
741
742fn mmio_read64(virt: u64, offset: usize) -> u64 {
743    // SAFETY: as above.
744    unsafe { core::ptr::read_volatile((virt as usize + offset) as *const u64) }
745}
746
747fn mmio_write32(virt: u64, offset: usize, value: u32) {
748    // SAFETY: as above.
749    unsafe { core::ptr::write_volatile((virt as usize + offset) as *mut u32, value) }
750}
751
752fn mmio_write64(virt: u64, offset: usize, value: u64) {
753    // SAFETY: as above.
754    unsafe { core::ptr::write_volatile((virt as usize + offset) as *mut u64, value) }
755}
756
757fn wait_bits(virt: u64, offset: usize, mask: u32) -> bool {
758    for _ in 0..1_000_000 {
759        if mmio_read32(virt, offset) & mask == mask {
760            return true;
761        }
762        core::hint::spin_loop();
763    }
764    false
765}
766
767unsafe fn table_read(phys: u64, index: usize) -> u64 {
768    let ptr = memory::phys_to_virt(phys) as *const u64;
769    // SAFETY: `phys` is a 4 KiB table owned by the backend.
770    unsafe { core::ptr::read_volatile(ptr.add(index)) }
771}
772
773unsafe fn table_write(phys: u64, index: usize, value: u64) {
774    let ptr = memory::phys_to_virt(phys) as *mut u64;
775    // SAFETY: as above.
776    unsafe { core::ptr::write_volatile(ptr.add(index), value) }
777}
778
779fn install_root_entry(root: u64, bus: u8, context: u64) -> Result<(), IommuError> {
780    let entry = SL_PRESENT | (context & SL_ADDR_MASK);
781    // SAFETY: `root` is a 4 KiB root table; the bus selects a 16-byte entry.
782    unsafe {
783        table_write(root, (bus as usize) * 2, entry);
784        table_write(root, (bus as usize) * 2 + 1, 0);
785    }
786    Ok(())
787}
788
789/// Give every PCI function a pass-through context entry unless it already has
790/// a translated one.
791///
792/// This lets devices that still program physical addresses (GPU, USB,
793/// virtio-console/rng, boot loader) keep working when translation is enabled.
794/// It is not an isolation guarantee for those devices, but it keeps the boot
795/// alive while drivers are migrated one by one.
796fn install_passthrough_contexts(state: &mut VtdState) -> Result<(), IommuError> {
797    if state.units.is_empty() {
798        return Ok(());
799    }
800    if state.units.iter().any(|unit| unit.ecap & ECAP_PT == 0) {
801        log::warn!(
802            "[IOMMU] pass-through unsupported by a DRHD; activation needs all DMA masters migrated"
803        );
804        return Err(IommuError::Unsupported);
805    }
806
807    // Pass-through legacy context entry: P=1, TT=10.
808    const PASSTHROUGH_ENTRY: u64 = SL_PRESENT | (0b10 << 2);
809
810    for bus in 0..=u8::MAX {
811        let context = match state.context_tables.get(&bus) {
812            Some(context) => *context,
813            None => {
814                let context = alloc_zeroed_table()?;
815                state.context_tables.insert(bus, context);
816                install_root_entry(state.root, bus, context)?;
817                context
818            }
819        };
820        for devfn in 0..256usize {
821            // SAFETY: `context` is a 4 KiB table, devfn < 256.
822            let low = unsafe { table_read(context, devfn * 2) };
823            if low & SL_PRESENT == 0 {
824                // SAFETY: same as above.
825                unsafe {
826                    table_write(context, devfn * 2, PASSTHROUGH_ENTRY);
827                    table_write(context, devfn * 2 + 1, 0);
828                }
829            }
830        }
831    }
832    Ok(())
833}
834
835/// Legacy context entry (ESXi `IOMMU-ANALYSE.md` §3.4).
836///
837/// `TT = 00` selects second-level translation; AGAW is encoded in bits 6:4
838/// and repeated in the low bits of the second qword; the domain id occupies
839/// bits 23:8 of the second qword.
840fn install_context_entry(
841    context: u64,
842    sbdf: Sbdf,
843    domain: DomainId,
844    slpt: u64,
845) -> Result<(), IommuError> {
846    // AGAW 010 = 48-bit guest address width.
847    const AGAW: u64 = 0b010;
848    let low = SL_PRESENT | (AGAW << 4) | (slpt & SL_ADDR_MASK);
849    let high = (((domain.raw() as u64) << 8) & 0x00ff_ff00) | AGAW;
850    let index = ((sbdf.device as usize) << 3) | sbdf.function as usize;
851    // SAFETY: `context` is a 4 KiB table, index < 256.
852    unsafe {
853        table_write(context, index * 2, low);
854        table_write(context, index * 2 + 1, high);
855    }
856    Ok(())
857}
858
859fn next_table(table: u64, index: usize) -> Result<u64, IommuError> {
860    // SAFETY: `table` is a 4 KiB table and `index` < 512.
861    let entry = unsafe { table_read(table, index) };
862    if entry & SL_PRESENT != 0 {
863        return Ok(entry & SL_ADDR_MASK);
864    }
865    let fresh = alloc_zeroed_table()?;
866    // SAFETY: same as above.
867    unsafe {
868        table_write(table, index, SL_PRESENT | SL_WRITE | (fresh & SL_ADDR_MASK));
869    }
870    Ok(fresh)
871}
872
873fn install_leaf(
874    slpt: u64,
875    iova: u64,
876    phys: u64,
877    kind: MappingKind,
878    prot: DmaProt,
879) -> Result<(), IommuError> {
880    let mut flags = SL_PRESENT;
881    if prot.writable() {
882        flags |= SL_WRITE;
883    }
884    let pml4 = ((iova >> 39) & 0x1ff) as usize;
885    let pdpt = ((iova >> 30) & 0x1ff) as usize;
886    let pd = ((iova >> 21) & 0x1ff) as usize;
887    let pt = ((iova >> 12) & 0x1ff) as usize;
888
889    let pdpt_table = next_table(slpt, pml4)?;
890    if kind == MappingKind::Page1G {
891        // SAFETY: `pdpt_table` is a 4 KiB table.
892        unsafe {
893            table_write(
894                pdpt_table,
895                pdpt,
896                flags | SL_SUPERPAGE | (phys & SL_ADDR_MASK & !((1u64 << 30) - 1)),
897            );
898        }
899        return Ok(());
900    }
901
902    let pd_table = next_table(pdpt_table, pdpt)?;
903    if kind == MappingKind::Page2M {
904        // SAFETY: `pd_table` is a 4 KiB table.
905        unsafe {
906            table_write(
907                pd_table,
908                pd,
909                flags | SL_SUPERPAGE | (phys & SL_ADDR_MASK & !((1u64 << 21) - 1)),
910            );
911        }
912        return Ok(());
913    }
914
915    let pt_table = next_table(pd_table, pd)?;
916    // SAFETY: `pt_table` is a 4 KiB table.
917    unsafe {
918        table_write(pt_table, pt, flags | (phys & SL_ADDR_MASK));
919    }
920    Ok(())
921}
922
923fn clear_leaf(slpt: u64, iova: u64, kind: MappingKind) -> Result<(), IommuError> {
924    let pml4 = ((iova >> 39) & 0x1ff) as usize;
925    let pdpt = ((iova >> 30) & 0x1ff) as usize;
926    let pd = ((iova >> 21) & 0x1ff) as usize;
927    let pt = ((iova >> 12) & 0x1ff) as usize;
928
929    // SAFETY: all tables are 4 KiB and indices are masked to 9 bits.
930    unsafe {
931        let pdpt_entry = table_read(slpt, pml4);
932        if pdpt_entry & SL_PRESENT == 0 {
933            return Ok(());
934        }
935        let pdpt_table = pdpt_entry & SL_ADDR_MASK;
936        if kind == MappingKind::Page1G {
937            table_write(pdpt_table, pdpt, 0);
938            return Ok(());
939        }
940        let pd_entry = table_read(pdpt_table, pdpt);
941        if pd_entry & SL_PRESENT == 0 {
942            return Ok(());
943        }
944        let pd_table = pd_entry & SL_ADDR_MASK;
945        if kind == MappingKind::Page2M {
946            table_write(pd_table, pd, 0);
947            return Ok(());
948        }
949        let pt_entry = table_read(pd_table, pt);
950        if pt_entry & SL_PRESENT == 0 {
951            return Ok(());
952        }
953        let pt_table = pt_entry & SL_ADDR_MASK;
954        table_write(pt_table, pt, 0);
955    }
956    Ok(())
957}