synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / bounds.rs
| 1 | //! Host bound probes: ADR 0003 section 9 step A0 (experiment X0, section 6.4). |
| 2 | //! |
| 3 | //! Measures the host inputs of the section 6.2 bounds: memory bandwidth (every core |
| 4 | //! streaming a read and a copy), device read and write bandwidth (sequential |
| 5 | //! `O_DIRECT` on the store's filesystem; writes are timed through `fdatasync`), |
| 6 | //! all-core SHA-256 throughput (the `sha2` crate Synapse uses, and the CPU's SHA-2 |
| 7 | //! instructions), and all-core Ed25519 verification throughput (`ed25519-dalek`, the |
| 8 | //! implementation Synapse uses). The flush time is not measured again: it is taken from |
| 9 | //! W1's sealed `floor.json` (Phase 5), pinned by its SHA-256 in the protocol. |
| 10 | //! |
| 11 | //! Evidence discipline: |
| 12 | //! - `protocol.json` fixes the repetitions, the central, spread, and bound statistics, |
| 13 | //! and every probe size before the run. The raw data carries the protocol's SHA-256, |
| 14 | //! and every run must have exactly the work the protocol fixed. |
| 15 | //! - `raw.json` holds integers only (nanoseconds, work units, microjoule counter |
| 16 | //! readings), so `report.json` is a pure function of the protocol and raw bytes, and |
| 17 | //! [`verify_evidence`] recomputes it byte for byte and checks every file listed in |
| 18 | //! `SHA256SUMS`. That proves consistency only; authenticity comes from |
| 19 | //! the git history and review of the sealing commit. |
| 20 | //! - A repetition marked `error` is excluded and counted in the report; protocol v1 |
| 21 | //! allows none, so any excluded repetition refuses the report. |
| 22 | //! - Rates measured here are labelled achieved (a lower bound on the hardware's |
| 23 | //! capability), never the bound itself; see [`BoundInputKind`]. |
| 24 | //! - Energy preflight runs before anything else: without a working `aien_spbm` meter |
| 25 | //! the run refuses with `INSTRUMENT_UNAVAILABLE` and writes nothing. |
| 26 | //! |
| 27 | //! The figures are measurements, not targets; no test asserts a speed. |
| 28 | |
| 29 | use crate::energy::{Spbm, COUNTER_WRAP_UJ, MAX_SAMPLE_GAP, SAMPLE_PERIOD, SENSOR_PERIOD_S}; |
| 30 | use crate::floor::FloorReport; |
| 31 | use crate::host::{collect_host_info, HostInfo}; |
| 32 | use crate::stats::LatencySummary; |
| 33 | use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; |
| 34 | use serde::{Deserialize, Serialize}; |
| 35 | use sha2::{Digest, Sha256}; |
| 36 | use std::fmt; |
| 37 | use std::fs::{self, File, OpenOptions}; |
| 38 | use std::hint::black_box; |
| 39 | use std::io::Write; |
| 40 | use std::os::unix::fs::{FileExt, OpenOptionsExt}; |
| 41 | use std::path::{Path, PathBuf}; |
| 42 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 43 | use std::sync::{Arc, Barrier, Mutex}; |
| 44 | use std::time::{Duration, Instant}; |
| 45 | |
| 46 | /// Refusal code when the energy meter is missing or not counting (ADR 0003 section 6.2). |
| 47 | pub const INSTRUMENT_UNAVAILABLE: &str = "INSTRUMENT_UNAVAILABLE"; |
| 48 | pub const PROTOCOL_SCHEMA: &str = "synapse-bench/a0-host-bounds-protocol/v1"; |
| 49 | pub const RAW_SCHEMA: &str = "synapse-bench/a0-host-bounds-raw/v1"; |
| 50 | pub const REPORT_SCHEMA: &str = "synapse-bench/a0-host-bounds-report/v2"; |
| 51 | /// A range needs at least three repetitions to say anything about spread. |
| 52 | pub const MIN_REPETITIONS: u32 = 3; |
| 53 | pub const PROTOCOL_FILE: &str = "protocol.json"; |
| 54 | pub const RAW_FILE: &str = "raw.json"; |
| 55 | pub const REPORT_FILE: &str = "report.json"; |
| 56 | /// Checksums of the sealed files, in the `sha256sum` format. |
| 57 | pub const SUMS_FILE: &str = "SHA256SUMS"; |
| 58 | /// Repetitions a protocol v1 run may exclude (runs marked `error`). v1 has no |
| 59 | /// allowance field, so none: any errored repetition refuses the report. |
| 60 | pub const MAX_EXCLUDED_REPETITIONS: u32 = 0; |
| 61 | |
| 62 | const ENERGY_LABELS: [&str; 3] = ["pkg", "cpu_e", "cpu_p"]; |
| 63 | const DIRECT_IO_ALIGN: usize = 4096; |
| 64 | const ED25519_ITEMS_PER_THREAD: usize = 16; |
| 65 | |
| 66 | // --------------------------------------------------------------------------------- |
| 67 | // Refusals and verification errors |
| 68 | // --------------------------------------------------------------------------------- |
| 69 | |
| 70 | /// Why a run refused to produce figures. |
| 71 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 72 | pub enum BoundsRefusal { |
| 73 | InstrumentUnavailable(String), |
| 74 | ProtocolInvalid(String), |
| 75 | HostMismatch(String), |
| 76 | W1SourceMismatch(String), |
| 77 | EvidenceExists(String), |
| 78 | Io(String), |
| 79 | } |
| 80 | |
| 81 | impl BoundsRefusal { |
| 82 | pub fn code(&self) -> &'static str { |
| 83 | match self { |
| 84 | Self::InstrumentUnavailable(_) => INSTRUMENT_UNAVAILABLE, |
| 85 | Self::ProtocolInvalid(_) => "PROTOCOL_INVALID", |
| 86 | Self::HostMismatch(_) => "HOST_MISMATCH", |
| 87 | Self::W1SourceMismatch(_) => "W1_SOURCE_MISMATCH", |
| 88 | Self::EvidenceExists(_) => "EVIDENCE_EXISTS", |
| 89 | Self::Io(_) => "IO_FAILURE", |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | pub fn detail(&self) -> &str { |
| 94 | match self { |
| 95 | Self::InstrumentUnavailable(d) |
| 96 | | Self::ProtocolInvalid(d) |
| 97 | | Self::HostMismatch(d) |
| 98 | | Self::W1SourceMismatch(d) |
| 99 | | Self::EvidenceExists(d) |
| 100 | | Self::Io(d) => d, |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl fmt::Display for BoundsRefusal { |
| 106 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 107 | write!(f, "{}: {}", self.code(), self.detail()) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// Why sealed evidence failed verification. |
| 112 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 113 | pub enum VerifyError { |
| 114 | Io(String), |
| 115 | Parse(String), |
| 116 | ProtocolInvalid(String), |
| 117 | ProtocolDigestMismatch { protocol: String, raw_names: String }, |
| 118 | RepetitionMismatch(String), |
| 119 | WorkMismatch(String), |
| 120 | ReportMismatch { first_difference_at: usize }, |
| 121 | ExcludedRepetitions(String), |
| 122 | ChecksumsMissing(String), |
| 123 | ChecksumMismatch(String), |
| 124 | } |
| 125 | |
| 126 | impl fmt::Display for VerifyError { |
| 127 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 128 | match self { |
| 129 | Self::Io(d) => write!(f, "IO_FAILURE: {d}"), |
| 130 | Self::Parse(d) => write!(f, "PARSE_FAILURE: {d}"), |
| 131 | Self::ProtocolInvalid(d) => write!(f, "PROTOCOL_INVALID: {d}"), |
| 132 | Self::ProtocolDigestMismatch { |
| 133 | protocol, |
| 134 | raw_names, |
| 135 | } => write!( |
| 136 | f, |
| 137 | "PROTOCOL_DIGEST_MISMATCH: protocol.json is {protocol}, raw.json names {raw_names}" |
| 138 | ), |
| 139 | Self::RepetitionMismatch(d) => write!(f, "REPETITION_MISMATCH: {d}"), |
| 140 | Self::WorkMismatch(d) => write!(f, "WORK_MISMATCH: {d}"), |
| 141 | Self::ReportMismatch { |
| 142 | first_difference_at, |
| 143 | } => write!( |
| 144 | f, |
| 145 | "REPORT_MISMATCH: recomputed report differs from report.json at byte {first_difference_at}" |
| 146 | ), |
| 147 | Self::ExcludedRepetitions(d) => write!(f, "EXCLUDED_REPETITIONS: {d}"), |
| 148 | Self::ChecksumsMissing(d) => write!(f, "CHECKSUMS_MISSING: {d}"), |
| 149 | Self::ChecksumMismatch(d) => write!(f, "CHECKSUM_MISMATCH: {d}"), |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | // --------------------------------------------------------------------------------- |
| 155 | // Protocol (fixed before the runs) |
| 156 | // --------------------------------------------------------------------------------- |
| 157 | |
| 158 | /// Central statistic across repetitions. |
| 159 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 160 | #[serde(rename_all = "snake_case")] |
| 161 | pub enum CentralStatistic { |
| 162 | /// Middle value; mean of the two middle values for an even count. |
| 163 | Median, |
| 164 | } |
| 165 | |
| 166 | /// Spread statistic across repetitions. |
| 167 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 168 | #[serde(rename_all = "snake_case")] |
| 169 | pub enum SpreadStatistic { |
| 170 | /// Minimum and maximum. |
| 171 | Range, |
| 172 | } |
| 173 | |
| 174 | /// Which repetition value becomes the bound input. |
| 175 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 176 | #[serde(rename_all = "snake_case")] |
| 177 | pub enum BoundStatistic { |
| 178 | /// The highest rate any repetition reached: the host demonstrably did at least that. |
| 179 | MaxRate, |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 183 | #[serde(deny_unknown_fields)] |
| 184 | pub struct MemoryParams { |
| 185 | pub bytes_per_thread: u64, |
| 186 | pub passes: u64, |
| 187 | } |
| 188 | |
| 189 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 190 | #[serde(deny_unknown_fields)] |
| 191 | pub struct DeviceParams { |
| 192 | pub file_bytes: u64, |
| 193 | pub chunk_bytes: u64, |
| 194 | pub threads: u32, |
| 195 | } |
| 196 | |
| 197 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 198 | #[serde(deny_unknown_fields)] |
| 199 | pub struct HashParams { |
| 200 | pub block_bytes: u64, |
| 201 | pub blocks_per_thread: u64, |
| 202 | } |
| 203 | |
| 204 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 205 | #[serde(deny_unknown_fields)] |
| 206 | pub struct VerifyParams { |
| 207 | pub message_bytes: u64, |
| 208 | pub verifications_per_thread: u64, |
| 209 | } |
| 210 | |
| 211 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 212 | #[serde(deny_unknown_fields)] |
| 213 | pub struct PreflightParams { |
| 214 | pub observe_ms: u64, |
| 215 | pub min_counter_changes: u32, |
| 216 | } |
| 217 | |
| 218 | /// W1's sealed flush measurement, pinned by digest. |
| 219 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 220 | #[serde(deny_unknown_fields)] |
| 221 | pub struct W1Source { |
| 222 | /// Path relative to the repository root. |
| 223 | pub path: String, |
| 224 | /// Lowercase hex SHA-256 of the file. |
| 225 | pub sha256: String, |
| 226 | /// `floor.json` storage probe names to carry into the report. |
| 227 | pub probes: Vec<String>, |
| 228 | } |
| 229 | |
| 230 | /// Everything fixed before the runs. |
| 231 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 232 | #[serde(deny_unknown_fields)] |
| 233 | pub struct Protocol { |
| 234 | pub schema: String, |
| 235 | pub repetitions: u32, |
| 236 | pub central_statistic: CentralStatistic, |
| 237 | pub spread_statistic: SpreadStatistic, |
| 238 | pub bound_statistic: BoundStatistic, |
| 239 | /// Threads for the memory, hashing, and verification probes (one per CPU). |
| 240 | pub threads: u32, |
| 241 | pub idle_ms: u64, |
| 242 | pub memory: MemoryParams, |
| 243 | pub device: DeviceParams, |
| 244 | pub sha256: HashParams, |
| 245 | pub ed25519: VerifyParams, |
| 246 | pub energy_preflight: PreflightParams, |
| 247 | pub w1_flush: W1Source, |
| 248 | } |
| 249 | |
| 250 | impl Protocol { |
| 251 | /// Parse and validate protocol bytes. |
| 252 | pub fn parse(bytes: &[u8]) -> Result<Self, String> { |
| 253 | let p: Protocol = serde_json::from_slice(bytes).map_err(|e| format!("parse: {e}"))?; |
| 254 | p.validate()?; |
| 255 | Ok(p) |
| 256 | } |
| 257 | |
| 258 | pub fn validate(&self) -> Result<(), String> { |
| 259 | let fail = |why: &str| Err(why.to_string()); |
| 260 | if self.schema != PROTOCOL_SCHEMA { |
| 261 | return Err(format!( |
| 262 | "schema {:?}, expected {PROTOCOL_SCHEMA:?}", |
| 263 | self.schema |
| 264 | )); |
| 265 | } |
| 266 | if self.repetitions < MIN_REPETITIONS { |
| 267 | return Err(format!( |
| 268 | "{} repetitions; a range needs at least {MIN_REPETITIONS}", |
| 269 | self.repetitions |
| 270 | )); |
| 271 | } |
| 272 | if self.threads == 0 || self.device.threads == 0 { |
| 273 | return fail("thread counts must be positive"); |
| 274 | } |
| 275 | if self.idle_ms == 0 { |
| 276 | return fail("idle_ms must be positive"); |
| 277 | } |
| 278 | let m = &self.memory; |
| 279 | if m.bytes_per_thread == 0 || !m.bytes_per_thread.is_multiple_of(8) || m.passes == 0 { |
| 280 | return fail( |
| 281 | "memory: bytes_per_thread must be a positive multiple of 8 and passes positive", |
| 282 | ); |
| 283 | } |
| 284 | let d = &self.device; |
| 285 | if d.chunk_bytes == 0 || !d.chunk_bytes.is_multiple_of(DIRECT_IO_ALIGN as u64) { |
| 286 | return fail("device: chunk_bytes must be a positive multiple of 4096 (O_DIRECT)"); |
| 287 | } |
| 288 | if d.file_bytes == 0 |
| 289 | || !d |
| 290 | .file_bytes |
| 291 | .is_multiple_of(d.chunk_bytes * u64::from(d.threads)) |
| 292 | { |
| 293 | return fail( |
| 294 | "device: file_bytes must be a positive multiple of chunk_bytes times threads", |
| 295 | ); |
| 296 | } |
| 297 | if self.sha256.block_bytes == 0 || self.sha256.blocks_per_thread == 0 { |
| 298 | return fail("sha256: block_bytes and blocks_per_thread must be positive"); |
| 299 | } |
| 300 | if self.ed25519.message_bytes == 0 || self.ed25519.verifications_per_thread == 0 { |
| 301 | return fail("ed25519: message_bytes and verifications_per_thread must be positive"); |
| 302 | } |
| 303 | let e = &self.energy_preflight; |
| 304 | if e.observe_ms == 0 || e.min_counter_changes == 0 { |
| 305 | return fail("energy_preflight: observe_ms and min_counter_changes must be positive"); |
| 306 | } |
| 307 | let w = &self.w1_flush; |
| 308 | let hex64 = w.sha256.len() == 64 |
| 309 | && w.sha256 |
| 310 | .bytes() |
| 311 | .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); |
| 312 | if w.path.is_empty() || !hex64 || w.probes.is_empty() { |
| 313 | return fail( |
| 314 | "w1_flush: path, a lowercase hex SHA-256, and at least one probe are required", |
| 315 | ); |
| 316 | } |
| 317 | Ok(()) |
| 318 | } |
| 319 | |
| 320 | /// Work units every run of `probe` must report (fixed by the protocol). |
| 321 | pub fn expected_units(&self, probe: ProbeKind) -> u64 { |
| 322 | let t = u64::from(self.threads); |
| 323 | match probe { |
| 324 | ProbeKind::Idle => 0, |
| 325 | ProbeKind::MemoryRead => t * self.memory.bytes_per_thread * self.memory.passes, |
| 326 | ProbeKind::MemoryCopy => 2 * t * self.memory.bytes_per_thread * self.memory.passes, |
| 327 | ProbeKind::DeviceWrite | ProbeKind::DeviceRead => self.device.file_bytes, |
| 328 | ProbeKind::Sha256Sha2Crate | ProbeKind::Sha256ArmInstructions => { |
| 329 | t * self.sha256.block_bytes * self.sha256.blocks_per_thread |
| 330 | } |
| 331 | ProbeKind::Ed25519Verify => t * self.ed25519.verifications_per_thread, |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// Threads every run of `probe` must use. |
| 336 | pub fn expected_threads(&self, probe: ProbeKind) -> u32 { |
| 337 | match probe { |
| 338 | ProbeKind::Idle => 0, |
| 339 | ProbeKind::DeviceWrite | ProbeKind::DeviceRead => self.device.threads, |
| 340 | _ => self.threads, |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // --------------------------------------------------------------------------------- |
| 346 | // Probes |
| 347 | // --------------------------------------------------------------------------------- |
| 348 | |
| 349 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 350 | #[serde(rename_all = "snake_case")] |
| 351 | pub enum ProbeKind { |
| 352 | Idle, |
| 353 | MemoryRead, |
| 354 | MemoryCopy, |
| 355 | DeviceWrite, |
| 356 | DeviceRead, |
| 357 | Sha256Sha2Crate, |
| 358 | Sha256ArmInstructions, |
| 359 | Ed25519Verify, |
| 360 | } |
| 361 | |
| 362 | /// Order of probes inside every repetition. |
| 363 | pub const PROBE_ORDER: [ProbeKind; 8] = [ |
| 364 | ProbeKind::Idle, |
| 365 | ProbeKind::MemoryRead, |
| 366 | ProbeKind::MemoryCopy, |
| 367 | ProbeKind::DeviceWrite, |
| 368 | ProbeKind::DeviceRead, |
| 369 | ProbeKind::Sha256Sha2Crate, |
| 370 | ProbeKind::Sha256ArmInstructions, |
| 371 | ProbeKind::Ed25519Verify, |
| 372 | ]; |
| 373 | |
| 374 | impl ProbeKind { |
| 375 | pub fn unit(self) -> &'static str { |
| 376 | match self { |
| 377 | Self::Idle => "none", |
| 378 | Self::Ed25519Verify => "verification", |
| 379 | _ => "byte", |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | pub fn description(self) -> &'static str { |
| 384 | match self { |
| 385 | Self::Idle => "harness sleeps; other tenants keep running (idle baseline power)", |
| 386 | Self::MemoryRead => "every thread sums its own buffer of u64 words, one thread pinned per CPU", |
| 387 | Self::MemoryCopy => "every thread copies its own buffer into a second one; units count bytes read plus bytes written", |
| 388 | Self::DeviceWrite => "sequential O_DIRECT overwrite of an already written file, one region per thread, each thread ends with fdatasync", |
| 389 | Self::DeviceRead => "sequential O_DIRECT read of the same file, one region per thread, read-back pattern checked", |
| 390 | Self::Sha256Sha2Crate => "every thread hashes one block repeatedly with the sha2 crate as Synapse builds it", |
| 391 | Self::Sha256ArmInstructions => "every thread hashes one block repeatedly with the CPU's SHA-2 instructions (checked against the sha2 crate first)", |
| 392 | Self::Ed25519Verify => "every thread verifies prepared Ed25519 signatures with ed25519-dalek as Synapse builds it", |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// Elapsed wall time and work units of one timed probe. |
| 398 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 399 | pub struct Timed { |
| 400 | pub elapsed_ns: u64, |
| 401 | pub units: u64, |
| 402 | } |
| 403 | |
| 404 | fn pin_current_thread(cpu: usize) { |
| 405 | // SAFETY: `set` is a zeroed cpu_set_t; CPU_SET and sched_setaffinity(0, ...) only |
| 406 | // touch it and the calling thread's affinity. Failure leaves the thread unpinned. |
| 407 | unsafe { |
| 408 | let mut set: libc::cpu_set_t = std::mem::zeroed(); |
| 409 | libc::CPU_SET(cpu, &mut set); |
| 410 | let _ = libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | /// Run `work` on one thread per state, all released together; time from release until |
| 415 | /// the last thread finishes. Each thread is pinned to CPU `index % online CPUs`. |
| 416 | pub fn timed_parallel<S: Send>( |
| 417 | states: &mut [S], |
| 418 | work: impl Fn(usize, &mut S) -> Result<u64, String> + Sync, |
| 419 | ) -> Result<Timed, String> { |
| 420 | let n = states.len(); |
| 421 | let cpus = std::thread::available_parallelism().map_or(1, |c| c.get()); |
| 422 | let start = Barrier::new(n + 1); |
| 423 | let end = Barrier::new(n + 1); |
| 424 | let (elapsed, results) = std::thread::scope(|s| { |
| 425 | let handles: Vec<_> = states |
| 426 | .iter_mut() |
| 427 | .enumerate() |
| 428 | .map(|(i, st)| { |
| 429 | let (start, end, work) = (&start, &end, &work); |
| 430 | s.spawn(move || { |
| 431 | pin_current_thread(i % cpus); |
| 432 | start.wait(); |
| 433 | let r = work(i, st); |
| 434 | end.wait(); |
| 435 | r |
| 436 | }) |
| 437 | }) |
| 438 | .collect(); |
| 439 | start.wait(); |
| 440 | let t = Instant::now(); |
| 441 | end.wait(); |
| 442 | let elapsed = t.elapsed(); |
| 443 | let results: Vec<Result<u64, String>> = handles |
| 444 | .into_iter() |
| 445 | .map(|h| { |
| 446 | h.join() |
| 447 | .unwrap_or_else(|_| Err("probe thread panicked".into())) |
| 448 | }) |
| 449 | .collect(); |
| 450 | (elapsed, results) |
| 451 | }); |
| 452 | let mut units = 0u64; |
| 453 | for r in results { |
| 454 | units += r?; |
| 455 | } |
| 456 | Ok(Timed { |
| 457 | elapsed_ns: elapsed.as_nanos() as u64, |
| 458 | units, |
| 459 | }) |
| 460 | } |
| 461 | |
| 462 | /// Per-thread buffer for the memory read probe. |
| 463 | pub struct ReadState { |
| 464 | pub words: Vec<u64>, |
| 465 | pub checksum: u64, |
| 466 | } |
| 467 | |
| 468 | /// Buffers of `bytes_per_thread` bytes, word `j` of thread `t` holding `t * 2^32 + j`. |
| 469 | pub fn memory_read_states(threads: u32, bytes_per_thread: u64) -> Vec<ReadState> { |
| 470 | (0..u64::from(threads)) |
| 471 | .map(|t| ReadState { |
| 472 | words: (0..bytes_per_thread / 8).map(|j| (t << 32) + j).collect(), |
| 473 | checksum: 0, |
| 474 | }) |
| 475 | .collect() |
| 476 | } |
| 477 | |
| 478 | /// Every thread sums its buffer `passes` times (wrapping); the sum is kept for checking. |
| 479 | pub fn memory_read(states: &mut [ReadState], passes: u64) -> Result<Timed, String> { |
| 480 | timed_parallel(states, |_, st| { |
| 481 | let mut acc = 0u64; |
| 482 | for _ in 0..passes { |
| 483 | let words = black_box(st.words.as_slice()); |
| 484 | acc = acc.wrapping_add(words.iter().fold(0u64, |a, &w| a.wrapping_add(w))); |
| 485 | } |
| 486 | st.checksum = black_box(acc); |
| 487 | Ok(passes * st.words.len() as u64 * 8) |
| 488 | }) |
| 489 | } |
| 490 | |
| 491 | /// Per-thread buffers for the memory copy probe. |
| 492 | pub struct CopyState { |
| 493 | pub src: Vec<u64>, |
| 494 | pub dst: Vec<u64>, |
| 495 | } |
| 496 | |
| 497 | pub fn memory_copy_states(threads: u32, bytes_per_thread: u64) -> Vec<CopyState> { |
| 498 | let words = (bytes_per_thread / 8) as usize; |
| 499 | (0..u64::from(threads)) |
| 500 | .map(|t| CopyState { |
| 501 | src: (0..words as u64) |
| 502 | .map(|j| (t << 32) ^ j.wrapping_mul(31)) |
| 503 | .collect(), |
| 504 | dst: vec![u64::MAX; words], |
| 505 | }) |
| 506 | .collect() |
| 507 | } |
| 508 | |
| 509 | /// Every thread copies `src` into `dst` `passes` times; units are bytes read plus written. |
| 510 | pub fn memory_copy(states: &mut [CopyState], passes: u64) -> Result<Timed, String> { |
| 511 | timed_parallel(states, |_, st| { |
| 512 | for _ in 0..passes { |
| 513 | let src = black_box(st.src.as_slice()); |
| 514 | st.dst.copy_from_slice(src); |
| 515 | black_box(st.dst.as_mut_ptr()); |
| 516 | } |
| 517 | Ok(2 * passes * st.src.len() as u64 * 8) |
| 518 | }) |
| 519 | } |
| 520 | |
| 521 | /// A heap buffer whose usable slice starts on a 4096-byte boundary (for `O_DIRECT`). |
| 522 | pub struct AlignedBytes { |
| 523 | storage: Vec<u8>, |
| 524 | offset: usize, |
| 525 | len: usize, |
| 526 | } |
| 527 | |
| 528 | impl AlignedBytes { |
| 529 | pub fn new(len: usize, fill: u8) -> Result<Self, String> { |
| 530 | let storage = vec![fill; len + DIRECT_IO_ALIGN]; |
| 531 | let offset = storage.as_ptr().align_offset(DIRECT_IO_ALIGN); |
| 532 | if offset > DIRECT_IO_ALIGN { |
| 533 | return Err("cannot align buffer for O_DIRECT".into()); |
| 534 | } |
| 535 | Ok(Self { |
| 536 | storage, |
| 537 | offset, |
| 538 | len, |
| 539 | }) |
| 540 | } |
| 541 | |
| 542 | pub fn as_slice(&self) -> &[u8] { |
| 543 | &self.storage[self.offset..self.offset + self.len] |
| 544 | } |
| 545 | |
| 546 | pub fn as_mut_slice(&mut self) -> &mut [u8] { |
| 547 | &mut self.storage[self.offset..self.offset + self.len] |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | fn io<T>(r: std::io::Result<T>, what: &str) -> Result<T, String> { |
| 552 | r.map_err(|e| format!("{what}: {e}")) |
| 553 | } |
| 554 | |
| 555 | /// Write `bytes` of zeros to `path` and fsync, so later probes overwrite allocated blocks. |
| 556 | pub fn prepare_device_file(path: &Path, bytes: u64) -> Result<(), String> { |
| 557 | let mut f = io(File::create(path), "create device file")?; |
| 558 | let chunk = vec![0u8; 4 << 20]; |
| 559 | let mut left = bytes; |
| 560 | while left > 0 { |
| 561 | let n = left.min(chunk.len() as u64) as usize; |
| 562 | io(f.write_all(&chunk[..n]), "prewrite device file")?; |
| 563 | left -= n as u64; |
| 564 | } |
| 565 | io(f.sync_all(), "fsync device file") |
| 566 | } |
| 567 | |
| 568 | /// One thread's region of the device file. |
| 569 | pub struct DeviceState { |
| 570 | file: File, |
| 571 | buf: AlignedBytes, |
| 572 | offset: u64, |
| 573 | chunks: u64, |
| 574 | } |
| 575 | |
| 576 | fn device_states( |
| 577 | path: &Path, |
| 578 | p: &DeviceParams, |
| 579 | write: bool, |
| 580 | fill: u8, |
| 581 | ) -> Result<Vec<DeviceState>, String> { |
| 582 | let region = p.file_bytes / u64::from(p.threads); |
| 583 | (0..u64::from(p.threads)) |
| 584 | .map(|t| { |
| 585 | let mut o = OpenOptions::new(); |
| 586 | if write { |
| 587 | o.write(true); |
| 588 | } else { |
| 589 | o.read(true); |
| 590 | } |
| 591 | let file = io( |
| 592 | o.custom_flags(libc::O_DIRECT).open(path), |
| 593 | "open device file O_DIRECT", |
| 594 | )?; |
| 595 | Ok(DeviceState { |
| 596 | file, |
| 597 | buf: AlignedBytes::new(p.chunk_bytes as usize, fill)?, |
| 598 | offset: t * region, |
| 599 | chunks: region / p.chunk_bytes, |
| 600 | }) |
| 601 | }) |
| 602 | .collect() |
| 603 | } |
| 604 | |
| 605 | /// Overwrite the whole file with `pattern` (each thread its region), each thread |
| 606 | /// ending with `fdatasync`; the time includes the flushes. |
| 607 | pub fn device_write(path: &Path, p: &DeviceParams, pattern: u8) -> Result<Timed, String> { |
| 608 | let mut states = device_states(path, p, true, pattern)?; |
| 609 | timed_parallel(&mut states, |_, st| { |
| 610 | let len = st.buf.as_slice().len() as u64; |
| 611 | for k in 0..st.chunks { |
| 612 | io( |
| 613 | st.file.write_all_at(st.buf.as_slice(), st.offset + k * len), |
| 614 | "O_DIRECT write", |
| 615 | )?; |
| 616 | } |
| 617 | io(st.file.sync_data(), "fdatasync")?; |
| 618 | Ok(st.chunks * len) |
| 619 | }) |
| 620 | } |
| 621 | |
| 622 | /// Read the whole file (each thread its region) and check that every chunk starts and |
| 623 | /// ends with `pattern`. |
| 624 | pub fn device_read(path: &Path, p: &DeviceParams, pattern: u8) -> Result<Timed, String> { |
| 625 | let mut states = device_states(path, p, false, !pattern)?; |
| 626 | timed_parallel(&mut states, |_, st| { |
| 627 | let len = st.buf.as_slice().len() as u64; |
| 628 | for k in 0..st.chunks { |
| 629 | let off = st.offset + k * len; |
| 630 | io( |
| 631 | st.file.read_exact_at(st.buf.as_mut_slice(), off), |
| 632 | "O_DIRECT read", |
| 633 | )?; |
| 634 | let b = st.buf.as_slice(); |
| 635 | if b[0] != pattern || b[b.len() - 1] != pattern { |
| 636 | return Err(format!("read-back mismatch at offset {off}")); |
| 637 | } |
| 638 | } |
| 639 | Ok(st.chunks * len) |
| 640 | }) |
| 641 | } |
| 642 | |
| 643 | /// Per-thread block for the hashing probes. |
| 644 | pub struct HashState { |
| 645 | pub block: Vec<u8>, |
| 646 | pub last: [u8; 32], |
| 647 | } |
| 648 | |
| 649 | pub fn hash_states(threads: u32, block_bytes: u64) -> Vec<HashState> { |
| 650 | (0..threads) |
| 651 | .map(|t| HashState { |
| 652 | block: (0..block_bytes) |
| 653 | .map(|j| (j as u8).wrapping_mul(13) ^ t as u8) |
| 654 | .collect(), |
| 655 | last: [0u8; 32], |
| 656 | }) |
| 657 | .collect() |
| 658 | } |
| 659 | |
| 660 | /// Every thread hashes its block `blocks` times with the `sha2` crate. |
| 661 | pub fn sha256_sha2_crate(states: &mut [HashState], blocks: u64) -> Result<Timed, String> { |
| 662 | timed_parallel(states, |_, st| { |
| 663 | for _ in 0..blocks { |
| 664 | st.last = Sha256::digest(black_box(st.block.as_slice())).into(); |
| 665 | } |
| 666 | Ok(blocks * st.block.len() as u64) |
| 667 | }) |
| 668 | } |
| 669 | |
| 670 | /// Every thread hashes its block `blocks` times with the CPU's SHA-2 instructions, after |
| 671 | /// checking that they give the `sha2` crate's digest for that block. |
| 672 | pub fn sha256_arm_instructions(states: &mut [HashState], blocks: u64) -> Result<Timed, String> { |
| 673 | for st in states.iter() { |
| 674 | let want: [u8; 32] = Sha256::digest(&st.block).into(); |
| 675 | match sha256_arm(&st.block) { |
| 676 | None => return Err("CPU SHA-2 instructions not available".into()), |
| 677 | Some(d) if d != want => { |
| 678 | return Err("SHA-2 instruction digest differs from the sha2 crate".into()) |
| 679 | } |
| 680 | Some(_) => {} |
| 681 | } |
| 682 | } |
| 683 | timed_parallel(states, |_, st| { |
| 684 | for _ in 0..blocks { |
| 685 | st.last = sha256_arm(black_box(st.block.as_slice())).unwrap_or([0u8; 32]); |
| 686 | } |
| 687 | Ok(blocks * st.block.len() as u64) |
| 688 | }) |
| 689 | } |
| 690 | |
| 691 | /// Prepared signatures for one verification thread. |
| 692 | pub struct VerifyState { |
| 693 | pub items: Vec<(VerifyingKey, Vec<u8>, Signature)>, |
| 694 | } |
| 695 | |
| 696 | pub fn verify_states(threads: u32, message_bytes: u64) -> Vec<VerifyState> { |
| 697 | (0..threads) |
| 698 | .map(|t| VerifyState { |
| 699 | items: (0..ED25519_ITEMS_PER_THREAD) |
| 700 | .map(|i| { |
| 701 | let mut seed = [0u8; 32]; |
| 702 | seed[0] = t as u8; |
| 703 | seed[1] = i as u8; |
| 704 | seed[2] = 0xa0; |
| 705 | let key = SigningKey::from_bytes(&seed); |
| 706 | let msg: Vec<u8> = (0..message_bytes).map(|j| (j as u8) ^ i as u8).collect(); |
| 707 | let sig = key.sign(&msg); |
| 708 | (key.verifying_key(), msg, sig) |
| 709 | }) |
| 710 | .collect(), |
| 711 | }) |
| 712 | .collect() |
| 713 | } |
| 714 | |
| 715 | /// Every thread verifies `per_thread` signatures; any failed verification is an error. |
| 716 | pub fn ed25519_verify(states: &mut [VerifyState], per_thread: u64) -> Result<Timed, String> { |
| 717 | timed_parallel(states, |t, st| { |
| 718 | for i in 0..per_thread { |
| 719 | let (key, msg, sig) = &st.items[i as usize % st.items.len()]; |
| 720 | key.verify(black_box(msg), sig) |
| 721 | .map_err(|_| format!("thread {t}: verification {i} failed"))?; |
| 722 | } |
| 723 | Ok(per_thread) |
| 724 | }) |
| 725 | } |
| 726 | |
| 727 | // --------------------------------------------------------------------------------- |
| 728 | // SHA-256 with the Armv8 SHA-2 instructions |
| 729 | // --------------------------------------------------------------------------------- |
| 730 | |
| 731 | /// SHA-256 with the CPU's SHA-2 instructions; `None` when the CPU lacks them. |
| 732 | pub fn sha256_arm(data: &[u8]) -> Option<[u8; 32]> { |
| 733 | #[cfg(target_arch = "aarch64")] |
| 734 | { |
| 735 | if std::arch::is_aarch64_feature_detected!("sha2") { |
| 736 | // SAFETY: the `sha2` feature was detected at run time. |
| 737 | return Some(unsafe { arm::sha256(data) }); |
| 738 | } |
| 739 | } |
| 740 | let _ = data; |
| 741 | None |
| 742 | } |
| 743 | |
| 744 | #[cfg(target_arch = "aarch64")] |
| 745 | mod arm { |
| 746 | use core::arch::aarch64::*; |
| 747 | |
| 748 | const K: [u32; 64] = [ |
| 749 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, |
| 750 | 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, |
| 751 | 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, |
| 752 | 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, |
| 753 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, |
| 754 | 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, |
| 755 | 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, |
| 756 | 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, |
| 757 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, |
| 758 | 0xc67178f2, |
| 759 | ]; |
| 760 | |
| 761 | const H0: [u32; 8] = [ |
| 762 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, |
| 763 | 0x5be0cd19, |
| 764 | ]; |
| 765 | |
| 766 | /// Compress whole 64-byte blocks into `state`. |
| 767 | #[target_feature(enable = "sha2")] |
| 768 | unsafe fn compress(state: &mut [u32; 8], data: &[u8]) { |
| 769 | let mut abcd = vld1q_u32(state.as_ptr()); |
| 770 | let mut efgh = vld1q_u32(state.as_ptr().add(4)); |
| 771 | for block in data.as_chunks::<64>().0 { |
| 772 | let (abcd0, efgh0) = (abcd, efgh); |
| 773 | let p = block.as_ptr(); |
| 774 | let load = |o: usize| vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(p.add(o)))); |
| 775 | let mut w = [load(0), load(16), load(32), load(48)]; |
| 776 | for i in 0..16 { |
| 777 | let wk = vaddq_u32(w[i % 4], vld1q_u32(K.as_ptr().add(4 * i))); |
| 778 | let prev = abcd; |
| 779 | abcd = vsha256hq_u32(abcd, efgh, wk); |
| 780 | efgh = vsha256h2q_u32(efgh, prev, wk); |
| 781 | if i < 12 { |
| 782 | w[i % 4] = vsha256su1q_u32( |
| 783 | vsha256su0q_u32(w[i % 4], w[(i + 1) % 4]), |
| 784 | w[(i + 2) % 4], |
| 785 | w[(i + 3) % 4], |
| 786 | ); |
| 787 | } |
| 788 | } |
| 789 | abcd = vaddq_u32(abcd, abcd0); |
| 790 | efgh = vaddq_u32(efgh, efgh0); |
| 791 | } |
| 792 | vst1q_u32(state.as_mut_ptr(), abcd); |
| 793 | vst1q_u32(state.as_mut_ptr().add(4), efgh); |
| 794 | } |
| 795 | |
| 796 | /// # Safety |
| 797 | /// The CPU must support the Armv8 `sha2` feature. |
| 798 | #[target_feature(enable = "sha2")] |
| 799 | pub unsafe fn sha256(data: &[u8]) -> [u8; 32] { |
| 800 | let mut state = H0; |
| 801 | let full = data.len() / 64 * 64; |
| 802 | compress(&mut state, &data[..full]); |
| 803 | let rest = &data[full..]; |
| 804 | let mut tail = [0u8; 128]; |
| 805 | tail[..rest.len()].copy_from_slice(rest); |
| 806 | tail[rest.len()] = 0x80; |
| 807 | let tail_len = if rest.len() < 56 { 64 } else { 128 }; |
| 808 | let bits = (data.len() as u64).wrapping_mul(8); |
| 809 | tail[tail_len - 8..tail_len].copy_from_slice(&bits.to_be_bytes()); |
| 810 | compress(&mut state, &tail[..tail_len]); |
| 811 | let mut out = [0u8; 32]; |
| 812 | for (i, word) in state.iter().enumerate() { |
| 813 | out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes()); |
| 814 | } |
| 815 | out |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | // --------------------------------------------------------------------------------- |
| 820 | // Energy: preflight and raw sampling |
| 821 | // --------------------------------------------------------------------------------- |
| 822 | |
| 823 | /// Check the energy meter before any probe runs: the `aien_spbm` device must exist |
| 824 | /// under `hwmon_root`, the `pkg`, `cpu_e`, and `cpu_p` counters must be readable with |
| 825 | /// clear overflow flags, and `pkg` must change at least `min_counter_changes` times in |
| 826 | /// `observe_ms` without decreasing. Otherwise the run refuses with |
| 827 | /// `INSTRUMENT_UNAVAILABLE` and no figure is produced. |
| 828 | pub fn energy_preflight(hwmon_root: &Path, p: &PreflightParams) -> Result<Spbm, BoundsRefusal> { |
| 829 | let refuse = |why: String| BoundsRefusal::InstrumentUnavailable(why); |
| 830 | let spbm = Spbm::find_in(hwmon_root).ok_or_else(|| { |
| 831 | refuse(format!( |
| 832 | "no aien_spbm hwmon device under {}", |
| 833 | hwmon_root.display() |
| 834 | )) |
| 835 | })?; |
| 836 | for label in ENERGY_LABELS { |
| 837 | if spbm.energy_uj(label).is_none() { |
| 838 | return Err(refuse(format!("energy channel {label} unreadable"))); |
| 839 | } |
| 840 | match spbm.overflow_raw(label) { |
| 841 | Some(0) => {} |
| 842 | Some(v) => return Err(refuse(format!("overflow flag {v} set on {label}"))), |
| 843 | None => return Err(refuse(format!("overflow flag of {label} unreadable"))), |
| 844 | } |
| 845 | } |
| 846 | let mut last = spbm |
| 847 | .energy_uj("pkg") |
| 848 | .ok_or_else(|| refuse("pkg became unreadable".into()))?; |
| 849 | let mut changes = 0u32; |
| 850 | let start = Instant::now(); |
| 851 | while start.elapsed() < Duration::from_millis(p.observe_ms) { |
| 852 | std::thread::sleep(Duration::from_millis(1)); |
| 853 | let v = spbm |
| 854 | .energy_uj("pkg") |
| 855 | .ok_or_else(|| refuse("pkg became unreadable".into()))?; |
| 856 | if v < last { |
| 857 | return Err(refuse("pkg counter decreased during preflight".into())); |
| 858 | } |
| 859 | if v != last { |
| 860 | changes += 1; |
| 861 | last = v; |
| 862 | } |
| 863 | } |
| 864 | if changes < p.min_counter_changes { |
| 865 | return Err(refuse(format!( |
| 866 | "pkg counter changed {changes} times in {} ms; the protocol needs {}", |
| 867 | p.observe_ms, p.min_counter_changes |
| 868 | ))); |
| 869 | } |
| 870 | Ok(spbm) |
| 871 | } |
| 872 | |
| 873 | /// One meter reading: nanoseconds since the window opened and raw counters in microjoules. |
| 874 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 875 | pub struct RawEnergySample { |
| 876 | pub t_ns: u64, |
| 877 | pub pkg_uj: Option<u64>, |
| 878 | pub cpu_e_uj: Option<u64>, |
| 879 | pub cpu_p_uj: Option<u64>, |
| 880 | } |
| 881 | |
| 882 | /// Every meter reading of one window, with the overflow flags at both edges. |
| 883 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 884 | pub struct RawEnergy { |
| 885 | pub overflow_at_start: bool, |
| 886 | pub overflow_at_end: bool, |
| 887 | pub samples: Vec<RawEnergySample>, |
| 888 | } |
| 889 | |
| 890 | fn any_overflow(s: &Spbm) -> bool { |
| 891 | ENERGY_LABELS |
| 892 | .iter() |
| 893 | .any(|l| s.overflow_raw(l).is_none_or(|v| v != 0)) |
| 894 | } |
| 895 | |
| 896 | fn read_sample(s: &Spbm, t0: Instant) -> RawEnergySample { |
| 897 | RawEnergySample { |
| 898 | t_ns: t0.elapsed().as_nanos() as u64, |
| 899 | pkg_uj: s.energy_uj("pkg"), |
| 900 | cpu_e_uj: s.energy_uj("cpu_e"), |
| 901 | cpu_p_uj: s.energy_uj("cpu_p"), |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | /// A 10 Hz sampler recording raw counters (no arithmetic happens while sampling). |
| 906 | struct Sampler { |
| 907 | spbm: Spbm, |
| 908 | t0: Instant, |
| 909 | overflow_at_start: bool, |
| 910 | first: RawEnergySample, |
| 911 | stop: Arc<AtomicBool>, |
| 912 | samples: Arc<Mutex<Vec<RawEnergySample>>>, |
| 913 | handle: Option<std::thread::JoinHandle<()>>, |
| 914 | } |
| 915 | |
| 916 | impl Sampler { |
| 917 | fn start(spbm: &Spbm) -> Self { |
| 918 | let t0 = Instant::now(); |
| 919 | let overflow_at_start = any_overflow(spbm); |
| 920 | let first = read_sample(spbm, t0); |
| 921 | let stop = Arc::new(AtomicBool::new(false)); |
| 922 | let samples = Arc::new(Mutex::new(Vec::new())); |
| 923 | let handle = { |
| 924 | let (s, stop, samples) = (spbm.clone(), stop.clone(), samples.clone()); |
| 925 | std::thread::spawn(move || { |
| 926 | let mut next = t0 + SAMPLE_PERIOD; |
| 927 | while !stop.load(Ordering::Relaxed) { |
| 928 | let now = Instant::now(); |
| 929 | if now < next { |
| 930 | std::thread::sleep((next - now).min(Duration::from_millis(5))); |
| 931 | continue; |
| 932 | } |
| 933 | let sm = read_sample(&s, t0); |
| 934 | if let Ok(mut v) = samples.lock() { |
| 935 | v.push(sm); |
| 936 | } |
| 937 | next += SAMPLE_PERIOD; |
| 938 | } |
| 939 | }) |
| 940 | }; |
| 941 | Self { |
| 942 | spbm: spbm.clone(), |
| 943 | t0, |
| 944 | overflow_at_start, |
| 945 | first, |
| 946 | stop, |
| 947 | samples, |
| 948 | handle: Some(handle), |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | fn finish(mut self) -> RawEnergy { |
| 953 | let last = read_sample(&self.spbm, self.t0); |
| 954 | self.stop.store(true, Ordering::Relaxed); |
| 955 | if let Some(h) = self.handle.take() { |
| 956 | let _ = h.join(); |
| 957 | } |
| 958 | let mut samples = vec![self.first]; |
| 959 | samples.extend(self.samples.lock().map(|v| v.clone()).unwrap_or_default()); |
| 960 | samples.push(last); |
| 961 | RawEnergy { |
| 962 | overflow_at_start: self.overflow_at_start, |
| 963 | overflow_at_end: any_overflow(&self.spbm), |
| 964 | samples, |
| 965 | } |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | // --------------------------------------------------------------------------------- |
| 970 | // Raw evidence |
| 971 | // --------------------------------------------------------------------------------- |
| 972 | |
| 973 | /// Instruments and their resolution. |
| 974 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 975 | pub struct Instruments { |
| 976 | pub clock: String, |
| 977 | pub clock_resolution_ns: u64, |
| 978 | pub energy_sensor: String, |
| 979 | /// Smallest energy step the counter reports, microjoules. |
| 980 | pub energy_step_uj: u64, |
| 981 | /// Firmware update period assumed for the edge uncertainty, milliseconds. |
| 982 | pub energy_update_period_ms: u64, |
| 983 | pub energy_sample_period_ms: u64, |
| 984 | } |
| 985 | |
| 986 | /// One storage probe carried over from W1's `floor.json`. |
| 987 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 988 | pub struct W1FlushProbe { |
| 989 | pub name: String, |
| 990 | pub description: String, |
| 991 | pub latency: LatencySummary, |
| 992 | } |
| 993 | |
| 994 | /// W1's flush measurement as sealed in Phase 5. |
| 995 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 996 | pub struct W1Flush { |
| 997 | pub path: String, |
| 998 | pub sha256: String, |
| 999 | pub probes: Vec<W1FlushProbe>, |
| 1000 | } |
| 1001 | |
| 1002 | /// One probe run: integers only. |
| 1003 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 1004 | pub struct RawRun { |
| 1005 | pub probe: ProbeKind, |
| 1006 | pub rep: u32, |
| 1007 | pub threads: u32, |
| 1008 | pub work_units: u64, |
| 1009 | pub elapsed_ns: u64, |
| 1010 | pub error: Option<String>, |
| 1011 | pub energy: RawEnergy, |
| 1012 | /// `/proc/loadavg` as read at the start and end of the run (other tenants are a confounder). |
| 1013 | pub loadavg_start: Option<String>, |
| 1014 | pub loadavg_end: Option<String>, |
| 1015 | } |
| 1016 | |
| 1017 | /// Everything `report.json` is computed from. |
| 1018 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1019 | pub struct RawEvidence { |
| 1020 | pub schema: String, |
| 1021 | pub protocol_sha256: String, |
| 1022 | pub source_rev: String, |
| 1023 | pub started_utc: String, |
| 1024 | pub host: HostInfo, |
| 1025 | pub instruments: Instruments, |
| 1026 | pub w1_flush: W1Flush, |
| 1027 | pub runs: Vec<RawRun>, |
| 1028 | } |
| 1029 | |
| 1030 | pub fn sha256_hex(bytes: &[u8]) -> String { |
| 1031 | hex::encode(Sha256::digest(bytes)) |
| 1032 | } |
| 1033 | |
| 1034 | /// Load W1's `floor.json` from `repo_root`, check its digest, and copy the named probes. |
| 1035 | pub fn load_w1_flush(repo_root: &Path, src: &W1Source) -> Result<W1Flush, BoundsRefusal> { |
| 1036 | let path = repo_root.join(&src.path); |
| 1037 | let bytes = fs::read(&path) |
| 1038 | .map_err(|e| BoundsRefusal::W1SourceMismatch(format!("read {}: {e}", path.display())))?; |
| 1039 | let found = sha256_hex(&bytes); |
| 1040 | if found != src.sha256 { |
| 1041 | return Err(BoundsRefusal::W1SourceMismatch(format!( |
| 1042 | "{} has SHA-256 {found}; the protocol pins {}", |
| 1043 | src.path, src.sha256 |
| 1044 | ))); |
| 1045 | } |
| 1046 | let floor: FloorReport = serde_json::from_slice(&bytes) |
| 1047 | .map_err(|e| BoundsRefusal::W1SourceMismatch(format!("parse {}: {e}", src.path)))?; |
| 1048 | let probes = src |
| 1049 | .probes |
| 1050 | .iter() |
| 1051 | .map(|name| { |
| 1052 | floor |
| 1053 | .storage |
| 1054 | .iter() |
| 1055 | .find(|p| &p.name == name) |
| 1056 | .and_then(|p| { |
| 1057 | p.latency.clone().map(|latency| W1FlushProbe { |
| 1058 | name: p.name.clone(), |
| 1059 | description: p.description.clone(), |
| 1060 | latency, |
| 1061 | }) |
| 1062 | }) |
| 1063 | .ok_or_else(|| { |
| 1064 | BoundsRefusal::W1SourceMismatch(format!( |
| 1065 | "probe {name} missing or without latency in {}", |
| 1066 | src.path |
| 1067 | )) |
| 1068 | }) |
| 1069 | }) |
| 1070 | .collect::<Result<Vec<_>, _>>()?; |
| 1071 | Ok(W1Flush { |
| 1072 | path: src.path.clone(), |
| 1073 | sha256: src.sha256.clone(), |
| 1074 | probes, |
| 1075 | }) |
| 1076 | } |
| 1077 | |
| 1078 | fn clock_resolution_ns() -> u64 { |
| 1079 | let mut ts = libc::timespec { |
| 1080 | tv_sec: 0, |
| 1081 | tv_nsec: 0, |
| 1082 | }; |
| 1083 | // SAFETY: `ts` is a valid, exclusively borrowed timespec. |
| 1084 | let rc = unsafe { libc::clock_getres(libc::CLOCK_MONOTONIC, &mut ts) }; |
| 1085 | if rc != 0 { |
| 1086 | return 0; |
| 1087 | } |
| 1088 | ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64 |
| 1089 | } |
| 1090 | |
| 1091 | // --------------------------------------------------------------------------------- |
| 1092 | // Running |
| 1093 | // --------------------------------------------------------------------------------- |
| 1094 | |
| 1095 | /// Where a run reads its protocol and writes its evidence. |
| 1096 | #[derive(Debug, Clone)] |
| 1097 | pub struct BoundsConfig { |
| 1098 | /// Holds `protocol.json`; `raw.json` and `report.json` are written here. |
| 1099 | pub evidence_dir: PathBuf, |
| 1100 | /// Scratch directory on the store's filesystem (device probes write here). |
| 1101 | pub work_dir: PathBuf, |
| 1102 | /// Root that `protocol.w1_flush.path` is relative to. |
| 1103 | pub repo_root: PathBuf, |
| 1104 | /// Where hwmon devices are listed (normally [`crate::energy::HWMON_ROOT`]). |
| 1105 | pub hwmon_root: PathBuf, |
| 1106 | pub source_rev: String, |
| 1107 | } |
| 1108 | |
| 1109 | fn measured( |
| 1110 | spbm: &Spbm, |
| 1111 | probe: ProbeKind, |
| 1112 | rep: u32, |
| 1113 | threads: u32, |
| 1114 | work: impl FnOnce() -> Result<Timed, String>, |
| 1115 | ) -> RawRun { |
| 1116 | let loadavg_start = loadavg_line(); |
| 1117 | let sampler = Sampler::start(spbm); |
| 1118 | let result = work(); |
| 1119 | let energy = sampler.finish(); |
| 1120 | let loadavg_end = loadavg_line(); |
| 1121 | let (work_units, elapsed_ns, error) = match result { |
| 1122 | Ok(t) => (t.units, t.elapsed_ns, None), |
| 1123 | Err(e) => (0, 0, Some(e)), |
| 1124 | }; |
| 1125 | RawRun { |
| 1126 | probe, |
| 1127 | rep, |
| 1128 | threads, |
| 1129 | work_units, |
| 1130 | elapsed_ns, |
| 1131 | error, |
| 1132 | energy, |
| 1133 | loadavg_start, |
| 1134 | loadavg_end, |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | fn loadavg_line() -> Option<String> { |
| 1139 | fs::read_to_string("/proc/loadavg") |
| 1140 | .ok() |
| 1141 | .map(|s| s.trim().to_string()) |
| 1142 | } |
| 1143 | |
| 1144 | fn device_pattern(rep: u32) -> u8 { |
| 1145 | 0x41 + (rep % 64) as u8 |
| 1146 | } |
| 1147 | |
| 1148 | fn run_probe(spbm: &Spbm, p: &Protocol, probe: ProbeKind, rep: u32, device_file: &Path) -> RawRun { |
| 1149 | let threads = p.expected_threads(probe); |
| 1150 | match probe { |
| 1151 | ProbeKind::Idle => measured(spbm, probe, rep, threads, || { |
| 1152 | let t = Instant::now(); |
| 1153 | std::thread::sleep(Duration::from_millis(p.idle_ms)); |
| 1154 | Ok(Timed { |
| 1155 | elapsed_ns: t.elapsed().as_nanos() as u64, |
| 1156 | units: 0, |
| 1157 | }) |
| 1158 | }), |
| 1159 | ProbeKind::MemoryRead => { |
| 1160 | let mut st = memory_read_states(p.threads, p.memory.bytes_per_thread); |
| 1161 | measured(spbm, probe, rep, threads, || { |
| 1162 | memory_read(&mut st, p.memory.passes) |
| 1163 | }) |
| 1164 | } |
| 1165 | ProbeKind::MemoryCopy => { |
| 1166 | let mut st = memory_copy_states(p.threads, p.memory.bytes_per_thread); |
| 1167 | measured(spbm, probe, rep, threads, || { |
| 1168 | memory_copy(&mut st, p.memory.passes) |
| 1169 | }) |
| 1170 | } |
| 1171 | ProbeKind::DeviceWrite => measured(spbm, probe, rep, threads, || { |
| 1172 | device_write(device_file, &p.device, device_pattern(rep)) |
| 1173 | }), |
| 1174 | ProbeKind::DeviceRead => measured(spbm, probe, rep, threads, || { |
| 1175 | device_read(device_file, &p.device, device_pattern(rep)) |
| 1176 | }), |
| 1177 | ProbeKind::Sha256Sha2Crate => { |
| 1178 | let mut st = hash_states(p.threads, p.sha256.block_bytes); |
| 1179 | measured(spbm, probe, rep, threads, || { |
| 1180 | sha256_sha2_crate(&mut st, p.sha256.blocks_per_thread) |
| 1181 | }) |
| 1182 | } |
| 1183 | ProbeKind::Sha256ArmInstructions => { |
| 1184 | let mut st = hash_states(p.threads, p.sha256.block_bytes); |
| 1185 | measured(spbm, probe, rep, threads, || { |
| 1186 | sha256_arm_instructions(&mut st, p.sha256.blocks_per_thread) |
| 1187 | }) |
| 1188 | } |
| 1189 | ProbeKind::Ed25519Verify => { |
| 1190 | let mut st = verify_states(p.threads, p.ed25519.message_bytes); |
| 1191 | measured(spbm, probe, rep, threads, || { |
| 1192 | ed25519_verify(&mut st, p.ed25519.verifications_per_thread) |
| 1193 | }) |
| 1194 | } |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | /// Run every probe `repetitions` times (probe order fixed by [`PROBE_ORDER`]), write |
| 1199 | /// `raw.json`, then compute `report.json` from the bytes just written. |
| 1200 | /// |
| 1201 | /// Refuses before touching the work or evidence directory when the protocol is invalid |
| 1202 | /// or the energy meter is unavailable (`INSTRUMENT_UNAVAILABLE`). |
| 1203 | pub fn run_bounds(cfg: &BoundsConfig) -> Result<Report, BoundsRefusal> { |
| 1204 | let protocol_bytes = fs::read(cfg.evidence_dir.join(PROTOCOL_FILE)) |
| 1205 | .map_err(|e| BoundsRefusal::Io(format!("read {PROTOCOL_FILE}: {e}")))?; |
| 1206 | let protocol = Protocol::parse(&protocol_bytes).map_err(BoundsRefusal::ProtocolInvalid)?; |
| 1207 | let spbm = energy_preflight(&cfg.hwmon_root, &protocol.energy_preflight)?; |
| 1208 | for name in [RAW_FILE, REPORT_FILE, SUMS_FILE] { |
| 1209 | if cfg.evidence_dir.join(name).exists() { |
| 1210 | return Err(BoundsRefusal::EvidenceExists(format!( |
| 1211 | "{name} already exists; sealed evidence is never overwritten" |
| 1212 | ))); |
| 1213 | } |
| 1214 | } |
| 1215 | let cpus = std::thread::available_parallelism().map_or(1, |c| c.get()); |
| 1216 | if protocol.threads as usize > cpus { |
| 1217 | return Err(BoundsRefusal::HostMismatch(format!( |
| 1218 | "protocol fixes {} threads; this host has {cpus} CPUs", |
| 1219 | protocol.threads |
| 1220 | ))); |
| 1221 | } |
| 1222 | let w1_flush = load_w1_flush(&cfg.repo_root, &protocol.w1_flush)?; |
| 1223 | let work = cfg |
| 1224 | .work_dir |
| 1225 | .join(format!("synapse-a0-bounds-{}", std::process::id())); |
| 1226 | fs::create_dir_all(&work) |
| 1227 | .map_err(|e| BoundsRefusal::Io(format!("mkdir {}: {e}", work.display())))?; |
| 1228 | let host = collect_host_info(&work); |
| 1229 | let started_utc = crate::utc_timestamp(); |
| 1230 | let device_file = work.join("device.dat"); |
| 1231 | let prepared = prepare_device_file(&device_file, protocol.device.file_bytes); |
| 1232 | let mut runs = Vec::new(); |
| 1233 | for rep in 0..protocol.repetitions { |
| 1234 | for probe in PROBE_ORDER { |
| 1235 | let run = match (&prepared, probe) { |
| 1236 | (Err(e), ProbeKind::DeviceWrite | ProbeKind::DeviceRead) => RawRun { |
| 1237 | probe, |
| 1238 | rep, |
| 1239 | threads: protocol.expected_threads(probe), |
| 1240 | work_units: 0, |
| 1241 | elapsed_ns: 0, |
| 1242 | error: Some(e.clone()), |
| 1243 | energy: RawEnergy::default(), |
| 1244 | loadavg_start: None, |
| 1245 | loadavg_end: None, |
| 1246 | }, |
| 1247 | _ => run_probe(&spbm, &protocol, probe, rep, &device_file), |
| 1248 | }; |
| 1249 | runs.push(run); |
| 1250 | } |
| 1251 | } |
| 1252 | let _ = fs::remove_dir_all(&work); |
| 1253 | let raw = RawEvidence { |
| 1254 | schema: RAW_SCHEMA.into(), |
| 1255 | protocol_sha256: sha256_hex(&protocol_bytes), |
| 1256 | source_rev: cfg.source_rev.clone(), |
| 1257 | started_utc, |
| 1258 | host, |
| 1259 | instruments: Instruments { |
| 1260 | clock: "CLOCK_MONOTONIC (std::time::Instant)".into(), |
| 1261 | clock_resolution_ns: clock_resolution_ns(), |
| 1262 | energy_sensor: "aien_spbm hwmon, SoC package only (GB10 SPBM firmware counters; \ |
| 1263 | pkg, cpu_e, cpu_p; no published accuracy; not compared with an \ |
| 1264 | external meter; NVMe drive energy outside it, UNMEASURED)" |
| 1265 | .into(), |
| 1266 | energy_step_uj: 1000, |
| 1267 | energy_update_period_ms: (SENSOR_PERIOD_S * 1000.0) as u64, |
| 1268 | energy_sample_period_ms: SAMPLE_PERIOD.as_millis() as u64, |
| 1269 | }, |
| 1270 | w1_flush, |
| 1271 | runs, |
| 1272 | }; |
| 1273 | let raw_bytes = serde_json::to_vec_pretty(&raw) |
| 1274 | .map_err(|e| BoundsRefusal::Io(format!("serialize raw: {e}")))?; |
| 1275 | fs::write(cfg.evidence_dir.join(RAW_FILE), &raw_bytes) |
| 1276 | .map_err(|e| BoundsRefusal::Io(format!("write {RAW_FILE}: {e}")))?; |
| 1277 | let raw_bytes = fs::read(cfg.evidence_dir.join(RAW_FILE)) |
| 1278 | .map_err(|e| BoundsRefusal::Io(format!("reread {RAW_FILE}: {e}")))?; |
| 1279 | let report = compute_report(&protocol_bytes, &raw_bytes) |
| 1280 | .map_err(|e| BoundsRefusal::Io(format!("compute report: {e}")))?; |
| 1281 | fs::write(cfg.evidence_dir.join(REPORT_FILE), report_bytes(&report)?) |
| 1282 | .map_err(|e| BoundsRefusal::Io(format!("write {REPORT_FILE}: {e}")))?; |
| 1283 | let sums = sha256sums(&cfg.evidence_dir, &[PROTOCOL_FILE, RAW_FILE, REPORT_FILE]) |
| 1284 | .map_err(|e| BoundsRefusal::Io(format!("checksum sealed files: {e}")))?; |
| 1285 | fs::write(cfg.evidence_dir.join(SUMS_FILE), sums) |
| 1286 | .map_err(|e| BoundsRefusal::Io(format!("write {SUMS_FILE}: {e}")))?; |
| 1287 | Ok(report) |
| 1288 | } |
| 1289 | |
| 1290 | // --------------------------------------------------------------------------------- |
| 1291 | // Report: a pure function of the protocol and raw bytes |
| 1292 | // --------------------------------------------------------------------------------- |
| 1293 | |
| 1294 | /// Energy figures of one window, derived from raw counters only. |
| 1295 | #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] |
| 1296 | pub struct EnergyFigures { |
| 1297 | pub valid: bool, |
| 1298 | pub refusal: Option<String>, |
| 1299 | pub samples: usize, |
| 1300 | pub window_s: Option<f64>, |
| 1301 | pub largest_gap_ms: Option<f64>, |
| 1302 | pub pkg_j: Option<f64>, |
| 1303 | pub cpu_p_j: Option<f64>, |
| 1304 | pub cpu_e_j: Option<f64>, |
| 1305 | pub pkg_mean_w: Option<f64>, |
| 1306 | /// `pkg_mean_w * 0.1 s * sqrt(2/3)`: the analytic edge uncertainty, joules. |
| 1307 | pub pkg_edge_sd_j: Option<f64>, |
| 1308 | pub pkg_j_per_unit: Option<f64>, |
| 1309 | /// `(pkg_j - idle W * window_s) / units`, idle W from the same repetition's idle run. |
| 1310 | pub pkg_j_per_unit_above_idle: Option<f64>, |
| 1311 | } |
| 1312 | |
| 1313 | /// Apply the energy refusal rules of [`crate::energy`] to raw counters: refuse when an |
| 1314 | /// overflow flag is set at an edge, a gap between samples exceeds 300 ms, fewer than |
| 1315 | /// 90% of the expected samples arrived, a counter is unreadable or decreased, or the |
| 1316 | /// counter is within one window of the 32-bit wrap. |
| 1317 | pub fn energy_figures(raw: &RawEnergy, work_units: u64, idle_w: Option<f64>) -> EnergyFigures { |
| 1318 | let s = &raw.samples; |
| 1319 | let mut f = EnergyFigures { |
| 1320 | samples: s.len(), |
| 1321 | ..Default::default() |
| 1322 | }; |
| 1323 | if s.len() < 2 { |
| 1324 | f.refusal = Some("fewer than two samples".into()); |
| 1325 | return f; |
| 1326 | } |
| 1327 | let window_ns = s[s.len() - 1].t_ns.saturating_sub(s[0].t_ns); |
| 1328 | let window_s = window_ns as f64 / 1e9; |
| 1329 | f.window_s = Some(window_s); |
| 1330 | let largest_gap = s |
| 1331 | .windows(2) |
| 1332 | .map(|w| w[1].t_ns.saturating_sub(w[0].t_ns)) |
| 1333 | .max() |
| 1334 | .unwrap_or(0); |
| 1335 | f.largest_gap_ms = Some(largest_gap as f64 / 1e6); |
| 1336 | let expected = window_ns / SAMPLE_PERIOD.as_nanos() as u64; |
| 1337 | let delta = |get: fn(&RawEnergySample) -> Option<u64>| -> Result<u64, String> { |
| 1338 | let mut prev: Option<u64> = None; |
| 1339 | for x in s { |
| 1340 | let v = get(x).ok_or("counter read failed (overflow or missing)")?; |
| 1341 | if prev.is_some_and(|p| v < p) { |
| 1342 | return Err("energy counter decreased".into()); |
| 1343 | } |
| 1344 | prev = Some(v); |
| 1345 | } |
| 1346 | let (a, b) = (get(&s[0]).unwrap_or(0), get(&s[s.len() - 1]).unwrap_or(0)); |
| 1347 | if COUNTER_WRAP_UJ.saturating_sub(b) <= b - a { |
| 1348 | return Err("counter within one window of the 32-bit wrap".into()); |
| 1349 | } |
| 1350 | Ok(b - a) |
| 1351 | }; |
| 1352 | let refusal = if raw.overflow_at_start || raw.overflow_at_end { |
| 1353 | Some("overflow flag set at a window edge".to_string()) |
| 1354 | } else if largest_gap > MAX_SAMPLE_GAP.as_nanos() as u64 { |
| 1355 | Some("gap between consecutive samples above 300 ms".into()) |
| 1356 | } else if (s.len() as u64 - 2) * 10 < expected * 9 { |
| 1357 | Some(format!( |
| 1358 | "fewer than 90% of expected samples ({} of {expected})", |
| 1359 | s.len() - 2 |
| 1360 | )) |
| 1361 | } else { |
| 1362 | None |
| 1363 | }; |
| 1364 | if let Some(why) = refusal { |
| 1365 | f.refusal = Some(why); |
| 1366 | return f; |
| 1367 | } |
| 1368 | let (pkg, cpu_p, cpu_e) = match ( |
| 1369 | delta(|x| x.pkg_uj), |
| 1370 | delta(|x| x.cpu_p_uj), |
| 1371 | delta(|x| x.cpu_e_uj), |
| 1372 | ) { |
| 1373 | (Ok(a), Ok(b), Ok(c)) => (a, b, c), |
| 1374 | (a, b, c) => { |
| 1375 | f.refusal = [a.err(), b.err(), c.err()].into_iter().flatten().next(); |
| 1376 | return f; |
| 1377 | } |
| 1378 | }; |
| 1379 | let pkg_j = pkg as f64 / 1e6; |
| 1380 | f.valid = true; |
| 1381 | f.pkg_j = Some(pkg_j); |
| 1382 | f.cpu_p_j = Some(cpu_p as f64 / 1e6); |
| 1383 | f.cpu_e_j = Some(cpu_e as f64 / 1e6); |
| 1384 | if window_ns > 0 { |
| 1385 | let w = pkg_j / window_s; |
| 1386 | f.pkg_mean_w = Some(w); |
| 1387 | f.pkg_edge_sd_j = Some(w * SENSOR_PERIOD_S * (2.0f64 / 3.0).sqrt()); |
| 1388 | } |
| 1389 | if work_units > 0 { |
| 1390 | f.pkg_j_per_unit = Some(pkg_j / work_units as f64); |
| 1391 | f.pkg_j_per_unit_above_idle = idle_w.map(|w| (pkg_j - w * window_s) / work_units as f64); |
| 1392 | } |
| 1393 | f |
| 1394 | } |
| 1395 | |
| 1396 | /// Median, minimum, and maximum across repetitions (no rounding). |
| 1397 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 1398 | pub struct Stat { |
| 1399 | pub median: f64, |
| 1400 | pub min: f64, |
| 1401 | pub max: f64, |
| 1402 | pub n: usize, |
| 1403 | } |
| 1404 | |
| 1405 | pub fn stat(values: &[f64]) -> Option<Stat> { |
| 1406 | let mut v: Vec<f64> = values.iter().copied().filter(|x| x.is_finite()).collect(); |
| 1407 | if v.is_empty() { |
| 1408 | return None; |
| 1409 | } |
| 1410 | v.sort_by(|a, b| a.total_cmp(b)); |
| 1411 | let n = v.len(); |
| 1412 | let median = if n % 2 == 1 { |
| 1413 | v[n / 2] |
| 1414 | } else { |
| 1415 | (v[n / 2 - 1] + v[n / 2]) / 2.0 |
| 1416 | }; |
| 1417 | Some(Stat { |
| 1418 | median, |
| 1419 | min: v[0], |
| 1420 | max: v[n - 1], |
| 1421 | n, |
| 1422 | }) |
| 1423 | } |
| 1424 | |
| 1425 | /// Figures of one probe run. |
| 1426 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 1427 | pub struct RepFigures { |
| 1428 | pub rep: u32, |
| 1429 | pub work_units: u64, |
| 1430 | pub elapsed_s: f64, |
| 1431 | /// `work_units / elapsed_s`. |
| 1432 | pub rate_per_s: Option<f64>, |
| 1433 | pub error: Option<String>, |
| 1434 | pub energy: EnergyFigures, |
| 1435 | } |
| 1436 | |
| 1437 | /// One probe across all repetitions. |
| 1438 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 1439 | pub struct ProbeSummary { |
| 1440 | pub probe: ProbeKind, |
| 1441 | pub unit: String, |
| 1442 | pub description: String, |
| 1443 | pub threads: u32, |
| 1444 | pub errors: u32, |
| 1445 | pub valid_energy_reps: u32, |
| 1446 | pub rate_per_s: Option<Stat>, |
| 1447 | pub pkg_mean_w: Option<Stat>, |
| 1448 | pub pkg_j_per_unit: Option<Stat>, |
| 1449 | pub pkg_j_per_unit_above_idle: Option<Stat>, |
| 1450 | pub reps: Vec<RepFigures>, |
| 1451 | } |
| 1452 | |
| 1453 | /// What a measured bound input is allowed to claim. A rate measured on this host is |
| 1454 | /// never the hardware's capability: a better workload can exceed it. So a hardware |
| 1455 | /// rate is only ever `Achieved` (a lower bound on capability; the physical bound comes |
| 1456 | /// from the vendor's published figure or the link, outside this run). Where no |
| 1457 | /// closed-form limit exists, section 6.2 makes the best all-core implementation the |
| 1458 | /// reference, replaced whenever a later measurement beats it. There is no third label. |
| 1459 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 1460 | pub enum BoundInputKind { |
| 1461 | #[serde(rename = "achieved (lower bound on capability)")] |
| 1462 | Achieved, |
| 1463 | #[serde(rename = "implementation reference (section 6.2 replacement rule)")] |
| 1464 | ImplementationReference, |
| 1465 | } |
| 1466 | |
| 1467 | impl fmt::Display for BoundInputKind { |
| 1468 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1469 | f.write_str(match self { |
| 1470 | Self::Achieved => "achieved (lower bound on capability)", |
| 1471 | Self::ImplementationReference => { |
| 1472 | "implementation reference (section 6.2 replacement rule)" |
| 1473 | } |
| 1474 | }) |
| 1475 | } |
| 1476 | } |
| 1477 | |
| 1478 | /// One section 6.2 bound input. |
| 1479 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 1480 | pub struct BoundInput { |
| 1481 | pub name: String, |
| 1482 | pub value: f64, |
| 1483 | pub unit: String, |
| 1484 | pub probe: ProbeKind, |
| 1485 | pub statistic: BoundStatistic, |
| 1486 | pub kind: BoundInputKind, |
| 1487 | } |
| 1488 | |
| 1489 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 1490 | pub struct Report { |
| 1491 | pub schema: String, |
| 1492 | pub protocol_sha256: String, |
| 1493 | pub raw_sha256: String, |
| 1494 | pub source_rev: String, |
| 1495 | pub repetitions: u32, |
| 1496 | pub central_statistic: CentralStatistic, |
| 1497 | pub spread_statistic: SpreadStatistic, |
| 1498 | pub bound_statistic: BoundStatistic, |
| 1499 | /// Repetitions marked `error` (they skip their work). At most |
| 1500 | /// [`MAX_EXCLUDED_REPETITIONS`]; reported even when zero. |
| 1501 | pub excluded_repetitions: u32, |
| 1502 | pub instruments: Instruments, |
| 1503 | pub w1_flush: W1Flush, |
| 1504 | pub bound_inputs: Vec<BoundInput>, |
| 1505 | pub probes: Vec<ProbeSummary>, |
| 1506 | } |
| 1507 | |
| 1508 | fn report_bytes(r: &Report) -> Result<Vec<u8>, BoundsRefusal> { |
| 1509 | serde_json::to_vec_pretty(r).map_err(|e| BoundsRefusal::Io(format!("serialize report: {e}"))) |
| 1510 | } |
| 1511 | |
| 1512 | /// Checks the runs against the protocol and returns how many repetitions are excluded |
| 1513 | /// (marked `error`). Refuses when that exceeds [`MAX_EXCLUDED_REPETITIONS`]. |
| 1514 | fn check_runs(p: &Protocol, raw: &RawEvidence) -> Result<u32, VerifyError> { |
| 1515 | let want = PROBE_ORDER.len() * p.repetitions as usize; |
| 1516 | if raw.runs.len() != want { |
| 1517 | return Err(VerifyError::RepetitionMismatch(format!( |
| 1518 | "{} runs; the protocol fixes {} probes x {} repetitions = {want}", |
| 1519 | raw.runs.len(), |
| 1520 | PROBE_ORDER.len(), |
| 1521 | p.repetitions |
| 1522 | ))); |
| 1523 | } |
| 1524 | for probe in PROBE_ORDER { |
| 1525 | let mut reps: Vec<u32> = raw |
| 1526 | .runs |
| 1527 | .iter() |
| 1528 | .filter(|r| r.probe == probe) |
| 1529 | .map(|r| r.rep) |
| 1530 | .collect(); |
| 1531 | reps.sort_unstable(); |
| 1532 | if reps != (0..p.repetitions).collect::<Vec<_>>() { |
| 1533 | return Err(VerifyError::RepetitionMismatch(format!( |
| 1534 | "{probe:?} has repetitions {reps:?}; the protocol fixes 0..{}", |
| 1535 | p.repetitions |
| 1536 | ))); |
| 1537 | } |
| 1538 | } |
| 1539 | for r in &raw.runs { |
| 1540 | if r.threads != p.expected_threads(r.probe) { |
| 1541 | return Err(VerifyError::WorkMismatch(format!( |
| 1542 | "{:?} rep {} used {} threads; the protocol fixes {}", |
| 1543 | r.probe, |
| 1544 | r.rep, |
| 1545 | r.threads, |
| 1546 | p.expected_threads(r.probe) |
| 1547 | ))); |
| 1548 | } |
| 1549 | if r.error.is_none() && r.work_units != p.expected_units(r.probe) { |
| 1550 | return Err(VerifyError::WorkMismatch(format!( |
| 1551 | "{:?} rep {} did {} units; the protocol fixes {}", |
| 1552 | r.probe, |
| 1553 | r.rep, |
| 1554 | r.work_units, |
| 1555 | p.expected_units(r.probe) |
| 1556 | ))); |
| 1557 | } |
| 1558 | } |
| 1559 | let excluded: Vec<String> = raw |
| 1560 | .runs |
| 1561 | .iter() |
| 1562 | .filter_map(|r| { |
| 1563 | r.error |
| 1564 | .as_ref() |
| 1565 | .map(|e| format!("{:?} rep {} ({e})", r.probe, r.rep)) |
| 1566 | }) |
| 1567 | .collect(); |
| 1568 | if excluded.len() as u32 > MAX_EXCLUDED_REPETITIONS { |
| 1569 | return Err(VerifyError::ExcludedRepetitions(format!( |
| 1570 | "{} repetition(s) marked error, protocol v1 allows {MAX_EXCLUDED_REPETITIONS}: {}", |
| 1571 | excluded.len(), |
| 1572 | excluded.join(", ") |
| 1573 | ))); |
| 1574 | } |
| 1575 | Ok(excluded.len() as u32) |
| 1576 | } |
| 1577 | |
| 1578 | fn bound_inputs(probes: &[ProbeSummary]) -> Vec<BoundInput> { |
| 1579 | let max_of = |k: ProbeKind| { |
| 1580 | probes |
| 1581 | .iter() |
| 1582 | .find(|s| s.probe == k) |
| 1583 | .and_then(|s| s.rate_per_s.as_ref()) |
| 1584 | .map(|s| s.max) |
| 1585 | }; |
| 1586 | let mut out = Vec::new(); |
| 1587 | let mut push = |
| 1588 | |name: &str, unit: &str, kind: BoundInputKind, probe: ProbeKind, value: Option<f64>| { |
| 1589 | if let Some(value) = value { |
| 1590 | out.push(BoundInput { |
| 1591 | name: name.into(), |
| 1592 | value, |
| 1593 | unit: unit.into(), |
| 1594 | probe, |
| 1595 | statistic: BoundStatistic::MaxRate, |
| 1596 | kind, |
| 1597 | }); |
| 1598 | } |
| 1599 | }; |
| 1600 | let hw = BoundInputKind::Achieved; |
| 1601 | let imp = BoundInputKind::ImplementationReference; |
| 1602 | for (name, unit, probe) in [ |
| 1603 | ("memory_read_bandwidth", "B/s", ProbeKind::MemoryRead), |
| 1604 | ( |
| 1605 | "memory_copy_bandwidth", |
| 1606 | "B/s (read plus written)", |
| 1607 | ProbeKind::MemoryCopy, |
| 1608 | ), |
| 1609 | ( |
| 1610 | "device_write_bandwidth", |
| 1611 | "B/s (through fdatasync)", |
| 1612 | ProbeKind::DeviceWrite, |
| 1613 | ), |
| 1614 | ("device_read_bandwidth", "B/s", ProbeKind::DeviceRead), |
| 1615 | ] { |
| 1616 | push(name, unit, hw, probe, max_of(probe)); |
| 1617 | } |
| 1618 | let sha = [ProbeKind::Sha256Sha2Crate, ProbeKind::Sha256ArmInstructions] |
| 1619 | .into_iter() |
| 1620 | .filter_map(|k| max_of(k).map(|v| (k, v))) |
| 1621 | .max_by(|a, b| a.1.total_cmp(&b.1)); |
| 1622 | if let Some((k, v)) = sha { |
| 1623 | push("sha256_all_core_throughput", "B/s", imp, k, Some(v)); |
| 1624 | } |
| 1625 | push( |
| 1626 | "ed25519_verify_all_core_throughput", |
| 1627 | "verifications/s", |
| 1628 | imp, |
| 1629 | ProbeKind::Ed25519Verify, |
| 1630 | max_of(ProbeKind::Ed25519Verify), |
| 1631 | ); |
| 1632 | out |
| 1633 | } |
| 1634 | |
| 1635 | /// Compute the report from the exact protocol and raw bytes. Checks that the raw data |
| 1636 | /// names this protocol's digest and has exactly the repetitions and work it fixed. |
| 1637 | pub fn compute_report(protocol_bytes: &[u8], raw_bytes: &[u8]) -> Result<Report, VerifyError> { |
| 1638 | let protocol = Protocol::parse(protocol_bytes).map_err(VerifyError::ProtocolInvalid)?; |
| 1639 | let raw: RawEvidence = |
| 1640 | serde_json::from_slice(raw_bytes).map_err(|e| VerifyError::Parse(format!("raw: {e}")))?; |
| 1641 | if raw.schema != RAW_SCHEMA { |
| 1642 | return Err(VerifyError::Parse(format!("raw schema {:?}", raw.schema))); |
| 1643 | } |
| 1644 | let protocol_sha256 = sha256_hex(protocol_bytes); |
| 1645 | if raw.protocol_sha256 != protocol_sha256 { |
| 1646 | return Err(VerifyError::ProtocolDigestMismatch { |
| 1647 | protocol: protocol_sha256, |
| 1648 | raw_names: raw.protocol_sha256, |
| 1649 | }); |
| 1650 | } |
| 1651 | let excluded_repetitions = check_runs(&protocol, &raw)?; |
| 1652 | let idle_w = |rep: u32| { |
| 1653 | raw.runs |
| 1654 | .iter() |
| 1655 | .find(|r| r.probe == ProbeKind::Idle && r.rep == rep && r.error.is_none()) |
| 1656 | .and_then(|r| energy_figures(&r.energy, 0, None).pkg_mean_w) |
| 1657 | }; |
| 1658 | let probes: Vec<ProbeSummary> = PROBE_ORDER |
| 1659 | .iter() |
| 1660 | .map(|&probe| { |
| 1661 | let mut runs: Vec<&RawRun> = raw.runs.iter().filter(|r| r.probe == probe).collect(); |
| 1662 | runs.sort_by_key(|r| r.rep); |
| 1663 | let reps: Vec<RepFigures> = runs |
| 1664 | .iter() |
| 1665 | .map(|r| { |
| 1666 | let ok = r.error.is_none(); |
| 1667 | let elapsed_s = r.elapsed_ns as f64 / 1e9; |
| 1668 | RepFigures { |
| 1669 | rep: r.rep, |
| 1670 | work_units: r.work_units, |
| 1671 | elapsed_s, |
| 1672 | rate_per_s: (ok && r.work_units > 0 && r.elapsed_ns > 0) |
| 1673 | .then(|| r.work_units as f64 * 1e9 / r.elapsed_ns as f64), |
| 1674 | error: r.error.clone(), |
| 1675 | energy: if ok { |
| 1676 | energy_figures(&r.energy, r.work_units, idle_w(r.rep)) |
| 1677 | } else { |
| 1678 | EnergyFigures { |
| 1679 | refusal: Some("probe failed".into()), |
| 1680 | ..Default::default() |
| 1681 | } |
| 1682 | }, |
| 1683 | } |
| 1684 | }) |
| 1685 | .collect(); |
| 1686 | let col = |f: fn(&RepFigures) -> Option<f64>| { |
| 1687 | stat(&reps.iter().filter_map(f).collect::<Vec<_>>()) |
| 1688 | }; |
| 1689 | ProbeSummary { |
| 1690 | probe, |
| 1691 | unit: probe.unit().into(), |
| 1692 | description: probe.description().into(), |
| 1693 | threads: protocol.expected_threads(probe), |
| 1694 | errors: reps.iter().filter(|r| r.error.is_some()).count() as u32, |
| 1695 | valid_energy_reps: reps.iter().filter(|r| r.energy.valid).count() as u32, |
| 1696 | rate_per_s: col(|r| r.rate_per_s), |
| 1697 | pkg_mean_w: col(|r| r.energy.pkg_mean_w), |
| 1698 | pkg_j_per_unit: col(|r| r.energy.pkg_j_per_unit), |
| 1699 | pkg_j_per_unit_above_idle: col(|r| r.energy.pkg_j_per_unit_above_idle), |
| 1700 | reps, |
| 1701 | } |
| 1702 | }) |
| 1703 | .collect(); |
| 1704 | Ok(Report { |
| 1705 | schema: REPORT_SCHEMA.into(), |
| 1706 | protocol_sha256, |
| 1707 | raw_sha256: sha256_hex(raw_bytes), |
| 1708 | source_rev: raw.source_rev, |
| 1709 | repetitions: protocol.repetitions, |
| 1710 | central_statistic: protocol.central_statistic, |
| 1711 | spread_statistic: protocol.spread_statistic, |
| 1712 | bound_statistic: protocol.bound_statistic, |
| 1713 | excluded_repetitions, |
| 1714 | instruments: raw.instruments, |
| 1715 | w1_flush: raw.w1_flush, |
| 1716 | bound_inputs: bound_inputs(&probes), |
| 1717 | probes, |
| 1718 | }) |
| 1719 | } |
| 1720 | |
| 1721 | /// `SHA256SUMS` text in the `sha256sum` format over `names` in `dir`. |
| 1722 | pub fn sha256sums(dir: &Path, names: &[&str]) -> std::io::Result<String> { |
| 1723 | let mut out = String::new(); |
| 1724 | for name in names { |
| 1725 | out.push_str(&format!( |
| 1726 | "{} {name}\n", |
| 1727 | sha256_hex(&fs::read(dir.join(name))?) |
| 1728 | )); |
| 1729 | } |
| 1730 | Ok(out) |
| 1731 | } |
| 1732 | |
| 1733 | /// Checks every file `SHA256SUMS` lists against its digest, and requires the three |
| 1734 | /// sealed files to be listed. |
| 1735 | fn verify_sums(dir: &Path) -> Result<(), VerifyError> { |
| 1736 | let text = fs::read_to_string(dir.join(SUMS_FILE)) |
| 1737 | .map_err(|e| VerifyError::ChecksumsMissing(format!("read {SUMS_FILE}: {e}")))?; |
| 1738 | let mut listed = Vec::new(); |
| 1739 | for (i, line) in text.lines().enumerate() { |
| 1740 | let (digest, name) = line |
| 1741 | .split_once(" ") |
| 1742 | .filter(|(d, n)| d.len() == 64 && !n.is_empty()) |
| 1743 | .ok_or_else(|| VerifyError::Parse(format!("{SUMS_FILE} line {}: {line:?}", i + 1)))?; |
| 1744 | let bytes = fs::read(dir.join(name)).map_err(|e| { |
| 1745 | VerifyError::ChecksumMismatch(format!("{name} listed but unreadable: {e}")) |
| 1746 | })?; |
| 1747 | let actual = sha256_hex(&bytes); |
| 1748 | if actual != digest { |
| 1749 | return Err(VerifyError::ChecksumMismatch(format!( |
| 1750 | "{name} is {actual}, {SUMS_FILE} lists {digest}" |
| 1751 | ))); |
| 1752 | } |
| 1753 | listed.push(name); |
| 1754 | } |
| 1755 | let missing: Vec<&str> = [PROTOCOL_FILE, RAW_FILE, REPORT_FILE] |
| 1756 | .into_iter() |
| 1757 | .filter(|n| !listed.contains(n)) |
| 1758 | .collect(); |
| 1759 | if !missing.is_empty() { |
| 1760 | return Err(VerifyError::ChecksumsMissing(format!( |
| 1761 | "{SUMS_FILE} does not list {}", |
| 1762 | missing.join(", ") |
| 1763 | ))); |
| 1764 | } |
| 1765 | Ok(()) |
| 1766 | } |
| 1767 | |
| 1768 | /// Recompute `report.json` from `protocol.json` and `raw.json` in `dir`, require the |
| 1769 | /// result to match byte for byte, then check every file `SHA256SUMS` lists. |
| 1770 | /// |
| 1771 | /// This proves consistency (the report is what the raw data implies) and that the |
| 1772 | /// files are the ones that were checksummed. It does not prove authenticity: anyone |
| 1773 | /// can edit `raw.json` and regenerate both files. Authenticity comes from the git |
| 1774 | /// history and review of the commit that sealed them. |
| 1775 | pub fn verify_evidence(dir: &Path) -> Result<Report, VerifyError> { |
| 1776 | let read = |name: &str| { |
| 1777 | fs::read(dir.join(name)).map_err(|e| VerifyError::Io(format!("read {name}: {e}"))) |
| 1778 | }; |
| 1779 | let (protocol, raw, sealed) = (read(PROTOCOL_FILE)?, read(RAW_FILE)?, read(REPORT_FILE)?); |
| 1780 | let report = compute_report(&protocol, &raw)?; |
| 1781 | let again = serde_json::to_vec_pretty(&report) |
| 1782 | .map_err(|e| VerifyError::Parse(format!("serialize report: {e}")))?; |
| 1783 | if again != sealed { |
| 1784 | let first_difference_at = again |
| 1785 | .iter() |
| 1786 | .zip(&sealed) |
| 1787 | .position(|(a, b)| a != b) |
| 1788 | .unwrap_or(again.len().min(sealed.len())); |
| 1789 | return Err(VerifyError::ReportMismatch { |
| 1790 | first_difference_at, |
| 1791 | }); |
| 1792 | } |
| 1793 | verify_sums(dir)?; |
| 1794 | Ok(report) |
| 1795 | } |
| 1796 | |
| 1797 | #[cfg(test)] |
| 1798 | mod tests; |