use super::traits::{PreflightAuditor, EnvironmentGuard, SensorBus, ActuatorBus, HardwareWatchdog, AuditError, AuditStep, SafetyStatus, EnvironmentCtx}; 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::{info, debug}; 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, pwm_paths: Vec, pwm_enable_paths: Vec, pl1_paths: Vec, pl2_paths: Vec, freq_path: PathBuf, last_poll: Mutex, last_temp: Mutex, last_fans: Mutex>, msr_file: Mutex, last_energy: Mutex<(u64, Instant)>, last_watts: Mutex, } impl DellXps9380Sal { /// Initializes the Dell SAL, opening the MSR interface and discovering sensors and PWM nodes. pub fn init(ctx: EnvironmentCtx, facts: SystemFactSheet) -> Result { 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::(); 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::().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"); 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); 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, last_poll: Mutex::new(Instant::now() - Duration::from_secs(2)), last_temp: Mutex::new(0.0), 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, }) } fn read_msr(&self, msr: u32) -> Result { 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 + '_> { let mut steps = Vec::new(); steps.push(AuditStep { description: "Root Privileges".to_string(), outcome: if unsafe { libc::getuid() } == 0 { Ok(()) } else { Err(AuditError::RootRequired) } }); 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<()> { Ok(()) } fn restore(&self) -> Result<()> { Ok(()) } } impl SensorBus for DellXps9380Sal { fn get_temp(&self) -> Result { let mut last_poll = self.last_poll.lock().unwrap(); let now = Instant::now(); // # 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)?; let val = s.trim().parse::()? / 1000.0; *self.last_temp.lock().unwrap() = val; *last_poll = now; Ok(val) } fn get_power_w(&self) -> Result { 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() { 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::()?; 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); } 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::()? / 1000000.0) } } fn get_fan_rpms(&self) -> Result> { 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 { let mut val = 0; for i in 0..5 { match fs::read_to_string(path) { Ok(s) => { if let Ok(rpm) = s.trim().parse::() { 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) } fn get_freq_mhz(&self) -> Result { let s = fs::read_to_string(&self.freq_path)?; Ok(s.trim().parse::()? / 1000.0) } fn get_throttling_status(&self) -> Result { 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"])?; // 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: 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: 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: 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(()) } } impl HardwareWatchdog for DellXps9380Sal { fn get_safety_status(&self) -> Result { 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) { } }