use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThermalZoneType {
Acpi,
X86Pkg,
Pch,
Soc,
Gpu,
Nvme,
Iwlwifi,
Other(String),
}
impl std::fmt::Display for ThermalZoneType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Acpi => write!(f, "ACPI"),
Self::X86Pkg => write!(f, "x86_pkg"),
Self::Pch => write!(f, "PCH"),
Self::Soc => write!(f, "SoC"),
Self::Gpu => write!(f, "GPU"),
Self::Nvme => write!(f, "NVMe"),
Self::Iwlwifi => write!(f, "iwlwifi"),
Self::Other(s) => write!(f, "{}", s),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TripPointType {
Active,
Passive,
Hot,
Critical,
}
impl std::fmt::Display for TripPointType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Active => write!(f, "active"),
Self::Passive => write!(f, "passive"),
Self::Hot => write!(f, "hot"),
Self::Critical => write!(f, "critical"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TripPoint {
pub index: u32,
pub trip_type: TripPointType,
pub temp_mc: Option<i64>,
pub hysteresis_mc: Option<i64>,
}
impl TripPoint {
pub fn temp_c(&self) -> Option<f64> {
self.temp_mc.map(|mc| mc as f64 / 1000.0)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoolingDeviceInfo {
pub name: String,
pub cooling_type: String,
pub cur_state: Option<u32>,
pub max_state: Option<u32>,
}
impl CoolingDeviceInfo {
pub fn utilization_pct(&self) -> Option<f64> {
let (cur, max) = (self.cur_state?, self.max_state?);
if max == 0 {
return None;
}
Some((cur as f64 / max as f64) * 100.0)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThermalZoneInfo {
pub name: String,
pub zone_type: ThermalZoneType,
pub type_string: String,
pub temp_mc: Option<i64>,
pub policy: String,
pub available_policies: Vec<String>,
pub trip_points: Vec<TripPoint>,
pub enabled: bool,
pub passive_active: bool,
}
impl ThermalZoneInfo {
pub fn temp_c(&self) -> Option<f64> {
self.temp_mc.map(|mc| mc as f64 / 1000.0)
}
pub fn headroom_to_critical_c(&self) -> Option<f64> {
let here = self.temp_c()?;
self.trip_points
.iter()
.filter(|tp| tp.trip_type == TripPointType::Critical)
.find_map(|tp| tp.temp_c())
.map(|critical| critical - here)
}
pub fn is_throttling(&self) -> Option<bool> {
let here = self.temp_mc?;
let passive: Vec<i64> = self
.trip_points
.iter()
.filter(|tp| tp.trip_type == TripPointType::Passive)
.filter_map(|tp| tp.temp_mc)
.collect();
(!passive.is_empty()).then(|| passive.iter().any(|t| here >= *t))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThermalZoneOverview {
pub zones: Vec<ThermalZoneInfo>,
pub cooling_devices: Vec<CoolingDeviceInfo>,
pub zone_count: u32,
pub hottest_zone: String,
pub hottest_temp_c: Option<f64>,
pub throttling_count: u32,
pub recommendations: Vec<String>,
}
pub struct ThermalZoneMonitor {
overview: ThermalZoneOverview,
}
impl ThermalZoneMonitor {
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) -> &ThermalZoneOverview {
&self.overview
}
pub fn zones(&self) -> &[ThermalZoneInfo] {
&self.overview.zones
}
pub fn cooling_devices(&self) -> &[CoolingDeviceInfo] {
&self.overview.cooling_devices
}
pub fn hottest(&self) -> Option<&ThermalZoneInfo> {
self.overview
.zones
.iter()
.filter(|z| z.temp_mc.is_some())
.max_by_key(|z| z.temp_mc)
}
pub fn throttling_zones(&self) -> Vec<&ThermalZoneInfo> {
self.overview
.zones
.iter()
.filter(|z| z.is_throttling() == Some(true))
.collect()
}
#[cfg(target_os = "linux")]
fn scan() -> Result<ThermalZoneOverview, IronError> {
let thermal_path = std::path::Path::new("/sys/class/thermal");
if !thermal_path.exists() {
return Ok(Self::empty_overview());
}
let mut zones = Vec::new();
let mut cooling = Vec::new();
let entries = std::fs::read_dir(thermal_path).map_err(IronError::Io)?;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
let path = entry.path();
if name.starts_with("thermal_zone") {
if let Some(zone) = Self::read_zone(&path, &name) {
zones.push(zone);
}
} else if name.starts_with("cooling_device") {
if let Some(cd) = Self::read_cooling_device(&path, &name) {
cooling.push(cd);
}
}
}
zones.sort_by(|a, b| a.name.cmp(&b.name));
cooling.sort_by(|a, b| a.name.cmp(&b.name));
let zone_count = zones.len() as u32;
let throttling = zones
.iter()
.filter(|z| z.is_throttling() == Some(true))
.count() as u32;
let (hottest_zone, hottest_temp) = zones
.iter()
.filter(|z| z.temp_mc.is_some())
.max_by_key(|z| z.temp_mc)
.map(|z| (z.name.clone(), z.temp_c()))
.unwrap_or((String::new(), None));
let mut recs = Vec::new();
if throttling > 0 {
recs.push(format!(
"{} zone(s) in thermal throttling state",
throttling
));
}
for zone in &zones {
if let Some(headroom) = zone.headroom_to_critical_c() {
if headroom < 10.0 {
recs.push(format!(
"{}: only {:.1}°C from critical shutdown temperature",
zone.name, headroom
));
}
}
}
Ok(ThermalZoneOverview {
zones,
cooling_devices: cooling,
zone_count,
hottest_zone,
hottest_temp_c: hottest_temp,
throttling_count: throttling,
recommendations: recs,
})
}
#[cfg(target_os = "linux")]
fn read_zone(path: &std::path::Path, name: &str) -> Option<ThermalZoneInfo> {
let type_string = Self::read_sysfs(&path.join("type")).unwrap_or_default();
let zone_type = match type_string.as_str() {
"acpitz" | "ACPI\\_THM" => ThermalZoneType::Acpi,
s if s.starts_with("x86_pkg") => ThermalZoneType::X86Pkg,
"pch_cannonlake" | "pch_skylake" | "pch_alderlake" | "pch_raptorlake" => {
ThermalZoneType::Pch
}
s if s.contains("pch") => ThermalZoneType::Pch,
s if s.contains("soc") || s.contains("SoC") => ThermalZoneType::Soc,
s if s.contains("gpu") || s.contains("GPU") => ThermalZoneType::Gpu,
s if s.starts_with("nvme") => ThermalZoneType::Nvme,
"iwlwifi_1" | "iwlwifi" => ThermalZoneType::Iwlwifi,
s if s.contains("iwlwifi") => ThermalZoneType::Iwlwifi,
other if !other.is_empty() => ThermalZoneType::Other(other.to_string()),
_ => ThermalZoneType::Other("unknown".to_string()),
};
let temp_mc = Self::read_sysfs_i64(&path.join("temp"));
let policy = Self::read_sysfs(&path.join("policy")).unwrap_or_default();
let available_policies = Self::read_sysfs(&path.join("available_policies"))
.map(|s| s.split_whitespace().map(String::from).collect())
.unwrap_or_default();
let mode_str = Self::read_sysfs(&path.join("mode")).unwrap_or_else(|| "enabled".into());
let enabled = mode_str != "disabled";
let mut trip_points = Vec::new();
for i in 0..20 {
let tp_temp_path = path.join(format!("trip_point_{}_temp", i));
let tp_type_path = path.join(format!("trip_point_{}_type", i));
if !tp_temp_path.exists() {
break;
}
let tp_temp = Self::read_sysfs_i64(&tp_temp_path);
let tp_type_str = Self::read_sysfs(&tp_type_path).unwrap_or_default();
let tp_type = match tp_type_str.as_str() {
"active" => TripPointType::Active,
"passive" => TripPointType::Passive,
"hot" => TripPointType::Hot,
"critical" => TripPointType::Critical,
_ => continue,
};
let hyst = Self::read_sysfs_i64(&path.join(format!("trip_point_{}_hyst", i)));
trip_points.push(TripPoint {
index: i,
trip_type: tp_type,
temp_mc: tp_temp,
hysteresis_mc: hyst,
});
}
let passive_active = trip_points
.iter()
.filter(|tp| tp.trip_type == TripPointType::Passive)
.any(|tp| temp_mc >= tp.temp_mc);
Some(ThermalZoneInfo {
name: name.to_string(),
zone_type,
type_string,
temp_mc,
policy,
available_policies,
trip_points,
enabled,
passive_active,
})
}
#[cfg(target_os = "linux")]
fn read_cooling_device(path: &std::path::Path, name: &str) -> Option<CoolingDeviceInfo> {
let cooling_type = Self::read_sysfs(&path.join("type")).unwrap_or_default();
let cur_state = Self::read_sysfs_u32(&path.join("cur_state"));
let max_state = Self::read_sysfs_u32(&path.join("max_state"));
Some(CoolingDeviceInfo {
name: name.to_string(),
cooling_type,
cur_state,
max_state,
})
}
#[cfg(target_os = "linux")]
fn read_sysfs(path: &std::path::Path) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|s| s.trim().to_string())
}
#[cfg(target_os = "linux")]
fn read_sysfs_i64(path: &std::path::Path) -> Option<i64> {
std::fs::read_to_string(path)
.ok()
.and_then(|s| s.trim().parse().ok())
}
#[cfg(target_os = "linux")]
fn read_sysfs_u32(path: &std::path::Path) -> Option<u32> {
std::fs::read_to_string(path)
.ok()
.and_then(|s| s.trim().parse().ok())
}
#[cfg(not(target_os = "linux"))]
fn scan() -> Result<ThermalZoneOverview, IronError> {
Err(IronError::UnsupportedPlatform(
"thermal zones are read from `/sys/class/thermal`, which this platform does not expose"
.into(),
))
}
fn empty_overview() -> ThermalZoneOverview {
ThermalZoneOverview {
zones: Vec::new(),
cooling_devices: Vec::new(),
zone_count: 0,
hottest_zone: String::new(),
hottest_temp_c: None,
throttling_count: 0,
recommendations: Vec::new(),
}
}
}
impl Default for ThermalZoneMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
overview: Self::empty_overview(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zone_type_display() {
assert_eq!(ThermalZoneType::X86Pkg.to_string(), "x86_pkg");
assert_eq!(ThermalZoneType::Pch.to_string(), "PCH");
assert_eq!(ThermalZoneType::Nvme.to_string(), "NVMe");
}
#[test]
fn test_trip_point_temp() {
let tp = TripPoint {
index: 0,
trip_type: TripPointType::Critical,
temp_mc: Some(105_000),
hysteresis_mc: Some(0),
};
assert!((tp.temp_c().expect("a read trip point") - 105.0).abs() < 0.01);
let unread = TripPoint {
index: 1,
trip_type: TripPointType::Critical,
temp_mc: None,
hysteresis_mc: None,
};
assert_eq!(unread.temp_c(), None);
}
#[test]
fn test_throttle_detection() {
let zone = ThermalZoneInfo {
name: "thermal_zone0".into(),
zone_type: ThermalZoneType::X86Pkg,
type_string: "x86_pkg_temp".into(),
temp_mc: Some(95_000),
policy: "step_wise".into(),
available_policies: vec!["step_wise".into()],
trip_points: vec![
TripPoint {
index: 0,
trip_type: TripPointType::Passive,
temp_mc: Some(90_000),
hysteresis_mc: Some(2_000),
},
TripPoint {
index: 1,
trip_type: TripPointType::Critical,
temp_mc: Some(105_000),
hysteresis_mc: Some(0),
},
],
enabled: true,
passive_active: true,
};
assert_eq!(zone.is_throttling(), Some(true));
assert!((zone.headroom_to_critical_c().unwrap() - 10.0).abs() < 0.01);
}
#[test]
fn an_unread_zone_does_not_report_that_it_is_not_throttling() {
let zone = ThermalZoneInfo {
name: "thermal_zone0".into(),
zone_type: ThermalZoneType::X86Pkg,
type_string: "x86_pkg_temp".into(),
temp_mc: None,
policy: "step_wise".into(),
available_policies: vec!["step_wise".into()],
trip_points: vec![TripPoint {
index: 0,
trip_type: TripPointType::Passive,
temp_mc: Some(90_000),
hysteresis_mc: Some(2_000),
}],
enabled: true,
passive_active: false,
};
assert_eq!(
zone.is_throttling(),
None,
concat!(
"with no temperature there is no answer, and `false` is ",
"the answer that gets acted on"
)
);
assert_eq!(zone.temp_c(), None);
assert_eq!(
zone.headroom_to_critical_c(),
None,
"headroom from an unknown temperature is unknown"
);
}
#[test]
fn test_cooling_utilization() {
let cd = CoolingDeviceInfo {
name: "cooling_device0".into(),
cooling_type: "Processor".into(),
cur_state: Some(5),
max_state: Some(10),
};
assert!((cd.utilization_pct().expect("both states read") - 50.0).abs() < 0.01);
}
#[test]
fn test_monitor_default() {
let monitor = ThermalZoneMonitor::default();
let _overview = monitor.overview();
}
#[test]
fn test_serialization() {
let zone = ThermalZoneInfo {
name: "thermal_zone0".into(),
zone_type: ThermalZoneType::Acpi,
type_string: "acpitz".into(),
temp_mc: Some(45_000),
policy: "step_wise".into(),
available_policies: Vec::new(),
trip_points: Vec::new(),
enabled: true,
passive_active: false,
};
let json = serde_json::to_string(&zone).unwrap();
assert!(json.contains("acpitz"));
let _: ThermalZoneInfo = serde_json::from_str(&json).unwrap();
}
}