3 Commits

Author SHA1 Message Date
48c3b46a0c implemented i8kmon formatter 2026-02-26 14:25:41 +01:00
dc4c8281a9 Delete README.md 2026-02-26 14:12:31 +01:00
e27fb3c3ca Delete config/models/dell_inc./xps_13_9380.toml 2026-02-26 14:12:21 +01:00
7 changed files with 187 additions and 199 deletions

View File

@@ -1,87 +0,0 @@
# xps-thermal-bench(8)
## NAME
xps-thermal-bench - Scientific, power-aware thermal optimizer for Dell XPS laptops
## SYNOPSIS
**xps-thermal-bench** [*OPTIONS*]
## DESCRIPTION
**xps-thermal-bench** is a professional diagnostic utility that automates the generation and deployment of optimized **i8kmon(1)** and **throttled** configurations. It uses scientific thermal resistance modeling and real-world throughput benchmarks to find the perfect balance between performance and acoustics for your specific hardware unit.
### Key Scientific Features:
* **Environmental Calibration**: Samples your natural ambient idle temperature at startup to anchor fan curves correctly for your specific session (TTY vs. Desktop).
* **Thermal Resistance ($R_{\theta}$) Modeling**: Calculates the exact cooling efficiency (C/W) of your heatsink to determine sustainable power limits.
* **Thermal Inertia Tracking**: Measures how fast your laptop sheds heat to dynamically tune fan hysteresis, preventing the high-pitched "RPM hunting" common in thin-and-light chassis.
* **Silicon Knee Detection**: Identifies your CPU's unique throttling point by monitoring frequency stability jitter during load.
* **Interactive Deployment**: One-key installation of generated profiles directly to the system with automatic service restarts.
## WORKFLOW
1. **System Audit**: The tool validates your kernel modules (`dell_smm`), power state (AC is required for accuracy), and interfering services.
2. **Calibration**: Captures your current environmental thermal floor.
3. **Benchmarking**: Runs a matrix of loads (25%100%) against every fan tier.
4. **Optimization**: Calculates Quiet, Balanced, and Performance profiles using the gathered telemetry.
5. **Installation**: Press **'i'** in the TUI to deploy your favorite profile and restart services immediately.
## OPTIONS
**-b, --baseline-temp** *CELSIUS*
Target temperature for the cooling phase between tests. Default: 50.
**-c, --critical-temp** *CELSIUS*
Safety ceiling at which a test is aborted. Default: 95.
**-C, --i8kmon-conf** *PATH*
Override the path to the i8kmon configuration. (Default: Auto-discovered via systemd).
**-T, --throttled-conf** *PATH*
Override the path to the throttled configuration. (Default: Auto-discovered via systemd).
**-e, --export-dir** *DIR*
Directory to write generated configurations and backups.
**-f, --history-file** *PATH*
Path to the JSON telemetry database. Default: thermal_history.json.
**-q, --quick**
Fast-track mode (skips intermediate 50% and 75% load tiers).
**-s, --stressor** *STRESSOR*
stress-ng workload type (e.g., `matrixprod`, `avx`, `cpu`, `fft`). Default: matrixprod.
**--no-tui**
Disables the interactive terminal UI for a structured stdout log.
**--skip-checks**
Bypasses the system audit. Use only if you know your hardware is compatible.
**--reprocess** [*HISTORY_JSON*]
Generates new profiles and power limits from existing data without hardware tests.
## KEYBINDS (TUI Mode)
**TAB**
Cycle between Quiet, Balanced, and Performance profile previews.
**i**
**Install** the currently selected profile to the system and restart services.
**q**
Quit and restore original system state (governors, frequencies, services).
## SAFETY & CLEANUP
The tool is designed to be "interruption-safe." Even if the program panics or is killed via `Ctrl+C`, it utilizes the Rust `Drop` trait to ensure:
* Original CPU scaling governors are restored.
* CPU frequency limits are unlocked.
* Background power management services (like `auto-cpufreq` or `tlp`) are restarted.
## SETUP
### Prerequisites
- **Kernel**: `dell_smm_hwmon` must be loaded.
- **Power**: AC adapter must be connected.
- **Dependencies**: `stress-ng`, `i8kmon`, and `throttled`.
### Installation
```bash
cargo build --release
sudo ./target/release/xps-thermal-bench
```
## SEE ALSO
**i8kmon(1)**, **throttled(8)**, **stress-ng(1)**

View File

@@ -1,105 +0,0 @@
[meta]
vendor = "Dell Inc."
family = "XPS"
model = "XPS 13 9380"
[[requirements]]
id = "msr-writes"
name = "MSR Write Access"
check_type = "Cmdline"
target = "msr.allow_writes=on"
action = "Manual"
severity = "Fatal"
message = "Throttled requires MSR write access to bypass TDP locks."
solution = "Add msr.allow_writes=on to kernel parameters."
[[requirements]]
id = "dell-smm-ignore-dmi"
name = "Dell SMM Ignore DMI"
check_type = "Cmdline"
target = "dell_smm_hwmon.ignore_dmi=1"
action = "Manual"
severity = "Fatal"
message = "Required to force load fan control driver on this model."
solution = "Add dell_smm_hwmon.ignore_dmi=1 to kernel parameters."
[[requirements]]
id = "bios-fan-ctrl"
name = "BIOS Fan Control"
check_type = "Service"
target = "dell-bios-fan-control"
invert = true
action = "AutoRestore"
severity = "Warning"
message = "BIOS overrides i8kmon, causing fan pulsing."
solution = "Tool will disable BIOS fan control (0) during run."
[[diagnostics]]
id = "gpe-storm-fix"
name = "Interrupt Storm Fix"
check_type = "Cmdline"
target = "acpi_mask_gpe=0x6E"
action = "Manual"
severity = "Warning"
message = "GPE 0x6E often storms on 9380, wasting 20% CPU."
solution = "Add acpi_mask_gpe=0x6E to kernel parameters."
[[diagnostics]]
id = "s3-sleep"
name = "S3 Deep Sleep"
check_type = "Cmdline"
target = "mem_sleep_default=deep"
action = "Manual"
severity = "Warning"
message = "Modern Standby (s2idle) fails to sleep properly on 9380."
solution = "Add mem_sleep_default=deep to force S3 sleep."
[[diagnostics]]
id = "psr-fix"
name = "Panel Self Refresh Fix"
check_type = "Cmdline"
target = "i915.enable_psr=0"
action = "Manual"
severity = "Warning"
message = "PSR causes screen freezes on 9380."
solution = "Add i915.enable_psr=0 to kernel parameters."
[[diagnostics]]
id = "color-range-fix"
name = "Full RGB Color Range"
check_type = "Cmdline"
target = "i915.color_range=2"
action = "Manual"
severity = "Warning"
message = "Ensures full 0-255 RGB range on external monitors."
solution = "Add i915.color_range=2 to kernel parameters."
[[diagnostics]]
id = "nvme-latency-fix"
name = "NVMe Latency Fix"
check_type = "Cmdline"
target = "nvme_core.default_ps_max_latency_us=5500"
action = "Manual"
severity = "Warning"
message = "Prevents SSD hangs on certain 9380 firmware."
solution = "Add nvme_core.default_ps_max_latency_us=5500 to kernel parameters."
[[diagnostics]]
id = "audio-pop-fix"
name = "Audio Pop Fix"
check_type = "Cmdline"
target = "snd_hda_intel.power_save=0"
action = "Manual"
severity = "Warning"
message = "Prevents 'popping' sound in headphones."
solution = "Add snd_hda_intel.power_save=0 to kernel parameters."
[[diagnostics]]
id = "intel-sgx"
name = "Intel SGX State"
check_type = "File"
target = "/dev/sgx"
action = "Manual"
severity = "Warning"
message = "SGX must be 'Software Controlled' for MSR access."
solution = "Set Intel SGX to 'Software Controlled' in BIOS."

View File

@@ -0,0 +1,41 @@
pub struct I8kmonConfig {
pub t_ambient: f32,
pub t_max_fan: f32,
}
pub struct I8kmonTranslator;
impl I8kmonTranslator {
pub fn generate_conf(config: &I8kmonConfig) -> String {
let t_off = config.t_ambient + 5.0;
let t_low_on = config.t_ambient + 12.0;
let t_low_off = config.t_ambient + 10.0;
let t_high_on = config.t_max_fan;
let t_high_off = config.t_max_fan - 5.0;
let t_low_trigger = (config.t_max_fan - 15.0).max(t_low_on + 2.0);
format!(
r#"# Generated by ember-tune Optimizer
# Grounded in physical thermal resistance
set config(gen_shadow) 1
set config(i8k_ignore_dmi) 1
# Fan states: {{state_low state_high temp_on temp_off}}
set config(0) {{0 0 {t_low_on:.0} {t_off:.0}}}
set config(1) {{1 1 {t_low_trigger:.0} {t_low_off:.0}}}
set config(2) {{2 2 {t_high_on:.0} {t_high_off:.0}}}
# Speed thresholds (approximate for XPS 9380)
set config(speed_low) 2500
set config(speed_high) 4500
"#,
t_low_on = t_low_on,
t_off = t_off,
t_low_trigger = t_low_trigger,
t_low_off = t_low_off,
t_high_on = t_high_on,
t_high_off = t_high_off
)
}
}

View File

@@ -1 +1,2 @@
pub mod throttled; pub mod throttled;
pub mod i8kmon;

View File

@@ -1,3 +1,4 @@
use std::collections::HashSet;
pub struct ThrottledConfig { pub struct ThrottledConfig {
pub pl1_limit: f32, pub pl1_limit: f32,
@@ -11,7 +12,7 @@ impl ThrottledTranslator {
pub fn generate_conf(config: &ThrottledConfig) -> String { pub fn generate_conf(config: &ThrottledConfig) -> String {
format!( format!(
r#"[GENERAL] r#"[GENERAL]
# Generated by FerroTherm Optimizer # Generated by ember-tune Optimizer
# Physical Sweet Spot found at {pl1:.1}W # Physical Sweet Spot found at {pl1:.1}W
[BATTERY] [BATTERY]
@@ -35,4 +36,98 @@ Trip_Temp_C: {trip:.0}
trip = config.trip_temp trip = config.trip_temp
) )
} }
/// Merges benchmarked values into an existing throttled.conf content.
/// Preserves all other sections (like [UnderVOLT]), comments, and formatting.
pub fn merge_conf(existing_content: &str, config: &ThrottledConfig) -> String {
let mut sections = Vec::new();
let mut current_section_name = String::new();
let mut current_section_lines = Vec::new();
// 1. Parse into sections to ensure we only update keys in [BATTERY] and [AC]
for line in existing_content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
if !current_section_lines.is_empty() || !current_section_name.is_empty() {
sections.push((current_section_name.clone(), current_section_lines.clone()));
}
current_section_name = trimmed[1..trimmed.len() - 1].to_string();
current_section_lines = vec![line.to_string()];
} else {
current_section_lines.push(line.to_string());
}
}
sections.push((current_section_name, current_section_lines));
let target_keys = [
("PL1_Tdp_W", format!("{:.0}", config.pl1_limit)),
("PL2_Tdp_W", format!("{:.0}", config.pl2_limit)),
("Trip_Temp_C", format!("{:.0}", config.trip_temp)),
];
let mut result_lines = Vec::new();
let mut handled_sections = HashSet::new();
// 2. Process sections
for (name, mut lines) in sections {
if name == "BATTERY" || name == "AC" {
handled_sections.insert(name.clone());
let mut updated_keys = HashSet::new();
let mut new_lines = Vec::new();
for line in lines {
let mut updated = false;
let trimmed = line.trim();
if !trimmed.starts_with('#') && !trimmed.is_empty() {
if let Some((key, _)) = trimmed.split_once(':') {
let key = key.trim();
for (target_key, new_value) in &target_keys {
if key == *target_key {
if let Some(colon_idx) = line.find(':') {
let prefix = &line[..colon_idx + 1];
let rest = &line[colon_idx + 1..];
let comment = if let Some(hash_idx) = rest.find('#') {
&rest[hash_idx..]
} else {
""
};
new_lines.push(format!("{} {}{}", prefix, new_value, comment));
updated_keys.insert(*target_key);
updated = true;
break;
}
}
}
}
}
if !updated {
new_lines.push(line);
}
}
for (target_key, new_value) in &target_keys {
if !updated_keys.contains(*target_key) {
new_lines.push(format!("{}: {}", target_key, new_value));
}
}
lines = new_lines;
}
result_lines.extend(lines);
}
// 3. Add missing sections if they didn't exist at all
for section_name in &["BATTERY", "AC"] {
if !handled_sections.contains(*section_name) {
result_lines.push(String::new());
result_lines.push(format!("[{}]", section_name));
for (target_key, new_value) in &target_keys {
result_lines.push(format!("{}: {}", target_key, new_value));
}
}
}
result_lines.join("\n")
}
} }

View File

@@ -182,7 +182,7 @@ impl BenchmarkOrchestrator {
// Phase 5: Finalizing // Phase 5: Finalizing
self.phase = BenchmarkPhase::Finalizing; self.phase = BenchmarkPhase::Finalizing;
self.log("Benchmark sequence complete. Generating configuration...")?; self.log("Benchmark sequence complete. Generating configurations...")?;
let config = crate::engine::formatters::throttled::ThrottledConfig { let config = crate::engine::formatters::throttled::ThrottledConfig {
pl1_limit: res.silicon_knee_watts, pl1_limit: res.silicon_knee_watts,
@@ -190,9 +190,25 @@ impl BenchmarkOrchestrator {
trip_temp: res.max_temp_c.max(95.0), trip_temp: res.max_temp_c.max(95.0),
}; };
let conf_content = crate::engine::formatters::throttled::ThrottledTranslator::generate_conf(&config); // 1. Throttled (Merged if exists)
std::fs::write("throttled.conf", conf_content)?; let throttled_path = "throttled.conf";
self.log("✓ Saved 'throttled.conf'.")?; let existing_throttled = std::fs::read_to_string(throttled_path).unwrap_or_default();
let throttled_content = if existing_throttled.is_empty() {
crate::engine::formatters::throttled::ThrottledTranslator::generate_conf(&config)
} else {
crate::engine::formatters::throttled::ThrottledTranslator::merge_conf(&existing_throttled, &config)
};
std::fs::write(throttled_path, throttled_content)?;
self.log("✓ Saved 'throttled.conf' (merged).")?;
// 2. i8kmon
let i8k_config = crate::engine::formatters::i8kmon::I8kmonConfig {
t_ambient: self.profile.ambient_temp,
t_max_fan: res.max_temp_c - 5.0, // Aim to hit max fan before max temp
};
let i8k_content = crate::engine::formatters::i8kmon::I8kmonTranslator::generate_conf(&i8k_config);
std::fs::write("i8kmon.conf", i8k_content)?;
self.log("✓ Saved 'i8kmon.conf'.")?;
self.guard.restore()?; self.guard.restore()?;
self.log("✓ Environment restored.")?; self.log("✓ Environment restored.")?;

View File

@@ -96,7 +96,19 @@ impl PreflightAuditor for DellXps9380Sal {
outcome: if unsafe { libc::getuid() } == 0 { Ok(()) } else { Err(AuditError::RootRequired) } outcome: if unsafe { libc::getuid() } == 0 { Ok(()) } else { Err(AuditError::RootRequired) }
}); });
// 2. Kernel parameters check // 2. Kernel modules check (simplified check via sysfs/proc)
let modules = ["dell_smm_hwmon", "msr", "intel_rapl_msr"];
for mod_name in modules {
let path = format!("/sys/module/{}", mod_name);
steps.push(AuditStep {
description: format!("Kernel Module: {}", mod_name),
outcome: if PathBuf::from(path).exists() { Ok(()) } else {
Err(AuditError::ToolMissing(format!("Module '{}' not loaded. Run 'sudo modprobe {}'", mod_name, mod_name)))
}
});
}
// 3. Kernel parameters check
let cmdline = fs::read_to_string("/proc/cmdline").unwrap_or_default(); let cmdline = fs::read_to_string("/proc/cmdline").unwrap_or_default();
steps.push(AuditStep { steps.push(AuditStep {
description: "Kernel Param: dell_smm_hwmon.ignore_dmi=1".to_string(), description: "Kernel Param: dell_smm_hwmon.ignore_dmi=1".to_string(),
@@ -104,6 +116,12 @@ impl PreflightAuditor for DellXps9380Sal {
Err(AuditError::MissingKernelParam("dell_smm_hwmon.ignore_dmi=1".to_string())) Err(AuditError::MissingKernelParam("dell_smm_hwmon.ignore_dmi=1".to_string()))
} }
}); });
steps.push(AuditStep {
description: "Kernel Param: dell_smm_hwmon.restricted=0".to_string(),
outcome: if cmdline.contains("dell_smm_hwmon.restricted=0") { Ok(()) } else {
Err(AuditError::MissingKernelParam("dell_smm_hwmon.restricted=0".to_string()))
}
});
steps.push(AuditStep { steps.push(AuditStep {
description: "Kernel Param: msr.allow_writes=on".to_string(), description: "Kernel Param: msr.allow_writes=on".to_string(),
outcome: if cmdline.contains("msr.allow_writes=on") { Ok(()) } else { outcome: if cmdline.contains("msr.allow_writes=on") { Ok(()) } else {
@@ -111,7 +129,16 @@ impl PreflightAuditor for DellXps9380Sal {
} }
}); });
// 3. Check AC power // 4. Lockdown check
let lockdown = fs::read_to_string("/sys/kernel/security/lockdown").unwrap_or_default();
steps.push(AuditStep {
description: "Kernel Lockdown Status".to_string(),
outcome: if lockdown.contains("[none]") || lockdown.is_empty() { Ok(()) } else {
Err(AuditError::KernelIncompatible("Kernel is in lockdown mode. Set to 'none' to allow MSR/SMM writes.".to_string()))
}
});
// 5. Check AC power
let ac_status = fs::read_to_string("/sys/class/power_supply/AC/online").unwrap_or_else(|_| "0".to_string()); let ac_status = fs::read_to_string("/sys/class/power_supply/AC/online").unwrap_or_else(|_| "0".to_string());
steps.push(AuditStep { steps.push(AuditStep {
description: "AC Power Connection".to_string(), description: "AC Power Connection".to_string(),