strat9_kernel/dma/mapper.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//! Per-device DMA address translation.
24//!
25//! Drivers keep working with physical addresses for CPU access, but program
26//! `DmaMapper::translate()` results into hardware. When IOMMU translation is
27//! inactive the mapper is an identity function, so the same code path is
28//! used at boot and after activation.
29
30use alloc::sync::Arc;
31
32use crate::hardware::iommu::{self, DmaProt, Domain, FaultPolicy, Sbdf};
33
34/// Physical <-> device address translator bound to one PCI function.
35pub struct DmaMapper {
36 domain: Option<Arc<Domain>>,
37}
38
39impl DmaMapper {
40 /// Build a translator for `sbdf`; creates a domain only when IOMMU
41 /// translation is active.
42 pub fn for_sbdf(sbdf: Sbdf) -> Self {
43 if iommu::enabled() {
44 Self {
45 domain: iommu::find_domain(sbdf)
46 .or_else(|| iommu::domain_for_owned(sbdf, None, FaultPolicy::Log).ok()),
47 }
48 } else {
49 Self { domain: None }
50 }
51 }
52
53 /// Map `[phys, phys + len)` and return the device address.
54 pub fn translate(&self, phys: u64, len: usize, prot: DmaProt) -> u64 {
55 if let Some(domain) = &self.domain {
56 if let Ok(iova) = domain.map_auto(phys, len as u64, prot) {
57 return iova;
58 }
59 }
60 phys
61 }
62
63 /// Release a mapping previously returned by [`DmaMapper::translate`].
64 pub fn release(&self, address: u64, len: usize) {
65 if let Some(domain) = &self.domain {
66 if domain.translate(address).is_some() {
67 let _ = domain.unmap(address, len as u64);
68 }
69 }
70 }
71
72 /// True when translation is active.
73 pub fn is_translating(&self) -> bool {
74 self.domain.is_some() && iommu::enabled()
75 }
76}