// SPDX-License-Identifier: MIT //! Hardware detection model. //! //! The detection core decides what is physically attached to a control board and whether that //! combination is safe to run. It never talks to a chain directly; backends report what they //! probed, and this module turns that into a `HardwarePlan` the miner can execute. //! //! Identification deliberately does not require a hashboard EEPROM. The EEPROM, when present and //! valid, confirms a board revision; a chain probe alone is enough to select a chip profile. /// Chip families the detection core can name. `Unknown` is a real answer, not a placeholder. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ChipModel { Bm1362, Bm1366, Bm1368, Bm1370, Bm1398, Unknown, } impl ChipModel { /// Stable wire/API name for this chip family. pub fn name(self) -> &'static str { match self { Self::Bm1362 => "bm1362", Self::Bm1366 => "bm1366", Self::Bm1368 => "bm1368", Self::Bm1370 => "bm1370", Self::Bm1398 => "bm1398", Self::Unknown => "unknown", } } } /// How a chain reports temperature. PIC boards proxy telemetry through the power MCU. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SensorTopology { Pic, NoPic, Unknown, } /// State of a hashboard EEPROM. Absence is normal and must never block detection. #[derive(Clone, Debug, Eq, PartialEq)] pub enum EepromState { Present { model: String }, Absent, Invalid, } /// What a backend observed on one physical chain. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ChainReport { pub index: u8, pub chip: ChipModel, pub chips_found: u16, pub eeprom: EepromState, /// Nonce responses per mille of dispatched work, when the backend could measure it. pub response_per_mille: Option, } impl ChainReport { pub fn is_identified(&self) -> bool { self.chip != ChipModel::Unknown && self.chips_found > 0 } } /// Safe operating envelope for one hashboard/chip profile, from the profile database. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Envelope { pub v_min_mv: u16, pub v_max_mv: u16, pub f_min_mhz: u16, pub f_max_mhz: u16, } impl Envelope { /// Voltage that pairs with a frequency across this envelope. /// /// Voltage follows frequency linearly between the profile's floor and ceiling and is clamped /// outside it. Boards do not run at a fixed voltage across their frequency range, so reporting /// one voltage while the frequency moves would describe a machine that does not exist. pub fn voltage_for(self, frequency_mhz: u16) -> u16 { if frequency_mhz <= self.f_min_mhz { return self.v_min_mv; } if frequency_mhz >= self.f_max_mhz { return self.v_max_mv; } let span_f = u32::from(self.f_max_mhz - self.f_min_mhz); let span_v = u32::from(self.v_max_mv - self.v_min_mv); let offset = u32::from(frequency_mhz - self.f_min_mhz); let voltage = u32::from(self.v_min_mv) + (span_v * offset) / span_f; voltage.min(u32::from(u16::MAX)) as u16 } pub fn intersect(self, other: Envelope) -> Option { let v_min_mv = self.v_min_mv.max(other.v_min_mv); let v_max_mv = self.v_max_mv.min(other.v_max_mv); let f_min_mhz = self.f_min_mhz.max(other.f_min_mhz); let f_max_mhz = self.f_max_mhz.min(other.f_max_mhz); if v_min_mv > v_max_mv || f_min_mhz > f_max_mhz { return None; } Some(Envelope { v_min_mv, v_max_mv, f_min_mhz, f_max_mhz, }) } } /// A hashboard profile from the database. #[derive(Clone, Debug, Eq, PartialEq)] pub struct BoardProfile { pub name: String, pub chip: ChipModel, pub sensor: SensorTopology, pub chains: u8, pub envelope: Envelope, } /// What the PSU reports about itself and what it can deliver. #[derive(Clone, Debug, Eq, PartialEq)] pub struct PsuCapability { pub name: String, pub envelope: Envelope, pub max_dc_watts: u16, } /// Which fans cool which thermal zones, learned by active probing. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FanZone { pub fan: u8, pub zones: Vec, } /// Why detection refused a combination. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DetectionError { NoChains, UnknownChip, ChipProfileMismatch, PsuUnidentified, EnvelopeEmpty, } /// Operating point chosen for the machine. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct OperatingPoint { pub voltage_mv: u16, pub frequency_mhz: u16, /// True when the profile was confirmed by an EEPROM or a full chain identification. pub confirmed: bool, } /// The result of detection: everything the miner needs and nothing it has to guess. #[derive(Clone, Debug, Eq, PartialEq)] pub struct HardwarePlan { pub profile: String, pub chip: ChipModel, pub chains: Vec, pub envelope: Envelope, pub operating_point: OperatingPoint, pub psu: String, pub fan_zones: Vec, } impl HardwarePlan { /// Chains that identified but reported no nonces, or fewer than expected chips. pub fn degraded_chains(&self, expected: u16) -> Vec { self.chains .iter() .filter(|chain| { chain.chips_found < expected || chain.response_per_mille.is_some_and(|ratio| ratio == 0) }) .map(|chain| chain.index) .collect() } } /// Turn observations into a plan, or refuse. /// /// Refusal is a feature: an unverified or out-of-envelope combination must not mine silently. pub fn plan( chains: &[ChainReport], profile: &BoardProfile, psu: Option<&PsuCapability>, fan_zones: Vec, ) -> Result { if chains.is_empty() { return Err(DetectionError::NoChains); } if chains.iter().all(|chain| chain.chip == ChipModel::Unknown) { return Err(DetectionError::UnknownChip); } if chains .iter() .filter(|chain| chain.is_identified()) .any(|chain| chain.chip != profile.chip) { return Err(DetectionError::ChipProfileMismatch); } let psu = psu.ok_or(DetectionError::PsuUnidentified)?; let envelope = profile .envelope .intersect(psu.envelope) .ok_or(DetectionError::EnvelopeEmpty)?; let confirmed = chains .iter() .any(|chain| matches!(chain.eeprom, EepromState::Present { .. })) && chains.iter().all(ChainReport::is_identified); let operating_point = if confirmed { OperatingPoint { voltage_mv: envelope.v_max_mv.min(profile.envelope.v_max_mv), frequency_mhz: envelope.f_max_mhz.min(profile.envelope.f_max_mhz), confirmed: true, } } else { // Unverified hardware runs at the conservative floor of the usable envelope. OperatingPoint { voltage_mv: envelope.v_min_mv, frequency_mhz: envelope.f_min_mhz, confirmed: false, } }; Ok(HardwarePlan { profile: profile.name.clone(), chip: profile.chip, chains: chains.to_vec(), envelope, operating_point, psu: psu.name.clone(), fan_zones, }) } /// Outcome of one chip-identification attempt on a chain. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ProbeOutcome { /// Chips answered: the model and how many responded. Identified { chip: ChipModel, chips: u16 }, /// The port is electrically silent (no signal at all). Silent, /// Bytes arrived but did not frame as a chip response: wrong baud, noise, or a dead TX. Garbled, } /// Backend contract for identification. /// /// Framing, baud switching and electrical detail stay in the SDK image for that family; the OS /// only decides how many attempts to spend and what the results mean. pub trait DetectionBackend { type Error; /// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate /// interface/baud set deterministically. A transport failure is an error, never `Silent`. fn probe(&mut self, chain: u8, attempt: u8) -> Result; /// Read the hashboard EEPROM, or report that it is absent or unreadable. fn eeprom(&mut self, chain: u8) -> Result; /// Identify the PSU, if this backend can. `None` means "cannot tell", which refuses later. fn identify_psu(&mut self) -> Result, Self::Error>; } /// How many identification attempts to spend per chain before declaring it unidentified. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ProbeBudget { pub attempts: u8, } impl Default for ProbeBudget { fn default() -> Self { Self { attempts: 4 } } } /// Probe one chain until it identifies or the budget is spent. /// /// A chain that never identifies is reported as `ChipModel::Unknown` with zero chips rather than /// being dropped, so the plan can refuse explicitly and the API can show why. pub fn probe_chain( backend: &mut B, chain: u8, budget: ProbeBudget, ) -> Result { let mut outcome = ProbeOutcome::Silent; for attempt in 0..budget.attempts.max(1) { outcome = backend.probe(chain, attempt)?; if matches!(outcome, ProbeOutcome::Identified { .. }) { break; } } let (chip, chips_found) = match outcome { ProbeOutcome::Identified { chip, chips } => (chip, chips), _ => (ChipModel::Unknown, 0), }; Ok(ChainReport { index: chain, chip, chips_found, eeprom: backend.eeprom(chain)?, response_per_mille: None, }) } /// Probe every declared chain port. pub fn detect_chains( backend: &mut B, chains: &[u8], budget: ProbeBudget, ) -> Result, B::Error> { let mut reports = Vec::with_capacity(chains.len()); for &chain in chains { reports.push(probe_chain(backend, chain, budget)?); } Ok(reports) } /// Everything the caller knows before probing: which ports exist, how hard to try, and how the /// hashboards report temperature. #[derive(Clone, Debug, Eq, PartialEq)] pub struct DetectionRequest<'a> { pub chain_ports: &'a [u8], pub budget: ProbeBudget, pub sensor: SensorTopology, pub fan_zones: Vec, } /// Why a detection run did not produce a plan. #[derive(Clone, Debug, Eq, PartialEq)] pub enum DetectionFailure { Backend(E), Refused(DetectionError), NoProfile, } /// Detect, select a profile, and decide whether the machine may run. /// /// The profile is selected by chip, sensor wiring and the number of physical chain ports, so a /// machine with a dead chain still matches its profile and runs degraded instead of being /// reclassified as a different model. pub fn run_detection( backend: &mut B, db: &crate::profiles::ProfileDb, request: &DetectionRequest<'_>, ) -> Result> { let reports = detect_chains(backend, request.chain_ports, request.budget) .map_err(DetectionFailure::Backend)?; let chip = reports .iter() .find(|report| report.is_identified()) .map(|report| report.chip) .ok_or(DetectionFailure::Refused(DetectionError::UnknownChip))?; let chains = u8::try_from(request.chain_ports.len()).unwrap_or(u8::MAX); let profile = db .find(chip, chains, request.sensor) .ok_or(DetectionFailure::NoProfile)?; let psu = backend.identify_psu().map_err(DetectionFailure::Backend)?; plan(&reports, profile, psu.as_ref(), request.fan_zones.clone()) .map_err(DetectionFailure::Refused) } #[cfg(test)] mod tests { use super::*; fn profile() -> BoardProfile { BoardProfile { name: "s19jpro-bm1362".into(), chip: ChipModel::Bm1362, sensor: SensorTopology::Pic, chains: 3, envelope: Envelope { v_min_mv: 1100, v_max_mv: 1500, f_min_mhz: 300, f_max_mhz: 700, }, } } fn psu() -> PsuCapability { PsuCapability { name: "APW12".into(), envelope: Envelope { v_min_mv: 1200, v_max_mv: 1600, f_min_mhz: 0, f_max_mhz: 1000, }, max_dc_watts: 3600, } } fn chain(index: u8, eeprom: EepromState) -> ChainReport { ChainReport { index, chip: ChipModel::Bm1362, chips_found: 126, eeprom, response_per_mille: Some(980), } } #[test] fn confirmed_plan_uses_verified_ceiling() { let chains = [chain( 0, EepromState::Present { model: "BHB42601".into(), }, )]; let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); assert!(plan.operating_point.confirmed); assert_eq!(plan.operating_point.voltage_mv, 1500); assert_eq!(plan.operating_point.frequency_mhz, 700); assert_eq!(plan.envelope.v_min_mv, 1200); } #[test] fn absent_eeprom_still_yields_a_conservative_plan() { let chains = [chain(0, EepromState::Absent)]; let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); assert!(!plan.operating_point.confirmed); assert_eq!(plan.operating_point.voltage_mv, plan.envelope.v_min_mv); assert_eq!(plan.operating_point.frequency_mhz, plan.envelope.f_min_mhz); } #[test] fn unknown_chip_refuses() { let mut chains = [chain(0, EepromState::Absent)]; chains[0].chip = ChipModel::Unknown; assert_eq!( plan(&chains, &profile(), Some(&psu()), Vec::new()), Err(DetectionError::UnknownChip) ); } #[test] fn wrong_chip_refuses() { let mut chains = [chain(0, EepromState::Absent)]; chains[0].chip = ChipModel::Bm1366; assert_eq!( plan(&chains, &profile(), Some(&psu()), Vec::new()), Err(DetectionError::ChipProfileMismatch) ); } #[test] fn missing_psu_refuses() { let chains = [chain(0, EepromState::Absent)]; assert_eq!( plan(&chains, &profile(), None, Vec::new()), Err(DetectionError::PsuUnidentified) ); } #[test] fn incompatible_psu_refuses() { let chains = [chain(0, EepromState::Absent)]; let weak = PsuCapability { name: "APW3".into(), envelope: Envelope { v_min_mv: 700, v_max_mv: 1090, f_min_mhz: 0, f_max_mhz: 1000, }, max_dc_watts: 1600, }; assert_eq!( plan(&chains, &profile(), Some(&weak), Vec::new()), Err(DetectionError::EnvelopeEmpty) ); } #[test] fn empty_chain_set_refuses() { assert_eq!( plan(&[], &profile(), Some(&psu()), Vec::new()), Err(DetectionError::NoChains) ); } #[test] fn degraded_chains_are_reported_not_fatal() { let mut silent = chain(1, EepromState::Absent); silent.response_per_mille = Some(0); let chains = [chain(0, EepromState::Absent), silent]; let plan = plan(&chains, &profile(), Some(&psu()), Vec::new()).expect("plan"); assert_eq!(plan.degraded_chains(126), vec![1]); } #[test] fn fan_zones_are_carried_into_the_plan() { let chains = [chain(0, EepromState::Absent)]; let zones = vec![FanZone { fan: 0, zones: vec![0, 1], }]; let plan = plan(&chains, &profile(), Some(&psu()), zones.clone()).expect("plan"); assert_eq!(plan.fan_zones, zones); } struct ScriptedProbe { plan: std::collections::VecDeque, eeprom: EepromState, calls: usize, fail_at: u8, psu: Option, } impl ScriptedProbe { fn new(plan: &[ProbeOutcome], eeprom: EepromState) -> Self { Self { plan: plan.iter().copied().collect(), eeprom, calls: 0, fail_at: u8::MAX, psu: Some(psu()), } } } impl DetectionBackend for ScriptedProbe { type Error = (); fn probe(&mut self, _chain: u8, attempt: u8) -> Result { self.calls += 1; if attempt == self.fail_at { return Err(()); } Ok(self.plan.pop_front().unwrap_or(ProbeOutcome::Silent)) } fn eeprom(&mut self, _chain: u8) -> Result { Ok(self.eeprom.clone()) } fn identify_psu(&mut self) -> Result, ()> { Ok(self.psu.clone()) } } #[test] fn probe_retries_until_the_chain_identifies() { let mut backend = ScriptedProbe::new( &[ ProbeOutcome::Silent, ProbeOutcome::Garbled, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ], EepromState::Absent, ); let report = probe_chain(&mut backend, 0, ProbeBudget { attempts: 4 }).expect("probe"); assert_eq!(backend.calls, 3); assert_eq!(report.chip, ChipModel::Bm1362); assert_eq!(report.chips_found, 126); assert!(report.is_identified()); } #[test] fn probe_exhaustion_is_reported_not_hidden() { let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); let report = probe_chain(&mut backend, 1, ProbeBudget { attempts: 4 }).expect("probe"); assert_eq!(backend.calls, 4); assert_eq!(report.chip, ChipModel::Unknown); assert_eq!(report.chips_found, 0); assert!(!report.is_identified()); } #[test] fn probe_keeps_the_eeprom_state_even_when_unidentified() { let mut backend = ScriptedProbe::new( &[ProbeOutcome::Garbled; 2], EepromState::Present { model: "BHB42601".into(), }, ); let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 }).expect("probe"); assert_eq!(report.chip, ChipModel::Unknown); assert_eq!( report.eeprom, EepromState::Present { model: "BHB42601".into() } ); } #[test] fn detection_covers_every_declared_chain_port() { let mut backend = ScriptedProbe::new( &[ ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ], EepromState::Absent, ); let reports = detect_chains(&mut backend, &[0, 1, 2], ProbeBudget::default()).expect("detect"); assert_eq!(reports.len(), 3); assert_eq!( reports.iter().map(|r| r.index).collect::>(), vec![0, 1, 2] ); assert!(reports.iter().all(ChainReport::is_identified)); } #[test] fn transport_failure_is_not_reported_as_a_silent_port() { let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); backend.fail_at = 1; assert_eq!( probe_chain(&mut backend, 0, ProbeBudget::default()), Err(()) ); assert_eq!(backend.calls, 2); } #[test] fn unidentified_chain_makes_the_plan_refuse() { let mut backend = ScriptedProbe::new(&[ProbeOutcome::Silent; 4], EepromState::Absent); let reports = detect_chains(&mut backend, &[0], ProbeBudget::default()).expect("detect"); assert_eq!( plan(&reports, &profile(), Some(&psu()), Vec::new()), Err(DetectionError::UnknownChip) ); } fn db() -> crate::profiles::ProfileDb { crate::profiles::ProfileDb::new(vec![profile()]).expect("db") } #[test] fn run_detection_emits_a_plan_end_to_end() { let mut backend = ScriptedProbe::new( &[ ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ], EepromState::Absent, ); let request = DetectionRequest { chain_ports: &[0, 1, 2], budget: ProbeBudget::default(), sensor: SensorTopology::Pic, fan_zones: vec![FanZone { fan: 0, zones: vec![0], }], }; let plan = run_detection(&mut backend, &db(), &request).expect("plan"); assert_eq!(plan.chains.len(), 3); assert_eq!(plan.psu, "APW12"); assert!(!plan.operating_point.confirmed); assert_eq!(plan.operating_point.voltage_mv, 1200); } #[test] fn run_detection_refuses_when_no_profile_matches() { let mut backend = ScriptedProbe::new( &[ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }], EepromState::Absent, ); let request = DetectionRequest { chain_ports: &[0], budget: ProbeBudget::default(), sensor: SensorTopology::Pic, fan_zones: Vec::new(), }; assert_eq!( run_detection(&mut backend, &db(), &request), Err(DetectionFailure::NoProfile) ); } #[test] fn run_detection_runs_degraded_with_a_dead_chain() { let mut backend = ScriptedProbe::new( &[ ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, ProbeOutcome::Silent, ProbeOutcome::Silent, ProbeOutcome::Silent, ProbeOutcome::Silent, ], EepromState::Absent, ); let request = DetectionRequest { chain_ports: &[0, 1, 2], budget: ProbeBudget::default(), sensor: SensorTopology::Pic, fan_zones: Vec::new(), }; let plan = run_detection(&mut backend, &db(), &request).expect("plan"); assert_eq!(plan.degraded_chains(126), vec![2]); } #[test] fn voltage_follows_frequency_and_clamps_outside_the_envelope() { let envelope = Envelope { v_min_mv: 1100, v_max_mv: 1500, f_min_mhz: 300, f_max_mhz: 700, }; assert_eq!(envelope.voltage_for(200), 1100); assert_eq!(envelope.voltage_for(300), 1100); assert_eq!(envelope.voltage_for(500), 1300); assert_eq!(envelope.voltage_for(700), 1500); assert_eq!(envelope.voltage_for(900), 1500); } #[test] fn a_single_frequency_envelope_reports_its_floor() { let envelope = Envelope { v_min_mv: 1200, v_max_mv: 1400, f_min_mhz: 500, f_max_mhz: 500, }; assert_eq!(envelope.voltage_for(500), 1200); assert_eq!(envelope.voltage_for(600), 1400); } }