source-pr / source (pull_request) Successful in 13s
The reference server answers the real ALKH contract from a fixed machine description, so the whole OS path can run on a development host and a backend author has a concrete example of every opcode. It serves detection, frequency, fan, temperature and power over one socket. Power was the missing measurement: a power target could not regulate because the HAL had no way to report watts, so READ_POWER joins the verbs behind CAP_POWER. With it, --boot against the reference server settles the loop at 623 MHz for a 2400 W target (4 W per MHz in the model) instead of holding at the boot frequency. Fan mapping stays opt-in for --boot (ALKANE_FAN_FANS/ALKANE_FAN_ZONES) because it perturbs the machine and takes minutes.
355 lines
13 KiB
Rust
355 lines
13 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
use alkane_os::app;
|
|
use alkane_os::detect::{
|
|
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
|
|
PsuCapability, SensorTopology,
|
|
};
|
|
use alkane_os::hal_wire::HalClient;
|
|
use alkane_os::management::MiningStatus;
|
|
use alkane_os::miner::{Bm1366Miner, ChipModel};
|
|
use alkane_os::runtime::{Tick, TickOutcome};
|
|
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
|
|
use alkane_os::target_matrix;
|
|
use alkane_os::tuning::{PidConfig, TuningTarget};
|
|
use alkane_os::HardwareBackend;
|
|
use std::error::Error;
|
|
use std::io;
|
|
use std::net::SocketAddr;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
|
let socket = args.next().ok_or("missing HAL socket")?;
|
|
let address: SocketAddr = args.next().ok_or("missing pool address")?.parse()?;
|
|
let worker = args.next().ok_or("missing pool worker")?;
|
|
let chip = match args.next().as_deref() {
|
|
Some("BM1362") => ChipModel::Bm1362,
|
|
Some("BM1366") => ChipModel::Bm1366,
|
|
_ => return Err("select BM1362 or BM1366".into()),
|
|
};
|
|
let max_accepts: Option<u64> = args.next().map(|value| value.parse()).transpose()?;
|
|
if args.next().is_some() || worker.is_empty() || max_accepts == Some(0) {
|
|
return Err("invalid simulator mining arguments".into());
|
|
}
|
|
let password = std::env::var("ALKANE_POOL_PASSWORD")
|
|
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
|
|
let status = Arc::new(MiningStatus::new());
|
|
let api = std::env::var("ALKANE_API_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let web = std::env::var("ALKANE_WEB_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let servers = app::start(Arc::clone(&status), api, web)?;
|
|
let (api_address, web_address) = servers.addresses();
|
|
if let Some(address) = api_address {
|
|
println!("management API on {address}");
|
|
}
|
|
if let Some(address) = web_address {
|
|
println!("web UI on http://{address}/");
|
|
}
|
|
|
|
// Connect to the pool before enabling power. The SDK HAL server owns the
|
|
// power lease and cuts power if this process stalls or disconnects.
|
|
let mut pool = PoolConnection::connect(
|
|
address,
|
|
concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
|
|
&worker,
|
|
&password,
|
|
Duration::from_secs(2),
|
|
Duration::from_secs(5),
|
|
)
|
|
.map_err(|error| io::Error::other(format!("pool handshake: {error:?}")))?;
|
|
let mut backend = HalClient::connect(socket)?;
|
|
let mut miner = Bm1366Miner::new_for_chip(&mut backend, chip, 0, 0, 0, 100, 80_000)
|
|
.ok_or("invalid simulator safety configuration")?;
|
|
miner.start()?;
|
|
status.set_running(true);
|
|
let mut accepted = 0_u64;
|
|
loop {
|
|
let (event, reports) = pool
|
|
.cycle(&mut miner)
|
|
.map_err(|error| io::Error::other(format!("mining cycle: {error:?}")))?;
|
|
match event {
|
|
PoolEvent::ShareAccepted(_) => {
|
|
accepted += 1;
|
|
status.share_accepted();
|
|
if max_accepts == Some(accepted) {
|
|
miner.stop()?;
|
|
status.set_running(false);
|
|
println!("simulator shares accepted: {accepted}");
|
|
return Ok(());
|
|
}
|
|
}
|
|
PoolEvent::ShareRejected(id) => {
|
|
status.share_rejected();
|
|
eprintln!("pool rejected share request {id}");
|
|
}
|
|
_ => {}
|
|
}
|
|
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A backend that answers without hardware, so the boot path can be exercised on any machine.
|
|
struct SelfCheckBackend;
|
|
|
|
impl DetectionBackend for SelfCheckBackend {
|
|
type Error = ();
|
|
|
|
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
|
|
Ok(ProbeOutcome::Identified {
|
|
chip: DetectedChip::Bm1362,
|
|
chips: 126,
|
|
})
|
|
}
|
|
|
|
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
|
|
Ok(EepromState::Absent)
|
|
}
|
|
|
|
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
|
|
Ok(Some(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,
|
|
}))
|
|
}
|
|
}
|
|
|
|
/// Run detection, the runtime loop and the API document against the self-check backend.
|
|
///
|
|
/// This is the smoke test an image can run on a bench machine before any hashboard is attached:
|
|
/// it proves the profile database parses, detection produces a plan, the tuner moves within the
|
|
/// envelope and the published document is well formed.
|
|
fn self_check() -> Result<(), Box<dyn Error>> {
|
|
let status = MiningStatus::new();
|
|
let config = app::BootConfig {
|
|
profile_db_json: include_str!("../profiles.example.json").to_owned(),
|
|
chain_ports: vec![0, 1, 2],
|
|
sensor: SensorTopology::Pic,
|
|
budget: ProbeBudget::default(),
|
|
fan_zones: Vec::new(),
|
|
target: TuningTarget::PowerW(2_400.0),
|
|
pid: PidConfig::default(),
|
|
ceiling_mc: 95_000,
|
|
fault_policy: Default::default(),
|
|
};
|
|
let mut backend = SelfCheckBackend;
|
|
let mut runtime = app::boot(&mut backend, &config, &status)?;
|
|
let start = runtime.operating_point().frequency_mhz;
|
|
for _ in 0..20 {
|
|
let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz);
|
|
runtime.tick(&Tick {
|
|
power_w: Some(power),
|
|
hashrate_ths: None,
|
|
hottest_mc: Some(70_000),
|
|
ambient_mc: None,
|
|
dt_s: 1.0,
|
|
});
|
|
}
|
|
let end = runtime.operating_point().frequency_mhz;
|
|
if end <= start {
|
|
return Err("self-check: frequency did not move toward the target".into());
|
|
}
|
|
if runtime.active_chains().len() != 3 {
|
|
return Err("self-check: detection did not expose three chains".into());
|
|
}
|
|
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
|
|
let document = status.hardware_document();
|
|
if document["available"] != true {
|
|
return Err("self-check: hardware document is not available".into());
|
|
}
|
|
println!("{}", serde_json::to_string_pretty(&document)?);
|
|
Ok(())
|
|
}
|
|
|
|
fn parse_target(text: &str) -> Result<TuningTarget, Box<dyn Error>> {
|
|
let (kind, value) = text
|
|
.split_once(':')
|
|
.ok_or("target must look like power:2400")?;
|
|
let value: f32 = value.parse()?;
|
|
Ok(match kind {
|
|
"power" => TuningTarget::PowerW(value),
|
|
"hashrate" => TuningTarget::HashrateThs(value),
|
|
"ambient" => TuningTarget::AmbientC {
|
|
margin_mc: value as i32,
|
|
},
|
|
"fan" => TuningTarget::MaxFan {
|
|
max_pwm: value as u8,
|
|
},
|
|
_ => return Err("target must be power, hashrate, ambient or fan".into()),
|
|
})
|
|
}
|
|
|
|
/// Boot a real board through the HAL socket, then run a bounded tuning loop.
|
|
fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
|
let socket = args.next().ok_or("missing HAL socket")?;
|
|
let profiles = args.next().ok_or("missing profile database path")?;
|
|
let target = parse_target(&args.next().ok_or("missing target")?)?;
|
|
let sensor = match args.next().as_deref() {
|
|
Some("nopic") => SensorTopology::NoPic,
|
|
Some("pic") | None => SensorTopology::Pic,
|
|
Some(_) => return Err("sensor must be pic or nopic".into()),
|
|
};
|
|
let ticks: usize = args
|
|
.next()
|
|
.map(|value| value.parse())
|
|
.transpose()?
|
|
.unwrap_or(30);
|
|
let profile_db_json = std::fs::read_to_string(&profiles)?;
|
|
let status = Arc::new(MiningStatus::new());
|
|
let api = std::env::var("ALKANE_API_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let web = std::env::var("ALKANE_WEB_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let servers = app::start(Arc::clone(&status), api, web)?;
|
|
|
|
let config = app::BootConfig {
|
|
profile_db_json,
|
|
chain_ports: vec![0, 1, 2],
|
|
sensor,
|
|
budget: ProbeBudget::default(),
|
|
fan_zones: Vec::new(),
|
|
target,
|
|
pid: PidConfig::default(),
|
|
ceiling_mc: 95_000,
|
|
fault_policy: Default::default(),
|
|
};
|
|
let map_path = std::path::PathBuf::from(
|
|
std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()),
|
|
);
|
|
// Fan mapping is opt-in: it perturbs the machine and takes minutes, so a plain boot skips it.
|
|
let fans: u8 = std::env::var("ALKANE_FAN_FANS")
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(0);
|
|
let zones: u8 = std::env::var("ALKANE_FAN_ZONES")
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(0);
|
|
let settings = app::HalBoot {
|
|
config: &config,
|
|
sweep: alkane_os::fanmap::SweepConfig {
|
|
fans,
|
|
zones,
|
|
low_pwm: 40,
|
|
high_pwm: 100,
|
|
repeats: 1,
|
|
settle_ms: 20_000,
|
|
},
|
|
thresholds: Default::default(),
|
|
map_path: &map_path,
|
|
};
|
|
let (mut runtime, _map) =
|
|
app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?;
|
|
println!(
|
|
"detected {} with {} active chains",
|
|
runtime.plan().profile,
|
|
runtime.active_chains().len()
|
|
);
|
|
|
|
let mut client = HalClient::connect(std::path::Path::new(&socket))?;
|
|
for _ in 0..ticks {
|
|
let hottest = client.read_temperature_mc(0).ok();
|
|
let power_w = client.read_power_w().ok().map(f32::from);
|
|
let outcome = runtime.tick(&Tick {
|
|
power_w,
|
|
hashrate_ths: None,
|
|
hottest_mc: hottest,
|
|
ambient_mc: None,
|
|
dt_s: 1.0,
|
|
});
|
|
if let TickOutcome::Run(command) = outcome {
|
|
for chain in runtime.active_chains() {
|
|
client.set_chain_frequency(chain, command.frequency_mhz)?;
|
|
}
|
|
if let Some(pwm) = command.fan_pwm {
|
|
client.set_fan_target(0, pwm)?;
|
|
}
|
|
}
|
|
if let Some(reason) = runtime.stop_reason() {
|
|
println!("stopped: {reason:?}");
|
|
break;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(&status.hardware_document())?
|
|
);
|
|
let _ = servers;
|
|
Ok(())
|
|
}
|
|
|
|
fn main() {
|
|
let mut args = std::env::args().skip(1);
|
|
match args.next().as_deref() {
|
|
Some("--list-targets") => {
|
|
println!("control_board,hash_chip,algorithm");
|
|
for target in target_matrix() {
|
|
println!(
|
|
"{},{},{:?}",
|
|
target.control.id, target.chip.id, target.chip.algorithm
|
|
);
|
|
}
|
|
}
|
|
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
|
|
Some("--boot") => {
|
|
if let Err(error) = boot_hal(args) {
|
|
eprintln!("boot failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--sim-hal") => {
|
|
let socket = match args.next() {
|
|
Some(path) => path,
|
|
None => {
|
|
eprintln!("usage: alkane-os --sim-hal SOCKET");
|
|
std::process::exit(2);
|
|
}
|
|
};
|
|
if let Err(error) = alkane_os::hal_sim::serve(
|
|
std::path::Path::new(&socket),
|
|
alkane_os::hal_sim::SimConfig::default(),
|
|
) {
|
|
eprintln!("reference HAL stopped: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--self-check") => {
|
|
if let Err(error) = self_check() {
|
|
eprintln!("self-check failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--mine-simulator") => {
|
|
if let Err(error) = sim_mine(args) {
|
|
eprintln!("simulator mining failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
_ => {
|
|
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
|
|
eprintln!(
|
|
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
|
|
);
|
|
std::process::exit(2);
|
|
}
|
|
}
|
|
}
|