use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IommuType {
IntelVtd,
AmdVi,
ArmSmmu,
AppleDart,
Unknown,
}
impl std::fmt::Display for IommuType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::IntelVtd => write!(f, "Intel VT-d"),
Self::AmdVi => write!(f, "AMD-Vi"),
Self::ArmSmmu => write!(f, "ARM SMMU"),
Self::AppleDart => write!(f, "Apple DART"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IommuDevice {
pub bdf: String,
pub description: String,
pub driver: Option<String>,
pub vfio_bound: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IommuGroup {
pub id: u32,
pub devices: Vec<IommuDevice>,
pub isolated: Option<bool>,
pub passthrough_candidate: Option<bool>,
}
#[cfg(any(target_os = "linux", test))]
fn group_isolation(devices: &[IommuDevice]) -> (Option<bool>, Option<bool>) {
if devices.len() != 1 {
return (None, None);
}
let candidate = !devices[0].bdf.ends_with(".0") || devices[0].driver.is_some();
(Some(true), Some(candidate))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IommuOverview {
pub enabled: bool,
pub iommu_type: IommuType,
pub groups: Vec<IommuGroup>,
pub total_groups: u32,
pub passthrough_groups: u32,
pub interrupt_remapping: Option<bool>,
pub dmar_present: bool,
pub recommendations: Vec<String>,
}
pub struct IommuMonitor {
overview: IommuOverview,
}
impl IommuMonitor {
pub fn new() -> Result<Self, IronError> {
let overview = Self::scan()?;
Ok(Self { overview })
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.overview = Self::scan()?;
Ok(())
}
pub fn overview(&self) -> &IommuOverview {
&self.overview
}
pub fn groups(&self) -> &[IommuGroup] {
&self.overview.groups
}
pub fn group_for_device(&self, bdf: &str) -> Option<&IommuGroup> {
self.overview
.groups
.iter()
.find(|g| g.devices.iter().any(|d| d.bdf == bdf))
}
pub fn passthrough_candidates(&self) -> Vec<&IommuGroup> {
self.overview
.groups
.iter()
.filter(|g| g.passthrough_candidate == Some(true))
.collect()
}
#[cfg(target_os = "linux")]
fn scan() -> Result<IommuOverview, IronError> {
let iommu_groups_path = std::path::Path::new("/sys/kernel/iommu_groups");
let enabled = iommu_groups_path.exists();
if !enabled {
return Ok(IommuOverview {
enabled: false,
iommu_type: IommuType::Unknown,
groups: Vec::new(),
total_groups: 0,
passthrough_groups: 0,
interrupt_remapping: None,
dmar_present: false,
recommendations: vec![
"IOMMU not enabled; add intel_iommu=on or amd_iommu=on to kernel cmdline"
.into(),
],
});
}
let iommu_type = Self::detect_type();
let mut groups = Vec::new();
if let Ok(entries) = std::fs::read_dir(iommu_groups_path) {
let mut group_ids: Vec<u32> = entries
.flatten()
.filter_map(|e| e.file_name().to_string_lossy().parse::<u32>().ok())
.collect();
group_ids.sort();
for gid in group_ids {
if let Ok(group) = Self::read_group(gid) {
groups.push(group);
}
}
}
let total = groups.len() as u32;
let passthrough = groups
.iter()
.filter(|g| g.passthrough_candidate == Some(true))
.count() as u32;
let interrupt_remapping: Option<bool> = None;
let dmar_present = std::path::Path::new("/sys/firmware/acpi/tables/DMAR").exists()
|| std::path::Path::new("/sys/firmware/acpi/tables/IVRS").exists();
let mut recommendations = Vec::new();
if interrupt_remapping == Some(false) {
recommendations
.push("Interrupt remapping may not be active; needed for secure VFIO".into());
}
if passthrough > 0 {
recommendations.push(format!(
"{} IOMMU groups suitable for device passthrough (VFIO)",
passthrough
));
}
Ok(IommuOverview {
enabled,
iommu_type,
groups,
total_groups: total,
passthrough_groups: passthrough,
interrupt_remapping,
dmar_present,
recommendations,
})
}
#[cfg(target_os = "linux")]
fn detect_type() -> IommuType {
if std::path::Path::new("/sys/firmware/acpi/tables/DMAR").exists() {
return IommuType::IntelVtd;
}
if std::path::Path::new("/sys/firmware/acpi/tables/IVRS").exists() {
return IommuType::AmdVi;
}
let mut driver_dirs: Vec<&str> = Vec::new();
if let Ok(units) = std::fs::read_dir("/sys/class/iommu") {
for unit in units.flatten() {
for name in ["intel-iommu", "amd-iommu"] {
if unit.path().join(name).is_dir() {
driver_dirs.push(name);
}
}
}
}
iommu_type_from_driver_dirs(&driver_dirs)
}
#[cfg(target_os = "linux")]
fn read_group(gid: u32) -> Result<IommuGroup, IronError> {
let devices_path = format!("/sys/kernel/iommu_groups/{}/devices", gid);
let mut devices = Vec::new();
if let Ok(entries) = std::fs::read_dir(&devices_path) {
for entry in entries.flatten() {
let bdf = entry.file_name().to_string_lossy().to_string();
let driver = std::fs::read_link(entry.path().join("driver"))
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
let vfio_bound = driver.as_deref() == Some("vfio-pci");
let vendor = std::fs::read_to_string(entry.path().join("vendor"))
.ok()
.map(|s| s.trim().to_string())
.unwrap_or_default();
let device_id = std::fs::read_to_string(entry.path().join("device"))
.ok()
.map(|s| s.trim().to_string())
.unwrap_or_default();
let description = if !vendor.is_empty() && !device_id.is_empty() {
format!("{}:{}", vendor, device_id)
} else {
bdf.clone()
};
devices.push(IommuDevice {
bdf,
description,
driver,
vfio_bound,
});
}
}
let (isolated, passthrough_candidate) = group_isolation(&devices);
Ok(IommuGroup {
id: gid,
devices,
isolated,
passthrough_candidate,
})
}
#[cfg(target_os = "windows")]
fn scan() -> Result<IommuOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"IOMMU groups are read from `/sys/kernel/iommu_groups`, which Windows does not expose"
.into(),
))
}
#[cfg(target_os = "macos")]
fn scan() -> Result<IommuOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"IOMMU groups are read from `/sys/kernel/iommu_groups`, which macOS does not expose"
.into(),
))
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
fn scan() -> Result<IommuOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"IOMMU groups are read from `/sys/kernel/iommu_groups`, which this platform does not expose"
.into(),
))
}
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn iommu_type_from_driver_dirs(names: &[&str]) -> IommuType {
let intel = names.contains(&"intel-iommu");
let amd = names.contains(&"amd-iommu");
match (intel, amd) {
(true, false) => IommuType::IntelVtd,
(false, true) => IommuType::AmdVi,
_ => IommuType::Unknown,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_single_driver_directory_names_its_technology() {
assert_eq!(
iommu_type_from_driver_dirs(&["intel-iommu"]),
IommuType::IntelVtd
);
assert_eq!(
iommu_type_from_driver_dirs(&["amd-iommu"]),
IommuType::AmdVi
);
}
#[test]
fn no_driver_directory_is_unknown_not_a_guess() {
assert_eq!(iommu_type_from_driver_dirs(&[]), IommuType::Unknown);
}
#[test]
fn two_technologies_are_unknown() {
assert_eq!(
iommu_type_from_driver_dirs(&["intel-iommu", "amd-iommu"]),
IommuType::Unknown
);
}
#[test]
fn a_name_that_only_resembles_a_driver_is_not_one() {
assert_eq!(
iommu_type_from_driver_dirs(&["intel_iommu", "amd_iommu"]),
IommuType::Unknown
);
}
#[test]
fn test_iommu_type_display() {
assert_eq!(IommuType::IntelVtd.to_string(), "Intel VT-d");
assert_eq!(IommuType::AmdVi.to_string(), "AMD-Vi");
assert_eq!(IommuType::AppleDart.to_string(), "Apple DART");
}
#[test]
fn test_group_isolation() {
let group = IommuGroup {
id: 0,
devices: vec![IommuDevice {
bdf: "0000:01:00.0".into(),
description: "GPU".into(),
driver: Some("nvidia".into()),
vfio_bound: false,
}],
isolated: Some(true),
passthrough_candidate: Some(true),
};
assert_eq!(group.isolated, Some(true));
assert_eq!(group.devices.len(), 1);
}
#[test]
fn multi_device_group_isolation_is_unknown_not_false() {
let dev = |bdf: &str| IommuDevice {
bdf: bdf.into(),
description: "d".into(),
driver: None,
vfio_bound: false,
};
let multi = vec![dev("0000:01:00.0"), dev("0000:01:00.1")];
assert_eq!(group_isolation(&multi), (None, None));
assert_eq!(group_isolation(&[]), (None, None));
assert_eq!(
group_isolation(&[dev("0000:02:00.0")]),
(Some(true), Some(false))
);
assert_eq!(
group_isolation(&[dev("0000:02:00.1")]),
(Some(true), Some(true))
);
}
#[test]
fn test_multi_device_group() {
let group = IommuGroup {
id: 1,
devices: vec![
IommuDevice {
bdf: "0000:01:00.0".into(),
description: "GPU".into(),
driver: Some("amdgpu".into()),
vfio_bound: false,
},
IommuDevice {
bdf: "0000:01:00.1".into(),
description: "Audio".into(),
driver: Some("snd_hda_intel".into()),
vfio_bound: false,
},
],
isolated: None,
passthrough_candidate: None,
};
assert_eq!(group.isolated, None);
}
#[test]
fn test_serialization() {
let dev = IommuDevice {
bdf: "0000:01:00.0".into(),
description: "NVIDIA GPU".into(),
driver: Some("nvidia".into()),
vfio_bound: false,
};
let json = serde_json::to_string(&dev).unwrap();
assert!(json.contains("0000:01:00.0"));
let _: IommuDevice = serde_json::from_str(&json).unwrap();
}
}