// SPDX-License-Identifier: MIT //! Active fan-to-thermal-zone mapping. //! //! Antminer chassis wire fans to zones in a way that is not reported by the hardware: a fan may //! cool one hashboard heavily and another barely, and the front/back, top/bottom labels are //! physical. The mapping is learned by stepping one fan at a time and watching which zone's //! temperature responds, which is why this module takes measurements rather than configuration. use crate::detect::FanZone; /// One sensor reading taken while a fan was held at a given duty. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ZoneReading { pub zone: u8, pub temp_mc: i32, } /// One measurement step: a fan duty and the temperatures observed during it. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ProbeSample { pub fan: u8, pub pwm: u8, pub readings: Vec, } /// Thresholds that decide when a response is real. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct MapThresholds { /// Minimum cooling (millidegrees) between the low and high duty to count as a response. pub min_drop_mc: i32, /// Minimum margin over the next-best fan, in parts per thousand of the best response. pub min_margin_per_mille: u16, } impl Default for MapThresholds { fn default() -> Self { Self { min_drop_mc: 500, min_margin_per_mille: 250, } } } /// The learned mapping. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct FanMap { pub assignments: Vec, /// Zones whose response was ambiguous and were therefore left unassigned. pub unresolved: Vec, /// Per assigned zone, the margin over the runner-up in parts per thousand. pub confidence_per_mille: Vec, } impl FanMap { /// Zones a fan was confidently assigned to. pub fn zones_for(&self, fan: u8) -> Vec { self.assignments .iter() .find(|assignment| assignment.fan == fan) .map(|assignment| assignment.zones.clone()) .unwrap_or_default() } } /// Response per (fan, zone): positive means the zone cooled when that fan sped up. fn responses(samples: &[ProbeSample], zones: &[u8]) -> Vec<(u8, Vec<(u8, i32)>)> { let mut fans: Vec = samples.iter().map(|sample| sample.fan).collect(); fans.sort_unstable(); fans.dedup(); let mut out = Vec::new(); for fan in fans { let fan_samples: Vec<&ProbeSample> = samples.iter().filter(|sample| sample.fan == fan).collect(); let min_pwm = fan_samples.iter().map(|sample| sample.pwm).min(); let max_pwm = fan_samples.iter().map(|sample| sample.pwm).max(); let (Some(low), Some(high)) = (min_pwm, max_pwm) else { continue; }; if low == high { continue; } let mut per_zone = Vec::with_capacity(zones.len()); for &zone in zones { let mean_at = |pwm: u8| -> Option { let values: Vec = fan_samples .iter() .filter(|sample| sample.pwm == pwm) .flat_map(|sample| { sample .readings .iter() .filter(|reading| reading.zone == zone) .map(|reading| reading.temp_mc) }) .collect(); if values.is_empty() { return None; } let sum: i64 = values.iter().map(|value| *value as i64).sum(); Some((sum / values.len() as i64) as i32) }; // Duty goes up, temperature should come down: response = warm-run minus fast-run. if let (Some(slow_temp), Some(fast_temp)) = (mean_at(low), mean_at(high)) { per_zone.push((zone, slow_temp - fast_temp)); } } out.push((fan, per_zone)); } out } /// Learn which fans cool which zones from a stepped measurement run. /// /// Every zone goes to the fan with the strongest cooling response, provided that response clears /// `min_drop_mc` and beats the runner-up by `min_margin_per_mille`. Anything weaker stays /// unresolved instead of being guessed, so a noisy run cannot invent a fan map. pub fn map_fans(samples: &[ProbeSample], zones: &[u8], thresholds: MapThresholds) -> FanMap { let responses = responses(samples, zones); let mut map = FanMap::default(); for &zone in zones { let mut ranked: Vec<(i32, u8)> = responses .iter() .filter_map(|(fan, per_zone)| { per_zone .iter() .find(|(candidate, _)| *candidate == zone) .map(|(_, drop)| (*drop, *fan)) }) .collect(); ranked.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.0)); let Some(&(best_drop, best_fan)) = ranked.first() else { map.unresolved.push(zone); continue; }; let runner_up = ranked.get(1).map(|(drop, _)| *drop).unwrap_or(0); let margin = best_drop - runner_up.max(0); let margin_per_mille = if best_drop > 0 { ((margin as i64 * 1000) / best_drop as i64) as u16 } else { 0 }; if best_drop < thresholds.min_drop_mc || margin_per_mille < thresholds.min_margin_per_mille { map.unresolved.push(zone); continue; } match map .assignments .iter_mut() .find(|assignment| assignment.fan == best_fan) { Some(assignment) => assignment.zones.push(zone), None => map.assignments.push(FanZone { fan: best_fan, zones: vec![zone], }), } map.confidence_per_mille.push(margin_per_mille); } map } /// Safe limits for a fan-mapping sweep. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct SweepConfig { pub fans: u8, pub zones: u8, /// Lowest duty used during probing. Never zero: the boards must keep airflow. pub low_pwm: u8, pub high_pwm: u8, /// Readings taken per (fan, duty) step; the mapper averages them. pub repeats: u8, /// Time to wait after a duty change before reading temperatures. pub settle_ms: u32, } impl Default for SweepConfig { fn default() -> Self { Self { fans: 4, zones: 3, low_pwm: 40, high_pwm: 100, repeats: 2, settle_ms: 20_000, } } } /// Minimum duty a sweep may use. Airflow is never removed to make a measurement. pub const MIN_PROBE_PWM: u8 = 20; /// Why a sweep did not run. #[derive(Clone, Debug, Eq, PartialEq)] pub enum SweepError { Backend(E), InvalidConfig(&'static str), } /// The two backend actions a sweep needs. pub trait FanProbe { type Error; fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error>; fn read_zone(&mut self, zone: u8) -> Result; } /// Step every fan between the low and high duty and record what the zones do. /// /// One fan is moved at a time while the others hold their previous duty, so the response belongs /// to that fan. The run ends with every fan back at `high_pwm`: leaving a fan low after probing /// would be a thermal hazard for whatever runs next. pub fn sweep( backend: &mut B, config: &SweepConfig, mut settle: S, ) -> Result, SweepError> { if config.fans == 0 { return Err(SweepError::InvalidConfig("no fans to sweep")); } if config.zones == 0 { return Err(SweepError::InvalidConfig("no zones to read")); } if config.low_pwm < MIN_PROBE_PWM { return Err(SweepError::InvalidConfig( "probe duty below the safe minimum", )); } if config.high_pwm > 100 { return Err(SweepError::InvalidConfig("probe duty above 100 percent")); } if config.low_pwm >= config.high_pwm { return Err(SweepError::InvalidConfig("probe duty range is empty")); } if config.repeats == 0 { return Err(SweepError::InvalidConfig("no readings requested")); } let mut samples = Vec::new(); for fan in 0..config.fans { for pwm in [config.low_pwm, config.high_pwm] { backend.set_fan(fan, pwm).map_err(SweepError::Backend)?; settle(config.settle_ms); for _ in 0..config.repeats { let mut readings = Vec::with_capacity(config.zones as usize); for zone in 0..config.zones { readings.push(ZoneReading { zone, temp_mc: backend.read_zone(zone).map_err(SweepError::Backend)?, }); } samples.push(ProbeSample { fan, pwm, readings }); } } } for fan in 0..config.fans { backend .set_fan(fan, config.high_pwm) .map_err(SweepError::Backend)?; } Ok(samples) } #[cfg(test)] mod tests { use super::*; fn sample(fan: u8, pwm: u8, zone_temps: &[(u8, i32)]) -> ProbeSample { ProbeSample { fan, pwm, readings: zone_temps .iter() .map(|(zone, temp)| ZoneReading { zone: *zone, temp_mc: *temp, }) .collect(), } } #[test] fn each_zone_is_assigned_to_the_fan_that_cools_it() { let samples = vec![ sample(0, 30, &[(0, 70_000), (1, 60_000)]), sample(0, 100, &[(0, 50_000), (1, 59_000)]), sample(1, 30, &[(0, 69_000), (1, 60_000)]), sample(1, 100, &[(0, 68_000), (1, 40_000)]), ]; let map = map_fans(&samples, &[0, 1], MapThresholds::default()); assert_eq!(map.zones_for(0), vec![0]); assert_eq!(map.zones_for(1), vec![1]); assert!(map.unresolved.is_empty()); } #[test] fn ambiguity_leaves_a_zone_unresolved() { let samples = vec![ sample(0, 30, &[(0, 70_000)]), sample(0, 100, &[(0, 60_000)]), sample(1, 30, &[(0, 70_500)]), sample(1, 100, &[(0, 60_500)]), ]; let map = map_fans(&samples, &[0], MapThresholds::default()); assert!(map.assignments.is_empty()); assert_eq!(map.unresolved, vec![0]); } #[test] fn a_fan_that_does_not_change_temperature_is_not_assigned() { let samples = vec![ sample(0, 30, &[(0, 60_000)]), sample(0, 100, &[(0, 59_900)]), ]; let map = map_fans(&samples, &[0], MapThresholds::default()); assert!(map.assignments.is_empty()); assert_eq!(map.unresolved, vec![0]); } #[test] fn a_fan_without_duty_range_is_skipped() { let samples = vec![sample(0, 50, &[(0, 60_000)]), sample(0, 50, &[(0, 60_000)])]; let map = map_fans(&samples, &[0], MapThresholds::default()); assert!(map.assignments.is_empty()); assert_eq!(map.unresolved, vec![0]); } #[test] fn one_fan_can_own_several_zones() { let samples = vec![ sample(0, 30, &[(0, 70_000), (1, 71_000), (2, 55_000)]), sample(0, 100, &[(0, 55_000), (1, 56_000), (2, 54_000)]), sample(1, 30, &[(0, 70_000), (1, 71_000), (2, 54_000)]), sample(1, 100, &[(0, 69_000), (1, 70_000), (2, 50_000)]), ]; let map = map_fans(&samples, &[0, 1, 2], MapThresholds::default()); assert_eq!(map.zones_for(0), vec![0, 1]); assert_eq!(map.zones_for(1), vec![2]); } struct ThermalMock { duty: Vec, owners: Vec<(u8, u8)>, fail: bool, } impl ThermalMock { fn new(owners: &[(u8, u8)]) -> Self { let fans = owners.iter().map(|(fan, _)| *fan).max().unwrap_or(0) + 1; Self { duty: vec![100; fans as usize], owners: owners.to_vec(), fail: false, } } } impl FanProbe for ThermalMock { type Error = &'static str; fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> { if self.fail { return Err("fan bus down"); } self.duty[fan as usize] = pwm; Ok(()) } fn read_zone(&mut self, zone: u8) -> Result { if self.fail { return Err("sensor bus down"); } let owner = self .owners .iter() .find(|(_, candidate)| *candidate == zone) .map(|(fan, _)| *fan) .expect("zone has an owner"); let cooled = self.duty[owner as usize] >= 100; Ok(if cooled { 50_000 } else { 70_000 }) } } #[test] fn sweep_then_map_resolves_each_zone() { let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); let config = SweepConfig { fans: 2, zones: 2, low_pwm: 40, high_pwm: 100, repeats: 2, settle_ms: 0, }; let samples = sweep(&mut backend, &config, |_| {}).expect("sweep"); assert_eq!(samples.len(), 2 * 2 * 2); let map = map_fans(&samples, &[0, 1], MapThresholds::default()); assert_eq!(map.zones_for(0), vec![0]); assert_eq!(map.zones_for(1), vec![1]); assert!(map.unresolved.is_empty()); } #[test] fn sweep_restores_every_fan_to_high_duty() { let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); let config = SweepConfig { fans: 2, zones: 2, low_pwm: 40, high_pwm: 100, repeats: 1, settle_ms: 0, }; sweep(&mut backend, &config, |_| {}).expect("sweep"); assert_eq!(backend.duty, vec![100, 100]); } #[test] fn sweep_refuses_an_unsafe_duty() { let mut backend = ThermalMock::new(&[(0, 0)]); let config = SweepConfig { fans: 1, zones: 1, low_pwm: 10, high_pwm: 100, repeats: 1, settle_ms: 0, }; assert_eq!( sweep(&mut backend, &config, |_| {}), Err(SweepError::InvalidConfig( "probe duty below the safe minimum" )) ); } #[test] fn sweep_refuses_an_empty_range_and_zero_reads() { let mut backend = ThermalMock::new(&[(0, 0)]); let flat = SweepConfig { fans: 1, zones: 1, low_pwm: 60, high_pwm: 60, repeats: 1, settle_ms: 0, }; assert!(matches!( sweep(&mut backend, &flat, |_| {}), Err(SweepError::InvalidConfig(_)) )); let no_reads = SweepConfig { repeats: 0, ..flat }; assert!(matches!( sweep(&mut backend, &no_reads, |_| {}), Err(SweepError::InvalidConfig(_)) )); } #[test] fn sweep_propagates_backend_failures() { let mut backend = ThermalMock::new(&[(0, 0)]); backend.fail = true; let config = SweepConfig::default(); assert_eq!( sweep(&mut backend, &config, |_| {}), Err(SweepError::Backend("fan bus down")) ); } }