diff --git a/README.md b/README.md index 5ec4812b..4cf9add5 100644 --- a/README.md +++ b/README.md @@ -818,6 +818,15 @@ Keep the unit's `RuntimeDirectory=speakerguardd` and `/run/speakerguardd` for its model state and keep it across restarts. A unit without them leaves the state unwritten, and every restart starts cold. +The first start of a boot starts from evidence (`src/boot.rs`) rather than +latched at the coils' limit. Before its first unlock of a boot the daemon +writes `/run/speakerguardd.unlocked` (the boot id), beside the +RuntimeDirectory rather than in it, so cleaning or removing +`/run/speakerguardd` cannot make a later start of the boot look like the +first. The daemon needs `/run` writable for it, or it never takes the +lock. Replace the binary only across a reboot: an older build without the +marker that ran earlier in the same boot can look like no daemon at all. + The PCM udev event and `multi-user.target` can both precede ALSA card discovery. The daemon retries a missing card for up to 30 seconds, using a monotonic deadline and 100 ms polling, before returning the discovery error. diff --git a/speakerguardd.service b/speakerguardd.service index 9d080c73..39db1711 100644 --- a/speakerguardd.service +++ b/speakerguardd.service @@ -3,7 +3,13 @@ Description=Speaker Protection Daemon (feed-forward) # Restarts are safe: until the daemon renews the card's volume lock the # speakers sit at the card's safe level. A restarted daemon resumes the # thermal model from /run/speakerguardd/state only after a clean stop, and -# otherwise starts it at the coils' limit. A crash loop gives up after five +# otherwise starts it at the coils' limit. The first start of a boot +# (no /run state and no /run/speakerguardd.unlocked marker of this boot) +# starts from evidence (boot_resume = evidence, on machines where every +# owner governs one model): the hottest any protected past can have left +# the speakers, narrowed by the last run's record in /var/lib/speakerguardd +# (a clean stop's, or a checkpoint written every 10 s while running). +# The marker sits outside the RuntimeDirectory, so cleaning it keeps it. A crash loop gives up after five # attempts and leaves the speakers at that level. # One daemon owns the speaker sense PCM and the volume interlock: whichever # takes it first protects the speakers, and the other cannot start. This diff --git a/src/boot.rs b/src/boot.rs new file mode 100644 index 00000000..b14cbec3 --- /dev/null +++ b/src/boot.rs @@ -0,0 +1,688 @@ +// SPDX-License-Identifier: MIT +//! The model's starting point at the first start of a boot, from evidence +//! (`boot_resume = evidence`, the default). +//! +//! macOS's loudspeaker manager starts its thermal model at the chassis +//! ambient every time it starts, and plays at full level straight away. +//! The previous default here started every boot at the coils' hard limit, +//! latched, which held the Neo 20 dB down for half a minute and then +//! released 12 dB over eight minutes. This start is as loud as macOS's +//! wherever that can be shown to be safe, and no louder. +//! +//! **The one assumption.** Whatever drove the speakers before this boot +//! kept every voice coil at or under its hard limit `T` (`t_limit`): this +//! daemon (its latch and floor hand the card over before a coil can get +//! there), the kernel's safe level when no daemon held the card (far under +//! it), or another OS's own protection (macOS's loudspeaker manager on +//! these machines enforces the same hard limit, from the same tuning). +//! No other assumption is made: not that no other OS ran, not that the +//! clocks are right beyond what they are checked for, not that the machine +//! was off. +//! +//! **The first start of a boot.** The uptime is credited as time at the +//! card's safe level only when no daemon can have unlocked the card since +//! the kernel started. The absence of the /run state alone does not show +//! that (it can be lost, or never written). So, before the first unlock +//! of every boot, a daemon writes a marker beside the /run state's +//! directory carrying the boot id (`marker_path`: /run/speakerguardd.unlocked, +//! outside the unit's RuntimeDirectory, so neither `systemctl clean +//! --what=runtime` nor removing /run/speakerguardd takes it), durably, and +//! never removes it; and with a +//! record for the next boot configured it unlocks only once its /run state +//! is written (no removal counts instead). A start that finds the marker +//! from this boot (or any marker it cannot read) starts latched. So does +//! one that finds speakersafetyd's flag (guard.rs `FOREIGN_FLAGS`, checked +//! for every start), or a kernel override of the card's safe level +//! (`protection_override`). +//! +//! **One model.** The assumption bounds the model an owner governed. A +//! model the past owner did not govern has no bound from it: speakersafetyd +//! governs the asahi model, macOS on the V/I machines its own, with +//! constants up to three times apart. So the evidence start runs only +//! where every owner governs the same model: no V/I sense, the legacy +//! governor and no guard (the Neo, whose model is macOS's lsm2 static model +//! with its constants). Anywhere else `evidence` starts latched +//! (`one_model`). +//! +//! **Residual risks** (accepted, see the 2026-10-31 safety review): +//! - An RTC set back by another OS by less than the true elapsed time +//! narrows the magnet's bound wrongly. Early in boot the system clock is +//! set from the RTC, so the two agreeing proves little there. The error +//! is at most `(M* - m0) exp(-(1 + r) d' / tau_m)` with `d'` the RTC +//! interval: about 12 K on the Neo at 60 s, under 1 K past 200 s, and it +//! needs an OS that writes the RTC backwards while playing loud. +//! - macOS appears to start its model at the 50 C ambient each boot, so its +//! model can under-read the truth after a hot hand-over from Linux. +//! Simulated: with reboot gaps of 20 s or more each way the truth stays +//! under this start on both nodes for every macOS play length (10 s to +//! 1000 s); only with 10 s + 5 s gaps is the magnet 2.4 K over, and +//! there macOS itself had already taken the true coil to 149-164 C. +//! - A daemon without the marker (0.1.12 before it) that ran earlier in the +//! same boot and fell back to removing its /run state looks like no +//! daemon at all. Replace the binary only across a reboot. +//! +//! **The magnet bound.** With the two-node model (the coil follows the +//! magnet plus `P Rc` with `tau_c`, the magnet follows ambient plus `P Rm` +//! with `tau_m`), let `r = Rm / Rc` and `Y = tau_m M - r tau_c C`. +//! Eliminating `P` between the two equations gives +//! +//! ```text +//! Y' = ta + r (1 - e) C - (1 + r) Y / tau_m, e = (1 + r) tau_c / tau_m +//! ``` +//! +//! With `e < 1` the coefficient of `C` is positive, so while `C <= T`, +//! `Y` relaxes at least as fast as toward `Y* = tau_m (ta + r (1 - e) T) / +//! (1 + r)` from wherever it started, whatever the power did. Then +//! `M = (Y + r tau_c C) / tau_m <= (Y + r tau_c T) / tau_m`, which at `Y*` +//! is exactly `M* = (ta + r T) / (1 + r)`: the magnet of a coil held at its +//! limit for ever. A magnet can never be pumped above that by bursts, and +//! from a known (saved) magnet it approaches it no faster than the formula +//! says (`magnet_bound`). On the Neo `M*` is 84.5 C, where the latched +//! start assumed 135 C and waited for it to cool with a 100 s time constant. +//! +//! **The start.** Every model node starts from the hottest it can be now: +//! the coil at `T` and the magnet at the bound above at the moment the last +//! owner stopped, then at least this boot's uptime at the kernel's safe +//! level (no daemon held the card before this one: no state under /run), +//! for any length of time from there on (`tail_bound`). A record from the +//! last run (a clean stop, or a checkpoint written every few seconds while +//! running, see `Record`) narrows the magnet's bound to its saved magnet +//! plus what the time since can have added; without one, or one that +//! cannot be trusted, the bound is `M*` itself. Chassis sensors (hwmon) +//! can only raise a start, never lower it: a coil can be 80 K over its +//! chassis a second after loud playback, so no sensor can vouch for it. A +//! sensor hotter than the model's ambient is the ambient of the bound (the +//! magnet relaxes toward it), and the start is no colder than it plus a +//! margin. +//! +//! **Clocks.** Only the RTC interval since the record narrows anything, +//! and only by bounding how long another owner had to warm the magnet: a +//! clock that runs fast or jumps forward only makes the start hotter. A +//! clock that went back, an RTC that disagrees with the system clock at +//! either end, or a record written without a synchronized clock, gives the +//! interval no upper bound (the start is `M*`'s). The cooling credit is +//! this boot's uptime alone, which no clock setting can change. + +use std::path::Path; +use std::time::Duration; + +use crate::engine::Thermal; + +/// Discretization margin on the magnet bound (K): the daemon's model steps +/// the magnet before the coil in 10 ms substeps, the proof is continuous. +/// The randomized test below shows the discrete model inside 0.05 K of it. +pub const MAGNET_MARGIN_K: f64 = 1.0; +/// Margin over a chassis sensor that raises a start (K). +pub const SENSOR_MARGIN_K: f64 = 2.0; +/// How often a running daemon checkpoints its model for the next boot. +pub const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(10); +/// Two clocks read a little apart, and the RTC's whole seconds. +const SLACK: Duration = Duration::from_secs(2); +const MAGIC: &str = "speakerguardd-evidence 1"; + +/// The hottest a magnet can be after `d` seconds (None: any time) of any +/// program that kept its coil at or under `t_hard`, from a saved magnet +/// `m0` (None: unknown). See the module comment. +#[cfg_attr(not(test), allow(dead_code))] +pub fn magnet_bound(th: &Thermal, t_hard: f64, ta: f64, m0: Option, d: Option) -> f64 { + magnet_bound_in(th, t_hard, ta, ta, m0, d) +} + +/// `magnet_bound` with the ambient since the record at most `ta`, and the +/// coil at the record at least `c_lo` (the model's own ambient: no node of +/// it goes colder). A hotter `ta` only makes the bound hotter. +pub fn magnet_bound_in(th: &Thermal, t_hard: f64, ta: f64, c_lo: f64, m0: Option, d: Option) -> f64 { + let r = th.tr_magnet / th.tr_coil; + let e = (1.0 + r) * th.tau_coil / th.tau_magnet; + let valid = [r, e, t_hard, ta].iter().all(|v| v.is_finite()) && r > 0.0 && e < 1.0; + if !valid { + // the bound needs the magnet much slower than the coil; without it + // only the independent one holds: nothing over the hard limit + return m0.map_or(t_hard, |m| m.max(t_hard)); + } + let y_star = th.tau_magnet * (ta + r * (1.0 - e) * t_hard) / (1.0 + r); + let y = match m0 { + None => y_star, + Some(m0) => { + // the coil was at least the model's ambient (no model node + // goes colder), which only makes this starting Y larger + let y0 = th.tau_magnet * m0 - r * th.tau_coil * c_lo.min(ta); + match d { + _ if y0 >= y_star => y0, + None => y_star, + Some(d) => y_star + (y0 - y_star) * (-(1.0 + r) * d.max(0.0) / th.tau_magnet).exp(), + } + } + }; + (y + r * th.tau_coil * t_hard) / th.tau_magnet + MAGNET_MARGIN_K +} + +/// The hottest the model's coil and magnet can be at any time `lo` seconds +/// or more after (coil, magnet), at a constant `power` (the card's safe +/// level's worst case) all along. +pub fn tail_bound(th: &Thermal, coil: f64, magnet: f64, power: f64, lo: f64, ta: f64) -> (f64, f64) { + let mut t = th.clone(); + t.t_coil = coil; + t.t_magnet = magnet; + t.hold(power, lo.max(0.0), ta); + let (c_at, m_at) = (t.t_coil, t.t_magnet); + // from there on, for as long as it may be: the end of a very long hold + // is the steady state, and `hold` returns its bounds over the span + let (c, m) = t.hold(power, 1e7, ta); + let steady_m = ta + power * th.tr_magnet; + let steady_c = steady_m + power * th.tr_coil; + (c.max(c_at).max(steady_c), m.max(m_at).max(steady_m)) +} + +/// The start of one node pair: the coil at `t_hard` (or the saved coil, if +/// hotter) and the bounded magnet when the last owner stopped, then at +/// least `uptime` at `safe_power`. +#[cfg_attr(not(test), allow(dead_code))] +pub fn start_bound(th: &Thermal, t_hard: f64, ta: f64, safe_power: f64, uptime: f64, saved: Option<(f64, f64)>, d: Option) -> (f64, f64) { + start_bound_in(th, t_hard, ta, ta, safe_power, uptime, saved, d) +} + +/// `start_bound` with the ambient `ta` (the hottest of the model's own and +/// a chassis sensor's) and the model's own ambient `c_lo` (the coldest a +/// saved coil can have been). +#[allow(clippy::too_many_arguments)] +pub fn start_bound_in(th: &Thermal, t_hard: f64, ta: f64, c_lo: f64, safe_power: f64, uptime: f64, saved: Option<(f64, f64)>, d: Option) -> (f64, f64) { + let m = magnet_bound_in(th, t_hard, ta, c_lo, saved.map(|s| s.1), d); + let m = saved.map_or(m, |s| m.max(s.1)); + let c = saved.map_or(t_hard, |s| s.0.max(t_hard)).max(m); + tail_bound(th, c, m, safe_power, uptime, ta) +} + +/// The most energy (J) a coil kept at or under `t_hard` can have taken in +/// `len` seconds: from tau_c C' = M + P Rc - C, the energy is +/// (tau_c (C_end - C_start) + integral (C - M)) / Rc, with C <= t_hard and +/// C, M >= ta. +pub fn protected_energy(th: &Thermal, t_hard: f64, ta: f64, len: f64) -> f64 { + if !(len > 0.0) { + return 0.0; + } + let rise = (t_hard - ta).max(0.0); + (th.tau_coil * rise + len * rise) / th.tr_coil +} + +/// The power budgets' history at a start (newest last, (seconds, watts)): +/// at the safe level since this boot began, and before that at most +/// `older` joules in the rest of the minute. +pub fn budget_history(uptime: f64, safe_power: f64, older: f64) -> Vec<(f64, f64)> { + let recent = uptime.clamp(0.0, 60.0); + let len = 60.0 - recent; + let mut h = Vec::new(); + if len > 0.0 { + h.push((len, older.max(0.0) / len)); + } + if recent > 0.0 { + h.push((recent, safe_power)); + } + h +} + +/// The hottest chassis or ambient sensor the SMC reports (°C), if any. +pub fn chassis_temperature(hwmon: &Path) -> Option { + let mut best: Option = None; + for dev in std::fs::read_dir(hwmon).ok()?.flatten() { + let dir = dev.path(); + let name = std::fs::read_to_string(dir.join("name")).unwrap_or_default(); + if name.trim() != "macsmc_hwmon" { + continue; + } + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for e in entries.flatten() { + let file = e.file_name().to_string_lossy().to_string(); + let Some(stem) = file.strip_suffix("_label") else { continue }; + let label = std::fs::read_to_string(e.path()).unwrap_or_default(); + let label = label.trim(); + if label != "Ambient" && !label.starts_with("Chassis") { + continue; + } + let Some(v) = std::fs::read_to_string(dir.join(format!("{stem}_input"))).ok().and_then(|v| v.trim().parse::().ok()) else { continue }; + let c = v / 1000.0; + // a reading outside what a chassis can be is a broken sensor + if c.is_finite() && (-40.0..=150.0).contains(&c) { + best = Some(best.map_or(c, |b: f64| b.max(c))); + } + } + } + best +} + +/// The marker a daemon writes before the first unlock of a boot, and +/// never removes (see the module comment): beside the /run state's +/// directory, named after it (`/run/speakerguardd/state` gives +/// `/run/speakerguardd.unlocked`), or next to a state with no directory. +pub const MARKER_NAME: &str = "unlocked"; + +pub fn marker_path(state: &Path) -> std::path::PathBuf { + let dir = state.parent().filter(|d| !d.as_os_str().is_empty()); + match (dir.and_then(Path::parent).filter(|g| !g.as_os_str().is_empty()), dir.and_then(Path::file_name)) { + (Some(up), Some(name)) => up.join(format!("{}.{MARKER_NAME}", name.to_string_lossy())), + _ => state.with_file_name(MARKER_NAME), + } +} + +/// The marker's text: the boot id, or `unknown`. +pub fn marker_text(now: &Stamp) -> String { + format!("{}\n", now.boot_id.as_deref().filter(|b| !b.trim().is_empty()).unwrap_or("unknown")) +} + +/// Why a daemon may have unlocked the card this boot (`marker` read with +/// this boot's `now`), or None when no marker of this boot exists. Only a +/// marker naming another boot id, with this boot's known, is set aside +/// (a /run that is not a tmpfs); anything unreadable counts. +pub fn marker_says_unlocked(marker: &Path, now: &Stamp) -> Option { + match std::fs::read_to_string(marker) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => Some(format!("{}: {e}", marker.display())), + Ok(text) => { + let id = text.trim(); + match now.boot_id.as_deref() { + Some(b) if !id.is_empty() && id != "unknown" && !same_id(id, b) => None, + _ => Some(format!("{} says a daemon unlocked the card this boot", marker.display())), + } + } + } +} + +/// The kernel parameters that override the card's safe level. +pub const OVERRIDE_PARAMS: &[&str] = &["/sys/module/snd_soc_macaudio/parameters/please_blow_up_my_speakers"]; + +/// Why the card's safe level since boot cannot be vouched for by this +/// machine's state (`flags`, `params`), or None. A parameter that cannot +/// be read, or reads anything but 0 or N, counts as set. +pub fn protection_override(flags: &[&str], params: &[&str]) -> Option { + for f in flags { + match std::fs::symlink_metadata(f) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + _ => return Some(format!("{f}: speakersafetyd has run since boot")), + } + } + for p in params { + match std::fs::read_to_string(p) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Some(format!("{p}: {e}")), + Ok(v) if matches!(v.trim(), "0" | "N" | "n") => {} + Ok(v) => return Some(format!("{p} is {}: the kernel's safe level is overridden", v.trim())), + } + } + None +} + +/// What a record says about the moment it was written. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Stamp { + pub boot_id: Option, + pub machine_id: Option, + /// The RTC (whole seconds since the epoch). + pub rtc: Option, + /// CLOCK_REALTIME. + pub realtime: Option, + /// The system clock was synchronized (NTP) when read. + pub synced: bool, +} + +/// A record of the model for the next boot under /var/lib: a clean stop's +/// (`clean`), or a checkpoint of a running daemon (`running`). Both are +/// used the same way (a starting magnet and the time since); a checkpoint +/// carries no promise that the program stopped with it, and needs none. +#[derive(Debug, Clone, PartialEq)] +pub struct Record { + pub clean: bool, + pub stamp: Stamp, + pub config: u64, + /// Boot time from the snapshot to the clock reads. + pub pairing: Duration, + /// The state text (state.rs) of the snapshot. + pub state: String, +} + +fn fnv(text: &str) -> u64 { + text.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3)) +} + +fn word(s: &Option) -> String { + s.as_deref().filter(|w| !w.is_empty() && !w.contains(char::is_whitespace)).unwrap_or("-").to_string() +} + +pub fn encode(r: &Record) -> String { + let body = format!( + "kind {}\nboot_id {}\nmachine_id {}\nconfig {:016x}\nrtc_s {}\nrealtime_ns {}\nsynced {}\npairing_ns {}\n{}", + if r.clean { "clean" } else { "running" }, + word(&r.stamp.boot_id), + word(&r.stamp.machine_id), + r.config, + r.stamp.rtc.map_or("-".into(), |v| v.to_string()), + r.stamp.realtime.map_or("-".into(), |v| v.as_nanos().to_string()), + r.stamp.synced as u8, + r.pairing.as_nanos(), + r.state + ); + format!("{MAGIC}\nsum {:016x}\n{body}", fnv(&format!("{MAGIC}\n{body}"))) +} + +pub fn decode(text: &str) -> Option { + let rest = text.strip_prefix(MAGIC)?.strip_prefix('\n')?; + let (sum, body) = rest.strip_prefix("sum ")?.split_once('\n')?; + if sum.len() != 16 || u64::from_str_radix(sum, 16).ok()? != fnv(&format!("{MAGIC}\n{body}")) { + return None; + } + let mut lines = body.splitn(9, '\n'); + let mut field = |key: &str| -> Option { lines.next()?.strip_prefix(key)?.strip_prefix(' ').map(str::to_string) }; + let clean = match field("kind")?.as_str() { + "clean" => true, + "running" => false, + _ => return None, + }; + let opt = |v: String| (v != "-").then_some(v); + let boot_id = opt(field("boot_id")?); + let machine_id = opt(field("machine_id")?); + let config = u64::from_str_radix(&field("config")?, 16).ok()?; + let rtc = match field("rtc_s")?.as_str() { + "-" => None, + v => Some(v.parse().ok()?), + }; + let realtime = match field("realtime_ns")?.as_str() { + "-" => None, + v => Some(Duration::from_nanos(v.parse().ok()?)), + }; + let synced = match field("synced")?.as_str() { + "0" => false, + "1" => true, + _ => return None, + }; + let pairing = Duration::from_nanos(field("pairing_ns")?.parse().ok()?); + let state = lines.next()?.to_string(); + Some(Record { clean, stamp: Stamp { boot_id, machine_id, rtc, realtime, synced }, config, pairing, state }) +} + +/// A boot id as the kernel writes it, compared without dashes or case. +fn same_id(a: &str, b: &str) -> bool { + let n = |s: &str| s.trim().replace('-', "").to_ascii_lowercase(); + !n(a).is_empty() && n(a) == n(b) +} + +fn agree(s: &Stamp) -> bool { + match (s.rtc, s.realtime) { + (Some(rtc), Some(rt)) => Duration::from_secs(rtc).abs_diff(rt) <= SLACK, + _ => false, + } +} + +/// Why a record cannot be used at all (another machine, configuration or +/// this very boot), or the longest the time since its snapshot can be (s), +/// None when the clocks give no upper bound. +pub fn usable(r: &Record, now: &Stamp, config: u64) -> Result, String> { + match (&r.stamp.machine_id, &now.machine_id) { + (Some(a), Some(b)) if a == b => {} + _ => return Err("written on another machine (or without a machine id)".into()), + } + if r.config != config { + return Err("written under another configuration".into()); + } + match (&r.stamp.boot_id, &now.boot_id) { + (Some(a), Some(b)) if same_id(a, b) => return Err("written in this boot".into()), + (Some(_), Some(_)) => {} + _ => return Err("no boot id".into()), + } + Ok(elapsed_max(r, now)) +} + +/// The longest the time since the record's snapshot can have been (s), by +/// an RTC that agreed with a synchronized system clock when the record was +/// written and agrees with the system clock now; None otherwise. +pub fn elapsed_max(r: &Record, now: &Stamp) -> Option { + if !(r.stamp.synced && agree(&r.stamp) && agree(now)) { + return None; + } + let then = r.stamp.rtc?; + let at = now.rtc?; + let rtc = at.checked_sub(then)? as f64; + // whole seconds at both ends, the reads' placement, 0.1% rate error, + // and the time from the snapshot to its clock reads + let hi = rtc + SLACK.as_secs_f64() + 0.1 + rtc / 999.0 + r.pairing.as_secs_f64(); + hi.is_finite().then_some(hi) +} + +/// The clocks and ids as read now (Linux). +pub fn read_stamp() -> Stamp { + let read = |p: &str| std::fs::read_to_string(p).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: a valid, writable timespec. + let ok = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) } == 0 && ts.tv_sec > 0; + let realtime = ok.then(|| Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)); + Stamp { + boot_id: read("/proc/sys/kernel/random/boot_id"), + machine_id: read("/etc/machine-id"), + rtc: read("/sys/class/rtc/rtc0/since_epoch").and_then(|s| s.parse().ok()).filter(|&s| s > 0), + realtime, + synced: crate::wallclock::synchronized_realtime().is_some(), + } +} + +/// Writes checkpoints for the next boot off the protection loop: a durable +/// write can block for longer than the card's 250 ms lease. The loop hands +/// over the state text and its boot time; the thread reads the clocks +/// (measuring how long after the snapshot that was) and writes the record. +pub struct Checkpointer { + tx: Option>, + thread: Option>, +} + +pub fn boottime() -> Duration { + let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: a valid, writable timespec. + unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut ts) }; + Duration::new(ts.tv_sec.max(0) as u64, ts.tv_nsec.clamp(0, 999_999_999) as u32) +} + +impl Checkpointer { + pub fn spawn(path: std::path::PathBuf, config: u64, write: fn(&Path, &str) -> std::io::Result<()>) -> Checkpointer { + let (tx, rx) = std::sync::mpsc::sync_channel::<(String, Duration)>(1); + let thread = std::thread::Builder::new() + .name("checkpoint".into()) + .spawn(move || { + let mut failed = false; + while let Ok((state, at)) = rx.recv() { + let stamp = read_stamp(); + let pairing = boottime().saturating_sub(at); + let text = encode(&Record { clean: false, stamp, config, pairing, state }); + match write(&path, &text) { + Ok(()) => failed = false, + Err(e) if !failed => { + crate::warn!("{}: {e}; the next boot starts from its own bounds", path.display()); + failed = true; + } + Err(_) => {} + } + } + }) + .ok(); + Checkpointer { tx: thread.as_ref().map(|_| tx), thread } + } + + /// Hand a snapshot over; dropped if the last one is still being written. + pub fn offer(&self, state: String, at: Duration) { + if let Some(tx) = &self.tx { + let _ = tx.try_send((state, at)); + } + } + + /// Wait for the thread to finish what it holds (before a clean record). + pub fn finish(&mut self) { + self.tx = None; + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +impl Drop for Checkpointer { + fn drop(&mut self) { + self.finish(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn neo() -> Thermal { + Thermal::new(38.0, 3.3, 26.0, 100.0, 50.0) + } + + /// The bound itself: M* for the Neo, and the saved magnet's approach. + #[test] + fn the_magnet_bound_is_the_held_coil_steady_state() { + let th = neo(); + let m_star = (50.0 + 26.0 / 38.0 * 135.0) / (1.0 + 26.0 / 38.0); + assert!((magnet_bound(&th, 135.0, 50.0, None, None) - MAGNET_MARGIN_K - m_star).abs() < 1e-9); + assert!((m_star - 84.53).abs() < 0.01, "{m_star}"); + // from a cold magnet: rises with the time allowed, never past M* + let mut last = 0.0; + for d in [0.0, 1.0, 10.0, 30.0, 100.0, 1000.0, 1e6] { + let m = magnet_bound(&th, 135.0, 50.0, Some(50.0), Some(d)); + assert!(m >= last && m <= m_star + MAGNET_MARGIN_K + 1e-9, "{d}: {m}"); + last = m; + } + // a hot saved magnet keeps its own bound (no credit from Y) + assert!(magnet_bound(&th, 135.0, 50.0, Some(120.0), Some(1e6)) >= 120.0); + } + + /// Any program at all that keeps the discrete model's coil under the + /// limit leaves its magnet under the bound, from any magnet, for any + /// length of time: random bursts, held power, and coil-chasing + /// bang-bang drives that hold the coil at the limit. + #[test] + fn no_program_under_the_coil_limit_beats_the_magnet_bound() { + use crate::config::Config; + let cfg = Config::parse(include_str!("../conf/apple/j700.conf")).unwrap(); + let spec = cfg.speakers[0].clone(); + let ta = cfg.globals.t_ambient; + let th = neo(); + let mut seed = 0x9e3779b97f4a7c15u64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let mut worst: f64 = f64::NEG_INFINITY; + for case in 0..300 { + let mut s = crate::model::SpeakerState::new(spec.clone(), ta); + let m0 = ta + rnd() * 40.0; + s.t_magnet = m0; + s.t_coil = m0 + rnd() * (spec.t_limit - m0); + let full = s.worst_case_power(0.0); + let mut t = 0.0; + let style = case % 3; + while t < 600.0 { + let dt = 0.01; + let want = match style { + 0 => if rnd() < 0.3 { full * rnd() } else { 0.0 }, + 1 => full, + _ => if rnd() < 0.5 { full } else { full * 0.1 }, + }; + // the most of `want` that keeps the coil under the limit + let mut p = want; + for _ in 0..40 { + if s.peak_if(p, dt, ta) < spec.t_limit { break; } + p *= 0.7; + } + if s.peak_if(p, dt, ta) >= spec.t_limit { p = 0.0; } + s.step(p, dt, ta); + t += dt; + let bound = magnet_bound(&th, spec.t_limit, ta, Some(m0), Some(t)) - MAGNET_MARGIN_K; + worst = worst.max(s.t_magnet - bound); + assert!(s.t_coil < spec.t_limit); + } + } + assert!(worst < 0.05, "the discrete model beat the continuous bound by {worst} K"); + } + + #[test] + fn records_round_trip_and_refuse_damage() { + let stamp = Stamp { boot_id: Some("ab-cd".into()), machine_id: Some("m".into()), rtc: Some(1000), realtime: Some(Duration::from_millis(1_000_400)), synced: true }; + let r = Record { clean: true, stamp: stamp.clone(), config: 7, pairing: Duration::from_millis(3), state: "speakerguardd-state 3\nboottime_ns 1\nend\n".into() }; + let text = encode(&r); + assert_eq!(decode(&text), Some(r.clone())); + for n in 0..text.len() { + assert!(decode(&text[..n]).is_none(), "accepted a prefix of {n} bytes"); + } + assert!(decode(&text.replacen("kind clean", "kind running", 1)).is_none(), "the checksum let a kind change through"); + assert!(decode(&text.replacen("rtc_s 1000", "rtc_s 900", 1)).is_none()); + let running = Record { clean: false, stamp: Stamp { rtc: None, realtime: None, synced: false, ..stamp }, ..r }; + assert_eq!(decode(&encode(&running)), Some(running)); + } + + fn stamp(boot: &str, rtc: u64, rt_ms: u64, synced: bool) -> Stamp { + Stamp { boot_id: Some(boot.into()), machine_id: Some("m".into()), rtc: Some(rtc), realtime: Some(Duration::from_millis(rt_ms)), synced } + } + + #[test] + fn only_checked_clocks_bound_the_time_since() { + let rec = |s: Stamp| Record { clean: true, stamp: s, config: 1, pairing: Duration::from_millis(5), state: String::new() }; + let r = rec(stamp("a", 1000, 1_000_500, true)); + let hi = usable(&r, &stamp("b", 1030, 1_030_200, false), 1).unwrap().unwrap(); + assert!(hi >= 30.0 && hi < 33.0, "{hi}"); + // the clock went back: no bound + assert_eq!(usable(&r, &stamp("b", 990, 990_000, false), 1), Ok(None)); + // RTC and system clock disagree now, or then; unsynchronized then + assert_eq!(usable(&r, &stamp("b", 1030, 1_090_000, false), 1), Ok(None)); + assert_eq!(usable(&rec(stamp("a", 1000, 1_100_000, true)), &stamp("b", 1030, 1_030_000, false), 1), Ok(None)); + assert_eq!(usable(&rec(stamp("a", 1000, 1_000_000, false)), &stamp("b", 1030, 1_030_000, false), 1), Ok(None)); + // a missing RTC + let mut no_rtc = stamp("b", 1030, 1_030_000, false); + no_rtc.rtc = None; + assert_eq!(usable(&r, &no_rtc, 1), Ok(None)); + // refused outright + assert!(usable(&r, &stamp("A", 1030, 1_030_000, false), 1).is_err(), "same boot"); + assert!(usable(&r, &stamp("b", 1030, 1_030_000, false), 2).is_err(), "another configuration"); + let mut other = stamp("b", 1030, 1_030_000, false); + other.machine_id = Some("n".into()); + assert!(usable(&r, &other, 1).is_err(), "another machine"); + } + + #[test] + fn a_start_is_never_under_any_protected_past() { + // Every past that kept the coil under 135 C, then `uptime` or + // more at the safe level, ends under the start bound. + let th = neo(); + let safe = 7.33f64.powi(2) / 4.2 / 100.0; + for &uptime in &[1.0, 8.5, 30.0] { + let (c, m) = start_bound(&th, 135.0, 50.0, safe, uptime, None, None); + for &(c0, m0) in &[(135.0, 84.5), (135.0, 80.0), (100.0, 84.5), (60.0, 60.0)] { + for &after in &[uptime, uptime + 1.0, uptime + 60.0, uptime + 3600.0] { + let mut t = th.clone(); + t.t_coil = c0; + t.t_magnet = m0; + t.hold(safe, after, 50.0); + assert!(t.t_coil <= c + 1e-9 && t.t_magnet <= m + 1e-9, "uptime {uptime}, from {c0}/{m0} after {after}: {t:?} over {c}/{m}"); + } + } + } + } + + #[test] + fn sensors_are_read_from_the_smc_only() { + let dir = std::env::temp_dir().join(format!("sg-hwmon-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let smc = dir.join("hwmon4"); + let nvme = dir.join("hwmon0"); + std::fs::create_dir_all(&smc).unwrap(); + std::fs::create_dir_all(&nvme).unwrap(); + std::fs::write(smc.join("name"), "macsmc_hwmon\n").unwrap(); + for (i, label, v) in [(1, "Ambient", 29130), (2, "Chassis 3", 46812), (3, "P-cluster Temperature 1", 91000), (4, "Chassis 9", 999000)] { + std::fs::write(smc.join(format!("temp{i}_label")), format!("{label}\n")).unwrap(); + std::fs::write(smc.join(format!("temp{i}_input")), format!("{v}\n")).unwrap(); + } + std::fs::write(nvme.join("name"), "nvme\n").unwrap(); + std::fs::write(nvme.join("temp1_label"), "Chassis\n").unwrap(); + std::fs::write(nvme.join("temp1_input"), "70000\n").unwrap(); + assert_eq!(chassis_temperature(&dir), Some(46.812)); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(chassis_temperature(Path::new("/nonexistent-hwmon")), None); + } +} diff --git a/src/config.rs b/src/config.rs index 016cf046..1248fe04 100644 --- a/src/config.rs +++ b/src/config.rs @@ -130,8 +130,11 @@ pub struct Globals { /// to the kernel. Needs V/I sense on every speaker. pub guard: Option, /// What the first start of a boot assumes of the time since the last - /// one (persist.rs): `latched` (the default) starts at the coils' - /// limit; `idle` resumes the state a clean stop at shutdown left, the + /// one: `evidence` (the default, boot.rs) starts from the hottest any + /// owner that kept the coils under their hard limit can have left + /// them, narrowed by the last run's record, where every owner governs + /// one model (guard.rs `one_model`; latched elsewhere); `latched` starts at the + /// coils' limit (persist.rs); `idle` resumes the state a clean stop at shutdown left, the /// gap at the card's safe level, which is only sound on a machine no /// other OS drives the speakers on. pub boot_resume: BootResume, @@ -139,6 +142,7 @@ pub struct Globals { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BootResume { + Evidence, Latched, Idle, } @@ -345,9 +349,10 @@ impl Config { Some(v) => return Err(ConfigError(format!("[Globals] guard {v:?}: none or asahi"))), }, boot_resume: match g.get("boot_resume").map(String::as_str) { - None | Some("latched") => BootResume::Latched, + None | Some("evidence") => BootResume::Evidence, + Some("latched") => BootResume::Latched, Some("idle") => BootResume::Idle, - Some(v) => return Err(ConfigError(format!("[Globals] boot_resume {v:?}: latched or idle"))), + Some(v) => return Err(ConfigError(format!("[Globals] boot_resume {v:?}: evidence, latched or idle"))), }, }; if !(globals.max_reduction.is_finite() && globals.max_reduction > 0.0) { diff --git a/src/engine.rs b/src/engine.rs index b1a68a84..4de276fa 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1394,6 +1394,60 @@ impl Engine { /// Nothing is known about the speakers: every model at its hard limit, /// latched. + /// The first start of a boot from evidence (boot.rs): every model node + /// from the hottest a protected past can have left it, `saved` (the + /// last run's record, if usable) narrowing the magnet, `d` the longest + /// another owner can have had since it, at least `uptime` at the + /// card's safe level since, and no colder than `floor` (a chassis + /// sensor plus margin). Nothing is latched that is under its limit. + pub fn assume_evidence(&mut self, saved: Option<&crate::state::Saved>, d: Option, uptime: f64, floor: f64) { + use crate::boot::{budget_history, protected_energy, start_bound_in, SENSOR_MARGIN_K}; + let g = self.cfg.globals.clone(); + let ta = g.t_ambient; + // a chassis sensor over the model's ambient is the bound's ambient + let ta_hi = if floor.is_finite() { ta.max(floor - SENSOR_MARGIN_K) } else { ta }; + let safe = 10f64.powf(-g.safe_reduction.max(0.0) / 10.0); + let names: Vec = self.cfg.speakers.iter().map(|s| state_name(&s.name)).collect(); + for (k, s) in self.asahi.iter_mut().flatten().enumerate() { + let rec = saved.and_then(|x| x.asahi.iter().find(|a| a.name == names[k])).map(|a| (a.t_coil, a.t_magnet)); + let p = s.v_worst * s.v_worst / s.z_min * safe; + let (c, m) = start_bound_in(&s.th, s.t_limit, ta_hi, ta, p, uptime, rec, d); + s.th.t_coil = c.max(floor); + s.th.t_magnet = m.max(floor); + s.coil_peak = s.th.t_coil; + s.magnet_peak = s.th.t_magnet; + s.coil_hyst = s.th.t_coil; + s.magnet_hyst = s.th.t_magnet; + s.gain = 0.0; + s.hard = !(s.coil_peak < s.t_limit && s.magnet_peak < s.t_limit); + } + for (k, s) in self.unified.iter_mut().flatten().enumerate() { + let rec = saved.and_then(|x| x.unified.iter().find(|u| u.name == names[k])); + let p_ff = s.v_worst * s.v_worst / s.r_ff * safe; + let (c, m) = start_bound_in(&s.ff, s.t_limit, ta_hi, ta, p_ff, uptime, rec.map(|u| u.ff), d); + s.ff.t_coil = c.max(floor); + s.ff.t_magnet = m.max(floor); + let mut peak = hi(s.ff.t_coil, s.ff.t_magnet); + let z_min = s.z_min; + if let Some(v) = s.vi.as_mut() { + let p_vi = s.v_worst * s.v_worst / z_min * safe; + let (c, m) = start_bound_in(v, s.t_limit, ta_hi, ta, p_vi, uptime, rec.and_then(|u| u.vi), d); + v.t_coil = c.max(floor); + v.t_magnet = m.max(floor); + peak = hi(peak, hi(v.t_coil, v.t_magnet)); + } + s.peak = peak; + s.hard = !(peak < s.t_limit); + s.reduction = 0.0; + let len = 60.0 - uptime.clamp(0.0, 60.0); + let older = protected_energy(&s.ff, s.t_limit, ta, len) + .max(rec.map_or(0.0, |u| 60.0 * u.mean_60s)) + .min(s.v_worst * s.v_worst / s.r_ff * len); + s.history = budget_history(uptime, p_ff, older).into_iter().collect(); + s.history_s = s.history.iter().map(|e| e.0).sum(); + } + } + pub fn assume_latched(&mut self) { let g = self.cfg.globals.clone(); for s in self.asahi.iter_mut().flatten() { diff --git a/src/guard.rs b/src/guard.rs index e6e4c42a..f35d91b4 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -72,6 +72,8 @@ use crate::{debug, info, warn}; #[cfg(test)] mod onset_tests; +#[cfg(test)] +mod evidence_tests; /// The kernel locks the volume again 250 ms after the last write; write well /// inside that while the speakers play. @@ -219,6 +221,19 @@ pub trait Hw { fn rate_events(&mut self) -> bool; /// The card's change events are being delivered. fn events_available(&self) -> bool; + /// The clocks and ids for an evidence record (boot.rs); none by default. + fn stamp(&self) -> crate::boot::Stamp { + crate::boot::Stamp::default() + } + /// The hottest chassis sensor (°C), if the machine reports one. + fn chassis(&self) -> Option { + None + } + /// Why the card's safe level since boot cannot be vouched for (a + /// kernel override is set), if it cannot. + fn protection_override(&self) -> Option { + None + } /// The clocks and the boot's id (persist.rs); none by default. fn wall(&self) -> crate::persist::Wall { crate::persist::Wall::default() @@ -317,6 +332,66 @@ fn state_write_durable(path: &std::path::Path, text: &str) -> io::Result<()> { sync_dir(path) } +/// Every owner of these speakers governs one model (boot.rs, "One +/// model"): no V/I sense, the legacy governor, no guard. +pub fn one_model(cfg: &Config) -> bool { + cfg.controls.vsense.is_none() && cfg.controls.isense.is_none() && cfg.globals.governor == Governor::Legacy && cfg.globals.guard.is_none() +} + +/// The first start of a boot with `boot_resume = evidence` (boot.rs): the +/// models from the hottest a protected past can have left them, the last +/// run's record under /var/lib narrowing it where it can, and a line for +/// the journal saying which. The record is read here and removed by +/// `invalidate` before the lock can be lifted, as before. None when the +/// record is this very boot's: a daemon ran this boot (its /run state is +/// gone), so the card has not held its safe level since the kernel started. +fn evidence_start(hw: &H, cfg: &Config, persist: Option<&std::path::Path>) -> Option<(Vec, Option, String)> { + let g = &cfg.globals; + let uptime = hw.boottime().as_secs_f64(); + let now = hw.stamp(); + let fp = crate::record::fingerprint(cfg); + let mut why = String::from("no record of the last run"); + let mut saved: Option = None; + let mut d: Option = None; + if let Some(pp) = persist { + match std::fs::read_to_string(pp) { + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => why = format!("{}: {e}", pp.display()), + Ok(text) => match crate::boot::decode(&text) { + None => why = format!("{}: unreadable or damaged record", pp.display()), + Some(r) if r.stamp.boot_id.is_some() && r.stamp.boot_id == now.boot_id => return None, + Some(r) => match crate::boot::usable(&r, &now, fp) { + Err(e) => why = format!("{}: {e}", pp.display()), + Ok(hi) => match state::decode(&r.state) { + Some(st) if st.speakers.iter().all(|x| x.t_coil.is_finite() && x.t_magnet.is_finite() && x.t_coil >= g.t_ambient - 1e-6 && x.t_magnet >= g.t_ambient - 1e-6) => { + d = hi.map(|h| (h - uptime).max(0.0)); + let kind = if r.clean { "a clean stop" } else { "a running checkpoint" }; + why = match hi { + Some(h) => format!("{kind} from {h:.0} s ago at most"), + None => format!("{kind}, no trustworthy clock interval"), + }; + saved = Some(st); + } + _ => why = format!("{}: implausible model state", pp.display()), + }, + }, + }, + } + } + let floor = hw.chassis().map_or(f64::NEG_INFINITY, |t| t + crate::boot::SENSOR_MARGIN_K); + let mut speakers: Vec = cfg.speakers.iter().map(|s| SpeakerState::with_globals(s.clone(), g)).collect(); + for s in speakers.iter_mut() { + let rec = saved.as_ref().and_then(|x| x.speakers.iter().find(|y| y.name == crate::engine::state_name(&s.spec.name))).map(|y| (y.t_coil, y.t_magnet, y.mean_60s)); + s.assume_evidence(g, rec, d, uptime, floor); + } + let mut engine = Engine::new(cfg, g.governor == Governor::Unified || g.shadow); + if let Some(e) = engine.as_mut() { + e.assume_evidence(saved.as_ref(), d, uptime, floor); + } + let temps: Vec = speakers.iter().map(|s| format!("{} coil {:.1} C magnet {:.1} C", s.spec.name, s.t_coil, s.t_magnet)).collect(); + Some((speakers, engine, format!("starting from evidence ({why}; {uptime:.1} s at the safe level since boot): {}", temps.join(", ")))) +} + /// How long a sense capture has gone without data. #[derive(Default)] pub struct StallClock(Option); @@ -530,6 +605,13 @@ pub struct Guard { /// The state kept across a reboot (persist.rs), and the configuration's /// fingerprint it is bound to. persist_path: Option, + /// This run has written the /run marker that no later start of this + /// boot may start from evidence (boot.rs). + marked: bool, + /// Writes the running checkpoints for the next boot (boot_resume = + /// evidence), off the protection loop. + checkpoint: Option, + last_checkpoint: Option, config_fp: u64, last_save_try: Option, save_failed: bool, @@ -606,7 +688,12 @@ impl Guard { // the unified governor's opt-in, an unqualified machine's, and the // asahi governor's sense, before the card is touched cfg.check_governor()?; - let globals = cfg.globals.clone(); + let mut globals = cfg.globals.clone(); + if globals.boot_resume == BootResume::Evidence && !one_model(cfg) { + // C2 of the 2026-10-31 safety review (boot.rs, "One model") + info!("boot_resume evidence needs one model shared with every other owner (no V/I sense, the legacy governor, no guard): the first start of a boot is latched"); + globals.boot_resume = BootResume::Latched; + } let governing = globals.governor; let mut engine = Engine::new(cfg, governing == Governor::Unified || globals.shadow); if governing != Governor::Legacy && !engine.as_ref().is_some_and(|e| e.has(governing)) { @@ -658,6 +745,8 @@ impl Guard { let mut restored_at = None; // no state under /run at all: the first start of a boot let mut first_of_boot = false; + // ... started from evidence (boot.rs) + let mut evidence = false; match &state_path { None => { warn!("no model state file: assuming hot speakers (latched)"); @@ -686,10 +775,37 @@ impl Guard { }, Err(e) if e.kind() == io::ErrorKind::NotFound => { first_of_boot = true; - if !(persist_path.is_some() && globals.boot_resume == BootResume::Idle) { - info!("{}: no model state; assuming hot speakers (latched)", path.display()); + if globals.boot_resume == BootResume::Evidence && persist_path.is_some() { + // no /run state is not proof that no daemon unlocked + // the card this boot: the marker is (boot.rs), and + // nothing may have overridden the card's safe level + let refused = crate::boot::marker_says_unlocked(&crate::boot::marker_path(path), &hw.stamp()).or_else(|| hw.protection_override()); + let start = match refused { + Some(why) => Err(Some(why)), + None => evidence_start(hw, cfg, persist_path.as_deref()).ok_or(None), + }; + match start { + Err(Some(why)) => { + info!("{}: no model state, but {why}; assuming hot speakers (latched)", path.display()); + latched(&mut speakers, &mut engine); + } + Ok((sp, en, why)) => { + speakers = sp; + engine = en; + evidence = true; + info!("{why}"); + } + Err(None) => { + info!("{}: no model state, but a record from this boot; assuming hot speakers (latched)", path.display()); + latched(&mut speakers, &mut engine); + } + } + } else { + if !(persist_path.is_some() && globals.boot_resume == BootResume::Idle) { + info!("{}: no model state; assuming hot speakers (latched)", path.display()); + } + latched(&mut speakers, &mut engine); } - latched(&mut speakers, &mut engine); } Err(e) => { warn!("{}: {e}; assuming hot speakers (latched)", path.display()); @@ -754,6 +870,7 @@ impl Guard { info!("{}: speakersafetyd has run since boot; assuming hot speakers (latched)", p.display()); latched(&mut speakers, &mut engine); resumed = false; + evidence = false; break; } } @@ -794,7 +911,11 @@ impl Guard { } } } - let unknown_floor = if resumed { globals.safe_reduction } else { 0.0 }; + // after a clean stop, or at the first start of a boot (no daemon + // has unlocked the card since the kernel started), the card has + // applied at least its own safe level + let globals_boot_resume = globals.boot_resume; + let unknown_floor = if resumed || evidence { globals.safe_reduction } else { 0.0 }; let mut g = Guard { playback_cfg: cfg.clone(), playback: None, @@ -837,7 +958,13 @@ impl Guard { min_failures: 0, target_failures: 0, state_path, + checkpoint: match (&persist_path, globals_boot_resume) { + (Some(pp), BootResume::Evidence) => Some(crate::boot::Checkpointer::spawn(pp.clone(), crate::record::fingerprint(cfg), |p, t| state_write_durable(p, t))), + _ => None, + }, + last_checkpoint: None, persist_path, + marked: false, config_fp: crate::record::fingerprint(cfg), last_save_try: None, save_failed: false, @@ -868,6 +995,22 @@ impl Guard { /// Replace the state file with this run's status (released 0), or /// remove it. True once no clean stop is left for a later start. fn invalidate(&mut self, hw: &H) -> bool { + // with a record for the next boot, a later start of this boot that + // finds no /run state may start from evidence: the marker that it + // must not goes down first, durably, and stays (boot.rs) + if let (Some(_), Some(path), false) = (&self.persist_path, &self.state_path, self.marked) { + let marker = crate::boot::marker_path(path); + match state_write_durable(&marker, &crate::boot::marker_text(&hw.stamp())) { + Ok(()) => self.marked = true, + Err(e) => { + if !self.invalidate_failed { + warn!("{}: {e}; the marker for this boot could not be written, so the lock is not taken", marker.display()); + self.invalidate_failed = true; + } + return false; + } + } + } if let Some(pp) = self.persist_path.clone() { match state_remove_durable(&pp) { Ok(()) => {} @@ -885,6 +1028,15 @@ impl Guard { if self.save_now(hw) { return true; } + if self.persist_path.is_some() { + // fail closed: a restart must find this run's state, never + // none (removing it would make it look like a first start) + if !self.invalidate_failed { + warn!("{}: the model state could not be written, so the lock is not taken", path.display()); + self.invalidate_failed = true; + } + return false; + } match state_remove(&path) { Ok(()) => true, Err(e) if e.kind() == io::ErrorKind::NotFound => true, @@ -1075,6 +1227,21 @@ impl Guard { /// failure costs only the next boot's latched start. fn persist(&mut self, hw: &H, after: Duration) { let Some(pp) = self.persist_path.clone() else { return }; + if self.globals.boot_resume == BootResume::Evidence { + // no checkpoint may land after the clean record + if let Some(mut c) = self.checkpoint.take() { + c.finish(); + } + let stamp = hw.stamp(); + let pairing = hw.boottime().saturating_sub(after); + let state = state::encode_full(after, after, &self.speakers, self.engine.as_ref(), false, true, self.recovering); + let text = crate::boot::encode(&crate::boot::Record { clean: true, stamp, config: self.config_fp, pairing, state }); + match state_write_durable(&pp, &text) { + Ok(()) => info!("model state kept for the next boot in {}", pp.display()), + Err(e) => warn!("{}: {e}; the next boot starts from its own bounds", pp.display()), + } + return; + } if self.globals.boot_resume != BootResume::Idle || !hw.shutting_down() { return; } @@ -2414,9 +2581,30 @@ impl Guard { if self.last_save_try.is_none_or(|t| hw.now().duration_since(t) >= SAVE_INTERVAL) { self.save_now(hw); } + self.offer_checkpoint(hw); Ok(()) } + /// Every CHECKPOINT_INTERVAL, the model as it is now for the next boot + /// (boot.rs: a running checkpoint is only ever a starting magnet; the + /// time after it is bounded by the protected-past rule, not trusted). + fn offer_checkpoint(&mut self, hw: &H) { + if self.checkpoint.is_none() || self.stopping || !self.invalidated { + return; + } + let now = hw.now(); + if self.last_checkpoint.is_some_and(|t| now.duration_since(t) < crate::boot::CHECKPOINT_INTERVAL) { + return; + } + self.last_checkpoint = Some(now); + let boot = hw.boottime(); + let covered = boot.saturating_sub(now.saturating_duration_since(self.account_to)); + let text = state::encode_full(boot, covered, &self.speakers, self.engine.as_ref(), self.armed, false, self.recovering); + if let Some(c) = &self.checkpoint { + c.offer(text, boot); + } + } + /// Write the state file as a status readout (a restart does not /// resume it). pub fn save(&mut self, hw: &H) { @@ -2546,6 +2734,12 @@ pub mod fake { /// The clocks and boot id (persist.rs), and whether the system is /// shutting down. pub wall: crate::persist::Wall, + /// The clocks and ids an evidence record sees (boot.rs). + pub stamp: crate::boot::Stamp, + /// The hottest chassis sensor. + pub chassis: Option, + /// A kernel override of the safe level is set (boot.rs). + pub overridden: Option, pub wall_delay: Duration, wall_elapsed: std::cell::Cell, pub shutting: bool, @@ -2608,6 +2802,9 @@ pub mod fake { tweak: None, delivered: 0, wall: crate::persist::Wall::default(), + stamp: crate::boot::Stamp::default(), + chassis: None, + overridden: None, wall_delay: Duration::ZERO, wall_elapsed: std::cell::Cell::new(Duration::ZERO), shutting: false, @@ -2804,6 +3001,15 @@ pub mod fake { } impl Hw for FakeHw { + fn stamp(&self) -> crate::boot::Stamp { + self.stamp.clone() + } + fn chassis(&self) -> Option { + self.chassis + } + fn protection_override(&self) -> Option { + self.overridden.clone() + } fn wall(&self) -> crate::persist::Wall { self.wall_elapsed.set(self.wall_elapsed.get() + self.wall_delay); self.wall.clone() @@ -3164,6 +3370,8 @@ pub(crate) mod tests { static N: AtomicU32 = AtomicU32::new(0); let dir = std::env::temp_dir().join(format!("speakerguardd-test-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); let _ = std::fs::remove_dir_all(&dir); + // and a stale evidence marker beside it (boot.rs `marker_path`) + let _ = std::fs::remove_file(crate::boot::marker_path(&dir.join("state"))); std::fs::create_dir_all(&dir).unwrap(); Some(dir.join("state")) } @@ -3940,9 +4148,7 @@ pub(crate) mod tests { // a hot run, stopped at shutdown (or not); its persisted file let shutdown = |idle: bool, shutting: bool| { let mut cfg = j700(); - if idle { - cfg.globals.boot_resume = BootResume::Idle; - } + cfg.globals.boot_resume = if idle { BootResume::Idle } else { BootResume::Latched }; let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); hw.level = Box::new(|_| 0.6); @@ -6739,11 +6945,14 @@ mod persist_review { } } - /// The default ignores the record's contents and clocks entirely: the - /// same models and card writes as a start without it. + /// `latched` ignores the record's contents and clocks entirely: the + /// same models and card writes as a start without it. (The default + /// is now `evidence`, guard/evidence_tests.rs, which reads only its + /// own format and never this one.) #[test] fn the_default_is_the_start_without_it() { - let cfg = j700(); + let mut cfg = j700(); + cfg.globals.boot_resume = BootResume::Latched; let valid = fixture(&cfg, 60.0, 55.0); for (name, text) in [("valid", valid.clone()), ("empty", String::new()), ("partial", valid[..valid.len() / 2].into()), ("cold", fixture(&cfg, -49.0, -49.0))] { for gap in [0, 60, 86400] { @@ -7031,7 +7240,11 @@ mod persist_review { /// for such machines (persist.rs, README). #[test] fn the_default_is_the_parents_start_after_another_os() { - let cfg = j700(); + // `latched`: the default before evidence starts (boot.rs), whose + // own assumption (another OS kept its coil under the hard limit, + // so its magnet under M*) is checked in guard/evidence_tests.rs + let mut cfg = j700(); + cfg.globals.boot_resume = BootResume::Latched; let peak = |g: &mut Guard, hw: &mut FakeHw| { hw.level = Box::new(|_| 1.0); while hw.t < Duration::from_secs(30) { diff --git a/src/guard/evidence_tests.rs b/src/guard/evidence_tests.rs new file mode 100644 index 00000000..78e1ca6c --- /dev/null +++ b/src/guard/evidence_tests.rs @@ -0,0 +1,583 @@ +// SPDX-License-Identifier: MIT +//! The first start of a boot from evidence (boot.rs): every start path, at +//! the guard, on the Neo's configuration. + +use super::fake::*; +use super::tests::{j700, missing_state, run_until, tmp_state}; +use super::*; +use crate::boot::{self, Stamp}; + +const UPTIME: Duration = Duration::from_millis(8500); +const RTC0: u64 = 1_800_000_000; + +fn stamp(boot: &str, rtc: u64, synced: bool) -> Stamp { + Stamp { boot_id: Some(boot.into()), machine_id: Some("m".into()), rtc: Some(rtc), realtime: Some(Duration::from_secs(rtc) + Duration::from_millis(300)), synced } +} + +fn secs(s: f64) -> Duration { + Duration::from_secs_f64(s) +} + +/// A run of `play_s` seconds at `level` of full scale, stopped cleanly; +/// the record it left for the next boot, and its coil at the stop. +fn shutdown(level: f64, play_s: f64) -> (Config, PathBuf, f64, f64) { + let cfg = j700(); + // from a cold clean stop of this same boot (/run), at boot time 1000 s + let (run, keep) = (tmp_state().unwrap(), missing_state().unwrap()); + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = Duration::from_secs(1000); + hw.stamp = stamp("first", RTC0 - 3600, true); + hw.machine = Some("m".into()); + hw.level = Box::new(move |_| level); + let mut g = Guard::start_persist(&mut hw, &cfg, 20.0, Some(run), Some(keep.clone())).unwrap(); + run_until(&mut g, &mut hw, secs(play_s)).unwrap(); + hw.stamp = stamp("first", RTC0, true); + g.stop(&mut hw).unwrap(); + while !g.released(&hw) { + g.tick(&mut hw).unwrap(); + } + g.final_save(&hw).unwrap(); + (cfg, keep, g.speakers[0].t_coil, g.speakers[0].t_magnet) +} + +/// The next boot `gap` RTC seconds after the record, 8.5 s up. +fn boot_with(cfg: &Config, keep: Option<&PathBuf>, now: Stamp, chassis: Option) -> (Guard, FakeHw) { + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = UPTIME; + hw.stamp = now; + hw.chassis = chassis; + hw.machine = Some("m".into()); + let keep = keep.cloned().unwrap_or_else(|| missing_state().unwrap()); + let g = Guard::start_persist(&mut hw, cfg, 20.0, missing_state(), Some(keep.clone())).unwrap(); + assert!(!keep.exists(), "the start did not consume the record"); + (g, hw) +} + +fn magnet(g: &Guard) -> f64 { + g.speakers.iter().map(|s| s.t_magnet).fold(f64::NEG_INFINITY, f64::max) +} + +fn coil(g: &Guard) -> f64 { + g.speakers.iter().map(|s| s.t_coil).fold(f64::NEG_INFINITY, f64::max) +} + +/// The no-record start: the protected-past bound (M* = 84.5 C on the Neo) +/// after 8.5 s at the safe level, not latched, and the lock taken within a +/// fraction of a second at a few dB at most. +#[test] +fn no_record_starts_from_the_protected_bound_and_unlocks_at_once() { + let cfg = j700(); + let (mut g, mut hw) = boot_with(&cfg, None, stamp("second", RTC0, false), None); + assert!(g.speakers.iter().all(|s| !s.hard), "latched without evidence of a hot coil"); + let m_star = (50.0 + 26.0 / 38.0 * 135.0) / (1.0 + 26.0 / 38.0); + // M* (plus the margin), cooled for the uptime at the safe level + assert!(magnet(&g) <= m_star + boot::MAGNET_MARGIN_K && magnet(&g) > m_star - 5.0, "magnet {}", magnet(&g)); + assert!(coil(&g) < 100.0, "coil {}", coil(&g)); + run_until(&mut g, &mut hw, secs(1.0)).unwrap(); + assert!(g.armed(), "the lock was not taken within a second"); + // this branch's onset reserve (full-dose, against the working limit) + // sets the level from here: 7.6 dB at this start, 4.0 dB cold + assert!(hw.reduction <= 8.0, "{} dB at the first unlock", hw.reduction); + let first = hw.reduction; + // and it releases as the magnet cools + run_until(&mut g, &mut hw, secs(200.0)).unwrap(); + assert!(hw.reduction <= first - 1.0, "{} dB after 200 s idle", hw.reduction); +} + +/// A clean reboot of a cold machine: the record narrows the magnet to what +/// the half minute since can have added, under the no-record start. +#[test] +fn a_quick_clean_reboot_starts_near_cold() { + let (cfg, keep, c0, _) = shutdown(0.0, 20.0); + assert!(c0 < 60.0, "{c0}"); + let (cold, _) = boot_with(&j700(), None, stamp("second", RTC0 + 35, false), None); + let (mut g, mut hw) = boot_with(&cfg, Some(&keep), stamp("second", RTC0 + 35, false), None); + assert!(g.speakers.iter().all(|s| !s.hard)); + assert!(magnet(&g) < magnet(&cold) - 15.0, "record magnet {} against none {}", magnet(&g), magnet(&cold)); + run_until(&mut g, &mut hw, secs(1.0)).unwrap(); + assert!(g.armed()); + let (mut none, mut hw0) = boot_with(&j700(), None, stamp("second", RTC0 + 35, false), None); + run_until(&mut none, &mut hw0, secs(1.0)).unwrap(); + assert!(hw.reduction <= hw0.reduction - 1.5, "{} dB at the first unlock after a quick reboot, {} without a record", hw.reduction, hw0.reduction); +} + +/// A hot clean stop: the start is never cooler than the stop decayed at +/// the safe level for the uptime alone, and a long gap gives no less than +/// the no-record start (another owner can have had all of it). +#[test] +fn a_hot_record_decays_only_by_the_uptime() { + let (cfg, keep, c0, m0) = shutdown(0.6, 120.0); + assert!(m0 > 60.0, "the run was not hot: coil {c0} magnet {m0}"); + let text = std::fs::read_to_string(&keep).unwrap(); + for gap in [30u64, 600, 86_400] { + std::fs::write(&keep, &text).unwrap(); + let (g, _) = boot_with(&cfg, Some(&keep), stamp("second", RTC0 + gap, false), None); + // the record's own magnet, after 8.5 s at the safe level at most + assert!(magnet(&g) >= m0 - 3.0, "gap {gap}: magnet {} against {m0} at the stop", magnet(&g)); + let (none, _) = boot_with(&cfg, None, stamp("second", RTC0 + gap, false), None); + if gap >= 600 { + assert!(magnet(&g) >= magnet(&none) - 0.01, "gap {gap}: under the no-record start"); + } + } +} + +/// A checkpoint of a running daemon (the dirty marker) is used only for its +/// magnet: the same as a clean stop's, never a promise that the program +/// stopped with it. +#[test] +fn a_running_checkpoint_is_written_and_used_without_trust() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = UPTIME; + hw.stamp = stamp("first", RTC0, true); + hw.machine = Some("m".into()); + hw.level = Box::new(|_| 0.6); + let mut g = Guard::start_persist(&mut hw, &cfg, 20.0, Some(run), Some(keep.clone())).unwrap(); + run_until(&mut g, &mut hw, secs(25.0)).unwrap(); + g.checkpoint.as_mut().unwrap().finish(); + let text = std::fs::read_to_string(&keep).expect("no checkpoint after 25 s"); + let rec = boot::decode(&text).expect("a damaged checkpoint"); + assert!(!rec.clean); + // a crash now: the next boot, a minute on + let (g2, _) = boot_with(&cfg, Some(&keep), stamp("second", RTC0 + 60, false), None); + assert!(g2.speakers.iter().all(|s| !s.hard)); + assert!(magnet(&g2) >= g.speakers.iter().map(|s| s.t_magnet).fold(0.0, f64::max) - 3.0); + // the same snapshot as a clean stop starts no cooler + std::fs::write(&keep, boot::encode(&boot::Record { clean: true, ..rec })).unwrap(); + let (g3, _) = boot_with(&cfg, Some(&keep), stamp("second", RTC0 + 60, false), None); + assert!((magnet(&g3) - magnet(&g2)).abs() < 1e-9); +} + +/// Clocks that went back, disagree, or were not synchronized when the +/// record was written give no interval: the magnet bound of an unknown +/// time (no colder than the no-record start). +#[test] +fn untrustworthy_clocks_give_no_interval() { + let (cfg, keep, _, _) = shutdown(0.0, 20.0); + let text = std::fs::read_to_string(&keep).unwrap(); + let (none, _) = boot_with(&cfg, None, stamp("second", RTC0 + 35, false), None); + let mut disagree = stamp("second", RTC0 + 35, false); + disagree.realtime = Some(Duration::from_secs(RTC0 + 3600)); + let mut no_rtc = stamp("second", RTC0 + 35, false); + no_rtc.rtc = None; + for (why, now) in [("went back", stamp("second", RTC0 - 100, false)), ("disagree now", disagree), ("no RTC", no_rtc)] { + std::fs::write(&keep, &text).unwrap(); + let (g, _) = boot_with(&cfg, Some(&keep), now, None); + assert!(magnet(&g) >= magnet(&none) - 1.0, "{why}: magnet {} against {}", magnet(&g), magnet(&none)); + assert!(g.speakers.iter().all(|s| !s.hard), "{why}"); + } + // unsynchronized when written + let rec = boot::decode(&text).unwrap(); + std::fs::write(&keep, boot::encode(&boot::Record { stamp: Stamp { synced: false, ..rec.stamp.clone() }, ..rec })).unwrap(); + let (g, _) = boot_with(&cfg, Some(&keep), stamp("second", RTC0 + 35, false), None); + assert!(magnet(&g) >= magnet(&none) - 1.0); +} + +/// Damage, another machine or configuration: as no record. A record of +/// this very boot (the daemon ran this boot, its /run state is gone): +/// latched, as before. +#[test] +fn corrupt_foreign_and_same_boot_records() { + let (cfg, keep, _, _) = shutdown(0.0, 20.0); + let text = std::fs::read_to_string(&keep).unwrap(); + let (none, _) = boot_with(&cfg, None, stamp("second", RTC0 + 35, false), None); + let at = text.find("speaker Left ").unwrap() + "speaker Left ".len(); + let digit = text.as_bytes()[at]; + let mut flipped = text.clone(); + flipped.replace_range(at..at + 1, if digit == b'5' { "4" } else { "5" }); + assert_ne!(flipped, text); + let mut other = cfg.clone(); + other.globals.t_hysteresis += 1.0; + let mut foreign = stamp("second", RTC0 + 35, false); + foreign.machine_id = Some("other".into()); + for (why, body, c, now) in [ + ("flipped", flipped, cfg.clone(), stamp("second", RTC0 + 35, false)), + ("truncated", text[..text.len() / 2].to_string(), cfg.clone(), stamp("second", RTC0 + 35, false)), + ("garbage", "\u{0}\u{1}nonsense".to_string(), cfg.clone(), stamp("second", RTC0 + 35, false)), + ("another configuration", text.clone(), other, stamp("second", RTC0 + 35, false)), + ("another machine", text.clone(), cfg.clone(), foreign), + ] { + std::fs::write(&keep, body).unwrap(); + let (g, _) = boot_with(&c, Some(&keep), now, None); + assert!((magnet(&g) - magnet(&none)).abs() < 1e-6, "{why}: {} against {}", magnet(&g), magnet(&none)); + } + std::fs::write(&keep, &text).unwrap(); + let (g, _) = boot_with(&cfg, Some(&keep), stamp("first", RTC0 + 35, false), None); + assert!(g.speakers.iter().all(|s| s.hard), "a record of this boot was taken as the last boot's"); +} + +/// A hot chassis raises the start; a cool one changes nothing. +#[test] +fn chassis_sensors_only_raise_the_start() { + let cfg = j700(); + let (base, _) = boot_with(&cfg, None, stamp("second", RTC0, false), None); + let (cool, _) = boot_with(&cfg, None, stamp("second", RTC0, false), Some(35.0)); + assert_eq!(magnet(&cool), magnet(&base)); + let (hot, _) = boot_with(&cfg, None, stamp("second", RTC0, false), Some(95.0)); + assert!(magnet(&hot) >= 97.0 && coil(&hot) >= 97.0); +} + +/// `boot_resume = latched` keeps the old start. +#[test] +fn latched_remains_selectable() { + let mut cfg = j700(); + cfg.globals.boot_resume = BootResume::Latched; + let (g, _) = boot_with(&cfg, None, stamp("second", RTC0, false), None); + assert!(g.speakers.iter().all(|s| s.hard)); +} + +/// From the no-record start, ten minutes of full-scale square wave: the +/// model never reaches the limit and the guard keeps the card. Truth is +/// stepped beside it from the worst protected past (coil at the limit, the +/// magnet at M*, 8.5 s at the safe level) with the gain the card applied: +/// it stays under the hard limit as well. +#[test] +fn full_scale_from_the_evidence_start_stays_under_the_limit() { + let cfg = j700(); + let (mut g, mut hw) = boot_with(&cfg, None, stamp("second", RTC0, false), None); + hw.level = Box::new(|_| 1.0); + let ta = cfg.globals.t_ambient; + let mut truth: Vec = cfg.speakers.iter().map(|s| SpeakerState::with_globals(s.clone(), &cfg.globals)).collect(); + let m_star = (ta + 26.0 / 38.0 * 135.0) / (1.0 + 26.0 / 38.0); + for t in truth.iter_mut() { + t.t_coil = t.spec.t_limit - 1e-6; + t.t_magnet = m_star; + let p = t.worst_case_power(cfg.globals.safe_reduction); + t.step(p, UPTIME.as_secs_f64(), ta); + t.hard = false; + } + let mut last = hw.t; + let mut hottest: f64 = 0.0; + while hw.t < secs(600.0) { + let applied = if g.armed() { hw.reduction } else { cfg.globals.safe_reduction.max(hw.reduction) }; + g.tick(&mut hw).unwrap(); + let dt = (hw.t - last).as_secs_f64(); + last = hw.t; + for (t, s) in truth.iter_mut().zip(&g.speakers) { + let p = t.worst_case_power(applied); + t.step(p, dt, ta); + assert!(s.t_peak < s.spec.t_limit, "the model reached its limit at {:?}", hw.t); + hottest = hottest.max(t.t_peak); + } + } + assert!(hottest < cfg.speakers[0].t_limit, "the worst past's coil reached {hottest}"); +} + +/// The attenuation against time after boot, for the report (run with +/// --ignored --nocapture): no record, a quick clean reboot, and the latched +/// start it replaces; idle, then pink-like program at -10 dBFS RMS. +#[test] +#[ignore] +fn print_attenuation_after_boot() { + let (cfg, keep, _, _) = shutdown(0.0, 20.0); + let mut latched = j700(); + latched.globals.boot_resume = BootResume::Latched; + for (name, c, k, gap) in [("no record", j700(), None, 35u64), ("quick reboot", cfg.clone(), Some(&keep), 35), ("latched (old)", latched, None, 35)] { + let (mut g, mut hw) = boot_with(&c, k, stamp("second", RTC0 + gap, false), None); + hw.level = Box::new(|_| 0.316); + let mut line = format!("{name:>14}:"); + for t in [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 240.0, 480.0] { + run_until(&mut g, &mut hw, secs(t)).unwrap(); + let db = if g.armed() { hw.reduction } else { 20.0 }; + line += &format!(" {t}s={db:.1}"); + } + eprintln!("{line}"); + } +} + +/// The attenuation the guard holds at idle from a resumed (c, m), for the +/// report (--ignored --nocapture). +#[test] +#[ignore] +fn print_idle_attenuation_by_temperature() { + let cfg = j700(); + for &(c, m) in &[(50.0, 50.0), (60.0, 55.0), (70.0, 60.0), (80.0, 70.0), (85.0, 75.0), (92.0, 83.0), (100.0, 85.0)] { + let path = missing_state().unwrap(); + let mut sp: Vec = cfg.speakers.iter().map(|s| SpeakerState::new(s.clone(), 50.0)).collect(); + for s in sp.iter_mut() { s.t_coil = c; s.t_magnet = m; s.t_peak = c; } + let boot = Duration::from_secs(1000); + std::fs::write(&path, state::encode(boot, boot, &sp, false, true)).unwrap(); + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = boot; + let mut g = Guard::start(&mut hw, &cfg, 20.0, Some(path)).unwrap(); + run_until(&mut g, &mut hw, secs(1.0)).unwrap(); + let idle = hw.reduction; + hw.level = Box::new(|_| 0.2); + run_until(&mut g, &mut hw, secs(1.5)).unwrap(); + eprintln!("coil {c} magnet {m}: idle {idle:.1} dB, -14 dBFS square {:.1} dB, floor {:.2} dB", hw.reduction, g.floor_db(0.0)); + } +} + +// ---- C1 of the 2026-10-31 safety review: a missing /run state does not +// prove that no daemon unlocked the card this boot. + +/// A start of this boot with its /run state at `run` (and the marker next +/// to it), the record at `keep`, `setup` applied to the card first. +fn start_at(cfg: &Config, run: &std::path::Path, keep: &std::path::Path, now: Stamp, setup: impl FnOnce(&mut FakeHw)) -> (Guard, FakeHw) { + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = UPTIME; + hw.stamp = now; + hw.machine = Some("m".into()); + setup(&mut hw); + let g = Guard::start_persist(&mut hw, cfg, 20.0, Some(run.to_path_buf()), Some(keep.to_path_buf())).unwrap(); + (g, hw) +} + +fn marker_of(run: &std::path::Path) -> PathBuf { + boot::marker_path(run) +} + +/// Truth from `crashed` (coil, magnet per speaker), 1 s at the safe level, +/// then `g` driving full scale for 120 s with the gains it lets through; +/// the hottest the true coil gets. +fn truth_after_restart(cfg: &Config, g: &mut Guard, hw: &mut FakeHw, crashed: &[(f64, f64)]) -> f64 { + let ta = cfg.globals.t_ambient; + let mut truth: Vec = g.speakers.iter().zip(crashed).map(|(s, &(c, m))| { + let mut t = SpeakerState::new(s.spec.clone(), ta); + t.t_coil = c; + t.t_magnet = m; + let p = t.worst_case_power(cfg.globals.safe_reduction); + t.step(p, 1.0, ta); + t.hard = false; + t + }).collect(); + hw.level = Box::new(|_| 1.0); + let mut last = hw.t; + let mut hottest: f64 = 0.0; + while hw.t < secs(120.0) { + let applied = if g.armed() { hw.reduction } else { cfg.globals.safe_reduction.max(hw.reduction) }; + g.tick(hw).unwrap(); + let dt = (hw.t - last).as_secs_f64(); + last = hw.t; + for t in truth.iter_mut() { + let p = t.worst_case_power(applied); + t.step(p, dt, ta); + hottest = hottest.max(t.t_peak.max(t.t_coil)); + } + } + hottest +} + +/// SAFETY REVIEW counterexample (C1), kept as a regression test. The +/// reviewer's premise (both writes fail) can no longer unlock at all, see +/// the next test; here the first run unlocks normally, plays full scale +/// for a minute and dies without a clean stop, and its /run state is then +/// lost and the record under /var/lib never written (its temporary name +/// is a directory, standing in for ENOSPC). The restart a second later in +/// the same boot finds neither file, but finds the marker: latched, never +/// cooler than the crashed model, and truth stays under the hard limit. +#[test] +fn review_crash_restart_without_run_state_is_not_a_first_start() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + std::fs::create_dir_all(keep.with_extension("tmp")).unwrap(); + let mut hw = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw.boot = UPTIME; + hw.stamp = stamp("first", RTC0, true); + hw.machine = Some("m".into()); + hw.level = Box::new(|_| 1.0); + let mut g = Guard::start_persist(&mut hw, &cfg, 20.0, Some(run.clone()), Some(keep.clone())).unwrap(); + run_until(&mut g, &mut hw, secs(60.0)).unwrap(); + assert!(g.armed(), "the first run never unlocked"); + let crashed: Vec<(f64, f64)> = g.speakers.iter().map(|s| (s.t_coil, s.t_magnet)).collect(); + let boot_at_crash = hw.boot + hw.t; + // a crash: no stop, no final save; the checkpointer thread just ends + drop(g); + std::fs::remove_file(&run).unwrap(); + assert!(!run.exists() && !keep.exists(), "the test premise: neither file is there"); + assert!(marker_of(&run).exists(), "no marker after an unlock"); + let mut hw2 = FakeHw::new(cfg.globals.channels, cfg.globals.period); + hw2.boot = boot_at_crash + secs(1.0); + hw2.stamp = stamp("first", RTC0 + 70, true); + hw2.machine = Some("m".into()); + let mut g2 = Guard::start_persist(&mut hw2, &cfg, 20.0, Some(run), Some(keep)).unwrap(); + let start: Vec<(f64, f64)> = g2.speakers.iter().map(|s| (s.t_coil, s.t_magnet)).collect(); + eprintln!("crashed model {crashed:?}; restart starts at {start:?}"); + assert!(g2.speakers.iter().all(|s| s.hard), "the restart did not start latched"); + assert!(start.iter().zip(&crashed).all(|(s, c)| s.0 >= c.0 - 1.0 && s.1 >= c.1 - 1.0), "the restart started cooler than the crashed model: {start:?} against {crashed:?}"); + let hottest = truth_after_restart(&cfg, &mut g2, &mut hw2, &crashed); + let limit = cfg.speakers[0].t_limit; + eprintln!("truth hottest {hottest} C over 120 s of full scale from the restart"); + assert!(hottest < limit, "truth reached {hottest} C against the {limit} C hard limit"); +} + +/// The reviewer's literal premise: the /run state and the record both fail +/// to write. Fail closed: the run never unlocks (no removal of the /run +/// state counts as invalidating it), and its restart starts latched. +#[test] +fn a_run_state_that_cannot_be_written_keeps_the_card_locked() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + std::fs::create_dir_all(run.with_extension("tmp")).unwrap(); + std::fs::create_dir_all(keep.with_extension("tmp")).unwrap(); + let (mut g, mut hw) = start_at(&cfg, &run, &keep, stamp("first", RTC0, true), |hw| hw.level = Box::new(|_| 1.0)); + run_until(&mut g, &mut hw, secs(60.0)).unwrap(); + assert!(!g.armed(), "unlocked without a /run state"); + assert!(hw.reduction >= cfg.globals.safe_reduction - 1e-9, "{} dB", hw.reduction); + drop(g); + assert!(!run.exists() && !keep.exists()); + let (g2, _) = start_at(&cfg, &run, &keep, stamp("first", RTC0 + 70, true), |_| {}); + assert!(g2.speakers.iter().all(|s| s.hard), "the restart did not start latched"); +} + +/// The marker is written (with the boot id) before the first unlock, and a +/// clean stop leaves it in place. +#[test] +fn the_marker_is_written_before_the_unlock_and_kept() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + let (mut g, mut hw) = start_at(&cfg, &run, &keep, stamp("second", RTC0, false), |_| {}); + assert!(!g.speakers.iter().any(|s| s.hard), "not an evidence start"); + assert_eq!(std::fs::read_to_string(marker_of(&run)).unwrap().trim(), "second", "no marker before the unlock"); + run_until(&mut g, &mut hw, secs(1.0)).unwrap(); + assert!(g.armed()); + g.stop(&mut hw).unwrap(); + while !g.released(&hw) { + g.tick(&mut hw).unwrap(); + } + g.final_save(&hw).unwrap(); + assert!(marker_of(&run).exists(), "the marker was removed"); +} + +/// A marker that cannot be written: the lock is never taken. +#[test] +fn a_marker_that_cannot_be_written_keeps_the_card_locked() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + std::fs::create_dir_all(marker_of(&run).with_extension("tmp")).unwrap(); + let (mut g, mut hw) = start_at(&cfg, &run, &keep, stamp("second", RTC0, false), |_| {}); + run_until(&mut g, &mut hw, secs(5.0)).unwrap(); + assert!(!g.armed(), "unlocked without the marker"); +} + +/// This boot's marker, or one that cannot be read, refuses the evidence +/// start; another boot's (a /run that is not a tmpfs) does not. +#[test] +fn the_marker_refuses_the_evidence_start() { + let cfg = j700(); + for (why, body, latched) in [("this boot's", Some("second\n"), true), ("this boot's, dashes and case", Some("SE-COND\n"), true), ("unknown boot", Some("unknown\n"), true), ("empty", Some(""), true), ("unreadable", None, true), ("another boot's", Some("first\n"), false)] { + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + match body { + Some(b) => std::fs::write(marker_of(&run), b).unwrap(), + None => std::fs::create_dir_all(marker_of(&run)).unwrap(), + } + let (g, _) = start_at(&cfg, &run, &keep, stamp("second", RTC0, false), |_| {}); + assert_eq!(g.speakers.iter().all(|s| s.hard), latched, "{why}"); + } + // no boot id now: any marker counts + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + std::fs::write(marker_of(&run), "first\n").unwrap(); + let mut now = stamp("x", RTC0, false); + now.boot_id = None; + let (g, _) = start_at(&cfg, &run, &keep, now, |_| {}); + assert!(g.speakers.iter().all(|s| s.hard), "a marker was set aside without a boot id"); +} + +/// A kernel override of the safe level refuses the evidence start +/// (speakersafetyd's flag latches every start, guard.rs). +#[test] +fn a_protection_override_refuses_the_evidence_start() { + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + let (g, _) = start_at(&cfg, &run, &keep, stamp("second", RTC0, false), |hw| hw.overridden = Some("please_blow_up_my_speakers is 1".into())); + assert!(g.speakers.iter().all(|s| s.hard), "an override did not latch the start"); +} + +/// The override check itself, on files: a missing parameter or flag is no +/// override; 0/N is none; anything else, or an unreadable one, is one. +#[test] +fn protection_override_reads_flags_and_parameters() { + let dir = missing_state().unwrap().parent().unwrap().to_path_buf(); + let p = dir.join("param"); + let flag = dir.join("flag"); + let (ps, fs) = (p.to_str().unwrap(), flag.to_str().unwrap()); + assert_eq!(boot::protection_override(&[fs], &[ps]), None); + for (v, set) in [("0\n", false), ("N\n", false), ("1\n", true), ("Y\n", true), ("-1\n", true)] { + std::fs::write(&p, v).unwrap(); + assert_eq!(boot::protection_override(&[fs], &[ps]).is_some(), set, "{v:?}"); + } + std::fs::remove_file(&p).unwrap(); + std::fs::create_dir_all(&p).unwrap(); + assert!(boot::protection_override(&[fs], &[ps]).is_some(), "an unreadable parameter"); + std::fs::remove_dir(&p).unwrap(); + std::fs::write(&flag, "").unwrap(); + assert!(boot::protection_override(&[fs], &[ps]).is_some(), "speakersafetyd's flag"); +} + +/// A chassis sensor over the model's ambient is the bound's ambient, not +/// only a floor: the magnet starts at least at M* for that ambient +/// (cooled for the uptime), above the floor alone. +#[test] +fn a_hot_chassis_raises_the_ambient_of_the_bound() { + let cfg = j700(); + let (base, _) = boot_with(&cfg, None, stamp("second", RTC0, false), None); + let (warm, _) = boot_with(&cfg, None, stamp("second", RTC0, false), Some(65.0)); + let r = 26.0 / 38.0; + let m_star = |ta: f64| (ta + r * 135.0) / (1.0 + r); + // the floor alone (67 C) is under the 50 C ambient's bound + assert!(magnet(&base) > 67.0 + 10.0); + assert!(magnet(&warm) >= magnet(&base) + (m_star(65.0) - m_star(50.0)) - 0.5, "{} against {}", magnet(&warm), magnet(&base)); +} + +// ---- C2 of the 2026-10-31 safety review: the evidence start only where +// every owner governs one model. + +/// Of every profile, only the Neo's has one model shared with every other +/// owner; a V/I machine, or the Neo under another governor or a guard, +/// has not. +#[test] +fn only_one_model_profiles_take_the_evidence_start() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("conf/apple"); + let mut seen = 0; + for e in std::fs::read_dir(&dir).unwrap().flatten() { + let board = e.file_name().to_string_lossy().trim_end_matches(".conf").to_string(); + let cfg = Config::parse(&std::fs::read_to_string(e.path()).unwrap()).unwrap_or_else(|e| panic!("{board}: {e}")); + assert_eq!(one_model(&cfg), board == "j700", "{board}"); + seen += 1; + } + assert!(seen >= 35, "{seen} profiles"); + let mut cfg = j700(); + cfg.globals.governor = Governor::Unified; + assert!(!one_model(&cfg)); + let mut cfg = j700(); + cfg.globals.guard = Some(Governor::Asahi); + assert!(!one_model(&cfg)); +} + +/// A V/I machine with no /run state starts latched although `evidence` +/// is its default, and writes no evidence record at a clean stop. +#[test] +fn a_vi_machine_starts_latched_under_evidence() { + let cfg = super::tests::j413(); + assert_eq!(cfg.globals.boot_resume, BootResume::Evidence); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + let mut hw = FakeHw::per_speaker(&cfg); + hw.boot = UPTIME; + hw.stamp = stamp("second", RTC0, false); + hw.machine = Some("m".into()); + let g = Guard::start_persist(&mut hw, &cfg, 20.0, Some(run), Some(keep.clone())).unwrap(); + assert!(g.speakers.iter().all(|s| s.hard), "a V/I machine started from evidence"); + assert!(g.checkpoint.is_none(), "a V/I machine checkpoints for an evidence start"); +} + +/// The marker sits outside the /run state's directory (the unit's +/// RuntimeDirectory): `systemctl clean --what=runtime` or removing the +/// directory after an unlock leaves it, and the next start of the boot is +/// latched (non-blocking note 1 of the round 2 safety review). +#[test] +fn the_marker_survives_the_runtime_directory() { + assert_eq!(boot::marker_path(std::path::Path::new("/run/speakerguardd/state")), std::path::Path::new("/run/speakerguardd.unlocked")); + assert_eq!(boot::marker_path(std::path::Path::new("state")), std::path::Path::new("unlocked")); + let cfg = j700(); + let (run, keep) = (missing_state().unwrap(), missing_state().unwrap()); + let (mut g, mut hw) = start_at(&cfg, &run, &keep, stamp("second", RTC0, false), |_| {}); + run_until(&mut g, &mut hw, secs(2.0)).unwrap(); + assert!(g.armed()); + drop(g); + std::fs::remove_dir_all(run.parent().unwrap()).unwrap(); + assert!(marker_of(&run).exists(), "removing the runtime directory took the marker"); + let (g2, _) = start_at(&cfg, &run, &keep, stamp("second", RTC0 + 10, false), |_| {}); + assert!(g2.speakers.iter().all(|s| s.hard), "the start after the runtime directory was removed was not latched"); + let _ = std::fs::remove_file(marker_of(&run)); +} diff --git a/src/main.rs b/src/main.rs index 6c339fde..5f523993 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,7 @@ //! its safe volume, and the daemon takes the lock back once it can. mod alsa; +mod boot; mod config; mod engine; mod guard; @@ -126,7 +127,7 @@ fn usage() -> ! { --wait-for-card Wait for card discovery before failing (default 30; 0 disables waiting)\n \ -m, --max-reduction Historical recording threshold, accepted for compatibility (writes use the hardware range)\n \ -s, --state Model state kept across restarts (default /run/speakerguardd/state)\n \ - --persist Model state kept across a reboot, with boot_resume = idle (default /var/lib/speakerguardd/state; empty: never kept or resumed, still removed)\n \ + --persist The last run's record for the next boot (boot_resume = evidence or idle; default /var/lib/speakerguardd/state; empty: every boot starts latched, the file still removed)\n \ --governor legacy, asahi or unified (default: the config's, else legacy)\n \ --guard asahi: the unified governor's card also gets the asahi governor's reductions (default: the config's, else none)\n \ --shadow Run every governor and log them to shadow.jsonl next to the state\n \ @@ -575,6 +576,16 @@ impl Hw for RealHw { fn events_available(&self) -> bool { self.card.events } + fn stamp(&self) -> boot::Stamp { + boot::read_stamp() + } + fn chassis(&self) -> Option { + boot::chassis_temperature(std::path::Path::new("/sys/class/hwmon")) + } + fn protection_override(&self) -> Option { + // speakersafetyd's flags are checked for every start (guard.rs) + boot::protection_override(&[], boot::OVERRIDE_PARAMS) + } fn wall(&self) -> persist::Wall { let realtime = wallclock::synchronized_realtime(); let synced = realtime.is_some(); diff --git a/src/model.rs b/src/model.rs index 88a06326..64d8bd32 100644 --- a/src/model.rs +++ b/src/model.rs @@ -330,6 +330,39 @@ impl SpeakerState { self.history_s = 60.0; } + /// The first start of a boot from evidence (boot.rs): the hottest a + /// past that kept the coil under its limit can have left it, `saved` + /// (coil, magnet, 60 s mean of the last run's record) narrowing the + /// magnet, `d` the longest another owner can have had since, at least + /// `uptime` at the card's safe level since, and no colder than + /// `floor`. The budgets hold the safe level for the uptime and before + /// it the most a protected coil can have taken in the rest of the + /// minute (or the record's, if more). Latched only at the limit. + pub fn assume_evidence(&mut self, globals: &Globals, saved: Option<(f64, f64, f64)>, d: Option, uptime: f64, floor: f64) { + use crate::boot::{budget_history, protected_energy, start_bound_in, SENSOR_MARGIN_K}; + self.configure_voltage(globals); + let s = &self.spec; + let ta = globals.t_ambient; + // a chassis sensor over the model's ambient raises the ambient the + // bound relaxes toward, not only the floor (`floor` is the sensor + // plus its margin) + let ta_hi = if floor.is_finite() { ta.max(floor - SENSOR_MARGIN_K) } else { ta }; + let th = crate::engine::Thermal::new(s.tr_coil, s.tau_coil, s.tr_magnet, s.tau_magnet, ta_hi); + let safe = self.worst_case_power(globals.safe_reduction); + let (c, m) = start_bound_in(&th, s.t_limit, ta_hi, ta, safe, uptime, saved.map(|x| (x.0, x.1)), d); + self.t_coil = c.max(floor); + self.t_magnet = m.max(floor); + self.t_peak = self.t_coil; + self.hard = !(self.t_peak < s.t_limit); + self.reduction_db = 0.0; + self.reducing = false; + let len = 60.0 - uptime.clamp(0.0, 60.0); + let older = protected_energy(&th, s.t_limit, ta, len).max(saved.map_or(0.0, |x| 60.0 * x.2)).min(self.worst_case_power(0.0) * len); + self.history = budget_history(uptime, safe, older).into_iter().collect(); + self.history_s = self.history.iter().map(|e| e.0).sum(); + self.playback_means = None; + } + /// The steady state at `power` watts, as if it had run for ever; the /// budgets see it as a minute at `pre` watts before the gain. pub fn settle_at(&mut self, power: f64, pre: f64, t_ambient: f64) { diff --git a/src/record.rs b/src/record.rs index 945a66dc..ea4f9b14 100644 --- a/src/record.rs +++ b/src/record.rs @@ -109,7 +109,8 @@ pub fn fingerprint(cfg: &Config) -> u64 { globals = globals.replace(", amp_gain_index: None", ""); // nor a file on the default boot_resume (the recordings made before // the key existed still match) - globals = globals.replace(", boot_resume: Latched", ""); + // (and the boot start, which says nothing of what a recording holds) + globals = globals.replace(", boot_resume: Latched", "").replace(", boot_resume: Evidence", ""); // nor does a speaker without its own z_min let speakers = format!("{:?}", cfg.speakers).replace(", z_min_override: None", ""); let text = format!("{globals}{:?}{speakers}", cfg.controls);