updated
This commit is contained in:
@@ -1,11 +1,12 @@
|
||||
use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus, EnvironmentCtx};
|
||||
use crate::sal::safety::{TdpLimitMicroWatts, FanSpeedPercentage};
|
||||
use crate::sal::safety::{PowerLimitWatts, FanSpeedPercent};
|
||||
use anyhow::{Result, Context, anyhow};
|
||||
use std::fs;
|
||||
use std::path::{PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::thread;
|
||||
use std::sync::Mutex;
|
||||
use tracing::{debug, warn};
|
||||
use tracing::{info, debug};
|
||||
use crate::sal::heuristic::discovery::SystemFactSheet;
|
||||
|
||||
/// Implementation of the System Abstraction Layer for the Dell XPS 13 9380.
|
||||
@@ -15,30 +16,66 @@ pub struct DellXps9380Sal {
|
||||
temp_path: PathBuf,
|
||||
pwr_path: PathBuf,
|
||||
fan_paths: Vec<PathBuf>,
|
||||
pwm_paths: Vec<PathBuf>,
|
||||
pwm_enable_paths: Vec<PathBuf>,
|
||||
pl1_paths: Vec<PathBuf>,
|
||||
pl2_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.
|
||||
/// Initializes the Dell SAL, opening the MSR interface and discovering sensors and PWM nodes.
|
||||
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();
|
||||
|
||||
// 1. Discover PWM and Enable nodes associated with the fan paths
|
||||
let mut pwm_paths = Vec::new();
|
||||
let mut pwm_enable_paths = Vec::new();
|
||||
for fan_p in &fan_paths {
|
||||
if let Some(parent) = fan_p.parent() {
|
||||
let fan_file = fan_p.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
let fan_idx = fan_file.chars().filter(|c| c.is_ascii_digit()).collect::<String>();
|
||||
let idx = if fan_idx.is_empty() { "1".to_string() } else { fan_idx };
|
||||
|
||||
let pwm_p = parent.join(format!("pwm{}", idx));
|
||||
if pwm_p.exists() { pwm_paths.push(pwm_p); }
|
||||
|
||||
let enable_p = parent.join(format!("pwm{}_enable", idx));
|
||||
if enable_p.exists() { pwm_enable_paths.push(enable_p); }
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Map all RAPL constraints
|
||||
let mut pl1_paths = Vec::new();
|
||||
let mut pl2_paths = Vec::new();
|
||||
for rapl_p in &facts.rapl_paths {
|
||||
pl1_paths.push(rapl_p.join("constraint_0_power_limit_uw"));
|
||||
pl2_paths.push(rapl_p.join("constraint_1_power_limit_uw"));
|
||||
}
|
||||
|
||||
// 3. Physical Sensor Verification & Warm Cache Priming
|
||||
let mut initial_fans = Vec::new();
|
||||
for fan_p in &fan_paths {
|
||||
let mut rpm = 0;
|
||||
for _ in 0..3 {
|
||||
if let Ok(val) = fs::read_to_string(fan_p) {
|
||||
rpm = val.trim().parse::<u32>().unwrap_or(0);
|
||||
if rpm > 0 { break; }
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
info!("SAL Warm-Start: Fan sensor {:?} -> {} RPM", fan_p, rpm);
|
||||
initial_fans.push(rpm);
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
@@ -47,25 +84,26 @@ impl DellXps9380Sal {
|
||||
|
||||
let initial_energy = fs::read_to_string(pwr_base.join("energy_uj")).unwrap_or_default().trim().parse().unwrap_or(0);
|
||||
|
||||
info!("SAL: Dell XPS 9380 Initialized. ({} fans, {} RAPL nodes found)",
|
||||
fan_paths.len(), facts.rapl_paths.len());
|
||||
|
||||
Ok(Self {
|
||||
temp_path,
|
||||
pwr_path: pwr_base.join("power1_average"),
|
||||
fan_paths,
|
||||
pwm_paths,
|
||||
pwm_enable_paths,
|
||||
pl1_paths,
|
||||
pl2_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()),
|
||||
last_fans: Mutex::new(initial_fans),
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -93,7 +131,6 @@ impl PreflightAuditor for DellXps9380Sal {
|
||||
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 {
|
||||
@@ -104,19 +141,14 @@ impl PreflightAuditor for DellXps9380Sal {
|
||||
},
|
||||
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,
|
||||
});
|
||||
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)))
|
||||
}
|
||||
outcome: if path.exists() { Ok(()) } else { Err(AuditError::ToolMissing(format!("Module '{}' not loaded.", mod_name))) }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -138,9 +170,7 @@ impl PreflightAuditor for DellXps9380Sal {
|
||||
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()))
|
||||
}
|
||||
outcome: if ac_status.trim() == "1" { Ok(()) } else { Err(AuditError::AcPowerMissing("System must be on AC power".to_string())) }
|
||||
});
|
||||
|
||||
Box::new(steps.into_iter())
|
||||
@@ -148,49 +178,16 @@ impl PreflightAuditor for DellXps9380Sal {
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
fn suppress(&self) -> Result<()> { Ok(()) }
|
||||
fn restore(&self) -> Result<()> { 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) {
|
||||
// # SAFETY: High frequency polling for watchdog
|
||||
if now.duration_since(*last_poll) < Duration::from_millis(100) {
|
||||
return Ok(*self.last_temp.lock().unwrap());
|
||||
}
|
||||
let s = fs::read_to_string(&self.temp_path)?;
|
||||
@@ -201,7 +198,7 @@ impl SensorBus for DellXps9380Sal {
|
||||
}
|
||||
|
||||
fn get_power_w(&self) -> Result<f32> {
|
||||
let rapl_base = self.pl1_path.parent().context("RAPL path error")?;
|
||||
let rapl_base = self.fact_sheet.rapl_paths.first().context("RAPL path error")?;
|
||||
let energy_path = rapl_base.join("energy_uj");
|
||||
|
||||
if energy_path.exists() {
|
||||
@@ -212,14 +209,9 @@ impl SensorBus for DellXps9380Sal {
|
||||
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
|
||||
}
|
||||
|
||||
if delta_t < 0.1 { return Ok(*last_watts); }
|
||||
let watts = (delta_e as f32 / 1_000_000.0) / delta_t;
|
||||
*last_energy = (e2, t2);
|
||||
*last_watts = watts;
|
||||
@@ -236,12 +228,27 @@ impl SensorBus for DellXps9380Sal {
|
||||
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); }
|
||||
let mut val = 0;
|
||||
for i in 0..5 {
|
||||
match fs::read_to_string(path) {
|
||||
Ok(s) => {
|
||||
if let Ok(rpm) = s.trim().parse::<u32>() {
|
||||
val = rpm;
|
||||
if rpm > 0 { break; }
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
debug!("SAL: Fan poll retry {} for {:?} failed: {}", i+1, path, e);
|
||||
}
|
||||
}
|
||||
thread::sleep(Duration::from_millis(150));
|
||||
}
|
||||
fans.push(val);
|
||||
}
|
||||
|
||||
*self.last_fans.lock().unwrap() = fans.clone();
|
||||
*last_poll = now;
|
||||
Ok(fans)
|
||||
@@ -253,7 +260,6 @@ impl SensorBus for DellXps9380Sal {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -266,24 +272,47 @@ impl ActuatorBus for DellXps9380Sal {
|
||||
let tool_str = tool_path.to_string_lossy();
|
||||
|
||||
match mode {
|
||||
"max" | "Manual" => { self.ctx.runner.run(&tool_str, &["0"])?; }
|
||||
"max" | "Manual" => {
|
||||
self.ctx.runner.run(&tool_str, &["0"])?;
|
||||
// Disabling BIOS control requires immediate PWM override
|
||||
self.set_fan_speed(FanSpeedPercent::new(100)?)?;
|
||||
}
|
||||
"auto" | "Auto" => { self.ctx.runner.run(&tool_str, &["1"])?; }
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_fan_speed(&self, _speed: FanSpeedPercentage) -> Result<()> {
|
||||
fn set_fan_speed(&self, speed: FanSpeedPercent) -> Result<()> {
|
||||
let pwm_val = ((speed.get() as u32 * 255) / 100) as u8;
|
||||
for p in &self.pwm_enable_paths { let _ = fs::write(p, "1"); }
|
||||
for path in &self.pwm_paths { let _ = fs::write(path, pwm_val.to_string()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_sustained_power_limit(&self, limit: TdpLimitMicroWatts) -> Result<()> {
|
||||
fs::write(&self.pl1_path, limit.as_u64().to_string())?;
|
||||
fn set_sustained_power_limit(&self, limit: PowerLimitWatts) -> Result<()> {
|
||||
for path in &self.pl1_paths {
|
||||
debug!("SAL: Applying PL1 ({:.1}W) to {:?}", limit.get(), path);
|
||||
fs::write(path, limit.as_microwatts().to_string())
|
||||
.with_context(|| format!("Failed to write PL1 to {:?}", path))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
let enable_p = parent.join("constraint_0_enabled");
|
||||
let _ = fs::write(&enable_p, "1");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_burst_power_limit(&self, limit: TdpLimitMicroWatts) -> Result<()> {
|
||||
fs::write(&self.pl2_path, limit.as_u64().to_string())?;
|
||||
fn set_burst_power_limit(&self, limit: PowerLimitWatts) -> Result<()> {
|
||||
for path in &self.pl2_paths {
|
||||
debug!("SAL: Applying PL2 ({:.1}W) to {:?}", limit.get(), path);
|
||||
fs::write(path, limit.as_microwatts().to_string())
|
||||
.with_context(|| format!("Failed to write PL2 to {:?}", path))?;
|
||||
if let Some(parent) = path.parent() {
|
||||
let enable_p = parent.join("constraint_1_enabled");
|
||||
let _ = fs::write(&enable_p, "1");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -305,7 +334,5 @@ impl HardwareWatchdog for DellXps9380Sal {
|
||||
}
|
||||
|
||||
impl Drop for DellXps9380Sal {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.restore();
|
||||
}
|
||||
fn drop(&mut self) { }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user