Files
ember-tune-rs/src/sal/dell_xps_9380.rs
2026-02-27 17:04:47 +01:00

312 lines
12 KiB
Rust

use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus, EnvironmentCtx};
use crate::sal::safety::{TdpLimitMicroWatts, FanSpeedPercentage};
use anyhow::{Result, Context, anyhow};
use std::fs;
use std::path::{PathBuf};
use std::time::{Duration, Instant};
use std::sync::Mutex;
use tracing::{debug, warn};
use crate::sal::heuristic::discovery::SystemFactSheet;
/// Implementation of the System Abstraction Layer for the Dell XPS 13 9380.
pub struct DellXps9380Sal {
ctx: EnvironmentCtx,
fact_sheet: SystemFactSheet,
temp_path: PathBuf,
pwr_path: PathBuf,
fan_paths: Vec<PathBuf>,
freq_path: PathBuf,
pl1_path: PathBuf,
pl2_path: PathBuf,
last_poll: Mutex<Instant>,
last_temp: Mutex<f32>,
last_fans: Mutex<Vec<u32>>,
suppressed_services: Mutex<Vec<String>>,
msr_file: Mutex<fs::File>,
last_energy: Mutex<(u64, Instant)>,
last_watts: Mutex<f32>,
// --- Original State for Restoration ---
original_pl1: Mutex<Option<u64>>,
original_pl2: Mutex<Option<u64>>,
original_fan_mode: Mutex<Option<String>>,
}
impl DellXps9380Sal {
/// Initializes the Dell SAL, opening the MSR interface and discovering sensors.
pub fn init(ctx: EnvironmentCtx, facts: SystemFactSheet) -> Result<Self> {
let temp_path = facts.temp_path.clone().context("Dell SAL requires temperature sensor")?;
let pwr_base = facts.rapl_paths.first().cloned().context("Dell SAL requires RAPL interface")?;
let fan_paths = facts.fan_paths.clone();
let freq_path = ctx.sysfs_base.join("sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
let msr_path = ctx.sysfs_base.join("dev/cpu/0/msr");
let msr_file = fs::OpenOptions::new().read(true).write(true).open(&msr_path)
.with_context(|| format!("Failed to open {:?}. Is the 'msr' module loaded?", msr_path))?;
let initial_energy = fs::read_to_string(pwr_base.join("energy_uj")).unwrap_or_default().trim().parse().unwrap_or(0);
Ok(Self {
temp_path,
pwr_path: pwr_base.join("power1_average"),
fan_paths,
freq_path,
pl1_path: pwr_base.join("constraint_0_power_limit_uw"),
pl2_path: pwr_base.join("constraint_1_power_limit_uw"),
last_poll: Mutex::new(Instant::now() - Duration::from_secs(2)),
last_temp: Mutex::new(0.0),
last_fans: Mutex::new(Vec::new()),
suppressed_services: Mutex::new(Vec::new()),
msr_file: Mutex::new(msr_file),
last_energy: Mutex::new((initial_energy, Instant::now())),
last_watts: Mutex::new(0.0),
fact_sheet: facts,
ctx,
original_pl1: Mutex::new(None),
original_pl2: Mutex::new(None),
original_fan_mode: Mutex::new(None),
})
}
fn read_msr(&self, msr: u32) -> Result<u64> {
use std::os::unix::fs::FileExt;
let mut buf = [0u8; 8];
let file = self.msr_file.lock().unwrap();
file.read_at(&mut buf, msr as u64)?;
Ok(u64::from_le_bytes(buf))
}
fn write_msr(&self, msr: u32, val: u64) -> Result<()> {
use std::os::unix::fs::FileExt;
let file = self.msr_file.lock().unwrap();
file.write_at(&val.to_le_bytes(), msr as u64)?;
Ok(())
}
}
impl PreflightAuditor for DellXps9380Sal {
fn audit(&self) -> Box<dyn Iterator<Item = AuditStep> + '_> {
let mut steps = Vec::new();
steps.push(AuditStep {
description: "Root Privileges".to_string(),
outcome: if unsafe { libc::getuid() } == 0 { Ok(()) } else { Err(AuditError::RootRequired) }
});
// RAPL Lock Check (MSR 0x610)
let rapl_lock = match self.read_msr(0x610) {
Ok(val) => {
if (val & (1 << 63)) != 0 {
Err(AuditError::KernelIncompatible("RAPL Registers are locked by BIOS. Power limit tuning is impossible.".to_string()))
} else {
Ok(())
}
},
Err(e) => Err(AuditError::ToolMissing(format!("Cannot read MSR 0x610: {}", e))),
};
steps.push(AuditStep {
description: "MSR 0x610 RAPL Lock Status".to_string(),
outcome: rapl_lock,
});
let modules = ["dell_smm_hwmon", "msr", "intel_rapl_msr"];
for mod_name in modules {
let path = self.ctx.sysfs_base.join(format!("sys/module/{}", mod_name));
steps.push(AuditStep {
description: format!("Kernel Module: {}", mod_name),
outcome: if path.exists() { Ok(()) } else {
Err(AuditError::ToolMissing(format!("Module '{}' not loaded.", mod_name)))
}
});
}
let cmdline_path = self.ctx.sysfs_base.join("proc/cmdline");
let cmdline = fs::read_to_string(cmdline_path).unwrap_or_default();
let params = [
("dell_smm_hwmon.ignore_dmi=1", "dell_smm_hwmon.ignore_dmi=1"),
("dell_smm_hwmon.restricted=0", "dell_smm_hwmon.restricted=0"),
("msr.allow_writes=on", "msr.allow_writes=on"),
];
for (label, p) in params {
steps.push(AuditStep {
description: format!("Kernel Param: {}", label),
outcome: if cmdline.contains(p) { Ok(()) } else { Err(AuditError::MissingKernelParam(p.to_string())) }
});
}
let ac_status_path = self.ctx.sysfs_base.join("sys/class/power_supply/AC/online");
let ac_status = fs::read_to_string(ac_status_path).unwrap_or_else(|_| "0".to_string());
steps.push(AuditStep {
description: "AC Power Connection".to_string(),
outcome: if ac_status.trim() == "1" { Ok(()) } else {
Err(AuditError::AcPowerMissing("System must be on AC power".to_string()))
}
});
Box::new(steps.into_iter())
}
}
impl EnvironmentGuard for DellXps9380Sal {
fn suppress(&self) -> Result<()> {
if let Ok(pl1) = fs::read_to_string(&self.pl1_path) {
*self.original_pl1.lock().unwrap() = pl1.trim().parse().ok();
}
if let Ok(pl2) = fs::read_to_string(&self.pl2_path) {
*self.original_pl2.lock().unwrap() = pl2.trim().parse().ok();
}
*self.original_fan_mode.lock().unwrap() = Some("1".to_string());
let services = ["tlp", "thermald", "i8kmon"];
let mut suppressed = self.suppressed_services.lock().unwrap();
for s in services {
if self.ctx.runner.run("systemctl", &["is-active", "--quiet", s]).is_ok() {
let _ = self.ctx.runner.run("systemctl", &["stop", s]);
suppressed.push(s.to_string());
}
}
Ok(())
}
fn restore(&self) -> Result<()> {
if let Some(pl1) = *self.original_pl1.lock().unwrap() {
let _ = fs::write(&self.pl1_path, pl1.to_string());
}
if let Some(pl2) = *self.original_pl2.lock().unwrap() {
let _ = fs::write(&self.pl2_path, pl2.to_string());
}
if let Some(tool_path) = self.fact_sheet.paths.tools.get("dell_fan_ctrl") {
let _ = self.ctx.runner.run(&tool_path.to_string_lossy(), &["1"]);
}
let mut suppressed = self.suppressed_services.lock().unwrap();
for s in suppressed.drain(..) {
let _ = self.ctx.runner.run("systemctl", &["start", &s]);
}
Ok(())
}
}
impl SensorBus for DellXps9380Sal {
fn get_temp(&self) -> Result<f32> {
let mut last_poll = self.last_poll.lock().unwrap();
let now = Instant::now();
if now.duration_since(*last_poll) < Duration::from_millis(1000) {
return Ok(*self.last_temp.lock().unwrap());
}
let s = fs::read_to_string(&self.temp_path)?;
let val = s.trim().parse::<f32>()? / 1000.0;
*self.last_temp.lock().unwrap() = val;
*last_poll = now;
Ok(val)
}
fn get_power_w(&self) -> Result<f32> {
let rapl_base = self.pl1_path.parent().context("RAPL path error")?;
let energy_path = rapl_base.join("energy_uj");
if energy_path.exists() {
let mut last_energy = self.last_energy.lock().unwrap();
let mut last_watts = self.last_watts.lock().unwrap();
let e2_str = fs::read_to_string(&energy_path)?;
let e2 = e2_str.trim().parse::<u64>()?;
let t2 = Instant::now();
let (e1, t1) = *last_energy;
let delta_e = e2.wrapping_sub(e1);
let delta_t = t2.duration_since(t1).as_secs_f32();
if delta_t < 0.1 {
return Ok(*last_watts); // Return cached if polled too fast
}
let watts = (delta_e as f32 / 1_000_000.0) / delta_t;
*last_energy = (e2, t2);
*last_watts = watts;
Ok(watts)
} else {
let s = fs::read_to_string(&self.pwr_path)?;
Ok(s.trim().parse::<f32>()? / 1000000.0)
}
}
fn get_fan_rpms(&self) -> Result<Vec<u32>> {
let mut last_poll = self.last_poll.lock().unwrap();
let now = Instant::now();
if now.duration_since(*last_poll) < Duration::from_millis(1000) {
return Ok(self.last_fans.lock().unwrap().clone());
}
let mut fans = Vec::new();
for path in &self.fan_paths {
if let Ok(s) = fs::read_to_string(path) {
if let Ok(rpm) = s.trim().parse::<u32>() { fans.push(rpm); }
}
}
*self.last_fans.lock().unwrap() = fans.clone();
*last_poll = now;
Ok(fans)
}
fn get_freq_mhz(&self) -> Result<f32> {
let s = fs::read_to_string(&self.freq_path)?;
Ok(s.trim().parse::<f32>()? / 1000.0)
}
fn get_throttling_status(&self) -> Result<bool> {
// MSR 0x19C bit 0 is "Thermal Status", bit 1 is "Thermal Log"
let val = self.read_msr(0x19C)?;
Ok((val & 0x1) != 0)
}
}
impl ActuatorBus for DellXps9380Sal {
fn set_fan_mode(&self, mode: &str) -> Result<()> {
let tool_path = self.fact_sheet.paths.tools.get("dell_fan_ctrl")
.ok_or_else(|| anyhow!("Dell fan control tool not found in PATH"))?;
let tool_str = tool_path.to_string_lossy();
match mode {
"max" | "Manual" => { self.ctx.runner.run(&tool_str, &["0"])?; }
"auto" | "Auto" => { self.ctx.runner.run(&tool_str, &["1"])?; }
_ => {}
}
Ok(())
}
fn set_fan_speed(&self, _speed: FanSpeedPercentage) -> Result<()> {
Ok(())
}
fn set_sustained_power_limit(&self, limit: TdpLimitMicroWatts) -> Result<()> {
fs::write(&self.pl1_path, limit.as_u64().to_string())?;
Ok(())
}
fn set_burst_power_limit(&self, limit: TdpLimitMicroWatts) -> Result<()> {
fs::write(&self.pl2_path, limit.as_u64().to_string())?;
Ok(())
}
}
impl HardwareWatchdog for DellXps9380Sal {
fn get_safety_status(&self) -> Result<SafetyStatus> {
let temp = self.get_temp()?;
if temp > 98.0 {
return Ok(SafetyStatus::EmergencyAbort(format!("Thermal Runaway: {:.1}°C", temp)));
}
if let Ok(msr_val) = self.read_msr(0x1FC) {
if (msr_val & 0x1) != 0 && temp < 85.0 {
let _ = self.write_msr(0x1FC, msr_val & !0x1);
return Ok(SafetyStatus::Warning("BD PROCHOT Latch Cleared".to_string()));
}
}
Ok(SafetyStatus::Nominal)
}
}
impl Drop for DellXps9380Sal {
fn drop(&mut self) {
let _ = self.restore();
}
}