use super::traits::{
Clocks, Device, Error, FanSpeed, GpuProcess, Memory, PciInfo, Power, Temperature,
TemperatureThresholds, Utilization, Vendor,
};
use std::fs;
use std::path::PathBuf;
pub struct IntelGpu {
index: u32,
#[allow(dead_code)]
card_path: PathBuf,
device_path: PathBuf,
gt_path: Option<PathBuf>, }
impl IntelGpu {
pub fn new(index: u32, card_path: PathBuf) -> Result<Self, Error> {
let device_path = card_path.join("device");
if !device_path.exists() {
return Err(Error::InitializationFailed(
"Device path does not exist".to_string(),
));
}
let gt_path = card_path.join("gt");
let gt_path = if gt_path.exists() {
Some(gt_path)
} else {
None
};
Ok(Self {
index,
card_path,
device_path,
gt_path,
})
}
fn read_sysfs_string(&self, attr: &str) -> Option<String> {
fs::read_to_string(self.device_path.join(attr))
.ok()
.map(|s| s.trim().to_string())
}
#[allow(dead_code)]
fn read_sysfs_u64(&self, attr: &str) -> Option<u64> {
self.read_sysfs_string(attr)?.parse::<u64>().ok()
}
fn read_gt_string(&self, attr: &str) -> Option<String> {
let gt_path = self.gt_path.as_ref()?;
if let Ok(content) = fs::read_to_string(gt_path.join("gt0").join(attr)) {
return Some(content.trim().to_string());
}
fs::read_to_string(gt_path.join(attr))
.ok()
.map(|s| s.trim().to_string())
}
fn read_gt_u64(&self, attr: &str) -> Option<u64> {
self.read_gt_string(attr)?.parse::<u64>().ok()
}
fn read_xe_freq_mhz(&self, attr: &str) -> Option<u32> {
let tiles = fs::read_dir(&self.device_path).ok()?;
for tile in tiles.filter_map(|e| e.ok()) {
if !tile.file_name().to_string_lossy().starts_with("tile") {
continue;
}
let Ok(gts) = fs::read_dir(tile.path()) else {
continue;
};
for gt in gts.filter_map(|e| e.ok()) {
if !gt.file_name().to_string_lossy().starts_with("gt") {
continue;
}
let content = fs::read_to_string(gt.path().join("freq0").join(attr));
if let Some(freq) = content.ok().and_then(|s| parse_freq_mhz(&s)) {
return Some(freq);
}
}
}
None
}
fn read_hwmon_temp(&self, hwmon_path: &std::path::Path, sensor: &str) -> Option<f32> {
fs::read_to_string(hwmon_path.join(sensor))
.ok()
.and_then(|s| s.trim().parse::<i32>().ok())
.map(|millidegrees| millidegrees as f32 / 1000.0)
}
fn get_temperature_thresholds(
&self,
hwmon_path: &std::path::Path,
) -> Option<TemperatureThresholds> {
let critical = self.read_hwmon_temp(hwmon_path, "temp1_crit");
let shutdown = critical;
let slowdown = None;
if critical.is_some() || shutdown.is_some() {
Some(TemperatureThresholds {
slowdown,
shutdown,
critical,
memory_critical: None,
})
} else {
None
}
}
fn get_driver_name(&self) -> Option<String> {
if let Ok(link) = fs::read_link(self.device_path.join("driver")) {
if let Some(name) = link.file_name() {
return Some(name.to_string_lossy().to_string());
}
}
None
}
}
impl Device for IntelGpu {
fn vendor(&self) -> Vendor {
Vendor::Intel
}
fn index(&self) -> u32 {
self.index
}
fn name(&self) -> Result<String, Error> {
if let Some(name) = self.read_sysfs_string("product_name") {
return Ok(name);
}
if let Some(device_id) = self.read_sysfs_string("device") {
let name = match device_id.as_str() {
"0x4680" | "0x4682" | "0x4688" | "0x468a" | "0x468b" => "Intel Arc A770",
"0x4690" | "0x4692" | "0x4693" => "Intel Arc A750",
"0x56a0" | "0x56a1" | "0x56a2" => "Intel Arc A580",
"0x56a5" | "0x56a6" => "Intel Arc A380",
"0x46a0" | "0x46a1" | "0x46a2" | "0x46a3" | "0x46a6" | "0x46a8" | "0x46aa"
| "0x462a" | "0x4626" | "0x4628" => "Intel Iris Xe",
_ => "Intel GPU",
};
return Ok(format!("{} ({})", name, device_id));
}
Ok(format!("Intel GPU #{}", self.index))
}
fn uuid(&self) -> Result<String, Error> {
Err(Error::NotSupported)
}
fn pci_info(&self) -> Result<PciInfo, Error> {
let link = fs::read_link(&self.device_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read device link: {}", e)))?;
let path_str = link.to_string_lossy();
for component in path_str.split('/').rev() {
if let Some((domain, bus, device, function)) = PciInfo::parse_address(component) {
return Ok(PciInfo {
domain,
bus,
device,
function,
bus_id: format!("{:04x}:{:02x}:{:02x}.{}", domain, bus, device, function),
pcie_generation: None,
pcie_link_width: None,
});
}
}
Err(Error::QueryFailed("Could not parse PCI info".to_string()))
}
fn driver_version(&self) -> Result<String, Error> {
let driver = self
.get_driver_name()
.ok_or_else(|| Error::QueryFailed("no driver is bound to this device".to_string()))?;
fs::read_to_string(format!("/sys/module/{}/version", driver))
.map(|version| version.trim().to_string())
.map_err(|e| {
Error::QueryFailed(format!("{} module version not readable: {}", driver, e))
})
}
fn temperature(&self) -> Result<Temperature, Error> {
let hwmon_path = self.device_path.join("hwmon");
if !hwmon_path.exists() {
return Ok(Temperature {
edge: None,
junction: None,
memory: None,
hotspot: None,
vr_gfx: None,
vr_soc: None,
vr_mem: None,
hbm: None,
thresholds: None,
});
}
let hwmon_dirs: Vec<_> = fs::read_dir(&hwmon_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read hwmon dir: {}", e)))?
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().starts_with("hwmon"))
.collect();
if hwmon_dirs.is_empty() {
return Ok(Temperature {
edge: None,
junction: None,
memory: None,
hotspot: None,
vr_gfx: None,
vr_soc: None,
vr_mem: None,
hbm: None,
thresholds: None,
});
}
let hwmon = hwmon_dirs[0].path();
let junction = self.read_hwmon_temp(&hwmon, "temp1_input");
let thresholds = self.get_temperature_thresholds(&hwmon);
Ok(Temperature {
edge: None,
junction,
memory: None,
hotspot: None,
vr_gfx: None,
vr_soc: None,
vr_mem: None,
hbm: None,
thresholds,
})
}
fn power(&self) -> Result<Power, Error> {
let hwmon_path = self.device_path.join("hwmon");
if !hwmon_path.exists() {
return Err(Error::NotSupported);
}
let hwmon_dirs: Vec<_> = fs::read_dir(&hwmon_path)
.map_err(|e| Error::QueryFailed(format!("Failed to read hwmon dir: {}", e)))?
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().starts_with("hwmon"))
.collect();
if hwmon_dirs.is_empty() {
return Err(Error::NotSupported);
}
let hwmon = hwmon_dirs[0].path();
let read_power = |sensor: &str| -> Option<f32> {
fs::read_to_string(hwmon.join(sensor))
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.map(|microwatts| microwatts as f32 / 1_000_000.0)
};
let current = read_power("power1_input");
let limit = read_power("power1_cap");
let max_limit = read_power("power1_cap_max");
Ok(Power {
current,
average: current,
limit,
default_limit: None,
min_limit: None,
max_limit,
enforced_limit: limit,
})
}
fn clocks(&self) -> Result<Clocks, Error> {
if let Some(freq) = self.read_xe_freq_mhz("act_freq") {
return Ok(Clocks {
graphics: Some(freq),
memory: None,
sm: None,
video: None,
});
}
if let Some(freq_str) = self.read_sysfs_string("gt_cur_freq_mhz") {
if let Ok(freq) = freq_str.parse::<u32>() {
return Ok(Clocks {
graphics: Some(freq),
memory: None,
sm: None,
video: None,
});
}
}
Ok(Clocks {
graphics: None,
memory: None,
sm: None,
video: None,
})
}
fn utilization(&self) -> Result<Utilization, Error> {
Ok(Utilization {
gpu: None,
memory: None,
encoder: None,
decoder: None,
jpeg: None,
ofa: None,
})
}
fn memory(&self) -> Result<Memory, Error> {
if let Some(total) = self.read_gt_u64("mem_info/total") {
let used = self.read_gt_u64("mem_info/used");
let free = used.map(|u| total.saturating_sub(u));
return Ok(Memory {
total: Some(total),
used,
free,
bar1_total: None,
bar1_used: None,
});
}
Ok(Memory {
total: None,
used: None,
free: None,
bar1_total: None,
bar1_used: None,
})
}
fn fan_speed(&self) -> Result<Option<FanSpeed>, Error> {
let hwmon_path = self.device_path.join("hwmon");
if !hwmon_path.exists() {
return Ok(None);
}
let hwmon_dir = fs::read_dir(&hwmon_path)
.ok()
.and_then(|rd| rd.filter_map(|e| e.ok()).nth(0))
.map(|e| e.path());
if let Some(hwmon) = hwmon_dir {
if let Some(pwm) = fs::read_to_string(hwmon.join("pwm1"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
{
let pwm_max = fs::read_to_string(hwmon.join("pwm1_max"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
.unwrap_or(255);
if let Some(percentage) = pwm_percent(pwm, pwm_max) {
return Ok(Some(FanSpeed::Percent(percentage)));
}
}
if let Some(rpm) = fs::read_to_string(hwmon.join("fan1_input"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
{
return Ok(Some(FanSpeed::Rpm(rpm)));
}
}
Ok(None)
}
fn performance_state(&self) -> Result<Option<String>, Error> {
if let Some(boost) = self.read_sysfs_string("gt_boost_freq_mhz") {
return Ok(Some(format!("Boost: {} MHz", boost)));
}
Ok(None)
}
fn processes(&self) -> Result<Vec<Box<dyn GpuProcess>>, Error> {
Err(Error::NotSupportedBecause(
concat!(
"GPU process lists are not read on the xe/i915 sysfs path; ",
"DRM clients are in /proc/*/fdinfo, which this reader does not parse"
)
.to_string(),
))
}
}
fn parse_freq_mhz(content: &str) -> Option<u32> {
content.trim().parse::<u32>().ok()
}
fn pwm_percent(pwm: u32, pwm_max: u32) -> Option<u32> {
(pwm_max > 0).then(|| pwm.saturating_mul(100) / pwm_max)
}
pub fn enumerate(failures: &mut Vec<String>) -> Result<Vec<Box<dyn Device>>, Error> {
let mut devices: Vec<Box<dyn Device>> = Vec::new();
let drm_path = std::path::Path::new("/sys/class/drm");
if !drm_path.exists() {
return Ok(devices);
}
let entries = fs::read_dir(drm_path).map_err(|e| {
Error::InitializationFailed(format!("Failed to read /sys/class/drm: {}", e))
})?;
for entry in entries.filter_map(|e| e.ok()) {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if !name_str.starts_with("card") || name_str.contains('-') {
continue;
}
let index = name_str.trim_start_matches("card").parse::<u32>().ok();
let Some(index) = index else {
continue;
};
let card_path = entry.path();
let device_path = card_path.join("device");
if let Ok(vendor_id) = fs::read_to_string(device_path.join("vendor")) {
if vendor_id.trim() == "0x8086" {
if let Ok(class) = fs::read_to_string(device_path.join("class")) {
if class.trim().starts_with("0x03") {
match IntelGpu::new(index, card_path) {
Ok(gpu) => devices.push(Box::new(gpu)),
Err(e) => failures.push(format!("card{index}: {e}")),
}
}
}
}
}
}
if devices.is_empty() {
return Err(Error::NoDevicesFound);
}
Ok(devices)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intel_vendor() {
let vendor = Vendor::Intel;
assert_eq!(format!("{}", vendor), "Intel");
}
#[test]
fn xe_freq_file_is_mhz_and_is_not_converted() {
assert_eq!(parse_freq_mhz("1950\n"), Some(1950));
assert_eq!(parse_freq_mhz("300"), Some(300));
assert_eq!(parse_freq_mhz(""), None);
assert_eq!(parse_freq_mhz("n/a"), None);
}
#[test]
fn fan_percent_has_no_value_for_a_zero_maximum() {
assert_eq!(pwm_percent(128, 255), Some(50));
assert_eq!(pwm_percent(255, 255), Some(100));
assert_eq!(pwm_percent(10, 0), None);
}
}