Skip to main content

strat9_kernel/arch/iommu/
mod.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//! Architecture-neutral IOMMU backend interface.
24//!
25//! The hardware-specific programming (root/context tables, invalidation,
26//! fault registers) lives behind [`Backend`].  The generic layer only decides
27//! which backend is authoritative and whether it may be activated.
28//!
29//! P0 ships the discovery skeleton: the x86_64 backend reports what the DMAR
30//! describes but keeps [`Backend::is_ready`] false until the actual table
31//! programming has been validated.  Consequently
32//! `hardware::iommu::activate()` still returns `false` and no device is ever
33//! silently placed behind an untested translation unit.
34
35use crate::hardware::iommu::{DmaProt, DomainId, MappingKind, Sbdf};
36
37/// Errors returned by an IOMMU backend.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum IommuError {
40    /// No unit is described by the firmware.
41    NotPresent,
42    /// The backend exists but has not been validated.
43    NotReady,
44    /// A feature is not implemented by this backend.
45    Unsupported,
46    /// The hardware refused a programming step.
47    Hardware,
48    /// The domain id is not known to the hardware layer.
49    InvalidDomain,
50}
51
52/// Summary produced by firmware discovery.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Discovery {
55    /// True when a DMAR (or IVRS for AMD) table was found.
56    pub present: bool,
57    /// True when the backend may be activated.
58    pub ready: bool,
59    /// Short backend name for logs.
60    pub backend: &'static str,
61    /// Number of remapping hardware units.
62    pub units: u32,
63    /// Number of reserved memory regions.
64    pub rmrrs: u32,
65    /// Number of ATS-capable root-port structures.
66    pub atsrs: u32,
67    /// Host address width, in bits.
68    pub host_address_width: u8,
69    /// Interrupt remapping is advertised.
70    pub intr_remap: bool,
71    /// Firmware asked the OS to keep x2APIC disabled.
72    pub x2apic_opt_out: bool,
73}
74
75impl Discovery {
76    /// Result when no IOMMU exists.
77    pub const fn absent() -> Self {
78        Self {
79            present: false,
80            ready: false,
81            backend: "none",
82            units: 0,
83            rmrrs: 0,
84            atsrs: 0,
85            host_address_width: 0,
86            intr_remap: false,
87            x2apic_opt_out: false,
88        }
89    }
90}
91
92/// One MSI message allocated through interrupt remapping.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct MsiAllocation {
95    /// Opaque cookie for [`Backend::free_msi`] (0 is invalid).
96    pub cookie: u32,
97    /// Message address the device must write to.
98    pub address: u64,
99    /// Message data (0 when delivered through an IRTE doorbell).
100    pub data: u32,
101}
102
103/// A hardware translation backend.
104pub trait Backend: Send + Sync {
105    /// Stable backend name (`"vt-d"`, `"amd-vi"`, `"none"`).
106    fn name(&self) -> &'static str;
107
108    /// True only when the backend has been validated end to end.
109    fn is_ready(&self) -> bool;
110
111    /// Program translation for every registered domain and enable it.
112    fn activate(&self) -> Result<(), IommuError>;
113
114    /// Flush cached translations for one domain.
115    fn invalidate_domain(&self, domain: DomainId);
116
117    /// Install one shadow mapping in the backend's page tables.
118    fn map(
119        &self,
120        _domain: DomainId,
121        _sbdf: Sbdf,
122        _iova: u64,
123        _phys: u64,
124        _len: u64,
125        _prot: DmaProt,
126        _kind: MappingKind,
127    ) -> Result<(), IommuError> {
128        Err(IommuError::Unsupported)
129    }
130
131    /// Remove one shadow mapping from the backend's page tables.
132    fn unmap(
133        &self,
134        _domain: DomainId,
135        _sbdf: Sbdf,
136        _iova: u64,
137        _len: u64,
138        _kind: MappingKind,
139    ) -> Result<(), IommuError> {
140        Err(IommuError::Unsupported)
141    }
142
143    /// True when interrupt remapping is advertised.
144    fn interrupt_remapping(&self) -> bool {
145        false
146    }
147
148    /// True when interrupt remapping is actually programmed and usable.
149    fn interrupt_remapping_active(&self) -> bool {
150        false
151    }
152
153    /// Allocate an IRTE and return the MSI message to program.
154    fn allocate_msi(&self, _sbdf: Sbdf, _vector: u8) -> Result<MsiAllocation, IommuError> {
155        Err(IommuError::Unsupported)
156    }
157
158    /// Release an IRTE previously returned by [`Backend::allocate_msi`].
159    fn free_msi(&self, _cookie: u32) -> Result<(), IommuError> {
160        Err(IommuError::Unsupported)
161    }
162}
163
164/// Backend used when no IOMMU exists (or none is usable).
165pub struct NoIommu;
166
167impl Backend for NoIommu {
168    fn name(&self) -> &'static str {
169        "none"
170    }
171
172    fn is_ready(&self) -> bool {
173        false
174    }
175
176    fn activate(&self) -> Result<(), IommuError> {
177        Err(IommuError::NotPresent)
178    }
179
180    fn invalidate_domain(&self, _domain: DomainId) {}
181}
182
183static NO_IOMMU: NoIommu = NoIommu;
184
185/// Discover the platform IOMMU and cache the result.
186///
187/// Safe to call more than once; the second call re-parses the firmware tables.
188pub fn init() -> Discovery {
189    #[cfg(target_arch = "x86_64")]
190    {
191        return super::x86_64::iommu::init();
192    }
193    #[cfg(not(target_arch = "x86_64"))]
194    {
195        Discovery::absent()
196    }
197}
198
199/// Return the discovery summary recorded by [`init`].
200pub fn discovery() -> Discovery {
201    #[cfg(target_arch = "x86_64")]
202    {
203        return super::x86_64::iommu::discovery();
204    }
205    #[cfg(not(target_arch = "x86_64"))]
206    {
207        Discovery::absent()
208    }
209}
210
211/// Return the authoritative backend.
212///
213/// Falls back to [`NoIommu`] whenever the architecture has no usable backend.
214pub fn backend() -> &'static dyn Backend {
215    #[cfg(target_arch = "x86_64")]
216    {
217        if let Some(backend) = super::x86_64::iommu::backend() {
218            return backend;
219        }
220    }
221    &NO_IOMMU
222}
223
224/// True when a backend is present and validated for activation.
225pub fn is_available() -> bool {
226    backend().is_ready()
227}
228
229/// Try to activate translation through the authoritative backend.
230pub fn activate() -> Result<(), IommuError> {
231    backend().activate()
232}
233
234/// Install one mapping in the authoritative backend.
235pub fn map_domain(
236    domain: DomainId,
237    sbdf: Sbdf,
238    iova: u64,
239    phys: u64,
240    len: u64,
241    prot: DmaProt,
242    kind: MappingKind,
243) -> Result<(), IommuError> {
244    let backend = backend();
245    if backend.name() == "none" {
246        // No IOMMU: the software domain remains the source of truth.
247        return Ok(());
248    }
249    backend.map(domain, sbdf, iova, phys, len, prot, kind)
250}
251
252/// Remove one mapping from the authoritative backend.
253pub fn unmap_domain(
254    domain: DomainId,
255    sbdf: Sbdf,
256    iova: u64,
257    len: u64,
258    kind: MappingKind,
259) -> Result<(), IommuError> {
260    let backend = backend();
261    if backend.name() == "none" {
262        return Ok(());
263    }
264    backend.unmap(domain, sbdf, iova, len, kind)
265}
266
267/// True when MSI interrupt remapping is active (not merely advertised).
268pub fn interrupt_remapping_active() -> bool {
269    backend().interrupt_remapping_active()
270}
271
272/// Allocate an MSI message through interrupt remapping.
273pub fn allocate_msi(sbdf: Sbdf, vector: u8) -> Result<MsiAllocation, IommuError> {
274    backend().allocate_msi(sbdf, vector)
275}
276
277/// Release an IRTE cookie.
278pub fn free_msi(cookie: u32) -> Result<(), IommuError> {
279    backend().free_msi(cookie)
280}