use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PciClass {
Unclassified,
MassStorage,
NetworkController,
DisplayController,
MultimediaController,
MemoryController,
Bridge,
CommunicationController,
SystemPeripheral,
InputDevice,
DockingStation,
Processor,
SerialBusController,
WirelessController,
IntelligentController,
SatelliteComm,
EncryptionController,
SignalProcessing,
ProcessingAccelerator,
Instrumentation,
CoProcessor,
Other(u8),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PciLinkInfo {
pub speed: String,
pub width: String,
pub max_speed: Option<String>,
pub max_width: Option<String>,
pub generation: Option<u8>,
}
#[cfg(any(target_os = "windows", test))]
fn pcie_generation_of_encoding(encoding: u32) -> Option<u8> {
u8::try_from(encoding)
.ok()
.filter(|generation| (1..=6).contains(generation))
}
#[cfg(any(target_os = "linux", test))]
fn power_state_of(text: &str) -> Option<String> {
let state = text.trim();
(!state.is_empty() && !matches!(state, "unknown" | "error")).then(|| state.to_string())
}
#[cfg(any(target_os = "linux", test))]
fn parse_link_rate_gts(text: &str) -> Option<f64> {
text.split_whitespace().next()?.parse::<f64>().ok()
}
#[cfg(any(target_os = "linux", test))]
fn pcie_generation_of(rate_gts: f64) -> Option<u8> {
[
(2.5, 1),
(5.0, 2),
(8.0, 3),
(16.0, 4),
(32.0, 5),
(64.0, 6),
]
.into_iter()
.find(|(rate, _)| (rate_gts - rate).abs() < 1e-6)
.map(|(_, generation)| generation)
}
#[cfg(any(target_os = "windows", test))]
fn base_class_of_hardware_ids(ids: &str) -> Option<u8> {
ids.lines().find_map(|line| {
let (_, class) = line.trim().rsplit_once("CC_")?;
let hex = class.get(..2)?;
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
u8::from_str_radix(hex, 16).ok()
})
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PciDeviceInfo {
pub address: Option<String>,
pub vendor_id: String,
pub device_id: String,
pub subsystem_vendor_id: Option<String>,
pub subsystem_device_id: Option<String>,
pub class_code: Option<String>,
pub class: Option<PciClass>,
pub vendor_name: String,
pub device_name: String,
pub driver: String,
pub kernel_module: Option<String>,
pub revision: String,
pub iommu_group: Option<u32>,
pub link_info: Option<PciLinkInfo>,
pub sriov_capable: Option<bool>,
pub sriov_vfs: Option<u32>,
pub numa_node: Option<u32>,
pub power_state: Option<String>,
}
pub struct PciDeviceMonitor {
devices: Vec<PciDeviceInfo>,
}
#[cfg(target_os = "windows")]
pub(crate) fn pci_address_of(pnp_id: &str) -> Option<String> {
PciDeviceMonitor::registry_location_and_service(pnp_id).0
}
impl PciDeviceMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
devices: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.devices.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
Ok(())
}
pub fn devices(&self) -> &[PciDeviceInfo] {
&self.devices
}
pub fn devices_by_class(&self, class: PciClass) -> Vec<&PciDeviceInfo> {
self.devices
.iter()
.filter(|d| d.class.as_ref() == Some(&class))
.collect()
}
pub fn devices_by_vendor(&self, vendor_id: &str) -> Vec<&PciDeviceInfo> {
self.devices
.iter()
.filter(|d| d.vendor_id == vendor_id)
.collect()
}
pub fn gpus(&self) -> Vec<&PciDeviceInfo> {
self.devices_by_class(PciClass::DisplayController)
}
pub fn network_devices(&self) -> Vec<&PciDeviceInfo> {
let mut devs = self.devices_by_class(PciClass::NetworkController);
devs.extend(self.devices_by_class(PciClass::WirelessController));
devs
}
pub fn storage_devices(&self) -> Vec<&PciDeviceInfo> {
self.devices_by_class(PciClass::MassStorage)
}
pub fn sriov_devices(&self) -> Vec<&PciDeviceInfo> {
self.devices
.iter()
.filter(|d| d.sriov_capable == Some(true))
.collect()
}
pub fn classify_pci(class_byte: u8) -> PciClass {
match class_byte {
0x00 => PciClass::Unclassified,
0x01 => PciClass::MassStorage,
0x02 => PciClass::NetworkController,
0x03 => PciClass::DisplayController,
0x04 => PciClass::MultimediaController,
0x05 => PciClass::MemoryController,
0x06 => PciClass::Bridge,
0x07 => PciClass::CommunicationController,
0x08 => PciClass::SystemPeripheral,
0x09 => PciClass::InputDevice,
0x0A => PciClass::DockingStation,
0x0B => PciClass::Processor,
0x0C => PciClass::SerialBusController,
0x0D => PciClass::WirelessController,
0x0E => PciClass::IntelligentController,
0x0F => PciClass::SatelliteComm,
0x10 => PciClass::EncryptionController,
0x11 => PciClass::SignalProcessing,
0x12 => PciClass::ProcessingAccelerator,
0x13 => PciClass::Instrumentation,
0x40 => PciClass::CoProcessor,
other => PciClass::Other(other),
}
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
let pci_base = std::path::Path::new("/sys/bus/pci/devices");
if !pci_base.exists() {
return Ok(());
}
let entries = std::fs::read_dir(pci_base)
.map_err(|e| IronError::System(format!("cannot read /sys/bus/pci/devices: {e}")))?;
for entry in entries.flatten() {
let address = entry.file_name().to_string_lossy().to_string();
let base = entry.path();
let vendor_id = Self::read_hex_id(&base.join("vendor"));
let device_id = Self::read_hex_id(&base.join("device"));
let subsystem_vendor_id =
Self::present(Self::read_hex_id(&base.join("subsystem_vendor")));
let subsystem_device_id =
Self::present(Self::read_hex_id(&base.join("subsystem_device")));
let revision = Self::read_hex_id(&base.join("revision"));
let class_byte = Self::read_trimmed(&base.join("class"))
.trim_start_matches("0x")
.get(..2)
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
let class = class_byte.map(Self::classify_pci);
let class_code = class_byte.map(|b| format!("{:02x}", b));
let driver = std::fs::read_link(base.join("driver"))
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.unwrap_or_default();
let kernel_module = std::fs::read_link(base.join("driver/module"))
.ok()
.and_then(|p| module_name_of_link(&p));
let iommu_group = std::fs::read_link(base.join("iommu_group"))
.ok()
.and_then(|p| p.file_name().and_then(|n| n.to_string_lossy().parse().ok()));
let numa_node = Self::read_trimmed(&base.join("numa_node"))
.parse::<i32>()
.ok()
.and_then(|n| u32::try_from(n).ok());
let power_state = power_state_of(&Self::read_trimmed(&base.join("power_state")));
let sriov_capable = base.join("sriov_totalvfs").exists();
let sriov_vfs = if sriov_capable {
Self::read_trimmed(&base.join("sriov_numvfs")).parse().ok()
} else {
Some(0)
};
let link_info = {
let speed = Self::read_trimmed(&base.join("current_link_speed"));
let width = Self::read_trimmed(&base.join("current_link_width"));
let max_speed = Self::present(Self::read_trimmed(&base.join("max_link_speed")));
let max_width = Self::present(Self::read_trimmed(&base.join("max_link_width")));
if !speed.is_empty() || max_speed.is_some() {
let generation = max_speed
.as_deref()
.and_then(parse_link_rate_gts)
.and_then(pcie_generation_of);
Some(PciLinkInfo {
speed,
width,
max_speed,
max_width,
generation,
})
} else {
None
}
};
let (vendor_name, device_name) = Self::lookup_pci_names(&vendor_id, &device_id);
self.devices.push(PciDeviceInfo {
address: Some(address),
vendor_id,
device_id,
subsystem_vendor_id,
subsystem_device_id,
class_code,
class,
vendor_name,
device_name,
driver,
kernel_module,
revision,
iommu_group,
link_info,
sriov_capable: Some(sriov_capable),
sriov_vfs,
numa_node,
power_state,
});
}
Ok(())
}
#[cfg(target_os = "linux")]
fn lookup_pci_names(vendor_id: &str, _device_id: &str) -> (String, String) {
let vendor = match vendor_id {
"10de" => "NVIDIA Corporation",
"1002" => "Advanced Micro Devices [AMD/ATI]",
"8086" => "Intel Corporation",
"14e4" => "Broadcom Inc.",
"1b36" => "Red Hat (Virtio)",
"15b3" => "Mellanox Technologies",
"1af4" => "Virtio",
"144d" => "Samsung Electronics",
"1987" => "Phison Electronics",
"126f" => "Silicon Motion",
"1179" => "Toshiba/Kioxia",
"1c5c" => "SK Hynix",
"c0a9" => "Micron Technology",
"106b" => "Apple Inc.",
"1022" => "Advanced Micro Devices [AMD]",
_ => "",
};
(vendor.to_string(), String::new())
}
#[cfg(target_os = "linux")]
fn read_trimmed(path: &std::path::Path) -> String {
std::fs::read_to_string(path)
.unwrap_or_default()
.trim()
.to_string()
}
#[cfg(target_os = "linux")]
fn read_hex_id(path: &std::path::Path) -> String {
Self::read_trimmed(path)
.trim_start_matches("0x")
.to_lowercase()
}
#[cfg(target_os = "linux")]
fn present(value: String) -> Option<String> {
(!value.is_empty()).then_some(value)
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
let output = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command",
r#"Get-CimInstance Win32_PnPEntity | Where-Object { $_.PNPDeviceID -like 'PCI\*' } | Select-Object Name, Manufacturer, PNPDeviceID, ConfigManagerErrorCode -First 500 | ConvertTo-Json -Compress"#])
.output()
.map_err(|e| IronError::CommandFailed(format!("powershell: {e}")))?;
if !output.status.success() {
return Err(IronError::CommandFailed(format!(
"Win32_PnPEntity query exited {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let text = String::from_utf8(output.stdout)
.map_err(|e| IronError::Parse(format!("Win32_PnPEntity output not UTF-8: {e}")))?;
if text.trim().is_empty() {
return Ok(());
}
let val: serde_json::Value = serde_json::from_str(&text)
.map_err(|e| IronError::Parse(format!("Win32_PnPEntity JSON: {e}")))?;
let items = match &val {
serde_json::Value::Array(arr) => arr.clone(),
obj @ serde_json::Value::Object(_) => vec![obj.clone()],
_ => vec![],
};
for item in &items {
let pnp_id = item["PNPDeviceID"].as_str().unwrap_or("");
let name = item["Name"].as_str().unwrap_or("").to_string();
let vendor_name = item["Manufacturer"].as_str().unwrap_or("").to_string();
let vendor_id = Self::extract_pnp_field(pnp_id, "VEN_");
let device_id = Self::extract_pnp_field(pnp_id, "DEV_");
let (subsystem_vendor_id, subsystem_device_id) =
split_subsys_field(&Self::extract_pnp_field(pnp_id, "SUBSYS_"));
let class_byte = Self::registry_class_code(pnp_id);
let (bdf, service) = Self::registry_location_and_service(pnp_id);
self.devices.push(PciDeviceInfo {
address: bdf,
vendor_id,
device_id,
subsystem_vendor_id,
subsystem_device_id,
class_code: class_byte.map(|b| format!("{b:02x}")),
class: class_byte.map(Self::classify_pci),
vendor_name,
device_name: name,
driver: service.unwrap_or_default(),
kernel_module: None,
revision: String::new(),
iommu_group: None,
link_info: Self::devnode_link_info(pnp_id),
sriov_capable: None,
sriov_vfs: None,
numa_node: None,
power_state: None,
});
}
Ok(())
}
#[cfg(target_os = "windows")]
fn registry_location_and_service(pnp_id: &str) -> (Option<String>, Option<String>) {
use winreg::enums::*;
use winreg::RegKey;
if pnp_id.is_empty() {
return (None, None);
}
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let path = format!(r"SYSTEM\CurrentControlSet\Enum\{pnp_id}");
let Ok(key) = hklm.open_subkey_with_flags(&path, KEY_READ) else {
return (None, None);
};
let bdf = key
.get_value::<String, _>("LocationInformation")
.ok()
.and_then(|loc| Self::parse_location_bdf(&loc));
let service = key
.get_value::<String, _>("Service")
.ok()
.filter(|s| !s.trim().is_empty());
(bdf, service)
}
#[cfg(target_os = "windows")]
fn registry_class_code(pnp_id: &str) -> Option<u8> {
use winreg::enums::*;
use winreg::RegKey;
if pnp_id.is_empty() {
return None;
}
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let path = format!(r"SYSTEM\CurrentControlSet\Enum\{pnp_id}");
let key = hklm.open_subkey_with_flags(&path, KEY_READ).ok()?;
let ids: String = key.get_value("HardwareID").ok()?;
base_class_of_hardware_ids(&ids)
}
#[cfg(target_os = "windows")]
fn devnode_link_info(pnp_id: &str) -> Option<PciLinkInfo> {
use std::os::windows::ffi::OsStrExt;
use windows::core::GUID;
use windows::core::PCWSTR;
use windows::Win32::Devices::DeviceAndDriverInstallation::{
CM_Get_DevNode_PropertyW, CM_Locate_DevNodeW, CM_LOCATE_DEVNODE_NORMAL, CR_SUCCESS,
};
use windows::Win32::Devices::Properties::{DEVPROPKEY, DEVPROPTYPE};
const PCI_DEVICE_FMTID: GUID = GUID::from_u128(0x3ab22e31_8264_4b4e_9af5_a8d2d8e33e62);
const PID_CURRENT_LINK_SPEED: u32 = 9;
const PID_CURRENT_LINK_WIDTH: u32 = 10;
const PID_MAX_LINK_SPEED: u32 = 11;
const PID_MAX_LINK_WIDTH: u32 = 12;
let wide: Vec<u16> = std::ffi::OsStr::new(pnp_id)
.encode_wide()
.chain(std::iter::once(0))
.collect();
let mut devinst = 0u32;
let located = unsafe {
CM_Locate_DevNodeW(
&mut devinst,
PCWSTR(wide.as_ptr()),
CM_LOCATE_DEVNODE_NORMAL,
)
};
if located != CR_SUCCESS {
return None;
}
let read_u32 = |pid: u32| -> Option<u32> {
let key = DEVPROPKEY {
fmtid: PCI_DEVICE_FMTID,
pid,
};
let mut value = 0u32;
let mut ty = DEVPROPTYPE::default();
let mut len = std::mem::size_of::<u32>() as u32;
let ret = unsafe {
CM_Get_DevNode_PropertyW(
devinst,
&key,
&mut ty,
Some(&mut value as *mut u32 as *mut u8),
&mut len,
0,
)
};
(ret == CR_SUCCESS).then_some(value)
};
let current_width = read_u32(PID_CURRENT_LINK_WIDTH)?;
let max_width = read_u32(PID_MAX_LINK_WIDTH).map(|w| format!("x{w}"));
let current_speed = read_u32(PID_CURRENT_LINK_SPEED);
let max_encoding = read_u32(PID_MAX_LINK_SPEED);
let max_speed = max_encoding.map(Self::link_speed_label);
Some(PciLinkInfo {
speed: current_speed
.map(Self::link_speed_label)
.unwrap_or_default(),
width: format!("x{current_width}"),
max_speed,
max_width,
generation: max_encoding.and_then(pcie_generation_of_encoding),
})
}
#[cfg(target_os = "windows")]
fn link_speed_label(encoding: u32) -> String {
match encoding {
1 => "2.5 GT/s".to_string(),
2 => "5.0 GT/s".to_string(),
3 => "8.0 GT/s".to_string(),
4 => "16.0 GT/s".to_string(),
5 => "32.0 GT/s".to_string(),
6 => "64.0 GT/s".to_string(),
other if other > 0 => format!("PCIe gen {other}"),
_ => String::new(),
}
}
#[cfg(target_os = "windows")]
fn parse_location_bdf(location: &str) -> Option<String> {
let open = location.rfind('(')?;
let close = location.rfind(')')?;
if close <= open + 1 {
return None;
}
let mut parts = location[open + 1..close].split(',');
let bus: u32 = parts.next()?.trim().parse().ok()?;
let device: u32 = parts.next()?.trim().parse().ok()?;
let function: u32 = parts.next()?.trim().parse().ok()?;
if parts.next().is_some() {
return None;
}
Some(format!("0000:{bus:02x}:{device:02x}.{function}"))
}
#[cfg(target_os = "windows")]
fn extract_pnp_field(pnp_id: &str, prefix: &str) -> String {
pnp_id
.find(prefix)
.map(|pos| {
let start = pos + prefix.len();
pnp_id[start..]
.chars()
.take_while(|c| c.is_ascii_hexdigit())
.collect::<String>()
.to_lowercase()
})
.unwrap_or_default()
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
let output = std::process::Command::new("system_profiler")
.args(["SPPCIDataType", "-json"])
.output()
.map_err(|e| IronError::CommandFailed(format!("system_profiler: {e}")))?;
if !output.status.success() {
return Err(IronError::CommandFailed(format!(
"system_profiler SPPCIDataType exited {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let text = String::from_utf8(output.stdout)
.map_err(|e| IronError::Parse(format!("system_profiler output not UTF-8: {e}")))?;
let val: serde_json::Value = serde_json::from_str(&text)
.map_err(|e| IronError::Parse(format!("SPPCIDataType JSON: {e}")))?;
if let Some(items) = val["SPPCIDataType"].as_array() {
for item in items {
let name = item["_name"].as_str().unwrap_or("").to_string();
let vendor_id = item["sppci_vendor-id"]
.as_str()
.unwrap_or("")
.trim_start_matches("0x")
.to_lowercase();
let device_id = item["sppci_device-id"]
.as_str()
.unwrap_or("")
.trim_start_matches("0x")
.to_lowercase();
let slot = item["sppci_slot_name"].as_str().unwrap_or("").to_string();
let driver = item["sppci_driver_installed"]
.as_str()
.unwrap_or("")
.to_string();
let link_speed = item["sppci_link-speed"].as_str().unwrap_or("").to_string();
let link_width = item["sppci_link-width"].as_str().unwrap_or("").to_string();
let link_info = if !link_speed.is_empty() {
Some(PciLinkInfo {
speed: link_speed.clone(),
width: link_width.clone(),
max_speed: None,
max_width: None,
generation: None,
})
} else {
None
};
self.devices.push(PciDeviceInfo {
address: (!slot.is_empty()).then_some(slot),
vendor_id,
device_id,
subsystem_vendor_id: None,
subsystem_device_id: None,
class_code: None,
class: None,
vendor_name: String::new(),
device_name: name,
driver,
kernel_module: None,
revision: String::new(),
iommu_group: None,
link_info,
sriov_capable: None,
sriov_vfs: None,
numa_node: None,
power_state: None,
});
}
}
Ok(())
}
}
impl Default for PciDeviceMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
devices: Vec::new(),
})
}
}
impl std::fmt::Display for PciClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unclassified => write!(f, "Unclassified"),
Self::MassStorage => write!(f, "Mass Storage"),
Self::NetworkController => write!(f, "Network Controller"),
Self::DisplayController => write!(f, "Display Controller"),
Self::MultimediaController => write!(f, "Multimedia"),
Self::MemoryController => write!(f, "Memory Controller"),
Self::Bridge => write!(f, "Bridge"),
Self::CommunicationController => write!(f, "Communication"),
Self::SystemPeripheral => write!(f, "System Peripheral"),
Self::InputDevice => write!(f, "Input Device"),
Self::DockingStation => write!(f, "Docking Station"),
Self::Processor => write!(f, "Processor"),
Self::SerialBusController => write!(f, "Serial Bus"),
Self::WirelessController => write!(f, "Wireless"),
Self::IntelligentController => write!(f, "Intelligent Controller"),
Self::SatelliteComm => write!(f, "Satellite"),
Self::EncryptionController => write!(f, "Encryption"),
Self::SignalProcessing => write!(f, "Signal Processing"),
Self::ProcessingAccelerator => write!(f, "Processing Accelerator"),
Self::Instrumentation => write!(f, "Instrumentation"),
Self::CoProcessor => write!(f, "Co-Processor"),
Self::Other(c) => write!(f, "Other(0x{:02x})", c),
}
}
}
#[cfg(any(target_os = "linux", test))]
fn module_name_of_link(target: &std::path::Path) -> Option<String> {
target
.file_name()
.map(|n| n.to_string_lossy().trim().to_string())
.filter(|n| !n.is_empty())
}
#[cfg(any(target_os = "windows", test))]
fn split_subsys_field(field: &str) -> (Option<String>, Option<String>) {
let field = field.trim();
if field.len() != 8 || !field.bytes().all(|b| b.is_ascii_hexdigit()) {
return (None, None);
}
let lower = field.to_ascii_lowercase();
let device = lower[..4].to_string();
let vendor = lower[4..].to_string();
(Some(vendor), Some(device))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kernel_module_is_the_basename_of_the_module_link() {
let target = std::path::Path::new("../../../../../module/nvidia");
assert_eq!(module_name_of_link(target).as_deref(), Some("nvidia"));
let drm = std::path::Path::new("../../../../../module/nvidia_drm");
assert_eq!(module_name_of_link(drm).as_deref(), Some("nvidia_drm"));
assert_eq!(module_name_of_link(std::path::Path::new("")), None);
}
#[test]
fn subsys_field_splits_device_then_vendor() {
let (vendor, device) = split_subsys_field("88771043");
assert_eq!(vendor.as_deref(), Some("1043"));
assert_eq!(device.as_deref(), Some("8877"));
}
#[test]
fn subsys_field_from_a_pnp_id_is_lowercased() {
let pnp = r"PCI\VEN_144D&DEV_A810&SUBSYS_A801144D&REV_00\4&2EC11BF&0&000A";
let field = pnp
.find("SUBSYS_")
.map(|p| &pnp[p + 7..p + 7 + 8])
.unwrap_or("");
let (vendor, device) = split_subsys_field(field);
assert_eq!(vendor.as_deref(), Some("144d"));
assert_eq!(device.as_deref(), Some("a801"));
}
#[test]
fn sysfs_link_speed_maps_to_generation_by_rate() {
let generation = |attr: &str| parse_link_rate_gts(attr).and_then(pcie_generation_of);
assert_eq!(generation("2.5 GT/s PCIe"), Some(1));
assert_eq!(generation("5.0 GT/s PCIe"), Some(2));
assert_eq!(generation("8.0 GT/s PCIe"), Some(3));
assert_eq!(generation("16.0 GT/s PCIe"), Some(4));
assert_eq!(generation("32.0 GT/s PCIe"), Some(5));
assert_eq!(generation("64.0 GT/s PCIe"), Some(6));
}
#[test]
fn sysfs_link_speed_that_is_not_a_known_rate_has_no_generation() {
assert_eq!(parse_link_rate_gts("Unknown"), None);
assert_eq!(parse_link_rate_gts(""), None);
assert_eq!(pcie_generation_of(7.0), None);
assert_eq!(pcie_generation_of(0.0), None);
}
#[test]
fn subsys_field_of_the_wrong_shape_is_absent() {
assert_eq!(split_subsys_field(""), (None, None));
assert_eq!(split_subsys_field("1043"), (None, None));
assert_eq!(split_subsys_field("8877104G"), (None, None));
}
#[cfg(target_os = "windows")]
#[test]
fn link_speed_encodings_render_as_transfer_rates() {
assert_eq!(PciDeviceMonitor::link_speed_label(1), "2.5 GT/s");
assert_eq!(PciDeviceMonitor::link_speed_label(3), "8.0 GT/s");
assert_eq!(PciDeviceMonitor::link_speed_label(4), "16.0 GT/s");
assert_eq!(PciDeviceMonitor::link_speed_label(6), "64.0 GT/s");
}
#[cfg(target_os = "windows")]
#[test]
fn an_unknown_generation_is_labelled_rather_than_guessed() {
assert_eq!(PciDeviceMonitor::link_speed_label(7), "PCIe gen 7");
assert_eq!(PciDeviceMonitor::link_speed_label(0), "");
}
#[cfg(target_os = "windows")]
#[test]
fn a_location_string_yields_a_conventional_bdf() {
let loc = r"@System32\drivers\pci.sys,#65536;PCI bus %1, device %2, function %3;(122,0,0)";
assert_eq!(
PciDeviceMonitor::parse_location_bdf(loc),
Some("0000:7a:00.0".to_string())
);
let loc2 = r"@System32\drivers\pci.sys,#65536;PCI bus %1, device %2, function %3;(0,2,1)";
assert_eq!(
PciDeviceMonitor::parse_location_bdf(loc2),
Some("0000:00:02.1".to_string())
);
}
#[cfg(target_os = "windows")]
#[test]
fn a_location_string_without_a_value_triple_is_refused() {
assert_eq!(
PciDeviceMonitor::parse_location_bdf("PCI bus %1, device %2, function %3"),
None
);
assert_eq!(PciDeviceMonitor::parse_location_bdf(""), None);
assert_eq!(PciDeviceMonitor::parse_location_bdf("()"), None);
assert_eq!(PciDeviceMonitor::parse_location_bdf("(1,2)"), None);
assert_eq!(PciDeviceMonitor::parse_location_bdf("(1,2,3,4)"), None);
assert_eq!(PciDeviceMonitor::parse_location_bdf("(a,b,c)"), None);
}
#[test]
fn test_monitor_creation() {
match PciDeviceMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_monitor_default() {
let monitor = PciDeviceMonitor::default();
let _ = monitor.devices();
let _ = monitor.gpus();
let _ = monitor.network_devices();
let _ = monitor.storage_devices();
}
#[test]
fn test_class_display() {
assert_eq!(
PciClass::DisplayController.to_string(),
"Display Controller"
);
assert_eq!(PciClass::MassStorage.to_string(), "Mass Storage");
}
#[test]
fn test_classify_pci() {
assert_eq!(
PciDeviceMonitor::classify_pci(0x03),
PciClass::DisplayController
);
assert_eq!(PciDeviceMonitor::classify_pci(0x01), PciClass::MassStorage);
assert_eq!(
PciDeviceMonitor::classify_pci(0x02),
PciClass::NetworkController
);
}
#[test]
fn base_class_is_read_from_the_cc_hardware_id() {
let ids = "PCI\\VEN_10DE&DEV_2203&SUBSYS_161810DE&REV_A1\n\
PCI\\VEN_10DE&DEV_2203&SUBSYS_161810DE\n\
PCI\\VEN_10DE&DEV_2203&CC_030000\n\
PCI\\VEN_10DE&DEV_2203&CC_0300";
assert_eq!(base_class_of_hardware_ids(ids), Some(0x03));
assert_eq!(
PciDeviceMonitor::classify_pci(0x03),
PciClass::DisplayController
);
}
#[test]
fn a_device_without_a_cc_entry_has_no_read_class() {
assert_eq!(
base_class_of_hardware_ids("PCI\\VEN_8086&DEV_1234&SUBSYS_00000000"),
None
);
assert_eq!(base_class_of_hardware_ids(""), None);
assert_eq!(base_class_of_hardware_ids("PCI\\VEN_8086&CC_zz0000"), None);
}
#[test]
fn power_state_keeps_only_a_d_state() {
assert_eq!(power_state_of("D0\n").as_deref(), Some("D0"));
assert_eq!(power_state_of("D3hot").as_deref(), Some("D3hot"));
assert_eq!(power_state_of("unknown"), None);
assert_eq!(power_state_of("error"), None);
assert_eq!(power_state_of(""), None);
}
#[test]
fn windows_link_encoding_is_a_generation_only_within_one_to_six() {
assert_eq!(pcie_generation_of_encoding(1), Some(1));
assert_eq!(pcie_generation_of_encoding(4), Some(4));
assert_eq!(pcie_generation_of_encoding(6), Some(6));
assert_eq!(pcie_generation_of_encoding(0), None);
assert_eq!(pcie_generation_of_encoding(7), None);
assert_eq!(pcie_generation_of_encoding(u32::MAX), None);
}
#[test]
fn test_serialization() {
let dev = PciDeviceInfo {
address: Some("0000:00:02.0".into()),
vendor_id: "8086".into(),
device_id: "a780".into(),
subsystem_vendor_id: Some("1043".into()),
subsystem_device_id: Some("8877".into()),
class_code: Some("03".into()),
class: Some(PciClass::DisplayController),
vendor_name: "Intel Corporation".into(),
device_name: "UHD Graphics".into(),
driver: "i915".into(),
kernel_module: None,
revision: "00".into(),
iommu_group: Some(1),
link_info: None,
sriov_capable: Some(false),
sriov_vfs: Some(0),
numa_node: Some(0),
power_state: Some("D0".into()),
};
let json = serde_json::to_string(&dev).unwrap();
assert!(json.contains("Intel"));
let _: PciDeviceInfo = serde_json::from_str(&json).unwrap();
}
}