Carry detection verbs over the HAL wire contract
source-pr / source (pull_request) Successful in 12s
source-pr / source (pull_request) Successful in 12s
Add capability negotiation and three detection verbs to the local HAL contract: CAPABILITIES, PROBE_CHAIN, READ_EEPROM and IDENTIFY_PSU. A backend that predates them rejects the capability query, which surfaces as a protocol error instead of a silent zero. HalClient implements ChainProbe, so the OS detection driver can run against a real board without knowing the family. The probe contract is now error-aware: a transport failure propagates as an error and is never reported as a silent port, and probe_chain/detect_chains are generic over the backend. A wire round-trip test drives a mock backend over a socket pair and checks the encoding of all three verbs.
This commit is contained in:
+50
-24
@@ -217,11 +217,13 @@ pub enum ProbeOutcome {
|
||||
/// 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 ChainProbe {
|
||||
type Error;
|
||||
|
||||
/// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate
|
||||
/// interface/baud set deterministically.
|
||||
fn probe(&mut self, chain: u8, attempt: u8) -> ProbeOutcome;
|
||||
/// interface/baud set deterministically. A transport failure is an error, never `Silent`.
|
||||
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error>;
|
||||
/// Read the hashboard EEPROM, or report that it is absent or unreadable.
|
||||
fn eeprom(&mut self, chain: u8) -> EepromState;
|
||||
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error>;
|
||||
}
|
||||
|
||||
/// How many identification attempts to spend per chain before declaring it unidentified.
|
||||
@@ -240,10 +242,14 @@ impl Default for ProbeBudget {
|
||||
///
|
||||
/// 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 impl ChainProbe, chain: u8, budget: ProbeBudget) -> ChainReport {
|
||||
pub fn probe_chain<B: ChainProbe>(
|
||||
backend: &mut B,
|
||||
chain: u8,
|
||||
budget: ProbeBudget,
|
||||
) -> Result<ChainReport, B::Error> {
|
||||
let mut outcome = ProbeOutcome::Silent;
|
||||
for attempt in 0..budget.attempts.max(1) {
|
||||
outcome = backend.probe(chain, attempt);
|
||||
outcome = backend.probe(chain, attempt)?;
|
||||
if matches!(outcome, ProbeOutcome::Identified { .. }) {
|
||||
break;
|
||||
}
|
||||
@@ -252,25 +258,26 @@ pub fn probe_chain(backend: &mut impl ChainProbe, chain: u8, budget: ProbeBudget
|
||||
ProbeOutcome::Identified { chip, chips } => (chip, chips),
|
||||
_ => (ChipModel::Unknown, 0),
|
||||
};
|
||||
ChainReport {
|
||||
Ok(ChainReport {
|
||||
index: chain,
|
||||
chip,
|
||||
chips_found,
|
||||
eeprom: backend.eeprom(chain),
|
||||
eeprom: backend.eeprom(chain)?,
|
||||
response_per_mille: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Probe every declared chain port.
|
||||
pub fn detect_chains(
|
||||
backend: &mut impl ChainProbe,
|
||||
pub fn detect_chains<B: ChainProbe>(
|
||||
backend: &mut B,
|
||||
chains: &[u8],
|
||||
budget: ProbeBudget,
|
||||
) -> Vec<ChainReport> {
|
||||
chains
|
||||
.iter()
|
||||
.map(|&chain| probe_chain(backend, chain, budget))
|
||||
.collect()
|
||||
) -> Result<Vec<ChainReport>, B::Error> {
|
||||
let mut reports = Vec::with_capacity(chains.len());
|
||||
for &chain in chains {
|
||||
reports.push(probe_chain(backend, chain, budget)?);
|
||||
}
|
||||
Ok(reports)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -419,6 +426,7 @@ mod tests {
|
||||
plan: std::collections::VecDeque<ProbeOutcome>,
|
||||
eeprom: EepromState,
|
||||
calls: usize,
|
||||
fail_at: u8,
|
||||
}
|
||||
|
||||
impl ScriptedProbe {
|
||||
@@ -427,18 +435,24 @@ mod tests {
|
||||
plan: plan.iter().copied().collect(),
|
||||
eeprom,
|
||||
calls: 0,
|
||||
fail_at: u8::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainProbe for ScriptedProbe {
|
||||
fn probe(&mut self, _chain: u8, _attempt: u8) -> ProbeOutcome {
|
||||
type Error = ();
|
||||
|
||||
fn probe(&mut self, _chain: u8, attempt: u8) -> Result<ProbeOutcome, ()> {
|
||||
self.calls += 1;
|
||||
self.plan.pop_front().unwrap_or(ProbeOutcome::Silent)
|
||||
if attempt == self.fail_at {
|
||||
return Err(());
|
||||
}
|
||||
Ok(self.plan.pop_front().unwrap_or(ProbeOutcome::Silent))
|
||||
}
|
||||
|
||||
fn eeprom(&mut self, _chain: u8) -> EepromState {
|
||||
self.eeprom.clone()
|
||||
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
|
||||
Ok(self.eeprom.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,7 +469,7 @@ mod tests {
|
||||
],
|
||||
EepromState::Absent,
|
||||
);
|
||||
let report = probe_chain(&mut backend, 0, ProbeBudget { attempts: 4 });
|
||||
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);
|
||||
@@ -465,7 +479,7 @@ mod tests {
|
||||
#[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 });
|
||||
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);
|
||||
@@ -480,7 +494,7 @@ mod tests {
|
||||
model: "BHB42601".into(),
|
||||
},
|
||||
);
|
||||
let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 });
|
||||
let report = probe_chain(&mut backend, 2, ProbeBudget { attempts: 2 }).expect("probe");
|
||||
assert_eq!(report.chip, ChipModel::Unknown);
|
||||
assert_eq!(
|
||||
report.eeprom,
|
||||
@@ -509,7 +523,8 @@ mod tests {
|
||||
],
|
||||
EepromState::Absent,
|
||||
);
|
||||
let reports = detect_chains(&mut backend, &[0, 1, 2], ProbeBudget::default());
|
||||
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<_>>(),
|
||||
@@ -518,10 +533,21 @@ mod tests {
|
||||
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());
|
||||
let reports = detect_chains(&mut backend, &[0], ProbeBudget::default()).expect("detect");
|
||||
assert_eq!(
|
||||
plan(&reports, &profile(), Some(&psu()), Vec::new()),
|
||||
Err(DetectionError::UnknownChip)
|
||||
|
||||
+223
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
|
||||
|
||||
use crate::detect::{ChainProbe, ChipModel, EepromState, Envelope, ProbeOutcome, PsuCapability};
|
||||
use crate::HardwareBackend;
|
||||
use std::fmt;
|
||||
use std::io::{self, Read, Write};
|
||||
@@ -24,6 +25,23 @@ const SET_CHAIN_RESET: u8 = 3;
|
||||
const SET_FAN_TARGET: u8 = 4;
|
||||
const READ_TEMPERATURE: u8 = 5;
|
||||
const SET_PSU_ENABLED: u8 = 6;
|
||||
const CAPABILITIES: u8 = 7;
|
||||
const PROBE_CHAIN: u8 = 8;
|
||||
const READ_EEPROM: u8 = 9;
|
||||
const IDENTIFY_PSU: u8 = 10;
|
||||
|
||||
/// Backend feature bits reported by `CAPABILITIES`.
|
||||
pub const CAP_CHAIN_PROBE: u32 = 1 << 0;
|
||||
pub const CAP_EEPROM: u32 = 1 << 1;
|
||||
pub const CAP_PSU_IDENTITY: u32 = 1 << 2;
|
||||
|
||||
const PROBE_IDENTIFIED: u8 = 0;
|
||||
const PROBE_SILENT: u8 = 1;
|
||||
const PROBE_GARBLED: u8 = 2;
|
||||
|
||||
const EEPROM_PRESENT: u8 = 0;
|
||||
const EEPROM_ABSENT: u8 = 1;
|
||||
const EEPROM_INVALID: u8 = 2;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
compile_error!("Alkane HAL sockets require Linux");
|
||||
@@ -337,6 +355,120 @@ fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
impl HalClient {
|
||||
/// Feature mask advertised by the backend. Old backends reject the opcode, which surfaces as
|
||||
/// a protocol error rather than a silent zero.
|
||||
pub fn capabilities(&mut self) -> Result<u32, HalError> {
|
||||
let body = self.exchange(CAPABILITIES, &[])?;
|
||||
let bytes: [u8; 4] = body
|
||||
.try_into()
|
||||
.map_err(|_| HalError::Protocol("invalid capability response"))?;
|
||||
Ok(u32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn require(&mut self, capability: u32) -> Result<(), HalError> {
|
||||
if self.capabilities()? & capability == 0 {
|
||||
return Err(HalError::Protocol("backend lacks a detection capability"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn probe_chain(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, HalError> {
|
||||
self.require(CAP_CHAIN_PROBE)?;
|
||||
let body = self.exchange(PROBE_CHAIN, &[chain, attempt])?;
|
||||
if body.len() != 4 {
|
||||
self.poison();
|
||||
return Err(HalError::Protocol("invalid probe response"));
|
||||
}
|
||||
let chips = u16::from_le_bytes([body[2], body[3]]);
|
||||
match body[0] {
|
||||
PROBE_IDENTIFIED => match chip_from_wire(body[1]) {
|
||||
Some(chip) => Ok(ProbeOutcome::Identified { chip, chips }),
|
||||
None => {
|
||||
self.poison();
|
||||
Err(HalError::Protocol("unknown chip identifier"))
|
||||
}
|
||||
},
|
||||
PROBE_SILENT => Ok(ProbeOutcome::Silent),
|
||||
PROBE_GARBLED => Ok(ProbeOutcome::Garbled),
|
||||
_ => {
|
||||
self.poison();
|
||||
Err(HalError::Protocol("invalid probe outcome"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_eeprom(&mut self, chain: u8) -> Result<EepromState, HalError> {
|
||||
self.require(CAP_EEPROM)?;
|
||||
let body = self.exchange(READ_EEPROM, &[chain])?;
|
||||
match body.first().copied() {
|
||||
Some(EEPROM_ABSENT) if body.len() == 1 => Ok(EepromState::Absent),
|
||||
Some(EEPROM_INVALID) if body.len() == 1 => Ok(EepromState::Invalid),
|
||||
Some(EEPROM_PRESENT) if body.len() > 1 => {
|
||||
let model = std::str::from_utf8(&body[1..])
|
||||
.map_err(|_| HalError::Protocol("invalid EEPROM model text"))?;
|
||||
Ok(EepromState::Present {
|
||||
model: model.to_owned(),
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
self.poison();
|
||||
Err(HalError::Protocol("invalid EEPROM response"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn identify_psu(&mut self) -> Result<PsuCapability, HalError> {
|
||||
self.require(CAP_PSU_IDENTITY)?;
|
||||
let body = self.exchange(IDENTIFY_PSU, &[])?;
|
||||
let name_len = *body
|
||||
.first()
|
||||
.ok_or(HalError::Protocol("empty PSU response"))? as usize;
|
||||
if body.len() != name_len + 1 + 10 {
|
||||
self.poison();
|
||||
return Err(HalError::Protocol("invalid PSU response"));
|
||||
}
|
||||
let name = std::str::from_utf8(&body[1..1 + name_len])
|
||||
.map_err(|_| HalError::Protocol("invalid PSU name"))?
|
||||
.to_owned();
|
||||
let at = 1 + name_len;
|
||||
let word = |offset: usize| u16::from_le_bytes([body[at + offset], body[at + offset + 1]]);
|
||||
Ok(PsuCapability {
|
||||
name,
|
||||
envelope: Envelope {
|
||||
v_min_mv: word(0),
|
||||
v_max_mv: word(2),
|
||||
f_min_mhz: word(4),
|
||||
f_max_mhz: word(6),
|
||||
},
|
||||
max_dc_watts: word(8),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainProbe for HalClient {
|
||||
type Error = HalError;
|
||||
|
||||
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error> {
|
||||
self.probe_chain(chain, attempt)
|
||||
}
|
||||
|
||||
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error> {
|
||||
self.read_eeprom(chain)
|
||||
}
|
||||
}
|
||||
|
||||
fn chip_from_wire(value: u8) -> Option<ChipModel> {
|
||||
match value {
|
||||
1 => Some(ChipModel::Bm1362),
|
||||
2 => Some(ChipModel::Bm1366),
|
||||
3 => Some(ChipModel::Bm1368),
|
||||
4 => Some(ChipModel::Bm1370),
|
||||
5 => Some(ChipModel::Bm1398),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl HardwareBackend for HalClient {
|
||||
type Error = HalError;
|
||||
|
||||
@@ -403,3 +535,94 @@ impl HardwareBackend for HalClient {
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
fn mock_backend(mut server: UnixStream) {
|
||||
loop {
|
||||
let mut header = [0_u8; 16];
|
||||
if server.read_exact(&mut header).is_err() {
|
||||
return;
|
||||
}
|
||||
let opcode = header[5];
|
||||
let sequence = [header[8], header[9], header[10], header[11]];
|
||||
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
|
||||
let mut payload = vec![0_u8; length];
|
||||
if length > 0 && server.read_exact(&mut payload).is_err() {
|
||||
return;
|
||||
}
|
||||
let body: Vec<u8> = match opcode {
|
||||
CAPABILITIES => {
|
||||
let mut body = vec![0_u8];
|
||||
body.extend_from_slice(
|
||||
&(CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY).to_le_bytes(),
|
||||
);
|
||||
body
|
||||
}
|
||||
PROBE_CHAIN => vec![0, PROBE_IDENTIFIED, 1, 126, 0],
|
||||
READ_EEPROM => {
|
||||
let mut body = vec![0, EEPROM_PRESENT];
|
||||
body.extend_from_slice(b"BHB42601");
|
||||
body
|
||||
}
|
||||
IDENTIFY_PSU => {
|
||||
let name = b"APW12";
|
||||
let mut body = vec![0_u8];
|
||||
body.push(name.len() as u8);
|
||||
body.extend_from_slice(name);
|
||||
for word in [1200_u16, 1600, 0, 1000, 3600] {
|
||||
body.extend_from_slice(&word.to_le_bytes());
|
||||
}
|
||||
body
|
||||
}
|
||||
_ => vec![1],
|
||||
};
|
||||
let mut out = [0_u8; 16];
|
||||
out[..4].copy_from_slice(&MAGIC);
|
||||
out[4] = VERSION;
|
||||
out[5] = opcode;
|
||||
out[6..8].copy_from_slice(&RESPONSE.to_le_bytes());
|
||||
out[8..12].copy_from_slice(&sequence);
|
||||
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
if server.write_all(&out).is_err() || server.write_all(&body).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_verbs_round_trip_over_the_wire() {
|
||||
let (client_stream, server_stream) = UnixStream::pair().expect("socket pair");
|
||||
let server = std::thread::spawn(move || mock_backend(server_stream));
|
||||
let mut client = HalClient::from_stream(client_stream).expect("client");
|
||||
|
||||
assert_eq!(
|
||||
client.capabilities().expect("capabilities"),
|
||||
CAP_CHAIN_PROBE | CAP_EEPROM | CAP_PSU_IDENTITY
|
||||
);
|
||||
match client.probe_chain(0, 0).expect("probe") {
|
||||
ProbeOutcome::Identified { chip, chips } => {
|
||||
assert_eq!(chip, ChipModel::Bm1362);
|
||||
assert_eq!(chips, 126);
|
||||
}
|
||||
other => panic!("unexpected probe outcome: {other:?}"),
|
||||
}
|
||||
assert_eq!(
|
||||
client.read_eeprom(0).expect("eeprom"),
|
||||
EepromState::Present {
|
||||
model: "BHB42601".into()
|
||||
}
|
||||
);
|
||||
let psu = client.identify_psu().expect("psu");
|
||||
assert_eq!(psu.name, "APW12");
|
||||
assert_eq!(psu.envelope.v_min_mv, 1200);
|
||||
assert_eq!(psu.envelope.v_max_mv, 1600);
|
||||
assert_eq!(psu.max_dc_watts, 3600);
|
||||
|
||||
drop(client);
|
||||
server.join().expect("server thread");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user