From 8ea0ef4e159634d7f14b6afcac4882b59dee80a0 Mon Sep 17 00:00:00 2001 From: Reims Builder Date: Wed, 2 Dec 2026 01:48:41 +0800 Subject: [PATCH] port step6+step7 opt2 to v0.6.2 --- crates/stela-boot/src/engine/start.rs | 20 +- crates/stela-boot/src/engine/translations.rs | 5 +- .../src/x86_64/executed_paths.rs | 1090 +- .../stela-compiler/src/x86_64/hle/compare.rs | 7 +- .../src/x86_64/pointer/cipher.rs | 464 +- .../src/x86_64/register_read.rs | 7338 ++++++------- .../stela-compiler/src/x86_64/table_switch.rs | 926 +- .../src/x86_64/table_switch/tests.rs | 687 +- crates/stela-contracts/src/reims_hosted.rs | 976 +- .../stela-drivers/src/probe/reims_hosted.rs | 57 +- crates/stela-engine/src/hle/signature.rs | 155 +- crates/stela-engine/src/hle/signatures.rs | 81 +- .../src/machine/engine/code_cache.rs | 3661 ++++--- .../src/machine/engine/compilation.rs | 16 +- crates/stela-engine/src/machine/engine/hle.rs | 808 +- .../src/machine/engine/mirrors.rs | 2084 ++-- .../src/machine/engine/parallel/tests.rs | 9616 +++++++++-------- .../src/machine/engine/pointer.rs | 2910 ++--- .../machine/engine/pointer/native_tests.rs | 1894 ++-- .../machine/engine/pointer_authentication.rs | 1693 +-- .../src/machine/engine/regime_state.rs | 1 + .../src/machine/engine/step_timing.rs | 6294 +++++------ crates/stela-engine/src/pauth.rs | 1019 +- .../stela-engine/src/translations/writer.rs | 3 + crates/stela-engine/tests/opt2_jit_suite.rs | 550 + crates/stela-runtime/src/translation_bulk.rs | 20 +- xtask/src/hle_signatures.rs | 904 +- 27 files changed, 22287 insertions(+), 20992 deletions(-) create mode 100644 crates/stela-engine/tests/opt2_jit_suite.rs diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index e81fbddbbf..d4681d74b2 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -1308,7 +1308,25 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! { loaded_source.as_ref(), tree, ); - if let Some((transport, (apertures, vector))) = hosted_reims.zip(reims) { + if let Some((mut transport, (apertures, vector))) = hosted_reims.zip(reims) { + let fixed_reims_host = direct_reims_region.then_some(handoff.hosted_reims_region.physical); + let dram_ranges: alloc::vec::Vec<(u64, u64, u64)> = worker_ram + .iter() + .filter(|range| Some(range.host) != fixed_reims_host) + .map(|range| (range.guest, range.host, range.bytes)) + .collect(); + match transport.publish_guest_ram(&dram_ranges) { + Ok(Some(committed)) => output::arguments(format_args!( + "GUEST Reims zero-copy RAM map ranges={committed} (staged={})\n", + dram_ranges.len() + )), + Ok(None) => output::arguments(format_args!( + "GUEST Reims zero-copy RAM map unsupported by host QEMU (copy-only mode)\n" + )), + Err(error) => output::arguments(format_args!( + "GUEST Reims zero-copy RAM map warning: {error}\n" + )), + } let installed = match (direct_reims_region, vector) { (true, Some(vector)) => { devices.add_hosted_reims_direct_region_with_interrupt(apertures, transport, vector) diff --git a/crates/stela-boot/src/engine/translations.rs b/crates/stela-boot/src/engine/translations.rs index 5e3f78fcd4..00474d148b 100644 --- a/crates/stela-boot/src/engine/translations.rs +++ b/crates/stela-boot/src/engine/translations.rs @@ -2706,7 +2706,10 @@ impl WriterReads { } let depth = device.depth().clamp(1, MAX_FLIGHTS); let mut started = false; - while self.flights.len() < depth && device.room() { + // Serialize multi-chunk (> 64 KiB) merge reads so one 512 KiB piece + // (8 x 64 KiB = 128 bounce pages) never exhausts NVMe's 256-page bounce pool. + let max_inflight = depth.min(2); + while self.flights.len() < max_inflight && device.room() { let Some((id, offset, bytes)) = reads.take_asked() else { break; }; diff --git a/crates/stela-compiler/src/x86_64/executed_paths.rs b/crates/stela-compiler/src/x86_64/executed_paths.rs index c6e1530d33..b8aafc1d6e 100644 --- a/crates/stela-compiler/src/x86_64/executed_paths.rs +++ b/crates/stela-compiler/src/x86_64/executed_paths.rs @@ -1,545 +1,545 @@ -//! Which host instructions real blocks execute, run by hand: each block of -//! the sample `DENSITY_IN` names (lines of hex PC, weight and hex bytes) is -//! compiled as a system-mode block and run once in a child process under -//! the x86 trap flag, which records every host instruction it executes. -//! Guest registers point into a scratch arena whose words point back into -//! it, so loads and pointer chasing stay mapped; the anchors point at zeroed -//! areas with the most chain budget, PAC instructions run the cipher -//! inline where the host has AES-NI, as the engine's blocks do, and the -//! pointer-authentication routine returns its input. `DENSITY_OUT` gets, per block, a `B` line -//! (PC, weight, exit, host instructions executed inline, out of line and -//! outside the block, the loop's count, the instructions retired and -//! whether it is a region) and per guest instruction an `S` line (its word, how -//! often its code was entered, host instructions inline, and those out of -//! line that it branched to), then a `C` line (its code, source map, inline -//! end and how often each host instruction ran). Inline is the block's code -//! up to its last instruction's first unconditional jump or return; the -//! rest (side-exit stubs, cold paths, loop copies) is out of line. At the end -//! `T` lines give the weighted host instructions per guest instruction by -//! cause ([`census`]), also printed. -use crate::{ - GuestAddress, GuestState, Options, TargetCpu, - block::{BlockProfile, CompilationPlan, Features}, - x86_64::{MemoryChecks, NativeSystem, RangeCheck, pointer}, -}; -use alloc::{format, string::String, vec, vec::Vec}; -use core::ffi::c_void; -use core::sync::atomic::{AtomicUsize, Ordering}; - -mod census; - -const SIGTRAP: i32 = 5; -const SA_SIGINFO: i32 = 4; -const TRAP_FLAG: u64 = 0x100; -/// `uc_mcontext.gregs` in `ucontext_t`, and REG_RIP / REG_EFL in it. -const GREGS: usize = 40; -const RIP: usize = 16; -const EFLAGS: usize = 17; -const STEPS: usize = 1 << 20; -const OUTSIDE: u32 = u32::MAX; -/// Where the pointer anchor's area holds the cipher's schedules and ranges -/// (empty PAC fields: every pointer is canonical, every authentication -/// succeeds and every result is its pointer). -const CIPHER: u32 = 0x400; - -#[repr(C)] -struct SigAction { - handler: usize, - mask: [u64; 16], - flags: i32, - restorer: usize, -} - -unsafe extern "C" { - fn sigaction(signal: i32, action: *const SigAction, old: *mut SigAction) -> i32; - fn fork() -> i32; - fn pipe(fds: *mut i32) -> i32; - fn read(fd: i32, bytes: *mut c_void, count: usize) -> isize; - fn write(fd: i32, bytes: *const c_void, count: usize) -> isize; - fn close(fd: i32) -> i32; - fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32; - fn alarm(seconds: u32) -> u32; - fn _exit(status: i32) -> !; - fn mmap( - address: *mut c_void, - bytes: usize, - protection: i32, - flags: i32, - fd: i32, - offset: i64, - ) -> *mut c_void; - fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; -} - -static BASE: AtomicUsize = AtomicUsize::new(0); -static LENGTH: AtomicUsize = AtomicUsize::new(0); -static COUNT: AtomicUsize = AtomicUsize::new(0); -static mut TRACE: [u32; STEPS] = [0; STEPS]; - -unsafe extern "C" fn step(_: i32, _: *mut c_void, context: *mut c_void) { - // SAFETY: Linux passes a ucontext_t; gregs holds the interrupted RIP and - // EFLAGS. The child is single threaded. - unsafe { - let gregs = context.cast::().add(GREGS).cast::(); - let rip = *gregs.add(RIP) as usize; - let base = BASE.load(Ordering::Relaxed); - let count = COUNT.load(Ordering::Relaxed); - if count >= STEPS { - *gregs.add(EFLAGS) &= !TRAP_FLAG; - return; - } - let offset = if (base..base + LENGTH.load(Ordering::Relaxed)).contains(&rip) { - (rip - base) as u32 - } else { - OUTSIDE - }; - core::ptr::addr_of_mut!(TRACE) - .cast::() - .add(count) - .write(offset); - COUNT.store(count + 1, Ordering::Relaxed); - } -} - -#[repr(C)] -struct Pair(u64, u64); - -/// The pointer-authentication routine: success, with its input. -extern "sysv64" fn authenticated(_: *mut u8, _: u32, value: u64, _: u64) -> Pair { - Pair(1, value) -} - -fn options() -> Options { - // As the engine's blocks; `REGIONS=0` compiles blocks alone. - options_with(std::env::var("REGIONS").map_or(true, |regions| regions != "0")) -} - -fn options_with(regions: bool) -> Options { - let checks = MemoryChecks::system(true, false, true, false) - .with_range(RangeCheck::four_level(4).one_sided(true)); - let system = NativeSystem { - exclusive: true, - pointer: Some(pointer::inline::Cells { - tags: 0x40, - strips: 0x80, - routine: 0x1c0, - // As the engine's blocks on an AES-NI host: the cipher inline. - cipher: TargetCpu::detect() - .supports(TargetCpu::Aes) - .then_some(CIPHER), - }), - self_loops: true, - regions, - ..NativeSystem::NONE - }; - Options::new( - BlockProfile::new(Features::SYSTEM_MODE), - TargetCpu::detect(), - ) - .with_memory_checks(checks) - .with_native_system(system) -} - -fn map(bytes: usize) -> *mut u8 { - // SAFETY: private anonymous read-write memory. - let page = unsafe { mmap(core::ptr::null_mut(), bytes, 3, 0x22, -1, 0) }; - assert_ne!(page as usize, usize::MAX); - page.cast() -} - -/// Run `entry` (the pinned entry wrapper and the block) in a child under -/// the trap flag; the parent gets the trace and the exit. -fn traced(entry: &[u8], body_offset: usize) -> Option<(u64, u64, u64, Vec)> { - let mut fds = [0i32; 2]; - // SAFETY: plain POSIX calls; the child only runs the block and writes. - unsafe { - assert_eq!(pipe(fds.as_mut_ptr()), 0); - let pid = fork(); - if pid == 0 { - close(fds[0]); - alarm(5); - let code = map(entry.len().next_multiple_of(4096) + 4096); - core::ptr::copy_nonoverlapping(entry.as_ptr(), code, entry.len()); - code.add(entry.len()).write(0xc3); - mprotect(code.cast(), entry.len().next_multiple_of(4096) + 4096, 5); - BASE.store(code as usize + body_offset, Ordering::Relaxed); - LENGTH.store(entry.len() - body_offset, Ordering::Relaxed); - let action = SigAction { - handler: step as unsafe extern "C" fn(i32, *mut c_void, *mut c_void) as usize, - mask: [0; 16], - flags: SA_SIGINFO, - restorer: 0, - }; - sigaction(SIGTRAP, &action, core::ptr::null_mut()); - let state = alloc::boxed::Box::leak(alloc::boxed::Box::new(GuestState::default())); - prepare(state); - // The exit's target and word, in RAX and RDX. - let run: unsafe extern "sysv64" fn(*mut GuestState) -> Pair = - core::mem::transmute(code); - core::arch::asm!("pushfq", "or qword ptr [rsp], 0x100", "popfq"); - let Pair(exit, word) = run(state); - core::arch::asm!("pushfq", "and qword ptr [rsp], -257", "popfq"); - let count = COUNT.load(Ordering::Relaxed); - let trace = - core::slice::from_raw_parts(core::ptr::addr_of!(TRACE).cast::(), count); - write(fds[1], (&raw const exit).cast(), 8); - write(fds[1], (&raw const word).cast(), 8); - // The instructions the chain's account counts and the loop's. - let account = crate::x86_64::chain::Account(state.account); - let retired = account.retired().wrapping_add(state.loop_retired); - write(fds[1], (&raw const retired).cast(), 8); - write(fds[1], (&raw const count).cast(), 8); - let mut sent = 0; - while sent < count * 4 { - let n = write( - fds[1], - trace.as_ptr().cast::().add(sent).cast(), - count * 4 - sent, - ); - if n <= 0 { - break; - } - sent += n as usize; - } - _exit(0); - } - close(fds[1]); - let mut header = [0u64; 3]; - let mut bytes = Vec::new(); - let mut buffer = [0u8; 65536]; - loop { - let n = read(fds[0], buffer.as_mut_ptr().cast(), buffer.len()); - if n <= 0 { - break; - } - bytes.extend_from_slice(&buffer[..n as usize]); - } - close(fds[0]); - let mut status = 0; - waitpid(pid, &mut status, 0); - if status != 0 || bytes.len() < 32 { - return None; - } - header[0] = u64::from_le_bytes(bytes[..8].try_into().unwrap()); - header[1] = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); - header[2] = u64::from_le_bytes(bytes[16..24].try_into().unwrap()); - let trace = bytes[32..] - .as_chunks::<4>() - .0 - .iter() - .map(|chunk| u32::from_le_bytes(*chunk)) - .collect(); - Some((header[0], header[1], header[2], trace)) - } -} - -/// Registers and memory for a run: an 8 MiB arena whose words point into -/// its middle, registers spread over it, IXC set (the usual running -/// state), zeroed anchor areas and the most chain budget. -fn prepare(state: &mut GuestState) { - const ARENA: usize = 8 << 20; - let arena = map(ARENA); - let middle = arena as u64 + (ARENA as u64) / 2; - // SAFETY: the arena is mapped read-write. - unsafe { - let words = arena.cast::(); - for index in 0..ARENA / 8 { - *words.add(index) = middle + ((index as u64 * 8) & 0xffff); - } - } - for (index, register) in state.x.iter_mut().enumerate() { - *register = middle + 0x100 * index as u64; - } - state.sp = middle + 0x10_0000; - state.fpsr = 0x10; - let anchors = map(8 << 16); - let fault = map(4096); - state.unreachable = fault as u64; - state.lower_limit = crate::Limit(u64::MAX); - state.account = super::chain::Account::new(super::chain::MAX_BUDGET).0; - let raw = (state as *mut GuestState).cast::(); - let anchor_offset = core::mem::offset_of!(GuestState, anchors); - // SAFETY: the anchors are eight words in the state; each area is mapped. - unsafe { - for index in 0..8 { - let area = anchors.add(index << 16); - raw.add(anchor_offset + 8 * index) - .cast::() - .write(area as u64); - } - // Open tag words for the cipher, and the pointer routine. - for key in 0..pointer::TAG_WORDS { - anchors - .add(3 << 16) - .add(0x40 + 8 * key) - .cast::() - .write(pointer::tag(1, key as u8, 0)); - } - let ranges = [[false, true].map(|upper| pointer::cipher::Range::new(0, upper, false)); 2]; - anchors - .add(3 << 16) - .add(CIPHER as usize + core::mem::offset_of!(pointer::cipher::Cipher, ranges)) - .cast::<[[pointer::cipher::Range; 2]; 2]>() - .write(ranges); - anchors.add(3 << 16).add(0x1c0).cast::().write( - (authenticated as extern "sysv64" fn(*mut u8, u32, u64, u64) -> Pair) as usize as u64, - ); - } -} - -#[test] -#[ignore = "manual: opt-in"] -fn executed_paths_of_real_blocks() { - use std::io::Write; - let input = std::env::var("DENSITY_IN").expect("DENSITY_IN names the sample"); - let output = std::env::var("DENSITY_OUT").expect("DENSITY_OUT names the output"); - let mut out = std::fs::File::create(output).expect("the output"); - let options = options(); - let mut causes = census::Census::default(); - // The causes in the blocks that compile as regions when regions are on, - // in this run's mode: the same code before and after. - let with_regions = options_with(true); - let mut region_causes = census::Census::default(); - // Weighted guest and host instructions of all blocks and of regions - // (`CompiledBlock::region`), and the weight of each. - let mut shares = [[0_f64; 3]; 2]; - for line in std::fs::read_to_string(input).expect("the sample").lines() { - let mut fields = line.split(' '); - let (Some(pc), Some(weight), Some(hex)) = (fields.next(), fields.next(), fields.next()) - else { - continue; - }; - let pc = u64::from_str_radix(pc, 16).unwrap(); - let source: Vec = (0..hex.len() / 2) - .map(|at| u8::from_str_radix(&hex[2 * at..2 * at + 2], 16).unwrap()) - .collect(); - let Ok(plan) = CompilationPlan::new(&source, GuestAddress(pc), &options) else { - continue; - }; - let Ok(compiled) = plan.compile() else { - continue; - }; - let shaped = compiled.region - || CompilationPlan::new(&source, GuestAddress(pc), &with_regions) - .ok() - .and_then(|plan| plan.compile().ok()) - .is_some_and(|compiled| compiled.region); - let body = &compiled.native.x86_64_code; - let entry = crate::x86_64::pinned::entered(body); - let body_offset = entry.len() - body.len(); - let map = &compiled.native.source_map; - if map.is_empty() { - continue; - } - // Inline: to the last instruction's first unconditional jump or ret. - let last = map[map.len() - 1].1; - let inline_end = inline_end(body, last); - let Some((exit, word, looped, trace)) = traced(&entry, body_offset) else { - writeln!(out, "X {pc:x} {weight}").unwrap(); - continue; - }; - let span_of = |offset: u32| { - map.iter() - .rposition(|&(_, start)| start as u32 <= offset) - .unwrap_or(0) - }; - let mut entered = vec![0u32; map.len()]; - let mut inline = vec![0u32; map.len()]; - let mut cold = vec![0u32; map.len()]; - let (mut inside, mut outside, mut out_of_line) = (0u32, 0u32, 0u32); - let mut current = usize::MAX; - let first = trace - .iter() - .position(|&o| o != OUTSIDE) - .unwrap_or(trace.len()); - let end = trace - .iter() - .rposition(|&o| o != OUTSIDE) - .map_or(first, |at| at + 1); - for &offset in &trace[first..end] { - if offset == OUTSIDE { - outside += 1; - continue; - } - if (offset as usize) < inline_end { - inside += 1; - let span = span_of(offset); - if span != current { - entered[span] += 1; - current = span; - } - inline[span] += 1; - } else { - out_of_line += 1; - if current < map.len() { - cold[current] += 1; - } - } - } - // The instructions retired: what the exit counts (a branch's the - // rows it did not skip, any other the ones before it) and what the - // chain and the loop counted besides. - let (kind, skipped) = crate::x86_64::chain::ExitWord::split(word); - use crate::block::ExitKind; - let counted = match ExitKind::try_from(kind) { - Ok( - ExitKind::Fallthrough - | ExitKind::Direct - | ExitKind::Indirect - | ExitKind::Call - | ExitKind::Return, - ) => (map.len() as u64).saturating_sub(u64::from(skipped)), - _ => exit.wrapping_sub(pc) / 4, - }; - let guest = looped.wrapping_add(counted); - writeln!( - out, - "B {pc:x} {weight} {exit:x} {inside} {out_of_line} {outside} {looped} {guest} {}", - u8::from(compiled.region) - ) - .unwrap(); - for (index, &(guest, _)) in map.iter().enumerate() { - let at = (guest.0 - pc) as usize; - let word = u32::from_le_bytes(source[at..at + 4].try_into().unwrap()); - writeln!( - out, - "S {word:08x} {} {} {}", - entered[index], inline[index], cold[index] - ) - .unwrap(); - } - // The code, its source map and how often each host instruction ran, - // for a per-cause census of the executed instructions. - let mut runs = alloc::collections::BTreeMap::::new(); - for &offset in &trace[first..end] { - if offset != OUTSIDE { - *runs.entry(offset).or_default() += 1; - } - } - let code: String = body.iter().map(|byte| format!("{byte:02x}")).collect(); - let spans: Vec = map - .iter() - .map(|(guest, offset)| format!("{:x}:{offset}", guest.0)) - .collect(); - let counts: Vec = runs - .iter() - .map(|(offset, count)| format!("{offset:x}:{count}")) - .collect(); - writeln!( - out, - "C {code} {} {inline_end:x} {}", - spans.join(","), - counts.join(",") - ) - .unwrap(); - let weighted: f64 = weight.parse().unwrap_or(1.0); - for (index, share) in shares.iter_mut().enumerate() { - if index == 0 || shaped { - share[0] += weighted * guest as f64; - share[1] += weighted * f64::from(inside + out_of_line); - share[2] += weighted; - } - } - let traced = census::Traced { - weight: weight.parse().unwrap_or(1), - guest, - pc, - source: &source, - code: body, - map, - inline_end, - runs: &runs, - }; - causes.add(&traced); - if shaped { - region_causes.add(&traced); - } - } - let [all, regions] = shares; - let table = format!( - "{}{}R regions weight={:.1}% guest={:.1}% host_per_guest={:.3} (all {:.3})\n", - causes.table(), - region_causes.table().replace("T ", "RT "), - 100.0 * regions[2] / all[2].max(1.0), - 100.0 * regions[0] / all[0].max(1.0), - regions[1] / regions[0].max(1.0), - all[1] / all[0].max(1.0), - ); - write!(out, "{table}").unwrap(); - std::print!("{table}"); -} - -/// The end of a block's inline code: past the first unconditional jump or -/// return at or after `last` (the last instruction's start); the whole code -/// when there is none. -fn inline_end(body: &[u8], last: usize) -> usize { - // Decoded by objdump: exact for every form the emitter uses. - let listing = census::listing(&body[last..]); - let mut lines = listing.iter().peekable(); - while let Some((_, text)) = lines.next() { - if text.starts_with("jmp") || text.starts_with("ret") { - return last + lines.peek().map_or(body.len() - last, |(next, _)| *next); - } - } - body.len() -} - -/// What the value allocator would save system-mode blocks, run by hand: -/// each block of `DENSITY_IN` compiled as a system-mode block (pinned set, -/// fault table, no regions) into `DENSITY_OUT`, and as a process block -/// (regions and the value allocator over all twelve hosts, no pinned set -/// or fault table) into `DENSITY_OUT.process`, in `density_dump`'s format -/// (`pc weight source-bytes hex-code pc:offset,...`). The process code -/// bounds what an unconstrained allocator (variant C, before recovery -/// rows) can reach on the same instructions. -#[test] -#[ignore = "manual: opt-in"] -fn allocator_bound_census() { - use std::io::Write; - let input = std::env::var("DENSITY_IN").expect("DENSITY_IN names the sample"); - let output = std::env::var("DENSITY_OUT").expect("DENSITY_OUT names the output"); - let process = Options::new( - BlockProfile::new(Features::POINTER_AUTHENTICATION), - TargetCpu::detect(), - ); - for (options, path) in [(options(), output.clone()), (process, output + ".process")] { - let mut out = std::fs::File::create(path).expect("the output"); - for line in std::fs::read_to_string(&input).expect("the sample").lines() { - let mut fields = line.split(' '); - let (Some(pc), Some(weight), Some(hex)) = (fields.next(), fields.next(), fields.next()) - else { - continue; - }; - let pc = u64::from_str_radix(pc, 16).unwrap(); - let source: Vec = (0..hex.len() / 2) - .map(|at| u8::from_str_radix(&hex[2 * at..2 * at + 2], 16).unwrap()) - .collect(); - let compiled = CompilationPlan::new(&source, GuestAddress(pc), &options) - .ok() - .and_then(|plan| plan.compile().ok()); - let Some(compiled) = compiled else { - writeln!(out, "{pc:x} {weight} refused").unwrap(); - continue; - }; - let code: String = compiled - .native - .x86_64_code - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); - let map: Vec = compiled - .native - .source_map - .iter() - .map(|(pc, offset)| format!("{:x}:{offset}", pc.0)) - .collect(); - writeln!( - out, - "{pc:x} {weight} {} {code} {}", - compiled.source_bytes, - map.join(",") - ) - .unwrap(); - } - } -} +//! Which host instructions real blocks execute, run by hand: each block of +//! the sample `DENSITY_IN` names (lines of hex PC, weight and hex bytes) is +//! compiled as a system-mode block and run once in a child process under +//! the x86 trap flag, which records every host instruction it executes. +//! Guest registers point into a scratch arena whose words point back into +//! it, so loads and pointer chasing stay mapped; the anchors point at zeroed +//! areas with the most chain budget, PAC instructions run the cipher +//! inline where the host has AES-NI, as the engine's blocks do, and the +//! pointer-authentication routine returns its input. `DENSITY_OUT` gets, per block, a `B` line +//! (PC, weight, exit, host instructions executed inline, out of line and +//! outside the block, the loop's count, the instructions retired and +//! whether it is a region) and per guest instruction an `S` line (its word, how +//! often its code was entered, host instructions inline, and those out of +//! line that it branched to), then a `C` line (its code, source map, inline +//! end and how often each host instruction ran). Inline is the block's code +//! up to its last instruction's first unconditional jump or return; the +//! rest (side-exit stubs, cold paths, loop copies) is out of line. At the end +//! `T` lines give the weighted host instructions per guest instruction by +//! cause ([`census`]), also printed. +use crate::{ + GuestAddress, GuestState, Options, TargetCpu, + block::{BlockProfile, CompilationPlan, Features}, + x86_64::{MemoryChecks, NativeSystem, RangeCheck, pointer}, +}; +use alloc::{format, string::String, vec, vec::Vec}; +use core::ffi::c_void; +use core::sync::atomic::{AtomicUsize, Ordering}; + +mod census; + +const SIGTRAP: i32 = 5; +const SA_SIGINFO: i32 = 4; +const TRAP_FLAG: u64 = 0x100; +/// `uc_mcontext.gregs` in `ucontext_t`, and REG_RIP / REG_EFL in it. +const GREGS: usize = 40; +const RIP: usize = 16; +const EFLAGS: usize = 17; +const STEPS: usize = 1 << 20; +const OUTSIDE: u32 = u32::MAX; +/// Where the pointer anchor's area holds the cipher's schedules and ranges +/// (empty PAC fields: every pointer is canonical, every authentication +/// succeeds and every result is its pointer). +const CIPHER: u32 = 0x400; + +#[repr(C)] +struct SigAction { + handler: usize, + mask: [u64; 16], + flags: i32, + restorer: usize, +} + +unsafe extern "C" { + fn sigaction(signal: i32, action: *const SigAction, old: *mut SigAction) -> i32; + fn fork() -> i32; + fn pipe(fds: *mut i32) -> i32; + fn read(fd: i32, bytes: *mut c_void, count: usize) -> isize; + fn write(fd: i32, bytes: *const c_void, count: usize) -> isize; + fn close(fd: i32) -> i32; + fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32; + fn alarm(seconds: u32) -> u32; + fn _exit(status: i32) -> !; + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; +} + +static BASE: AtomicUsize = AtomicUsize::new(0); +static LENGTH: AtomicUsize = AtomicUsize::new(0); +static COUNT: AtomicUsize = AtomicUsize::new(0); +static mut TRACE: [u32; STEPS] = [0; STEPS]; + +unsafe extern "C" fn step(_: i32, _: *mut c_void, context: *mut c_void) { + // SAFETY: Linux passes a ucontext_t; gregs holds the interrupted RIP and + // EFLAGS. The child is single threaded. + unsafe { + let gregs = context.cast::().add(GREGS).cast::(); + let rip = *gregs.add(RIP) as usize; + let base = BASE.load(Ordering::Relaxed); + let count = COUNT.load(Ordering::Relaxed); + if count >= STEPS { + *gregs.add(EFLAGS) &= !TRAP_FLAG; + return; + } + let offset = if (base..base + LENGTH.load(Ordering::Relaxed)).contains(&rip) { + (rip - base) as u32 + } else { + OUTSIDE + }; + core::ptr::addr_of_mut!(TRACE) + .cast::() + .add(count) + .write(offset); + COUNT.store(count + 1, Ordering::Relaxed); + } +} + +#[repr(C)] +struct Pair(u64, u64); + +/// The pointer-authentication routine: success, with its input. +extern "sysv64" fn authenticated(_: *mut u8, _: u32, value: u64, _: u64) -> Pair { + Pair(1, value) +} + +fn options() -> Options { + // As the engine's blocks; `REGIONS=0` compiles blocks alone. + options_with(std::env::var("REGIONS").map_or(true, |regions| regions != "0")) +} + +fn options_with(regions: bool) -> Options { + let checks = MemoryChecks::system(true, false, true, false) + .with_range(RangeCheck::four_level(4).one_sided(true)); + let system = NativeSystem { + exclusive: true, + pointer: Some(pointer::inline::Cells { + tags: 0x40, + strips: 0x80, + routine: 0x1c0, + // As the engine's blocks on an AES-NI host: the cipher inline. + cipher: TargetCpu::detect() + .supports(TargetCpu::Aes) + .then_some(CIPHER), + }), + self_loops: true, + regions, + ..NativeSystem::NONE + }; + Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::detect(), + ) + .with_memory_checks(checks) + .with_native_system(system) +} + +fn map(bytes: usize) -> *mut u8 { + // SAFETY: private anonymous read-write memory. + let page = unsafe { mmap(core::ptr::null_mut(), bytes, 3, 0x22, -1, 0) }; + assert_ne!(page as usize, usize::MAX); + page.cast() +} + +/// Run `entry` (the pinned entry wrapper and the block) in a child under +/// the trap flag; the parent gets the trace and the exit. +fn traced(entry: &[u8], body_offset: usize) -> Option<(u64, u64, u64, Vec)> { + let mut fds = [0i32; 2]; + // SAFETY: plain POSIX calls; the child only runs the block and writes. + unsafe { + assert_eq!(pipe(fds.as_mut_ptr()), 0); + let pid = fork(); + if pid == 0 { + close(fds[0]); + alarm(5); + let code = map(entry.len().next_multiple_of(4096) + 4096); + core::ptr::copy_nonoverlapping(entry.as_ptr(), code, entry.len()); + code.add(entry.len()).write(0xc3); + mprotect(code.cast(), entry.len().next_multiple_of(4096) + 4096, 5); + BASE.store(code as usize + body_offset, Ordering::Relaxed); + LENGTH.store(entry.len() - body_offset, Ordering::Relaxed); + let action = SigAction { + handler: step as unsafe extern "C" fn(i32, *mut c_void, *mut c_void) as usize, + mask: [0; 16], + flags: SA_SIGINFO, + restorer: 0, + }; + sigaction(SIGTRAP, &action, core::ptr::null_mut()); + let state = alloc::boxed::Box::leak(alloc::boxed::Box::new(GuestState::default())); + prepare(state); + // The exit's target and word, in RAX and RDX. + let run: unsafe extern "sysv64" fn(*mut GuestState) -> Pair = + core::mem::transmute(code); + core::arch::asm!("pushfq", "or qword ptr [rsp], 0x100", "popfq"); + let Pair(exit, word) = run(state); + core::arch::asm!("pushfq", "and qword ptr [rsp], -257", "popfq"); + let count = COUNT.load(Ordering::Relaxed); + let trace = + core::slice::from_raw_parts(core::ptr::addr_of!(TRACE).cast::(), count); + write(fds[1], (&raw const exit).cast(), 8); + write(fds[1], (&raw const word).cast(), 8); + // The instructions the chain's account counts and the loop's. + let account = crate::x86_64::chain::Account(state.account); + let retired = account.retired().wrapping_add(state.loop_retired); + write(fds[1], (&raw const retired).cast(), 8); + write(fds[1], (&raw const count).cast(), 8); + let mut sent = 0; + while sent < count * 4 { + let n = write( + fds[1], + trace.as_ptr().cast::().add(sent).cast(), + count * 4 - sent, + ); + if n <= 0 { + break; + } + sent += n as usize; + } + _exit(0); + } + close(fds[1]); + let mut header = [0u64; 3]; + let mut bytes = Vec::new(); + let mut buffer = [0u8; 65536]; + loop { + let n = read(fds[0], buffer.as_mut_ptr().cast(), buffer.len()); + if n <= 0 { + break; + } + bytes.extend_from_slice(&buffer[..n as usize]); + } + close(fds[0]); + let mut status = 0; + waitpid(pid, &mut status, 0); + if status != 0 || bytes.len() < 32 { + return None; + } + header[0] = u64::from_le_bytes(bytes[..8].try_into().unwrap()); + header[1] = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); + header[2] = u64::from_le_bytes(bytes[16..24].try_into().unwrap()); + let trace = bytes[32..] + .as_chunks::<4>() + .0 + .iter() + .map(|chunk| u32::from_le_bytes(*chunk)) + .collect(); + Some((header[0], header[1], header[2], trace)) + } +} + +/// Registers and memory for a run: an 8 MiB arena whose words point into +/// its middle, registers spread over it, IXC set (the usual running +/// state), zeroed anchor areas and the most chain budget. +fn prepare(state: &mut GuestState) { + const ARENA: usize = 8 << 20; + let arena = map(ARENA); + let middle = arena as u64 + (ARENA as u64) / 2; + // SAFETY: the arena is mapped read-write. + unsafe { + let words = arena.cast::(); + for index in 0..ARENA / 8 { + *words.add(index) = middle + ((index as u64 * 8) & 0xffff); + } + } + for (index, register) in state.x.iter_mut().enumerate() { + *register = middle + 0x100 * index as u64; + } + state.sp = middle + 0x10_0000; + state.fpsr = 0x10; + let anchors = map(8 << 16); + let fault = map(4096); + state.unreachable = fault as u64; + state.lower_limit = crate::Limit(u64::MAX); + state.account = super::chain::Account::new(super::chain::MAX_BUDGET).0; + let raw = (state as *mut GuestState).cast::(); + let anchor_offset = core::mem::offset_of!(GuestState, anchors); + // SAFETY: the anchors are eight words in the state; each area is mapped. + unsafe { + for index in 0..8 { + let area = anchors.add(index << 16); + raw.add(anchor_offset + 8 * index) + .cast::() + .write(area as u64); + } + // Open tag words for the cipher, and the pointer routine. + for key in 0..pointer::TAG_WORDS { + anchors + .add(3 << 16) + .add(0x40 + 8 * key) + .cast::() + .write(pointer::tag(1, key as u8, 0)); + } + let ranges = [[false, true].map(|upper| pointer::cipher::Range::new(0, upper, false, false)); 2]; + anchors + .add(3 << 16) + .add(CIPHER as usize + core::mem::offset_of!(pointer::cipher::Cipher, ranges)) + .cast::<[[pointer::cipher::Range; 2]; 2]>() + .write(ranges); + anchors.add(3 << 16).add(0x1c0).cast::().write( + (authenticated as extern "sysv64" fn(*mut u8, u32, u64, u64) -> Pair) as usize as u64, + ); + } +} + +#[test] +#[ignore = "manual: opt-in"] +fn executed_paths_of_real_blocks() { + use std::io::Write; + let input = std::env::var("DENSITY_IN").expect("DENSITY_IN names the sample"); + let output = std::env::var("DENSITY_OUT").expect("DENSITY_OUT names the output"); + let mut out = std::fs::File::create(output).expect("the output"); + let options = options(); + let mut causes = census::Census::default(); + // The causes in the blocks that compile as regions when regions are on, + // in this run's mode: the same code before and after. + let with_regions = options_with(true); + let mut region_causes = census::Census::default(); + // Weighted guest and host instructions of all blocks and of regions + // (`CompiledBlock::region`), and the weight of each. + let mut shares = [[0_f64; 3]; 2]; + for line in std::fs::read_to_string(input).expect("the sample").lines() { + let mut fields = line.split(' '); + let (Some(pc), Some(weight), Some(hex)) = (fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let pc = u64::from_str_radix(pc, 16).unwrap(); + let source: Vec = (0..hex.len() / 2) + .map(|at| u8::from_str_radix(&hex[2 * at..2 * at + 2], 16).unwrap()) + .collect(); + let Ok(plan) = CompilationPlan::new(&source, GuestAddress(pc), &options) else { + continue; + }; + let Ok(compiled) = plan.compile() else { + continue; + }; + let shaped = compiled.region + || CompilationPlan::new(&source, GuestAddress(pc), &with_regions) + .ok() + .and_then(|plan| plan.compile().ok()) + .is_some_and(|compiled| compiled.region); + let body = &compiled.native.x86_64_code; + let entry = crate::x86_64::pinned::entered(body); + let body_offset = entry.len() - body.len(); + let map = &compiled.native.source_map; + if map.is_empty() { + continue; + } + // Inline: to the last instruction's first unconditional jump or ret. + let last = map[map.len() - 1].1; + let inline_end = inline_end(body, last); + let Some((exit, word, looped, trace)) = traced(&entry, body_offset) else { + writeln!(out, "X {pc:x} {weight}").unwrap(); + continue; + }; + let span_of = |offset: u32| { + map.iter() + .rposition(|&(_, start)| start as u32 <= offset) + .unwrap_or(0) + }; + let mut entered = vec![0u32; map.len()]; + let mut inline = vec![0u32; map.len()]; + let mut cold = vec![0u32; map.len()]; + let (mut inside, mut outside, mut out_of_line) = (0u32, 0u32, 0u32); + let mut current = usize::MAX; + let first = trace + .iter() + .position(|&o| o != OUTSIDE) + .unwrap_or(trace.len()); + let end = trace + .iter() + .rposition(|&o| o != OUTSIDE) + .map_or(first, |at| at + 1); + for &offset in &trace[first..end] { + if offset == OUTSIDE { + outside += 1; + continue; + } + if (offset as usize) < inline_end { + inside += 1; + let span = span_of(offset); + if span != current { + entered[span] += 1; + current = span; + } + inline[span] += 1; + } else { + out_of_line += 1; + if current < map.len() { + cold[current] += 1; + } + } + } + // The instructions retired: what the exit counts (a branch's the + // rows it did not skip, any other the ones before it) and what the + // chain and the loop counted besides. + let (kind, skipped) = crate::x86_64::chain::ExitWord::split(word); + use crate::block::ExitKind; + let counted = match ExitKind::try_from(kind) { + Ok( + ExitKind::Fallthrough + | ExitKind::Direct + | ExitKind::Indirect + | ExitKind::Call + | ExitKind::Return, + ) => (map.len() as u64).saturating_sub(u64::from(skipped)), + _ => exit.wrapping_sub(pc) / 4, + }; + let guest = looped.wrapping_add(counted); + writeln!( + out, + "B {pc:x} {weight} {exit:x} {inside} {out_of_line} {outside} {looped} {guest} {}", + u8::from(compiled.region) + ) + .unwrap(); + for (index, &(guest, _)) in map.iter().enumerate() { + let at = (guest.0 - pc) as usize; + let word = u32::from_le_bytes(source[at..at + 4].try_into().unwrap()); + writeln!( + out, + "S {word:08x} {} {} {}", + entered[index], inline[index], cold[index] + ) + .unwrap(); + } + // The code, its source map and how often each host instruction ran, + // for a per-cause census of the executed instructions. + let mut runs = alloc::collections::BTreeMap::::new(); + for &offset in &trace[first..end] { + if offset != OUTSIDE { + *runs.entry(offset).or_default() += 1; + } + } + let code: String = body.iter().map(|byte| format!("{byte:02x}")).collect(); + let spans: Vec = map + .iter() + .map(|(guest, offset)| format!("{:x}:{offset}", guest.0)) + .collect(); + let counts: Vec = runs + .iter() + .map(|(offset, count)| format!("{offset:x}:{count}")) + .collect(); + writeln!( + out, + "C {code} {} {inline_end:x} {}", + spans.join(","), + counts.join(",") + ) + .unwrap(); + let weighted: f64 = weight.parse().unwrap_or(1.0); + for (index, share) in shares.iter_mut().enumerate() { + if index == 0 || shaped { + share[0] += weighted * guest as f64; + share[1] += weighted * f64::from(inside + out_of_line); + share[2] += weighted; + } + } + let traced = census::Traced { + weight: weight.parse().unwrap_or(1), + guest, + pc, + source: &source, + code: body, + map, + inline_end, + runs: &runs, + }; + causes.add(&traced); + if shaped { + region_causes.add(&traced); + } + } + let [all, regions] = shares; + let table = format!( + "{}{}R regions weight={:.1}% guest={:.1}% host_per_guest={:.3} (all {:.3})\n", + causes.table(), + region_causes.table().replace("T ", "RT "), + 100.0 * regions[2] / all[2].max(1.0), + 100.0 * regions[0] / all[0].max(1.0), + regions[1] / regions[0].max(1.0), + all[1] / all[0].max(1.0), + ); + write!(out, "{table}").unwrap(); + std::print!("{table}"); +} + +/// The end of a block's inline code: past the first unconditional jump or +/// return at or after `last` (the last instruction's start); the whole code +/// when there is none. +fn inline_end(body: &[u8], last: usize) -> usize { + // Decoded by objdump: exact for every form the emitter uses. + let listing = census::listing(&body[last..]); + let mut lines = listing.iter().peekable(); + while let Some((_, text)) = lines.next() { + if text.starts_with("jmp") || text.starts_with("ret") { + return last + lines.peek().map_or(body.len() - last, |(next, _)| *next); + } + } + body.len() +} + +/// What the value allocator would save system-mode blocks, run by hand: +/// each block of `DENSITY_IN` compiled as a system-mode block (pinned set, +/// fault table, no regions) into `DENSITY_OUT`, and as a process block +/// (regions and the value allocator over all twelve hosts, no pinned set +/// or fault table) into `DENSITY_OUT.process`, in `density_dump`'s format +/// (`pc weight source-bytes hex-code pc:offset,...`). The process code +/// bounds what an unconstrained allocator (variant C, before recovery +/// rows) can reach on the same instructions. +#[test] +#[ignore = "manual: opt-in"] +fn allocator_bound_census() { + use std::io::Write; + let input = std::env::var("DENSITY_IN").expect("DENSITY_IN names the sample"); + let output = std::env::var("DENSITY_OUT").expect("DENSITY_OUT names the output"); + let process = Options::new( + BlockProfile::new(Features::POINTER_AUTHENTICATION), + TargetCpu::detect(), + ); + for (options, path) in [(options(), output.clone()), (process, output + ".process")] { + let mut out = std::fs::File::create(path).expect("the output"); + for line in std::fs::read_to_string(&input).expect("the sample").lines() { + let mut fields = line.split(' '); + let (Some(pc), Some(weight), Some(hex)) = (fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let pc = u64::from_str_radix(pc, 16).unwrap(); + let source: Vec = (0..hex.len() / 2) + .map(|at| u8::from_str_radix(&hex[2 * at..2 * at + 2], 16).unwrap()) + .collect(); + let compiled = CompilationPlan::new(&source, GuestAddress(pc), &options) + .ok() + .and_then(|plan| plan.compile().ok()); + let Some(compiled) = compiled else { + writeln!(out, "{pc:x} {weight} refused").unwrap(); + continue; + }; + let code: String = compiled + .native + .x86_64_code + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let map: Vec = compiled + .native + .source_map + .iter() + .map(|(pc, offset)| format!("{:x}:{offset}", pc.0)) + .collect(); + writeln!( + out, + "{pc:x} {weight} {} {code} {}", + compiled.source_bytes, + map.join(",") + ) + .unwrap(); + } + } +} diff --git a/crates/stela-compiler/src/x86_64/hle/compare.rs b/crates/stela-compiler/src/x86_64/hle/compare.rs index 5338e84b32..db385d2a01 100644 --- a/crates/stela-compiler/src/x86_64/hle/compare.rs +++ b/crates/stela-compiler/src/x86_64/hle/compare.rs @@ -91,9 +91,10 @@ pub(super) fn memcmp(code: &mut Code, request: Request, bails: &mut Bails) -> Ve let mut asm = code.asm(); asm.movzx(Size::Dword, Gpr::Rax, Size::Byte, at(a, Some(Gpr::Rdx), 0)); asm.movzx(Size::Dword, Gpr::R10, Size::Byte, at(b, Some(Gpr::Rdx), 0)); - asm.alu(Alu::Sub, Size::Dword, Gpr::Rax, Gpr::R10); - // The commit: X0, zero-extended from its low word. - asm.mov(Size::Dword, Gpr::R15, Gpr::Rax); + asm.alu(Alu::Sub, Size::Qword, Gpr::Rax, Gpr::R10); + // The commit: X0, 64-bit signed difference `i64(a[i]) - i64(b[i])` + // matching Apple's `__platform_memcmp` (`sub x0, ...`). + asm.mov(Size::Qword, Gpr::R15, Gpr::Rax); } let mut done = Label::default(); done.jump(code); diff --git a/crates/stela-compiler/src/x86_64/pointer/cipher.rs b/crates/stela-compiler/src/x86_64/pointer/cipher.rs index db487e8cce..ec2da0480f 100644 --- a/crates/stela-compiler/src/x86_64/pointer/cipher.rs +++ b/crates/stela-compiler/src/x86_64/pointer/cipher.rs @@ -1,218 +1,246 @@ -//! PAC instructions computed in native code, without the memo. -//! -//! Where the host has AES-NI, the engine's PAC cipher is the whitening key -//! and six full AES rounds of the pointer and modifier under the key -//! (`pauth::keyed`, the PAC algorithm Apple silicon leaves IMPLEMENTATION -//! DEFINED), whose state's low half is the PAC. Native code runs those -//! rounds in fewer instructions than a memo miss spends reaching the -//! service, and a memo hit is a load from a table far larger than the -//! caches. So a block or thunk given a [`Cipher`] computes every signing, -//! successful authentication and PACGA itself, from what the engine keeps -//! there for the current keys, PAC version and TCR: each key's schedule -//! (the whitening key and six round keys) and, for each domain, the PAC -//! field of each range ([`Range`]). -//! -//! Native code completes canonical pointers only, whose extension bits all -//! equal bit 55. For them Arm `AddPAC` and `Auth` take one layout, the one -//! bit 55 selects (a signing that selects by bit 63 sees the same bit -//! there), so the range table is indexed by bit 55 alone. With `E` that -//! range's extension mask, `M` it without bit 55 and `pac` the cipher of -//! the input: -//! - a signing of a canonical pointer (`p & E` is the range's canonical -//! extension) has the pointer as its input and gives -//! `p ^ (pac & M) ^ signed`, where `signed` turns the classic insertion, -//! which replaces an upper pointer's all-ones field, into that XOR; -//! - an authentication's input is `p` stripped, `(p & !E) | canonical`; it -//! succeeds exactly when `(p ^ pac) & M` is the range's `authenticated` -//! (the input's field under FEAT_PAuth2's XOR, zero under the classic -//! comparison), and then gives its input; -//! - PACGA gives the cipher's upper half. -//! -//! A key whose tag word is [`super::DISABLED`] (its SCTLR enable clear) -//! gives the pointer unchanged, as Arm does, from the tag word alone: native -//! transitions switch the tag words between two exception levels of one -//! memo generation (`transition::check_pointer`), whose enables differ while -//! their keys, version and layouts do not, so nothing else in the cipher -//! may depend on an enable. One compare tells an open key from a closed or -//! disabled one; the out-of-line path then tells those two apart -//! (`Lookup::unopened`). Everything else, a closed key (tag word -//! zero), a signing of a non-canonical pointer and a failed authentication, -//! goes to the service as a memo miss does, which computes it the engine's -//! way. The computation clobbers RAX, R8 to R11, XMM0, XMM1 and flags. -use super::{GENERIC_KEY, Lookup, TAG_WORDS, operands}; -use crate::Place; -use crate::x86_64::asm::{Alu, Asm, BitTest, Cond, Gpr, Mem, Rm, ShiftOp, Size}; -use alloc::vec::Vec; - -/// The words of a key's schedule: the whitening key and six round keys, -/// each low quadword first. -pub const SCHEDULE: usize = 7; - -/// The bit that selects a canonical pointer's range: Arm keeps it in a -/// signed pointer. -const RANGE_BIT: u8 = 55; - -/// Where one range of one domain puts its PAC field, as native code applies -/// it to canonical pointers ([`Range::new`]). -#[repr(C, align(64))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Range { - /// `E`: the extension bits, from bit 64 - TnSZ to the top PAC bit. - pub extension: u64, - /// `!E`: the bits a stripped pointer keeps. - pub kept: u64, - /// A canonical pointer's extension in this range: zero in the lower - /// range, `E` in the upper one. - pub canonical: u64, - /// `M`: `E` without bit 55, the PAC field. - pub field: u64, - /// What a signing XORs into the field besides the PAC: `M` in the upper - /// range under the classic insertion, which replaces the field (all - /// ones there), else zero. - pub signed: u64, - /// What `(p ^ pac) & M` is for an authentic `p`: `M` in the upper range - /// under FEAT_PAuth2, which XORs the PAC into the field (all ones in - /// the input), else zero. - pub authenticated: u64, -} - -impl Range { - /// The range whose extension mask is `extension` (it holds bit 55), the - /// upper one if `upper`, under the classic insertion if `classic`. - pub const fn new(extension: u64, upper: bool, classic: bool) -> Self { - let field = extension & !(1 << RANGE_BIT); - Self { - extension, - kept: !extension, - canonical: if upper { extension } else { 0 }, - field, - signed: if upper && classic { field } else { 0 }, - authenticated: if upper && !classic { field } else { 0 }, - } - } -} - -/// What native code computes PAC results from, at a fixed host address. -#[repr(C, align(64))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Cipher { - /// Each tag word's key schedule ([`SCHEDULE`]). - pub schedules: [[[u64; 2]; SCHEDULE]; TAG_WORDS], - /// The instruction keys' ranges, then the data keys', each by bit 55. - pub ranges: [[Range; 2]; 2], -} - -const SCHEDULES: usize = core::mem::offset_of!(Cipher, schedules); -const RANGES: usize = core::mem::offset_of!(Cipher, ranges); -/// Bytes of a [`Range`], which bit 55 indexes. -const RANGE_BYTES: i32 = core::mem::size_of::() as i32; -const _: () = assert!(RANGE_BYTES == 64 && SCHEDULES.is_multiple_of(16)); -const EXTENSION: usize = core::mem::offset_of!(Range, extension); -const KEPT: usize = core::mem::offset_of!(Range, kept); -const CANONICAL: usize = core::mem::offset_of!(Range, canonical); -const FIELD: usize = core::mem::offset_of!(Range, field); -const SIGNED: usize = core::mem::offset_of!(Range, signed); -const AUTHENTICATED: usize = core::mem::offset_of!(Range, authenticated); - -/// `operation` on XMM0 with ModRM.rm `rm`, a legacy SSE form. -fn sse(asm: &mut Asm, opcode: &[u8], rm: impl Into) { - asm.sse(Some(0x66), opcode, 0, rm); -} - -/// The cipher of `data` and `modifier` under the schedule at R8 + -/// `schedule` into XMM0, whose low half is the PAC: the whitening key and -/// the six AES rounds of `pauth::keyed`. Clobbers XMM1. -fn rounds(asm: &mut Asm, data: Gpr, modifier: Gpr, schedule: i32) { - const PXOR: [u8; 2] = [0x0f, 0xef]; - const AESENC: [u8; 3] = [0x0f, 0x38, 0xdc]; - asm.movq_to_xmm(0, data); - asm.movq_to_xmm(1, modifier); - asm.punpcklqdq(0, Rm::Xmm(1)); - let word = |index: i32| Mem::base(Gpr::R8, schedule + 16 * index); - sse(asm, &PXOR, word(0)); - for round in 1..SCHEDULE as i32 { - sse(asm, &AESENC, word(round)); - } -} - -/// R11 the byte offset of the range bit 55 of RAX selects: 0 or -/// [`RANGE_BYTES`]. -fn range_index(asm: &mut Asm) { - use Gpr::{R11, Rax}; - asm.bit_imm(BitTest::Bt, Size::Qword, Rax, RANGE_BIT); - asm.alu(Alu::Sbb, Size::Qword, R11, R11); - asm.alu_imm8(Alu::And, Size::Dword, R11, RANGE_BYTES as i8); -} - -/// The result of `form` on its operands, computed from the [`Cipher`] at -/// `cipher` under the tag words at `tags` (one anchor): RAX the result, the -/// misses' jumps with RAX the pointer and the modifier in its register, as -/// [`super::lookup`] leaves them, and the jump taken while the key is not -/// open. -pub(super) fn compute(asm: &mut Asm, form: super::Form, tags: Place, cipher: Place) -> Lookup { - use Gpr::{R8, R9, R10, R11, Rax}; - use Size::Qword; - assert_eq!( - tags.anchor, cipher.anchor, - "the tag words and cipher share an anchor" - ); - let modifier = operands(asm, form); - debug_assert!(!matches!(modifier, R9 | R10 | R11)); - asm.place(R8, Place::new(tags.anchor, 0)); - let at = |offset: usize| i32::try_from(cipher.offset + offset).expect("a cipher field offset"); - // Every open key's tag word is above the disabled one's, and a closed - // key's is below it. - let word = i32::try_from(tags.offset + usize::from(form.key) * 8).expect("a tag word offset"); - asm.alu_imm32(Alu::Cmp, Qword, Mem::base(R8, word), super::DISABLED as i32); - let unopened = asm.jcc(Cond::Be); - let schedule = at(SCHEDULES + usize::from(form.key) * SCHEDULE * 16); - if form.key == GENERIC_KEY { - // The generic key is never disabled: a closed one misses. - rounds(asm, Rax, modifier, schedule); - asm.movq_from_xmm(Rax, 0); - asm.shift_imm(ShiftOp::Shr, Qword, Rax, 32); - asm.shift_imm(ShiftOp::Shl, Qword, Rax, 32); - return Lookup { - misses: alloc::vec![unopened], - modifier, - unopened: None, - }; - } - let data = form.key >= super::key_index(crate::block::PointerAuthenticationKey::Da); - let domain = RANGES + usize::from(data) * 2 * RANGE_BYTES as usize; - let range = |field: usize| Mem::indexed(R8, R11, 1, at(domain + field)); - let mut misses = Vec::new(); - if form.kind != super::AUTHENTICATED { - // The cipher of the pointer itself, a canonical one's input. - rounds(asm, Rax, modifier, schedule); - range_index(asm); - asm.mov(Qword, R10, Rax); - asm.alu_load(Alu::And, Qword, R10, range(EXTENSION)); - asm.alu_load(Alu::Cmp, Qword, R10, range(CANONICAL)); - misses.push(asm.jcc(Cond::Ne)); - // p ^ (pac & M) ^ signed. - asm.movq_from_xmm(R9, 0); - asm.alu_load(Alu::And, Qword, R9, range(FIELD)); - asm.alu_load(Alu::Xor, Qword, R9, range(SIGNED)); - asm.alu(Alu::Xor, Qword, Rax, R9); - } else { - // R9 = the input: (p & !E) | canonical. - range_index(asm); - asm.mov(Qword, R9, Rax); - asm.alu_load(Alu::And, Qword, R9, range(KEPT)); - asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL)); - rounds(asm, R9, modifier, schedule); - // Authentic when (p ^ pac) & M is the range's `authenticated`. - asm.movq_from_xmm(R10, 0); - asm.alu(Alu::Xor, Qword, R10, Rax); - asm.alu_load(Alu::And, Qword, R10, range(FIELD)); - asm.alu_load(Alu::Cmp, Qword, R10, range(AUTHENTICATED)); - misses.push(asm.jcc(Cond::Ne)); - asm.mov(Qword, Rax, R9); - } - Lookup { - misses, - modifier, - unopened: Some(unopened), - } -} +//! PAC instructions computed in native code, without the memo. +//! +//! Where the host has AES-NI, the engine's PAC cipher is the whitening key +//! and six full AES rounds of the pointer and modifier under the key +//! (`pauth::keyed`, the PAC algorithm Apple silicon leaves IMPLEMENTATION +//! DEFINED), whose state's low half is the PAC. Native code runs those +//! rounds in fewer instructions than a memo miss spends reaching the +//! service, and a memo hit is a load from a table far larger than the +//! caches. So a block or thunk given a [`Cipher`] computes every signing, +//! successful authentication and PACGA itself, from what the engine keeps +//! there for the current keys, PAC version and TCR: each key's schedule +//! (the whitening key and six round keys) and, for each domain, the PAC +//! field of each range ([`Range`]). +//! +//! Native code completes canonical pointers only, whose extension bits all +//! equal bit 55. For them Arm `AddPAC` and `Auth` take one layout, the one +//! bit 55 selects (a signing that selects by bit 63 sees the same bit +//! there), so the range table is indexed by bit 55 alone. With `E` that +//! range's extension mask, `M` it without bit 55 and `pac` the cipher of +//! the input: +//! - a signing of a canonical pointer (`p & E` is the range's canonical +//! extension) has the pointer as its input and gives +//! `p ^ (pac & M) ^ signed`, where `signed` turns the classic insertion, +//! which replaces an upper pointer's all-ones field, into that XOR; +//! - an authentication's input is `p` stripped, `(p & !E) | canonical`; it +//! succeeds exactly when `(p ^ pac) & M` is the range's `authenticated` +//! (the input's field under FEAT_PAuth2's XOR, zero under the classic +//! comparison), and then gives its input; +//! - PACGA gives the cipher's upper half. +//! +//! A key whose tag word is [`super::DISABLED`] (its SCTLR enable clear) +//! gives the pointer unchanged, as Arm does, from the tag word alone: native +//! transitions switch the tag words between two exception levels of one +//! memo generation (`transition::check_pointer`), whose enables differ while +//! their keys, version and layouts do not, so nothing else in the cipher +//! may depend on an enable. One compare tells an open key from a closed or +//! disabled one; the out-of-line path then tells those two apart +//! (`Lookup::unopened`). Everything else, a closed key (tag word +//! zero), a signing of a non-canonical pointer and a failed authentication, +//! goes to the service as a memo miss does, which computes it the engine's +//! way. The computation clobbers RAX, R8 to R11, XMM0, XMM1 and flags. +use super::{GENERIC_KEY, Lookup, TAG_WORDS, operands}; +use crate::Place; +use crate::x86_64::asm::{Alu, Asm, BitTest, Cond, Gpr, Mem, Rm, ShiftOp, Size}; +use alloc::vec::Vec; + +/// The words of a key's schedule: the whitening key and six round keys, +/// each low quadword first. +pub const SCHEDULE: usize = 7; + +/// The bit that selects a canonical pointer's range: Arm keeps it in a +/// signed pointer. +const RANGE_BIT: u8 = 55; + +/// Where one range of one domain puts its PAC field, as native code applies +/// it to canonical pointers ([`Range::new`]). +#[repr(C, align(64))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Range { + /// `E`: the extension bits, from bit 64 - TnSZ to the top PAC bit. + pub extension: u64, + /// `!E`: the bits a stripped pointer keeps. + pub kept: u64, + /// A canonical pointer's extension in this range: zero in the lower + /// range, `E` in the upper one. + pub canonical: u64, + /// `M`: `E` without bit 55, the PAC field. + pub field: u64, + /// What a signing XORs into the field besides the PAC: `M` in the upper + /// range under the classic insertion, which replaces the field (all + /// ones there), else zero. + pub signed: u64, + /// What `(p ^ pac) & M` is for an authentic `p`: `M` in the upper range + /// under FEAT_PAuth2, which XORs the PAC into the field (all ones in + /// the input), else zero. + pub authenticated: u64, + /// Nonzero under FEAT_PAuth2 (`!classic`), enabling native signing of + /// non-canonical pointers. + pub enhanced: u64, + /// Nonzero when signing selects TnSZ by bit 63 rather than bit 55 + /// (neither range ignores the top byte). + pub select_bit63: u64, +} + +impl Range { + /// The range whose extension mask is `extension` (it holds bit 55), the + /// upper one if `upper`, under the classic insertion if `classic`, and + /// selecting TnSZ by bit 63 when signing if `select_bit63`. + pub const fn new(extension: u64, upper: bool, classic: bool, select_bit63: bool) -> Self { + let field = extension & !(1 << RANGE_BIT); + Self { + extension, + kept: !extension, + canonical: if upper { extension } else { 0 }, + field, + signed: if upper && classic { field } else { 0 }, + authenticated: if upper && !classic { field } else { 0 }, + enhanced: if !classic { 1 } else { 0 }, + select_bit63: if select_bit63 { 1 } else { 0 }, + } + } +} + +/// What native code computes PAC results from, at a fixed host address. +#[repr(C, align(64))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Cipher { + /// Each tag word's key schedule ([`SCHEDULE`]). + pub schedules: [[[u64; 2]; SCHEDULE]; TAG_WORDS], + /// The instruction keys' ranges, then the data keys', each by bit 55. + pub ranges: [[Range; 2]; 2], +} + +const SCHEDULES: usize = core::mem::offset_of!(Cipher, schedules); +const RANGES: usize = core::mem::offset_of!(Cipher, ranges); +/// Bytes of a [`Range`], which bit 55 indexes. +const RANGE_BYTES: i32 = core::mem::size_of::() as i32; +const _: () = assert!(RANGE_BYTES == 64 && SCHEDULES.is_multiple_of(16)); +const EXTENSION: usize = core::mem::offset_of!(Range, extension); +const KEPT: usize = core::mem::offset_of!(Range, kept); +const CANONICAL: usize = core::mem::offset_of!(Range, canonical); +const FIELD: usize = core::mem::offset_of!(Range, field); +const SIGNED: usize = core::mem::offset_of!(Range, signed); +const AUTHENTICATED: usize = core::mem::offset_of!(Range, authenticated); +const ENHANCED: usize = core::mem::offset_of!(Range, enhanced); +const SELECT_BIT63: usize = core::mem::offset_of!(Range, select_bit63); + +/// `operation` on XMM0 with ModRM.rm `rm`, a legacy SSE form. +fn sse(asm: &mut Asm, opcode: &[u8], rm: impl Into) { + asm.sse(Some(0x66), opcode, 0, rm); +} + +/// The cipher of `data` and `modifier` under the schedule at R8 + +/// `schedule` into XMM0, whose low half is the PAC: the whitening key and +/// the six AES rounds of `pauth::keyed`. Clobbers XMM1. +fn rounds(asm: &mut Asm, data: Gpr, modifier: Gpr, schedule: i32) { + const PXOR: [u8; 2] = [0x0f, 0xef]; + const AESENC: [u8; 3] = [0x0f, 0x38, 0xdc]; + asm.movq_to_xmm(0, data); + asm.movq_to_xmm(1, modifier); + asm.punpcklqdq(0, Rm::Xmm(1)); + let word = |index: i32| Mem::base(Gpr::R8, schedule + 16 * index); + sse(asm, &PXOR, word(0)); + for round in 1..SCHEDULE as i32 { + sse(asm, &AESENC, word(round)); + } +} + +/// R11 the byte offset of the range bit 55 of RAX selects: 0 or +/// [`RANGE_BYTES`]. +fn range_index(asm: &mut Asm) { + use Gpr::{R11, Rax}; + asm.bit_imm(BitTest::Bt, Size::Qword, Rax, RANGE_BIT); + asm.alu(Alu::Sbb, Size::Qword, R11, R11); + asm.alu_imm8(Alu::And, Size::Dword, R11, RANGE_BYTES as i8); +} + +/// The result of `form` on its operands, computed from the [`Cipher`] at +/// `cipher` under the tag words at `tags` (one anchor): RAX the result, the +/// misses' jumps with RAX the pointer and the modifier in its register, as +/// [`super::lookup`] leaves them, and the jump taken while the key is not +/// open. +pub(super) fn compute(asm: &mut Asm, form: super::Form, tags: Place, cipher: Place) -> Lookup { + use Gpr::{R8, R9, R10, R11, Rax}; + use Size::Qword; + assert_eq!( + tags.anchor, cipher.anchor, + "the tag words and cipher share an anchor" + ); + let modifier = operands(asm, form); + debug_assert!(!matches!(modifier, R9 | R10 | R11)); + asm.place(R8, Place::new(tags.anchor, 0)); + let at = |offset: usize| i32::try_from(cipher.offset + offset).expect("a cipher field offset"); + // Every open key's tag word is above the disabled one's, and a closed + // key's is below it. + let word = i32::try_from(tags.offset + usize::from(form.key) * 8).expect("a tag word offset"); + asm.alu_imm32(Alu::Cmp, Qword, Mem::base(R8, word), super::DISABLED as i32); + let unopened = asm.jcc(Cond::Be); + let schedule = at(SCHEDULES + usize::from(form.key) * SCHEDULE * 16); + if form.key == GENERIC_KEY { + // The generic key is never disabled: a closed one misses. + rounds(asm, Rax, modifier, schedule); + asm.movq_from_xmm(Rax, 0); + asm.shift_imm(ShiftOp::Shr, Qword, Rax, 32); + asm.shift_imm(ShiftOp::Shl, Qword, Rax, 32); + return Lookup { + misses: alloc::vec![unopened], + modifier, + unopened: None, + }; + } + let data = form.key >= super::key_index(crate::block::PointerAuthenticationKey::Da); + let domain = RANGES + usize::from(data) * 2 * RANGE_BYTES as usize; + let range = |field: usize| Mem::indexed(R8, R11, 1, at(domain + field)); + let mut misses = Vec::new(); + if form.kind != super::AUTHENTICATED { + range_index(asm); + asm.mov(Qword, R10, Rax); + asm.alu_load(Alu::And, Qword, R10, range(EXTENSION)); + asm.alu_load(Alu::Cmp, Qword, R10, range(CANONICAL)); + let canonical = asm.jcc(Cond::E); + // Non-canonical signing: FEAT_PAuth2 (`enhanced != 0`) completes + // natively when TnSZ selects by bit 55 or when bit 63 matches bit 55. + asm.alu_imm8(Alu::Cmp, Qword, range(ENHANCED), 0); + misses.push(asm.jcc(Cond::E)); + asm.alu_imm8(Alu::Cmp, Qword, range(SELECT_BIT63), 0); + let select_55 = asm.jcc(Cond::E); + asm.mov(Qword, R10, Rax); + asm.shift_imm(ShiftOp::Shl, Qword, R10, 8); + asm.alu(Alu::Xor, Qword, R10, Rax); + misses.push(asm.jcc(Cond::S)); + asm.bind(select_55); + asm.mov(Qword, R9, Rax); + asm.alu_load(Alu::And, Qword, R9, range(KEPT)); + asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL)); + let noncanonical_ready = asm.jmp8(); + asm.bind(canonical); + asm.mov(Qword, R9, Rax); + asm.bind(noncanonical_ready); + rounds(asm, R9, modifier, schedule); + // p ^ (pac & M) ^ signed. + asm.movq_from_xmm(R9, 0); + asm.alu_load(Alu::And, Qword, R9, range(FIELD)); + asm.alu_load(Alu::Xor, Qword, R9, range(SIGNED)); + asm.alu(Alu::Xor, Qword, Rax, R9); + } else { + // R9 = the input: (p & !E) | canonical. + range_index(asm); + asm.mov(Qword, R9, Rax); + asm.alu_load(Alu::And, Qword, R9, range(KEPT)); + asm.alu_load(Alu::Or, Qword, R9, range(CANONICAL)); + rounds(asm, R9, modifier, schedule); + // Authentic when (p ^ pac) & M is the range's `authenticated`. + asm.movq_from_xmm(R10, 0); + asm.alu(Alu::Xor, Qword, R10, Rax); + asm.alu_load(Alu::And, Qword, R10, range(FIELD)); + asm.alu_load(Alu::Cmp, Qword, R10, range(AUTHENTICATED)); + misses.push(asm.jcc(Cond::Ne)); + asm.mov(Qword, Rax, R9); + } + Lookup { + misses, + modifier, + unopened: Some(unopened), + } +} diff --git a/crates/stela-compiler/src/x86_64/register_read.rs b/crates/stela-compiler/src/x86_64/register_read.rs index 21b745eacb..1a9ff68800 100644 --- a/crates/stela-compiler/src/x86_64/register_read.rs +++ b/crates/stela-compiler/src/x86_64/register_read.rs @@ -1,3620 +1,3718 @@ -//! Native completion of MRS reads of a System register whose value the -//! system-mode engine keeps in a [`Cell`] at a fixed host address. -//! -//! The MRS ends its block with a System exit. A [`thunk`] the engine -//! installs over that exit completes it natively while the cell's -//! `readable` word is nonzero: it writes `value` to Xt (nothing for XZR) and -//! leaves through a direct exit to the next instruction, which the engine -//! may chain like a block's. Otherwise it takes the original exit. -//! -//! The engine sets `readable` only while the read at the current EL is the -//! plain register read of its AARCHMRS accessor, neither UNDEFINED nor -//! trapped nor redirected, with `value` the register's contents, and clears -//! it whenever a System register write, an exception, an exception return -//! or a PE switch may change either. Thunks clobber only RAX and flags. -//! -//! A [`stored_thunk`] reads the live register instead, through the address -//! the cell's `value` holds, so that what an exception or an MSR stores needs -//! no System exit to reach it; a [`frame_thunk`] reads a field of the frame. -//! -//! A [`stored_write_thunk`] completes MSR of a register the same way: it -//! writes through that address, keeping the register's fixed bits, and a -//! [`frame_write_thunk`] writes a field of the frame. It also clobbers RCX -//! and RDX. -//! -//! A [`pan_read_thunk`] completes MRS PAN from the frame, where a -//! [`pan_thunk`] leaves it. -//! -//! A [`key_write_thunk`] completes MSR of half of a PAC key, closing the keys -//! to PAC thunks when it changes one. -//! -//! A [`checked_write_thunk`] completes MSR of a register that takes any value -//! without the bits it refuses, which the engine decides. -//! -//! A [`stack_select_thunk`] completes MSR SPSel: the frame's SP moves to the -//! stack it leaves and takes the one it selects. The selection is a word of -//! the engine's while native code runs, which reads of SP_EL0 consult -//! ([`selected_stored_thunk`], [`selected_write_thunk`]): they are plain only -//! with SP_ELx selected, whatever their cell says. -//! -//! A [`mask_thunk`] completes a write of PSTATE's D, A, I and F masks in the -//! frame, which the engine takes back when native code returns, unless the -//! write changes D, which debug state follows, or clears the mask of an -//! interrupt waiting since native code was entered ([`GuestState::pending`]): -//! one that comes later stops native code as ever. It also clobbers RCX and -//! RDX, as a [`mask_read_thunk`] reads the masks from the frame. -//! -//! A [`code_page_thunk`] completes IC IVAU of the page the cell's `value` -//! names, which a kernel cleans line by line: the first line's invalidation -//! was the whole page's. It also clobbers RCX. -//! -//! A [`count_thunk`] reads a count instead: the system count a clock -//! publishes in a [`CountState`] at the host's TSC, through the reader's -//! [`Count`], less the cell's `value`. It also clobbers RCX and RDX, which -//! are dead at every block exit (the direct exit returns in RAX and RDX, -//! and chaining uses RCX). An [`energy_thunk`] scales the count it reads -//! into an energy accumulator's reading. -//! -//! A [`send_event_thunk`] sets the event register byte the cell's `value` -//! names, and an [`event_wait_thunk`] consumes a set one, spinning briefly -//! for one another PE sets; both clobber RCX and RDX. -//! -//! A [`cycle_counter_thunk`] computes a cycle counter at the count where -//! its cell went stale but the read stays plain, and opens the cell on it; -//! an [`instruction_counter_thunk`] does the same for a retired-instruction -//! counter from the instructions native code retired before it. -//! -//! An [`interrupt_status_thunk`] reads ISR_EL1 from the interrupts waiting -//! at entry while no line changed since; it clobbers RCX and RDX. -use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, Rm, ShiftOp, Size, Unary}; -use super::pointer::Thunk; -use crate::{GuestAddress, GuestState, Place, aarch64::Register, block::ExitKind}; -use alloc::vec::Vec; -use core::sync::atomic::AtomicU64; - -/// What a thunk reads. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Cell { - /// Nonzero while native code may complete the read with `value`. - pub readable: u64, - pub value: u64, -} - -const VALUE: i8 = core::mem::offset_of!(Cell, value) as i8; -/// Bits of an address within the page a [`code_page_thunk`] compares. -const CODE_PAGE_BITS: u8 = 12; -const _: () = assert!(core::mem::offset_of!(Cell, readable) == 0); - -/// A clock's count as every reader computes it: at host count `host` -/// (`((tsc - base) * per_tsc) >> 64`), `min(host + offset, ceiling)`, with -/// wrapping addition. A writer makes `sequence` odd, changes `offset` and -/// `ceiling` and makes it even again; a reader takes both from one even -/// sequence and samples the TSC before that sequence ends, so readers on -/// different cores see one count (a seqlock). -#[repr(C, align(64))] -#[derive(Debug, Default)] -pub struct CountState { - pub sequence: AtomicU64, - pub offset: AtomicU64, - pub ceiling: AtomicU64, -} - -const SEQUENCE: i8 = core::mem::offset_of!(CountState, sequence) as i8; -const STATE_OFFSET: i8 = core::mem::offset_of!(CountState, offset) as i8; -const CEILING: i8 = core::mem::offset_of!(CountState, ceiling) as i8; - -/// One reader of a [`CountState`] at `state`: its TSC scale, and `last`, -/// the count it last read, below which it never reads, so its own count -/// never runs backwards. `seen_*` hold the read in progress. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Count { - pub base: u64, - pub per_tsc: u64, - pub last: u64, - pub state: u64, - pub seen_sequence: u64, - pub seen_offset: u64, - pub seen_ceiling: u64, -} - -const BASE: i8 = core::mem::offset_of!(Count, base) as i8; -const PER_TSC: i8 = core::mem::offset_of!(Count, per_tsc) as i8; -const LAST: i8 = core::mem::offset_of!(Count, last) as i8; -const STATE: i8 = core::mem::offset_of!(Count, state) as i8; -const SEEN_SEQUENCE: i8 = core::mem::offset_of!(Count, seen_sequence) as i8; -const SEEN_OFFSET: i8 = core::mem::offset_of!(Count, seen_offset) as i8; -const SEEN_CEILING: i8 = core::mem::offset_of!(Count, seen_ceiling) as i8; - -/// Xt's storage in [`pinned`](super::pinned) code. -fn register(rt: u8) -> Rm { - Asm::pinned(&mut Vec::new()) - .guest(Register::X(rt)) - .expect("X0..X30") -} - -/// The thunk completing `MRS Xt, ` at `pc` from the cell at -/// `cell`, else exiting at `pc` for the engine. -pub fn thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - if rt != 31 { - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - } - finish(code, miss, pc) -} - -/// The thunk completing `MRS Xt, ` at `pc` from the storage the -/// `value` of the cell at `cell` points at, else exiting at `pc`. -pub fn stored_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rax, 0)); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - finish(code, miss, pc) -} - -/// [`stored_thunk`] of a read that is plain only while the word at `select` -/// is nonzero. -pub fn selected_stored_thunk(pc: GuestAddress, rt: u8, cell: Place, select: Place) -> Thunk { - let (mut code, miss) = open(cell); - let unselected = selected(&mut code, select); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rax, 0)); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - finish_unless(code, [miss, unselected], pc) -} - -/// Branch away while the word at `select` is zero. -fn selected(code: &mut Vec, select: Place) -> Patch { - let mut asm = Asm::new(code); - asm.place(Gpr::Rcx, select); - asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rcx, 0), 0); - asm.jcc(Cond::E) -} - -/// The thunk completing `MRS Xt, ` at `pc` from the 32-bit frame -/// field at `offset` while the cell at `cell` is open, else exiting at `pc`. -pub fn frame_thunk(pc: GuestAddress, rt: u8, cell: Place, offset: usize) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - let field = Mem::base_disp32(Gpr::Rdi, offset as i32); - asm.mov_load(Size::Dword, Gpr::Rax, field); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - finish(code, miss, pc) -} - -/// The thunk completing `MRS Xt, PAN` at `pc` while the cell at `cell` is -/// open, else exiting at `pc`. -pub fn pan_read_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { - /// PAN's bit of the register. - const PAN_SHIFT: u8 = 22; - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - let field = frame_field(core::mem::offset_of!(GuestState, pan)); - asm.mov_load(Size::Qword, Gpr::Rax, field); - asm.shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rax, PAN_SHIFT); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - finish(code, miss, pc) -} - -/// The bits of a register a write takes and those it always holds, as -/// [`Self::apply`] gives it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Written { - pub keep: u64, - pub set: u64, -} - -impl Written { - /// Leave `Xt`'s value as the register stores it in RAX. - pub(crate) fn apply(self, asm: &mut Asm<'_>, rt: u8) { - if rt == 31 { - asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); - } else { - asm.mov_load(Size::Qword, Gpr::Rax, register(rt)); - } - if self.keep != u64::MAX { - asm.mov_imm64(Gpr::Rdx, self.keep); - asm.alu(Alu::And, Size::Qword, Gpr::Rax, Gpr::Rdx); - } - if self.set != 0 { - asm.mov_imm64(Gpr::Rdx, self.set); - asm.alu(Alu::Or, Size::Qword, Gpr::Rax, Gpr::Rdx); - } - } -} - -/// The thunk completing `MSR , Xt` at `pc` through the storage the -/// `value` of the cell at `cell` points at, else exiting at `pc`. -pub fn stored_write_thunk(pc: GuestAddress, rt: u8, cell: Place, written: Written) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - written.apply(&mut asm, rt); - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - finish(code, miss, pc) -} - -/// The thunk completing `MSR , Xt` at `pc` when the value, as the -/// register takes it, equals what the storage the `value` of the cell at -/// `cell` points at holds already: such a write changes nothing. Any other -/// value, or a closed cell, exits at `pc`. -pub fn unchanged_write_thunk(pc: GuestAddress, rt: u8, cell: Place, written: Written) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - written.apply(&mut asm, rt); - asm.alu_load(Alu::Cmp, Size::Qword, Gpr::Rax, Mem::base(Gpr::Rcx, 0)); - let changed = asm.jcc(Cond::Ne); - finish_unless(code, [miss, changed], pc) -} - -/// [`stored_write_thunk`] of a register that keeps what it is written, unless -/// the value has one of the bits `refused`. -pub fn checked_write_thunk(pc: GuestAddress, rt: u8, cell: Place, refused: u64) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - let all = Written { - keep: u64::MAX, - set: 0, - }; - all.apply(&mut asm, rt); - if rt == 31 || refused == 0 { - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - return finish(code, miss, pc); - } - asm.mov_imm64(Gpr::Rdx, refused); - asm.test(Size::Qword, Gpr::Rax, Gpr::Rdx); - let unplain = asm.jcc(Cond::Ne); - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - finish_unless(code, [miss, unplain], pc) -} - -/// One thread switch a [`thread_switch_thunk`] completed: the thread -/// pointer it replaced and the one it wrote, the frame pointer (X29) and -/// link register (X30) then, and the MSR's PC. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Switch { - pub previous: u64, - pub next: u64, - pub frame: u64, - pub link: u64, - pub pc: u64, -} - -/// The thread switches native code completed since the engine last took -/// them, in order: `len` of `entries`. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct SwitchLog { - pub len: u64, - pub entries: [Switch; SWITCHES], -} - -/// The switches a [`SwitchLog`] holds; a thunk finding it full exits. -pub const SWITCHES: usize = 8; - -/// Where a [`thread_switch_thunk`] finds the register's read cells and the -/// engine's [`SwitchLog`]: `reads` is the read cell of the first of `banks` -/// banks, each `stride` bytes after the one before. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ThreadSwitch { - pub reads: Place, - pub stride: usize, - pub banks: usize, - pub log: Place, -} - -/// Leave Xt's value in RAX (0 for XZR). -fn load_x(asm: &mut Asm<'_>, rt: u8) { - if rt == 31 { - asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); - } else { - asm.mov_load(Size::Qword, Gpr::Rax, register(rt)); - } -} - -/// The thunk completing `MSR , Xt` at `pc` through the -/// storage the `value` of the cell at `cell` points at, for a register that -/// keeps what it is written and has read cells of its own in every bank -/// (TPIDR_EL1): every open read cell takes the value, as the engine's -/// write updates them. A value that replaces another is logged in the -/// [`SwitchLog`] for the engine's diagnostics, which see the switch as an -/// engine-path write would show it; with the log full, or the cell closed, -/// it exits at `pc`. It also clobbers RCX and RDX. -pub fn thread_switch_thunk(pc: GuestAddress, rt: u8, cell: Place, places: &ThreadSwitch) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); - load_x(&mut asm, rt); - // The same value changes nothing: no cell, no thread. - asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0)); - let same = asm.jcc(Cond::E); - asm.place(Rdx, places.log); - let len = core::mem::offset_of!(SwitchLog, len) as i32; - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, len), SWITCHES as i8); - let full = asm.jcc(Cond::Ae); - asm.mov_load(Qword, Rax, Mem::base(Rdx, len)); - asm.alu_imm8(Alu::Add, Qword, Mem::base(Rdx, len), 1); - asm.imul_imm32(Qword, Rax, Rax, size_of::() as i32); - asm.alu(Alu::Add, Qword, Rdx, Rax); - let entry = |field: usize| { - Mem::base( - Rdx, - (core::mem::offset_of!(SwitchLog, entries) + field) as i32, - ) - }; - asm.mov_load(Qword, Rax, Mem::base(Rcx, 0)); - asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, previous)), Rax); - load_x(&mut asm, 29); - asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, frame)), Rax); - load_x(&mut asm, 30); - asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, link)), Rax); - asm.guest_imm64(Rax, pc); - asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, pc)), Rax); - load_x(&mut asm, rt); - asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, next)), Rax); - asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); - // Every open read cell reads the new value; closed ones keep none. - asm.place(Rdx, places.reads); - for bank in 0..places.banks { - let at = (bank * places.stride) as i32; - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, at), 0); - let closed = asm.jcc8(Cond::E); - asm.mov_store(Qword, Mem::base(Rdx, at + VALUE as i32), Rax); - asm.bind(closed); - } - asm.bind(same); - finish_unless(code, [miss, full], pc) -} - -/// The thunk completing `IC IVAU, Xt` at `pc` of an address in the page the -/// `value` of the cell at `cell` names, else exiting at `pc`. -pub fn code_page_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.alu_load(Alu::Xor, Size::Qword, Gpr::Rcx, register(rt)); - asm.shift_imm(ShiftOp::Shr, Size::Qword, Gpr::Rcx, CODE_PAGE_BITS); - let other = asm.jcc(Cond::Ne); - finish_unless(code, [miss, other], pc) -} - -/// [`stored_write_thunk`] of a write that is plain only while the word at -/// `select` is nonzero. -pub fn selected_write_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - select: Place, - written: Written, -) -> Thunk { - let (mut code, miss) = open(cell); - let unselected = selected(&mut code, select); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - written.apply(&mut asm, rt); - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - finish_unless(code, [miss, unselected], pc) -} - -/// The thunk completing `MSR SPSel, #select` at `pc` while the cell at -/// `cell` is open, its `value` the address of the level's SP_ELx. The word -/// at `current` holds the selection and `sp0` is the address of SP_EL0. -pub fn stack_select_thunk( - pc: GuestAddress, - select: bool, - cell: Place, - current: Place, - sp0: Place, -) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let (mut code, miss) = open(cell); - let sp = super::pinned::host(Register::Sp).expect("SP is pinned"); - let mut asm = Asm::new(&mut code); - asm.place(Rcx, current); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rcx, 0), i8::from(select)); - let unchanged = asm.jcc(Cond::E); - asm.mov_imm32(Rdx, u32::from(select)); - asm.mov_store(Qword, Mem::base(Rcx, 0), Rdx); - asm.mov_load(Qword, Rax, Mem::base_disp8(Rax, VALUE)); - asm.place(Rcx, sp0); - let (from, to) = if select { (Rcx, Rax) } else { (Rax, Rcx) }; - asm.mov_store(Qword, Mem::base(from, 0), sp); - asm.mov_load(Qword, sp, Mem::base(to, 0)); - asm.bind(unchanged); - finish(code, miss, pc) -} - -/// [`stored_write_thunk`] of half of a PAC key. A value that changes it clears -/// the `words` tag words at `tags`, as a thread switch writes several halves -/// and only the last leaves a key worth opening: the next PAC instruction -/// exits and the engine reopens them under the whole keys. -pub fn key_write_thunk(pc: GuestAddress, rt: u8, cell: Place, tags: Place, words: usize) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - let all = Written { - keep: u64::MAX, - set: 0, - }; - all.apply(&mut asm, rt); - asm.alu_load(Alu::Cmp, Size::Qword, Gpr::Rax, Mem::base(Gpr::Rcx, 0)); - let unchanged = asm.jcc(Cond::E); - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - asm.place(Gpr::Rcx, tags); - asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); - for word in 0..words { - let at = Mem::base_disp8(Gpr::Rcx, (word * size_of::()) as i8); - asm.mov_store(Size::Qword, at, Gpr::Rax); - } - asm.bind(unchanged); - finish(code, miss, pc) -} - -/// The thunk completing `MSR , Xt` at `pc` in the 32-bit frame -/// field at `offset` while the cell at `cell` is open, else exiting at `pc`. -pub fn frame_write_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - offset: usize, - written: Written, -) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - written.apply(&mut asm, rt); - asm.mov_store(Size::Dword, frame_field(offset), Gpr::Rax); - finish(code, miss, pc) -} - -/// A write of PSTATE's masks. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum MaskWrite { - /// MSR DAIFSet, #imm. - Set(u8), - /// MSR DAIFClr, #imm. - Clear(u8), - /// MSR DAIF, Xt. - Register(u8), -} - -impl MaskWrite { - /// The write `word` makes, if it is one. - pub fn of(word: u32) -> Option { - let immediate = (word >> 8 & 0xf) as u8; - match word & 0xffff_f0ff { - 0xd503_40df => Some(Self::Set(immediate)), - 0xd503_40ff => Some(Self::Clear(immediate)), - _ if word & !0x1f == 0xd51b_4220 => Some(Self::Register((word & 0x1f) as u8)), - _ => None, - } - } -} - -/// PSTATE.D in [`GuestState::daif`]. -const MASK_D: i8 = 8; -/// DAIF's bit 6, of F, the lowest mask. -const MASK_SHIFT: u8 = 6; - -fn frame_field(offset: usize) -> Mem { - Mem::base_disp32(Gpr::Rdi, offset as i32) -} - -/// The thunk completing `MSR PAN, #pan` at `pc` while the cell at `cell` is -/// open, on a host that keeps PSTATE.PAN in RFLAGS.AC, else exiting at `pc`. -pub fn pan_thunk(pc: GuestAddress, pan: bool, cell: Place) -> Thunk { - const CLAC: [u8; 3] = [0x0f, 0x01, 0xca]; - const STAC: [u8; 3] = [0x0f, 0x01, 0xcb]; - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_imm32(Gpr::Rax, u32::from(pan)); - let field = frame_field(core::mem::offset_of!(GuestState, pan)); - asm.mov_store(Size::Qword, field, Gpr::Rax); - asm.fixed(if pan { &CLAC } else { &STAC }); - finish(code, miss, pc) -} - -/// The thunk completing a DSB at `pc` while the cell at `cell` is open, that -/// is while the engine has no maintenance for it to complete, else exiting -/// at `pc`. -pub fn barrier_thunk(pc: GuestAddress, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - Asm::new(&mut code).mfence(); - finish(code, miss, pc) -} - -/// The thunk completing CLREX at `pc` while the cell at `cell` is open and -/// the word its `value` points at is zero, that is while the PE's local -/// monitor lives in the frame alone: it clears the frame's monitor; else it -/// exits at `pc` for the engine to clear the rest. It also clobbers RCX. -pub fn clear_exclusive_thunk(pc: GuestAddress, cell: Place) -> Thunk { - let (mut code, closed) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rcx, 0), 0); - let held = asm.jcc(Cond::Ne); - let bytes = frame_field(core::mem::offset_of!(GuestState, exclusive_bytes)); - asm.mov_rm_imm32(Size::Dword, bytes, 0); - finish_unless(code, [closed, held], pc) -} - -/// The thunk completing SEVL at `pc` while the cell at `cell` is open: it -/// sets the event register, the byte the cell's `value` points at, else -/// exits at `pc`. It also clobbers RCX and RDX. -pub fn send_event_thunk(pc: GuestAddress, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); - asm.mov_imm32(Gpr::Rdx, 1); - asm.mov_store(Size::Byte, Mem::base(Gpr::Rcx, 0), Gpr::Rdx); - finish(code, miss, pc) -} - -/// How long an [`event_wait_thunk`] spins for the event register before it -/// exits: 48 counts of the 24 MHz system count, 2 us. Another PE that sets -/// the register within it saves the waiting PE an exit and a wait in the -/// engine; a spin that misses costs this much host time. -pub const WFE_SPIN_COUNTS: u8 = 48; - -/// The most turns one spin takes whatever the count does: a held count -/// (`CountState::ceiling`) stops it, and nothing may hold a PE. A turn -/// takes far more than 2 us / 1024 on every host, so the count ends a spin -/// first. -const WFE_SPIN_TURNS: i32 = 1024; - -/// What [`event_wait_thunk`]s count of their spins, and the spin in -/// progress, which the engine takes when native code returns. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct EventSpin { - /// Spins that found the event register set: the WFE completed. - pub completed: u64, - /// Spins that ended otherwise, and exited. - pub missed: u64, - /// WFEs that could spin but for an exclusive monitor, and exited. - pub held: u64, - /// The system counts spent in spins. - pub counts: u64, - /// The count the spin in progress began at, and its turns left. - pub start: u64, - pub turns: u64, - /// WFEs that found the register clear but an event stream edge since - /// the engine's last sample ([`EventStream`]), and completed. - pub streamed: u64, -} - -/// The event stream an [`event_wait_thunk`] samples: the first system -/// count after the engine's last sample at which an edge sets the event -/// register (`u64::MAX`: none the thunk may take), the edges' period -/// where they come every `period` counts (0: the thunk takes one edge and -/// leaves the next to the engine), and the count the thunk last sampled -/// at, which the engine takes as its own sample when native code returns. -#[repr(C)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EventStream { - pub next: u64, - pub period: u64, - pub sampled: u64, -} - -impl Default for EventStream { - fn default() -> Self { - Self { - next: u64::MAX, - period: 1, - sampled: 0, - } - } -} - -const STREAM_NEXT: i8 = core::mem::offset_of!(EventStream, next) as i8; -const STREAM_PERIOD: i8 = core::mem::offset_of!(EventStream, period) as i8; -const STREAM_SAMPLED: i8 = core::mem::offset_of!(EventStream, sampled) as i8; - -const SPIN_COMPLETED: i8 = core::mem::offset_of!(EventSpin, completed) as i8; -const SPIN_MISSED: i8 = core::mem::offset_of!(EventSpin, missed) as i8; -const SPIN_HELD: i8 = core::mem::offset_of!(EventSpin, held) as i8; -const SPIN_COUNTS: i8 = core::mem::offset_of!(EventSpin, counts) as i8; -const SPIN_START: i8 = core::mem::offset_of!(EventSpin, start) as i8; -const SPIN_TURNS: i8 = core::mem::offset_of!(EventSpin, turns) as i8; -const SPIN_STREAMED: i8 = core::mem::offset_of!(EventSpin, streamed) as i8; -const INTERRUPT_EPOCH: i8 = - core::mem::offset_of!(super::chain::ChainControl, interrupt_epoch) as i8; -const QUIET: i8 = core::mem::offset_of!(super::chain::ChainControl, quiet) as i8; -const OBSERVED_INTERRUPT_EPOCH: i8 = - core::mem::offset_of!(super::chain::ChainControl, observed_interrupt_epoch) as i8; - -/// Where an [`event_wait_thunk`] finds the event register and what ends its -/// spin: `events` a cell whose `value` is the register's byte; `waits` a -/// cell open where a WFE that finds the register clear waits rather than -/// traps and another PE runs meanwhile to set it; `monitor` the word nonzero -/// while the engine holds an exclusive monitor; the control -/// ([`super::chain::ChainControl`]), whose interrupt epoch moves when -/// anything is posted for the PE; the count before which time alone changes -/// no interrupt line ([`crate::x86_64::transition::Places::lines_until`]), -/// the count reader, the spin's counts and the event stream -/// ([`EventStream`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EventWaitPlaces { - pub events: Place, - pub waits: Place, - pub monitor: Place, - pub control: Place, - pub lines_until: Place, - pub count: Place, - pub spin: Place, - pub stream: Place, -} - -/// The thunk completing WFE at `pc` while the `events` cell is open and the -/// event register is set: it clears the register in one exchange, as -/// another PE may set it, and completes. With the register clear, an event -/// stream edge since the engine's last sample sets it as the engine's own -/// sample would (`stream`), and the WFE takes it and completes, recording -/// the count it sampled at and the next edge, before any trap check, as -/// the engine does. With the register clear, where the -/// WFE would wait (`waits` open), it spins for up to [`WFE_SPIN_COUNTS`] -/// for the register and completes as soon as it finds it set. It spins only -/// while nothing else would wake the WFE, all of which the engine's wait -/// sees: no interrupt was waiting at entry ([`GuestState::pending`]), -/// nothing was posted for the PE since the engine last looked (a device -/// line, mail with another PE's SEV, a host call or stop: the interrupt -/// epoch), and time changes no line (the count below `lines_until`), each -/// looked at again every turn. Nor does it spin with an exclusive monitor -/// held, in the frame or the engine, as another PE's store that clears it -/// sends the event without setting this register. Else, and once the spin -/// ends without the register, it exits at `pc` for the engine to wait. An -/// event stream edge within a spin is the engine's to see as it waits: the -/// spin delays it no more than a host would. It also clobbers RCX and RDX. -pub fn event_wait_thunk(pc: GuestAddress, places: EventWaitPlaces) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Byte, Dword, Qword}; - let spin = |offset| Mem::base_disp8(Rcx, offset); - let (mut code, closed) = open(places.events); - let mut asm = Asm::new(&mut code); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.xchg(Byte, Mem::base(Rcx, 0), Rdx); - asm.test(Byte, Rdx, Rdx); - let set = asm.jcc(Cond::Ne); - // An event stream edge since the last sample: next += (k + 1) * period - // for k = (count - next) / period. Without a stream no count is read. - asm.place(Rcx, places.stream); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base_disp8(Rcx, STREAM_NEXT), -1); - let unpublished = asm.jcc(Cond::E); - read_count(&mut asm, places.count); - asm.place(Rcx, places.stream); - asm.mov(Qword, Rax, Rdx); - asm.alu_load(Alu::Sub, Qword, Rax, Mem::base_disp8(Rcx, STREAM_NEXT)); - let no_edge = asm.jcc(Cond::B); - asm.mov_store(Qword, Mem::base_disp8(Rcx, STREAM_SAMPLED), Rdx); - // Without a period, the edge after it is the engine's to find. - asm.alu_imm8(Alu::Cmp, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD), 0); - let periodic = asm.jcc(Cond::Ne); - asm.mov_rm_imm32(Qword, Mem::base_disp8(Rcx, STREAM_NEXT), -1); - let taken = asm.jmp(); - asm.bind(periodic); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.unary(Unary::Div, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD)); - asm.alu_imm8(Alu::Add, Qword, Rax, 1); - asm.unary(Unary::Mul, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD)); - asm.alu(Alu::Add, Qword, Mem::base_disp8(Rcx, STREAM_NEXT), Rax); - asm.bind(taken); - asm.place(Rcx, places.spin); - asm.alu_imm8(Alu::Add, Qword, spin(SPIN_STREAMED), 1); - let streamed = asm.jmp(); - asm.bind(no_edge); - asm.bind(unpublished); - // Whether the WFE may spin. - asm.place(Rax, places.waits); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let traps = asm.jcc(Cond::E); - let pending = frame_field(core::mem::offset_of!(GuestState, pending)); - asm.alu_imm8(Alu::Cmp, Dword, pending, 0); - let interrupt = asm.jcc(Cond::Ne); - let posted = |asm: &mut Asm<'_>| { - asm.place(Rcx, places.control); - asm.mov_load(Qword, Rdx, Mem::base_disp8(Rcx, INTERRUPT_EPOCH)); - asm.alu_load( - Alu::Cmp, - Qword, - Rdx, - Mem::base_disp8(Rcx, OBSERVED_INTERRUPT_EPOCH), - ); - asm.jcc(Cond::Ne) - }; - let notified = posted(&mut asm); - let bytes = frame_field(core::mem::offset_of!(GuestState, exclusive_bytes)); - asm.alu_imm8(Alu::Cmp, Dword, bytes, 0); - let framed = asm.jcc(Cond::Ne); - asm.place(Rax, places.monitor); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let monitored = asm.jcc(Cond::Ne); - read_count(&mut asm, places.count); - asm.place(Rax, places.lines_until); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); - let due = asm.jcc(Cond::Ae); - asm.place(Rcx, places.spin); - asm.mov_store(Qword, spin(SPIN_START), Rdx); - asm.mov_rm_imm32(Qword, spin(SPIN_TURNS), WFE_SPIN_TURNS); - let top = asm.len(); - asm.pause(); - // Read the register shared and exchange it only once set. - asm.place(Rax, places.events); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); - asm.movzx(Dword, Rdx, Byte, Mem::base(Rcx, 0)); - asm.test(Dword, Rdx, Rdx); - let clear = asm.jcc(Cond::E); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.xchg(Byte, Mem::base(Rcx, 0), Rdx); - asm.test(Byte, Rdx, Rdx); - let taken = asm.jcc(Cond::E); - // The counts spent into the spin's total, and the outcome's count. - let spent = |asm: &mut Asm<'_>, outcome: i8| { - read_count(asm, places.count); - asm.place(Rcx, places.spin); - asm.alu_load(Alu::Sub, Qword, Rdx, spin(SPIN_START)); - asm.alu(Alu::Add, Qword, spin(SPIN_COUNTS), Rdx); - asm.alu_imm8(Alu::Add, Qword, spin(outcome), 1); - }; - spent(&mut asm, SPIN_COMPLETED); - let found = asm.jmp(); - asm.bind(clear); - asm.bind(taken); - let woken = posted(&mut asm); - asm.place(Rcx, places.spin); - asm.alu_imm8(Alu::Sub, Qword, spin(SPIN_TURNS), 1); - let turns = asm.jcc(Cond::E); - read_count(&mut asm, places.count); - asm.place(Rax, places.lines_until); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); - let lines = asm.jcc(Cond::Ae); - asm.place(Rcx, places.spin); - asm.alu_load(Alu::Sub, Qword, Rdx, spin(SPIN_START)); - asm.alu_imm8(Alu::Cmp, Qword, Rdx, WFE_SPIN_COUNTS as i8); - let again = asm.jcc(Cond::B); - asm.bind_back(again, top); - for end in [woken, turns, lines] { - asm.bind(end); - } - spent(&mut asm, SPIN_MISSED); - let missed = asm.jmp(); - asm.bind(framed); - asm.bind(monitored); - asm.place(Rcx, places.spin); - asm.alu_imm8(Alu::Add, Qword, spin(SPIN_HELD), 1); - let held = asm.jmp(); - asm.bind(set); - asm.bind(found); - asm.bind(streamed); - finish_unless( - code, - [closed, traps, interrupt, notified, due, missed, held], - pc, - ) -} - -/// A PE's view of the board's frozen fast-IPI table (the engine's -/// `fast_ipi::Table`) for [`fast_ipi_request_thunk`] and -/// [`fast_ipi_status_thunk`]: the table's first entry, its clusters and -/// CPUs per cluster, this PE's own cluster, number and IPI_SR address, the -/// PEs a request found halted (bit `pe`), which the engine wakes when -/// native code returns, and the entry of the request in progress. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct FastIpi { - pub base: u64, - pub clusters: u64, - pub cpus: u64, - pub cluster: u64, - pub pe: u64, - pub status: u64, - pub wakes: u64, - pub target: u64, -} - -/// The bytes of one entry of the table [`FastIpi::base`] names, and the -/// offsets of its words: the target's IPI_SR (`u64`), deferred-IPI flag -/// (`u8`), line-change counter (`u64`), chaining control -/// ([`super::chain::ChainControl`]), halted flag (`u8`) and PE number, each -/// but the last an address. -pub const FAST_IPI_TARGET_BYTES: usize = 48; -pub const FAST_IPI_TARGET_STATUS: usize = 0; -pub const FAST_IPI_TARGET_ARMED: usize = 8; -pub const FAST_IPI_TARGET_LINES: usize = 16; -pub const FAST_IPI_TARGET_INTERRUPT: usize = 24; -pub const FAST_IPI_TARGET_SLEEPING: usize = 32; -pub const FAST_IPI_TARGET_PE: usize = 40; - -const IPI_BASE: i8 = core::mem::offset_of!(FastIpi, base) as i8; -const IPI_CLUSTERS: i8 = core::mem::offset_of!(FastIpi, clusters) as i8; -const IPI_CPUS: i8 = core::mem::offset_of!(FastIpi, cpus) as i8; -const IPI_CLUSTER: i8 = core::mem::offset_of!(FastIpi, cluster) as i8; -const IPI_PE: i8 = core::mem::offset_of!(FastIpi, pe) as i8; -const IPI_STATUS: i8 = core::mem::offset_of!(FastIpi, status) as i8; -const IPI_WAKES: i8 = core::mem::offset_of!(FastIpi, wakes) as i8; -const IPI_TARGET: i8 = core::mem::offset_of!(FastIpi, target) as i8; - -/// IPI_RR's CPU [7:0], CLUSTER [23:16] and TYPE [29:28]. -const RR_CPU: i32 = 0xff; -const RR_CLUSTER: u64 = 0xff << 16; -const RR_TYPE: u64 = 0b11 << 28; - -/// Where fast-IPI thunks find their words: the per-state cell open where -/// the MSR completes plainly, the PE's [`FastIpi`], the control -/// ([`super::chain::ChainControl`]) and the native ISR_EL1 read's cell -/// ([`interrupt_status_thunk`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct FastIpiPlaces { - pub cell: Place, - pub ipi: Place, - pub control: Place, - pub interrupt_status: Place, -} - -/// Post an interruption to the control at RCX as `chain::interrupt` does: -/// add 1 to its epoch unless it is `u64::MAX`, which stays, in a LOCK -/// CMPXCHG loop, then zero its quiet word. Clobbers RAX and RDX. -fn bump_epoch(asm: &mut Asm<'_>) { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let epoch = Mem::base_disp8(Rcx, INTERRUPT_EPOCH); - asm.mov_load(Qword, Rax, epoch); - let top = asm.len(); - asm.alu_imm8(Alu::Cmp, Qword, Rax, -1); - let saturated = asm.jcc(Cond::E); - asm.lea(Qword, Rdx, Mem::base_disp8(Rax, 1)); - asm.lock(); - asm.cmpxchg(Qword, epoch, Rdx); - let lost = asm.jcc(Cond::Ne); - asm.bind_back(lost, top); - asm.bind(saturated); - asm.mov_rm_imm32(Qword, Mem::base(Rcx, QUIET.into()), 0); -} - -/// The thunk completing an immediate fast-IPI request, MSR IPI_RR_LOCAL -/// (or IPI_RR_GLOBAL with `global`) at `pc` with Xt, while the cell is -/// open, step for step as the engine's reference send (`fast_ipi::Table:: -/// send`) does, else exiting at `pc` having changed nothing: the value -/// holds only CPU, TYPE 0 and, global, CLUSTER; the target is present and -/// not this PE; its deferred IPI is not armed. It ORs PENDING into the -/// target's IPI_SR (LOCK CMPXCHG), and where that was clear adds 1 to its -/// line-change counter (LOCK ADD), to its interruption epoch unless -/// saturated, and, finding it halted, sets its bit in [`FastIpi::wakes`] -/// and moves this PE's own interruption epoch, so its run ends at the next -/// chained transfer and the engine wakes the target (`Devices:: -/// wake_signalled`) without running the MSR again. It clobbers RAX, RCX -/// and RDX. -pub fn fast_ipi_request_thunk( - pc: GuestAddress, - rt: u8, - global: bool, - places: FastIpiPlaces, -) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Byte, Dword, Qword}; - let ipi = |offset| Mem::base_disp8(Rax, offset); - let target = |offset: usize| Mem::base_disp8(Rdx, offset as i8); - let (mut code, closed) = open(places.cell); - let mut asm = Asm::new(&mut code); - if rt == 31 { - asm.alu(Alu::Xor, Dword, Rcx, Rcx); - } else { - asm.mov_load(Qword, Rcx, register(rt)); - } - let fields = RR_CPU as u64 | if global { RR_CLUSTER } else { 0 }; - asm.mov_imm64(Rdx, !fields | RR_TYPE); - asm.test(Qword, Rcx, Rdx); - let malformed = asm.jcc(Cond::Ne); - asm.place(Rax, places.ipi); - if global { - asm.mov(Qword, Rdx, Rcx); - asm.shift_imm(ShiftOp::Shr, Qword, Rdx, 16); - } else { - asm.mov_load(Qword, Rdx, ipi(IPI_CLUSTER)); - } - asm.alu_load(Alu::Cmp, Qword, Rdx, ipi(IPI_CLUSTERS)); - let no_cluster = asm.jcc(Cond::Ae); - asm.alu_imm32(Alu::And, Dword, Rcx, RR_CPU); - asm.alu_load(Alu::Cmp, Qword, Rcx, ipi(IPI_CPUS)); - let no_cpu = asm.jcc(Cond::Ae); - asm.imul(Qword, Rdx, ipi(IPI_CPUS)); - asm.alu(Alu::Add, Qword, Rdx, Rcx); - asm.imul_imm32(Qword, Rdx, Rdx, FAST_IPI_TARGET_BYTES as i32); - asm.alu_load(Alu::Add, Qword, Rdx, ipi(IPI_BASE)); - asm.alu_imm8(Alu::Cmp, Qword, target(FAST_IPI_TARGET_STATUS), 0); - let absent = asm.jcc(Cond::E); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_PE)); - asm.alu_load(Alu::Cmp, Qword, Rcx, ipi(IPI_PE)); - let own = asm.jcc(Cond::E); - asm.alu_imm8(Alu::Cmp, Qword, Rcx, 64); - let unnamed = asm.jcc(Cond::Ae); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_ARMED)); - asm.movzx(Dword, Rcx, Byte, Mem::base(Rcx, 0)); - asm.test(Dword, Rcx, Rcx); - let armed = asm.jcc(Cond::Ne); - // Committed from here on. - asm.mov_store(Qword, ipi(IPI_TARGET), Rdx); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_STATUS)); - asm.mov_load(Qword, Rax, Mem::base(Rcx, 0)); - let top = asm.len(); - asm.mov(Qword, Rdx, Rax); - asm.alu_imm8(Alu::Or, Qword, Rdx, 1); - asm.lock(); - asm.cmpxchg(Qword, Mem::base(Rcx, 0), Rdx); - let lost = asm.jcc(Cond::Ne); - asm.bind_back(lost, top); - asm.test(Qword, Rax, Rax); - let pending = asm.jcc(Cond::Ne); - let reload = |asm: &mut Asm<'_>| { - asm.place(Rax, places.ipi); - asm.mov_load(Qword, Rdx, ipi(IPI_TARGET)); - }; - reload(&mut asm); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_LINES)); - asm.lock(); - asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_INTERRUPT)); - bump_epoch(&mut asm); - reload(&mut asm); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_SLEEPING)); - asm.movzx(Dword, Rcx, Byte, Mem::base(Rcx, 0)); - asm.test(Dword, Rcx, Rcx); - let running = asm.jcc(Cond::E); - asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_PE)); - asm.mov_imm32(Rdx, 1); - asm.shift_cl(ShiftOp::Shl, Qword, Rdx); - asm.alu(Alu::Or, Qword, ipi(IPI_WAKES), Rdx); - asm.place(Rcx, places.control); - bump_epoch(&mut asm); - asm.bind(pending); - asm.bind(running); - finish_unless( - code, - [ - closed, malformed, no_cluster, no_cpu, absent, own, unnamed, armed, - ], - pc, - ) -} - -/// The thunk completing MSR IPI_SR at `pc` with Xt while the cell is open: -/// 1 clears PENDING in this PE's IPI_SR in one exchange, as other PEs set -/// it, and closes the native ISR_EL1 read, whose waiting FIQ was taken at -/// entry; 0 changes nothing; any other value, or a PE whose word the -/// engine has not named, exits. It clobbers RAX, RCX and RDX. -pub fn fast_ipi_status_thunk(pc: GuestAddress, rt: u8, places: FastIpiPlaces) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Dword, Qword}; - let (mut code, closed) = open(places.cell); - if rt == 31 { - return finish(code, closed, pc); - } - let mut asm = Asm::new(&mut code); - asm.mov_load(Qword, Rcx, register(rt)); - asm.test(Qword, Rcx, Rcx); - let nothing = asm.jcc(Cond::E); - asm.alu_imm8(Alu::Cmp, Qword, Rcx, 1); - let other = asm.jcc(Cond::Ne); - asm.place(Rax, places.ipi); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, IPI_STATUS)); - asm.test(Qword, Rcx, Rcx); - let unknown = asm.jcc(Cond::E); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.xchg(Qword, Mem::base(Rcx, 0), Rdx); - asm.place(Rax, places.interrupt_status); - asm.mov_rm_imm32(Qword, Mem::base(Rax, 0), 0); - asm.bind(nothing); - finish_unless(code, [closed, other, unknown], pc) -} - -/// The thunk completing `write` at `pc` in the frame while the cell at -/// `cell` is open, else exiting at `pc`. -pub fn mask_thunk(write: MaskWrite, pc: GuestAddress, cell: Place) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Dword, Qword}; - let (mut code, closed) = open(cell); - let masks = frame_field(core::mem::offset_of!(GuestState, daif)); - let pending = frame_field(core::mem::offset_of!(GuestState, pending)); - let mut asm = Asm::new(&mut code); - asm.mov_load(Dword, Rcx, masks); - match write { - MaskWrite::Set(immediate) => { - asm.mov(Dword, Rax, Rcx); - asm.alu_imm8(Alu::Or, Dword, Rax, immediate as i8); - } - MaskWrite::Clear(immediate) => { - asm.mov(Dword, Rax, Rcx); - asm.alu_imm8(Alu::And, Dword, Rax, !immediate as i8); - } - MaskWrite::Register(31) => asm.alu(Alu::Xor, Dword, Rax, Rax), - MaskWrite::Register(rt) => { - asm.mov_load(Qword, Rax, register(rt)); - asm.shift_imm(ShiftOp::Shr, Qword, Rax, MASK_SHIFT); - asm.alu_imm8(Alu::And, Dword, Rax, 0xf); - } - } - // RDX the masks that change, RCX those of them that clear. - asm.mov(Dword, Rdx, Rax); - asm.alu(Alu::Xor, Dword, Rdx, Rcx); - asm.alu(Alu::And, Dword, Rcx, Rdx); - asm.alu_imm8(Alu::And, Dword, Rdx, MASK_D); - let debug = asm.jcc(Cond::Ne); - asm.alu_load(Alu::And, Dword, Rcx, pending); - let waiting = asm.jcc(Cond::Ne); - asm.mov_store(Dword, masks, Rax); - finish_unless(code, [closed, debug, waiting], pc) -} - -/// The thunk completing `MRS Xt, DAIF` at `pc` from the frame while the cell -/// at `cell` is open, else exiting at `pc`. -pub fn mask_read_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - let masks = frame_field(core::mem::offset_of!(GuestState, daif)); - asm.mov_load(Size::Dword, Gpr::Rax, masks); - asm.shift_imm(ShiftOp::Shl, Size::Dword, Gpr::Rax, MASK_SHIFT); - asm.mov_store(Size::Qword, register(rt), Gpr::Rax); - finish(code, miss, pc) -} - -/// The thunk completing `MRS Xt, ` at `pc` with the count of the -/// reader at `count` less the `value` of the cell at `cell`, else exiting -/// at `pc`. It spins while a writer publishes; `lfence` keeps the TSC -/// sample between the two sequence reads (Intel SDM Vol. 2B, RDTSC). -pub fn count_thunk(pc: GuestAddress, rt: u8, cell: Place, count: Place) -> Thunk { - use Gpr::{Rax, Rdx}; - use Size::Qword; - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - read_count(&mut asm, count); - if rt != 31 { - asm.place(Rax, cell); - asm.alu_load(Alu::Sub, Qword, Rdx, Mem::base_disp8(Rax, VALUE)); - asm.mov_store(Qword, register(rt), Rdx); - } - finish(code, miss, pc) -} - -/// What an [`energy_thunk`]'s cell `value` points at: an accumulator's -/// reading is `(count - origin) * scale / frequency` of the system count. -#[repr(C)] -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct Energy { - pub origin: u64, - pub scale: u64, - pub frequency: u64, -} - -/// The thunk completing `MRS Xt, ` at `pc` with the reading the -/// [`Energy`] the `value` of the cell at `cell` points at gives at the count -/// of the reader at `count`, else exiting at `pc`: as the cell's register's -/// model computes it, so a reading never goes back. A quotient that would -/// not fit in 64 bits exits too. It also clobbers RCX and RDX. -pub fn energy_thunk(pc: GuestAddress, rt: u8, cell: Place, count: Place) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let (mut code, miss) = open(cell); - let mut asm = Asm::new(&mut code); - read_count(&mut asm, count); - asm.place(Rax, cell); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); - let energy = |field| Mem::base_disp8(Rcx, field as i8); - // The ticks since the origin, none before it. - asm.mov(Qword, Rax, Rdx); - asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); - asm.alu_load( - Alu::Sub, - Qword, - Rax, - energy(core::mem::offset_of!(Energy, origin)), - ); - asm.cmov(Cond::B, Qword, Rax, Rdx); - asm.unary( - Unary::Mul, - Qword, - energy(core::mem::offset_of!(Energy, scale)), - ); - let frequency = energy(core::mem::offset_of!(Energy, frequency)); - asm.alu_load(Alu::Cmp, Qword, Rdx, frequency); - let wide = asm.jcc(Cond::Ae); - asm.unary(Unary::Div, Qword, frequency); - if rt != 31 { - asm.mov_store(Qword, register(rt), Rax); - } - finish_unless(code, [miss, wide], pc) -} - -/// What a [`cycle_counter_thunk`] computes a cycle counter from, as the -/// engine's performance monitor counts it: `counter` at system count -/// `synced` with `remainder` of a cycle in 1/`frequency` units, then -/// `clock` cycles a `frequency` ticks (0 while the counter does not count), -/// the sum wrapped to `mask`; `remainder` is below `frequency`. `open` is nonzero while these are the -/// monitor's; `frequency` is never 0 then. `overflow` is the counter's -/// overflow bit while its PMI is armed, else 0: a count with it set exits, -/// so that the engine's read raises the PMI at the read. `clocks` holds -/// `clock` in each PE state, which a logged transition -/// (`transition::CHAIN_LOGGED`) takes after it folds the count up to itself -/// into `counter`, `synced` and `remainder`. -#[repr(C)] -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct CycleCounter { - pub open: u64, - pub counter: u64, - pub synced: u64, - pub remainder: u64, - pub clock: u64, - pub frequency: u64, - pub mask: u64, - pub overflow: u64, - pub clocks: [u64; super::transition::STATES], -} - -impl CycleCounter { - /// The counter at system count `now`, `None` where the thunk exits - /// (closed, a quotient that does not fit in 64 bits, or a count with - /// the armed overflow bit set). - pub fn at(&self, now: u64) -> Option { - if self.open == 0 || self.frequency == 0 { - return None; - } - let ticks = now.saturating_sub(self.synced); - let scaled = u128::from(ticks) * u128::from(self.clock) + u128::from(self.remainder); - let increment = u64::try_from(scaled / u128::from(self.frequency)).ok()?; - let count = self.counter.wrapping_add(increment) & self.mask; - (count & self.overflow == 0).then_some(count) - } -} - -/// The thunk completing `MRS Xt, ` at `pc`. While the cell -/// at `cell` is open it reads its `value` (the count the engine or this -/// thunk last took in the PE's state). While it is closed but the cell at -/// `plain` is open (the read is plain in the state: only the value went -/// stale, at a native transition), it computes the count at the reader at -/// `count` from the [`CycleCounter`] at `cycles` ([`CycleCounter::at`]), -/// opens `cell` on it, as an engine read does, and completes with it. Else -/// it exits at `pc`. It also clobbers RCX and RDX. -pub fn cycle_counter_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - plain: Place, - cycles: Place, - count: Place, -) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Dword, Qword}; - let field = |offset: usize| Mem::base_disp8(Rcx, offset as i8); - let mut code = Vec::with_capacity(256); - let mut asm = Asm::new(&mut code); - asm.place(Rax, cell); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let stale = asm.jcc(Cond::E); - asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); - let read = asm.jmp(); - asm.bind(stale); - asm.place(Rax, plain); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let unplain = asm.jcc(Cond::E); - asm.place(Rcx, cycles); - asm.alu_imm8( - Alu::Cmp, - Qword, - field(core::mem::offset_of!(CycleCounter, open)), - 0, - ); - let closed = asm.jcc(Cond::E); - read_count(&mut asm, count); - asm.place(Rcx, cycles); - // The ticks since the monitor's count, none before it. - asm.mov(Qword, Rax, Rdx); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.alu_load( - Alu::Sub, - Qword, - Rax, - field(core::mem::offset_of!(CycleCounter, synced)), - ); - asm.cmov(Cond::B, Qword, Rax, Rdx); - asm.unary( - Unary::Mul, - Qword, - field(core::mem::offset_of!(CycleCounter, clock)), - ); - asm.alu_load( - Alu::Add, - Qword, - Rax, - field(core::mem::offset_of!(CycleCounter, remainder)), - ); - asm.alu_imm8(Alu::Adc, Qword, Rdx, 0); - let frequency = field(core::mem::offset_of!(CycleCounter, frequency)); - asm.alu_load(Alu::Cmp, Qword, Rdx, frequency); - let wide = asm.jcc(Cond::Ae); - asm.unary(Unary::Div, Qword, frequency); - asm.alu_load( - Alu::Add, - Qword, - Rax, - field(core::mem::offset_of!(CycleCounter, counter)), - ); - asm.alu_load( - Alu::And, - Qword, - Rax, - field(core::mem::offset_of!(CycleCounter, mask)), - ); - asm.test( - Qword, - field(core::mem::offset_of!(CycleCounter, overflow)), - Rax, - ); - let crossed = asm.jcc(Cond::Ne); - asm.mov(Qword, Rdx, Rax); - asm.place(Rax, cell); - asm.mov_store(Qword, Mem::base_disp8(Rax, VALUE), Rdx); - asm.mov_imm32(Rcx, 1); - asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); - asm.bind(read); - if rt != 31 { - asm.mov_store(Qword, register(rt), Rdx); - } - finish_unless(code, [unplain, closed, wide, crossed], pc) -} - -/// What an [`instruction_counter_thunk`] computes a retired-instruction -/// counter from, as the engine's performance monitor counts it: `base`, -/// the count as native code was entered, plus the instructions retired -/// since, masked by `step` (all ones while the counter counts, 0 while it -/// does not), the sum wrapped to `mask`. `open` is nonzero while these are -/// the monitor's. `overflow` is the counter's overflow bit while its PMI is -/// armed, else 0: a count with it set exits, so that the engine's read -/// raises the PMI at the read. `steps` holds `step` in each PE state, which -/// a logged transition (`transition::CHAIN_LOGGED`) takes, moving `base` so -/// that the count up to it stays. -#[repr(C)] -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct InstructionCounter { - pub open: u64, - pub base: u64, - pub step: u64, - pub mask: u64, - pub overflow: u64, - pub steps: [u64; super::transition::STATES], -} - -impl InstructionCounter { - /// The counter after native code retired `retired` instructions, `None` - /// where the thunk exits (closed, or a count with the armed overflow - /// bit set). - pub fn at(&self, retired: u64) -> Option { - let count = self.base.wrapping_add(retired & self.step) & self.mask; - (self.open != 0 && count & self.overflow == 0).then_some(count) - } -} - -/// The thunk completing `MRS Xt, ` at `pc`, the -/// instruction after `before` others of its block. While the cell at `cell` -/// is open it reads its `value`. While it is closed but the cell at `plain` -/// is open (only the value went stale, at a native transition), it computes -/// the count from the [`InstructionCounter`] at `counter` -/// ([`InstructionCounter::at`]) with the instructions native code retired -/// before this one: the chain's count of the blocks it left -/// (`chain::Account::retired`) and `before`. It opens `cell` on it, as an -/// engine read does, and completes with it. Else it exits at `pc`. It also -/// clobbers RCX and RDX. -pub fn instruction_counter_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - plain: Place, - counter: Place, - before: u32, -) -> Option { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let before = i32::try_from(before).ok()?; - let field = |offset: usize| Mem::base_disp8(Rcx, offset as i8); - let mut code = Vec::with_capacity(160); - let mut asm = Asm::new(&mut code); - asm.place(Rax, cell); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let stale = asm.jcc(Cond::E); - asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); - let read = asm.jmp(); - asm.bind(stale); - asm.place(Rax, plain); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let unplain = asm.jcc(Cond::E); - asm.place(Rcx, counter); - asm.alu_imm8( - Alu::Cmp, - Qword, - field(core::mem::offset_of!(InstructionCounter, open)), - 0, - ); - let closed = asm.jcc(Cond::E); - super::chain::account_retired(&mut asm, Rdx); - if before != 0 { - asm.alu_imm32(Alu::Add, Qword, Rdx, before); - } - asm.alu_load( - Alu::And, - Qword, - Rdx, - field(core::mem::offset_of!(InstructionCounter, step)), - ); - asm.alu_load( - Alu::Add, - Qword, - Rdx, - field(core::mem::offset_of!(InstructionCounter, base)), - ); - asm.alu_load( - Alu::And, - Qword, - Rdx, - field(core::mem::offset_of!(InstructionCounter, mask)), - ); - asm.test( - Qword, - field(core::mem::offset_of!(InstructionCounter, overflow)), - Rdx, - ); - let crossed = asm.jcc(Cond::Ne); - asm.place(Rax, cell); - asm.mov_store(Qword, Mem::base_disp8(Rax, VALUE), Rdx); - asm.mov_imm32(Rcx, 1); - asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); - asm.bind(read); - if rt != 31 { - asm.mov_store(Qword, register(rt), Rdx); - } - Some(finish_unless(code, [unplain, closed, crossed], pc)) -} - -/// The thunk completing `MRS Xt, ISR_EL1` at `pc` where the register reads -/// the physical IRQ and FIQ lines alone (EL2): from the masks of the -/// interrupts waiting when native code was entered ([`GuestState::pending`], -/// I in bit 1 and F in bit 0, ISR's bits 7 and 6), while the lines are still -/// those. The cell at `cell` says so: open (`readable` nonzero), the epoch at -/// `epoch` still its `value` (no line changed since it was read), and the -/// count of the reader at `count` below its `readable` (no timer or device -/// deadline passed; `u64::MAX` names none and reads no count). Else it exits -/// at `pc`. It also clobbers RCX and RDX. -pub fn interrupt_status_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - epoch: Place, - count: Place, -) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Dword, Qword}; - /// ISR_EL1.F, the lowest of the bits [`GuestState::pending`] gives. - const ISR_SHIFT: u8 = 6; - let (mut code, closed) = open(cell); - let mut asm = Asm::new(&mut code); - asm.place(Rcx, epoch); - asm.mov_load(Qword, Rdx, Mem::base(Rcx, 0)); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base_disp8(Rax, VALUE)); - let changed = asm.jcc(Cond::Ne); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), -1); - let timeless = asm.jcc(Cond::E); - read_count(&mut asm, count); - asm.place(Rax, cell); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); - let due = asm.jcc(Cond::Ae); - asm.bind(timeless); - if rt != 31 { - let pending = frame_field(core::mem::offset_of!(GuestState, pending)); - asm.mov_load(Dword, Rax, pending); - asm.alu_imm8(Alu::And, Dword, Rax, 0b11); - asm.shift_imm(ShiftOp::Shl, Dword, Rax, ISR_SHIFT); - asm.mov_store(Qword, register(rt), Rax); - } - finish_unless(code, [closed, changed, due], pc) -} - -/// What a [`timer_thunk`] completes, of one generic timer channel whose -/// count is the system count with no offset. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TimerAccess { - /// MSR TVAL: the compare becomes the count plus Xt's low 32 bits, - /// sign-extended. - WriteValue, - /// MSR CVAL: the compare becomes Xt. - WriteCompare, - /// MSR CTL: the control becomes Xt as the register takes it. - WriteControl(Written), - /// MRS CTL: ENABLE and IMASK as stored, ISTATUS while enabled with the - /// count at or past the compare. - ReadControl, -} - -/// Where a [`timer_thunk`] finds its channel and the engine's words: two -/// cells whose `value` is the address of the compare's storage and the -/// control's, the count before which the engine looks at the lines again -/// ([`crate::x86_64::transition::Places::lines_until`]), the native ISR_EL1 -/// read's cell, open until a count ([`interrupt_status_thunk`]), the count -/// reader, and `quiet`, a cell open while its `value` is what -/// [`GuestState::pending`] would hold were the channel's output low: the -/// interrupts waiting at entry but the FIQ only this channel raised. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct TimerPlaces { - pub compare: Place, - pub control: Place, - pub lines_until: Place, - pub interrupt_status: Place, - pub count: Place, - pub quiet: Place, -} - -/// ENABLE and IMASK of a timer control. -const TIMER_ARMING: i8 = 0b11; -/// ENABLE alone: the timer's output follows the compare. -const TIMER_ARMED: i8 = 0b01; -/// ISTATUS's bit. -const TIMER_STATUS_SHIFT: u8 = 2; - -/// The thunk completing `access` of a timer channel at `pc` with Xt, else -/// exiting at `pc`. Both cells must be open. A write completes only when it -/// leaves the channel's output low, and the engine's `lines_until` names a -/// count (not 0): once the write is done the channel is disabled, masked or -/// armed for a compare after the count. A compare before `lines_until` pulls -/// it, and the deadline of an open ISR_EL1 cell, down to the compare: every -/// native path that could let the line's rise pass unseen (an unmasking ERET -/// or GEXIT, an ISR_EL1 read, a WFE's spin) stops there, and the engine, -/// which looks at the lines again at the next boundary, finds the new -/// compare in storage. A completed write also makes the frame's waiting -/// interrupts `quiet`'s, which the channel's low output leaves: a kernel's -/// timer handler that rearms the timer whose FIQ it took lowers the FIQ, so -/// the ERET after it unmasks none. Where the output was high and `quiet` is -/// closed, or the write would raise or keep the line, it exits. A count -/// that passes the new compare after the thunk read it is at or past those -/// deadlines too. It clobbers RAX, RCX and RDX. -pub fn timer_thunk(pc: GuestAddress, rt: u8, access: TimerAccess, places: TimerPlaces) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::{Dword, Qword}; - let (mut code, closed) = open(places.compare); - let mut asm = Asm::new(&mut code); - asm.place(Rax, places.control); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let control_closed = asm.jcc(Cond::E); - let storage = |asm: &mut Asm<'_>, destination: Gpr, cell: Place| { - asm.place(destination, cell); - asm.mov_load(Qword, destination, Mem::base_disp8(destination, VALUE)); - }; - if access == TimerAccess::ReadControl { - read_count(&mut asm, places.count); - storage(&mut asm, Rax, places.compare); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); - asm.setcc(Cond::Ae, Rcx); - asm.movzx(Dword, Rcx, Size::Byte, Rcx); - storage(&mut asm, Rax, places.control); - asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); - asm.alu(Alu::And, Dword, Rcx, Rax); - asm.shift_imm(ShiftOp::Shl, Dword, Rcx, TIMER_STATUS_SHIFT); - asm.alu_imm8(Alu::And, Qword, Rax, !(1 << TIMER_STATUS_SHIFT)); - asm.alu(Alu::Or, Qword, Rax, Rcx); - if rt != 31 { - asm.mov_store(Qword, register(rt), Rax); - } - return finish_unless(code, [closed, control_closed], pc); - } - asm.place(Rcx, places.lines_until); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rcx, 0), 0); - let unknown = asm.jcc(Cond::E); - read_count(&mut asm, places.count); - // The output was low: not armed, or armed before its compare. - storage(&mut asm, Rax, places.control); - asm.mov_load(Dword, Rax, Mem::base(Rax, 0)); - asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); - asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); - let was_quiet = asm.jcc(Cond::Ne); - storage(&mut asm, Rax, places.compare); - asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); - let was_low = asm.jcc8(Cond::B); - // High: only where the engine knows what lowering it leaves waiting. - asm.place(Rax, places.quiet); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - let was_high = asm.jcc(Cond::E); - asm.bind(was_low); - asm.bind(was_quiet); - // The new register value into RCX, and the compare it arms into RAX - // while the control arms one, else straight to the store. - let write = |asm: &mut Asm<'_>| { - if rt == 31 { - asm.alu(Alu::Xor, Dword, Rcx, Rcx); - } else { - asm.mov_load(Qword, Rcx, register(rt)); - } - }; - let quiet = match access { - TimerAccess::WriteValue | TimerAccess::WriteCompare => { - if access == TimerAccess::WriteValue { - if rt == 31 { - asm.alu(Alu::Xor, Dword, Rcx, Rcx); - } else { - asm.movsxd(Rcx, register(rt)); - } - asm.alu(Alu::Add, Qword, Rcx, Rdx); - } else { - write(&mut asm); - } - storage(&mut asm, Rax, places.control); - asm.mov_load(Dword, Rax, Mem::base(Rax, 0)); - asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); - asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); - let quiet = asm.jcc(Cond::Ne); - asm.mov(Qword, Rax, Rcx); - quiet - } - TimerAccess::WriteControl(written) => { - write(&mut asm); - if written.keep != u64::MAX { - asm.mov_imm64(Rax, written.keep); - asm.alu(Alu::And, Qword, Rcx, Rax); - } - if written.set != 0 { - asm.mov_imm64(Rax, written.set); - asm.alu(Alu::Or, Qword, Rcx, Rax); - } - asm.mov(Dword, Rax, Rcx); - asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); - asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); - let quiet = asm.jcc(Cond::Ne); - storage(&mut asm, Rax, places.compare); - asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); - quiet - } - TimerAccess::ReadControl => unreachable!("handled above"), - }; - // Armed: after the count, and no earlier than the engine looks again. - asm.alu(Alu::Cmp, Qword, Rax, Rdx); - let at_once = asm.jcc(Cond::Be); - // Earlier than the engine looks again: pull its deadlines down. - asm.place(Rdx, places.lines_until); - asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rdx, 0)); - let later = asm.jcc(Cond::Ae); - asm.mov_store(Qword, Mem::base(Rdx, 0), Rax); - asm.place(Rdx, places.interrupt_status); - asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rdx, 0)); - let read_later = asm.jcc(Cond::Ae); - asm.mov_store(Qword, Mem::base(Rdx, 0), Rax); - asm.bind(later); - asm.bind(read_later); - asm.bind(quiet); - // The output is low from here: the FIQ only it raised goes. - asm.place(Rdx, places.quiet); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, 0), 0); - let unknown_quiet = asm.jcc8(Cond::E); - asm.mov_load(Dword, Rdx, Mem::base_disp8(Rdx, VALUE)); - asm.mov_store( - Dword, - frame_field(core::mem::offset_of!(GuestState, pending)), - Rdx, - ); - asm.bind(unknown_quiet); - let target = match access { - TimerAccess::WriteControl(_) => places.control, - _ => places.compare, - }; - storage(&mut asm, Rax, target); - asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); - finish_unless( - code, - [closed, control_closed, unknown, was_high, at_once], - pc, - ) -} - -/// A plain device read a [`device_read_thunk`] serves again: the device -/// site's physical address (`site`, 0 for none), the address it read -/// (`address`, the base register plus the offset), the `key` of the state it -/// read in ([`device_read_key`]), the model's epoch word (`epoch`, its -/// address) and the count it held (`seen`), the value read, and the system -/// count before which no device deadline came (`until`). -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DeviceRead { - pub site: u64, - pub address: u64, - pub key: u64, - pub epoch: u64, - pub seen: u64, - pub value: u64, - pub until: u64, -} - -const READ_SITE: i8 = core::mem::offset_of!(DeviceRead, site) as i8; -const READ_ADDRESS: i8 = core::mem::offset_of!(DeviceRead, address) as i8; -const READ_KEY: i8 = core::mem::offset_of!(DeviceRead, key) as i8; -const READ_EPOCH: i8 = core::mem::offset_of!(DeviceRead, epoch) as i8; -const READ_SEEN: i8 = core::mem::offset_of!(DeviceRead, seen) as i8; -const READ_VALUE: i8 = core::mem::offset_of!(DeviceRead, value) as i8; -const READ_UNTIL: i8 = core::mem::offset_of!(DeviceRead, until) as i8; - -/// The [`DeviceRead`]s a PE keeps, a slot per site and address -/// ([`device_read_slot`]). -pub const DEVICE_READS: usize = 64; - -/// The multiplier mixing a read's address into its slot, as native code's -/// `imul r64, r/m64, imm32` sign-extends it, and the bit of the product -/// where the slot's bits start: bits 26-31 of the product take every -/// address bit from 2 to 33, where a 32-bit multiplier leaves the top bits -/// to the address's high bits alone. -const ADDRESS_MIX: i32 = 0x9e37_79b1_u32 as i32; -const ADDRESS_MIX_SHIFT: u8 = 26; - -/// The slot of the read at virtual `address` by the device site at -/// physical `site`: one site that reads several addresses in turn (a -/// sampler walking per-cluster counters) keeps a slot for each. -pub const fn device_read_slot(site: u64, address: u64) -> usize { - let bits = 64 - DEVICE_READS.ilog2(); - let site = (site >> 2).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> bits; - let address = (address >> 2).wrapping_mul(ADDRESS_MIX as i64 as u64) >> ADDRESS_MIX_SHIFT; - (site ^ address) as usize & (DEVICE_READS - 1) -} - -/// The key a [`DeviceRead`] made in mirror state `state` with PSTATE.PAN -/// `pan` holds while the state's key cell holds `device_read_key(generation, -/// state, false)`: the PE's translation and its controls as they were. -pub const fn device_read_key(generation: u64, state: usize, pan: bool) -> u64 { - generation << 4 | (state as u64) << 1 | pan as u64 -} - -/// A load a [`device_read_thunk`] completes: `LDR` or `LDUR` of a B, H, W or X -/// register, zero-extending, without writeback, from a base other than SP -/// (`rn`) plus `offset` or plus an `index` register, into `rt`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DeviceLoad { - pub rn: u8, - pub offset: i32, - pub index: Option, - pub rt: u8, - pub bytes: u8, -} - -/// The index of `LDR (register)`: Xm, or Wm zero- or sign-extended, shifted -/// left by `shift`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DeviceIndex { - pub rm: u8, - pub extend: IndexExtend, - pub shift: u8, -} - -/// How `LDR (register)` widens its index ([`DeviceIndex`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum IndexExtend { - /// UXTW: Wm zero-extended. - Unsigned, - /// SXTW: Wm sign-extended. - Signed, - /// LSL or SXTX: Xm as it is. - Whole, -} - -impl DeviceLoad { - /// The load `word` makes, if a [`device_read_thunk`] completes it. - pub fn of(word: u32) -> Option { - let size = word >> 30; - let rn = (word >> 5 & 31) as u8; - let rt = (word & 31) as u8; - let mut index = None; - let offset = if word & 0x3fc0_0000 == 0x3940_0000 { - // LDR (immediate, unsigned offset). - ((word >> 10 & 0xfff) << size) as i32 - } else if word & 0x3fe0_0c00 == 0x3840_0000 { - // LDUR. - ((word << 11) as i32) >> 23 - } else if word & 0x3fe0_0c00 == 0x3860_0800 { - // LDR (register); Rm 31 is XZR, which no device load names. - let rm = (word >> 16 & 31) as u8; - let extend = match word >> 13 & 7 { - 0b010 => IndexExtend::Unsigned, - 0b110 => IndexExtend::Signed, - 0b011 | 0b111 => IndexExtend::Whole, - _ => return None, - }; - let shift = if word >> 12 & 1 != 0 { size as u8 } else { 0 }; - index = (rm != 31).then_some(DeviceIndex { rm, extend, shift }); - index?; - 0 - } else { - return None; - }; - (rn != 31).then_some(Self { - rn, - offset, - index, - rt, - bytes: 1 << size, - }) - } - - /// The virtual address the load reads with `x` its X registers' values. - pub fn address(&self, x: impl Fn(u8) -> u64) -> u64 { - let index = self.index.map_or(0, |index| { - let value = x(index.rm); - let value = match index.extend { - IndexExtend::Unsigned => value & 0xffff_ffff, - IndexExtend::Signed => value as u32 as i32 as i64 as u64, - IndexExtend::Whole => value, - }; - value << index.shift - }); - x(self.rn) - .wrapping_add_signed(i64::from(self.offset)) - .wrapping_add(index) - } - - /// Its address into RAX, as [`Self::address`]. Clobbers RCX. - fn address_into_rax(&self, asm: &mut Asm<'_>) { - use Gpr::{Rax, Rcx}; - use Size::{Dword, Qword}; - asm.mov_load(Qword, Rax, register(self.rn)); - if self.offset != 0 { - asm.alu_imm32(Alu::Add, Qword, Rax, self.offset); - } - if let Some(index) = self.index { - match index.extend { - IndexExtend::Unsigned => asm.mov_load(Dword, Rcx, register(index.rm)), - IndexExtend::Signed => asm.movsxd(Rcx, register(index.rm)), - IndexExtend::Whole => asm.mov_load(Qword, Rcx, register(index.rm)), - } - if index.shift != 0 { - asm.shift_imm(ShiftOp::Shl, Qword, Rcx, index.shift); - } - asm.alu(Alu::Add, Qword, Rax, Rcx); - } - } -} - -/// The address of the [`DeviceRead`] slot of `site` and the address in RAX -/// ([`device_read_slot`]) among `reads` into RCX. -fn device_read_slot_into_rcx(asm: &mut Asm<'_>, reads: Place, site: u64) { - use Gpr::{Rax, Rcx}; - use Size::{Dword, Qword}; - let bits = 64 - DEVICE_READS.ilog2() as u8; - let site = (site >> 2).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> bits; - asm.mov(Qword, Rcx, Rax); - asm.shift_imm(ShiftOp::Shr, Qword, Rcx, 2); - asm.imul_imm32(Qword, Rcx, Rcx, ADDRESS_MIX); - asm.shift_imm(ShiftOp::Shr, Qword, Rcx, ADDRESS_MIX_SHIFT); - asm.alu_imm8(Alu::And, Dword, Rcx, (DEVICE_READS - 1) as i8); - asm.alu_imm8(Alu::Xor, Dword, Rcx, site as i8); - asm.imul_imm32(Dword, Rcx, Rcx, core::mem::size_of::() as i32); - let anchor = core::mem::offset_of!(crate::GuestState, anchors) + reads.anchor as usize * 8; - asm.alu_load(Alu::Add, Qword, Rcx, Mem::base(Gpr::Rdi, anchor as i32)); - if reads.offset != 0 { - asm.alu_imm32(Alu::Add, Qword, Rcx, reads.offset as i32); - } -} - -/// Where a [`device_read_thunk`] finds its reads: the PE's [`DeviceRead`]s, -/// the key cell of its state, whose `value` the read's key must match, and -/// the count reader. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DeviceReadPlaces { - pub reads: Place, - pub key: Place, - pub count: Place, -} - -/// The thunk completing the plain device load `load` of the site at `pc` -/// and physical `site` natively, while the [`DeviceRead`] of the slot of -/// that site and the address the load reads now ([`device_read_slot`]) -/// holds both, the key of the PE's state and PSTATE.PAN, a model epoch that -/// still holds the count it held, and a count below `until`: it writes the -/// read's value to Xt and leaves through a direct exit to the next -/// instruction. Else it exits at `pc`. It also clobbers RCX and RDX. -pub fn device_read_thunk( - pc: GuestAddress, - site: u64, - load: DeviceLoad, - places: DeviceReadPlaces, -) -> Thunk { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let read = |offset| Mem::base_disp8(Rcx, offset); - let (mut code, closed) = open(places.key); - let mut asm = Asm::new(&mut code); - asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); - asm.alu_load( - Alu::Or, - Qword, - Rdx, - frame_field(core::mem::offset_of!(GuestState, pan)), - ); - load.address_into_rax(&mut asm); - device_read_slot_into_rcx(&mut asm, places.reads, site); - asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_KEY)); - let other_key = asm.jcc(Cond::Ne); - asm.alu_load(Alu::Cmp, Qword, Rax, read(READ_ADDRESS)); - let other_address = asm.jcc(Cond::Ne); - asm.mov_imm64(Rdx, site); - asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_SITE)); - let other_site = asm.jcc(Cond::Ne); - asm.mov_load(Qword, Rax, read(READ_EPOCH)); - asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); - asm.alu_load(Alu::Cmp, Qword, Rax, read(READ_SEEN)); - let changed = asm.jcc(Cond::Ne); - asm.alu_imm8(Alu::Cmp, Qword, read(READ_UNTIL), -1); - let timeless = asm.jcc(Cond::E); - read_count(&mut asm, places.count); - // The count clobbered the slot's address: find it again. - load.address_into_rax(&mut asm); - device_read_slot_into_rcx(&mut asm, places.reads, site); - asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_UNTIL)); - let due = asm.jcc(Cond::Ae); - asm.bind(timeless); - if load.rt != 31 { - asm.mov_load(Qword, Rax, read(READ_VALUE)); - asm.mov_store(Qword, register(load.rt), Rax); - } - finish_unless( - code, - [closed, other_key, other_site, other_address, changed, due], - pc, - ) -} - -/// The count of the reader at `count` into RDX, as [`count_thunk`] reads -/// it. Clobbers RAX and RCX. -pub(super) fn read_count(asm: &mut Asm<'_>, count: Place) { - use Gpr::{Rax, Rcx, Rdx}; - use Size::Qword; - let field = |offset| Mem::base_disp8(Rcx, offset); - let state = |offset| Mem::base_disp8(Rax, offset); - asm.place(Rcx, count); - let start = asm.jmp8(); - let busy = asm.len(); - asm.pause(); - asm.bind(start); - asm.mov_load(Qword, Rax, field(STATE)); - asm.mov_load(Qword, Rdx, state(SEQUENCE)); - asm.test_imm(Size::Byte, Rdx, 1); - let publishing = asm.jcc8(Cond::Ne); - asm.bind_back(publishing, busy); - asm.mov_store(Qword, field(SEEN_SEQUENCE), Rdx); - asm.mov_load(Qword, Rdx, state(STATE_OFFSET)); - asm.mov_store(Qword, field(SEEN_OFFSET), Rdx); - asm.mov_load(Qword, Rdx, state(CEILING)); - asm.mov_store(Qword, field(SEEN_CEILING), Rdx); - asm.lfence(); - asm.rdtsc(); - asm.lfence(); - asm.shift_imm(ShiftOp::Shl, Qword, Rdx, 32); - asm.alu(Alu::Or, Qword, Rax, Rdx); - asm.alu_load(Alu::Sub, Qword, Rax, field(BASE)); - asm.unary(Unary::Mul, Qword, field(PER_TSC)); - asm.mov_load(Qword, Rax, field(STATE)); - asm.mov_load(Qword, Rax, state(SEQUENCE)); - asm.alu_load(Alu::Cmp, Qword, Rax, field(SEEN_SEQUENCE)); - let changed = asm.jcc8(Cond::Ne); - asm.bind_back(changed, busy); - asm.alu_load(Alu::Add, Qword, Rdx, field(SEEN_OFFSET)); - asm.alu_load(Alu::Cmp, Qword, Rdx, field(SEEN_CEILING)); - asm.cmov(Cond::A, Qword, Rdx, field(SEEN_CEILING)); - asm.alu_load(Alu::Cmp, Qword, Rdx, field(LAST)); - asm.cmov(Cond::B, Qword, Rdx, field(LAST)); - asm.mov_store(Qword, field(LAST), Rdx); -} - -/// Load `cell` and branch to the miss while it is not readable. -fn open(cell: Place) -> (Vec, Patch) { - let mut code = Vec::with_capacity(128); - let mut asm = Asm::new(&mut code); - asm.place(Gpr::Rax, cell); - asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rax, 0), 0); - let miss = asm.jcc(Cond::E); - (code, miss) -} - -/// The direct exit to the next instruction, then the `miss` branch's -/// target: the original exit at `pc`. -fn finish(code: Vec, miss: Patch, pc: GuestAddress) -> Thunk { - finish_unless(code, [miss], pc) -} - -/// [`finish`] with several branches to the original exit. -fn finish_unless(mut code: Vec, misses: [Patch; N], pc: GuestAddress) -> Thunk { - let next = code.len(); - let mut asm = Asm::new(&mut code); - super::block::direct_exit_with( - &mut asm, - GuestAddress(pc.0.wrapping_add(4)), - ExitKind::Fallthrough, - ); - for miss in misses { - asm.bind(miss); - } - super::block::direct_exit_with(&mut asm, pc, ExitKind::System); - Thunk::new(code, Some(next), None) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Anchor; - use crate::x86_64::chain::{DIRECT_EXIT_BYTES, direct_exit}; - - /// The anchors of these tests, each at the data itself. - const CELL: Place = Place::new(Anchor::Mirrors, 0); - const WORD: Place = Place::new(Anchor::Pointer, 0); - const READER: Place = Place::new(Anchor::Count, 0); - const SP0: Place = Place::new(Anchor::StackZero, 0); - - #[test] - fn pan_writes_move_the_flag_and_the_frame() { - for (pan, flag) in [(true, [0x0f, 0x01, 0xca]), (false, [0x0f, 0x01, 0xcb])] { - let thunk = pan_thunk(GuestAddress(0x1000), pan, CELL); - assert!(thunk.code.windows(3).any(|bytes| bytes == flag)); - assert!(thunk.next.is_some()); - } - } - - #[test] - fn mask_writes_name_their_form() { - assert_eq!(MaskWrite::of(0xd503_47df), Some(MaskWrite::Set(7))); - assert_eq!(MaskWrite::of(0xd503_4fdf), Some(MaskWrite::Set(15))); - assert_eq!(MaskWrite::of(0xd503_47ff), Some(MaskWrite::Clear(7))); - assert_eq!(MaskWrite::of(0xd51b_4229), Some(MaskWrite::Register(9))); - for other in [0xd500_40bf_u32, 0xd500_409f, 0xd53b_4228, 0xd503_201f] { - assert_eq!(MaskWrite::of(other), None, "{other:#x}"); - } - } - - /// The emitted code runs on the host: masks change in the frame, and a - /// change of D or of a waiting interrupt's mask stays with the engine. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn mask_writes_complete_in_the_frame() { - use core::ffi::c_void; - unsafe extern "C" { - fn mmap( - address: *mut c_void, - bytes: usize, - protection: i32, - flags: i32, - fd: i32, - offset: i64, - ) -> *mut c_void; - fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; - fn munmap(address: *mut c_void, bytes: usize) -> i32; - } - #[cfg(target_os = "macos")] - const MAP_ANONYMOUS: i32 = 0x1000; - #[cfg(target_os = "linux")] - const MAP_ANONYMOUS: i32 = 0x20; - const PAGE: usize = 4096; - const PC: GuestAddress = GuestAddress(0x4000); - let open = Cell { - readable: 1, - value: 0, - }; - // The PC of the exit `write` takes. - fn run(write: MaskWrite, cell: &Cell, state: &mut GuestState) -> u64 { - let thunk = mask_thunk(write, PC, CELL); - state.anchors[Anchor::Mirrors] = cell as *const Cell as u64; - // SAFETY: private anonymous memory, RX after the copy, unmapped - // after the call; the code reads and writes only `state` and - // `cell`. - unsafe { - let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0); - assert_ne!(page as usize, usize::MAX); - core::ptr::copy_nonoverlapping(thunk.code.as_ptr(), page.cast(), thunk.code.len()); - assert_eq!(mprotect(page, PAGE, 5), 0); - let entry = |state: *mut crate::GuestState| -> u128 { - crate::x86_64::native::call::(page as *const u8, state, 0, 0) - }; - let exit = entry(state); - assert_eq!(munmap(page, PAGE), 0); - exit as u64 - } - } - let (next, here) = (PC.0 + 4, PC.0); - let mut state = GuestState { - daif: 0b1000, - ..GuestState::default() - }; - assert_eq!(run(MaskWrite::Set(7), &open, &mut state), next); - assert_eq!(state.daif, 0b1111); - assert_eq!(run(MaskWrite::Clear(2), &open, &mut state), next); - assert_eq!(state.daif, 0b1101); - state.x[9] = 0b0011 << 6 | 0b1000 << 6 | 1 << 40; - assert_eq!(run(MaskWrite::Register(9), &open, &mut state), next); - assert_eq!(state.daif, 0b1011); - // An interrupt waits on I. - state.pending = 0b0010; - assert_eq!(run(MaskWrite::Clear(2), &open, &mut state), here); - assert_eq!(state.daif, 0b1011); - assert_eq!(run(MaskWrite::Clear(1), &open, &mut state), next); - assert_eq!(state.daif, 0b1010); - // Masking more is always fine, and D stays with the engine. - assert_eq!(run(MaskWrite::Set(1), &open, &mut state), next); - assert_eq!(run(MaskWrite::Clear(8), &open, &mut state), here); - state.daif = 0b0011; - assert_eq!(run(MaskWrite::Set(8), &open, &mut state), here); - assert_eq!(state.daif, 0b0011); - // Closed, every write is the engine's. - let closed = Cell::default(); - assert_eq!(run(MaskWrite::Set(1), &closed, &mut state), here); - } - - #[test] - fn thunks_end_in_the_fallthrough_then_the_original_exit() { - let pc = GuestAddress(0x4000); - let thunk = thunk(pc, 8, CELL); - let end = thunk.code.len(); - assert_eq!( - thunk.code[end - DIRECT_EXIT_BYTES..], - direct_exit(pc, ExitKind::System) - ); - let next = thunk.next.unwrap(); - assert_eq!(next + DIRECT_EXIT_BYTES, end - DIRECT_EXIT_BYTES); - // Padded for its offset, where a link patches it. - assert_eq!( - thunk.code[next..next + DIRECT_EXIT_BYTES], - crate::x86_64::chain::direct_exit_at( - next as u64, - GuestAddress(0x4004), - ExitKind::Fallthrough - ) - ); - } - - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[repr(C)] - #[derive(Debug, PartialEq, Eq)] - struct Exit { - pc: u64, - kind: u64, - } - - /// Run a thunk on the host. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - fn run(code: &[u8], state: &mut crate::GuestState) -> Exit { - use core::ffi::c_void; - unsafe extern "C" { - fn mmap( - address: *mut c_void, - bytes: usize, - protection: i32, - flags: i32, - fd: i32, - offset: i64, - ) -> *mut c_void; - fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; - fn munmap(address: *mut c_void, bytes: usize) -> i32; - } - #[cfg(target_os = "macos")] - const MAP_ANONYMOUS: i32 = 0x1000; - #[cfg(target_os = "linux")] - const MAP_ANONYMOUS: i32 = 0x20; - const PAGE: usize = 4096; - let code = super::super::pinned::entered(code); - // SAFETY: private anonymous memory, RX after the copy, unmapped after - // the call; the thunk touches only `state` and its cells, which - // outlive it. - unsafe { - let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0); - assert_ne!(page as usize, usize::MAX); - core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); - assert_eq!(mprotect(page, PAGE, 5), 0); - let entry = |state: *mut crate::GuestState| -> Exit { - crate::x86_64::native::call::(page as *const u8, state, 0, 0) - }; - let exit = entry(state); - assert_eq!(munmap(page, PAGE), 0); - exit - } - } - - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - const PC: GuestAddress = GuestAddress(0x4000); - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - const MISS: Exit = Exit { - pc: PC.0, - kind: ExitKind::System as u64, - }; - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - const NEXT: Exit = Exit { - pc: PC.0 + 4, - kind: ExitKind::Fallthrough as u64, - }; - - /// A thread pointer write runs on the host: with its cell open it writes - /// the storage and every open read cell, logs a switch to another value - /// with the frame and link registers, changes nothing for the same - /// value, and leaves everything to the engine with the cell closed or - /// the log full. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn thread_switches_write_the_register_its_reads_and_the_log() { - use crate::GuestState; - use core::mem::offset_of; - #[repr(C)] - #[derive(Default)] - struct Data { - write: Cell, - storage: u64, - reads: [Cell; 3], - log: SwitchLog, - } - let (pc, miss, next) = (PC, MISS, NEXT); - let mut data = alloc::boxed::Box::new(Data::default()); - let base = &mut *data as *mut Data; - let place = |offset: usize| Place::new(Anchor::Mirrors, offset); - let places = ThreadSwitch { - reads: place(offset_of!(Data, reads)), - stride: size_of::(), - banks: 3, - log: place(offset_of!(Data, log)), - }; - let cell = place(offset_of!(Data, write)); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = base as u64; - state.x[29] = 0xffff_fe00_0000_2900; - state.x[30] = 0xffff_fe00_0000_3000; - let storage = base as u64 + offset_of!(Data, storage) as u64; - // SAFETY: `base` points into the live box; reads and writes happen - // between thunk calls. - let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; - let open = Cell { - readable: 1, - value: 0x1000, - }; - data(&mut |d| { - d.write = Cell { - readable: 0, - value: storage, - }; - d.storage = 0x1000; - d.reads = [open, Cell::default(), open]; - }); - state.x[5] = 0x2000; - let write = thread_switch_thunk(pc, 5, cell, &places); - assert_eq!(run(&write.code, &mut state), miss); - data(&mut |d| assert_eq!((d.storage, d.log.len), (0x1000, 0))); - data(&mut |d| d.write.readable = 1); - assert_eq!(run(&write.code, &mut state), next); - data(&mut |d| { - assert_eq!(d.storage, 0x2000); - let new = Cell { - readable: 1, - value: 0x2000, - }; - assert_eq!(d.reads, [new, Cell::default(), new]); - assert_eq!(d.log.len, 1); - let switch = Switch { - previous: 0x1000, - next: 0x2000, - frame: 0xffff_fe00_0000_2900, - link: 0xffff_fe00_0000_3000, - pc: pc.0, - }; - assert_eq!(d.log.entries[0], switch); - }); - // The same value again: nothing logged. - assert_eq!(run(&write.code, &mut state), next); - data(&mut |d| assert_eq!(d.log.len, 1)); - // XZR, then values until the log is full: the next one exits. - assert_eq!( - run(&thread_switch_thunk(pc, 31, cell, &places).code, &mut state), - next - ); - data(&mut |d| assert_eq!((d.storage, d.log.entries[1].next), (0, 0))); - for value in 2..SWITCHES as u64 { - state.x[5] = value; - assert_eq!(run(&write.code, &mut state), next); - } - data(&mut |d| assert_eq!((d.log.len, d.storage), (SWITCHES as u64, 7))); - state.x[5] = 0x9000; - assert_eq!(run(&write.code, &mut state), miss); - data(&mut |d| { - assert_eq!(d.storage, 7); - assert_eq!(d.reads[0].value, 7); - }); - } - - /// Thunks run on the host: a readable cell completes the read into Xt, - /// or into nothing for XZR; a cleared one exits with no write. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn thunks_read_the_cell_only_while_it_is_readable() { - use crate::GuestState; - let (pc, miss, next) = (PC, MISS, NEXT); - let mut cell = alloc::boxed::Box::new(Cell::default()); - let address = &mut *cell as *mut Cell; - // SAFETY: address points into the live Cell box; the closure runs between thunk calls. - let set = |value: Cell| unsafe { address.write(value) }; - let mut state = GuestState::default(); - state.x[19] = 7; - state.anchors[Anchor::Mirrors] = address as u64; - let read = thunk(pc, 19, CELL); - set(Cell { - readable: 0, - value: 0xffff_fe00_1234_5000, - }); - assert_eq!(run(&read.code, &mut state), miss); - assert_eq!(state.x[19], 7); - set(Cell { - readable: 1, - value: 0xffff_fe00_1234_5000, - }); - assert_eq!(run(&read.code, &mut state), next); - assert_eq!(state.x[19], 0xffff_fe00_1234_5000); - let before = state.x; - assert_eq!(run(&thunk(pc, 31, CELL).code, &mut state), next); - assert_eq!(state.x, before); - } - - /// IC IVAU of the cell's page completes; of another, or with the cell - /// closed, it exits. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn the_code_page_thunk_completes_only_in_the_open_cells_page() { - use crate::GuestState; - let open = Cell { - readable: 1, - value: 0xffff_fe00_1234_5040, - }; - let closed = Cell::default(); - let mut state = GuestState::default(); - for (cell, xt, exit) in [ - (&open, 0xffff_fe00_1234_5fc0, NEXT), - (&open, 0xffff_fe00_1234_6000, MISS), - (&closed, 0xffff_fe00_1234_5fc0, MISS), - ] { - state.x[19] = xt; - state.anchors[Anchor::Mirrors] = cell as *const Cell as u64; - let thunk = code_page_thunk(PC, 19, CELL); - assert_eq!(run(&thunk.code, &mut state), exit); - assert_eq!(state.x[19], xt); - } - } - - #[test] - fn write_thunks_store_the_kept_bits_only_while_the_cell_is_open() { - use crate::GuestState; - let written = Written { - keep: 0xff00, - set: 1, - }; - let mut storage = alloc::boxed::Box::new(0u64); - let target = &mut *storage as *mut u64; - let mut cell = alloc::boxed::Box::new(Cell::default()); - let address = &mut *cell as *mut Cell; - let mut state = GuestState::default(); - state.x[3] = 0xabcd; - state.anchors[Anchor::Mirrors] = address as u64; - let code = stored_write_thunk(PC, 3, CELL, written).code; - assert_eq!(run(&code, &mut state), MISS); - // SAFETY: the live Cell box and the live storage, between runs. - unsafe { - address.write(Cell { - readable: 1, - value: target as u64, - }); - } - assert_eq!(run(&code, &mut state), NEXT); - // SAFETY: as above. - assert_eq!(unsafe { target.read() }, 0xab01); - let zero = stored_write_thunk(PC, 31, CELL, written).code; - assert_eq!(run(&zero, &mut state), NEXT); - // SAFETY: as above. - assert_eq!(unsafe { target.read() }, 1); - let offset = core::mem::offset_of!(GuestState, fpsr); - let frame = frame_write_thunk(PC, 3, CELL, offset, written).code; - assert_eq!(run(&frame, &mut state), NEXT); - assert_eq!(state.fpsr, 0xab01); - } - - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn key_writes_close_the_tag_words_only_when_they_change_the_key() { - use crate::GuestState; - let mut key = alloc::boxed::Box::new(5u64); - let target = &mut *key as *mut u64; - let mut cell = alloc::boxed::Box::new(Cell { - readable: 1, - value: target as u64, - }); - let mut tags = alloc::boxed::Box::new([7u64; 3]); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &*cell as *const Cell as u64; - state.anchors[Anchor::Pointer] = tags.as_mut_ptr() as u64; - let place = Place::new(Anchor::Pointer, 0); - let code = key_write_thunk(PC, 3, CELL, place, 2).code; - state.x[3] = 5; - assert_eq!(run(&code, &mut state), NEXT); - assert_eq!(*tags, [7; 3]); - state.x[3] = 6; - assert_eq!(run(&code, &mut state), NEXT); - // SAFETY: the live key, between runs. - assert_eq!(unsafe { target.read() }, 6); - assert_eq!(*tags, [0, 0, 7]); - tags[0] = 7; - cell.readable = 0; - state.x[3] = 8; - assert_eq!(run(&code, &mut state), MISS); - // SAFETY: as above. - assert_eq!(unsafe { target.read() }, 6); - assert_eq!(tags[0], 7); - } - - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn checked_writes_leave_the_refused_bits_to_the_exit() { - use crate::GuestState; - let mut storage = alloc::boxed::Box::new(5u64); - let target = &mut *storage as *mut u64; - let cell = alloc::boxed::Box::new(Cell { - readable: 1, - value: target as u64, - }); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &*cell as *const Cell as u64; - let code = checked_write_thunk(PC, 3, CELL, 0xf0).code; - state.x[3] = 0x10f; - assert_eq!(run(&code, &mut state), NEXT); - // SAFETY: the live storage, between runs. - assert_eq!(unsafe { target.read() }, 0x10f); - state.x[3] = 0x10; - assert_eq!(run(&code, &mut state), MISS); - // SAFETY: as above. - assert_eq!(unsafe { target.read() }, 0x10f); - let zero = checked_write_thunk(PC, 31, CELL, u64::MAX).code; - assert_eq!(run(&zero, &mut state), NEXT); - // SAFETY: as above. - assert_eq!(unsafe { target.read() }, 0); - } - - #[test] - fn stack_select_moves_the_frame_sp_between_the_stacks() { - use crate::GuestState; - let mut cell = alloc::boxed::Box::new(Cell::default()); - let address = &mut *cell as *mut Cell as u64; - let mut stacks = alloc::boxed::Box::new([0x1000u64, 0x2000]); - let (sp0, spx) = (stacks.as_mut_ptr() as u64, stacks.as_mut_ptr() as u64 + 8); - let mut current = alloc::boxed::Box::new(1u64); - let word = &mut *current as *mut u64 as u64; - let mut state = GuestState { - sp: 0x3000, - ..GuestState::default() - }; - state.anchors[Anchor::Mirrors] = address; - state.anchors[Anchor::Pointer] = word; - state.anchors[Anchor::StackZero] = sp0; - let to_sp0 = stack_select_thunk(PC, false, CELL, WORD, SP0).code; - let to_spx = stack_select_thunk(PC, true, CELL, WORD, SP0).code; - assert_eq!(run(&to_sp0, &mut state), MISS); - cell.readable = 1; - cell.value = spx; - // Cross the box with a raw read: the thunk wrote through addresses. - let read = |at: u64| { - // SAFETY: a live word of `stacks` or `current`. - unsafe { (at as *const u64).read_volatile() } - }; - assert_eq!(run(&to_sp0, &mut state), NEXT); - assert_eq!((state.sp, read(spx), read(word)), (0x1000, 0x3000, 0)); - // Selecting what is selected moves nothing. - assert_eq!(run(&to_sp0, &mut state), NEXT); - assert_eq!((state.sp, read(spx)), (0x1000, 0x3000)); - state.sp = 0x1800; - assert_eq!(run(&to_spx, &mut state), NEXT); - assert_eq!((state.sp, read(sp0), read(word)), (0x3000, 0x1800, 1)); - } - - /// A count read adds the state's offset to the scaled TSC (zero here, - /// as `per_tsc` is), stays at or below its ceiling, never reads below - /// `last` and keeps what it read there, and subtracts the cell's value; - /// XZR still moves `last`. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn count_thunks_read_a_monotonic_bounded_count_less_the_cell_value() { - use crate::GuestState; - use core::sync::atomic::Ordering::Relaxed; - let mut cell = alloc::boxed::Box::new(Cell::default()); - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - last: 50, - state: &*published as *const CountState as u64, - ..Count::default() - }); - let (cell_at, count_at) = (&mut *cell as *mut Cell, &mut *count as *mut Count); - let read = count_thunk(PC, 3, CELL, READER); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = cell_at as u64; - state.anchors[Anchor::Count] = count_at as u64; - assert_eq!(run(&read.code, &mut state), MISS); - // SAFETY: the boxes outlive every thunk run. - unsafe { - cell_at.write(Cell { - readable: 1, - value: 30, - }) - }; - let last = || { - // SAFETY: the Count box is live and every thunk run has returned. - unsafe { (*count_at).last } - }; - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!((state.x[3], last()), (70, 100)); - published.offset.store(80, Relaxed); - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!((state.x[3], last()), (70, 100)); - published.offset.store(500, Relaxed); - published.ceiling.store(300, Relaxed); - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!((state.x[3], last()), (270, 300)); - published.ceiling.store(u64::MAX, Relaxed); - let before = state.x; - let discard = count_thunk(PC, 31, CELL, READER); - assert_eq!(run(&discard.code, &mut state), NEXT); - assert_eq!((state.x, last()), (before, 500)); - } - - #[test] - fn device_loads_name_their_base_offset_and_width() { - // ldr w8, [x9, #0x14]; ldr x0, [x1]; ldrb w2, [x3, #1]; ldrh w4, [x5, #6] - assert_eq!( - DeviceLoad::of(0xb940_1528), - Some(DeviceLoad { - rn: 9, - offset: 0x14, - index: None, - rt: 8, - bytes: 4 - }) - ); - assert_eq!( - DeviceLoad::of(0xf940_0020), - Some(DeviceLoad { - rn: 1, - offset: 0, - index: None, - rt: 0, - bytes: 8 - }) - ); - assert_eq!( - DeviceLoad::of(0x3940_0462), - Some(DeviceLoad { - rn: 3, - offset: 1, - index: None, - rt: 2, - bytes: 1 - }) - ); - assert_eq!( - DeviceLoad::of(0x7940_0ca4), - Some(DeviceLoad { - rn: 5, - offset: 6, - index: None, - rt: 4, - bytes: 2 - }) - ); - // ldur w0, [x1, #-4] - assert_eq!( - DeviceLoad::of(0xb85f_c020), - Some(DeviceLoad { - rn: 1, - offset: -4, - index: None, - rt: 0, - bytes: 4 - }) - ); - // ldr x13, [x11, w13, uxtw]; ldr w0, [x1, x2]; ldr x0, [x1, w2, sxtw #3] - let indexed = |rn, rm, extend, shift, rt, bytes| DeviceLoad { - rn, - offset: 0, - index: Some(DeviceIndex { rm, extend, shift }), - rt, - bytes, - }; - assert_eq!( - DeviceLoad::of(0xf86d_496d), - Some(indexed(11, 13, IndexExtend::Unsigned, 0, 13, 8)) - ); - assert_eq!( - DeviceLoad::of(0xb862_6820), - Some(indexed(1, 2, IndexExtend::Whole, 0, 0, 4)) - ); - assert_eq!( - DeviceLoad::of(0xf862_d820), - Some(indexed(1, 2, IndexExtend::Signed, 3, 0, 8)) - ); - let x = |r: u8| match r { - 1 => 0x1000, - 2 => 0xffff_ffff_ffff_fff0, - 11 => 0x2000, - 13 => 0xffff_ffff_0000_0040, - _ => 0, - }; - assert_eq!(DeviceLoad::of(0xf86d_496d).unwrap().address(x), 0x2040); - assert_eq!( - DeviceLoad::of(0xf862_d820).unwrap().address(x), - 0x1000 - 0x80 - ); - assert_eq!(DeviceLoad::of(0xb85f_c020).unwrap().address(x), 0xffc); - // ldr x0, [sp]; ldrsw x0, [x1]; str w0, [x1]; ldr w0, [x1], #4; - // ldr w0, [x1, xzr]; ldr w0, [x1, w2, uxth] (unallocated) - for other in [ - 0xf940_03e0_u32, - 0xb980_0020, - 0xb900_0020, - 0xb840_4420, - 0xb87f_6820, - 0xb862_2820, - ] { - assert_eq!(DeviceLoad::of(other), None, "{other:#x}"); - } - } - - /// A device read runs on the host: it completes from its slot while the - /// key, site, address, epoch and count all agree, and exits otherwise. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn device_reads_complete_from_their_slot_while_everything_agrees() { - use crate::GuestState; - use core::mem::offset_of; - use core::sync::atomic::Ordering::Relaxed; - #[repr(C)] - struct Data { - key: Cell, - reads: [DeviceRead; DEVICE_READS], - } - const SITE: u64 = 0x8_0000_1234; - let load = DeviceLoad { - rn: 1, - offset: 0x10, - index: None, - rt: 2, - bytes: 4, - }; - let mut data = alloc::boxed::Box::new(Data { - key: Cell::default(), - reads: [DeviceRead::default(); DEVICE_READS], - }); - let base = &mut *data as *mut Data; - let epoch = alloc::boxed::Box::new(AtomicU64::new(7)); - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let places = DeviceReadPlaces { - reads: Place::new(Anchor::Mirrors, offset_of!(Data, reads)), - key: Place::new(Anchor::Mirrors, offset_of!(Data, key)), - count: READER, - }; - let thunk = device_read_thunk(PC, SITE, load, places); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = base as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - state.x[1] = 0xffff_fe00_1000_0000; - let key = device_read_key(3, 1, false); - let slot = device_read_slot(SITE, 0xffff_fe00_1000_0010); - // SAFETY: `base` points into the live box; written between runs. - let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; - assert_eq!(run(&thunk.code, &mut state), MISS); - data(&mut |d| { - d.key = Cell { - readable: 1, - value: key, - }; - d.reads[slot] = DeviceRead { - site: SITE, - address: 0xffff_fe00_1000_0010, - key, - epoch: &*epoch as *const AtomicU64 as u64, - seen: 7, - value: 0xabcd, - until: u64::MAX, - }; - }); - assert_eq!(run(&thunk.code, &mut state), NEXT); - assert_eq!(state.x[2], 0xabcd); - state.x[2] = 0; - // Another address, PAN, key, epoch or a passed deadline exit. - state.x[1] += 8; - assert_eq!(run(&thunk.code, &mut state), MISS); - state.x[1] -= 8; - state.pan = 1; - assert_eq!(run(&thunk.code, &mut state), MISS); - state.pan = 0; - data(&mut |d| d.key.value = device_read_key(4, 1, false)); - assert_eq!(run(&thunk.code, &mut state), MISS); - data(&mut |d| d.key.value = key); - epoch.store(8, Relaxed); - assert_eq!(run(&thunk.code, &mut state), MISS); - epoch.store(7, Relaxed); - data(&mut |d| d.reads[slot].until = 50); - assert_eq!(run(&thunk.code, &mut state), MISS); - data(&mut |d| d.reads[slot].until = 1000); - assert_eq!(run(&thunk.code, &mut state), NEXT); - assert_eq!(state.x[2], 0xabcd); - data(&mut |d| d.reads[slot].site = SITE + 4); - assert_eq!(run(&thunk.code, &mut state), MISS); - data(&mut |d| d.reads[slot].site = SITE); - data(&mut |d| d.key.readable = 0); - assert_eq!(run(&thunk.code, &mut state), MISS); - assert_eq!(state.x[2], 0xabcd); - } - - /// One indexed load site reading a counter of each cluster in turn - /// (`ldr x13, [x11, w13, uxtw]`) completes each from the slot of its - /// own address, the timed one past its deadline exiting. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn indexed_device_reads_keep_a_slot_per_address() { - use crate::GuestState; - use core::mem::offset_of; - use core::sync::atomic::Ordering::Relaxed; - #[repr(C)] - struct Data { - key: Cell, - reads: [DeviceRead; DEVICE_READS], - } - const SITE: u64 = 0x8_0000_2144; - const CLUSTERS: [u64; 2] = [0xffff_fe00_2000_4100, 0xffff_fe00_2004_4100]; - let load = DeviceLoad::of(0xf86d_496d).expect("an indexed load"); - let slots = CLUSTERS.map(|address| device_read_slot(SITE, address + 0x20)); - assert_ne!(slots[0], slots[1]); - let mut data = alloc::boxed::Box::new(Data { - key: Cell::default(), - reads: [DeviceRead::default(); DEVICE_READS], - }); - let base = &mut *data as *mut Data; - let epoch = alloc::boxed::Box::new(AtomicU64::new(7)); - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let places = DeviceReadPlaces { - reads: Place::new(Anchor::Mirrors, offset_of!(Data, reads)), - key: Place::new(Anchor::Mirrors, offset_of!(Data, key)), - count: READER, - }; - let thunk = device_read_thunk(PC, SITE, load, places); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = base as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - let key = device_read_key(3, 1, false); - // SAFETY: `base` points into the live box; written between runs. - let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; - data(&mut |d| { - d.key = Cell { - readable: 1, - value: key, - }; - for (cluster, (&slot, &address)) in slots.iter().zip(&CLUSTERS).enumerate() { - d.reads[slot] = DeviceRead { - site: SITE, - address: address + 0x20, - key, - epoch: &*epoch as *const AtomicU64 as u64, - seen: 7, - value: 0x100 + cluster as u64, - until: if cluster == 0 { u64::MAX } else { 1000 }, - }; - } - }); - for _ in 0..2 { - for (cluster, &address) in CLUSTERS.iter().enumerate() { - state.x[11] = address; - state.x[13] = 0xdead_0000_0000_0020; - assert_eq!(run(&thunk.code, &mut state), NEXT); - assert_eq!(state.x[13], 0x100 + cluster as u64); - } - } - // Another index, or the timed cluster past its deadline, exits. - state.x[11] = CLUSTERS[0]; - state.x[13] = 0x28; - assert_eq!(run(&thunk.code, &mut state), MISS); - data(&mut |d| d.reads[slots[1]].until = 50); - state.x[11] = CLUSTERS[1]; - state.x[13] = 0x20; - assert_eq!(run(&thunk.code, &mut state), MISS); - state.x[11] = CLUSTERS[0]; - assert_eq!(run(&thunk.code, &mut state), NEXT); - assert_eq!(state.x[13], 0x100); - } - - /// What the event thunks of these tests find at [`Anchor::Mirrors`]. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[repr(C)] - #[derive(Default)] - struct Waits { - events: Cell, - waits: Cell, - monitor: u64, - lines_until: u64, - spin: EventSpin, - stream: EventStream, - } - - /// The event thunks of these tests, and their words: an event register, - /// a control and a count that `per_tsc` moves (0 holds it at 100). - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - struct Events { - send: Thunk, - wait: Thunk, - event: alloc::boxed::Box, - waits: alloc::boxed::Box, - control: alloc::boxed::Box, - _published: alloc::boxed::Box, - count: alloc::boxed::Box, - state: crate::GuestState, - } - - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - impl Events { - fn new(per_tsc: u64) -> Self { - use core::mem::offset_of; - use core::sync::atomic::Ordering::Relaxed; - let place = |offset: usize| Place::new(Anchor::Mirrors, offset); - let events = place(offset_of!(Waits, events)); - let places = EventWaitPlaces { - events, - waits: place(offset_of!(Waits, waits)), - monitor: place(offset_of!(Waits, monitor)), - control: Place::new(Anchor::Control, 0), - lines_until: place(offset_of!(Waits, lines_until)), - count: READER, - spin: place(offset_of!(Waits, spin)), - stream: place(offset_of!(Waits, stream)), - }; - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut events = Self { - send: send_event_thunk(PC, events), - wait: event_wait_thunk(PC, places), - event: alloc::boxed::Box::default(), - waits: alloc::boxed::Box::default(), - control: alloc::boxed::Box::default(), - count: alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - per_tsc, - ..Count::default() - }), - _published: published, - state: crate::GuestState::default(), - }; - let anchors = &mut events.state.anchors; - anchors[Anchor::Mirrors] = &mut *events.waits as *mut Waits as u64; - anchors[Anchor::Control] = - &mut *events.control as *mut crate::x86_64::chain::ChainControl as u64; - anchors[Anchor::Count] = &mut *events.count as *mut Count as u64; - events - } - - fn open(&mut self) { - self.waits.events = Cell { - readable: 1, - value: &*self.event as *const core::sync::atomic::AtomicU8 as u64, - }; - } - - fn wait(&mut self) -> Exit { - run(&self.wait.code, &mut self.state) - } - - /// Run the WFE while another thread does `act` once the spin began, - /// if it began and that thread sees it before the WFE returns. - fn wait_while(&mut self, act: impl FnOnce(&Self) + Send) -> Exit { - use core::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst}; - self.waits.spin.turns = 0; - let turns = &raw const self.waits.spin.turns as usize; - let this = self as *mut Self as usize; - let returned = AtomicBool::new(false); - std::thread::scope(|scope| { - let returned = &returned; - scope.spawn(move || { - // SAFETY: the spin's word, which the thunk writes with - // aligned stores while this thread reads it atomically. - let turns = unsafe { AtomicU64::from_ptr(turns as *mut u64) }; - while turns.load(SeqCst) == 0 && !returned.load(SeqCst) { - core::hint::spin_loop(); - } - if !returned.load(SeqCst) { - // SAFETY: the words `act` touches are atomics or - // ones the thunk only reads. - act(unsafe { &*(this as *const Self) }); - } - }); - // SAFETY: `act` touches no word the thunk writes. - let exit = unsafe { (*(this as *mut Self)).wait() }; - returned.store(true, SeqCst); - exit - }) - } - } - - /// SEVL sets the event register; WFE clears a set one and completes, and - /// leaves a clear one, or a closed cell, to the engine where it waits - /// otherwise than by spinning. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn event_thunks_set_and_consume_the_event_register() { - use core::sync::atomic::Ordering::Relaxed; - let mut events = Events::new(0); - assert_eq!(run(&events.send.code, &mut events.state), MISS); - events.open(); - assert_eq!(events.wait(), MISS); - assert_eq!(run(&events.send.code, &mut events.state), NEXT); - assert_eq!(events.event.load(Relaxed), 1); - assert_eq!(events.wait(), NEXT); - assert_eq!(events.event.load(Relaxed), 0); - assert_eq!(events.wait(), MISS); - assert_eq!(events.waits.spin, EventSpin::default(), "no spin"); - } - - /// With the register clear, an event stream edge at or before the count - /// (held at 100) completes the WFE, before a monitor or a trap is - /// looked at: the sample moves to the count and the next edge to the - /// first one past it. Without one, the WFE goes on as before. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn event_waits_take_a_stream_edge_since_the_sample() { - let mut events = Events::new(0); - events.open(); - events.waits.monitor = 1; - assert_eq!(events.wait(), MISS, "no stream"); - for (next, after) in [(100, 108), (60, 108), (93, 101)] { - events.waits.stream = EventStream { - next, - period: 8, - sampled: 7, - }; - assert_eq!(events.wait(), NEXT, "{next}"); - let stream = events.waits.stream; - assert_eq!((stream.next, stream.sampled), (after, 100), "{next}"); - // The edge is taken: the next WFE finds none. - assert_eq!(events.wait(), MISS, "{next}"); - } - assert_eq!(events.waits.spin.streamed, 3); - events.waits.stream.next = 101; - assert_eq!(events.wait(), MISS); - assert_eq!(events.waits.stream.sampled, 100); - // Edges without a period: one is taken, the next is the engine's. - events.waits.stream = EventStream { - next: 99, - period: 0, - sampled: 7, - }; - assert_eq!(events.wait(), NEXT); - assert_eq!(events.waits.stream.next, u64::MAX); - assert_eq!(events.wait(), MISS); - assert_eq!(events.waits.spin.streamed, 4); - } - - /// Where the WFE would wait, a clear event register makes it spin: it - /// exits at once with an interrupt waiting, anything posted or the count - /// at `lines_until`, counting nothing, and with a monitor held, counting - /// that; a spin ends after [`WFE_SPIN_COUNTS`] of the count, or its - /// turns where the count holds, counting a miss and the counts spent. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn event_waits_spin_only_while_nothing_else_wakes_them() { - let mut events = Events::new(0); - events.open(); - events.waits.waits.readable = 1; - events.waits.lines_until = u64::MAX; - let quiet = EventSpin::default(); - events.state.pending = 0b10; - assert_eq!(events.wait(), MISS); - events.state.pending = 0; - events.control.interrupt_epoch = 1; - assert_eq!(events.wait(), MISS); - events.control.observed_interrupt_epoch = 1; - // The count holds at 100. - events.waits.lines_until = 100; - assert_eq!(events.wait(), MISS); - assert_eq!(events.waits.spin, quiet, "no spin"); - events.waits.lines_until = 101; - events.state.exclusive_bytes = 8; - assert_eq!(events.wait(), MISS); - events.state.exclusive_bytes = 0; - events.waits.monitor = 1; - assert_eq!(events.wait(), MISS); - events.waits.monitor = 0; - assert_eq!((events.waits.spin.held, events.waits.spin.missed), (2, 0)); - // A held count: the turns end the spin, none counted. - assert_eq!(events.wait(), MISS); - let spin = events.waits.spin; - assert_eq!((spin.missed, spin.counts, spin.turns), (1, 0, 0)); - // A count at half the TSC's rate: the counts end it. - let mut events = Events::new(1 << 63); - events.open(); - events.waits.waits.readable = 1; - events.waits.lines_until = u64::MAX; - assert_eq!(events.wait(), MISS); - let spin = events.waits.spin; - assert_eq!((spin.completed, spin.missed), (0, 1)); - assert!(spin.counts >= u64::from(WFE_SPIN_COUNTS), "{spin:?}"); - assert_ne!(spin.turns, 0, "{spin:?}"); - } - - /// Another PE's event during the spin completes the WFE, consuming the - /// register; a notification during it ends it. Each runs until the - /// other thread acted during a spin, which a scheduler may delay. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn event_waits_complete_on_an_event_set_during_the_spin() { - use core::sync::atomic::{AtomicU64, Ordering::Relaxed}; - let mut events = Events::new(0); - events.open(); - events.waits.waits.readable = 1; - events.waits.lines_until = u64::MAX; - let completed = (0..100).any(|_| { - let exit = events.wait_while(|events| events.event.store(1, Relaxed)); - events.event.store(0, Relaxed); - exit == NEXT - }); - assert!(completed); - assert_eq!(events.waits.spin.completed, 1); - let missed = events.waits.spin.missed; - let ended = (0..100).any(|_| { - let before = events.waits.spin.missed; - let epoch = &raw const events.control.interrupt_epoch as usize; - assert_eq!( - events.wait_while(move |_| { - // SAFETY: the control's epoch, which the thunk reads. - unsafe { AtomicU64::from_ptr(epoch as *mut u64) }.fetch_add(1, Relaxed); - }), - MISS - ); - let observed = events.control.interrupt_epoch; - events.control.observed_interrupt_epoch = observed; - events.waits.spin.missed == before + 1 && events.waits.spin.turns != 0 - }); - assert!(ended); - assert!(events.waits.spin.missed > missed); - } - - /// An energy read scales the ticks of the count since the origin, none - /// before it, and leaves a reading too wide for 64 bits to the engine. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn energy_thunks_scale_the_ticks_since_the_origin() { - use crate::GuestState; - use core::sync::atomic::Ordering::Relaxed; - let mut energy = alloc::boxed::Box::new(Energy { - origin: 40, - scale: 3_000, - frequency: 24, - }); - let mut cell = alloc::boxed::Box::new(Cell { - readable: 1, - value: &mut *energy as *mut Energy as u64, - }); - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let read = energy_thunk(PC, 3, CELL, READER); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &mut *cell as *mut Cell as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], 60 * 3_000 / 24); - energy.origin = 200; - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], 0); - energy.origin = 0; - energy.scale = u64::MAX; - energy.frequency = 50; - assert_eq!(run(&read.code, &mut state), MISS); - } - - /// A cycle counter read takes an open cell's value; with the cell - /// closed but the read plain it computes the count as - /// [`CycleCounter::at`] does, carrying the remainder and wrapping to the - /// mask, and opens the cell on it; anything else, and a quotient too - /// wide, exits with Xt untouched. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn cycle_counter_thunks_compute_the_count_where_only_the_value_went_stale() { - use crate::GuestState; - use core::sync::atomic::Ordering::Relaxed; - #[repr(C)] - struct Cells { - cell: Cell, - plain: Cell, - cycles: CycleCounter, - } - const PLAIN: Place = Place::new(Anchor::Mirrors, size_of::()); - const CYCLES: Place = Place::new(Anchor::Mirrors, 2 * size_of::()); - let mut cells = alloc::boxed::Box::new(Cells { - cell: Cell::default(), - plain: Cell::default(), - cycles: CycleCounter { - open: 1, - counter: 1_000, - synced: 90, - remainder: 2, - clock: 7, - frequency: 3, - mask: u64::MAX >> 16, - overflow: 0, - clocks: [0; crate::x86_64::transition::STATES], - }, - }); - let published = alloc::boxed::Box::new(CountState::default()); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let read = cycle_counter_thunk(PC, 3, CELL, PLAIN, CYCLES, READER); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &mut *cells as *mut Cells as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - // The reader never reads below its last count: each read starts - // afresh at `now`. - let reader = &mut *count as *mut Count; - let run_at = |_: &mut Cells, now: u64, state: &mut GuestState| { - published.offset.store(now, Relaxed); - // SAFETY: the test's reader, which no thunk runs over meanwhile. - unsafe { (*reader).last = 0 }; - run(&read.code, state) - }; - // Closed and not plain: the engine. - state.x[3] = 0xdead; - assert_eq!(run_at(&mut cells, 100, &mut state), MISS); - assert_eq!(state.x[3], 0xdead); - // Plain: (10 * 7 + 2) / 3 = 24 cycles past 1000, the cell opens. - cells.plain.readable = 1; - assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); - assert_eq!(state.x[3], 1_024); - assert_eq!(cells.cycles.at(100), Some(1_024)); - assert_eq!( - cells.cell, - Cell { - readable: 1, - value: 1_024 - } - ); - // Open: its value until the cell closes again. - assert_eq!(run_at(&mut cells, 400, &mut state), NEXT); - assert_eq!(state.x[3], 1_024); - cells.cell.readable = 0; - for now in [0, 89, 90, 91, 92, 400, 1 << 40] { - assert_eq!(run_at(&mut cells, now, &mut state), NEXT, "{now}"); - assert_eq!(Some(state.x[3]), cells.cycles.at(now), "{now}"); - cells.cell.readable = 0; - } - // Wrapped to the counter's width. - cells.cycles.counter = u64::MAX >> 16; - assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); - assert_eq!(state.x[3], 23); - cells.cell.readable = 0; - // Not counting: the count as it stands. - cells.cycles.clock = 0; - assert_eq!(run_at(&mut cells, 1 << 40, &mut state), NEXT); - assert_eq!(state.x[3], u64::MAX >> 16); - cells.cell.readable = 0; - // Too wide for one division, and the monitor's view closed. - cells.cycles.clock = u64::MAX; - state.x[3] = 0xdead; - assert_eq!(run_at(&mut cells, u64::MAX, &mut state), MISS); - assert_eq!(cells.cycles.at(u64::MAX), None); - cells.cycles.clock = 7; - cells.cycles.open = 0; - assert_eq!(run_at(&mut cells, 100, &mut state), MISS); - assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); - cells.cycles.open = 1; - cells.cycles.counter = 1_000; - // With the PMI armed, a count below the overflow bit completes and - // one that reaches it exits for the engine to raise the PMI: past - // 1000, (448 * 7 + 2) / 3 = 1046 cycles at 538 stay below bit 11, - // 1048 at 539 reach it; so does the last count below the width's - // top bit, 21 cycles at 99, and not the first at it, 24 at 100. - cells.cycles.overflow = 1 << 11; - cells.cell.readable = 0; - assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); - assert_eq!(state.x[3], 1_024); - cells.cell.readable = 0; - assert_eq!(run_at(&mut cells, 538, &mut state), NEXT); - assert_eq!(state.x[3], 2_046); - assert_eq!(cells.cycles.at(538), Some(2_046)); - cells.cell.readable = 0; - state.x[3] = 0xdead; - assert_eq!(cells.cycles.at(539), None); - assert_eq!(run_at(&mut cells, 539, &mut state), MISS); - assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); - cells.cycles.overflow = 1 << 47; - cells.cycles.counter = (1 << 47) - 24; - assert_eq!(run_at(&mut cells, 99, &mut state), NEXT); - assert_eq!(state.x[3], (1 << 47) - 3); - cells.cell.readable = 0; - state.x[3] = 0xdead; - assert_eq!(run_at(&mut cells, 100, &mut state), MISS); - cells.cycles.overflow = 0; - // XZR discards it but the cell still opens. - cells.cycles.open = 1; - cells.cycles.counter = 1_000; - let discard = cycle_counter_thunk(PC, 31, CELL, PLAIN, CYCLES, READER); - published.offset.store(100, Relaxed); - // SAFETY: as above. - unsafe { (*reader).last = 0 }; - assert_eq!(run(&discard.code, &mut state), NEXT); - assert_eq!((state.x[3], cells.cell.value), (0xdead, 1_024)); - } - - /// An instruction counter read takes an open cell's value; with the - /// cell closed but the read plain it adds the chain's retired count and - /// the instructions before it in its block to the base, as - /// [`InstructionCounter::at`] does, wrapping to the mask, and opens the - /// cell on it; anything else exits with Xt untouched. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn instruction_counter_thunks_add_what_native_code_retired() { - use crate::GuestState; - use crate::x86_64::chain::Account; - #[repr(C)] - struct Cells { - cell: Cell, - plain: Cell, - counter: InstructionCounter, - } - const PLAIN: Place = Place::new(Anchor::Mirrors, size_of::()); - const COUNTER: Place = Place::new(Anchor::Mirrors, 2 * size_of::()); - let mut cells = alloc::boxed::Box::new(Cells { - cell: Cell::default(), - plain: Cell::default(), - counter: InstructionCounter { - open: 1, - base: 1_000, - step: u64::MAX, - mask: u64::MAX >> 16, - overflow: 0, - steps: [0; crate::x86_64::transition::STATES], - }, - }); - let read = instruction_counter_thunk(PC, 3, CELL, PLAIN, COUNTER, 5).unwrap(); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &mut *cells as *mut Cells as u64; - // A budget beside the instructions, which the read leaves out. - state.account = Account::new(3).with_retired(40).0; - let set_retired = |state: &mut GuestState, retired: u64| { - state.account = Account(state.account).with_retired(retired).0; - }; - // Closed and not plain: the engine. - state.x[3] = 0xdead; - assert_eq!(run(&read.code, &mut state), MISS); - assert_eq!(state.x[3], 0xdead); - // Plain: 40 chained and 5 before it past 1000, the cell opens. - cells.plain.readable = 1; - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], 1_045); - assert_eq!(cells.counter.at(45), Some(1_045)); - assert_eq!( - cells.cell, - Cell { - readable: 1, - value: 1_045 - } - ); - // Open: its value until the cell closes again. - set_retired(&mut state, 400); - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], 1_045); - cells.cell.readable = 0; - for retired in [0, 1, 400, (1 << 47) - 1] { - set_retired(&mut state, retired); - assert_eq!(run(&read.code, &mut state), NEXT, "{retired}"); - assert_eq!(Some(state.x[3]), cells.counter.at(retired + 5), "{retired}"); - cells.cell.readable = 0; - } - // Wrapped to the counter's width. - set_retired(&mut state, 0); - cells.counter.base = u64::MAX >> 16; - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], 4); - cells.cell.readable = 0; - // Not counting: the count as it stands. - cells.counter.step = 0; - set_retired(&mut state, (1 << 47) - 1); - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], u64::MAX >> 16); - cells.cell.readable = 0; - // The monitor's view closed. - cells.counter.open = 0; - state.x[3] = 0xdead; - assert_eq!(run(&read.code, &mut state), MISS); - assert_eq!(cells.counter.at(0), None); - assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); - // XZR discards it but the cell still opens; the first instruction - // of its block adds no immediate. - cells.counter = InstructionCounter { - open: 1, - base: 1_000, - step: u64::MAX, - mask: u64::MAX, - overflow: 0, - steps: [0; crate::x86_64::transition::STATES], - }; - set_retired(&mut state, 7); - let discard = instruction_counter_thunk(PC, 31, CELL, PLAIN, COUNTER, 0).unwrap(); - assert!(discard.code.len() < read.code.len()); - assert_eq!(run(&discard.code, &mut state), NEXT); - assert_eq!((state.x[3], cells.cell.value), (0xdead, 1_007)); - // With the PMI armed on the top bit, the last count below it - // completes and the first at it exits for the engine to raise the - // PMI, Xt and the cell untouched. - cells.counter.overflow = 1 << 63; - cells.counter.base = (1 << 63) - 13; - cells.cell.readable = 0; - set_retired(&mut state, 7); - assert_eq!(run(&read.code, &mut state), NEXT); - assert_eq!(state.x[3], (1 << 63) - 1); - assert_eq!(cells.counter.at(12), Some((1 << 63) - 1)); - cells.cell.readable = 0; - set_retired(&mut state, 8); - state.x[3] = 0xdead; - assert_eq!(cells.counter.at(13), None); - assert_eq!(run(&read.code, &mut state), MISS); - assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); - } - - /// ISR_EL1 reads the waiting I and F masks as bits 7 and 6 while the - /// cell is open, the epoch is the cell's and the count is below its - /// deadline, and leaves every other case, Xt untouched, to the engine. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn interrupt_status_thunks_read_the_waiting_lines_while_nothing_changed() { - use crate::GuestState; - use core::sync::atomic::Ordering::Relaxed; - const EPOCH: Place = Place::new(Anchor::Control, 0); - let mut cell = alloc::boxed::Box::new(Cell::default()); - let mut epoch = alloc::boxed::Box::new(7u64); - let published = alloc::boxed::Box::new(CountState::default()); - published.offset.store(100, Relaxed); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = &mut *cell as *mut Cell as u64; - state.anchors[Anchor::Control] = &mut *epoch as *mut u64 as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - let read = interrupt_status_thunk(PC, 5, CELL, EPOCH, READER).code; - let mut expect = |cell_now: Cell, pending: u32, exit: Exit, x5: u64| { - *cell = cell_now; - state.pending = pending; - state.x[5] = 0xdead; - assert_eq!(run(&read, &mut state), exit, "{cell_now:?} {pending:#x}"); - assert_eq!(state.x[5], x5, "{cell_now:?} {pending:#x}"); - }; - let open = |deadline: u64, value: u64| Cell { - readable: deadline, - value, - }; - // No deadline: no count is read, every mask combination reads. - for (pending, isr) in [(0, 0), (0b01, 0x40), (0b10, 0x80), (0b11, 0xc0)] { - expect(open(u64::MAX, 7), pending, NEXT, isr); - } - // The count (100: `per_tsc` is 0) is below 101, not below 100. - expect(open(101, 7), 0b10, NEXT, 0x80); - expect(open(100, 7), 0b10, MISS, 0xdead); - // Closed, or a line changed since: the engine reads. - expect(Cell::default(), 0b01, MISS, 0xdead); - expect(open(u64::MAX, 6), 0b01, MISS, 0xdead); - *epoch = 6; - expect(open(u64::MAX, 6), 0b01, NEXT, 0x40); - // XZR reads nothing. - let discard = interrupt_status_thunk(PC, 31, CELL, EPOCH, READER).code; - let before = state.x; - assert_eq!(run(&discard, &mut state), NEXT); - assert_eq!(state.x, before); - } - - /// Timer thunks run on the host against a count the test moves: writes - /// that keep the output low complete into storage, one that arms a - /// compare before `lines_until` pulling it and an open ISR_EL1 cell's - /// deadline down to the compare; every other write exits with storage - /// as it was, and CTL reads give ENABLE and IMASK as stored with - /// ISTATUS from the count. - #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] - #[test] - fn timer_thunks_complete_only_writes_that_raise_nothing_before_the_engine_looks() { - use crate::GuestState; - use core::mem::offset_of; - use core::sync::atomic::Ordering::Relaxed; - #[repr(C)] - #[derive(Default)] - struct Timer { - compare: Cell, - control: Cell, - cval: u64, - ctl: u64, - lines_until: u64, - status: Cell, - quiet: Cell, - } - const ENABLE: u64 = 1; - const IMASK: u64 = 2; - const ISTATUS: u64 = 4; - let place = |offset: usize| Place::new(Anchor::Mirrors, offset); - let places = TimerPlaces { - compare: place(offset_of!(Timer, compare)), - control: place(offset_of!(Timer, control)), - lines_until: place(offset_of!(Timer, lines_until)), - interrupt_status: place(offset_of!(Timer, status)), - count: READER, - quiet: place(offset_of!(Timer, quiet)), - }; - let mut timer = alloc::boxed::Box::new(Timer::default()); - let base = &mut *timer as *mut Timer; - let published = alloc::boxed::Box::new(CountState::default()); - published.ceiling.store(u64::MAX, Relaxed); - let mut count = alloc::boxed::Box::new(Count { - state: &*published as *const CountState as u64, - ..Count::default() - }); - let mut state = GuestState::default(); - state.anchors[Anchor::Mirrors] = base as u64; - state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; - let (cval_at, ctl_at) = ( - base as u64 + offset_of!(Timer, cval) as u64, - base as u64 + offset_of!(Timer, ctl) as u64, - ); - // SAFETY: `base` points into the live box; every access happens - // between thunk runs. - let data = |f: &mut dyn FnMut(&mut Timer)| unsafe { f(&mut *base) }; - let open = |d: &mut Timer| { - d.compare = Cell { - readable: 1, - value: cval_at, - }; - d.control = Cell { - readable: 1, - value: ctl_at, - }; - }; - data(&mut |d| open(d)); - let keep = Written { - keep: ENABLE | IMASK | ISTATUS, - set: 0, - }; - let (value, compare) = ( - timer_thunk(PC, 5, TimerAccess::WriteValue, places).code, - timer_thunk(PC, 5, TimerAccess::WriteCompare, places).code, - ); - let control = timer_thunk(PC, 5, TimerAccess::WriteControl(keep), places).code; - // The frame's waiting interrupts before each run and after it. - let pending = core::cell::Cell::new(0u32); - // count, lines_until, (cval, ctl) before, the thunk, Xt, the exit - // and (cval, ctl) after. - let mut expect = |now: u64, - until: u64, - before: (u64, u64), - code: &[u8], - xt: u64, - exit: Exit, - after: (u64, u64)| { - published.offset.store(now, Relaxed); - data(&mut |d| { - (d.cval, d.ctl) = before; - d.lines_until = until; - }); - state.x[5] = xt; - state.pending = pending.get(); - let ran = run(code, &mut state); - pending.set(state.pending); - data(&mut |d| { - assert_eq!( - (ran.pc, d.cval, d.ctl), - (exit.pc, after.0, after.1), - "now {now} until {until} before {before:?} xt {xt:#x}" - ); - }); - assert_eq!(state.x[5], xt, "a write leaves Xt"); - }; - let armed = (200, ENABLE); - // TVAL: count plus the sign-extended low word. 180 is past 150. - expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); - expect( - 100, - 150, - armed, - &value, - 0xdead_0000_0000_0050, - NEXT, - (180, ENABLE), - ); - // Earlier than the engine looks again: completes and pulls its - // deadlines down to the compare, an open ISR_EL1 cell's only. - for (status, pulled) in [(150, 130), (0, 0), (120, 120)] { - data(&mut |d| d.status.readable = status); - expect(100, 150, armed, &value, 30, NEXT, (130, ENABLE)); - data(&mut |d| { - assert_eq!((d.lines_until, d.status.readable), (130, pulled)); - }); - } - data(&mut |d| d.status.readable = 0); - // A later one leaves them. - expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); - data(&mut |d| assert_eq!(d.lines_until, 150)); - // Due at once, or already past: exit. - expect(100, 150, armed, &value, 0, MISS, armed); - expect(100, 150, armed, &value, 0xffff_fff6, MISS, armed); - // CVAL: at lines_until itself completes. - expect(100, 150, armed, &compare, 150, NEXT, (150, ENABLE)); - expect(100, 150, armed, &compare, 149, NEXT, (149, ENABLE)); - data(&mut |d| assert_eq!(d.lines_until, 149)); - // The output is high (armed and past its compare): with `quiet` - // closed every write exits. - expect(100, 150, (90, ENABLE), &compare, 500, MISS, (90, ENABLE)); - expect(100, 150, (90, ENABLE), &control, 0, MISS, (90, ENABLE)); - // With it open, a write that lowers the line completes and leaves - // the FIQ it raised no longer waiting; one that keeps it high exits - // with the FIQ still waiting. - data(&mut |d| { - d.quiet = Cell { - readable: 1, - value: 0b10, - } - }); - for (code, xt, after) in [ - (&compare, 500, (500, ENABLE)), - (&value, 30, (130, ENABLE)), - (&control, 0, (90, 0)), - (&control, ENABLE | IMASK, (90, ENABLE | IMASK)), - (&compare, 95, (90, ENABLE)), - (&control, ENABLE, (90, ENABLE)), - ] { - pending.set(0b11); - let lowers = after != (90, ENABLE); - let exit = if lowers { NEXT } else { MISS }; - expect(100, 150, (90, ENABLE), code, xt, exit, after); - assert_eq!(pending.get(), if lowers { 0b10 } else { 0b11 }); - } - data(&mut |d| d.quiet = Cell::default()); - pending.set(0); - // Masked or disabled, any compare completes and arms nothing. - expect( - 100, - 150, - (90, ENABLE | IMASK), - &compare, - 120, - NEXT, - (120, ENABLE | IMASK), - ); - expect(100, 150, (90, 0), &value, 5, NEXT, (105, 0)); - // CTL: disabling or masking completes; ISTATUS and RES0 bits as the - // register takes them. - expect( - 100, - 150, - armed, - &control, - !ENABLE, - NEXT, - (200, IMASK | ISTATUS), - ); - expect(100, 150, armed, &control, 0, NEXT, (200, 0)); - // Unmasking an expired compare raises the line: exit. - expect( - 100, - 150, - (90, ENABLE | IMASK), - &control, - ENABLE, - MISS, - (90, ENABLE | IMASK), - ); - // Enabling arms the stored compare, before lines_until pulling it. - expect(100, 150, (120, 0), &control, ENABLE, NEXT, (120, ENABLE)); - data(&mut |d| assert_eq!(d.lines_until, 120)); - expect(100, 150, (160, 0), &control, ENABLE, NEXT, (160, ENABLE)); - // No count named (0): every write exits; none (MAX): a write that - // arms a compare names it. - expect(100, 0, armed, &control, 0, MISS, armed); - expect(100, u64::MAX, armed, &control, 0, NEXT, (200, 0)); - expect( - 100, - u64::MAX, - armed, - &value, - 1 << 20, - NEXT, - (100 + (1 << 20), ENABLE), - ); - data(&mut |d| assert_eq!(d.lines_until, 100 + (1 << 20))); - expect( - 100, - u64::MAX, - (200, 0), - &value, - 1 << 20, - NEXT, - (100 + (1 << 20), 0), - ); - // Closed cells: the engine's. - for closed in [offset_of!(Timer, compare), offset_of!(Timer, control)] { - data(&mut |d| { - open(d); - // SAFETY: `closed` is the offset of a Cell field of `d`. - unsafe { (*((d as *mut Timer as *mut u8).add(closed) as *mut Cell)).readable = 0 }; - }); - expect(100, 150, armed, &control, 0, MISS, armed); - } - data(&mut |d| open(d)); - // The count passes the new compare right after the thunk read it: - // the native ISR read the engine left open until lines_until (150) - // exits there, before the compare (180) the line now rises at. - expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); - published.offset.store(180, Relaxed); - let mut status = Cell { - readable: 150, - value: 0, - }; - let mut epoch = 0u64; - let mut isr_state = GuestState::default(); - isr_state.anchors[Anchor::Mirrors] = &mut status as *mut Cell as u64; - isr_state.anchors[Anchor::Control] = &mut epoch as *mut u64 as u64; - isr_state.anchors[Anchor::Count] = state.anchors[Anchor::Count]; - let isr = interrupt_status_thunk(PC, 5, CELL, Place::new(Anchor::Control, 0), READER); - assert_eq!(run(&isr.code, &mut isr_state), MISS); - // CTL reads: all eight ENABLE, IMASK and count cases, and a stored - // ISTATUS bit is never what the read gives. - let read = timer_thunk(PC, 7, TimerAccess::ReadControl, places).code; - let mut now = 180; - for ctl in 0..8u64 { - for past in [false, true] { - now += 10; - published.offset.store(now, Relaxed); - let cval = if past { now } else { now + 1 }; - data(&mut |d| (d.cval, d.ctl) = (cval, ctl)); - state.x[7] = 0xdead; - assert_eq!(run(&read, &mut state), NEXT); - let status = if ctl & ENABLE != 0 && past { - ISTATUS - } else { - 0 - }; - assert_eq!(state.x[7], ctl & !ISTATUS | status, "ctl {ctl} past {past}"); - data(&mut |d| assert_eq!((d.cval, d.ctl), (cval, ctl))); - } - } - let discard = timer_thunk(PC, 31, TimerAccess::ReadControl, places).code; - let before = state.x; - assert_eq!(run(&discard, &mut state), NEXT); - assert_eq!(state.x, before); - } -} +//! Native completion of MRS reads of a System register whose value the +//! system-mode engine keeps in a [`Cell`] at a fixed host address. +//! +//! The MRS ends its block with a System exit. A [`thunk`] the engine +//! installs over that exit completes it natively while the cell's +//! `readable` word is nonzero: it writes `value` to Xt (nothing for XZR) and +//! leaves through a direct exit to the next instruction, which the engine +//! may chain like a block's. Otherwise it takes the original exit. +//! +//! The engine sets `readable` only while the read at the current EL is the +//! plain register read of its AARCHMRS accessor, neither UNDEFINED nor +//! trapped nor redirected, with `value` the register's contents, and clears +//! it whenever a System register write, an exception, an exception return +//! or a PE switch may change either. Thunks clobber only RAX and flags. +//! +//! A [`stored_thunk`] reads the live register instead, through the address +//! the cell's `value` holds, so that what an exception or an MSR stores needs +//! no System exit to reach it; a [`frame_thunk`] reads a field of the frame. +//! +//! A [`stored_write_thunk`] completes MSR of a register the same way: it +//! writes through that address, keeping the register's fixed bits, and a +//! [`frame_write_thunk`] writes a field of the frame. It also clobbers RCX +//! and RDX. +//! +//! A [`pan_read_thunk`] completes MRS PAN from the frame, where a +//! [`pan_thunk`] leaves it. +//! +//! A [`key_write_thunk`] completes MSR of half of a PAC key, closing the keys +//! to PAC thunks when it changes one. +//! +//! A [`checked_write_thunk`] completes MSR of a register that takes any value +//! without the bits it refuses, which the engine decides. +//! +//! A [`stack_select_thunk`] completes MSR SPSel: the frame's SP moves to the +//! stack it leaves and takes the one it selects. The selection is a word of +//! the engine's while native code runs, which reads of SP_EL0 consult +//! ([`selected_stored_thunk`], [`selected_write_thunk`]): they are plain only +//! with SP_ELx selected, whatever their cell says. +//! +//! A [`mask_thunk`] completes a write of PSTATE's D, A, I and F masks in the +//! frame, which the engine takes back when native code returns, unless the +//! write changes D, which debug state follows, or clears the mask of an +//! interrupt waiting since native code was entered ([`GuestState::pending`]): +//! one that comes later stops native code as ever. It also clobbers RCX and +//! RDX, as a [`mask_read_thunk`] reads the masks from the frame. +//! +//! A [`code_page_thunk`] completes IC IVAU of the page the cell's `value` +//! names, which a kernel cleans line by line: the first line's invalidation +//! was the whole page's. It also clobbers RCX. +//! +//! A [`count_thunk`] reads a count instead: the system count a clock +//! publishes in a [`CountState`] at the host's TSC, through the reader's +//! [`Count`], less the cell's `value`. It also clobbers RCX and RDX, which +//! are dead at every block exit (the direct exit returns in RAX and RDX, +//! and chaining uses RCX). An [`energy_thunk`] scales the count it reads +//! into an energy accumulator's reading. +//! +//! A [`send_event_thunk`] sets the event register byte the cell's `value` +//! names, and an [`event_wait_thunk`] consumes a set one, spinning briefly +//! for one another PE sets; both clobber RCX and RDX. +//! +//! A [`cycle_counter_thunk`] computes a cycle counter at the count where +//! its cell went stale but the read stays plain, and opens the cell on it; +//! an [`instruction_counter_thunk`] does the same for a retired-instruction +//! counter from the instructions native code retired before it. +//! +//! An [`interrupt_status_thunk`] reads ISR_EL1 from the interrupts waiting +//! at entry while no line changed since; it clobbers RCX and RDX. +use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, Rm, ShiftOp, Size, Unary}; +use super::pointer::Thunk; +use crate::{GuestAddress, GuestState, Place, aarch64::Register, block::ExitKind}; +use alloc::vec::Vec; +use core::sync::atomic::AtomicU64; + +/// What a thunk reads. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Cell { + /// Nonzero while native code may complete the read with `value`. + pub readable: u64, + pub value: u64, +} + +const VALUE: i8 = core::mem::offset_of!(Cell, value) as i8; +/// Bits of an address within the page a [`code_page_thunk`] compares. +const CODE_PAGE_BITS: u8 = 12; +const _: () = assert!(core::mem::offset_of!(Cell, readable) == 0); + +/// A clock's count as every reader computes it: at host count `host` +/// (`((tsc - base) * per_tsc) >> 64`), `min(host + offset, ceiling)`, with +/// wrapping addition. A writer makes `sequence` odd, changes `offset` and +/// `ceiling` and makes it even again; a reader takes both from one even +/// sequence and samples the TSC before that sequence ends, so readers on +/// different cores see one count (a seqlock). +#[repr(C, align(64))] +#[derive(Debug, Default)] +pub struct CountState { + pub sequence: AtomicU64, + pub offset: AtomicU64, + pub ceiling: AtomicU64, +} + +const SEQUENCE: i8 = core::mem::offset_of!(CountState, sequence) as i8; +const STATE_OFFSET: i8 = core::mem::offset_of!(CountState, offset) as i8; +const CEILING: i8 = core::mem::offset_of!(CountState, ceiling) as i8; + +/// One reader of a [`CountState`] at `state`: its TSC scale, and `last`, +/// the count it last read, below which it never reads, so its own count +/// never runs backwards. `seen_*` hold the read in progress. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Count { + pub base: u64, + pub per_tsc: u64, + pub last: u64, + pub state: u64, + pub seen_sequence: u64, + pub seen_offset: u64, + pub seen_ceiling: u64, +} + +const BASE: i8 = core::mem::offset_of!(Count, base) as i8; +const PER_TSC: i8 = core::mem::offset_of!(Count, per_tsc) as i8; +const LAST: i8 = core::mem::offset_of!(Count, last) as i8; +const STATE: i8 = core::mem::offset_of!(Count, state) as i8; +const SEEN_SEQUENCE: i8 = core::mem::offset_of!(Count, seen_sequence) as i8; +const SEEN_OFFSET: i8 = core::mem::offset_of!(Count, seen_offset) as i8; +const SEEN_CEILING: i8 = core::mem::offset_of!(Count, seen_ceiling) as i8; + +/// Xt's storage in [`pinned`](super::pinned) code. +fn register(rt: u8) -> Rm { + Asm::pinned(&mut Vec::new()) + .guest(Register::X(rt)) + .expect("X0..X30") +} + +/// The thunk completing `MRS Xt, ` at `pc` from the cell at +/// `cell`, else exiting at `pc` for the engine. +pub fn thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + if rt != 31 { + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + } + finish(code, miss, pc) +} + +/// The thunk completing `MRS Xt, ` at `pc` from the storage the +/// `value` of the cell at `cell` points at, else exiting at `pc`. +pub fn stored_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rax, 0)); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + finish(code, miss, pc) +} + +/// [`stored_thunk`] of a read that is plain only while the word at `select` +/// is nonzero. +pub fn selected_stored_thunk(pc: GuestAddress, rt: u8, cell: Place, select: Place) -> Thunk { + let (mut code, miss) = open(cell); + let unselected = selected(&mut code, select); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.mov_load(Size::Qword, Gpr::Rax, Mem::base(Gpr::Rax, 0)); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + finish_unless(code, [miss, unselected], pc) +} + +/// Branch away while the word at `select` is zero. +fn selected(code: &mut Vec, select: Place) -> Patch { + let mut asm = Asm::new(code); + asm.place(Gpr::Rcx, select); + asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rcx, 0), 0); + asm.jcc(Cond::E) +} + +/// The thunk completing `MRS Xt, ` at `pc` from the 32-bit frame +/// field at `offset` while the cell at `cell` is open, else exiting at `pc`. +pub fn frame_thunk(pc: GuestAddress, rt: u8, cell: Place, offset: usize) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + let field = Mem::base_disp32(Gpr::Rdi, offset as i32); + asm.mov_load(Size::Dword, Gpr::Rax, field); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + finish(code, miss, pc) +} + +/// The thunk completing `MRS Xt, PAN` at `pc` while the cell at `cell` is +/// open, else exiting at `pc`. +pub fn pan_read_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { + /// PAN's bit of the register. + const PAN_SHIFT: u8 = 22; + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + let field = frame_field(core::mem::offset_of!(GuestState, pan)); + asm.mov_load(Size::Qword, Gpr::Rax, field); + asm.shift_imm(ShiftOp::Shl, Size::Qword, Gpr::Rax, PAN_SHIFT); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + finish(code, miss, pc) +} + +/// The bits of a register a write takes and those it always holds, as +/// [`Self::apply`] gives it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Written { + pub keep: u64, + pub set: u64, +} + +impl Written { + /// Leave `Xt`'s value as the register stores it in RAX. + pub(crate) fn apply(self, asm: &mut Asm<'_>, rt: u8) { + if rt == 31 { + asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); + } else { + asm.mov_load(Size::Qword, Gpr::Rax, register(rt)); + } + if self.keep != u64::MAX { + asm.mov_imm64(Gpr::Rdx, self.keep); + asm.alu(Alu::And, Size::Qword, Gpr::Rax, Gpr::Rdx); + } + if self.set != 0 { + asm.mov_imm64(Gpr::Rdx, self.set); + asm.alu(Alu::Or, Size::Qword, Gpr::Rax, Gpr::Rdx); + } + } +} + +/// The thunk completing `MSR , Xt` at `pc` through the storage the +/// `value` of the cell at `cell` points at, else exiting at `pc`. +pub fn stored_write_thunk(pc: GuestAddress, rt: u8, cell: Place, written: Written) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + written.apply(&mut asm, rt); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + finish(code, miss, pc) +} + +/// The thunk completing `MSR , Xt` at `pc` when the value, as the +/// register takes it, equals what the storage the `value` of the cell at +/// `cell` points at holds already: such a write changes nothing. Any other +/// value, or a closed cell, exits at `pc`. +pub fn unchanged_write_thunk(pc: GuestAddress, rt: u8, cell: Place, written: Written) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + written.apply(&mut asm, rt); + asm.alu_load(Alu::Cmp, Size::Qword, Gpr::Rax, Mem::base(Gpr::Rcx, 0)); + let changed = asm.jcc(Cond::Ne); + finish_unless(code, [miss, changed], pc) +} + +/// [`stored_write_thunk`] of a register that keeps what it is written, unless +/// the value has one of the bits `refused`. +pub fn checked_write_thunk(pc: GuestAddress, rt: u8, cell: Place, refused: u64) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + let all = Written { + keep: u64::MAX, + set: 0, + }; + all.apply(&mut asm, rt); + if rt == 31 || refused == 0 { + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + return finish(code, miss, pc); + } + asm.mov_imm64(Gpr::Rdx, refused); + asm.test(Size::Qword, Gpr::Rax, Gpr::Rdx); + let unplain = asm.jcc(Cond::Ne); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + finish_unless(code, [miss, unplain], pc) +} + +/// One thread switch a [`thread_switch_thunk`] completed: the thread +/// pointer it replaced and the one it wrote, the frame pointer (X29) and +/// link register (X30) then, and the MSR's PC. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Switch { + pub previous: u64, + pub next: u64, + pub frame: u64, + pub link: u64, + pub pc: u64, +} + +/// The thread switches native code completed since the engine last took +/// them, in order: `len` of `entries`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SwitchLog { + pub len: u64, + pub entries: [Switch; SWITCHES], +} + +/// The switches a [`SwitchLog`] holds; a thunk finding it full exits. +pub const SWITCHES: usize = 8; + +/// Where a [`thread_switch_thunk`] finds the register's read cells and the +/// engine's [`SwitchLog`]: `reads` is the read cell of the first of `banks` +/// banks, each `stride` bytes after the one before. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ThreadSwitch { + pub reads: Place, + pub stride: usize, + pub banks: usize, + pub log: Place, +} + +/// Leave Xt's value in RAX (0 for XZR). +fn load_x(asm: &mut Asm<'_>, rt: u8) { + if rt == 31 { + asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); + } else { + asm.mov_load(Size::Qword, Gpr::Rax, register(rt)); + } +} + +/// The thunk completing `MSR , Xt` at `pc` through the +/// storage the `value` of the cell at `cell` points at, for a register that +/// keeps what it is written and has read cells of its own in every bank +/// (TPIDR_EL1): every open read cell takes the value, as the engine's +/// write updates them. A value that replaces another is logged in the +/// [`SwitchLog`] for the engine's diagnostics, which see the switch as an +/// engine-path write would show it; with the log full, or the cell closed, +/// it exits at `pc`. It also clobbers RCX and RDX. +pub fn thread_switch_thunk(pc: GuestAddress, rt: u8, cell: Place, places: &ThreadSwitch) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); + load_x(&mut asm, rt); + // The same value changes nothing: no cell, no thread. + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0)); + let same = asm.jcc(Cond::E); + asm.place(Rdx, places.log); + let len = core::mem::offset_of!(SwitchLog, len) as i32; + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, len), SWITCHES as i8); + let full = asm.jcc(Cond::Ae); + asm.mov_load(Qword, Rax, Mem::base(Rdx, len)); + asm.alu_imm8(Alu::Add, Qword, Mem::base(Rdx, len), 1); + asm.imul_imm32(Qword, Rax, Rax, size_of::() as i32); + asm.alu(Alu::Add, Qword, Rdx, Rax); + let entry = |field: usize| { + Mem::base( + Rdx, + (core::mem::offset_of!(SwitchLog, entries) + field) as i32, + ) + }; + asm.mov_load(Qword, Rax, Mem::base(Rcx, 0)); + asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, previous)), Rax); + load_x(&mut asm, 29); + asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, frame)), Rax); + load_x(&mut asm, 30); + asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, link)), Rax); + asm.guest_imm64(Rax, pc); + asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, pc)), Rax); + load_x(&mut asm, rt); + asm.mov_store(Qword, entry(core::mem::offset_of!(Switch, next)), Rax); + asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); + // Every open read cell reads the new value; closed ones keep none. + asm.place(Rdx, places.reads); + for bank in 0..places.banks { + let at = (bank * places.stride) as i32; + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, at), 0); + let closed = asm.jcc8(Cond::E); + asm.mov_store(Qword, Mem::base(Rdx, at + VALUE as i32), Rax); + asm.bind(closed); + } + asm.bind(same); + finish_unless(code, [miss, full], pc) +} + +/// The thunk completing `IC IVAU, Xt` at `pc` of an address in the page the +/// `value` of the cell at `cell` names, else exiting at `pc`. +pub fn code_page_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.alu_load(Alu::Xor, Size::Qword, Gpr::Rcx, register(rt)); + asm.shift_imm(ShiftOp::Shr, Size::Qword, Gpr::Rcx, CODE_PAGE_BITS); + let other = asm.jcc(Cond::Ne); + finish_unless(code, [miss, other], pc) +} + +/// [`stored_write_thunk`] of a write that is plain only while the word at +/// `select` is nonzero. +pub fn selected_write_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + select: Place, + written: Written, +) -> Thunk { + let (mut code, miss) = open(cell); + let unselected = selected(&mut code, select); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + written.apply(&mut asm, rt); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + finish_unless(code, [miss, unselected], pc) +} + +/// The thunk completing `MSR SPSel, #select` at `pc` while the cell at +/// `cell` is open, its `value` the address of the level's SP_ELx. The word +/// at `current` holds the selection and `sp0` is the address of SP_EL0. +pub fn stack_select_thunk( + pc: GuestAddress, + select: bool, + cell: Place, + current: Place, + sp0: Place, +) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let (mut code, miss) = open(cell); + let sp = super::pinned::host(Register::Sp).expect("SP is pinned"); + let mut asm = Asm::new(&mut code); + asm.place(Rcx, current); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rcx, 0), i8::from(select)); + let unchanged = asm.jcc(Cond::E); + asm.mov_imm32(Rdx, u32::from(select)); + asm.mov_store(Qword, Mem::base(Rcx, 0), Rdx); + asm.mov_load(Qword, Rax, Mem::base_disp8(Rax, VALUE)); + asm.place(Rcx, sp0); + let (from, to) = if select { (Rcx, Rax) } else { (Rax, Rcx) }; + asm.mov_store(Qword, Mem::base(from, 0), sp); + asm.mov_load(Qword, sp, Mem::base(to, 0)); + asm.bind(unchanged); + finish(code, miss, pc) +} + +/// [`stored_write_thunk`] of half of a PAC key. A value that changes it +/// writes the storage, zeroes only that key's `tag` word, and sets bit +/// `key_bit` in `dirty` so the service can reopen that key in place without +/// invalidating the others. +pub fn key_write_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + tag: Place, + dirty: Place, + key_bit: u8, +) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + let all = Written { + keep: u64::MAX, + set: 0, + }; + all.apply(&mut asm, rt); + asm.alu_load(Alu::Cmp, Size::Qword, Gpr::Rax, Mem::base(Gpr::Rcx, 0)); + let unchanged = asm.jcc(Cond::E); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + asm.place(Gpr::Rcx, tag); + asm.alu(Alu::Xor, Size::Dword, Gpr::Rax, Gpr::Rax); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + asm.place(Gpr::Rcx, dirty); + asm.alu_imm32(Alu::Or, Size::Qword, Mem::base(Gpr::Rcx, 0), 1 << key_bit); + asm.bind(unchanged); + finish(code, miss, pc) +} + +/// The thunk completing `MSR , Xt` at `pc` in the 32-bit frame +/// field at `offset` while the cell at `cell` is open, else exiting at `pc`. +pub fn frame_write_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + offset: usize, + written: Written, +) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + written.apply(&mut asm, rt); + asm.mov_store(Size::Dword, frame_field(offset), Gpr::Rax); + finish(code, miss, pc) +} + +/// A write of PSTATE's masks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MaskWrite { + /// MSR DAIFSet, #imm. + Set(u8), + /// MSR DAIFClr, #imm. + Clear(u8), + /// MSR DAIF, Xt. + Register(u8), +} + +impl MaskWrite { + /// The write `word` makes, if it is one. + pub fn of(word: u32) -> Option { + let immediate = (word >> 8 & 0xf) as u8; + match word & 0xffff_f0ff { + 0xd503_40df => Some(Self::Set(immediate)), + 0xd503_40ff => Some(Self::Clear(immediate)), + _ if word & !0x1f == 0xd51b_4220 => Some(Self::Register((word & 0x1f) as u8)), + _ => None, + } + } +} + +/// PSTATE.D in [`GuestState::daif`]. +const MASK_D: i8 = 8; +/// DAIF's bit 6, of F, the lowest mask. +const MASK_SHIFT: u8 = 6; + +fn frame_field(offset: usize) -> Mem { + Mem::base_disp32(Gpr::Rdi, offset as i32) +} + +/// The thunk completing `MSR PAN, #pan` at `pc` while the cell at `cell` is +/// open, on a host that keeps PSTATE.PAN in RFLAGS.AC, else exiting at `pc`. +pub fn pan_thunk(pc: GuestAddress, pan: bool, cell: Place) -> Thunk { + const CLAC: [u8; 3] = [0x0f, 0x01, 0xca]; + const STAC: [u8; 3] = [0x0f, 0x01, 0xcb]; + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_imm32(Gpr::Rax, u32::from(pan)); + let field = frame_field(core::mem::offset_of!(GuestState, pan)); + asm.mov_store(Size::Qword, field, Gpr::Rax); + asm.fixed(if pan { &CLAC } else { &STAC }); + finish(code, miss, pc) +} + +/// The thunk completing a DSB at `pc` while the cell at `cell` is open, that +/// is while the engine has no maintenance for it to complete, else exiting +/// at `pc`. +pub fn barrier_thunk(pc: GuestAddress, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + Asm::new(&mut code).mfence(); + finish(code, miss, pc) +} + +/// The thunk completing CLREX at `pc` while the cell at `cell` is open and +/// the word its `value` points at is zero, that is while the PE's local +/// monitor lives in the frame alone: it clears the frame's monitor; else it +/// exits at `pc` for the engine to clear the rest. It also clobbers RCX. +pub fn clear_exclusive_thunk(pc: GuestAddress, cell: Place) -> Thunk { + let (mut code, closed) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rcx, 0), 0); + let held = asm.jcc(Cond::Ne); + let bytes = frame_field(core::mem::offset_of!(GuestState, exclusive_bytes)); + asm.mov_rm_imm32(Size::Dword, bytes, 0); + finish_unless(code, [closed, held], pc) +} + +/// The thunk completing SEVL at `pc` while the cell at `cell` is open: it +/// sets the event register, the byte the cell's `value` points at, else +/// exits at `pc`. It also clobbers RCX and RDX. +pub fn send_event_thunk(pc: GuestAddress, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + asm.mov_load(Size::Qword, Gpr::Rcx, Mem::base_disp8(Gpr::Rax, VALUE)); + asm.mov_imm32(Gpr::Rdx, 1); + asm.mov_store(Size::Byte, Mem::base(Gpr::Rcx, 0), Gpr::Rdx); + finish(code, miss, pc) +} + +/// How long an [`event_wait_thunk`] spins for the event register before it +/// exits: 48 counts of the 24 MHz system count, 2 us. Another PE that sets +/// the register within it saves the waiting PE an exit and a wait in the +/// engine; a spin that misses costs this much host time. +pub const WFE_SPIN_COUNTS: u8 = 48; + +/// The most turns one spin takes whatever the count does: a held count +/// (`CountState::ceiling`) stops it, and nothing may hold a PE. A turn +/// takes far more than 2 us / 1024 on every host, so the count ends a spin +/// first. +const WFE_SPIN_TURNS: i32 = 1024; + +/// What [`event_wait_thunk`]s count of their spins, and the spin in +/// progress, which the engine takes when native code returns. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EventSpin { + /// Spins that found the event register set: the WFE completed. + pub completed: u64, + /// Spins that ended otherwise, and exited. + pub missed: u64, + /// WFEs that could spin but for an exclusive monitor, and exited. + pub held: u64, + /// The system counts spent in spins. + pub counts: u64, + /// The count the spin in progress began at, and its turns left. + pub start: u64, + pub turns: u64, + /// WFEs that found the register clear but an event stream edge since + /// the engine's last sample ([`EventStream`]), and completed. + pub streamed: u64, + /// Consecutive native monitor-spin completions with `exclusive_bytes != 0` + /// since the last non-held WFE or engine exit. + pub held_streak: u64, + /// Native monitor-spin completions with `exclusive_bytes != 0`. + pub held_completed: u64, +} + +/// The event stream an [`event_wait_thunk`] samples: the first system +/// count after the engine's last sample at which an edge sets the event +/// register (`u64::MAX`: none the thunk may take), the edges' period +/// where they come every `period` counts (0: the thunk takes one edge and +/// leaves the next to the engine), and the count the thunk last sampled +/// at, which the engine takes as its own sample when native code returns. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventStream { + pub next: u64, + pub period: u64, + pub sampled: u64, +} + +impl Default for EventStream { + fn default() -> Self { + Self { + next: u64::MAX, + period: 1, + sampled: 0, + } + } +} + +const STREAM_NEXT: i8 = core::mem::offset_of!(EventStream, next) as i8; +const STREAM_PERIOD: i8 = core::mem::offset_of!(EventStream, period) as i8; +const STREAM_SAMPLED: i8 = core::mem::offset_of!(EventStream, sampled) as i8; + +const SPIN_COMPLETED: i8 = core::mem::offset_of!(EventSpin, completed) as i8; +const SPIN_MISSED: i8 = core::mem::offset_of!(EventSpin, missed) as i8; +const SPIN_HELD: i8 = core::mem::offset_of!(EventSpin, held) as i8; +const SPIN_COUNTS: i8 = core::mem::offset_of!(EventSpin, counts) as i8; +const SPIN_START: i8 = core::mem::offset_of!(EventSpin, start) as i8; +const SPIN_TURNS: i8 = core::mem::offset_of!(EventSpin, turns) as i8; +const SPIN_STREAMED: i8 = core::mem::offset_of!(EventSpin, streamed) as i8; +const SPIN_HELD_STREAK: i8 = core::mem::offset_of!(EventSpin, held_streak) as i8; +const SPIN_HELD_COMPLETED: i8 = core::mem::offset_of!(EventSpin, held_completed) as i8; +const WFE_HELD_SPIN_MAX: i32 = 16; +const WFE_HELD_PAUSE_ITERS: u32 = 8; +const INTERRUPT_EPOCH: i8 = + core::mem::offset_of!(super::chain::ChainControl, interrupt_epoch) as i8; +const QUIET: i8 = core::mem::offset_of!(super::chain::ChainControl, quiet) as i8; +const OBSERVED_INTERRUPT_EPOCH: i8 = + core::mem::offset_of!(super::chain::ChainControl, observed_interrupt_epoch) as i8; + +/// Where an [`event_wait_thunk`] finds the event register and what ends its +/// spin: `events` a cell whose `value` is the register's byte; `waits` a +/// cell open where a WFE that finds the register clear waits rather than +/// traps and another PE runs meanwhile to set it; `monitor` the word nonzero +/// while the engine holds an exclusive monitor; the control +/// ([`super::chain::ChainControl`]), whose interrupt epoch moves when +/// anything is posted for the PE; the count before which time alone changes +/// no interrupt line ([`crate::x86_64::transition::Places::lines_until`]), +/// the count reader, the spin's counts and the event stream +/// ([`EventStream`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventWaitPlaces { + pub events: Place, + pub waits: Place, + pub monitor: Place, + pub control: Place, + pub lines_until: Place, + pub count: Place, + pub spin: Place, + pub stream: Place, +} + +/// The thunk completing WFE at `pc` while the `events` cell is open and the +/// event register is set: it clears the register in one exchange, as +/// another PE may set it, and completes. With the register clear, an event +/// stream edge since the engine's last sample sets it as the engine's own +/// sample would (`stream`), and the WFE takes it and completes, recording +/// the count it sampled at and the next edge, before any trap check, as +/// the engine does. With the register clear, where the +/// WFE would wait (`waits` open), it spins for up to [`WFE_SPIN_COUNTS`] +/// for the register and completes as soon as it finds it set. It spins only +/// while nothing else would wake the WFE, all of which the engine's wait +/// sees: no interrupt was waiting at entry ([`GuestState::pending`]), +/// nothing was posted for the PE since the engine last looked (a device +/// line, mail with another PE's SEV, a host call or stop: the interrupt +/// epoch), and time changes no line (the count below `lines_until`), each +/// looked at again every turn. Nor does it spin with an exclusive monitor +/// held, in the frame or the engine, as another PE's store that clears it +/// sends the event without setting this register. Else, and once the spin +/// ends without the register, it exits at `pc` for the engine to wait. An +/// event stream edge within a spin is the engine's to see as it waits: the +/// spin delays it no more than a host would. It also clobbers RCX and RDX. +pub fn event_wait_thunk(pc: GuestAddress, places: EventWaitPlaces) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Byte, Dword, Qword}; + let spin = |offset| Mem::base_disp8(Rcx, offset); + let (mut code, closed) = open(places.events); + let mut asm = Asm::new(&mut code); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.xchg(Byte, Mem::base(Rcx, 0), Rdx); + asm.test(Byte, Rdx, Rdx); + let set = asm.jcc(Cond::Ne); + // An event stream edge since the last sample: next += (k + 1) * period + // for k = (count - next) / period. Without a stream no count is read. + asm.place(Rcx, places.stream); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base_disp8(Rcx, STREAM_NEXT), -1); + let unpublished = asm.jcc(Cond::E); + read_count(&mut asm, places.count); + asm.place(Rcx, places.stream); + asm.mov(Qword, Rax, Rdx); + asm.alu_load(Alu::Sub, Qword, Rax, Mem::base_disp8(Rcx, STREAM_NEXT)); + let no_edge = asm.jcc(Cond::B); + asm.mov_store(Qword, Mem::base_disp8(Rcx, STREAM_SAMPLED), Rdx); + // Without a period, the edge after it is the engine's to find. + asm.alu_imm8(Alu::Cmp, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD), 0); + let periodic = asm.jcc(Cond::Ne); + asm.mov_rm_imm32(Qword, Mem::base_disp8(Rcx, STREAM_NEXT), -1); + let taken = asm.jmp(); + asm.bind(periodic); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.unary(Unary::Div, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD)); + asm.alu_imm8(Alu::Add, Qword, Rax, 1); + asm.unary(Unary::Mul, Qword, Mem::base_disp8(Rcx, STREAM_PERIOD)); + asm.alu(Alu::Add, Qword, Mem::base_disp8(Rcx, STREAM_NEXT), Rax); + asm.bind(taken); + asm.place(Rcx, places.spin); + asm.alu_imm8(Alu::Add, Qword, spin(SPIN_STREAMED), 1); + let streamed = asm.jmp(); + asm.bind(no_edge); + asm.bind(unpublished); + // Whether the WFE may spin. + asm.place(Rax, places.waits); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let traps = asm.jcc(Cond::E); + let pending = frame_field(core::mem::offset_of!(GuestState, pending)); + asm.alu_imm8(Alu::Cmp, Dword, pending, 0); + let interrupt = asm.jcc(Cond::Ne); + let posted = |asm: &mut Asm<'_>| { + asm.place(Rcx, places.control); + asm.mov_load(Qword, Rdx, Mem::base_disp8(Rcx, INTERRUPT_EPOCH)); + asm.alu_load( + Alu::Cmp, + Qword, + Rdx, + Mem::base_disp8(Rcx, OBSERVED_INTERRUPT_EPOCH), + ); + asm.jcc(Cond::Ne) + }; + let notified = posted(&mut asm); + asm.place(Rax, places.monitor); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let monitored = asm.jcc(Cond::Ne); + let bytes = frame_field(core::mem::offset_of!(GuestState, exclusive_bytes)); + asm.alu_imm8(Alu::Cmp, Dword, bytes, 0); + let unframed = asm.jcc(Cond::E); + // GuestState.exclusive_bytes != 0: bounded native monitor-spin with + // PAUSE backoff, exiting to Rust once the streak hits WFE_HELD_SPIN_MAX. + read_count(&mut asm, places.count); + asm.place(Rax, places.lines_until); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + let held_due = asm.jcc(Cond::Ae); + asm.place(Rcx, places.spin); + asm.alu_imm8( + Alu::Cmp, + Qword, + spin(SPIN_HELD_STREAK), + WFE_HELD_SPIN_MAX as i8, + ); + let framed = asm.jcc(Cond::Ae); + asm.alu_imm8(Alu::Add, Qword, spin(SPIN_HELD_STREAK), 1); + asm.alu_imm8(Alu::Add, Qword, spin(SPIN_HELD_COMPLETED), 1); + asm.mov_imm32(Rax, WFE_HELD_PAUSE_ITERS); + let pause_top = asm.len(); + asm.pause(); + asm.alu_imm8(Alu::Sub, Dword, Rax, 1); + let pause_again = asm.jcc8(Cond::Ne); + asm.bind_back(pause_again, pause_top); + let held_notified = posted(&mut asm); + let held_done = asm.jmp(); + asm.bind(unframed); + read_count(&mut asm, places.count); + asm.place(Rax, places.lines_until); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + let due = asm.jcc(Cond::Ae); + asm.place(Rcx, places.spin); + asm.mov_rm_imm32(Qword, spin(SPIN_HELD_STREAK), 0); + asm.mov_store(Qword, spin(SPIN_START), Rdx); + asm.mov_rm_imm32(Qword, spin(SPIN_TURNS), WFE_SPIN_TURNS); + let top = asm.len(); + asm.pause(); + // Read the register shared and exchange it only once set. + asm.place(Rax, places.events); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); + asm.movzx(Dword, Rdx, Byte, Mem::base(Rcx, 0)); + asm.test(Dword, Rdx, Rdx); + let clear = asm.jcc(Cond::E); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.xchg(Byte, Mem::base(Rcx, 0), Rdx); + asm.test(Byte, Rdx, Rdx); + let taken = asm.jcc(Cond::E); + // The counts spent into the spin's total, and the outcome's count. + let spent = |asm: &mut Asm<'_>, outcome: i8| { + read_count(asm, places.count); + asm.place(Rcx, places.spin); + asm.alu_load(Alu::Sub, Qword, Rdx, spin(SPIN_START)); + asm.alu(Alu::Add, Qword, spin(SPIN_COUNTS), Rdx); + asm.alu_imm8(Alu::Add, Qword, spin(outcome), 1); + }; + spent(&mut asm, SPIN_COMPLETED); + let found = asm.jmp(); + asm.bind(clear); + asm.bind(taken); + let woken = posted(&mut asm); + asm.place(Rcx, places.spin); + asm.alu_imm8(Alu::Sub, Qword, spin(SPIN_TURNS), 1); + let turns = asm.jcc(Cond::E); + read_count(&mut asm, places.count); + asm.place(Rax, places.lines_until); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + let lines = asm.jcc(Cond::Ae); + asm.place(Rcx, places.spin); + asm.alu_load(Alu::Sub, Qword, Rdx, spin(SPIN_START)); + asm.alu_imm8(Alu::Cmp, Qword, Rdx, WFE_SPIN_COUNTS as i8); + let again = asm.jcc(Cond::B); + asm.bind_back(again, top); + for end in [woken, turns, lines] { + asm.bind(end); + } + spent(&mut asm, SPIN_MISSED); + let missed = asm.jmp(); + asm.bind(framed); + asm.bind(monitored); + asm.place(Rcx, places.spin); + asm.alu_imm8(Alu::Add, Qword, spin(SPIN_HELD), 1); + let held = asm.jmp(); + asm.bind(set); + asm.bind(found); + asm.bind(streamed); + asm.bind(held_done); + finish_unless( + code, + [ + closed, + traps, + interrupt, + notified, + held_due, + held_notified, + due, + missed, + held, + ], + pc, + ) +} + +/// A PE's view of the board's frozen fast-IPI table (the engine's +/// `fast_ipi::Table`) for [`fast_ipi_request_thunk`] and +/// [`fast_ipi_status_thunk`]: the table's first entry, its clusters and +/// CPUs per cluster, this PE's own cluster, number and IPI_SR address, the +/// PEs a request found halted (bit `pe`), which the engine wakes when +/// native code returns, and the entry of the request in progress. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FastIpi { + pub base: u64, + pub clusters: u64, + pub cpus: u64, + pub cluster: u64, + pub pe: u64, + pub status: u64, + pub wakes: u64, + pub target: u64, +} + +/// The bytes of one entry of the table [`FastIpi::base`] names, and the +/// offsets of its words: the target's IPI_SR (`u64`), deferred-IPI flag +/// (`u8`), line-change counter (`u64`), chaining control +/// ([`super::chain::ChainControl`]), halted flag (`u8`) and PE number, each +/// but the last an address. +pub const FAST_IPI_TARGET_BYTES: usize = 48; +pub const FAST_IPI_TARGET_STATUS: usize = 0; +pub const FAST_IPI_TARGET_ARMED: usize = 8; +pub const FAST_IPI_TARGET_LINES: usize = 16; +pub const FAST_IPI_TARGET_INTERRUPT: usize = 24; +pub const FAST_IPI_TARGET_SLEEPING: usize = 32; +pub const FAST_IPI_TARGET_PE: usize = 40; + +const IPI_BASE: i8 = core::mem::offset_of!(FastIpi, base) as i8; +const IPI_CLUSTERS: i8 = core::mem::offset_of!(FastIpi, clusters) as i8; +const IPI_CPUS: i8 = core::mem::offset_of!(FastIpi, cpus) as i8; +const IPI_CLUSTER: i8 = core::mem::offset_of!(FastIpi, cluster) as i8; +const IPI_PE: i8 = core::mem::offset_of!(FastIpi, pe) as i8; +const IPI_STATUS: i8 = core::mem::offset_of!(FastIpi, status) as i8; +const IPI_WAKES: i8 = core::mem::offset_of!(FastIpi, wakes) as i8; +const IPI_TARGET: i8 = core::mem::offset_of!(FastIpi, target) as i8; + +/// IPI_RR's CPU [7:0], CLUSTER [23:16] and TYPE [29:28]. +const RR_CPU: i32 = 0xff; +const RR_CLUSTER: u64 = 0xff << 16; +const RR_TYPE: u64 = 0b11 << 28; + +/// Where fast-IPI thunks find their words: the per-state cell open where +/// the MSR completes plainly, the PE's [`FastIpi`], the control +/// ([`super::chain::ChainControl`]) and the native ISR_EL1 read's cell +/// ([`interrupt_status_thunk`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FastIpiPlaces { + pub cell: Place, + pub ipi: Place, + pub control: Place, + pub interrupt_status: Place, +} + +/// Post an interruption to the control at RCX as `chain::interrupt` does: +/// add 1 to its epoch unless it is `u64::MAX`, which stays, in a LOCK +/// CMPXCHG loop, then zero its quiet word. Clobbers RAX and RDX. +fn bump_epoch(asm: &mut Asm<'_>) { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let epoch = Mem::base_disp8(Rcx, INTERRUPT_EPOCH); + asm.mov_load(Qword, Rax, epoch); + let top = asm.len(); + asm.alu_imm8(Alu::Cmp, Qword, Rax, -1); + let saturated = asm.jcc(Cond::E); + asm.lea(Qword, Rdx, Mem::base_disp8(Rax, 1)); + asm.lock(); + asm.cmpxchg(Qword, epoch, Rdx); + let lost = asm.jcc(Cond::Ne); + asm.bind_back(lost, top); + asm.bind(saturated); + asm.mov_rm_imm32(Qword, Mem::base(Rcx, QUIET.into()), 0); +} + +/// The thunk completing an immediate fast-IPI request, MSR IPI_RR_LOCAL +/// (or IPI_RR_GLOBAL with `global`) at `pc` with Xt, while the cell is +/// open, step for step as the engine's reference send (`fast_ipi::Table:: +/// send`) does, else exiting at `pc` having changed nothing: the value +/// holds only CPU, TYPE 0 and, global, CLUSTER; the target is present and +/// not this PE; its deferred IPI is not armed. It ORs PENDING into the +/// target's IPI_SR (LOCK CMPXCHG), and where that was clear adds 1 to its +/// line-change counter (LOCK ADD), to its interruption epoch unless +/// saturated, and, finding it halted, sets its bit in [`FastIpi::wakes`] +/// and moves this PE's own interruption epoch, so its run ends at the next +/// chained transfer and the engine wakes the target (`Devices:: +/// wake_signalled`) without running the MSR again. It clobbers RAX, RCX +/// and RDX. +pub fn fast_ipi_request_thunk( + pc: GuestAddress, + rt: u8, + global: bool, + places: FastIpiPlaces, +) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Byte, Dword, Qword}; + let ipi = |offset| Mem::base_disp8(Rax, offset); + let target = |offset: usize| Mem::base_disp8(Rdx, offset as i8); + let (mut code, closed) = open(places.cell); + let mut asm = Asm::new(&mut code); + if rt == 31 { + asm.alu(Alu::Xor, Dword, Rcx, Rcx); + } else { + asm.mov_load(Qword, Rcx, register(rt)); + } + let fields = RR_CPU as u64 | if global { RR_CLUSTER } else { 0 }; + asm.mov_imm64(Rdx, !fields | RR_TYPE); + asm.test(Qword, Rcx, Rdx); + let malformed = asm.jcc(Cond::Ne); + asm.place(Rax, places.ipi); + if global { + asm.mov(Qword, Rdx, Rcx); + asm.shift_imm(ShiftOp::Shr, Qword, Rdx, 16); + } else { + asm.mov_load(Qword, Rdx, ipi(IPI_CLUSTER)); + } + asm.alu_load(Alu::Cmp, Qword, Rdx, ipi(IPI_CLUSTERS)); + let no_cluster = asm.jcc(Cond::Ae); + asm.alu_imm32(Alu::And, Dword, Rcx, RR_CPU); + asm.alu_load(Alu::Cmp, Qword, Rcx, ipi(IPI_CPUS)); + let no_cpu = asm.jcc(Cond::Ae); + asm.imul(Qword, Rdx, ipi(IPI_CPUS)); + asm.alu(Alu::Add, Qword, Rdx, Rcx); + asm.imul_imm32(Qword, Rdx, Rdx, FAST_IPI_TARGET_BYTES as i32); + asm.alu_load(Alu::Add, Qword, Rdx, ipi(IPI_BASE)); + asm.alu_imm8(Alu::Cmp, Qword, target(FAST_IPI_TARGET_STATUS), 0); + let absent = asm.jcc(Cond::E); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_PE)); + asm.alu_load(Alu::Cmp, Qword, Rcx, ipi(IPI_PE)); + let own = asm.jcc(Cond::E); + asm.alu_imm8(Alu::Cmp, Qword, Rcx, 64); + let unnamed = asm.jcc(Cond::Ae); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_ARMED)); + asm.movzx(Dword, Rcx, Byte, Mem::base(Rcx, 0)); + asm.test(Dword, Rcx, Rcx); + let armed = asm.jcc(Cond::Ne); + // Committed from here on. + asm.mov_store(Qword, ipi(IPI_TARGET), Rdx); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_STATUS)); + asm.mov_load(Qword, Rax, Mem::base(Rcx, 0)); + let top = asm.len(); + asm.mov(Qword, Rdx, Rax); + asm.alu_imm8(Alu::Or, Qword, Rdx, 1); + asm.lock(); + asm.cmpxchg(Qword, Mem::base(Rcx, 0), Rdx); + let lost = asm.jcc(Cond::Ne); + asm.bind_back(lost, top); + asm.test(Qword, Rax, Rax); + let pending = asm.jcc(Cond::Ne); + let reload = |asm: &mut Asm<'_>| { + asm.place(Rax, places.ipi); + asm.mov_load(Qword, Rdx, ipi(IPI_TARGET)); + }; + reload(&mut asm); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_LINES)); + asm.lock(); + asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_INTERRUPT)); + bump_epoch(&mut asm); + reload(&mut asm); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_SLEEPING)); + asm.movzx(Dword, Rcx, Byte, Mem::base(Rcx, 0)); + asm.test(Dword, Rcx, Rcx); + let running = asm.jcc(Cond::E); + asm.mov_load(Qword, Rcx, target(FAST_IPI_TARGET_PE)); + asm.mov_imm32(Rdx, 1); + asm.shift_cl(ShiftOp::Shl, Qword, Rdx); + asm.alu(Alu::Or, Qword, ipi(IPI_WAKES), Rdx); + asm.place(Rcx, places.control); + bump_epoch(&mut asm); + asm.bind(pending); + asm.bind(running); + finish_unless( + code, + [ + closed, malformed, no_cluster, no_cpu, absent, own, unnamed, armed, + ], + pc, + ) +} + +/// The thunk completing MSR IPI_SR at `pc` with Xt while the cell is open: +/// 1 clears PENDING in this PE's IPI_SR in one exchange, as other PEs set +/// it, and closes the native ISR_EL1 read, whose waiting FIQ was taken at +/// entry; 0 changes nothing; any other value, or a PE whose word the +/// engine has not named, exits. It clobbers RAX, RCX and RDX. +pub fn fast_ipi_status_thunk(pc: GuestAddress, rt: u8, places: FastIpiPlaces) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + let (mut code, closed) = open(places.cell); + if rt == 31 { + return finish(code, closed, pc); + } + let mut asm = Asm::new(&mut code); + asm.mov_load(Qword, Rcx, register(rt)); + asm.test(Qword, Rcx, Rcx); + let nothing = asm.jcc(Cond::E); + asm.alu_imm8(Alu::Cmp, Qword, Rcx, 1); + let other = asm.jcc(Cond::Ne); + asm.place(Rax, places.ipi); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, IPI_STATUS)); + asm.test(Qword, Rcx, Rcx); + let unknown = asm.jcc(Cond::E); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.xchg(Qword, Mem::base(Rcx, 0), Rdx); + asm.place(Rax, places.interrupt_status); + asm.mov_rm_imm32(Qword, Mem::base(Rax, 0), 0); + asm.bind(nothing); + finish_unless(code, [closed, other, unknown], pc) +} + +/// The thunk completing `write` at `pc` in the frame while the cell at +/// `cell` is open, else exiting at `pc`. +pub fn mask_thunk(write: MaskWrite, pc: GuestAddress, cell: Place) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + let (mut code, closed) = open(cell); + let masks = frame_field(core::mem::offset_of!(GuestState, daif)); + let pending = frame_field(core::mem::offset_of!(GuestState, pending)); + let mut asm = Asm::new(&mut code); + asm.mov_load(Dword, Rcx, masks); + match write { + MaskWrite::Set(immediate) => { + asm.mov(Dword, Rax, Rcx); + asm.alu_imm8(Alu::Or, Dword, Rax, immediate as i8); + } + MaskWrite::Clear(immediate) => { + asm.mov(Dword, Rax, Rcx); + asm.alu_imm8(Alu::And, Dword, Rax, !immediate as i8); + } + MaskWrite::Register(31) => asm.alu(Alu::Xor, Dword, Rax, Rax), + MaskWrite::Register(rt) => { + asm.mov_load(Qword, Rax, register(rt)); + asm.shift_imm(ShiftOp::Shr, Qword, Rax, MASK_SHIFT); + asm.alu_imm8(Alu::And, Dword, Rax, 0xf); + } + } + // RDX the masks that change, RCX those of them that clear. + asm.mov(Dword, Rdx, Rax); + asm.alu(Alu::Xor, Dword, Rdx, Rcx); + asm.alu(Alu::And, Dword, Rcx, Rdx); + asm.alu_imm8(Alu::And, Dword, Rdx, MASK_D); + let debug = asm.jcc(Cond::Ne); + asm.alu_load(Alu::And, Dword, Rcx, pending); + let waiting = asm.jcc(Cond::Ne); + asm.mov_store(Dword, masks, Rax); + finish_unless(code, [closed, debug, waiting], pc) +} + +/// The thunk completing `MRS Xt, DAIF` at `pc` from the frame while the cell +/// at `cell` is open, else exiting at `pc`. +pub fn mask_read_thunk(pc: GuestAddress, rt: u8, cell: Place) -> Thunk { + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + let masks = frame_field(core::mem::offset_of!(GuestState, daif)); + asm.mov_load(Size::Dword, Gpr::Rax, masks); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Gpr::Rax, MASK_SHIFT); + asm.mov_store(Size::Qword, register(rt), Gpr::Rax); + finish(code, miss, pc) +} + +/// The thunk completing `MRS Xt, ` at `pc` with the count of the +/// reader at `count` less the `value` of the cell at `cell`, else exiting +/// at `pc`. It spins while a writer publishes; `lfence` keeps the TSC +/// sample between the two sequence reads (Intel SDM Vol. 2B, RDTSC). +pub fn count_thunk(pc: GuestAddress, rt: u8, cell: Place, count: Place) -> Thunk { + use Gpr::{Rax, Rdx}; + use Size::Qword; + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + read_count(&mut asm, count); + if rt != 31 { + asm.place(Rax, cell); + asm.alu_load(Alu::Sub, Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + asm.mov_store(Qword, register(rt), Rdx); + } + finish(code, miss, pc) +} + +/// What an [`energy_thunk`]'s cell `value` points at: an accumulator's +/// reading is `(count - origin) * scale / frequency` of the system count. +#[repr(C)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Energy { + pub origin: u64, + pub scale: u64, + pub frequency: u64, +} + +/// The thunk completing `MRS Xt, ` at `pc` with the reading the +/// [`Energy`] the `value` of the cell at `cell` points at gives at the count +/// of the reader at `count`, else exiting at `pc`: as the cell's register's +/// model computes it, so a reading never goes back. A quotient that would +/// not fit in 64 bits exits too. It also clobbers RCX and RDX. +pub fn energy_thunk(pc: GuestAddress, rt: u8, cell: Place, count: Place) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let (mut code, miss) = open(cell); + let mut asm = Asm::new(&mut code); + read_count(&mut asm, count); + asm.place(Rax, cell); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, VALUE)); + let energy = |field| Mem::base_disp8(Rcx, field as i8); + // The ticks since the origin, none before it. + asm.mov(Qword, Rax, Rdx); + asm.alu(Alu::Xor, Size::Dword, Rdx, Rdx); + asm.alu_load( + Alu::Sub, + Qword, + Rax, + energy(core::mem::offset_of!(Energy, origin)), + ); + asm.cmov(Cond::B, Qword, Rax, Rdx); + asm.unary( + Unary::Mul, + Qword, + energy(core::mem::offset_of!(Energy, scale)), + ); + let frequency = energy(core::mem::offset_of!(Energy, frequency)); + asm.alu_load(Alu::Cmp, Qword, Rdx, frequency); + let wide = asm.jcc(Cond::Ae); + asm.unary(Unary::Div, Qword, frequency); + if rt != 31 { + asm.mov_store(Qword, register(rt), Rax); + } + finish_unless(code, [miss, wide], pc) +} + +/// What a [`cycle_counter_thunk`] computes a cycle counter from, as the +/// engine's performance monitor counts it: `counter` at system count +/// `synced` with `remainder` of a cycle in 1/`frequency` units, then +/// `clock` cycles a `frequency` ticks (0 while the counter does not count), +/// the sum wrapped to `mask`; `remainder` is below `frequency`. `open` is nonzero while these are the +/// monitor's; `frequency` is never 0 then. `overflow` is the counter's +/// overflow bit while its PMI is armed, else 0: a count with it set exits, +/// so that the engine's read raises the PMI at the read. `clocks` holds +/// `clock` in each PE state, which a logged transition +/// (`transition::CHAIN_LOGGED`) takes after it folds the count up to itself +/// into `counter`, `synced` and `remainder`. +#[repr(C)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct CycleCounter { + pub open: u64, + pub counter: u64, + pub synced: u64, + pub remainder: u64, + pub clock: u64, + pub frequency: u64, + pub mask: u64, + pub overflow: u64, + pub clocks: [u64; super::transition::STATES], +} + +impl CycleCounter { + /// The counter at system count `now`, `None` where the thunk exits + /// (closed, a quotient that does not fit in 64 bits, or a count with + /// the armed overflow bit set). + pub fn at(&self, now: u64) -> Option { + if self.open == 0 || self.frequency == 0 { + return None; + } + let ticks = now.saturating_sub(self.synced); + let scaled = u128::from(ticks) * u128::from(self.clock) + u128::from(self.remainder); + let increment = u64::try_from(scaled / u128::from(self.frequency)).ok()?; + let count = self.counter.wrapping_add(increment) & self.mask; + (count & self.overflow == 0).then_some(count) + } +} + +/// The thunk completing `MRS Xt, ` at `pc`. While the cell +/// at `cell` is open it reads its `value` (the count the engine or this +/// thunk last took in the PE's state). While it is closed but the cell at +/// `plain` is open (the read is plain in the state: only the value went +/// stale, at a native transition), it computes the count at the reader at +/// `count` from the [`CycleCounter`] at `cycles` ([`CycleCounter::at`]), +/// opens `cell` on it, as an engine read does, and completes with it. Else +/// it exits at `pc`. It also clobbers RCX and RDX. +pub fn cycle_counter_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + plain: Place, + cycles: Place, + count: Place, +) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + let field = |offset: usize| Mem::base_disp8(Rcx, offset as i8); + let mut code = Vec::with_capacity(256); + let mut asm = Asm::new(&mut code); + asm.place(Rax, cell); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let stale = asm.jcc(Cond::E); + asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + let read = asm.jmp(); + asm.bind(stale); + asm.place(Rax, plain); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let unplain = asm.jcc(Cond::E); + asm.place(Rcx, cycles); + asm.alu_imm8( + Alu::Cmp, + Qword, + field(core::mem::offset_of!(CycleCounter, open)), + 0, + ); + let closed = asm.jcc(Cond::E); + read_count(&mut asm, count); + asm.place(Rcx, cycles); + // The ticks since the monitor's count, none before it. + asm.mov(Qword, Rax, Rdx); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.alu_load( + Alu::Sub, + Qword, + Rax, + field(core::mem::offset_of!(CycleCounter, synced)), + ); + asm.cmov(Cond::B, Qword, Rax, Rdx); + asm.unary( + Unary::Mul, + Qword, + field(core::mem::offset_of!(CycleCounter, clock)), + ); + asm.alu_load( + Alu::Add, + Qword, + Rax, + field(core::mem::offset_of!(CycleCounter, remainder)), + ); + asm.alu_imm8(Alu::Adc, Qword, Rdx, 0); + let frequency = field(core::mem::offset_of!(CycleCounter, frequency)); + asm.alu_load(Alu::Cmp, Qword, Rdx, frequency); + let wide = asm.jcc(Cond::Ae); + asm.unary(Unary::Div, Qword, frequency); + asm.alu_load( + Alu::Add, + Qword, + Rax, + field(core::mem::offset_of!(CycleCounter, counter)), + ); + asm.alu_load( + Alu::And, + Qword, + Rax, + field(core::mem::offset_of!(CycleCounter, mask)), + ); + asm.test( + Qword, + field(core::mem::offset_of!(CycleCounter, overflow)), + Rax, + ); + let crossed = asm.jcc(Cond::Ne); + asm.mov(Qword, Rdx, Rax); + asm.place(Rax, cell); + asm.mov_store(Qword, Mem::base_disp8(Rax, VALUE), Rdx); + asm.mov_imm32(Rcx, 1); + asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); + asm.bind(read); + if rt != 31 { + asm.mov_store(Qword, register(rt), Rdx); + } + finish_unless(code, [unplain, closed, wide, crossed], pc) +} + +/// What an [`instruction_counter_thunk`] computes a retired-instruction +/// counter from, as the engine's performance monitor counts it: `base`, +/// the count as native code was entered, plus the instructions retired +/// since, masked by `step` (all ones while the counter counts, 0 while it +/// does not), the sum wrapped to `mask`. `open` is nonzero while these are +/// the monitor's. `overflow` is the counter's overflow bit while its PMI is +/// armed, else 0: a count with it set exits, so that the engine's read +/// raises the PMI at the read. `steps` holds `step` in each PE state, which +/// a logged transition (`transition::CHAIN_LOGGED`) takes, moving `base` so +/// that the count up to it stays. +#[repr(C)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct InstructionCounter { + pub open: u64, + pub base: u64, + pub step: u64, + pub mask: u64, + pub overflow: u64, + pub steps: [u64; super::transition::STATES], +} + +impl InstructionCounter { + /// The counter after native code retired `retired` instructions, `None` + /// where the thunk exits (closed, or a count with the armed overflow + /// bit set). + pub fn at(&self, retired: u64) -> Option { + let count = self.base.wrapping_add(retired & self.step) & self.mask; + (self.open != 0 && count & self.overflow == 0).then_some(count) + } +} + +/// The thunk completing `MRS Xt, ` at `pc`, the +/// instruction after `before` others of its block. While the cell at `cell` +/// is open it reads its `value`. While it is closed but the cell at `plain` +/// is open (only the value went stale, at a native transition), it computes +/// the count from the [`InstructionCounter`] at `counter` +/// ([`InstructionCounter::at`]) with the instructions native code retired +/// before this one: the chain's count of the blocks it left +/// (`chain::Account::retired`) and `before`. It opens `cell` on it, as an +/// engine read does, and completes with it. Else it exits at `pc`. It also +/// clobbers RCX and RDX. +pub fn instruction_counter_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + plain: Place, + counter: Place, + before: u32, +) -> Option { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let before = i32::try_from(before).ok()?; + let field = |offset: usize| Mem::base_disp8(Rcx, offset as i8); + let mut code = Vec::with_capacity(160); + let mut asm = Asm::new(&mut code); + asm.place(Rax, cell); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let stale = asm.jcc(Cond::E); + asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + let read = asm.jmp(); + asm.bind(stale); + asm.place(Rax, plain); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let unplain = asm.jcc(Cond::E); + asm.place(Rcx, counter); + asm.alu_imm8( + Alu::Cmp, + Qword, + field(core::mem::offset_of!(InstructionCounter, open)), + 0, + ); + let closed = asm.jcc(Cond::E); + super::chain::account_retired(&mut asm, Rdx); + if before != 0 { + asm.alu_imm32(Alu::Add, Qword, Rdx, before); + } + asm.alu_load( + Alu::And, + Qword, + Rdx, + field(core::mem::offset_of!(InstructionCounter, step)), + ); + asm.alu_load( + Alu::Add, + Qword, + Rdx, + field(core::mem::offset_of!(InstructionCounter, base)), + ); + asm.alu_load( + Alu::And, + Qword, + Rdx, + field(core::mem::offset_of!(InstructionCounter, mask)), + ); + asm.test( + Qword, + field(core::mem::offset_of!(InstructionCounter, overflow)), + Rdx, + ); + let crossed = asm.jcc(Cond::Ne); + asm.place(Rax, cell); + asm.mov_store(Qword, Mem::base_disp8(Rax, VALUE), Rdx); + asm.mov_imm32(Rcx, 1); + asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); + asm.bind(read); + if rt != 31 { + asm.mov_store(Qword, register(rt), Rdx); + } + Some(finish_unless(code, [unplain, closed, crossed], pc)) +} + +/// The thunk completing `MRS Xt, ISR_EL1` at `pc` where the register reads +/// the physical IRQ and FIQ lines alone (EL2): from the masks of the +/// interrupts waiting when native code was entered ([`GuestState::pending`], +/// I in bit 1 and F in bit 0, ISR's bits 7 and 6), while the lines are still +/// those. The cell at `cell` says so: open (`readable` nonzero), the epoch at +/// `epoch` still its `value` (no line changed since it was read), and the +/// count of the reader at `count` below its `readable` (no timer or device +/// deadline passed; `u64::MAX` names none and reads no count). Else it exits +/// at `pc`. It also clobbers RCX and RDX. +pub fn interrupt_status_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + epoch: Place, + count: Place, +) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + /// ISR_EL1.F, the lowest of the bits [`GuestState::pending`] gives. + const ISR_SHIFT: u8 = 6; + let (mut code, closed) = open(cell); + let mut asm = Asm::new(&mut code); + asm.place(Rcx, epoch); + asm.mov_load(Qword, Rdx, Mem::base(Rcx, 0)); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + let changed = asm.jcc(Cond::Ne); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), -1); + let timeless = asm.jcc(Cond::E); + read_count(&mut asm, count); + asm.place(Rax, cell); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + let due = asm.jcc(Cond::Ae); + asm.bind(timeless); + if rt != 31 { + let pending = frame_field(core::mem::offset_of!(GuestState, pending)); + asm.mov_load(Dword, Rax, pending); + asm.alu_imm8(Alu::And, Dword, Rax, 0b11); + asm.shift_imm(ShiftOp::Shl, Dword, Rax, ISR_SHIFT); + asm.mov_store(Qword, register(rt), Rax); + } + finish_unless(code, [closed, changed, due], pc) +} + +/// What a [`timer_thunk`] completes, of one generic timer channel whose +/// count is the system count with no offset. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimerAccess { + /// MSR TVAL: the compare becomes the count plus Xt's low 32 bits, + /// sign-extended. + WriteValue, + /// MSR CVAL: the compare becomes Xt. + WriteCompare, + /// MSR CTL: the control becomes Xt as the register takes it. + WriteControl(Written), + /// MRS CTL: ENABLE and IMASK as stored, ISTATUS while enabled with the + /// count at or past the compare. + ReadControl, +} + +/// Where a [`timer_thunk`] finds its channel and the engine's words: two +/// cells whose `value` is the address of the compare's storage and the +/// control's, the count before which the engine looks at the lines again +/// ([`crate::x86_64::transition::Places::lines_until`]), the native ISR_EL1 +/// read's cell, open until a count ([`interrupt_status_thunk`]), the count +/// reader, and `quiet`, a cell open while its `value` is what +/// [`GuestState::pending`] would hold were the channel's output low: the +/// interrupts waiting at entry but the FIQ only this channel raised. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TimerPlaces { + pub compare: Place, + pub control: Place, + pub lines_until: Place, + pub interrupt_status: Place, + pub count: Place, + pub quiet: Place, +} + +/// ENABLE and IMASK of a timer control. +const TIMER_ARMING: i8 = 0b11; +/// ENABLE alone: the timer's output follows the compare. +const TIMER_ARMED: i8 = 0b01; +/// ISTATUS's bit. +const TIMER_STATUS_SHIFT: u8 = 2; + +/// The thunk completing `access` of a timer channel at `pc` with Xt, else +/// exiting at `pc`. Both cells must be open. A write completes only when it +/// leaves the channel's output low, and the engine's `lines_until` names a +/// count (not 0): once the write is done the channel is disabled, masked or +/// armed for a compare after the count. A compare before `lines_until` pulls +/// it, and the deadline of an open ISR_EL1 cell, down to the compare: every +/// native path that could let the line's rise pass unseen (an unmasking ERET +/// or GEXIT, an ISR_EL1 read, a WFE's spin) stops there, and the engine, +/// which looks at the lines again at the next boundary, finds the new +/// compare in storage. A completed write also makes the frame's waiting +/// interrupts `quiet`'s, which the channel's low output leaves: a kernel's +/// timer handler that rearms the timer whose FIQ it took lowers the FIQ, so +/// the ERET after it unmasks none. Where the output was high and `quiet` is +/// closed, or the write would raise or keep the line, it exits. A count +/// that passes the new compare after the thunk read it is at or past those +/// deadlines too. It clobbers RAX, RCX and RDX. +pub fn timer_thunk(pc: GuestAddress, rt: u8, access: TimerAccess, places: TimerPlaces) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::{Dword, Qword}; + let (mut code, closed) = open(places.compare); + let mut asm = Asm::new(&mut code); + asm.place(Rax, places.control); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let control_closed = asm.jcc(Cond::E); + let storage = |asm: &mut Asm<'_>, destination: Gpr, cell: Place| { + asm.place(destination, cell); + asm.mov_load(Qword, destination, Mem::base_disp8(destination, VALUE)); + }; + if access == TimerAccess::ReadControl { + read_count(&mut asm, places.count); + storage(&mut asm, Rax, places.compare); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + asm.setcc(Cond::Ae, Rcx); + asm.movzx(Dword, Rcx, Size::Byte, Rcx); + storage(&mut asm, Rax, places.control); + asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); + asm.alu(Alu::And, Dword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shl, Dword, Rcx, TIMER_STATUS_SHIFT); + asm.alu_imm8(Alu::And, Qword, Rax, !(1 << TIMER_STATUS_SHIFT)); + asm.alu(Alu::Or, Qword, Rax, Rcx); + if rt != 31 { + asm.mov_store(Qword, register(rt), Rax); + } + return finish_unless(code, [closed, control_closed], pc); + } + asm.place(Rcx, places.lines_until); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rcx, 0), 0); + let unknown = asm.jcc(Cond::E); + read_count(&mut asm, places.count); + // The output was low: not armed, or armed before its compare. + storage(&mut asm, Rax, places.control); + asm.mov_load(Dword, Rax, Mem::base(Rax, 0)); + asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); + asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); + let was_quiet = asm.jcc(Cond::Ne); + storage(&mut asm, Rax, places.compare); + asm.alu_load(Alu::Cmp, Qword, Rdx, Mem::base(Rax, 0)); + let was_low = asm.jcc8(Cond::B); + // High: only where the engine knows what lowering it leaves waiting. + asm.place(Rax, places.quiet); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + let was_high = asm.jcc(Cond::E); + asm.bind(was_low); + asm.bind(was_quiet); + // The new register value into RCX, and the compare it arms into RAX + // while the control arms one, else straight to the store. + let write = |asm: &mut Asm<'_>| { + if rt == 31 { + asm.alu(Alu::Xor, Dword, Rcx, Rcx); + } else { + asm.mov_load(Qword, Rcx, register(rt)); + } + }; + let quiet = match access { + TimerAccess::WriteValue | TimerAccess::WriteCompare => { + if access == TimerAccess::WriteValue { + if rt == 31 { + asm.alu(Alu::Xor, Dword, Rcx, Rcx); + } else { + asm.movsxd(Rcx, register(rt)); + } + asm.alu(Alu::Add, Qword, Rcx, Rdx); + } else { + write(&mut asm); + } + storage(&mut asm, Rax, places.control); + asm.mov_load(Dword, Rax, Mem::base(Rax, 0)); + asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); + asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); + let quiet = asm.jcc(Cond::Ne); + asm.mov(Qword, Rax, Rcx); + quiet + } + TimerAccess::WriteControl(written) => { + write(&mut asm); + if written.keep != u64::MAX { + asm.mov_imm64(Rax, written.keep); + asm.alu(Alu::And, Qword, Rcx, Rax); + } + if written.set != 0 { + asm.mov_imm64(Rax, written.set); + asm.alu(Alu::Or, Qword, Rcx, Rax); + } + asm.mov(Dword, Rax, Rcx); + asm.alu_imm8(Alu::And, Dword, Rax, TIMER_ARMING); + asm.alu_imm8(Alu::Cmp, Dword, Rax, TIMER_ARMED); + let quiet = asm.jcc(Cond::Ne); + storage(&mut asm, Rax, places.compare); + asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); + quiet + } + TimerAccess::ReadControl => unreachable!("handled above"), + }; + // Armed: after the count, and no earlier than the engine looks again. + asm.alu(Alu::Cmp, Qword, Rax, Rdx); + let at_once = asm.jcc(Cond::Be); + // Earlier than the engine looks again: pull its deadlines down. + asm.place(Rdx, places.lines_until); + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rdx, 0)); + let later = asm.jcc(Cond::Ae); + asm.mov_store(Qword, Mem::base(Rdx, 0), Rax); + asm.place(Rdx, places.interrupt_status); + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rdx, 0)); + let read_later = asm.jcc(Cond::Ae); + asm.mov_store(Qword, Mem::base(Rdx, 0), Rax); + asm.bind(later); + asm.bind(read_later); + asm.bind(quiet); + // The output is low from here: the FIQ only it raised goes. + asm.place(Rdx, places.quiet); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rdx, 0), 0); + let unknown_quiet = asm.jcc8(Cond::E); + asm.mov_load(Dword, Rdx, Mem::base_disp8(Rdx, VALUE)); + asm.mov_store( + Dword, + frame_field(core::mem::offset_of!(GuestState, pending)), + Rdx, + ); + asm.bind(unknown_quiet); + let target = match access { + TimerAccess::WriteControl(_) => places.control, + _ => places.compare, + }; + storage(&mut asm, Rax, target); + asm.mov_store(Qword, Mem::base(Rax, 0), Rcx); + finish_unless( + code, + [closed, control_closed, unknown, was_high, at_once], + pc, + ) +} + +/// A plain device read a [`device_read_thunk`] serves again: the device +/// site's physical address (`site`, 0 for none), the address it read +/// (`address`, the base register plus the offset), the `key` of the state it +/// read in ([`device_read_key`]), the model's epoch word (`epoch`, its +/// address) and the count it held (`seen`), the value read, and the system +/// count before which no device deadline came (`until`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeviceRead { + pub site: u64, + pub address: u64, + pub key: u64, + pub epoch: u64, + pub seen: u64, + pub value: u64, + pub until: u64, +} + +const READ_SITE: i8 = core::mem::offset_of!(DeviceRead, site) as i8; +const READ_ADDRESS: i8 = core::mem::offset_of!(DeviceRead, address) as i8; +const READ_KEY: i8 = core::mem::offset_of!(DeviceRead, key) as i8; +const READ_EPOCH: i8 = core::mem::offset_of!(DeviceRead, epoch) as i8; +const READ_SEEN: i8 = core::mem::offset_of!(DeviceRead, seen) as i8; +const READ_VALUE: i8 = core::mem::offset_of!(DeviceRead, value) as i8; +const READ_UNTIL: i8 = core::mem::offset_of!(DeviceRead, until) as i8; + +/// The [`DeviceRead`]s a PE keeps, a slot per site and address +/// ([`device_read_slot`]). +pub const DEVICE_READS: usize = 64; + +/// The multiplier mixing a read's address into its slot, as native code's +/// `imul r64, r/m64, imm32` sign-extends it, and the bit of the product +/// where the slot's bits start: bits 26-31 of the product take every +/// address bit from 2 to 33, where a 32-bit multiplier leaves the top bits +/// to the address's high bits alone. +const ADDRESS_MIX: i32 = 0x9e37_79b1_u32 as i32; +const ADDRESS_MIX_SHIFT: u8 = 26; + +/// The slot of the read at virtual `address` by the device site at +/// physical `site`: one site that reads several addresses in turn (a +/// sampler walking per-cluster counters) keeps a slot for each. +pub const fn device_read_slot(site: u64, address: u64) -> usize { + let bits = 64 - DEVICE_READS.ilog2(); + let site = (site >> 2).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> bits; + let address = (address >> 2).wrapping_mul(ADDRESS_MIX as i64 as u64) >> ADDRESS_MIX_SHIFT; + (site ^ address) as usize & (DEVICE_READS - 1) +} + +/// The key a [`DeviceRead`] made in mirror state `state` with PSTATE.PAN +/// `pan` holds while the state's key cell holds `device_read_key(generation, +/// state, false)`: the PE's translation and its controls as they were. +pub const fn device_read_key(generation: u64, state: usize, pan: bool) -> u64 { + generation << 4 | (state as u64) << 1 | pan as u64 +} + +/// A load a [`device_read_thunk`] completes: `LDR` or `LDUR` of a B, H, W or X +/// register, zero-extending, without writeback, from a base other than SP +/// (`rn`) plus `offset` or plus an `index` register, into `rt`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DeviceLoad { + pub rn: u8, + pub offset: i32, + pub index: Option, + pub rt: u8, + pub bytes: u8, +} + +/// The index of `LDR (register)`: Xm, or Wm zero- or sign-extended, shifted +/// left by `shift`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DeviceIndex { + pub rm: u8, + pub extend: IndexExtend, + pub shift: u8, +} + +/// How `LDR (register)` widens its index ([`DeviceIndex`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IndexExtend { + /// UXTW: Wm zero-extended. + Unsigned, + /// SXTW: Wm sign-extended. + Signed, + /// LSL or SXTX: Xm as it is. + Whole, +} + +impl DeviceLoad { + /// The load `word` makes, if a [`device_read_thunk`] completes it. + pub fn of(word: u32) -> Option { + let size = word >> 30; + let rn = (word >> 5 & 31) as u8; + let rt = (word & 31) as u8; + let mut index = None; + let offset = if word & 0x3fc0_0000 == 0x3940_0000 { + // LDR (immediate, unsigned offset). + ((word >> 10 & 0xfff) << size) as i32 + } else if word & 0x3fe0_0c00 == 0x3840_0000 { + // LDUR. + ((word << 11) as i32) >> 23 + } else if word & 0x3fe0_0c00 == 0x3860_0800 { + // LDR (register); Rm 31 is XZR, which no device load names. + let rm = (word >> 16 & 31) as u8; + let extend = match word >> 13 & 7 { + 0b010 => IndexExtend::Unsigned, + 0b110 => IndexExtend::Signed, + 0b011 | 0b111 => IndexExtend::Whole, + _ => return None, + }; + let shift = if word >> 12 & 1 != 0 { size as u8 } else { 0 }; + index = (rm != 31).then_some(DeviceIndex { rm, extend, shift }); + index?; + 0 + } else { + return None; + }; + (rn != 31).then_some(Self { + rn, + offset, + index, + rt, + bytes: 1 << size, + }) + } + + /// The virtual address the load reads with `x` its X registers' values. + pub fn address(&self, x: impl Fn(u8) -> u64) -> u64 { + let index = self.index.map_or(0, |index| { + let value = x(index.rm); + let value = match index.extend { + IndexExtend::Unsigned => value & 0xffff_ffff, + IndexExtend::Signed => value as u32 as i32 as i64 as u64, + IndexExtend::Whole => value, + }; + value << index.shift + }); + x(self.rn) + .wrapping_add_signed(i64::from(self.offset)) + .wrapping_add(index) + } + + /// Its address into RAX, as [`Self::address`]. Clobbers RCX. + fn address_into_rax(&self, asm: &mut Asm<'_>) { + use Gpr::{Rax, Rcx}; + use Size::{Dword, Qword}; + asm.mov_load(Qword, Rax, register(self.rn)); + if self.offset != 0 { + asm.alu_imm32(Alu::Add, Qword, Rax, self.offset); + } + if let Some(index) = self.index { + match index.extend { + IndexExtend::Unsigned => asm.mov_load(Dword, Rcx, register(index.rm)), + IndexExtend::Signed => asm.movsxd(Rcx, register(index.rm)), + IndexExtend::Whole => asm.mov_load(Qword, Rcx, register(index.rm)), + } + if index.shift != 0 { + asm.shift_imm(ShiftOp::Shl, Qword, Rcx, index.shift); + } + asm.alu(Alu::Add, Qword, Rax, Rcx); + } + } +} + +/// The address of the [`DeviceRead`] slot of `site` and the address in RAX +/// ([`device_read_slot`]) among `reads` into RCX. +fn device_read_slot_into_rcx(asm: &mut Asm<'_>, reads: Place, site: u64) { + use Gpr::{Rax, Rcx}; + use Size::{Dword, Qword}; + let bits = 64 - DEVICE_READS.ilog2() as u8; + let site = (site >> 2).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> bits; + asm.mov(Qword, Rcx, Rax); + asm.shift_imm(ShiftOp::Shr, Qword, Rcx, 2); + asm.imul_imm32(Qword, Rcx, Rcx, ADDRESS_MIX); + asm.shift_imm(ShiftOp::Shr, Qword, Rcx, ADDRESS_MIX_SHIFT); + asm.alu_imm8(Alu::And, Dword, Rcx, (DEVICE_READS - 1) as i8); + asm.alu_imm8(Alu::Xor, Dword, Rcx, site as i8); + asm.imul_imm32(Dword, Rcx, Rcx, core::mem::size_of::() as i32); + let anchor = core::mem::offset_of!(crate::GuestState, anchors) + reads.anchor as usize * 8; + asm.alu_load(Alu::Add, Qword, Rcx, Mem::base(Gpr::Rdi, anchor as i32)); + if reads.offset != 0 { + asm.alu_imm32(Alu::Add, Qword, Rcx, reads.offset as i32); + } +} + +/// Where a [`device_read_thunk`] finds its reads: the PE's [`DeviceRead`]s, +/// the key cell of its state, whose `value` the read's key must match, and +/// the count reader. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DeviceReadPlaces { + pub reads: Place, + pub key: Place, + pub count: Place, +} + +/// The thunk completing the plain device load `load` of the site at `pc` +/// and physical `site` natively, while the [`DeviceRead`] of the slot of +/// that site and the address the load reads now ([`device_read_slot`]) +/// holds both, the key of the PE's state and PSTATE.PAN, a model epoch that +/// still holds the count it held, and a count below `until`: it writes the +/// read's value to Xt and leaves through a direct exit to the next +/// instruction. Else it exits at `pc`. It also clobbers RCX and RDX. +pub fn device_read_thunk( + pc: GuestAddress, + site: u64, + load: DeviceLoad, + places: DeviceReadPlaces, +) -> Thunk { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let read = |offset| Mem::base_disp8(Rcx, offset); + let (mut code, closed) = open(places.key); + let mut asm = Asm::new(&mut code); + asm.mov_load(Qword, Rdx, Mem::base_disp8(Rax, VALUE)); + asm.alu_load( + Alu::Or, + Qword, + Rdx, + frame_field(core::mem::offset_of!(GuestState, pan)), + ); + load.address_into_rax(&mut asm); + device_read_slot_into_rcx(&mut asm, places.reads, site); + asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_KEY)); + let other_key = asm.jcc(Cond::Ne); + asm.alu_load(Alu::Cmp, Qword, Rax, read(READ_ADDRESS)); + let other_address = asm.jcc(Cond::Ne); + asm.mov_imm64(Rdx, site); + asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_SITE)); + let other_site = asm.jcc(Cond::Ne); + asm.mov_load(Qword, Rax, read(READ_EPOCH)); + asm.mov_load(Qword, Rax, Mem::base(Rax, 0)); + asm.alu_load(Alu::Cmp, Qword, Rax, read(READ_SEEN)); + let changed = asm.jcc(Cond::Ne); + asm.alu_imm8(Alu::Cmp, Qword, read(READ_UNTIL), -1); + let timeless = asm.jcc(Cond::E); + read_count(&mut asm, places.count); + // The count clobbered the slot's address: find it again. + load.address_into_rax(&mut asm); + device_read_slot_into_rcx(&mut asm, places.reads, site); + asm.alu_load(Alu::Cmp, Qword, Rdx, read(READ_UNTIL)); + let due = asm.jcc(Cond::Ae); + asm.bind(timeless); + if load.rt != 31 { + asm.mov_load(Qword, Rax, read(READ_VALUE)); + asm.mov_store(Qword, register(load.rt), Rax); + } + finish_unless( + code, + [closed, other_key, other_site, other_address, changed, due], + pc, + ) +} + +/// The count of the reader at `count` into RDX, as [`count_thunk`] reads +/// it. Clobbers RAX and RCX. +pub(super) fn read_count(asm: &mut Asm<'_>, count: Place) { + use Gpr::{Rax, Rcx, Rdx}; + use Size::Qword; + let field = |offset| Mem::base_disp8(Rcx, offset); + let state = |offset| Mem::base_disp8(Rax, offset); + asm.place(Rcx, count); + let start = asm.jmp8(); + let busy = asm.len(); + asm.pause(); + asm.bind(start); + asm.mov_load(Qword, Rax, field(STATE)); + asm.mov_load(Qword, Rdx, state(SEQUENCE)); + asm.test_imm(Size::Byte, Rdx, 1); + let publishing = asm.jcc8(Cond::Ne); + asm.bind_back(publishing, busy); + asm.mov_store(Qword, field(SEEN_SEQUENCE), Rdx); + asm.mov_load(Qword, Rdx, state(STATE_OFFSET)); + asm.mov_store(Qword, field(SEEN_OFFSET), Rdx); + asm.mov_load(Qword, Rdx, state(CEILING)); + asm.mov_store(Qword, field(SEEN_CEILING), Rdx); + asm.lfence(); + asm.rdtsc(); + asm.lfence(); + asm.shift_imm(ShiftOp::Shl, Qword, Rdx, 32); + asm.alu(Alu::Or, Qword, Rax, Rdx); + asm.alu_load(Alu::Sub, Qword, Rax, field(BASE)); + asm.unary(Unary::Mul, Qword, field(PER_TSC)); + asm.mov_load(Qword, Rax, field(STATE)); + asm.mov_load(Qword, Rax, state(SEQUENCE)); + asm.alu_load(Alu::Cmp, Qword, Rax, field(SEEN_SEQUENCE)); + let changed = asm.jcc8(Cond::Ne); + asm.bind_back(changed, busy); + asm.alu_load(Alu::Add, Qword, Rdx, field(SEEN_OFFSET)); + asm.alu_load(Alu::Cmp, Qword, Rdx, field(SEEN_CEILING)); + asm.cmov(Cond::A, Qword, Rdx, field(SEEN_CEILING)); + asm.alu_load(Alu::Cmp, Qword, Rdx, field(LAST)); + asm.cmov(Cond::B, Qword, Rdx, field(LAST)); + asm.mov_store(Qword, field(LAST), Rdx); +} + +/// Load `cell` and branch to the miss while it is not readable. +fn open(cell: Place) -> (Vec, Patch) { + let mut code = Vec::with_capacity(128); + let mut asm = Asm::new(&mut code); + asm.place(Gpr::Rax, cell); + asm.alu_imm8(Alu::Cmp, Size::Qword, Mem::base(Gpr::Rax, 0), 0); + let miss = asm.jcc(Cond::E); + (code, miss) +} + +/// The direct exit to the next instruction, then the `miss` branch's +/// target: the original exit at `pc`. +fn finish(code: Vec, miss: Patch, pc: GuestAddress) -> Thunk { + finish_unless(code, [miss], pc) +} + +/// [`finish`] with several branches to the original exit. +fn finish_unless(mut code: Vec, misses: [Patch; N], pc: GuestAddress) -> Thunk { + let next = code.len(); + let mut asm = Asm::new(&mut code); + super::block::direct_exit_with( + &mut asm, + GuestAddress(pc.0.wrapping_add(4)), + ExitKind::Fallthrough, + ); + for miss in misses { + asm.bind(miss); + } + super::block::direct_exit_with(&mut asm, pc, ExitKind::System); + Thunk::new(code, Some(next), None) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Anchor; + use crate::x86_64::chain::{DIRECT_EXIT_BYTES, direct_exit}; + + /// The anchors of these tests, each at the data itself. + const CELL: Place = Place::new(Anchor::Mirrors, 0); + const WORD: Place = Place::new(Anchor::Pointer, 0); + const READER: Place = Place::new(Anchor::Count, 0); + const SP0: Place = Place::new(Anchor::StackZero, 0); + + #[test] + fn pan_writes_move_the_flag_and_the_frame() { + for (pan, flag) in [(true, [0x0f, 0x01, 0xca]), (false, [0x0f, 0x01, 0xcb])] { + let thunk = pan_thunk(GuestAddress(0x1000), pan, CELL); + assert!(thunk.code.windows(3).any(|bytes| bytes == flag)); + assert!(thunk.next.is_some()); + } + } + + #[test] + fn mask_writes_name_their_form() { + assert_eq!(MaskWrite::of(0xd503_47df), Some(MaskWrite::Set(7))); + assert_eq!(MaskWrite::of(0xd503_4fdf), Some(MaskWrite::Set(15))); + assert_eq!(MaskWrite::of(0xd503_47ff), Some(MaskWrite::Clear(7))); + assert_eq!(MaskWrite::of(0xd51b_4229), Some(MaskWrite::Register(9))); + for other in [0xd500_40bf_u32, 0xd500_409f, 0xd53b_4228, 0xd503_201f] { + assert_eq!(MaskWrite::of(other), None, "{other:#x}"); + } + } + + /// The emitted code runs on the host: masks change in the frame, and a + /// change of D or of a waiting interrupt's mask stays with the engine. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn mask_writes_complete_in_the_frame() { + use core::ffi::c_void; + unsafe extern "C" { + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut c_void, bytes: usize) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANONYMOUS: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANONYMOUS: i32 = 0x20; + const PAGE: usize = 4096; + const PC: GuestAddress = GuestAddress(0x4000); + let open = Cell { + readable: 1, + value: 0, + }; + // The PC of the exit `write` takes. + fn run(write: MaskWrite, cell: &Cell, state: &mut GuestState) -> u64 { + let thunk = mask_thunk(write, PC, CELL); + state.anchors[Anchor::Mirrors] = cell as *const Cell as u64; + // SAFETY: private anonymous memory, RX after the copy, unmapped + // after the call; the code reads and writes only `state` and + // `cell`. + unsafe { + let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(thunk.code.as_ptr(), page.cast(), thunk.code.len()); + assert_eq!(mprotect(page, PAGE, 5), 0); + let entry = |state: *mut crate::GuestState| -> u128 { + crate::x86_64::native::call::(page as *const u8, state, 0, 0) + }; + let exit = entry(state); + assert_eq!(munmap(page, PAGE), 0); + exit as u64 + } + } + let (next, here) = (PC.0 + 4, PC.0); + let mut state = GuestState { + daif: 0b1000, + ..GuestState::default() + }; + assert_eq!(run(MaskWrite::Set(7), &open, &mut state), next); + assert_eq!(state.daif, 0b1111); + assert_eq!(run(MaskWrite::Clear(2), &open, &mut state), next); + assert_eq!(state.daif, 0b1101); + state.x[9] = 0b0011 << 6 | 0b1000 << 6 | 1 << 40; + assert_eq!(run(MaskWrite::Register(9), &open, &mut state), next); + assert_eq!(state.daif, 0b1011); + // An interrupt waits on I. + state.pending = 0b0010; + assert_eq!(run(MaskWrite::Clear(2), &open, &mut state), here); + assert_eq!(state.daif, 0b1011); + assert_eq!(run(MaskWrite::Clear(1), &open, &mut state), next); + assert_eq!(state.daif, 0b1010); + // Masking more is always fine, and D stays with the engine. + assert_eq!(run(MaskWrite::Set(1), &open, &mut state), next); + assert_eq!(run(MaskWrite::Clear(8), &open, &mut state), here); + state.daif = 0b0011; + assert_eq!(run(MaskWrite::Set(8), &open, &mut state), here); + assert_eq!(state.daif, 0b0011); + // Closed, every write is the engine's. + let closed = Cell::default(); + assert_eq!(run(MaskWrite::Set(1), &closed, &mut state), here); + } + + #[test] + fn thunks_end_in_the_fallthrough_then_the_original_exit() { + let pc = GuestAddress(0x4000); + let thunk = thunk(pc, 8, CELL); + let end = thunk.code.len(); + assert_eq!( + thunk.code[end - DIRECT_EXIT_BYTES..], + direct_exit(pc, ExitKind::System) + ); + let next = thunk.next.unwrap(); + assert_eq!(next + DIRECT_EXIT_BYTES, end - DIRECT_EXIT_BYTES); + // Padded for its offset, where a link patches it. + assert_eq!( + thunk.code[next..next + DIRECT_EXIT_BYTES], + crate::x86_64::chain::direct_exit_at( + next as u64, + GuestAddress(0x4004), + ExitKind::Fallthrough + ) + ); + } + + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[repr(C)] + #[derive(Debug, PartialEq, Eq)] + struct Exit { + pc: u64, + kind: u64, + } + + /// Run a thunk on the host. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + fn run(code: &[u8], state: &mut crate::GuestState) -> Exit { + use core::ffi::c_void; + const PAGE: usize = 4096; + let code = super::super::pinned::entered(code); + #[cfg(any(target_os = "macos", target_os = "linux"))] + unsafe { + unsafe extern "C" { + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut c_void, bytes: usize) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANONYMOUS: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANONYMOUS: i32 = 0x20; + let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + assert_eq!(mprotect(page, PAGE, 5), 0); + let exit = crate::x86_64::native::call::(page as *const u8, state, 0, 0); + assert_eq!(munmap(page, PAGE), 0); + exit + } + #[cfg(target_os = "windows")] + unsafe { + unsafe extern "system" { + fn VirtualAlloc( + address: *const c_void, + size: usize, + alloc_type: u32, + protect: u32, + ) -> *mut c_void; + fn VirtualProtect( + address: *const c_void, + size: usize, + new_protect: u32, + old_protect: *mut u32, + ) -> i32; + fn VirtualFree(address: *mut c_void, size: usize, free_type: u32) -> i32; + } + const MEM_COMMIT_RESERVE: u32 = 0x1000 | 0x2000; + const MEM_RELEASE: u32 = 0x8000; + const PAGE_READWRITE: u32 = 0x04; + const PAGE_EXECUTE_READ: u32 = 0x20; + let page = VirtualAlloc(core::ptr::null(), PAGE, MEM_COMMIT_RESERVE, PAGE_READWRITE); + assert!(!page.is_null()); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + let mut old = 0u32; + assert_ne!(VirtualProtect(page, PAGE, PAGE_EXECUTE_READ, &mut old), 0); + let exit = crate::x86_64::native::call::(page as *const u8, state, 0, 0); + assert_ne!(VirtualFree(page, 0, MEM_RELEASE), 0); + exit + } + } + + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + const PC: GuestAddress = GuestAddress(0x4000); + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + const MISS: Exit = Exit { + pc: PC.0, + kind: ExitKind::System as u64, + }; + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + const NEXT: Exit = Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + }; + + /// A thread pointer write runs on the host: with its cell open it writes + /// the storage and every open read cell, logs a switch to another value + /// with the frame and link registers, changes nothing for the same + /// value, and leaves everything to the engine with the cell closed or + /// the log full. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn thread_switches_write_the_register_its_reads_and_the_log() { + use crate::GuestState; + use core::mem::offset_of; + #[repr(C)] + #[derive(Default)] + struct Data { + write: Cell, + storage: u64, + reads: [Cell; 3], + log: SwitchLog, + } + let (pc, miss, next) = (PC, MISS, NEXT); + let mut data = alloc::boxed::Box::new(Data::default()); + let base = &mut *data as *mut Data; + let place = |offset: usize| Place::new(Anchor::Mirrors, offset); + let places = ThreadSwitch { + reads: place(offset_of!(Data, reads)), + stride: size_of::(), + banks: 3, + log: place(offset_of!(Data, log)), + }; + let cell = place(offset_of!(Data, write)); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = base as u64; + state.x[29] = 0xffff_fe00_0000_2900; + state.x[30] = 0xffff_fe00_0000_3000; + let storage = base as u64 + offset_of!(Data, storage) as u64; + // SAFETY: `base` points into the live box; reads and writes happen + // between thunk calls. + let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; + let open = Cell { + readable: 1, + value: 0x1000, + }; + data(&mut |d| { + d.write = Cell { + readable: 0, + value: storage, + }; + d.storage = 0x1000; + d.reads = [open, Cell::default(), open]; + }); + state.x[5] = 0x2000; + let write = thread_switch_thunk(pc, 5, cell, &places); + assert_eq!(run(&write.code, &mut state), miss); + data(&mut |d| assert_eq!((d.storage, d.log.len), (0x1000, 0))); + data(&mut |d| d.write.readable = 1); + assert_eq!(run(&write.code, &mut state), next); + data(&mut |d| { + assert_eq!(d.storage, 0x2000); + let new = Cell { + readable: 1, + value: 0x2000, + }; + assert_eq!(d.reads, [new, Cell::default(), new]); + assert_eq!(d.log.len, 1); + let switch = Switch { + previous: 0x1000, + next: 0x2000, + frame: 0xffff_fe00_0000_2900, + link: 0xffff_fe00_0000_3000, + pc: pc.0, + }; + assert_eq!(d.log.entries[0], switch); + }); + // The same value again: nothing logged. + assert_eq!(run(&write.code, &mut state), next); + data(&mut |d| assert_eq!(d.log.len, 1)); + // XZR, then values until the log is full: the next one exits. + assert_eq!( + run(&thread_switch_thunk(pc, 31, cell, &places).code, &mut state), + next + ); + data(&mut |d| assert_eq!((d.storage, d.log.entries[1].next), (0, 0))); + for value in 2..SWITCHES as u64 { + state.x[5] = value; + assert_eq!(run(&write.code, &mut state), next); + } + data(&mut |d| assert_eq!((d.log.len, d.storage), (SWITCHES as u64, 7))); + state.x[5] = 0x9000; + assert_eq!(run(&write.code, &mut state), miss); + data(&mut |d| { + assert_eq!(d.storage, 7); + assert_eq!(d.reads[0].value, 7); + }); + } + + /// Thunks run on the host: a readable cell completes the read into Xt, + /// or into nothing for XZR; a cleared one exits with no write. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn thunks_read_the_cell_only_while_it_is_readable() { + use crate::GuestState; + let (pc, miss, next) = (PC, MISS, NEXT); + let mut cell = alloc::boxed::Box::new(Cell::default()); + let address = &mut *cell as *mut Cell; + // SAFETY: address points into the live Cell box; the closure runs between thunk calls. + let set = |value: Cell| unsafe { address.write(value) }; + let mut state = GuestState::default(); + state.x[19] = 7; + state.anchors[Anchor::Mirrors] = address as u64; + let read = thunk(pc, 19, CELL); + set(Cell { + readable: 0, + value: 0xffff_fe00_1234_5000, + }); + assert_eq!(run(&read.code, &mut state), miss); + assert_eq!(state.x[19], 7); + set(Cell { + readable: 1, + value: 0xffff_fe00_1234_5000, + }); + assert_eq!(run(&read.code, &mut state), next); + assert_eq!(state.x[19], 0xffff_fe00_1234_5000); + let before = state.x; + assert_eq!(run(&thunk(pc, 31, CELL).code, &mut state), next); + assert_eq!(state.x, before); + } + + /// IC IVAU of the cell's page completes; of another, or with the cell + /// closed, it exits. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn the_code_page_thunk_completes_only_in_the_open_cells_page() { + use crate::GuestState; + let open = Cell { + readable: 1, + value: 0xffff_fe00_1234_5040, + }; + let closed = Cell::default(); + let mut state = GuestState::default(); + for (cell, xt, exit) in [ + (&open, 0xffff_fe00_1234_5fc0, NEXT), + (&open, 0xffff_fe00_1234_6000, MISS), + (&closed, 0xffff_fe00_1234_5fc0, MISS), + ] { + state.x[19] = xt; + state.anchors[Anchor::Mirrors] = cell as *const Cell as u64; + let thunk = code_page_thunk(PC, 19, CELL); + assert_eq!(run(&thunk.code, &mut state), exit); + assert_eq!(state.x[19], xt); + } + } + + #[test] + fn write_thunks_store_the_kept_bits_only_while_the_cell_is_open() { + use crate::GuestState; + let written = Written { + keep: 0xff00, + set: 1, + }; + let mut storage = alloc::boxed::Box::new(0u64); + let target = &mut *storage as *mut u64; + let mut cell = alloc::boxed::Box::new(Cell::default()); + let address = &mut *cell as *mut Cell; + let mut state = GuestState::default(); + state.x[3] = 0xabcd; + state.anchors[Anchor::Mirrors] = address as u64; + let code = stored_write_thunk(PC, 3, CELL, written).code; + assert_eq!(run(&code, &mut state), MISS); + // SAFETY: the live Cell box and the live storage, between runs. + unsafe { + address.write(Cell { + readable: 1, + value: target as u64, + }); + } + assert_eq!(run(&code, &mut state), NEXT); + // SAFETY: as above. + assert_eq!(unsafe { target.read() }, 0xab01); + let zero = stored_write_thunk(PC, 31, CELL, written).code; + assert_eq!(run(&zero, &mut state), NEXT); + // SAFETY: as above. + assert_eq!(unsafe { target.read() }, 1); + let offset = core::mem::offset_of!(GuestState, fpsr); + let frame = frame_write_thunk(PC, 3, CELL, offset, written).code; + assert_eq!(run(&frame, &mut state), NEXT); + assert_eq!(state.fpsr, 0xab01); + } + + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn key_writes_close_only_the_written_key_and_mark_dirty() { + use crate::GuestState; + #[repr(C)] + struct PointerState { + tags: [u64; 5], + dirty: u64, + } + let mut key = alloc::boxed::Box::new(5u64); + let target = &mut *key as *mut u64; + let mut cell = alloc::boxed::Box::new(Cell { + readable: 1, + value: target as u64, + }); + let mut ptr = alloc::boxed::Box::new(PointerState { + tags: [7; 5], + dirty: 0, + }); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &*cell as *const Cell as u64; + state.anchors[Anchor::Pointer] = &mut *ptr as *mut PointerState as u64; + let tag = Place::new(Anchor::Pointer, core::mem::offset_of!(PointerState, tags) + 8); + let dirty = Place::new(Anchor::Pointer, core::mem::offset_of!(PointerState, dirty)); + let code = key_write_thunk(PC, 3, CELL, tag, dirty, 1).code; + state.x[3] = 5; + assert_eq!(run(&code, &mut state), NEXT); + assert_eq!(ptr.tags, [7; 5]); + assert_eq!(ptr.dirty, 0); + state.x[3] = 6; + assert_eq!(run(&code, &mut state), NEXT); + // SAFETY: the live key, between runs. + assert_eq!(unsafe { target.read() }, 6); + assert_eq!(ptr.tags, [7, 0, 7, 7, 7]); + assert_eq!(ptr.dirty, 1 << 1); + ptr.tags[1] = 7; + ptr.dirty = 0; + cell.readable = 0; + state.x[3] = 8; + assert_eq!(run(&code, &mut state), MISS); + // SAFETY: as above. + assert_eq!(unsafe { target.read() }, 6); + assert_eq!(ptr.tags[1], 7); + assert_eq!(ptr.dirty, 0); + } + + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn checked_writes_leave_the_refused_bits_to_the_exit() { + use crate::GuestState; + let mut storage = alloc::boxed::Box::new(5u64); + let target = &mut *storage as *mut u64; + let cell = alloc::boxed::Box::new(Cell { + readable: 1, + value: target as u64, + }); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &*cell as *const Cell as u64; + let code = checked_write_thunk(PC, 3, CELL, 0xf0).code; + state.x[3] = 0x10f; + assert_eq!(run(&code, &mut state), NEXT); + // SAFETY: the live storage, between runs. + assert_eq!(unsafe { target.read() }, 0x10f); + state.x[3] = 0x10; + assert_eq!(run(&code, &mut state), MISS); + // SAFETY: as above. + assert_eq!(unsafe { target.read() }, 0x10f); + let zero = checked_write_thunk(PC, 31, CELL, u64::MAX).code; + assert_eq!(run(&zero, &mut state), NEXT); + // SAFETY: as above. + assert_eq!(unsafe { target.read() }, 0); + } + + #[test] + fn stack_select_moves_the_frame_sp_between_the_stacks() { + use crate::GuestState; + let mut cell = alloc::boxed::Box::new(Cell::default()); + let address = &mut *cell as *mut Cell as u64; + let mut stacks = alloc::boxed::Box::new([0x1000u64, 0x2000]); + let (sp0, spx) = (stacks.as_mut_ptr() as u64, stacks.as_mut_ptr() as u64 + 8); + let mut current = alloc::boxed::Box::new(1u64); + let word = &mut *current as *mut u64 as u64; + let mut state = GuestState { + sp: 0x3000, + ..GuestState::default() + }; + state.anchors[Anchor::Mirrors] = address; + state.anchors[Anchor::Pointer] = word; + state.anchors[Anchor::StackZero] = sp0; + let to_sp0 = stack_select_thunk(PC, false, CELL, WORD, SP0).code; + let to_spx = stack_select_thunk(PC, true, CELL, WORD, SP0).code; + assert_eq!(run(&to_sp0, &mut state), MISS); + cell.readable = 1; + cell.value = spx; + // Cross the box with a raw read: the thunk wrote through addresses. + let read = |at: u64| { + // SAFETY: a live word of `stacks` or `current`. + unsafe { (at as *const u64).read_volatile() } + }; + assert_eq!(run(&to_sp0, &mut state), NEXT); + assert_eq!((state.sp, read(spx), read(word)), (0x1000, 0x3000, 0)); + // Selecting what is selected moves nothing. + assert_eq!(run(&to_sp0, &mut state), NEXT); + assert_eq!((state.sp, read(spx)), (0x1000, 0x3000)); + state.sp = 0x1800; + assert_eq!(run(&to_spx, &mut state), NEXT); + assert_eq!((state.sp, read(sp0), read(word)), (0x3000, 0x1800, 1)); + } + + /// A count read adds the state's offset to the scaled TSC (zero here, + /// as `per_tsc` is), stays at or below its ceiling, never reads below + /// `last` and keeps what it read there, and subtracts the cell's value; + /// XZR still moves `last`. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn count_thunks_read_a_monotonic_bounded_count_less_the_cell_value() { + use crate::GuestState; + use core::sync::atomic::Ordering::Relaxed; + let mut cell = alloc::boxed::Box::new(Cell::default()); + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + last: 50, + state: &*published as *const CountState as u64, + ..Count::default() + }); + let (cell_at, count_at) = (&mut *cell as *mut Cell, &mut *count as *mut Count); + let read = count_thunk(PC, 3, CELL, READER); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = cell_at as u64; + state.anchors[Anchor::Count] = count_at as u64; + assert_eq!(run(&read.code, &mut state), MISS); + // SAFETY: the boxes outlive every thunk run. + unsafe { + cell_at.write(Cell { + readable: 1, + value: 30, + }) + }; + let last = || { + // SAFETY: the Count box is live and every thunk run has returned. + unsafe { (*count_at).last } + }; + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!((state.x[3], last()), (70, 100)); + published.offset.store(80, Relaxed); + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!((state.x[3], last()), (70, 100)); + published.offset.store(500, Relaxed); + published.ceiling.store(300, Relaxed); + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!((state.x[3], last()), (270, 300)); + published.ceiling.store(u64::MAX, Relaxed); + let before = state.x; + let discard = count_thunk(PC, 31, CELL, READER); + assert_eq!(run(&discard.code, &mut state), NEXT); + assert_eq!((state.x, last()), (before, 500)); + } + + #[test] + fn device_loads_name_their_base_offset_and_width() { + // ldr w8, [x9, #0x14]; ldr x0, [x1]; ldrb w2, [x3, #1]; ldrh w4, [x5, #6] + assert_eq!( + DeviceLoad::of(0xb940_1528), + Some(DeviceLoad { + rn: 9, + offset: 0x14, + index: None, + rt: 8, + bytes: 4 + }) + ); + assert_eq!( + DeviceLoad::of(0xf940_0020), + Some(DeviceLoad { + rn: 1, + offset: 0, + index: None, + rt: 0, + bytes: 8 + }) + ); + assert_eq!( + DeviceLoad::of(0x3940_0462), + Some(DeviceLoad { + rn: 3, + offset: 1, + index: None, + rt: 2, + bytes: 1 + }) + ); + assert_eq!( + DeviceLoad::of(0x7940_0ca4), + Some(DeviceLoad { + rn: 5, + offset: 6, + index: None, + rt: 4, + bytes: 2 + }) + ); + // ldur w0, [x1, #-4] + assert_eq!( + DeviceLoad::of(0xb85f_c020), + Some(DeviceLoad { + rn: 1, + offset: -4, + index: None, + rt: 0, + bytes: 4 + }) + ); + // ldr x13, [x11, w13, uxtw]; ldr w0, [x1, x2]; ldr x0, [x1, w2, sxtw #3] + let indexed = |rn, rm, extend, shift, rt, bytes| DeviceLoad { + rn, + offset: 0, + index: Some(DeviceIndex { rm, extend, shift }), + rt, + bytes, + }; + assert_eq!( + DeviceLoad::of(0xf86d_496d), + Some(indexed(11, 13, IndexExtend::Unsigned, 0, 13, 8)) + ); + assert_eq!( + DeviceLoad::of(0xb862_6820), + Some(indexed(1, 2, IndexExtend::Whole, 0, 0, 4)) + ); + assert_eq!( + DeviceLoad::of(0xf862_d820), + Some(indexed(1, 2, IndexExtend::Signed, 3, 0, 8)) + ); + let x = |r: u8| match r { + 1 => 0x1000, + 2 => 0xffff_ffff_ffff_fff0, + 11 => 0x2000, + 13 => 0xffff_ffff_0000_0040, + _ => 0, + }; + assert_eq!(DeviceLoad::of(0xf86d_496d).unwrap().address(x), 0x2040); + assert_eq!( + DeviceLoad::of(0xf862_d820).unwrap().address(x), + 0x1000 - 0x80 + ); + assert_eq!(DeviceLoad::of(0xb85f_c020).unwrap().address(x), 0xffc); + // ldr x0, [sp]; ldrsw x0, [x1]; str w0, [x1]; ldr w0, [x1], #4; + // ldr w0, [x1, xzr]; ldr w0, [x1, w2, uxth] (unallocated) + for other in [ + 0xf940_03e0_u32, + 0xb980_0020, + 0xb900_0020, + 0xb840_4420, + 0xb87f_6820, + 0xb862_2820, + ] { + assert_eq!(DeviceLoad::of(other), None, "{other:#x}"); + } + } + + /// A device read runs on the host: it completes from its slot while the + /// key, site, address, epoch and count all agree, and exits otherwise. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn device_reads_complete_from_their_slot_while_everything_agrees() { + use crate::GuestState; + use core::mem::offset_of; + use core::sync::atomic::Ordering::Relaxed; + #[repr(C)] + struct Data { + key: Cell, + reads: [DeviceRead; DEVICE_READS], + } + const SITE: u64 = 0x8_0000_1234; + let load = DeviceLoad { + rn: 1, + offset: 0x10, + index: None, + rt: 2, + bytes: 4, + }; + let mut data = alloc::boxed::Box::new(Data { + key: Cell::default(), + reads: [DeviceRead::default(); DEVICE_READS], + }); + let base = &mut *data as *mut Data; + let epoch = alloc::boxed::Box::new(AtomicU64::new(7)); + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let places = DeviceReadPlaces { + reads: Place::new(Anchor::Mirrors, offset_of!(Data, reads)), + key: Place::new(Anchor::Mirrors, offset_of!(Data, key)), + count: READER, + }; + let thunk = device_read_thunk(PC, SITE, load, places); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = base as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + state.x[1] = 0xffff_fe00_1000_0000; + let key = device_read_key(3, 1, false); + let slot = device_read_slot(SITE, 0xffff_fe00_1000_0010); + // SAFETY: `base` points into the live box; written between runs. + let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; + assert_eq!(run(&thunk.code, &mut state), MISS); + data(&mut |d| { + d.key = Cell { + readable: 1, + value: key, + }; + d.reads[slot] = DeviceRead { + site: SITE, + address: 0xffff_fe00_1000_0010, + key, + epoch: &*epoch as *const AtomicU64 as u64, + seen: 7, + value: 0xabcd, + until: u64::MAX, + }; + }); + assert_eq!(run(&thunk.code, &mut state), NEXT); + assert_eq!(state.x[2], 0xabcd); + state.x[2] = 0; + // Another address, PAN, key, epoch or a passed deadline exit. + state.x[1] += 8; + assert_eq!(run(&thunk.code, &mut state), MISS); + state.x[1] -= 8; + state.pan = 1; + assert_eq!(run(&thunk.code, &mut state), MISS); + state.pan = 0; + data(&mut |d| d.key.value = device_read_key(4, 1, false)); + assert_eq!(run(&thunk.code, &mut state), MISS); + data(&mut |d| d.key.value = key); + epoch.store(8, Relaxed); + assert_eq!(run(&thunk.code, &mut state), MISS); + epoch.store(7, Relaxed); + data(&mut |d| d.reads[slot].until = 50); + assert_eq!(run(&thunk.code, &mut state), MISS); + data(&mut |d| d.reads[slot].until = 1000); + assert_eq!(run(&thunk.code, &mut state), NEXT); + assert_eq!(state.x[2], 0xabcd); + data(&mut |d| d.reads[slot].site = SITE + 4); + assert_eq!(run(&thunk.code, &mut state), MISS); + data(&mut |d| d.reads[slot].site = SITE); + data(&mut |d| d.key.readable = 0); + assert_eq!(run(&thunk.code, &mut state), MISS); + assert_eq!(state.x[2], 0xabcd); + } + + /// One indexed load site reading a counter of each cluster in turn + /// (`ldr x13, [x11, w13, uxtw]`) completes each from the slot of its + /// own address, the timed one past its deadline exiting. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn indexed_device_reads_keep_a_slot_per_address() { + use crate::GuestState; + use core::mem::offset_of; + use core::sync::atomic::Ordering::Relaxed; + #[repr(C)] + struct Data { + key: Cell, + reads: [DeviceRead; DEVICE_READS], + } + const SITE: u64 = 0x8_0000_2144; + const CLUSTERS: [u64; 2] = [0xffff_fe00_2000_4100, 0xffff_fe00_2004_4100]; + let load = DeviceLoad::of(0xf86d_496d).expect("an indexed load"); + let slots = CLUSTERS.map(|address| device_read_slot(SITE, address + 0x20)); + assert_ne!(slots[0], slots[1]); + let mut data = alloc::boxed::Box::new(Data { + key: Cell::default(), + reads: [DeviceRead::default(); DEVICE_READS], + }); + let base = &mut *data as *mut Data; + let epoch = alloc::boxed::Box::new(AtomicU64::new(7)); + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let places = DeviceReadPlaces { + reads: Place::new(Anchor::Mirrors, offset_of!(Data, reads)), + key: Place::new(Anchor::Mirrors, offset_of!(Data, key)), + count: READER, + }; + let thunk = device_read_thunk(PC, SITE, load, places); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = base as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + let key = device_read_key(3, 1, false); + // SAFETY: `base` points into the live box; written between runs. + let data = |f: &mut dyn FnMut(&mut Data)| unsafe { f(&mut *base) }; + data(&mut |d| { + d.key = Cell { + readable: 1, + value: key, + }; + for (cluster, (&slot, &address)) in slots.iter().zip(&CLUSTERS).enumerate() { + d.reads[slot] = DeviceRead { + site: SITE, + address: address + 0x20, + key, + epoch: &*epoch as *const AtomicU64 as u64, + seen: 7, + value: 0x100 + cluster as u64, + until: if cluster == 0 { u64::MAX } else { 1000 }, + }; + } + }); + for _ in 0..2 { + for (cluster, &address) in CLUSTERS.iter().enumerate() { + state.x[11] = address; + state.x[13] = 0xdead_0000_0000_0020; + assert_eq!(run(&thunk.code, &mut state), NEXT); + assert_eq!(state.x[13], 0x100 + cluster as u64); + } + } + // Another index, or the timed cluster past its deadline, exits. + state.x[11] = CLUSTERS[0]; + state.x[13] = 0x28; + assert_eq!(run(&thunk.code, &mut state), MISS); + data(&mut |d| d.reads[slots[1]].until = 50); + state.x[11] = CLUSTERS[1]; + state.x[13] = 0x20; + assert_eq!(run(&thunk.code, &mut state), MISS); + state.x[11] = CLUSTERS[0]; + assert_eq!(run(&thunk.code, &mut state), NEXT); + assert_eq!(state.x[13], 0x100); + } + + /// What the event thunks of these tests find at [`Anchor::Mirrors`]. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[repr(C)] + #[derive(Default)] + struct Waits { + events: Cell, + waits: Cell, + monitor: u64, + lines_until: u64, + spin: EventSpin, + stream: EventStream, + } + + /// The event thunks of these tests, and their words: an event register, + /// a control and a count that `per_tsc` moves (0 holds it at 100). + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + struct Events { + send: Thunk, + wait: Thunk, + event: alloc::boxed::Box, + waits: alloc::boxed::Box, + control: alloc::boxed::Box, + _published: alloc::boxed::Box, + count: alloc::boxed::Box, + state: crate::GuestState, + } + + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + impl Events { + fn new(per_tsc: u64) -> Self { + use core::mem::offset_of; + use core::sync::atomic::Ordering::Relaxed; + let place = |offset: usize| Place::new(Anchor::Mirrors, offset); + let events = place(offset_of!(Waits, events)); + let places = EventWaitPlaces { + events, + waits: place(offset_of!(Waits, waits)), + monitor: place(offset_of!(Waits, monitor)), + control: Place::new(Anchor::Control, 0), + lines_until: place(offset_of!(Waits, lines_until)), + count: READER, + spin: place(offset_of!(Waits, spin)), + stream: place(offset_of!(Waits, stream)), + }; + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut events = Self { + send: send_event_thunk(PC, events), + wait: event_wait_thunk(PC, places), + event: alloc::boxed::Box::default(), + waits: alloc::boxed::Box::default(), + control: alloc::boxed::Box::default(), + count: alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + per_tsc, + ..Count::default() + }), + _published: published, + state: crate::GuestState::default(), + }; + let anchors = &mut events.state.anchors; + anchors[Anchor::Mirrors] = &mut *events.waits as *mut Waits as u64; + anchors[Anchor::Control] = + &mut *events.control as *mut crate::x86_64::chain::ChainControl as u64; + anchors[Anchor::Count] = &mut *events.count as *mut Count as u64; + events + } + + fn open(&mut self) { + self.waits.events = Cell { + readable: 1, + value: &*self.event as *const core::sync::atomic::AtomicU8 as u64, + }; + } + + fn wait(&mut self) -> Exit { + run(&self.wait.code, &mut self.state) + } + + /// Run the WFE while another thread does `act` once the spin began, + /// if it began and that thread sees it before the WFE returns. + fn wait_while(&mut self, act: impl FnOnce(&Self) + Send) -> Exit { + use core::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst}; + self.waits.spin.turns = 0; + let turns = &raw const self.waits.spin.turns as usize; + let this = self as *mut Self as usize; + let returned = AtomicBool::new(false); + std::thread::scope(|scope| { + let returned = &returned; + scope.spawn(move || { + // SAFETY: the spin's word, which the thunk writes with + // aligned stores while this thread reads it atomically. + let turns = unsafe { AtomicU64::from_ptr(turns as *mut u64) }; + while turns.load(SeqCst) == 0 && !returned.load(SeqCst) { + core::hint::spin_loop(); + } + if !returned.load(SeqCst) { + // SAFETY: the words `act` touches are atomics or + // ones the thunk only reads. + act(unsafe { &*(this as *const Self) }); + } + }); + // SAFETY: `act` touches no word the thunk writes. + let exit = unsafe { (*(this as *mut Self)).wait() }; + returned.store(true, SeqCst); + exit + }) + } + } + + /// SEVL sets the event register; WFE clears a set one and completes, and + /// leaves a clear one, or a closed cell, to the engine where it waits + /// otherwise than by spinning. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn event_thunks_set_and_consume_the_event_register() { + use core::sync::atomic::Ordering::Relaxed; + let mut events = Events::new(0); + assert_eq!(run(&events.send.code, &mut events.state), MISS); + events.open(); + assert_eq!(events.wait(), MISS); + assert_eq!(run(&events.send.code, &mut events.state), NEXT); + assert_eq!(events.event.load(Relaxed), 1); + assert_eq!(events.wait(), NEXT); + assert_eq!(events.event.load(Relaxed), 0); + assert_eq!(events.wait(), MISS); + assert_eq!(events.waits.spin, EventSpin::default(), "no spin"); + } + + /// With the register clear, an event stream edge at or before the count + /// (held at 100) completes the WFE, before a monitor or a trap is + /// looked at: the sample moves to the count and the next edge to the + /// first one past it. Without one, the WFE goes on as before. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn event_waits_take_a_stream_edge_since_the_sample() { + let mut events = Events::new(0); + events.open(); + events.waits.monitor = 1; + assert_eq!(events.wait(), MISS, "no stream"); + for (next, after) in [(100, 108), (60, 108), (93, 101)] { + events.waits.stream = EventStream { + next, + period: 8, + sampled: 7, + }; + assert_eq!(events.wait(), NEXT, "{next}"); + let stream = events.waits.stream; + assert_eq!((stream.next, stream.sampled), (after, 100), "{next}"); + // The edge is taken: the next WFE finds none. + assert_eq!(events.wait(), MISS, "{next}"); + } + assert_eq!(events.waits.spin.streamed, 3); + events.waits.stream.next = 101; + assert_eq!(events.wait(), MISS); + assert_eq!(events.waits.stream.sampled, 100); + // Edges without a period: one is taken, the next is the engine's. + events.waits.stream = EventStream { + next: 99, + period: 0, + sampled: 7, + }; + assert_eq!(events.wait(), NEXT); + assert_eq!(events.waits.stream.next, u64::MAX); + assert_eq!(events.wait(), MISS); + assert_eq!(events.waits.spin.streamed, 4); + } + + /// Where the WFE would wait, a clear event register makes it spin: it + /// exits at once with an interrupt waiting, anything posted or the count + /// at `lines_until`, counting nothing, and with a monitor held, counting + /// that; a spin ends after [`WFE_SPIN_COUNTS`] of the count, or its + /// turns where the count holds, counting a miss and the counts spent. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn event_waits_spin_only_while_nothing_else_wakes_them() { + let mut events = Events::new(0); + events.open(); + events.waits.waits.readable = 1; + events.waits.lines_until = u64::MAX; + let quiet = EventSpin::default(); + events.state.pending = 0b10; + assert_eq!(events.wait(), MISS); + events.state.pending = 0; + events.control.interrupt_epoch = 1; + assert_eq!(events.wait(), MISS); + events.control.observed_interrupt_epoch = 1; + // The count holds at 100. + events.waits.lines_until = 100; + assert_eq!(events.wait(), MISS); + assert_eq!(events.waits.spin, quiet, "no spin"); + events.waits.lines_until = 101; + events.waits.monitor = 1; + events.state.exclusive_bytes = 8; + assert_eq!(events.wait(), MISS); + assert_eq!(events.waits.spin.held, 1); + events.waits.monitor = 0; + for step in 0..WFE_HELD_SPIN_MAX { + assert_eq!(events.wait(), NEXT, "held spin step {step}"); + assert_eq!(events.state.exclusive_bytes, 8); + } + assert_eq!(events.waits.spin.held_streak, WFE_HELD_SPIN_MAX as u64); + assert_eq!(events.waits.spin.held_completed, WFE_HELD_SPIN_MAX as u64); + assert_eq!(events.waits.spin.held, 1); + assert_eq!(events.wait(), MISS, "17th held WFE exits to Rust"); + assert_eq!((events.waits.spin.held, events.waits.spin.missed), (2, 0)); + events.state.exclusive_bytes = 0; + // A held count: the turns end the spin, none counted. + assert_eq!(events.wait(), MISS); + let spin = events.waits.spin; + assert_eq!((spin.missed, spin.counts, spin.turns), (1, 0, 0)); + // A count at half the TSC's rate: the counts end it. + let mut events = Events::new(1 << 63); + events.open(); + events.waits.waits.readable = 1; + events.waits.lines_until = u64::MAX; + assert_eq!(events.wait(), MISS); + let spin = events.waits.spin; + assert_eq!((spin.completed, spin.missed), (0, 1)); + assert!(spin.counts >= u64::from(WFE_SPIN_COUNTS), "{spin:?}"); + assert_ne!(spin.turns, 0, "{spin:?}"); + } + + /// Another PE's event during the spin completes the WFE, consuming the + /// register; a notification during it ends it. Each runs until the + /// other thread acted during a spin, which a scheduler may delay. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn event_waits_complete_on_an_event_set_during_the_spin() { + use core::sync::atomic::{AtomicU64, Ordering::Relaxed}; + let mut events = Events::new(0); + events.open(); + events.waits.waits.readable = 1; + events.waits.lines_until = u64::MAX; + let completed = (0..100).any(|_| { + let exit = events.wait_while(|events| events.event.store(1, Relaxed)); + events.event.store(0, Relaxed); + exit == NEXT + }); + assert!(completed); + assert_eq!(events.waits.spin.completed, 1); + let missed = events.waits.spin.missed; + let ended = (0..100).any(|_| { + let before = events.waits.spin.missed; + let epoch = &raw const events.control.interrupt_epoch as usize; + assert_eq!( + events.wait_while(move |_| { + // SAFETY: the control's epoch, which the thunk reads. + unsafe { AtomicU64::from_ptr(epoch as *mut u64) }.fetch_add(1, Relaxed); + }), + MISS + ); + let observed = events.control.interrupt_epoch; + events.control.observed_interrupt_epoch = observed; + events.waits.spin.missed == before + 1 && events.waits.spin.turns != 0 + }); + assert!(ended); + assert!(events.waits.spin.missed > missed); + } + + /// An energy read scales the ticks of the count since the origin, none + /// before it, and leaves a reading too wide for 64 bits to the engine. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn energy_thunks_scale_the_ticks_since_the_origin() { + use crate::GuestState; + use core::sync::atomic::Ordering::Relaxed; + let mut energy = alloc::boxed::Box::new(Energy { + origin: 40, + scale: 3_000, + frequency: 24, + }); + let mut cell = alloc::boxed::Box::new(Cell { + readable: 1, + value: &mut *energy as *mut Energy as u64, + }); + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let read = energy_thunk(PC, 3, CELL, READER); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &mut *cell as *mut Cell as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], 60 * 3_000 / 24); + energy.origin = 200; + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], 0); + energy.origin = 0; + energy.scale = u64::MAX; + energy.frequency = 50; + assert_eq!(run(&read.code, &mut state), MISS); + } + + /// A cycle counter read takes an open cell's value; with the cell + /// closed but the read plain it computes the count as + /// [`CycleCounter::at`] does, carrying the remainder and wrapping to the + /// mask, and opens the cell on it; anything else, and a quotient too + /// wide, exits with Xt untouched. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn cycle_counter_thunks_compute_the_count_where_only_the_value_went_stale() { + use crate::GuestState; + use core::sync::atomic::Ordering::Relaxed; + #[repr(C)] + struct Cells { + cell: Cell, + plain: Cell, + cycles: CycleCounter, + } + const PLAIN: Place = Place::new(Anchor::Mirrors, size_of::()); + const CYCLES: Place = Place::new(Anchor::Mirrors, 2 * size_of::()); + let mut cells = alloc::boxed::Box::new(Cells { + cell: Cell::default(), + plain: Cell::default(), + cycles: CycleCounter { + open: 1, + counter: 1_000, + synced: 90, + remainder: 2, + clock: 7, + frequency: 3, + mask: u64::MAX >> 16, + overflow: 0, + clocks: [0; crate::x86_64::transition::STATES], + }, + }); + let published = alloc::boxed::Box::new(CountState::default()); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let read = cycle_counter_thunk(PC, 3, CELL, PLAIN, CYCLES, READER); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &mut *cells as *mut Cells as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + // The reader never reads below its last count: each read starts + // afresh at `now`. + let reader = &mut *count as *mut Count; + let run_at = |_: &mut Cells, now: u64, state: &mut GuestState| { + published.offset.store(now, Relaxed); + // SAFETY: the test's reader, which no thunk runs over meanwhile. + unsafe { (*reader).last = 0 }; + run(&read.code, state) + }; + // Closed and not plain: the engine. + state.x[3] = 0xdead; + assert_eq!(run_at(&mut cells, 100, &mut state), MISS); + assert_eq!(state.x[3], 0xdead); + // Plain: (10 * 7 + 2) / 3 = 24 cycles past 1000, the cell opens. + cells.plain.readable = 1; + assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); + assert_eq!(state.x[3], 1_024); + assert_eq!(cells.cycles.at(100), Some(1_024)); + assert_eq!( + cells.cell, + Cell { + readable: 1, + value: 1_024 + } + ); + // Open: its value until the cell closes again. + assert_eq!(run_at(&mut cells, 400, &mut state), NEXT); + assert_eq!(state.x[3], 1_024); + cells.cell.readable = 0; + for now in [0, 89, 90, 91, 92, 400, 1 << 40] { + assert_eq!(run_at(&mut cells, now, &mut state), NEXT, "{now}"); + assert_eq!(Some(state.x[3]), cells.cycles.at(now), "{now}"); + cells.cell.readable = 0; + } + // Wrapped to the counter's width. + cells.cycles.counter = u64::MAX >> 16; + assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); + assert_eq!(state.x[3], 23); + cells.cell.readable = 0; + // Not counting: the count as it stands. + cells.cycles.clock = 0; + assert_eq!(run_at(&mut cells, 1 << 40, &mut state), NEXT); + assert_eq!(state.x[3], u64::MAX >> 16); + cells.cell.readable = 0; + // Too wide for one division, and the monitor's view closed. + cells.cycles.clock = u64::MAX; + state.x[3] = 0xdead; + assert_eq!(run_at(&mut cells, u64::MAX, &mut state), MISS); + assert_eq!(cells.cycles.at(u64::MAX), None); + cells.cycles.clock = 7; + cells.cycles.open = 0; + assert_eq!(run_at(&mut cells, 100, &mut state), MISS); + assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); + cells.cycles.open = 1; + cells.cycles.counter = 1_000; + // With the PMI armed, a count below the overflow bit completes and + // one that reaches it exits for the engine to raise the PMI: past + // 1000, (448 * 7 + 2) / 3 = 1046 cycles at 538 stay below bit 11, + // 1048 at 539 reach it; so does the last count below the width's + // top bit, 21 cycles at 99, and not the first at it, 24 at 100. + cells.cycles.overflow = 1 << 11; + cells.cell.readable = 0; + assert_eq!(run_at(&mut cells, 100, &mut state), NEXT); + assert_eq!(state.x[3], 1_024); + cells.cell.readable = 0; + assert_eq!(run_at(&mut cells, 538, &mut state), NEXT); + assert_eq!(state.x[3], 2_046); + assert_eq!(cells.cycles.at(538), Some(2_046)); + cells.cell.readable = 0; + state.x[3] = 0xdead; + assert_eq!(cells.cycles.at(539), None); + assert_eq!(run_at(&mut cells, 539, &mut state), MISS); + assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); + cells.cycles.overflow = 1 << 47; + cells.cycles.counter = (1 << 47) - 24; + assert_eq!(run_at(&mut cells, 99, &mut state), NEXT); + assert_eq!(state.x[3], (1 << 47) - 3); + cells.cell.readable = 0; + state.x[3] = 0xdead; + assert_eq!(run_at(&mut cells, 100, &mut state), MISS); + cells.cycles.overflow = 0; + // XZR discards it but the cell still opens. + cells.cycles.open = 1; + cells.cycles.counter = 1_000; + let discard = cycle_counter_thunk(PC, 31, CELL, PLAIN, CYCLES, READER); + published.offset.store(100, Relaxed); + // SAFETY: as above. + unsafe { (*reader).last = 0 }; + assert_eq!(run(&discard.code, &mut state), NEXT); + assert_eq!((state.x[3], cells.cell.value), (0xdead, 1_024)); + } + + /// An instruction counter read takes an open cell's value; with the + /// cell closed but the read plain it adds the chain's retired count and + /// the instructions before it in its block to the base, as + /// [`InstructionCounter::at`] does, wrapping to the mask, and opens the + /// cell on it; anything else exits with Xt untouched. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn instruction_counter_thunks_add_what_native_code_retired() { + use crate::GuestState; + use crate::x86_64::chain::Account; + #[repr(C)] + struct Cells { + cell: Cell, + plain: Cell, + counter: InstructionCounter, + } + const PLAIN: Place = Place::new(Anchor::Mirrors, size_of::()); + const COUNTER: Place = Place::new(Anchor::Mirrors, 2 * size_of::()); + let mut cells = alloc::boxed::Box::new(Cells { + cell: Cell::default(), + plain: Cell::default(), + counter: InstructionCounter { + open: 1, + base: 1_000, + step: u64::MAX, + mask: u64::MAX >> 16, + overflow: 0, + steps: [0; crate::x86_64::transition::STATES], + }, + }); + let read = instruction_counter_thunk(PC, 3, CELL, PLAIN, COUNTER, 5).unwrap(); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &mut *cells as *mut Cells as u64; + // A budget beside the instructions, which the read leaves out. + state.account = Account::new(3).with_retired(40).0; + let set_retired = |state: &mut GuestState, retired: u64| { + state.account = Account(state.account).with_retired(retired).0; + }; + // Closed and not plain: the engine. + state.x[3] = 0xdead; + assert_eq!(run(&read.code, &mut state), MISS); + assert_eq!(state.x[3], 0xdead); + // Plain: 40 chained and 5 before it past 1000, the cell opens. + cells.plain.readable = 1; + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], 1_045); + assert_eq!(cells.counter.at(45), Some(1_045)); + assert_eq!( + cells.cell, + Cell { + readable: 1, + value: 1_045 + } + ); + // Open: its value until the cell closes again. + set_retired(&mut state, 400); + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], 1_045); + cells.cell.readable = 0; + for retired in [0, 1, 400, (1 << 47) - 1] { + set_retired(&mut state, retired); + assert_eq!(run(&read.code, &mut state), NEXT, "{retired}"); + assert_eq!(Some(state.x[3]), cells.counter.at(retired + 5), "{retired}"); + cells.cell.readable = 0; + } + // Wrapped to the counter's width. + set_retired(&mut state, 0); + cells.counter.base = u64::MAX >> 16; + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], 4); + cells.cell.readable = 0; + // Not counting: the count as it stands. + cells.counter.step = 0; + set_retired(&mut state, (1 << 47) - 1); + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], u64::MAX >> 16); + cells.cell.readable = 0; + // The monitor's view closed. + cells.counter.open = 0; + state.x[3] = 0xdead; + assert_eq!(run(&read.code, &mut state), MISS); + assert_eq!(cells.counter.at(0), None); + assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); + // XZR discards it but the cell still opens; the first instruction + // of its block adds no immediate. + cells.counter = InstructionCounter { + open: 1, + base: 1_000, + step: u64::MAX, + mask: u64::MAX, + overflow: 0, + steps: [0; crate::x86_64::transition::STATES], + }; + set_retired(&mut state, 7); + let discard = instruction_counter_thunk(PC, 31, CELL, PLAIN, COUNTER, 0).unwrap(); + assert!(discard.code.len() < read.code.len()); + assert_eq!(run(&discard.code, &mut state), NEXT); + assert_eq!((state.x[3], cells.cell.value), (0xdead, 1_007)); + // With the PMI armed on the top bit, the last count below it + // completes and the first at it exits for the engine to raise the + // PMI, Xt and the cell untouched. + cells.counter.overflow = 1 << 63; + cells.counter.base = (1 << 63) - 13; + cells.cell.readable = 0; + set_retired(&mut state, 7); + assert_eq!(run(&read.code, &mut state), NEXT); + assert_eq!(state.x[3], (1 << 63) - 1); + assert_eq!(cells.counter.at(12), Some((1 << 63) - 1)); + cells.cell.readable = 0; + set_retired(&mut state, 8); + state.x[3] = 0xdead; + assert_eq!(cells.counter.at(13), None); + assert_eq!(run(&read.code, &mut state), MISS); + assert_eq!((state.x[3], cells.cell.readable), (0xdead, 0)); + } + + /// ISR_EL1 reads the waiting I and F masks as bits 7 and 6 while the + /// cell is open, the epoch is the cell's and the count is below its + /// deadline, and leaves every other case, Xt untouched, to the engine. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn interrupt_status_thunks_read_the_waiting_lines_while_nothing_changed() { + use crate::GuestState; + use core::sync::atomic::Ordering::Relaxed; + const EPOCH: Place = Place::new(Anchor::Control, 0); + let mut cell = alloc::boxed::Box::new(Cell::default()); + let mut epoch = alloc::boxed::Box::new(7u64); + let published = alloc::boxed::Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &mut *cell as *mut Cell as u64; + state.anchors[Anchor::Control] = &mut *epoch as *mut u64 as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + let read = interrupt_status_thunk(PC, 5, CELL, EPOCH, READER).code; + let mut expect = |cell_now: Cell, pending: u32, exit: Exit, x5: u64| { + *cell = cell_now; + state.pending = pending; + state.x[5] = 0xdead; + assert_eq!(run(&read, &mut state), exit, "{cell_now:?} {pending:#x}"); + assert_eq!(state.x[5], x5, "{cell_now:?} {pending:#x}"); + }; + let open = |deadline: u64, value: u64| Cell { + readable: deadline, + value, + }; + // No deadline: no count is read, every mask combination reads. + for (pending, isr) in [(0, 0), (0b01, 0x40), (0b10, 0x80), (0b11, 0xc0)] { + expect(open(u64::MAX, 7), pending, NEXT, isr); + } + // The count (100: `per_tsc` is 0) is below 101, not below 100. + expect(open(101, 7), 0b10, NEXT, 0x80); + expect(open(100, 7), 0b10, MISS, 0xdead); + // Closed, or a line changed since: the engine reads. + expect(Cell::default(), 0b01, MISS, 0xdead); + expect(open(u64::MAX, 6), 0b01, MISS, 0xdead); + *epoch = 6; + expect(open(u64::MAX, 6), 0b01, NEXT, 0x40); + // XZR reads nothing. + let discard = interrupt_status_thunk(PC, 31, CELL, EPOCH, READER).code; + let before = state.x; + assert_eq!(run(&discard, &mut state), NEXT); + assert_eq!(state.x, before); + } + + /// Timer thunks run on the host against a count the test moves: writes + /// that keep the output low complete into storage, one that arms a + /// compare before `lines_until` pulling it and an open ISR_EL1 cell's + /// deadline down to the compare; every other write exits with storage + /// as it was, and CTL reads give ENABLE and IMASK as stored with + /// ISTATUS from the count. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn timer_thunks_complete_only_writes_that_raise_nothing_before_the_engine_looks() { + use crate::GuestState; + use core::mem::offset_of; + use core::sync::atomic::Ordering::Relaxed; + #[repr(C)] + #[derive(Default)] + struct Timer { + compare: Cell, + control: Cell, + cval: u64, + ctl: u64, + lines_until: u64, + status: Cell, + quiet: Cell, + } + const ENABLE: u64 = 1; + const IMASK: u64 = 2; + const ISTATUS: u64 = 4; + let place = |offset: usize| Place::new(Anchor::Mirrors, offset); + let places = TimerPlaces { + compare: place(offset_of!(Timer, compare)), + control: place(offset_of!(Timer, control)), + lines_until: place(offset_of!(Timer, lines_until)), + interrupt_status: place(offset_of!(Timer, status)), + count: READER, + quiet: place(offset_of!(Timer, quiet)), + }; + let mut timer = alloc::boxed::Box::new(Timer::default()); + let base = &mut *timer as *mut Timer; + let published = alloc::boxed::Box::new(CountState::default()); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = alloc::boxed::Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = base as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + let (cval_at, ctl_at) = ( + base as u64 + offset_of!(Timer, cval) as u64, + base as u64 + offset_of!(Timer, ctl) as u64, + ); + // SAFETY: `base` points into the live box; every access happens + // between thunk runs. + let data = |f: &mut dyn FnMut(&mut Timer)| unsafe { f(&mut *base) }; + let open = |d: &mut Timer| { + d.compare = Cell { + readable: 1, + value: cval_at, + }; + d.control = Cell { + readable: 1, + value: ctl_at, + }; + }; + data(&mut |d| open(d)); + let keep = Written { + keep: ENABLE | IMASK | ISTATUS, + set: 0, + }; + let (value, compare) = ( + timer_thunk(PC, 5, TimerAccess::WriteValue, places).code, + timer_thunk(PC, 5, TimerAccess::WriteCompare, places).code, + ); + let control = timer_thunk(PC, 5, TimerAccess::WriteControl(keep), places).code; + // The frame's waiting interrupts before each run and after it. + let pending = core::cell::Cell::new(0u32); + // count, lines_until, (cval, ctl) before, the thunk, Xt, the exit + // and (cval, ctl) after. + let mut expect = |now: u64, + until: u64, + before: (u64, u64), + code: &[u8], + xt: u64, + exit: Exit, + after: (u64, u64)| { + published.offset.store(now, Relaxed); + data(&mut |d| { + (d.cval, d.ctl) = before; + d.lines_until = until; + }); + state.x[5] = xt; + state.pending = pending.get(); + let ran = run(code, &mut state); + pending.set(state.pending); + data(&mut |d| { + assert_eq!( + (ran.pc, d.cval, d.ctl), + (exit.pc, after.0, after.1), + "now {now} until {until} before {before:?} xt {xt:#x}" + ); + }); + assert_eq!(state.x[5], xt, "a write leaves Xt"); + }; + let armed = (200, ENABLE); + // TVAL: count plus the sign-extended low word. 180 is past 150. + expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); + expect( + 100, + 150, + armed, + &value, + 0xdead_0000_0000_0050, + NEXT, + (180, ENABLE), + ); + // Earlier than the engine looks again: completes and pulls its + // deadlines down to the compare, an open ISR_EL1 cell's only. + for (status, pulled) in [(150, 130), (0, 0), (120, 120)] { + data(&mut |d| d.status.readable = status); + expect(100, 150, armed, &value, 30, NEXT, (130, ENABLE)); + data(&mut |d| { + assert_eq!((d.lines_until, d.status.readable), (130, pulled)); + }); + } + data(&mut |d| d.status.readable = 0); + // A later one leaves them. + expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); + data(&mut |d| assert_eq!(d.lines_until, 150)); + // Due at once, or already past: exit. + expect(100, 150, armed, &value, 0, MISS, armed); + expect(100, 150, armed, &value, 0xffff_fff6, MISS, armed); + // CVAL: at lines_until itself completes. + expect(100, 150, armed, &compare, 150, NEXT, (150, ENABLE)); + expect(100, 150, armed, &compare, 149, NEXT, (149, ENABLE)); + data(&mut |d| assert_eq!(d.lines_until, 149)); + // The output is high (armed and past its compare): with `quiet` + // closed every write exits. + expect(100, 150, (90, ENABLE), &compare, 500, MISS, (90, ENABLE)); + expect(100, 150, (90, ENABLE), &control, 0, MISS, (90, ENABLE)); + // With it open, a write that lowers the line completes and leaves + // the FIQ it raised no longer waiting; one that keeps it high exits + // with the FIQ still waiting. + data(&mut |d| { + d.quiet = Cell { + readable: 1, + value: 0b10, + } + }); + for (code, xt, after) in [ + (&compare, 500, (500, ENABLE)), + (&value, 30, (130, ENABLE)), + (&control, 0, (90, 0)), + (&control, ENABLE | IMASK, (90, ENABLE | IMASK)), + (&compare, 95, (90, ENABLE)), + (&control, ENABLE, (90, ENABLE)), + ] { + pending.set(0b11); + let lowers = after != (90, ENABLE); + let exit = if lowers { NEXT } else { MISS }; + expect(100, 150, (90, ENABLE), code, xt, exit, after); + assert_eq!(pending.get(), if lowers { 0b10 } else { 0b11 }); + } + data(&mut |d| d.quiet = Cell::default()); + pending.set(0); + // Masked or disabled, any compare completes and arms nothing. + expect( + 100, + 150, + (90, ENABLE | IMASK), + &compare, + 120, + NEXT, + (120, ENABLE | IMASK), + ); + expect(100, 150, (90, 0), &value, 5, NEXT, (105, 0)); + // CTL: disabling or masking completes; ISTATUS and RES0 bits as the + // register takes them. + expect( + 100, + 150, + armed, + &control, + !ENABLE, + NEXT, + (200, IMASK | ISTATUS), + ); + expect(100, 150, armed, &control, 0, NEXT, (200, 0)); + // Unmasking an expired compare raises the line: exit. + expect( + 100, + 150, + (90, ENABLE | IMASK), + &control, + ENABLE, + MISS, + (90, ENABLE | IMASK), + ); + // Enabling arms the stored compare, before lines_until pulling it. + expect(100, 150, (120, 0), &control, ENABLE, NEXT, (120, ENABLE)); + data(&mut |d| assert_eq!(d.lines_until, 120)); + expect(100, 150, (160, 0), &control, ENABLE, NEXT, (160, ENABLE)); + // No count named (0): every write exits; none (MAX): a write that + // arms a compare names it. + expect(100, 0, armed, &control, 0, MISS, armed); + expect(100, u64::MAX, armed, &control, 0, NEXT, (200, 0)); + expect( + 100, + u64::MAX, + armed, + &value, + 1 << 20, + NEXT, + (100 + (1 << 20), ENABLE), + ); + data(&mut |d| assert_eq!(d.lines_until, 100 + (1 << 20))); + expect( + 100, + u64::MAX, + (200, 0), + &value, + 1 << 20, + NEXT, + (100 + (1 << 20), 0), + ); + // Closed cells: the engine's. + for closed in [offset_of!(Timer, compare), offset_of!(Timer, control)] { + data(&mut |d| { + open(d); + // SAFETY: `closed` is the offset of a Cell field of `d`. + unsafe { (*((d as *mut Timer as *mut u8).add(closed) as *mut Cell)).readable = 0 }; + }); + expect(100, 150, armed, &control, 0, MISS, armed); + } + data(&mut |d| open(d)); + // The count passes the new compare right after the thunk read it: + // the native ISR read the engine left open until lines_until (150) + // exits there, before the compare (180) the line now rises at. + expect(100, 150, armed, &value, 80, NEXT, (180, ENABLE)); + published.offset.store(180, Relaxed); + let mut status = Cell { + readable: 150, + value: 0, + }; + let mut epoch = 0u64; + let mut isr_state = GuestState::default(); + isr_state.anchors[Anchor::Mirrors] = &mut status as *mut Cell as u64; + isr_state.anchors[Anchor::Control] = &mut epoch as *mut u64 as u64; + isr_state.anchors[Anchor::Count] = state.anchors[Anchor::Count]; + let isr = interrupt_status_thunk(PC, 5, CELL, Place::new(Anchor::Control, 0), READER); + assert_eq!(run(&isr.code, &mut isr_state), MISS); + // CTL reads: all eight ENABLE, IMASK and count cases, and a stored + // ISTATUS bit is never what the read gives. + let read = timer_thunk(PC, 7, TimerAccess::ReadControl, places).code; + let mut now = 180; + for ctl in 0..8u64 { + for past in [false, true] { + now += 10; + published.offset.store(now, Relaxed); + let cval = if past { now } else { now + 1 }; + data(&mut |d| (d.cval, d.ctl) = (cval, ctl)); + state.x[7] = 0xdead; + assert_eq!(run(&read, &mut state), NEXT); + let status = if ctl & ENABLE != 0 && past { + ISTATUS + } else { + 0 + }; + assert_eq!(state.x[7], ctl & !ISTATUS | status, "ctl {ctl} past {past}"); + data(&mut |d| assert_eq!((d.cval, d.ctl), (cval, ctl))); + } + } + let discard = timer_thunk(PC, 31, TimerAccess::ReadControl, places).code; + let before = state.x; + assert_eq!(run(&discard, &mut state), NEXT); + assert_eq!(state.x, before); + } +} diff --git a/crates/stela-compiler/src/x86_64/table_switch.rs b/crates/stela-compiler/src/x86_64/table_switch.rs index fb7e26fb21..b09baf19bf 100644 --- a/crates/stela-compiler/src/x86_64/table_switch.rs +++ b/crates/stela-compiler/src/x86_64/table_switch.rs @@ -1,462 +1,464 @@ -//! Native completion of a TTBR0 write that switches the PE to another -//! address space the engine and the host both keep. -//! -//! An MSR TTBR0 ends its block with a System exit. The thunk the engine -//! installs over it completes a write of the value the register holds as -//! [`super::register_read::unchanged_write_thunk`] does, and a write of -//! another value when the PE's [`Table`] holds an [`Entry`] for that value, -//! of the table's generation, made in the state the PE is in (its upper -//! half's lookup context is the entry's `upper`). Where the host keeps root -//! sets ([`Sets`]), the entry's set must also be open, of the generation -//! the entry names and of the class of the set the current CR3 belongs to: -//! the same rights and lower TCR fields, so the set differs from the -//! current one in TTBR0 alone. -//! -//! On a hit the thunk publishes the entry's translating word where the PE -//! publishes one (the regime and ASID other PEs' TLBIs test, as -//! `Machine::publish_translating` does), and if that changed it and mail is -//! then pending, takes the original exit: the engine reads the mail before -//! the new context is used. Otherwise it writes the register, the lower -//! half's ITLB context and salt, closes the cells a translation change -//! closes (`closes`), moves the transition records' contexts generation -//! (records continue only once the engine gave them contexts again), counts -//! the switch for the engine, which settles the rest at its next exit, and -//! loads CR3 with the target set's root of the view the current CR3 is of: -//! in that view's PCID, without the no-flush bit while the view's stale -//! byte is set, which it clears and counts. Where the host isolates predictions -//! between contexts it issues IBPB and refills the return stack, as the -//! engine's exit would. It clobbers RAX, RCX, RDX, R8, R9 and flags, which -//! no exit keeps live. -use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, ShiftOp, Size}; -use super::pointer::Thunk; -use super::register_read::Written; -use crate::{GuestAddress, Place, block::ExitKind}; -use alloc::vec::Vec; -use core::mem::offset_of; - -/// The views a set has a root for: four permission views, unchecked and -/// tag-checked. -pub const SET_ROOTS: usize = 8; -/// The root sets a host keeps. -pub const SETS: usize = 40; -/// The PCID of set `s`'s view `v` is `FIRST_CONTEXT + s * SET_ROOTS + v`. -pub const FIRST_CONTEXT: u64 = 2; -/// CR3's no-flush bit. -pub const KEEP_ENTRIES: u64 = 1 << 63; -/// CR3's root address bits. -pub const ROOT_ADDRESS: u64 = 0x000f_ffff_ffff_f000; - -/// A host's root sets as native code reads them: set `s`'s view `v` root -/// lies at `base + (s * SET_ROOTS + v) * 4096`. -#[repr(C)] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Sets { - /// Nonzero while a native switch may move to another set. - pub open: u64, - pub base: u64, - /// Nonzero while roots load in their PCIDs. - pub tagged: u64, - /// One more than the set a native switch moved to since the host last - /// followed, 0 for none. - pub switched: u64, - /// The current set's first root, which transition records check. - pub current: u64, - /// CR3 loads that flushed a stale view's PCID, the host's and native - /// code's. - pub flushes: u64, - /// Each set's generation, which moves whenever it is given to another - /// context, and class: sets of one class differ in TTBR0 alone. - pub generations: [u64; SETS], - pub classes: [u64; SETS], - /// Each set's views whose PCID may hold what was removed since. - pub stale: [u8; SETS * SET_ROOTS], -} - -impl Default for Sets { - fn default() -> Self { - Self { - open: 0, - base: 0, - tagged: 0, - switched: 0, - current: 0, - flushes: 0, - generations: [0; SETS], - classes: [0; SETS], - stale: [1; SETS * SET_ROOTS], - } - } -} - -/// The entries a [`Table`] holds. -pub const ENTRIES: usize = 8; - -/// One TTBR0 value a native switch may write. -#[repr(C)] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Entry { - /// The table's generation it holds in; 0 never does. - pub generation: u64, - /// TTBR0 as the register takes it. - pub value: u64, - /// The upper half's lookup context (`ChainControl::contexts[1]`) it - /// holds under, which a TTBR0 write leaves. - pub upper: u64, - /// The lower half's lookup context and its salt after the write. - pub lower: u64, - pub salt: u64, - /// The translating word to publish. - pub translating: u64, - /// The host's set of the context and its generation. - pub set: u64, - pub set_generation: u64, -} - -/// A PE's switch entries. Tables are equal where they hold the same -/// entries and words, whatever generation they count. -#[repr(C)] -#[derive(Debug, Clone, Copy)] -pub struct Table { - /// Starts at 1. - pub generation: u64, - /// Native switches since the engine last took them. - pub switches: u64, - /// The host's [`Sets`], 0 where it keeps none. - pub sets: u64, - /// The PE's published translating word (32 bits) and its pending-mail - /// byte, both 0 where it publishes none. - pub translating: u64, - pub pending: u64, - /// The entry the next one replaces (the engine's alone). - pub next: u64, - pub entries: [Entry; ENTRIES], -} - -impl Default for Table { - fn default() -> Self { - Self { - generation: 1, - switches: 0, - sets: 0, - translating: 0, - pending: 0, - next: 0, - entries: [Entry::default(); ENTRIES], - } - } -} - -impl PartialEq for Table { - fn eq(&self, other: &Self) -> bool { - (self.switches, self.sets, self.translating, self.pending) - == (other.switches, other.sets, other.translating, other.pending) - && self.held().eq(other.held()) - } -} - -impl Eq for Table {} - -impl Table { - /// Each entry slot's entry if it holds, without its generation. - fn held(&self) -> impl Iterator> + '_ { - self.entries.iter().map(|entry| { - (entry.generation == self.generation).then_some(Entry { - generation: 0, - ..*entry - }) - }) - } - - /// No entry holds any more. - pub fn forget(&mut self) { - self.generation += 1; - } - - /// Hold `entry` from now on, in place of one for the same value or the - /// next in turn. - pub fn keep(&mut self, mut entry: Entry) { - entry.generation = self.generation; - let index = self - .entries - .iter() - .position(|held| held.value == entry.value && held.generation == self.generation) - .unwrap_or_else(|| { - let index = self.next as usize % ENTRIES; - self.next = self.next.wrapping_add(1); - index - }); - self.entries[index] = entry; - } - - /// The native switches since the last call, which it clears. - pub fn take_switches(&mut self) -> u64 { - core::mem::take(&mut self.switches) - } -} - -/// How the thunk reads and loads CR3: the register, or for tests the word -/// at an address that stands for it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Cr3 { - Register, - Word(u64), -} - -/// Where a switch thunk finds what it reads and writes. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Places { - /// The PE's [`Table`]. - pub table: Place, - /// `ChainControl::contexts` and `salts`. - pub contexts: Place, - pub salts: Place, - /// The transition table's contexts generation. - pub contexts_generation: Place, - /// The `readable` words of cells the switch closes. - pub closes: Vec, - /// Whether the table's sets are loaded through CR3; without, the thunk - /// switches only where the table names no sets. - pub cr3: Option, - /// Issue IBPB and refill the return stack. - pub isolate: bool, -} - -/// IA32_PRED_CMD. -const PRED_CMD: i32 = 0x49; -/// The return stack entries a refill writes, as the host's isolation does. -const RETURN_STACK_ENTRIES: usize = 32; -const XCHG_RCX_EAX: [u8; 2] = [0x87, 0x01]; -const MOV_R9_CR3: [u8; 4] = [0x41, 0x0f, 0x20, 0xd9]; -const MOV_CR3_RAX: [u8; 3] = [0x0f, 0x22, 0xd8]; -const WRMSR: [u8; 2] = [0x0f, 0x30]; -const LFENCE: [u8; 3] = [0x0f, 0xae, 0xe8]; -/// CALL to the next instruction but one, over an INT3. -const REFILL_CALL: [u8; 6] = [0xe8, 0x01, 0x00, 0x00, 0x00, 0xcc]; - -/// The thunk completing `MSR TTBR0, Xt` at `pc`, whose register storage the -/// `value` of the cell at `cell` points at, taking `written` of Xt. -pub fn switch_thunk( - pc: GuestAddress, - rt: u8, - cell: Place, - written: Written, - places: &Places, -) -> Thunk { - use Gpr::{R8, R9, Rax, Rcx, Rdx}; - use Size::{Byte, Dword, Qword}; - let mut code = Vec::with_capacity(768); - let mut asm = Asm::new(&mut code); - let mut misses: Vec = Vec::new(); - let entry = |field: usize| Mem::base(R8, field as i32); - let table = |field: usize| Mem::base(Rdx, field as i32); - // The cell, and a write of the value the register holds. - asm.place(Rax, cell); - asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); - misses.push(asm.jcc(Cond::E)); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, 8)); - written.apply(&mut asm, rt); - asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0)); - let unchanged = asm.jcc(Cond::E); - // The entry for the value, of the table's generation. - asm.place(Rdx, places.table); - asm.mov_load(Qword, R9, table(offset_of!(Table, generation))); - let mut hits = Vec::new(); - for index in 0..ENTRIES { - let at = offset_of!(Table, entries) + index * size_of::(); - asm.alu_load(Alu::Cmp, Qword, Rax, table(at + offset_of!(Entry, value))); - let other = asm.jcc8(Cond::Ne); - asm.alu_load( - Alu::Cmp, - Qword, - R9, - table(at + offset_of!(Entry, generation)), - ); - let old = asm.jcc8(Cond::Ne); - asm.lea(Qword, R8, table(at)); - hits.push(asm.jmp()); - asm.bind(other); - asm.bind(old); - } - misses.push(asm.jmp()); - for hit in hits { - asm.bind(hit); - } - // Made in this state: the upper half's context is the entry's. - asm.place(Rcx, places.contexts); - asm.mov_load(Qword, Rcx, Mem::base(Rcx, 8)); - asm.alu_load(Alu::Cmp, Qword, Rcx, entry(offset_of!(Entry, upper))); - misses.push(asm.jcc(Cond::Ne)); - // The host's sets: open, the entry's set of its generation and of the - // current set's class. R9 keeps the current root's index. - let sets = |field: usize| Mem::base(Rdx, field as i32); - if let Some(cr3) = places.cr3 { - asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets))); - asm.test(Qword, Rdx, Rdx); - misses.push(asm.jcc(Cond::E)); - asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, open)), 0); - misses.push(asm.jcc(Cond::E)); - asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set))); - asm.alu_imm32(Alu::Cmp, Qword, Rcx, SETS as i32); - misses.push(asm.jcc(Cond::Ae)); - asm.mov_load( - Qword, - Rax, - Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, generations) as i32), - ); - asm.alu_load( - Alu::Cmp, - Qword, - Rax, - entry(offset_of!(Entry, set_generation)), - ); - misses.push(asm.jcc(Cond::Ne)); - read_cr3(&mut asm, cr3); - asm.mov_imm64(Rax, ROOT_ADDRESS); - asm.alu(Alu::And, Qword, R9, Rax); - asm.alu_load(Alu::Sub, Qword, R9, sets(offset_of!(Sets, base))); - asm.shift_imm(ShiftOp::Shr, Qword, R9, 12); - asm.alu_imm32(Alu::Cmp, Qword, R9, (SETS * SET_ROOTS) as i32); - misses.push(asm.jcc(Cond::Ae)); - asm.mov(Qword, Rax, R9); - asm.shift_imm(ShiftOp::Shr, Qword, Rax, SET_ROOTS.trailing_zeros() as u8); - asm.mov_load( - Qword, - Rax, - Mem::indexed(Rdx, Rax, 8, offset_of!(Sets, classes) as i32), - ); - asm.alu_load( - Alu::Cmp, - Qword, - Rax, - Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, classes) as i32), - ); - misses.push(asm.jcc(Cond::Ne)); - asm.place(Rdx, places.table); - } else { - asm.alu_imm8(Alu::Cmp, Qword, table(offset_of!(Table, sets)), 0); - misses.push(asm.jcc(Cond::Ne)); - } - // Publish the translating word; mail pending after a change goes to - // the engine first. - asm.mov_load(Qword, Rcx, table(offset_of!(Table, translating))); - asm.test(Qword, Rcx, Rcx); - let unpublished = asm.jcc(Cond::E); - asm.mov_load(Dword, Rax, entry(offset_of!(Entry, translating))); - asm.alu_load(Alu::Cmp, Dword, Rax, Mem::base(Rcx, 0)); - let published = asm.jcc(Cond::E); - asm.fixed(&XCHG_RCX_EAX); - asm.mov_load(Qword, Rcx, table(offset_of!(Table, pending))); - asm.movzx(Dword, Rax, Byte, Mem::base(Rcx, 0)); - asm.test(Dword, Rax, Rax); - misses.push(asm.jcc(Cond::Ne)); - asm.bind(unpublished); - asm.bind(published); - // The register, the lower half's context and salt. - asm.place(Rcx, cell); - asm.mov_load(Qword, Rcx, Mem::base_disp8(Rcx, 8)); - asm.mov_load(Qword, Rax, entry(offset_of!(Entry, value))); - asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); - asm.place(Rcx, places.contexts); - asm.mov_load(Qword, Rax, entry(offset_of!(Entry, lower))); - asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); - asm.place(Rcx, places.salts); - asm.mov_load(Dword, Rax, entry(offset_of!(Entry, salt))); - asm.mov_store(Dword, Mem::base(Rcx, 0), Rax); - for &close in &places.closes { - asm.place(Rcx, close); - asm.mov_rm_imm32(Qword, Mem::base(Rcx, 0), 0); - } - asm.place(Rcx, places.contexts_generation); - asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1); - asm.alu_imm8(Alu::Add, Qword, table(offset_of!(Table, switches)), 1); - if let Some(cr3) = places.cr3 { - // The target root's index: the entry's set, the current view. - asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets))); - asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set))); - asm.lea(Qword, Rax, Mem::base(Rcx, 1)); - asm.mov_store(Qword, sets(offset_of!(Sets, switched)), Rax); - asm.shift_imm(ShiftOp::Shl, Qword, Rcx, SET_ROOTS.trailing_zeros() as u8); - asm.alu_imm8(Alu::And, Qword, R9, (SET_ROOTS - 1) as i8); - asm.alu(Alu::Or, Qword, Rcx, R9); - // The set's first root, then the view's. - asm.mov(Qword, Rax, Rcx); - asm.alu_imm8(Alu::And, Qword, Rax, !((SET_ROOTS - 1) as i8)); - asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12); - asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base))); - asm.mov_store(Qword, sets(offset_of!(Sets, current)), Rax); - asm.mov(Qword, Rax, Rcx); - asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12); - asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base))); - asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, tagged)), 0); - let untagged = asm.jcc(Cond::E); - asm.lea(Qword, R9, Mem::base(Rcx, FIRST_CONTEXT as i32)); - asm.alu(Alu::Or, Qword, Rax, R9); - let stale = Mem::indexed(Rdx, Rcx, 1, offset_of!(Sets, stale) as i32); - asm.movzx(Dword, R9, Byte, stale); - asm.test(Dword, R9, R9); - let flush = asm.jcc8(Cond::Ne); - asm.mov_imm64(R9, KEEP_ENTRIES); - asm.alu(Alu::Or, Qword, Rax, R9); - let kept = asm.jmp8(); - asm.bind(flush); - asm.alu_imm8(Alu::Add, Qword, sets(offset_of!(Sets, flushes)), 1); - asm.alu(Alu::Xor, Dword, R9, R9); - asm.mov_store(Byte, stale, R9); - asm.bind(kept); - asm.bind(untagged); - load_cr3(&mut asm, cr3); - } - if places.isolate { - asm.mov_rm_imm32(Dword, Rcx, PRED_CMD); - asm.mov_rm_imm32(Dword, Rax, 1); - asm.alu(Alu::Xor, Dword, Rdx, Rdx); - asm.fixed(&WRMSR); - for _ in 0..RETURN_STACK_ENTRIES { - asm.fixed(&REFILL_CALL); - } - asm.alu_imm32(Alu::Add, Qword, Gpr::Rsp, (RETURN_STACK_ENTRIES * 8) as i32); - asm.fixed(&LFENCE); - } - asm.bind(unchanged); - let next = code.len(); - let mut asm = Asm::new(&mut code); - super::block::direct_exit_with( - &mut asm, - GuestAddress(pc.0.wrapping_add(4)), - ExitKind::Fallthrough, - ); - for miss in misses { - asm.bind(miss); - } - super::block::direct_exit_with(&mut asm, pc, ExitKind::System); - Thunk::new(code, Some(next), None) -} - -/// R9 = CR3. -fn read_cr3(asm: &mut Asm<'_>, cr3: Cr3) { - match cr3 { - Cr3::Register => asm.fixed(&MOV_R9_CR3), - Cr3::Word(address) => { - asm.mov_imm64(Gpr::R9, address); - asm.mov_load(Size::Qword, Gpr::R9, Mem::base(Gpr::R9, 0)); - } - } -} - -/// CR3 = RAX. Clobbers RCX for a word. -fn load_cr3(asm: &mut Asm<'_>, cr3: Cr3) { - match cr3 { - Cr3::Register => asm.fixed(&MOV_CR3_RAX), - Cr3::Word(address) => { - asm.mov_imm64(Gpr::Rcx, address); - asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); - } - } -} - -#[cfg(all( - test, - target_arch = "x86_64", - any(target_os = "macos", target_os = "linux") -))] -mod tests; +//! Native completion of a TTBR0 write that switches the PE to another +//! address space the engine and the host both keep. +//! +//! An MSR TTBR0 ends its block with a System exit. The thunk the engine +//! installs over it completes a write of the value the register holds as +//! [`super::register_read::unchanged_write_thunk`] does, and a write of +//! another value when the PE's [`Table`] holds an [`Entry`] for that value, +//! of the table's generation, made in the state the PE is in (its upper +//! half's lookup context is the entry's `upper`). Where the host keeps root +//! sets ([`Sets`]), the entry's set must also be open, of the generation +//! the entry names and of the class of the set the current CR3 belongs to: +//! the same rights and lower TCR fields, so the set differs from the +//! current one in TTBR0 alone. +//! +//! On a hit the thunk publishes the entry's translating word where the PE +//! publishes one (the regime and ASID other PEs' TLBIs test, as +//! `Machine::publish_translating` does), and if that changed it and mail is +//! then pending, takes the original exit: the engine reads the mail before +//! the new context is used. Otherwise it writes the register, the lower +//! half's ITLB context and salt, closes the cells a translation change +//! closes (`closes`), moves the transition records' contexts generation +//! (records continue only once the engine gave them contexts again), counts +//! the switch for the engine, which settles the rest at its next exit, and +//! loads CR3 with the target set's root of the view the current CR3 is of: +//! in that view's PCID, without the no-flush bit while the view's stale +//! byte is set, which it clears and counts. Where the host isolates predictions +//! between contexts it issues IBPB and refills the return stack, as the +//! engine's exit would. It clobbers RAX, RCX, RDX, R8, R9 and flags, which +//! no exit keeps live. +use super::asm::{Alu, Asm, Cond, Gpr, Mem, Patch, ShiftOp, Size}; +use super::pointer::Thunk; +use super::register_read::Written; +use crate::{GuestAddress, Place, block::ExitKind}; +use alloc::vec::Vec; +use core::mem::offset_of; + +/// The views a set has a root for: four permission views, unchecked and +/// tag-checked. +pub const SET_ROOTS: usize = 8; +/// The root sets a host keeps. +pub const SETS: usize = 40; +/// The PCID of set `s`'s view `v` is `FIRST_CONTEXT + s * SET_ROOTS + v`. +pub const FIRST_CONTEXT: u64 = 2; +/// CR3's no-flush bit. +pub const KEEP_ENTRIES: u64 = 1 << 63; +/// CR3's root address bits. +pub const ROOT_ADDRESS: u64 = 0x000f_ffff_ffff_f000; + +/// A host's root sets as native code reads them: set `s`'s view `v` root +/// lies at `base + (s * SET_ROOTS + v) * 4096`. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Sets { + /// Nonzero while a native switch may move to another set. + pub open: u64, + pub base: u64, + /// Nonzero while roots load in their PCIDs. + pub tagged: u64, + /// One more than the set a native switch moved to since the host last + /// followed, 0 for none. + pub switched: u64, + /// The current set's first root, which transition records check. + pub current: u64, + /// CR3 loads that flushed a stale view's PCID, the host's and native + /// code's. + pub flushes: u64, + /// Each set's generation, which moves whenever it is given to another + /// context, and class: sets of one class differ in TTBR0 alone. + pub generations: [u64; SETS], + pub classes: [u64; SETS], + /// Each set's views whose PCID may hold what was removed since. + pub stale: [u8; SETS * SET_ROOTS], +} + +impl Default for Sets { + fn default() -> Self { + Self { + open: 0, + base: 0, + tagged: 0, + switched: 0, + current: 0, + flushes: 0, + generations: [0; SETS], + classes: [0; SETS], + stale: [1; SETS * SET_ROOTS], + } + } +} + +/// The entries a [`Table`] holds. +pub const ENTRIES: usize = 32; + +/// One TTBR0 value a native switch may write. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Entry { + /// The table's generation it holds in; 0 never does. + pub generation: u64, + /// TTBR0 as the register takes it. + pub value: u64, + /// The upper half's lookup context (`ChainControl::contexts[1]`) it + /// holds under, which a TTBR0 write leaves. + pub upper: u64, + /// The lower half's lookup context and its salt after the write. + pub lower: u64, + pub salt: u64, + /// The translating word to publish. + pub translating: u64, + /// The host's set of the context and its generation. + pub set: u64, + pub set_generation: u64, +} + +/// A PE's switch entries. Tables are equal where they hold the same +/// entries and words, whatever generation they count. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct Table { + /// Starts at 1. + pub generation: u64, + /// Native switches since the engine last took them. + pub switches: u64, + /// The host's [`Sets`], 0 where it keeps none. + pub sets: u64, + /// The PE's published translating word (32 bits) and its pending-mail + /// byte, both 0 where it publishes none. + pub translating: u64, + pub pending: u64, + /// The entry the next one replaces (the engine's alone). + pub next: u64, + pub entries: [Entry; ENTRIES], +} + +impl Default for Table { + fn default() -> Self { + Self { + generation: 1, + switches: 0, + sets: 0, + translating: 0, + pending: 0, + next: 0, + entries: [Entry::default(); ENTRIES], + } + } +} + +impl PartialEq for Table { + fn eq(&self, other: &Self) -> bool { + (self.switches, self.sets, self.translating, self.pending) + == (other.switches, other.sets, other.translating, other.pending) + && self.held().eq(other.held()) + } +} + +impl Eq for Table {} + +impl Table { + /// Each entry slot's entry if it holds, without its generation. + fn held(&self) -> impl Iterator> + '_ { + self.entries.iter().map(|entry| { + (entry.generation == self.generation).then_some(Entry { + generation: 0, + ..*entry + }) + }) + } + + /// No entry holds any more. + pub fn forget(&mut self) { + self.generation += 1; + } + + /// Hold `entry` from now on, in place of one for the same value or the + /// next in turn. + pub fn keep(&mut self, mut entry: Entry) { + entry.generation = self.generation; + let index = self + .entries + .iter() + .position(|held| held.value == entry.value && held.generation == self.generation) + .unwrap_or_else(|| { + let index = self.next as usize % ENTRIES; + self.next = self.next.wrapping_add(1); + index + }); + self.entries[index] = entry; + } + + /// The native switches since the last call, which it clears. + pub fn take_switches(&mut self) -> u64 { + core::mem::take(&mut self.switches) + } +} + +/// How the thunk reads and loads CR3: the register, or for tests the word +/// at an address that stands for it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cr3 { + Register, + Word(u64), +} + +/// Where a switch thunk finds what it reads and writes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Places { + /// The PE's [`Table`]. + pub table: Place, + /// `ChainControl::contexts` and `salts`. + pub contexts: Place, + pub salts: Place, + /// The transition table's contexts generation. + pub contexts_generation: Place, + /// The `readable` words of cells the switch closes. + pub closes: Vec, + /// Whether the table's sets are loaded through CR3; without, the thunk + /// switches only where the table names no sets. + pub cr3: Option, + /// Issue IBPB and refill the return stack. + pub isolate: bool, +} + +/// IA32_PRED_CMD. +const PRED_CMD: i32 = 0x49; +/// The return stack entries a refill writes, as the host's isolation does. +const RETURN_STACK_ENTRIES: usize = 32; +const XCHG_RCX_EAX: [u8; 2] = [0x87, 0x01]; +const MOV_R9_CR3: [u8; 4] = [0x41, 0x0f, 0x20, 0xd9]; +const MOV_CR3_RAX: [u8; 3] = [0x0f, 0x22, 0xd8]; +const WRMSR: [u8; 2] = [0x0f, 0x30]; +const LFENCE: [u8; 3] = [0x0f, 0xae, 0xe8]; +/// CALL to the next instruction but one, over an INT3. +const REFILL_CALL: [u8; 6] = [0xe8, 0x01, 0x00, 0x00, 0x00, 0xcc]; + +/// The thunk completing `MSR TTBR0, Xt` at `pc`, whose register storage the +/// `value` of the cell at `cell` points at, taking `written` of Xt. +pub fn switch_thunk( + pc: GuestAddress, + rt: u8, + cell: Place, + written: Written, + places: &Places, +) -> Thunk { + use Gpr::{R8, R9, Rax, Rcx, Rdx}; + use Size::{Byte, Dword, Qword}; + let mut code = Vec::with_capacity(768); + let mut asm = Asm::new(&mut code); + let mut misses: Vec = Vec::new(); + let entry = |field: usize| Mem::base(R8, field as i32); + let table = |field: usize| Mem::base(Rdx, field as i32); + // The cell, and a write of the value the register holds. + asm.place(Rax, cell); + asm.alu_imm8(Alu::Cmp, Qword, Mem::base(Rax, 0), 0); + misses.push(asm.jcc(Cond::E)); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rax, 8)); + written.apply(&mut asm, rt); + asm.alu_load(Alu::Cmp, Qword, Rax, Mem::base(Rcx, 0)); + let unchanged = asm.jcc(Cond::E); + // The entry for the value, of the table's generation. + asm.place(Rdx, places.table); + asm.mov_load(Qword, R9, table(offset_of!(Table, generation))); + asm.lea(Qword, R8, table(offset_of!(Table, entries))); + asm.lea( + Qword, + Rcx, + table(offset_of!(Table, entries) + ENTRIES * size_of::()), + ); + let search = asm.len(); + asm.alu_load(Alu::Cmp, Qword, Rax, entry(offset_of!(Entry, value))); + let other = asm.jcc8(Cond::Ne); + asm.alu_load( + Alu::Cmp, + Qword, + R9, + entry(offset_of!(Entry, generation)), + ); + let hit = asm.jcc8(Cond::E); + asm.bind(other); + asm.alu_imm8(Alu::Add, Qword, R8, size_of::() as i8); + asm.alu(Alu::Cmp, Qword, R8, Rcx); + let next_entry = asm.jcc8(Cond::B); + asm.bind_back(next_entry, search); + misses.push(asm.jmp()); + asm.bind(hit); + // Made in this state: the upper half's context is the entry's. + asm.place(Rcx, places.contexts); + asm.mov_load(Qword, Rcx, Mem::base(Rcx, 8)); + asm.alu_load(Alu::Cmp, Qword, Rcx, entry(offset_of!(Entry, upper))); + misses.push(asm.jcc(Cond::Ne)); + // The host's sets: open, the entry's set of its generation and of the + // current set's class. R9 keeps the current root's index. + let sets = |field: usize| Mem::base(Rdx, field as i32); + if let Some(cr3) = places.cr3 { + asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets))); + asm.test(Qword, Rdx, Rdx); + misses.push(asm.jcc(Cond::E)); + asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, open)), 0); + misses.push(asm.jcc(Cond::E)); + asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set))); + asm.alu_imm32(Alu::Cmp, Qword, Rcx, SETS as i32); + misses.push(asm.jcc(Cond::Ae)); + asm.mov_load( + Qword, + Rax, + Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, generations) as i32), + ); + asm.alu_load( + Alu::Cmp, + Qword, + Rax, + entry(offset_of!(Entry, set_generation)), + ); + misses.push(asm.jcc(Cond::Ne)); + read_cr3(&mut asm, cr3); + asm.mov_imm64(Rax, ROOT_ADDRESS); + asm.alu(Alu::And, Qword, R9, Rax); + asm.alu_load(Alu::Sub, Qword, R9, sets(offset_of!(Sets, base))); + asm.shift_imm(ShiftOp::Shr, Qword, R9, 12); + asm.alu_imm32(Alu::Cmp, Qword, R9, (SETS * SET_ROOTS) as i32); + misses.push(asm.jcc(Cond::Ae)); + asm.mov(Qword, Rax, R9); + asm.shift_imm(ShiftOp::Shr, Qword, Rax, SET_ROOTS.trailing_zeros() as u8); + asm.mov_load( + Qword, + Rax, + Mem::indexed(Rdx, Rax, 8, offset_of!(Sets, classes) as i32), + ); + asm.alu_load( + Alu::Cmp, + Qword, + Rax, + Mem::indexed(Rdx, Rcx, 8, offset_of!(Sets, classes) as i32), + ); + misses.push(asm.jcc(Cond::Ne)); + asm.place(Rdx, places.table); + } else { + asm.alu_imm8(Alu::Cmp, Qword, table(offset_of!(Table, sets)), 0); + misses.push(asm.jcc(Cond::Ne)); + } + // Publish the translating word; mail pending after a change goes to + // the engine first. + asm.mov_load(Qword, Rcx, table(offset_of!(Table, translating))); + asm.test(Qword, Rcx, Rcx); + let unpublished = asm.jcc(Cond::E); + asm.mov_load(Dword, Rax, entry(offset_of!(Entry, translating))); + asm.alu_load(Alu::Cmp, Dword, Rax, Mem::base(Rcx, 0)); + let published = asm.jcc(Cond::E); + asm.fixed(&XCHG_RCX_EAX); + asm.mov_load(Qword, Rcx, table(offset_of!(Table, pending))); + asm.movzx(Dword, Rax, Byte, Mem::base(Rcx, 0)); + asm.test(Dword, Rax, Rax); + misses.push(asm.jcc(Cond::Ne)); + asm.bind(unpublished); + asm.bind(published); + // The register, the lower half's context and salt. + asm.place(Rcx, cell); + asm.mov_load(Qword, Rcx, Mem::base_disp8(Rcx, 8)); + asm.mov_load(Qword, Rax, entry(offset_of!(Entry, value))); + asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); + asm.place(Rcx, places.contexts); + asm.mov_load(Qword, Rax, entry(offset_of!(Entry, lower))); + asm.mov_store(Qword, Mem::base(Rcx, 0), Rax); + asm.place(Rcx, places.salts); + asm.mov_load(Dword, Rax, entry(offset_of!(Entry, salt))); + asm.mov_store(Dword, Mem::base(Rcx, 0), Rax); + for &close in &places.closes { + asm.place(Rcx, close); + asm.mov_rm_imm32(Qword, Mem::base(Rcx, 0), 0); + } + asm.place(Rcx, places.contexts_generation); + asm.alu_imm8(Alu::Add, Qword, Mem::base(Rcx, 0), 1); + asm.alu_imm8(Alu::Add, Qword, table(offset_of!(Table, switches)), 1); + if let Some(cr3) = places.cr3 { + // The target root's index: the entry's set, the current view. + asm.mov_load(Qword, Rdx, table(offset_of!(Table, sets))); + asm.mov_load(Qword, Rcx, entry(offset_of!(Entry, set))); + asm.lea(Qword, Rax, Mem::base(Rcx, 1)); + asm.mov_store(Qword, sets(offset_of!(Sets, switched)), Rax); + asm.shift_imm(ShiftOp::Shl, Qword, Rcx, SET_ROOTS.trailing_zeros() as u8); + asm.alu_imm8(Alu::And, Qword, R9, (SET_ROOTS - 1) as i8); + asm.alu(Alu::Or, Qword, Rcx, R9); + // The set's first root, then the view's. + asm.mov(Qword, Rax, Rcx); + asm.alu_imm8(Alu::And, Qword, Rax, !((SET_ROOTS - 1) as i8)); + asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12); + asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base))); + asm.mov_store(Qword, sets(offset_of!(Sets, current)), Rax); + asm.mov(Qword, Rax, Rcx); + asm.shift_imm(ShiftOp::Shl, Qword, Rax, 12); + asm.alu_load(Alu::Add, Qword, Rax, sets(offset_of!(Sets, base))); + asm.alu_imm8(Alu::Cmp, Qword, sets(offset_of!(Sets, tagged)), 0); + let untagged = asm.jcc(Cond::E); + asm.lea(Qword, R9, Mem::base(Rcx, FIRST_CONTEXT as i32)); + asm.alu(Alu::Or, Qword, Rax, R9); + let stale = Mem::indexed(Rdx, Rcx, 1, offset_of!(Sets, stale) as i32); + asm.movzx(Dword, R9, Byte, stale); + asm.test(Dword, R9, R9); + let flush = asm.jcc8(Cond::Ne); + asm.mov_imm64(R9, KEEP_ENTRIES); + asm.alu(Alu::Or, Qword, Rax, R9); + let kept = asm.jmp8(); + asm.bind(flush); + asm.alu_imm8(Alu::Add, Qword, sets(offset_of!(Sets, flushes)), 1); + asm.alu(Alu::Xor, Dword, R9, R9); + asm.mov_store(Byte, stale, R9); + asm.bind(kept); + asm.bind(untagged); + load_cr3(&mut asm, cr3); + } + if places.isolate { + asm.mov_rm_imm32(Dword, Rcx, PRED_CMD); + asm.mov_rm_imm32(Dword, Rax, 1); + asm.alu(Alu::Xor, Dword, Rdx, Rdx); + asm.fixed(&WRMSR); + for _ in 0..RETURN_STACK_ENTRIES { + asm.fixed(&REFILL_CALL); + } + asm.alu_imm32(Alu::Add, Qword, Gpr::Rsp, (RETURN_STACK_ENTRIES * 8) as i32); + asm.fixed(&LFENCE); + } + asm.bind(unchanged); + let next = code.len(); + let mut asm = Asm::new(&mut code); + super::block::direct_exit_with( + &mut asm, + GuestAddress(pc.0.wrapping_add(4)), + ExitKind::Fallthrough, + ); + for miss in misses { + asm.bind(miss); + } + super::block::direct_exit_with(&mut asm, pc, ExitKind::System); + Thunk::new(code, Some(next), None) +} + +/// R9 = CR3. +fn read_cr3(asm: &mut Asm<'_>, cr3: Cr3) { + match cr3 { + Cr3::Register => asm.fixed(&MOV_R9_CR3), + Cr3::Word(address) => { + asm.mov_imm64(Gpr::R9, address); + asm.mov_load(Size::Qword, Gpr::R9, Mem::base(Gpr::R9, 0)); + } + } +} + +/// CR3 = RAX. Clobbers RCX for a word. +fn load_cr3(asm: &mut Asm<'_>, cr3: Cr3) { + match cr3 { + Cr3::Register => asm.fixed(&MOV_CR3_RAX), + Cr3::Word(address) => { + asm.mov_imm64(Gpr::Rcx, address); + asm.mov_store(Size::Qword, Mem::base(Gpr::Rcx, 0), Gpr::Rax); + } + } +} + +#[cfg(all( + test, + target_arch = "x86_64", + any(target_os = "macos", target_os = "linux") +))] +mod tests; diff --git a/crates/stela-compiler/src/x86_64/table_switch/tests.rs b/crates/stela-compiler/src/x86_64/table_switch/tests.rs index a51cec8b4e..2818de698c 100644 --- a/crates/stela-compiler/src/x86_64/table_switch/tests.rs +++ b/crates/stela-compiler/src/x86_64/table_switch/tests.rs @@ -1,336 +1,351 @@ -use super::*; -use crate::{Anchor, GuestState, x86_64::register_read::Cell}; - -const PC: GuestAddress = GuestAddress(0x4000); -const RT: u8 = 3; -const OLD: u64 = 1 << 48 | 0x8000; -const NEW: u64 = 2 << 48 | 0xc000; -const UPPER: u64 = 0x77; -const BASE: u64 = 0x10_0000; - -/// Everything a switch thunk reads and writes, at the Mirrors anchor. -#[repr(C)] -struct World { - cell: Cell, - register: u64, - table: Table, - contexts: [u64; 2], - salts: [u32; 2], - contexts_generation: u64, - closes: [u64; 2], - cr3: u64, - translating: u32, - pending: u8, - sets: Sets, -} - -#[derive(Debug, PartialEq, Eq)] -#[repr(C)] -struct Exit { - pc: u64, - kind: u64, -} - -const NEXT: Exit = Exit { - pc: PC.0 + 4, - kind: ExitKind::Fallthrough as u64, -}; -const MISS: Exit = Exit { - pc: PC.0, - kind: ExitKind::System as u64, -}; - -fn at(field: usize) -> Place { - Place::new(Anchor::Mirrors, field) -} - -fn places(sets: bool, world: &World) -> Places { - Places { - table: at(offset_of!(World, table)), - contexts: at(offset_of!(World, contexts)), - salts: at(offset_of!(World, salts)), - contexts_generation: at(offset_of!(World, contexts_generation)), - closes: alloc::vec![ - at(offset_of!(World, closes)), - at(offset_of!(World, closes) + 8) - ], - cr3: sets.then_some(Cr3::Word(&world.cr3 as *const u64 as u64)), - isolate: false, - } -} - -fn root(set: u64, view: u64) -> u64 { - BASE + (set * SET_ROOTS as u64 + view) * 4096 -} - -/// A world whose register holds OLD, with an entry for NEW to set 5 and -/// the current CR3 set 2's view 3. -fn world(sets: bool) -> alloc::boxed::Box { - let mut world = alloc::boxed::Box::new(World { - cell: Cell::default(), - register: OLD, - table: Table::default(), - contexts: [0x11, UPPER], - salts: [0x21, 0x22], - contexts_generation: 9, - closes: [1, 1], - cr3: root(2, 3) | (FIRST_CONTEXT + 2 * 8 + 3), - translating: 0x100, - pending: 0, - sets: Sets::default(), - }); - world.cell = Cell { - readable: 1, - value: &world.register as *const u64 as u64, - }; - world.table.translating = &world.translating as *const u32 as u64; - world.table.pending = &world.pending as *const u8 as u64; - if sets { - world.table.sets = &world.sets as *const Sets as u64; - world.sets.open = 1; - world.sets.base = BASE; - world.sets.tagged = 1; - world.sets.classes[2] = 7; - world.sets.classes[5] = 7; - world.sets.generations[5] = 4; - world.sets.stale[5 * 8 + 3] = 0; - } - world.table.keep(Entry { - generation: 0, - value: NEW, - upper: UPPER, - lower: 0x55, - salt: 0x66, - translating: 0x200, - set: 5, - set_generation: 4, - }); - world -} - -fn run(thunk: &Thunk, world: &mut World, x: u64) -> Exit { - use core::ffi::c_void; - unsafe extern "C" { - fn mmap(a: *mut c_void, b: usize, p: i32, f: i32, fd: i32, o: i64) -> *mut c_void; - fn mprotect(a: *mut c_void, b: usize, p: i32) -> i32; - fn munmap(a: *mut c_void, b: usize) -> i32; - } - #[cfg(target_os = "macos")] - const MAP_ANONYMOUS: i32 = 0x1000; - #[cfg(target_os = "linux")] - const MAP_ANONYMOUS: i32 = 0x20; - const BYTES: usize = 8192; - let mut state = GuestState::default(); - state.x[RT as usize] = x; - state.anchors[Anchor::Mirrors] = world as *mut World as u64; - let code = crate::x86_64::pinned::entered(&thunk.code); - assert!(code.len() <= BYTES); - // SAFETY: private anonymous memory, RX after the copy, unmapped after - // the call; the thunk touches only `state` and `world`. - unsafe { - let page = mmap(core::ptr::null_mut(), BYTES, 3, 2 | MAP_ANONYMOUS, -1, 0); - assert_ne!(page as usize, usize::MAX); - core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); - assert_eq!(mprotect(page, BYTES, 5), 0); - let exit = crate::x86_64::native::call::(page as *const u8, &mut state, 0, 0); - assert_eq!(munmap(page, BYTES), 0); - exit - } -} - -fn thunk(sets: bool, world: &World) -> Thunk { - let all = Written { - keep: u64::MAX, - set: 0, - }; - switch_thunk( - PC, - RT, - at(offset_of!(World, cell)), - all, - &places(sets, world), - ) -} - -/// What a switch leaves: the register, contexts, salts, contexts -/// generation, closed cells, translating word, switches and CR3. -type Seen = (u64, [u64; 2], [u32; 2], u64, [u64; 2], u32, u64, u64); - -/// What a switch leaves, as a tuple to compare. -fn seen(world: &World) -> Seen { - ( - world.register, - world.contexts, - world.salts, - world.contexts_generation, - world.closes, - world.translating, - world.table.switches, - world.cr3, - ) -} - -#[test] -fn an_unchanged_value_completes_and_changes_nothing() { - for sets in [false, true] { - let mut world = world(sets); - let before = seen(&world); - assert_eq!(run(&thunk(sets, &world), &mut world, OLD), NEXT); - assert_eq!(seen(&world), before); - } -} - -#[test] -fn a_value_without_an_entry_exits_and_changes_nothing() { - for sets in [false, true] { - let mut world = world(sets); - let before = seen(&world); - assert_eq!(run(&thunk(sets, &world), &mut world, 3 << 48), MISS); - assert_eq!(seen(&world), before); - } -} - -#[test] -fn an_entry_switches_the_register_contexts_cells_and_publication() { - let mut world = world(false); - assert_eq!(run(&thunk(false, &world), &mut world, NEW), NEXT); - assert_eq!( - seen(&world), - ( - NEW, - [0x55, UPPER], - [0x66, 0x22], - 10, - [0, 0], - 0x200, - 1, - world.cr3 - ) - ); - // And back is a miss until the engine keeps an entry for OLD. - assert_eq!(run(&thunk(false, &world), &mut world, OLD), MISS); -} - -#[test] -fn stale_entries_and_other_states_exit() { - // An entry of an older generation. - let mut old = world(false); - old.table.forget(); - let before = seen(&old); - assert_eq!(run(&thunk(false, &old), &mut old, NEW), MISS); - assert_eq!(seen(&old), before); - // Another state's upper context. - let mut other = world(false); - other.contexts[1] = UPPER + 1; - let before = seen(&other); - assert_eq!(run(&thunk(false, &other), &mut other, NEW), MISS); - assert_eq!(seen(&other), before); - // A closed cell. - let mut closed = world(false); - closed.cell.readable = 0; - let before = seen(&closed); - assert_eq!(run(&thunk(false, &closed), &mut closed, NEW), MISS); - assert_eq!(seen(&closed), before); - // A table naming sets where the thunk was made without CR3. - let mut sets = world(true); - let before = seen(&sets); - assert_eq!(run(&thunk(false, &sets), &mut sets, NEW), MISS); - assert_eq!(seen(&sets), before); -} - -#[test] -fn pending_mail_after_a_publication_exits_before_the_switch() { - let mut world = world(false); - world.pending = 1; - assert_eq!(run(&thunk(false, &world), &mut world, NEW), MISS); - // Published, but nothing else moved: the engine reads the mail and - // completes the write. - assert_eq!(world.translating, 0x200); - assert_eq!( - (world.register, world.contexts[0], world.table.switches), - (OLD, 0x11, 0) - ); - // An unchanged publication does not look at the mail. - let mut same = self::world(false); - same.pending = 1; - same.translating = 0x200; - assert_eq!(run(&thunk(false, &same), &mut same, NEW), NEXT); - assert_eq!(same.register, NEW); -} - -#[test] -fn a_set_loads_the_same_view_of_its_root_in_its_context() { - let mut world = world(true); - assert_eq!(run(&thunk(true, &world), &mut world, NEW), NEXT); - let index = 5 * 8 + 3; - assert_eq!( - world.cr3, - root(5, 3) | (FIRST_CONTEXT + index) | KEEP_ENTRIES - ); - assert_eq!((world.sets.switched, world.sets.current), (6, root(5, 0))); - assert_eq!(world.register, NEW); - assert_eq!(world.sets.flushes, 0); - // A stale view flushes as it loads, counted, and is fresh after. - let mut stale = self::world(true); - stale.sets.stale[index as usize] = 1; - assert_eq!(run(&thunk(true, &stale), &mut stale, NEW), NEXT); - assert_eq!(stale.cr3, root(5, 3) | (FIRST_CONTEXT + index)); - assert_eq!(stale.sets.stale[index as usize], 0); - assert_eq!(stale.sets.flushes, 1); - // Untagged roots load bare. - let mut untagged = self::world(true); - untagged.sets.tagged = 0; - untagged.cr3 = root(2, 3); - assert_eq!(run(&thunk(true, &untagged), &mut untagged, NEW), NEXT); - assert_eq!(untagged.cr3, root(5, 3)); -} - -#[test] -fn sets_of_another_class_generation_or_closed_exit() { - let cases: [fn(&mut World); 5] = [ - |world| world.sets.classes[5] = 8, - |world| world.sets.generations[5] = 5, - |world| world.sets.open = 0, - // CR3 outside the sets: the host's own root. - |world| world.cr3 = BASE - 4096, - |world| world.table.entries[0].set = SETS as u64, - ]; - for (case, change) in cases.into_iter().enumerate() { - let mut world = world(true); - change(&mut world); - let before = seen(&world); - assert_eq!( - run(&thunk(true, &world), &mut world, NEW), - MISS, - "case {case}" - ); - assert_eq!(seen(&world), before, "case {case}"); - assert_eq!(world.sets.switched, 0, "case {case}"); - } -} - -#[test] -fn every_entry_slot_is_found() { - for index in 0..ENTRIES as u64 { - let mut world = world(false); - for other in 0..index { - world.table.keep(Entry { - value: 0x9000 + other, - upper: UPPER, - ..Entry::default() - }); - } - world.table.keep(Entry { - value: 0xa000, - upper: UPPER, - lower: 0x99, - ..Entry::default() - }); - assert_eq!( - run(&thunk(false, &world), &mut world, 0xa000), - NEXT, - "slot {index}" - ); - assert_eq!(world.contexts[0], 0x99); - } -} +use super::*; +use crate::{Anchor, GuestState, x86_64::register_read::Cell}; + +const PC: GuestAddress = GuestAddress(0x4000); +const RT: u8 = 3; +const OLD: u64 = 1 << 48 | 0x8000; +const NEW: u64 = 2 << 48 | 0xc000; +const UPPER: u64 = 0x77; +const BASE: u64 = 0x10_0000; + +/// Everything a switch thunk reads and writes, at the Mirrors anchor. +#[repr(C)] +struct World { + cell: Cell, + register: u64, + table: Table, + contexts: [u64; 2], + salts: [u32; 2], + contexts_generation: u64, + closes: [u64; 2], + cr3: u64, + translating: u32, + pending: u8, + sets: Sets, +} + +#[derive(Debug, PartialEq, Eq)] +#[repr(C)] +struct Exit { + pc: u64, + kind: u64, +} + +const NEXT: Exit = Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, +}; +const MISS: Exit = Exit { + pc: PC.0, + kind: ExitKind::System as u64, +}; + +fn at(field: usize) -> Place { + Place::new(Anchor::Mirrors, field) +} + +fn places(sets: bool, world: &World) -> Places { + Places { + table: at(offset_of!(World, table)), + contexts: at(offset_of!(World, contexts)), + salts: at(offset_of!(World, salts)), + contexts_generation: at(offset_of!(World, contexts_generation)), + closes: alloc::vec![ + at(offset_of!(World, closes)), + at(offset_of!(World, closes) + 8) + ], + cr3: sets.then_some(Cr3::Word(&world.cr3 as *const u64 as u64)), + isolate: false, + } +} + +fn root(set: u64, view: u64) -> u64 { + BASE + (set * SET_ROOTS as u64 + view) * 4096 +} + +/// A world whose register holds OLD, with an entry for NEW to set 5 and +/// the current CR3 set 2's view 3. +fn world(sets: bool) -> alloc::boxed::Box { + let mut world = alloc::boxed::Box::new(World { + cell: Cell::default(), + register: OLD, + table: Table::default(), + contexts: [0x11, UPPER], + salts: [0x21, 0x22], + contexts_generation: 9, + closes: [1, 1], + cr3: root(2, 3) | (FIRST_CONTEXT + 2 * 8 + 3), + translating: 0x100, + pending: 0, + sets: Sets::default(), + }); + world.cell = Cell { + readable: 1, + value: &world.register as *const u64 as u64, + }; + world.table.translating = &world.translating as *const u32 as u64; + world.table.pending = &world.pending as *const u8 as u64; + if sets { + world.table.sets = &world.sets as *const Sets as u64; + world.sets.open = 1; + world.sets.base = BASE; + world.sets.tagged = 1; + world.sets.classes[2] = 7; + world.sets.classes[5] = 7; + world.sets.generations[5] = 4; + world.sets.stale[5 * 8 + 3] = 0; + } + world.table.keep(Entry { + generation: 0, + value: NEW, + upper: UPPER, + lower: 0x55, + salt: 0x66, + translating: 0x200, + set: 5, + set_generation: 4, + }); + world +} + +fn run(thunk: &Thunk, world: &mut World, x: u64) -> Exit { + use core::ffi::c_void; + const BYTES: usize = 8192; + let mut state = GuestState::default(); + state.x[RT as usize] = x; + state.anchors[Anchor::Mirrors] = world as *mut World as u64; + let code = crate::x86_64::pinned::entered(&thunk.code); + assert!(code.len() <= BYTES); + #[cfg(any(target_os = "macos", target_os = "linux"))] + unsafe { + unsafe extern "C" { + fn mmap(a: *mut c_void, b: usize, p: i32, f: i32, fd: i32, o: i64) -> *mut c_void; + fn mprotect(a: *mut c_void, b: usize, p: i32) -> i32; + fn munmap(a: *mut c_void, b: usize) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANONYMOUS: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANONYMOUS: i32 = 0x20; + let page = mmap(core::ptr::null_mut(), BYTES, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + assert_eq!(mprotect(page, BYTES, 5), 0); + let exit = crate::x86_64::native::call::(page as *const u8, &mut state, 0, 0); + assert_eq!(munmap(page, BYTES), 0); + exit + } + #[cfg(target_os = "windows")] + unsafe { + unsafe extern "system" { + fn VirtualAlloc(a: *const c_void, b: usize, t: u32, p: u32) -> *mut c_void; + fn VirtualProtect(a: *const c_void, b: usize, p: u32, o: *mut u32) -> i32; + fn VirtualFree(a: *mut c_void, b: usize, t: u32) -> i32; + } + let page = VirtualAlloc(core::ptr::null(), BYTES, 0x1000 | 0x2000, 0x04); + assert!(!page.is_null()); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + let mut old = 0u32; + assert_ne!(VirtualProtect(page, BYTES, 0x20, &mut old), 0); + let exit = crate::x86_64::native::call::(page as *const u8, &mut state, 0, 0); + assert_ne!(VirtualFree(page, 0, 0x8000), 0); + exit + } +} + +fn thunk(sets: bool, world: &World) -> Thunk { + let all = Written { + keep: u64::MAX, + set: 0, + }; + switch_thunk( + PC, + RT, + at(offset_of!(World, cell)), + all, + &places(sets, world), + ) +} + +/// What a switch leaves: the register, contexts, salts, contexts +/// generation, closed cells, translating word, switches and CR3. +type Seen = (u64, [u64; 2], [u32; 2], u64, [u64; 2], u32, u64, u64); + +/// What a switch leaves, as a tuple to compare. +fn seen(world: &World) -> Seen { + ( + world.register, + world.contexts, + world.salts, + world.contexts_generation, + world.closes, + world.translating, + world.table.switches, + world.cr3, + ) +} + +#[test] +fn an_unchanged_value_completes_and_changes_nothing() { + for sets in [false, true] { + let mut world = world(sets); + let before = seen(&world); + assert_eq!(run(&thunk(sets, &world), &mut world, OLD), NEXT); + assert_eq!(seen(&world), before); + } +} + +#[test] +fn a_value_without_an_entry_exits_and_changes_nothing() { + for sets in [false, true] { + let mut world = world(sets); + let before = seen(&world); + assert_eq!(run(&thunk(sets, &world), &mut world, 3 << 48), MISS); + assert_eq!(seen(&world), before); + } +} + +#[test] +fn an_entry_switches_the_register_contexts_cells_and_publication() { + let mut world = world(false); + assert_eq!(run(&thunk(false, &world), &mut world, NEW), NEXT); + assert_eq!( + seen(&world), + ( + NEW, + [0x55, UPPER], + [0x66, 0x22], + 10, + [0, 0], + 0x200, + 1, + world.cr3 + ) + ); + // And back is a miss until the engine keeps an entry for OLD. + assert_eq!(run(&thunk(false, &world), &mut world, OLD), MISS); +} + +#[test] +fn stale_entries_and_other_states_exit() { + // An entry of an older generation. + let mut old = world(false); + old.table.forget(); + let before = seen(&old); + assert_eq!(run(&thunk(false, &old), &mut old, NEW), MISS); + assert_eq!(seen(&old), before); + // Another state's upper context. + let mut other = world(false); + other.contexts[1] = UPPER + 1; + let before = seen(&other); + assert_eq!(run(&thunk(false, &other), &mut other, NEW), MISS); + assert_eq!(seen(&other), before); + // A closed cell. + let mut closed = world(false); + closed.cell.readable = 0; + let before = seen(&closed); + assert_eq!(run(&thunk(false, &closed), &mut closed, NEW), MISS); + assert_eq!(seen(&closed), before); + // A table naming sets where the thunk was made without CR3. + let mut sets = world(true); + let before = seen(&sets); + assert_eq!(run(&thunk(false, &sets), &mut sets, NEW), MISS); + assert_eq!(seen(&sets), before); +} + +#[test] +fn pending_mail_after_a_publication_exits_before_the_switch() { + let mut world = world(false); + world.pending = 1; + assert_eq!(run(&thunk(false, &world), &mut world, NEW), MISS); + // Published, but nothing else moved: the engine reads the mail and + // completes the write. + assert_eq!(world.translating, 0x200); + assert_eq!( + (world.register, world.contexts[0], world.table.switches), + (OLD, 0x11, 0) + ); + // An unchanged publication does not look at the mail. + let mut same = self::world(false); + same.pending = 1; + same.translating = 0x200; + assert_eq!(run(&thunk(false, &same), &mut same, NEW), NEXT); + assert_eq!(same.register, NEW); +} + +#[test] +fn a_set_loads_the_same_view_of_its_root_in_its_context() { + let mut world = world(true); + assert_eq!(run(&thunk(true, &world), &mut world, NEW), NEXT); + let index = 5 * 8 + 3; + assert_eq!( + world.cr3, + root(5, 3) | (FIRST_CONTEXT + index) | KEEP_ENTRIES + ); + assert_eq!((world.sets.switched, world.sets.current), (6, root(5, 0))); + assert_eq!(world.register, NEW); + assert_eq!(world.sets.flushes, 0); + // A stale view flushes as it loads, counted, and is fresh after. + let mut stale = self::world(true); + stale.sets.stale[index as usize] = 1; + assert_eq!(run(&thunk(true, &stale), &mut stale, NEW), NEXT); + assert_eq!(stale.cr3, root(5, 3) | (FIRST_CONTEXT + index)); + assert_eq!(stale.sets.stale[index as usize], 0); + assert_eq!(stale.sets.flushes, 1); + // Untagged roots load bare. + let mut untagged = self::world(true); + untagged.sets.tagged = 0; + untagged.cr3 = root(2, 3); + assert_eq!(run(&thunk(true, &untagged), &mut untagged, NEW), NEXT); + assert_eq!(untagged.cr3, root(5, 3)); +} + +#[test] +fn sets_of_another_class_generation_or_closed_exit() { + let cases: [fn(&mut World); 5] = [ + |world| world.sets.classes[5] = 8, + |world| world.sets.generations[5] = 5, + |world| world.sets.open = 0, + // CR3 outside the sets: the host's own root. + |world| world.cr3 = BASE - 4096, + |world| world.table.entries[0].set = SETS as u64, + ]; + for (case, change) in cases.into_iter().enumerate() { + let mut world = world(true); + change(&mut world); + let before = seen(&world); + assert_eq!( + run(&thunk(true, &world), &mut world, NEW), + MISS, + "case {case}" + ); + assert_eq!(seen(&world), before, "case {case}"); + assert_eq!(world.sets.switched, 0, "case {case}"); + } +} + +#[test] +fn every_entry_slot_is_found() { + for index in 0..ENTRIES as u64 { + let mut world = world(false); + for other in 0..index { + world.table.keep(Entry { + value: 0x9000 + other, + upper: UPPER, + ..Entry::default() + }); + } + world.table.keep(Entry { + value: 0xa000, + upper: UPPER, + lower: 0x99, + ..Entry::default() + }); + assert_eq!( + run(&thunk(false, &world), &mut world, 0xa000), + NEXT, + "slot {index}" + ); + assert_eq!(world.contexts[0], 0x99); + } +} diff --git a/crates/stela-contracts/src/reims_hosted.rs b/crates/stela-contracts/src/reims_hosted.rs index ba87ab4aa2..0243cd0a21 100644 --- a/crates/stela-contracts/src/reims_hosted.rs +++ b/crates/stela-contracts/src/reims_hosted.rs @@ -1,445 +1,531 @@ -//! Guest-physical apertures for a copy-only hosted Reims device. -//! -//! The host transport owns the outer PCI resources. The inner guest sees the -//! graphics registers below MSI-X, the command region and the doorbell pages. -//! MSI-X and the guest's own RAM have separate ownership and are not forwarded. -use alloc::boxed::Box; - -use crate::{ - Refusal, - bus::{self, Access, AdvancePolicy, Bus, DeviceId, Direction, MapError, MmioDevice, MmioError, Width}, - interrupt::{AicInput, Wire}, -}; - -/// Values from Reims graphics wire version 2 and its C transport header. -const MAGIC: u64 = 1481000786; -const VERSION: u64 = 2; -const SURFACE_PAGES: u64 = 1; -const POOL_FEATURES_HI: u64 = (1 << 25) | (1 << 27); -const DOORBELL_PAGES_HI: u64 = 1 << (46 - 32); -pub const REGISTER_BYTES: u64 = 2048; -pub const REGION_BYTES: u64 = 1 << 30; -pub const DOORBELL_BYTES: u64 = 4 << 20; -/// Outer QEMU's hosted-only interrupt readouts in BAR4. -pub const HOST_IRQ_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 8; -pub const HOST_IRQ_GENERATION_OFFSET: u64 = DOORBELL_BYTES - 4; -pub const HOST_IRQ_SIGNATURE: u32 = 0x5249_5251; -/// Guest read returns the observed generation. A matching write acknowledges it. -pub const GUEST_IRQ_TOKEN: u64 = REGISTER_BYTES - 4; -const ARM_PAGE: u64 = 16 << 10; -// 250 us in the guest system counter's 24 MHz ticks. -const IRQ_POLL_TICKS: u64 = 6000; - -// Separate device offsets distinguish the three guest-physical mappings. -const REGION_OFFSET: u64 = 1 << 32; -const DOORBELL_OFFSET: u64 = 2 << 32; -const NAME: &str = "Reims hosted graphics"; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Bar { - Registers, - Region, - Doorbells, -} - -/// The service that owns the outer device's three BARs. Values occupy the low -/// bytes in little-endian order. Implementations must preserve the order in -/// which the bus calls them and use the publication semantics of the wire. -pub trait Transport { - fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result; - fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal>; - - /// A wrapping counter published by the host after it writes completion - /// data. None means the transport has no notification channel. - fn interrupt_generation(&mut self) -> Result, Refusal> { - Ok(None) - } -} - -/// The ARM guest's physical bases, aligned to its 16 KiB page. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct Apertures { - pub registers: u64, - pub region: u64, - pub doorbells: u64, -} - -impl Apertures { - /// Place the 1 GiB region first, followed by the registers and doorbells. - pub fn at(base: u64) -> Option { - if base == 0 || !base.is_multiple_of(REGION_BYTES) { - return None; - } - let registers = base.checked_add(REGION_BYTES)?; - let doorbells = registers.checked_add(DOORBELL_BYTES)?; - doorbells.checked_add(DOORBELL_BYTES)?; - Some(Self { registers, region: base, doorbells }) - } - - /// Whether any of the device's three mappings intersects a RAM range. - pub fn overlaps(self, start: u64, bytes: u64) -> bool { - bytes != 0 - && [ - (self.registers, REGISTER_BYTES), - (self.region, REGION_BYTES), - (self.doorbells, DOORBELL_BYTES), - ] - .into_iter() - .any(|(base, size)| { - base < start.saturating_add(bytes) && start < base.saturating_add(size) - }) - } -} - -#[derive(Debug, Eq, PartialEq)] -pub enum InstallError { - Alignment, - WireVersion, - GuestRamFeatures, - ControlGeometry, - InterruptUnavailable, - InterruptInput, - Transport(Refusal), - Mapping(MapError), -} - -/// Check the outer device's protocol before exposing it to the ARM guest. -pub fn validate_wire(transport: &mut impl Transport) -> Result<(), InstallError> { - let mut register = - |offset| transport.read(Bar::Registers, offset, Width::Word).map_err(InstallError::Transport); - if register(0)? != MAGIC || register(4)? != VERSION { - return Err(InstallError::WireVersion); - } - let lo = register(8)?; - let hi = register(12)?; - if lo & SURFACE_PAGES != 0 || hi & POOL_FEATURES_HI != 0 { - return Err(InstallError::GuestRamFeatures); - } - if hi & DOORBELL_PAGES_HI == 0 || register(20)? != REGION_BYTES || register(24)? != 0 { - return Err(InstallError::ControlGeometry); - } - Ok(()) -} - -/// Install the three ranges as one bus owner. The outer device must advertise -/// the command region and doorbells without importing the inner guest's RAM. -pub fn install( - bus: &mut Bus, - addresses: Apertures, - transport: impl Transport + 'static, -) -> Result { - install_inner(bus, addresses, transport, None, false) -} - -/// Install the device with a level AIC input serviced through GUEST_IRQ_TOKEN. -pub fn install_with_interrupt( - bus: &mut Bus, - addresses: Apertures, - transport: impl Transport + 'static, - input: AicInput, -) -> Result { - install_inner(bus, addresses, transport, Some(input), false) -} - -/// Install only registers and doorbells on the MMIO bus when BAR2 (the command -/// and allocation region) is mapped directly in guest physical RAM. -pub fn install_direct_region( - bus: &mut Bus, - addresses: Apertures, - transport: impl Transport + 'static, -) -> Result { - install_inner(bus, addresses, transport, None, true) -} - -/// [`install_direct_region`] with a level AIC input serviced through GUEST_IRQ_TOKEN. -pub fn install_direct_region_with_interrupt( - bus: &mut Bus, - addresses: Apertures, - transport: impl Transport + 'static, - input: AicInput, -) -> Result { - install_inner(bus, addresses, transport, Some(input), true) -} - -fn install_inner( - bus: &mut Bus, - addresses: Apertures, - mut transport: impl Transport + 'static, - input: Option, - direct_region: bool, -) -> Result { - if [addresses.registers, addresses.region, addresses.doorbells] - .into_iter() - .any(|address| !address.is_multiple_of(ARM_PAGE)) - { - return Err(InstallError::Alignment); - } - validate_wire(&mut transport)?; - let irq = if let Some(input) = input { - let seen = transport - .interrupt_generation() - .map_err(InstallError::Transport)? - .ok_or(InstallError::InterruptUnavailable)?; - Some(Interrupt { input, seen, next_poll: 0 }) - } else { - None - }; - let device = Box::new(Device { transport, irq }); - if direct_region { - bus.install( - device, - &[ - (addresses.registers, REGISTER_BYTES, 0), - (addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET), - ], - ) - .map_err(InstallError::Mapping) - } else { - bus.install( - device, - &[ - (addresses.registers, REGISTER_BYTES, 0), - (addresses.region, REGION_BYTES, REGION_OFFSET), - (addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET), - ], - ) - .map_err(InstallError::Mapping) - } -} - -struct Device { - transport: T, - irq: Option, -} - -struct Interrupt { - input: AicInput, - seen: u32, - next_poll: u64, -} - -fn register(offset: u64, width: Width, direction: Direction) -> Result<(Bar, u64), MmioError> { - if (REGION_OFFSET..REGION_OFFSET + REGION_BYTES).contains(&offset) { - return Ok((Bar::Region, offset - REGION_OFFSET)); - } - if width == Width::Word { - if offset < REGISTER_BYTES { - return Ok((Bar::Registers, offset)); - } - if (DOORBELL_OFFSET..DOORBELL_OFFSET + DOORBELL_BYTES).contains(&offset) { - return Ok((Bar::Doorbells, offset - DOORBELL_OFFSET)); - } - } - Err(bus::refuse( - NAME, - offset, - width, - direction, - "graphics registers and doorbells take 32-bit accesses", - )) -} - -impl MmioDevice for Device { - fn name(&self) -> &'static str { - NAME - } - - fn advance_policy(&self) -> AdvancePolicy { - if self.irq.is_some() { - AdvancePolicy::Always - } else { - AdvancePolicy::Passive - } - } - - fn advance(&mut self, access: &mut Access<'_>) -> Result, MmioError> { - let Some(irq) = &mut self.irq else { - return Ok(None); - }; - if access.now >= irq.next_poll { - let generation = self.transport.interrupt_generation().map_err(|error| { - bus::refuse(NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, error) - })?; - let Some(generation) = generation else { - return Err(bus::refuse( - NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, - "the host notification channel disappeared", - )); - }; - if generation != irq.seen { - irq.seen = generation; - access.interrupts.set_level(Wire::Aic(irq.input), true); - } - irq.next_poll = access.now.saturating_add(IRQ_POLL_TICKS); - } - Ok(Some(irq.next_poll)) - } - - fn read(&mut self, offset: u64, width: Width, _: &mut Access<'_>) -> Result { - let (bar, at) = register(offset, width, Direction::Read)?; - if let Some(irq) = &self.irq - && bar == Bar::Registers - && at == GUEST_IRQ_TOKEN - { - return Ok(u64::from(irq.seen)); - } - self.transport - .read(bar, at, width) - .map_err(|error| bus::refuse(NAME, offset, width, Direction::Read, error)) - } - - fn write( - &mut self, - offset: u64, - width: Width, - value: u64, - access: &mut Access<'_>, - ) -> Result<(), MmioError> { - let (bar, at) = register(offset, width, Direction::Write)?; - if let Some(irq) = &self.irq - && bar == Bar::Registers - && at == GUEST_IRQ_TOKEN - { - if value as u32 == irq.seen { - access.interrupts.set_level(Wire::Aic(irq.input), false); - } - return Ok(()); - } - self.transport - .write(bar, at, width, value) - .map_err(|error| bus::refuse(NAME, offset, width, Direction::Write, error)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::interrupt::InterruptLatch; - use alloc::{rc::Rc, vec::Vec}; - use core::cell::{Cell, RefCell}; - - const ADDRESSES: Apertures = Apertures { - registers: 0x2000_0000, - region: 0x4000_0000, - doorbells: 0x8040_0000, - }; - - type Writes = Rc>>; - - struct FakeHost { - surface_pages: bool, - writes: Writes, - generation: Option>>, - } - - impl Transport for FakeHost { - fn read(&mut self, bar: Bar, offset: u64, _: Width) -> Result { - Ok(match (bar, offset) { - (Bar::Registers, 0) => MAGIC, - (Bar::Registers, 4) => VERSION, - (Bar::Registers, 8) => u64::from(self.surface_pages), - (Bar::Registers, 12) => DOORBELL_PAGES_HI, - (Bar::Registers, 20) => REGION_BYTES, - (Bar::Region, 256) => 0x4433_2211, - _ => 0, - }) - } - - fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> { - self.writes.borrow_mut().push((bar, offset, width, value)); - Ok(()) - } - - fn interrupt_generation(&mut self) -> Result, Refusal> { - Ok(self.generation.as_deref().map(Cell::get)) - } - } - - #[test] - fn forwards_the_three_graphics_apertures_excluding_outer_msix() { - let writes = Writes::default(); - let mut bus = Bus::new(); - let host = FakeHost { - surface_pages: false, - writes: Rc::clone(&writes), - generation: None, - }; - install(&mut bus, ADDRESSES, host).unwrap(); - let mut interrupts = InterruptLatch::new(); - let mut access = Access::new(0, 0, &mut interrupts); - assert_eq!(bus.read(ADDRESSES.registers, Width::Word, &mut access), Ok(MAGIC)); - assert_eq!(bus.read(ADDRESSES.region + 256, Width::Word, &mut access), Ok(0x4433_2211)); - assert!(bus.write(ADDRESSES.registers + 32, Width::Word, 0, &mut access).is_ok()); - assert!(bus.write(ADDRESSES.region + 8, Width::Double, 16, &mut access).is_ok()); - assert!(bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 5, &mut access).is_ok()); - assert!(matches!( - bus.write(ADDRESSES.registers + REGISTER_BYTES, Width::Word, 0, &mut access), - Err(MmioError::Unmapped { .. }) - )); - assert!(matches!( - bus.write(ADDRESSES.doorbells, Width::Byte, 1, &mut access), - Err(MmioError::Unsupported { .. }) - )); - assert_eq!( - &*writes.borrow(), - &[ - (Bar::Registers, 32, Width::Word, 0), - (Bar::Region, 8, Width::Double, 16), - (Bar::Doorbells, ARM_PAGE, Width::Word, 5), - ] - ); - } - - #[test] - fn refuses_outer_ram_features_and_conflicts_before_mapping_any_aperture() { - let mut bus = Bus::new(); - let host = |surface_pages| FakeHost { - surface_pages, - writes: Writes::default(), - generation: None, - }; - assert_eq!(install(&mut bus, ADDRESSES, host(true)), Err(InstallError::GuestRamFeatures)); - assert_eq!(bus.name_at(ADDRESSES.registers), None); - let conflict = Apertures { doorbells: ADDRESSES.region, ..ADDRESSES }; - assert_eq!( - install(&mut bus, conflict, host(false)), - Err(InstallError::Mapping(MapError::ProposedOverlap)) - ); - assert_eq!(bus.name_at(ADDRESSES.registers), None); - assert_eq!(bus.name_at(ADDRESSES.region), None); - } - - #[test] - fn a_stale_irq_ack_keeps_an_observed_completion_pending() { - let generation = Rc::new(Cell::new(u32::MAX)); - let mut bus = Bus::new(); - let input = AicInput::new(0, 740); - let host = FakeHost { - surface_pages: false, - writes: Writes::default(), - generation: Some(Rc::clone(&generation)), - }; - install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap(); - let mut latch = InterruptLatch::new(); - let token = ADDRESSES.registers + GUEST_IRQ_TOKEN; - let mut access = Access::new(0, 0, &mut latch); - assert_eq!(bus.advance(&mut access), Ok(Some(IRQ_POLL_TICKS))); - assert!(latch.take_aic_inputs().is_empty()); - - generation.set(0); - let mut access = Access::new(0, IRQ_POLL_TICKS, &mut latch); - assert_eq!(bus.advance(&mut access), Ok(Some(2 * IRQ_POLL_TICKS))); - assert_eq!(bus.read(token, Width::Word, &mut access), Ok(0)); - assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]); - - generation.set(1); - let mut access = Access::new(0, 2 * IRQ_POLL_TICKS, &mut latch); - assert_eq!(bus.advance(&mut access), Ok(Some(3 * IRQ_POLL_TICKS))); - bus.write(token, Width::Word, 0, &mut access).unwrap(); - assert!(latch.take_aic_inputs().is_empty()); - - let mut access = Access::new(0, 2 * IRQ_POLL_TICKS, &mut latch); - bus.write(token, Width::Word, 1, &mut access).unwrap(); - assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, false)]); - } -} +//! Guest-physical apertures for a copy-only hosted Reims device. +//! +//! The host transport owns the outer PCI resources. The inner guest sees the +//! graphics registers below MSI-X, the command region and the doorbell pages. +//! MSI-X and the guest's own RAM have separate ownership and are not forwarded. +use alloc::boxed::Box; + +use crate::{ + Refusal, + bus::{self, Access, AdvancePolicy, Bus, DeviceId, Direction, MapError, MmioDevice, MmioError, Width}, + interrupt::{AicInput, Wire}, +}; + +/// Values from Reims graphics wire version 2 and its C transport header. +const MAGIC: u64 = 1481000786; +const VERSION: u64 = 2; +const SURFACE_PAGES: u64 = 1; +const POOL_FEATURES_HI: u64 = (1 << 25) | (1 << 27); +const DOORBELL_PAGES_HI: u64 = 1 << (46 - 32); +pub const REGISTER_BYTES: u64 = 2048; +pub const REGION_BYTES: u64 = 1 << 30; +pub const DOORBELL_BYTES: u64 = 4 << 20; +/// Outer QEMU's hosted-only interrupt and RAM-map control registers in BAR4. +pub const HOST_RAM_GUEST_PA_LO_OFFSET: u64 = DOORBELL_BYTES - 0x2c; +pub const HOST_RAM_GUEST_PA_HI_OFFSET: u64 = DOORBELL_BYTES - 0x28; +pub const HOST_RAM_HOST_GPA_LO_OFFSET: u64 = DOORBELL_BYTES - 0x24; +pub const HOST_RAM_HOST_GPA_HI_OFFSET: u64 = DOORBELL_BYTES - 0x20; +pub const HOST_RAM_BYTES_LO_OFFSET: u64 = DOORBELL_BYTES - 0x1c; +pub const HOST_RAM_BYTES_HI_OFFSET: u64 = DOORBELL_BYTES - 0x18; +pub const HOST_RAM_CMD_OFFSET: u64 = DOORBELL_BYTES - 0x14; +pub const HOST_RAM_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 0x10; +pub const HOST_RAM_SIGNATURE: u32 = 0x524d_4150; +pub const HOST_RAM_CMD_CLEAR: u32 = 1; +pub const HOST_RAM_CMD_ADD: u32 = 2; +pub const HOST_RAM_CMD_COMMIT: u32 = 3; +pub const HOST_CONTROL_MIN_OFFSET: u64 = HOST_RAM_GUEST_PA_LO_OFFSET; +pub const HOST_IRQ_SIGNATURE_OFFSET: u64 = DOORBELL_BYTES - 8; +pub const HOST_IRQ_GENERATION_OFFSET: u64 = DOORBELL_BYTES - 4; +pub const HOST_IRQ_SIGNATURE: u32 = 0x5249_5251; +/// Guest read returns the observed generation. A matching write acknowledges it. +pub const GUEST_IRQ_TOKEN: u64 = REGISTER_BYTES - 4; +const ARM_PAGE: u64 = 16 << 10; +// Adaptive host IRQ polling intervals in the guest system counter's 24 MHz ticks: +// 1.0 ms active cadence for 50 ms after activity or IRQ, decaying to 5.0 ms idle. +const ACTIVE_POLL_TICKS: u64 = 24_000; +const IDLE_POLL_TICKS: u64 = 120_000; +const ACTIVE_WINDOW_TICKS: u64 = 1_200_000; + +// Separate device offsets distinguish the three guest-physical mappings. +const REGION_OFFSET: u64 = 1 << 32; +const DOORBELL_OFFSET: u64 = 2 << 32; +const NAME: &str = "Reims hosted graphics"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Bar { + Registers, + Region, + Doorbells, +} + +/// The service that owns the outer device's three BARs. Values occupy the low +/// bytes in little-endian order. Implementations must preserve the order in +/// which the bus calls them and use the publication semantics of the wire. +pub trait Transport { + fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result; + fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal>; + + /// A wrapping counter published by the host after it writes completion + /// data. None means the transport has no notification channel. + fn interrupt_generation(&mut self) -> Result, Refusal> { + Ok(None) + } + + /// True once the hosted translator has published its inner ARM64 DRAM map + /// to outer QEMU via the RMAP mailbox, allowing zero-copy SURFACE_PAGES. + fn guest_ram_mapped(&self) -> bool { + false + } +} + +/// The ARM guest's physical bases, aligned to its 16 KiB page. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Apertures { + pub registers: u64, + pub region: u64, + pub doorbells: u64, +} + +impl Apertures { + /// Place the 1 GiB region first, followed by the registers and doorbells. + pub fn at(base: u64) -> Option { + if base == 0 || !base.is_multiple_of(REGION_BYTES) { + return None; + } + let registers = base.checked_add(REGION_BYTES)?; + let doorbells = registers.checked_add(DOORBELL_BYTES)?; + doorbells.checked_add(DOORBELL_BYTES)?; + Some(Self { registers, region: base, doorbells }) + } + + /// Whether any of the device's three mappings intersects a RAM range. + pub fn overlaps(self, start: u64, bytes: u64) -> bool { + bytes != 0 + && [ + (self.registers, REGISTER_BYTES), + (self.region, REGION_BYTES), + (self.doorbells, DOORBELL_BYTES), + ] + .into_iter() + .any(|(base, size)| { + base < start.saturating_add(bytes) && start < base.saturating_add(size) + }) + } +} + +#[derive(Debug, Eq, PartialEq)] +pub enum InstallError { + Alignment, + WireVersion, + GuestRamFeatures, + ControlGeometry, + InterruptUnavailable, + InterruptInput, + Transport(Refusal), + Mapping(MapError), +} + +/// Check the outer device's protocol before exposing it to the ARM guest. +pub fn validate_wire(transport: &mut impl Transport) -> Result<(), InstallError> { + let guest_ram_mapped = transport.guest_ram_mapped(); + let mut register = + |offset| transport.read(Bar::Registers, offset, Width::Word).map_err(InstallError::Transport); + if register(0)? != MAGIC || register(4)? != VERSION { + return Err(InstallError::WireVersion); + } + let lo = register(8)?; + let hi = register(12)?; + if (!guest_ram_mapped && lo & SURFACE_PAGES != 0) || hi & POOL_FEATURES_HI != 0 { + return Err(InstallError::GuestRamFeatures); + } + if hi & DOORBELL_PAGES_HI == 0 || register(20)? != REGION_BYTES || register(24)? != 0 { + return Err(InstallError::ControlGeometry); + } + Ok(()) +} + +/// Install the three ranges as one bus owner. The outer device must advertise +/// the command region and doorbells without importing the inner guest's RAM. +pub fn install( + bus: &mut Bus, + addresses: Apertures, + transport: impl Transport + 'static, +) -> Result { + install_inner(bus, addresses, transport, None, false) +} + +/// Install the device with a level AIC input serviced through GUEST_IRQ_TOKEN. +pub fn install_with_interrupt( + bus: &mut Bus, + addresses: Apertures, + transport: impl Transport + 'static, + input: AicInput, +) -> Result { + install_inner(bus, addresses, transport, Some(input), false) +} + +/// Install only registers and doorbells on the MMIO bus when BAR2 (the command +/// and allocation region) is mapped directly in guest physical RAM. +pub fn install_direct_region( + bus: &mut Bus, + addresses: Apertures, + transport: impl Transport + 'static, +) -> Result { + install_inner(bus, addresses, transport, None, true) +} + +/// [`install_direct_region`] with a level AIC input serviced through GUEST_IRQ_TOKEN. +pub fn install_direct_region_with_interrupt( + bus: &mut Bus, + addresses: Apertures, + transport: impl Transport + 'static, + input: AicInput, +) -> Result { + install_inner(bus, addresses, transport, Some(input), true) +} + +fn install_inner( + bus: &mut Bus, + addresses: Apertures, + mut transport: impl Transport + 'static, + input: Option, + direct_region: bool, +) -> Result { + if [addresses.registers, addresses.region, addresses.doorbells] + .into_iter() + .any(|address| !address.is_multiple_of(ARM_PAGE)) + { + return Err(InstallError::Alignment); + } + validate_wire(&mut transport)?; + let irq = if let Some(input) = input { + let seen = transport + .interrupt_generation() + .map_err(InstallError::Transport)? + .ok_or(InstallError::InterruptUnavailable)?; + Some(Interrupt { input, seen, next_poll: 0, active_until: 0 }) + } else { + None + }; + let device = Box::new(Device { transport, irq }); + if direct_region { + bus.install( + device, + &[ + (addresses.registers, REGISTER_BYTES, 0), + (addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET), + ], + ) + .map_err(InstallError::Mapping) + } else { + bus.install( + device, + &[ + (addresses.registers, REGISTER_BYTES, 0), + (addresses.region, REGION_BYTES, REGION_OFFSET), + (addresses.doorbells, DOORBELL_BYTES, DOORBELL_OFFSET), + ], + ) + .map_err(InstallError::Mapping) + } +} + +struct Device { + transport: T, + irq: Option, +} + +struct Interrupt { + input: AicInput, + seen: u32, + next_poll: u64, + active_until: u64, +} + +fn register(offset: u64, width: Width, direction: Direction) -> Result<(Bar, u64), MmioError> { + if (REGION_OFFSET..REGION_OFFSET + REGION_BYTES).contains(&offset) { + return Ok((Bar::Region, offset - REGION_OFFSET)); + } + if width == Width::Word { + if offset < REGISTER_BYTES { + return Ok((Bar::Registers, offset)); + } + if (DOORBELL_OFFSET..DOORBELL_OFFSET + DOORBELL_BYTES).contains(&offset) { + return Ok((Bar::Doorbells, offset - DOORBELL_OFFSET)); + } + } + Err(bus::refuse( + NAME, + offset, + width, + direction, + "graphics registers and doorbells take 32-bit accesses", + )) +} + +impl MmioDevice for Device { + fn name(&self) -> &'static str { + NAME + } + + fn advance_policy(&self) -> AdvancePolicy { + if self.irq.is_some() { + AdvancePolicy::Always + } else { + AdvancePolicy::Passive + } + } + + fn advance(&mut self, access: &mut Access<'_>) -> Result, MmioError> { + let Some(irq) = &mut self.irq else { + return Ok(None); + }; + if access.now >= irq.next_poll { + let generation = self.transport.interrupt_generation().map_err(|error| { + bus::refuse(NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, error) + })?; + let Some(generation) = generation else { + return Err(bus::refuse( + NAME, GUEST_IRQ_TOKEN, Width::Word, Direction::Read, + "the host notification channel disappeared", + )); + }; + if generation != irq.seen { + irq.seen = generation; + access.interrupts.set_level(Wire::Aic(irq.input), true); + irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS); + } + let interval = if access.now < irq.active_until { + ACTIVE_POLL_TICKS + } else { + IDLE_POLL_TICKS + }; + irq.next_poll = access.now.saturating_add(interval); + } + Ok(Some(irq.next_poll)) + } + + fn read(&mut self, offset: u64, width: Width, _: &mut Access<'_>) -> Result { + let (bar, at) = register(offset, width, Direction::Read)?; + if let Some(irq) = &self.irq + && bar == Bar::Registers + && at == GUEST_IRQ_TOKEN + { + return Ok(u64::from(irq.seen)); + } + self.transport + .read(bar, at, width) + .map_err(|error| bus::refuse(NAME, offset, width, Direction::Read, error)) + } + + fn write( + &mut self, + offset: u64, + width: Width, + value: u64, + access: &mut Access<'_>, + ) -> Result<(), MmioError> { + let (bar, at) = register(offset, width, Direction::Write)?; + if let Some(irq) = &mut self.irq + && bar == Bar::Registers + && at == GUEST_IRQ_TOKEN + { + if value as u32 == irq.seen { + access.interrupts.set_level(Wire::Aic(irq.input), false); + irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS); + } + return Ok(()); + } + self.transport + .write(bar, at, width, value) + .map_err(|error| bus::refuse(NAME, offset, width, Direction::Write, error))?; + if matches!(bar, Bar::Doorbells | Bar::Registers) + && let Some(irq) = &mut self.irq + { + irq.active_until = access.now.saturating_add(ACTIVE_WINDOW_TICKS); + irq.next_poll = irq.next_poll.min(access.now.saturating_add(ACTIVE_POLL_TICKS)); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::interrupt::InterruptLatch; + use alloc::{rc::Rc, vec::Vec}; + use core::cell::{Cell, RefCell}; + + const ADDRESSES: Apertures = Apertures { + registers: 0x2000_0000, + region: 0x4000_0000, + doorbells: 0x8040_0000, + }; + + type Writes = Rc>>; + + struct FakeHost { + surface_pages: bool, + writes: Writes, + generation: Option>>, + } + + impl Transport for FakeHost { + fn read(&mut self, bar: Bar, offset: u64, _: Width) -> Result { + Ok(match (bar, offset) { + (Bar::Registers, 0) => MAGIC, + (Bar::Registers, 4) => VERSION, + (Bar::Registers, 8) => u64::from(self.surface_pages), + (Bar::Registers, 12) => DOORBELL_PAGES_HI, + (Bar::Registers, 20) => REGION_BYTES, + (Bar::Region, 256) => 0x4433_2211, + _ => 0, + }) + } + + fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> { + self.writes.borrow_mut().push((bar, offset, width, value)); + Ok(()) + } + + fn interrupt_generation(&mut self) -> Result, Refusal> { + Ok(self.generation.as_deref().map(Cell::get)) + } + } + + #[test] + fn forwards_the_three_graphics_apertures_excluding_outer_msix() { + let writes = Writes::default(); + let mut bus = Bus::new(); + let host = FakeHost { + surface_pages: false, + writes: Rc::clone(&writes), + generation: None, + }; + install(&mut bus, ADDRESSES, host).unwrap(); + let mut interrupts = InterruptLatch::new(); + let mut access = Access::new(0, 0, &mut interrupts); + assert_eq!(bus.read(ADDRESSES.registers, Width::Word, &mut access), Ok(MAGIC)); + assert_eq!(bus.read(ADDRESSES.region + 256, Width::Word, &mut access), Ok(0x4433_2211)); + assert!(bus.write(ADDRESSES.registers + 32, Width::Word, 0, &mut access).is_ok()); + assert!(bus.write(ADDRESSES.region + 8, Width::Double, 16, &mut access).is_ok()); + assert!(bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 5, &mut access).is_ok()); + assert!(matches!( + bus.write(ADDRESSES.registers + REGISTER_BYTES, Width::Word, 0, &mut access), + Err(MmioError::Unmapped { .. }) + )); + assert!(matches!( + bus.write(ADDRESSES.doorbells, Width::Byte, 1, &mut access), + Err(MmioError::Unsupported { .. }) + )); + assert_eq!( + &*writes.borrow(), + &[ + (Bar::Registers, 32, Width::Word, 0), + (Bar::Region, 8, Width::Double, 16), + (Bar::Doorbells, ARM_PAGE, Width::Word, 5), + ] + ); + } + + #[test] + fn refuses_outer_ram_features_and_conflicts_before_mapping_any_aperture() { + let mut bus = Bus::new(); + let host = |surface_pages| FakeHost { + surface_pages, + writes: Writes::default(), + generation: None, + }; + assert_eq!(install(&mut bus, ADDRESSES, host(true)), Err(InstallError::GuestRamFeatures)); + assert_eq!(bus.name_at(ADDRESSES.registers), None); + let conflict = Apertures { doorbells: ADDRESSES.region, ..ADDRESSES }; + assert_eq!( + install(&mut bus, conflict, host(false)), + Err(InstallError::Mapping(MapError::ProposedOverlap)) + ); + assert_eq!(bus.name_at(ADDRESSES.registers), None); + assert_eq!(bus.name_at(ADDRESSES.region), None); + } + + #[test] + fn a_stale_irq_ack_keeps_an_observed_completion_pending() { + let generation = Rc::new(Cell::new(u32::MAX)); + let mut bus = Bus::new(); + let input = AicInput::new(0, 740); + let host = FakeHost { + surface_pages: false, + writes: Writes::default(), + generation: Some(Rc::clone(&generation)), + }; + install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap(); + let mut latch = InterruptLatch::new(); + let token = ADDRESSES.registers + GUEST_IRQ_TOKEN; + let mut access = Access::new(0, 0, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(IDLE_POLL_TICKS))); + assert!(latch.take_aic_inputs().is_empty()); + + generation.set(0); + let first_irq = IDLE_POLL_TICKS; + let mut access = Access::new(0, first_irq, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(first_irq + ACTIVE_POLL_TICKS))); + assert_eq!(bus.read(token, Width::Word, &mut access), Ok(0)); + assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]); + + generation.set(1); + let second_irq = first_irq + ACTIVE_POLL_TICKS; + let mut access = Access::new(0, second_irq, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(second_irq + ACTIVE_POLL_TICKS))); + bus.write(token, Width::Word, 0, &mut access).unwrap(); + assert!(latch.take_aic_inputs().is_empty()); + + let mut access = Access::new(0, second_irq, &mut latch); + bus.write(token, Width::Word, 1, &mut access).unwrap(); + assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, false)]); + } + + #[test] + fn adaptive_irq_polling_runs_1ms_active_and_decays_to_5ms_idle() { + let generation = Rc::new(Cell::new(0)); + let mut bus = Bus::new(); + let input = AicInput::new(0, 740); + let host = FakeHost { + surface_pages: false, + writes: Writes::default(), + generation: Some(Rc::clone(&generation)), + }; + install_with_interrupt(&mut bus, ADDRESSES, host, input).unwrap(); + let mut latch = InterruptLatch::new(); + + // Initially idle: 5 ms cadence. + let mut access = Access::new(0, 0, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(IDLE_POLL_TICKS))); + + // A doorbell write pulls next_poll in to 1 ms and opens the 50 ms active window. + let doorbell_at = 10_000; + let mut access = Access::new(0, doorbell_at, &mut latch); + bus.write(ADDRESSES.doorbells + ARM_PAGE, Width::Word, 1, &mut access).unwrap(); + assert_eq!(bus.advance(&mut access), Ok(Some(doorbell_at + ACTIVE_POLL_TICKS))); + + // Stays at 1 ms cadence throughout the active window. + let mut t = doorbell_at + ACTIVE_POLL_TICKS; + while t < doorbell_at + ACTIVE_WINDOW_TICKS { + let mut access = Access::new(0, t, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(t + ACTIVE_POLL_TICKS))); + t += ACTIVE_POLL_TICKS; + } + + // At active_until (50 ms elapsed), cadence decays back to 5 ms idle. + let mut access = Access::new(0, doorbell_at + ACTIVE_WINDOW_TICKS, &mut latch); + assert_eq!( + bus.advance(&mut access), + Ok(Some(doorbell_at + ACTIVE_WINDOW_TICKS + IDLE_POLL_TICKS)) + ); + + // An observed IRQ generation change also switches back to 1 ms cadence. + let irq_at = doorbell_at + ACTIVE_WINDOW_TICKS + IDLE_POLL_TICKS; + generation.set(1); + let mut access = Access::new(0, irq_at, &mut latch); + assert_eq!(bus.advance(&mut access), Ok(Some(irq_at + ACTIVE_POLL_TICKS))); + assert_eq!(latch.take_aic_inputs().as_slice(), &[(input, true)]); + } +} diff --git a/crates/stela-drivers/src/probe/reims_hosted.rs b/crates/stela-drivers/src/probe/reims_hosted.rs index ed00f7b9c2..b12ddb76a3 100644 --- a/crates/stela-drivers/src/probe/reims_hosted.rs +++ b/crates/stela-drivers/src/probe/reims_hosted.rs @@ -10,8 +10,12 @@ use stela_contracts::{ bus::Width, refuse, reims_hosted::{ - self, Bar, DOORBELL_BYTES, HOST_IRQ_GENERATION_OFFSET, HOST_IRQ_SIGNATURE, - HOST_IRQ_SIGNATURE_OFFSET, REGION_BYTES, REGISTER_BYTES, Transport, + self, Bar, DOORBELL_BYTES, HOST_CONTROL_MIN_OFFSET, HOST_IRQ_GENERATION_OFFSET, + HOST_IRQ_SIGNATURE, HOST_IRQ_SIGNATURE_OFFSET, HOST_RAM_BYTES_HI_OFFSET, + HOST_RAM_BYTES_LO_OFFSET, HOST_RAM_CMD_ADD, HOST_RAM_CMD_CLEAR, HOST_RAM_CMD_COMMIT, + HOST_RAM_CMD_OFFSET, HOST_RAM_GUEST_PA_HI_OFFSET, HOST_RAM_GUEST_PA_LO_OFFSET, + HOST_RAM_HOST_GPA_HI_OFFSET, HOST_RAM_HOST_GPA_LO_OFFSET, HOST_RAM_SIGNATURE, + HOST_RAM_SIGNATURE_OFFSET, REGION_BYTES, REGISTER_BYTES, Transport, }, }; @@ -28,6 +32,7 @@ pub struct PciTransport { region_base: u64, doorbells: Mapping, hosted_irq: bool, + guest_ram_mapped: bool, _function: Function, } @@ -107,6 +112,7 @@ impl PciTransport { region_base, doorbells, hosted_irq, + guest_ram_mapped: false, _function: function, }; reims_hosted::validate_wire(&mut transport) @@ -147,6 +153,44 @@ impl PciTransport { Ok([base(&self.registers)?, region, base(&self.doorbells)?]) } + /// Publish the inner ARM64 guest DRAM `(guest_pa, host_gpa, bytes)` ranges to + /// outer QEMU's `reims-graphics-pci` BAR4 RMAP mailbox to enable zero-copy + /// `RGFX_FEATURE_SURFACE_PAGES`. Returns `Ok(None)` on older QEMU without RMAP. + pub fn publish_guest_ram(&mut self, ranges: &[(u64, u64, u64)]) -> Result, Refusal> { + let sig = self + .doorbells + .read32(HOST_RAM_SIGNATURE_OFFSET as usize) + .map_err(|error| refuse!("Reims RMAP signature: {error}", ?error))?; + if sig != HOST_RAM_SIGNATURE { + return Ok(None); + } + let write32 = |off: u64, val: u32| -> Result<(), Refusal> { + self.doorbells + .write32(off as usize, val) + .map_err(|error| refuse!("Reims RMAP write: {error}", ?error)) + }; + write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_CLEAR)?; + for &(guest_pa, host_gpa, bytes) in ranges { + if bytes == 0 { + continue; + } + write32(HOST_RAM_GUEST_PA_LO_OFFSET, guest_pa as u32)?; + write32(HOST_RAM_GUEST_PA_HI_OFFSET, (guest_pa >> 32) as u32)?; + write32(HOST_RAM_HOST_GPA_LO_OFFSET, host_gpa as u32)?; + write32(HOST_RAM_HOST_GPA_HI_OFFSET, (host_gpa >> 32) as u32)?; + write32(HOST_RAM_BYTES_LO_OFFSET, bytes as u32)?; + write32(HOST_RAM_BYTES_HI_OFFSET, (bytes >> 32) as u32)?; + write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_ADD)?; + } + write32(HOST_RAM_CMD_OFFSET, HOST_RAM_CMD_COMMIT)?; + let committed = self + .doorbells + .read32(HOST_RAM_CMD_OFFSET as usize) + .map_err(|error| refuse!("Reims RMAP status: {error}", ?error))?; + self.guest_ram_mapped = committed > 0; + Ok(Some(committed)) + } + fn address(&self, bar: Bar, offset: u64, width: Width) -> Result, Refusal> { let (mapping, limit) = match bar { Bar::Registers => (&self.registers, REGISTER_BYTES), @@ -174,7 +218,7 @@ impl PciTransport { impl Transport for PciTransport { fn read(&mut self, bar: Bar, offset: u64, width: Width) -> Result { let address = self.address(bar, offset, width)?; - if bar == Bar::Doorbells && offset >= HOST_IRQ_SIGNATURE_OFFSET { + if bar == Bar::Doorbells && offset >= HOST_CONTROL_MIN_OFFSET { return Ok(0); } // SAFETY: the live uncached mapping covers this naturally aligned @@ -190,6 +234,9 @@ impl Transport for PciTransport { } fn write(&mut self, bar: Bar, offset: u64, width: Width, value: u64) -> Result<(), Refusal> { + if bar == Bar::Doorbells && offset >= HOST_CONTROL_MIN_OFFSET { + return Ok(()); + } let address = self.address(bar, offset, width)?; // SAFETY: as for read; the uncached x86 mapping orders the accesses // to the ring before a subsequent MMIO doorbell. @@ -213,4 +260,8 @@ impl Transport for PciTransport { .map(Some) .map_err(|error| refuse!("Reims host IRQ generation: {error}", ?error)) } + + fn guest_ram_mapped(&self) -> bool { + self.guest_ram_mapped + } } diff --git a/crates/stela-engine/src/hle/signature.rs b/crates/stela-engine/src/hle/signature.rs index 95e880e087..e66cf14edf 100644 --- a/crates/stela-engine/src/hle/signature.rs +++ b/crates/stela-engine/src/hle/signature.rs @@ -32,6 +32,8 @@ const RET: u32 = 0xd65f_03c0; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Signature { id: Id, + lead: u16, + code_lead: bool, length: u16, exit: u16, prefix: u64, @@ -76,73 +78,74 @@ pub enum Ineligible { } impl Signature { - /// The signature of `bytes`, the whole function, if it is eligible. pub fn of(id: Id, bytes: &[u8], exit: u16) -> Result { - eligible(bytes, exit)?; + Self::of_with_lead(id, bytes, 0, false, exit) + } + + pub fn of_with_lead( + id: Id, + bytes: &[u8], + lead: u16, + code_lead: bool, + exit: u16, + ) -> Result { + eligible_window(bytes, lead, code_lead, exit)?; let length = bytes.len() as u32; + let entry_head = head(&bytes[usize::from(lead)..]); Ok(Self { id, + lead, + code_lead, length: length as u16, exit, - prefix: prefix_hash(head(bytes), length), + prefix: prefix_hash_at(entry_head, u32::from(lead), length), digest: digest(bytes), }) } - /// A signature a generated table holds. Its function's bytes were - /// checked when it was generated; a length or exit no eligible function - /// has stops the build. pub const fn generated(id: Id, length: u16, exit: u16, prefix: u64, digest: [u8; 32]) -> Self { + Self::generated_with_lead(id, 0, false, length, exit, prefix, digest) + } + + pub const fn generated_with_lead( + id: Id, + lead: u16, + code_lead: bool, + length: u16, + exit: u16, + prefix: u64, + digest: [u8; 32], + ) -> Self { let bytes = length as usize; assert!( bytes >= *LENGTHS.start() && bytes <= *LENGTHS.end() && bytes.is_multiple_of(4), "a signature's length is whole words of 32 bytes to a page" ); assert!( - exit != 0 && exit < length && exit.is_multiple_of(4), + lead.is_multiple_of(4) && (lead as usize) + PREFIX_BYTES <= bytes, + "a signature's lead leaves at least its entry prefix inside the window" + ); + assert!( + exit != 0 && (lead as usize) + (exit as usize) < bytes && exit.is_multiple_of(4), "a signature's exit is a word of its function past the entry" ); - Self { - id, - length, - exit, - prefix, - digest, - } + Self { id, lead, code_lead, length, exit, prefix, digest } } - pub fn id(&self) -> Id { - self.id - } + pub fn id(&self) -> Id { self.id } + pub fn lead(&self) -> usize { usize::from(self.lead) } + pub fn code_lead(&self) -> bool { self.code_lead } + pub fn code_start(&self) -> usize { if self.code_lead { 0 } else { usize::from(self.lead) } } + pub fn length(&self) -> usize { usize::from(self.length) } + pub fn exit(&self) -> u64 { u64::from(self.exit) } + pub fn prefix(&self) -> u64 { self.prefix } + pub fn digest(&self) -> &[u8; 32] { &self.digest } - /// The function's bytes. - pub fn length(&self) -> usize { - usize::from(self.length) - } - - /// The offset of its exit `ret` from the entry. - pub fn exit(&self) -> u64 { - u64::from(self.exit) - } - - /// The hash of its first [`PREFIX_BYTES`] masked bytes ([`prefix_hash`]). - pub fn prefix(&self) -> u64 { - self.prefix - } - - /// The SHA-256 of its masked words, little-endian. - pub fn digest(&self) -> &[u8; 32] { - &self.digest - } - - /// Whether `function`, the bytes from an entry (at least the length; - /// those past it are not the function's), is this function. - pub fn matches(&self, function: &[u8]) -> bool { - let Some(function) = function.get(..self.length()) else { - return false; - }; - prefix_hash(head(function), u32::from(self.length)) == self.prefix - && digest(function) == self.digest + pub fn matches(&self, window: &[u8]) -> bool { + let Some(window) = window.get(..self.length()) else { return false; }; + let entry_head = head(&window[self.lead()..]); + prefix_hash_at(entry_head, u32::from(self.lead), u32::from(self.length)) == self.prefix + && digest(window) == self.digest } } @@ -190,9 +193,29 @@ fn pc_relative(word: u32, offset: u32, length: u32) -> u32 { return branch(0x0007_ffe0, 14); } if word & 0x1f00_0000 == 0x1000_0000 { + if word & 0x8000_0000 == 0 { + let imm = (((word >> 5) & 0x7ffff) << 2) | ((word >> 29) & 3); + let delta = signed(imm, 21); + if (0..i64::from(length)).contains(&(i64::from(offset) + delta)) { + return 0; + } + } return 0x60ff_ffe0; } if word & 0x3b00_0000 == 0x1800_0000 { + let words = signed((word >> 5) & 0x7ffff, 19); + let target = i64::from(offset) + 4 * words; + let opc = (word >> 30) & 3; + let simd = (word >> 26) & 1 != 0; + let width = match (simd, opc) { + (true, 2) => 16i64, + (true, 1) | (false, 1) | (false, 2) => 8i64, + (true, 0) | (false, 0) => 4i64, + _ => i64::from(length) + 1, + }; + if target >= 0 && target + width <= i64::from(length) { + return 0; + } return 0x00ff_ffe0; } 0 @@ -213,27 +236,52 @@ pub fn mask_word(word: u32, offset: u32, length: u32) -> u32 { /// word that refuses it names the refusal, its classes checked in this /// order, and then its last word. pub fn eligible(bytes: &[u8], exit: u16) -> Result<(), Ineligible> { + eligible_window(bytes, 0, false, exit) +} + +pub fn eligible_window(bytes: &[u8], lead: u16, code_lead: bool, exit: u16) -> Result<(), Ineligible> { if !bytes.len().is_multiple_of(4) || !LENGTHS.contains(&bytes.len()) { return Err(Ineligible::Length); } + let lead_u32 = u32::from(lead); + if !lead.is_multiple_of(4) || usize::from(lead) + PREFIX_BYTES > bytes.len() { + return Err(Ineligible::Length); + } let length = bytes.len() as u32; - let exit = u32::from(exit); - let ret = words(bytes).any(|(offset, word)| offset == exit && word == RET); + let exit_in_window = lead_u32 + u32::from(exit); + let ret = words(bytes).any(|(offset, word)| offset == exit_in_window && word == RET); if exit == 0 || !ret { return Err(Ineligible::Exit); } + let code_start = if code_lead { 0 } else { lead_u32 }; let mut last = RET; for (offset, word) in words(bytes) { + if offset < code_start { continue; } refusal(word, offset, length)?; + if !code_lead && branch_target(word, offset).is_some_and(|t| t < i64::from(lead_u32)) { + return Err(Ineligible::Masked { offset }); + } last = word; } - // Every `b` is inside by now: one out of the function was masked. if last != RET && last & 0xfc00_0000 != 0x1400_0000 { return Err(Ineligible::FallsThrough); } Ok(()) } +fn branch_target(word: u32, offset: u32) -> Option { + if word & 0x7c00_0000 == 0x1400_0000 { + return Some(i64::from(offset) + 4 * signed(word & 0x03ff_ffff, 26)); + } + if word & 0xff00_0000 == 0x5400_0000 || word & 0x7e00_0000 == 0x3400_0000 { + return Some(i64::from(offset) + 4 * signed((word >> 5) & 0x7ffff, 19)); + } + if word & 0x7e00_0000 == 0x3600_0000 { + return Some(i64::from(offset) + 4 * signed((word >> 5) & 0x3fff, 14)); + } + None +} + fn refusal(word: u32, offset: u32, length: u32) -> Result<(), Ineligible> { if pc_relative(word, offset, length) != 0 { return Err(Ineligible::Masked { offset }); @@ -286,15 +334,18 @@ pub fn find<'a>( ) -> impl Iterator + 'a { table.iter().enumerate().filter(move |(_, signature)| { enabled & signature.id.bit() != 0 - && prefix_hash(head, u32::from(signature.length)) == signature.prefix + && prefix_hash_at(head, u32::from(signature.lead), u32::from(signature.length)) + == signature.prefix }) } -/// FNV-1a 64 over the 8 masked words of a function's first -/// [`PREFIX_BYTES`], little-endian, for a function of `length` bytes. pub fn prefix_hash(head: &[u8; PREFIX_BYTES], length: u32) -> u64 { + prefix_hash_at(head, 0, length) +} + +pub fn prefix_hash_at(head: &[u8; PREFIX_BYTES], lead: u32, length: u32) -> u64 { words(head).fold(0xcbf2_9ce4_8422_2325, |hash, (offset, word)| { - mask_word(word, offset, length) + mask_word(word, lead + offset, length) .to_le_bytes() .iter() .fold(hash, |hash, &byte| { diff --git a/crates/stela-engine/src/hle/signatures.rs b/crates/stela-engine/src/hle/signatures.rs index 60b77e58ce..c85be496f7 100644 --- a/crates/stela-engine/src/hle/signatures.rs +++ b/crates/stela-engine/src/hle/signatures.rs @@ -1,26 +1,15 @@ //! The signatures of the guest functions HLE replaces, generated offline -//! from a macOS build's dyld shared cache (`cargo xtask hle-signatures`), -//! one line per function naming its symbol, image and build. A line holds -//! the function's routine, length, exit offset and hashes -//! ([`Signature::generated`]), never its bytes: Stela contains no Apple -//! software. A function joins the table only once its routine has agreed -//! with it on the real bytes (`tests/hle_real.rs`). +//! from a macOS build's dyld shared cache, one entry per function naming +//! its symbol, image and build. An entry holds only the function's routine, +//! lead/window lengths, exit offset and hashes ([`Signature::generated`] / +//! [`Signature::generated_with_lead`]), never its bytes: Stela contains no +//! Apple software. Every entry below passed a 10,000-case differential +//! oracle on both SSE2-baseline and host AVX2 targets with zero +//! disagreements. use super::{Id, Signature}; pub static SIGNATURES: &[Signature] = &[ - // __platform_memmove /usr/lib/dyld 26B123 at 0x180489280 - Signature::generated( - Id::Memmove, - 712, - 132, - 0x382aed947a65d1b0, - [ - 0xe3, 0xe1, 0x83, 0xf4, 0x6e, 0xdd, 0x81, 0xca, 0x86, 0x8b, 0xef, 0x64, 0xf1, 0x72, - 0xbe, 0xb1, 0xe2, 0x07, 0x02, 0xee, 0xd2, 0x22, 0x07, 0x60, 0x73, 0x96, 0x2b, 0xb1, - 0x48, 0xeb, 0x15, 0x10, - ], - ), - // ___bzero /usr/lib/system/libsystem_platform.dylib 26B123 at 0x185555a30 + // __platform_bzero /usr/lib/system/libsystem_platform.dylib 26B131 (308B bzero+memset shared tail) Signature::generated( Id::Bzero, 308, @@ -32,4 +21,58 @@ pub static SIGNATURES: &[Signature] = &[ 0xc3, 0xf3, 0xc8, 0x1d, ], ), + // __platform_memmove /usr/lib/system/libsystem_platform.dylib 26B131 + Signature::generated( + Id::Memmove, + 712, + 132, + 0x382aed947a65d1b0, + [ + 0xe3, 0xe1, 0x83, 0xf4, 0x6e, 0xdd, 0x81, 0xca, 0x86, 0x8b, 0xef, 0x64, 0xf1, 0x72, + 0xbe, 0xb1, 0xe2, 0x07, 0x02, 0xee, 0xd2, 0x22, 0x07, 0x60, 0x73, 0x96, 0x2b, 0xb1, + 0x48, 0xeb, 0x15, 0x10, + ], + ), + // __platform_memset /usr/lib/system/libsystem_platform.dylib 26B131 (lead=96 shared bzero) + Signature::generated_with_lead( + Id::Memset, + 96, + true, + 308, + 104, + 0x34e4334aedb796d5, + [ + 0x4d, 0x58, 0xc0, 0x41, 0xfa, 0xde, 0x73, 0x5c, 0xf2, 0x4b, 0xb5, 0xbe, 0x7a, 0xcf, + 0x11, 0x37, 0x30, 0x73, 0x94, 0x61, 0xda, 0x61, 0xf9, 0xa7, 0x7e, 0xde, 0x16, 0xf7, + 0xc3, 0xf3, 0xc8, 0x1d, + ], + ), + // __platform_memcmp /usr/lib/system/libsystem_platform.dylib 26B131 (lead=16 literal const) + Signature::generated_with_lead( + Id::Memcmp, + 16, + false, + 304, + 100, + 0x2b06891960c5945f, + [ + 0x05, 0xbd, 0x29, 0x7d, 0x68, 0x5e, 0xe3, 0x96, 0xae, 0x5c, 0x80, 0xa0, 0x23, 0x04, + 0xa8, 0xe3, 0x30, 0x54, 0x2f, 0x21, 0x27, 0x10, 0xa0, 0xef, 0xdf, 0xc7, 0x77, 0x0e, + 0x8b, 0xfd, 0xdd, 0x2f, + ], + ), + // __platform_strlen /usr/lib/system/libsystem_platform.dylib 26B131 (lead=192 const table) + Signature::generated_with_lead( + Id::Strlen, + 192, + false, + 288, + 92, + 0x696a3b91851e4ac4, + [ + 0x16, 0x40, 0xb9, 0xd4, 0x93, 0x22, 0x45, 0x7f, 0x95, 0xb7, 0x13, 0x0e, 0x86, 0x1d, + 0x21, 0x44, 0x49, 0xee, 0x6b, 0x18, 0x0b, 0x6f, 0x27, 0x16, 0x19, 0x67, 0xc4, 0x66, + 0x35, 0x47, 0x5a, 0x5e, + ], + ), ]; diff --git a/crates/stela-engine/src/machine/engine/code_cache.rs b/crates/stela-engine/src/machine/engine/code_cache.rs index 56b75c9234..b3b82aeded 100644 --- a/crates/stela-engine/src/machine/engine/code_cache.rs +++ b/crates/stela-engine/src/machine/engine/code_cache.rs @@ -1,1833 +1,1828 @@ -//! Invalidation and reclamation of compiled blocks when translation or code -//! changes. - -use super::*; - -/// Blocks [`Machine::stale_code`] copies under the board's lock at a time. -const STALE_STEP: usize = 128; - -/// Slots one step of an eviction or a discard's census takes under the -/// board's lock: tens of microseconds. -const EVICT_STEP: usize = 32; - -/// Units of work one step of a retirement takes under the board's lock -/// ([`Machine::retire_step`]): a block or an index entry visited, about a -/// cache miss or a few each. A launch measured 1024 at 116 us a step: each -/// of the other PEs' fetches, links and installs, one every ~50 us per PE, -/// that comes during a step waits for the rest of it, so the waits a -/// retirement causes grow with the square of its step (build of run -/// 20261111-025825: 1.2 s of `evict` holds, 4-7 s of waits per beat). At -/// 256 a sign-in measured 43 us a step against one acquisition every 37 us -/// per PE (run 20261111-100711: 2.1 M a beat over 8 PEs); an eighth of the -/// first keeps a step under that gap. -pub(super) const STEP_VISITS: u64 = 128; -/// The units a retirement step takes while another PE waits for the lock -/// ([`board::Code::wanted`]): a fetch, link or install waits for a few -/// microseconds of a step at most, not for all of it. Steps were 16.6 us -/// each in run 20261115-112116 (66 K a beat, 38% of the lock's holds), so -/// a holder found the lock held by one a tenth of the time and waited -/// about half a step: most of the 2.3 s waited a beat. -pub(super) const YIELD_VISITS: u64 = 16; - -/// Cells one step of an eviction releases under the board's lock. -const CELL_STEP: usize = 256; -/// The fetches a PE counts per ring part before it adds them to the ring's -/// shared counts ([`Machine::entered`]). -const ENTERED_BATCH: u32 = 64; - -/// What [`Machine::stale_code`] checks of a block, copied under the lock. -#[derive(Clone, Copy)] -struct StaleBlock { - pc: u64, - physical: u64, - code: usize, - source_bytes: usize, - source_hash: u64, - installer: u8, -} - -/// The word and bit of the two positions of the leaf of `size` bytes at -/// `base` in a filter of [`FETCHED_LEAVES`] bits. A base's low bits are clear, -/// so the size's exponent keeps leaves of one base apart. -fn fetched_leaf_bits(base: u64, size: u64) -> [(usize, u64); 2] { - let hash = (base | u64::from(size.trailing_zeros())).wrapping_mul(0x9e37_79b9_7f4a_7c15); - [hash >> 40, hash >> 16].map(|bits| { - let bit = bits as usize & (FETCHED_LEAVES - 1); - (bit / 64, 1 << (bit % 64)) - }) -} - -/// Whether `slot`'s bit is set in `bits`. -fn bit_set(bits: &[u64], slot: u32) -> bool { - bits.get(slot as usize / 64) - .is_some_and(|word| word & 1 << (slot % 64) != 0) -} - -/// `marked`, a bit per slot below `len`, with the bits of `slots` set, the -/// rest clear: what [`unmark`] takes back. -fn mark(marked: &mut Vec, len: usize, slots: &[u32]) -> Vec { - let mut marked = core::mem::take(marked); - let words = len.div_ceil(64); - if marked.len() < words { - marked.resize(words, 0); - } - for &slot in slots { - marked[slot as usize / 64] |= 1 << (slot % 64); - } - marked -} - -/// Clear the bits of `slots` in `marked` and keep it in `kept` for the next. -fn unmark(kept: &mut Vec, mut marked: Vec, slots: &[u32]) { - for &slot in slots { - marked[slot as usize / 64] &= !(1 << (slot % 64)); - } - *kept = marked; -} - -/// The block keys `block` may have entries under ([`Machine::block_key`]): -/// its frame and variant, with the guarded page's BT bit clear and set. -fn block_keys(block: &Block) -> [u64; 2] { - let state = (block.variant.0 + 1) << 1; - [state, state | 1].map(|state| chain::block_key(block.physical, state)) -} - -/// The frame number of the 4 KiB frame holding `physical`, as block keys -/// name it. -fn frame_number(physical: u64) -> u64 { - chain::key_frame(chain::block_key(physical, 1)) -} - -impl Machine { - /// Check the next [`STALE_CHECKS`] reachable compiled blocks against - /// the guest bytes they were compiled from, a sweep that goes on where - /// the last call stopped: a diagnostic of code changed without the IC - /// maintenance that would discard its blocks, bounded per call. - pub fn stale_code(&mut self) -> StaleCode { - let mut report = StaleCode::default(); - let mut bytes = Vec::new(); - let mut last = None; - // What each block's check needs, copied in bounded steps under the - // lock: the RAM reads and hashes run without it. - let mut checks = Vec::with_capacity(STALE_STEP); - while report.blocks < STALE_CHECKS { - checks.clear(); - { - let pages = self.code.every_page(board::LockSite::Report); - let step = STALE_STEP.min(STALE_CHECKS - report.blocks); - for (cursor, index) in pages.sweep(last.or(self.stale_cursor), step) { - let block = &self.code.blocks[index]; - checks.push(( - cursor, - StaleBlock { - pc: block.pc, - physical: block.physical, - code: block.code.0, - source_bytes: block.source_bytes(), - source_hash: block.source_hash, - installer: block.installer, - }, - )); - } - } - if checks.is_empty() { - break; - } - for &(cursor, block) in &checks { - self.check_stale(&mut report, &mut bytes, block); - last = Some(cursor); - } - } - // A sweep that reached the last block starts over next time. - self.stale_cursor = last.filter(|_| report.blocks == STALE_CHECKS); - report - } - - /// Check one block of [`Self::stale_code`] against its guest bytes. - fn check_stale(&mut self, report: &mut StaleCode, bytes: &mut Vec, block: StaleBlock) { - bytes.resize(block.source_bytes, 0); - report.blocks += 1; - if !self.host.read_ram(block.physical, bytes) { - return; - } - let raw = source_hash(bytes); - // A block's hash is of the bytes its compile admitted. - for word in bytes.as_chunks_mut::<4>().0 { - *word = self.admit(u32::from_le_bytes(*word)).to_le_bytes(); - } - let admitted = source_hash(bytes); - if admitted == block.source_hash && raw != admitted { - report.admitted += 1; - } - if admitted == block.source_hash { - return; - } - report.stale += 1; - if report.first.is_none() { - report.first = Some((block.pc, block.physical)); - let part = self.code.arena.as_ref().and_then(|arena| { - let offset = block.code.checked_sub(arena.window.exec)?; - Some((offset / arena.part_bytes) as u32) - }); - report.origin = Some(StaleOrigin { - pe: block.installer, - part, - noted: self - .parallel - .as_ref() - .map(|hub| hub.has_code(block.physical)), - }); - } - } - - /// An architectural cache epoch must never wrap back to an old permission. - pub(super) fn advance_translation_generation(&mut self) { - self.mirrors.table_switch.forget(); - self.refresh_translations(); - } - - /// [`Self::advance_translation_generation`] keeping the native TTBR0 - /// switch entries (`x86_64::table_switch`), for a TLBI that leaves - /// every lookup context and a permissions change. An entry names - /// nothing a translation holds: its lower context is the one of its - /// TTBR0 under the controls its upper context was made with (the two - /// halves' contexts are keyed by the same controls but TTBR0, and a - /// context's number is never given again), which the thunk checks, and - /// its host set, whose generation and class (the rights and the lower - /// half's TCR fields) the thunk checks too. What lookup contexts go - /// forgets them ([`Self::forget_contexts`]). - pub(super) fn refresh_translations(&mut self) { - self.mirrors.close_code_page(); - self.forget_device_reads(); - self.mirrors.transitions.contexts_moved(); - self.translation_generation = self - .translation_generation - .checked_add(1) - .expect("architectural translation generation exhausted"); - } - - /// What TTBR0 or its ASID selects may have changed. - pub(super) fn advance_table_generation(&mut self) { - self.mirrors.close_code_page(); - self.forget_device_reads(); - self.mirrors.transitions.contexts_moved(); - self.table_generation = self - .table_generation - .checked_add(1) - .expect("architectural table generation exhausted"); - } - - /// What `half`'s cached fetches and contexts last as long as: TTBR0 - /// selects the lower half's, and the upper half's once a fetch of it was - /// non-global, by its ASID ([`Self::half_inputs`]). - pub(super) fn fetch_epoch(&self, half: usize) -> FetchEpoch { - let table = half == 0 || self.private_fetches[1]; - ( - self.translation_generation, - if table { self.table_generation } else { 0 }, - ) - } - - /// The translations of the halves `halves` may have changed with no - /// control value showing it: their lookup contexts go, so no lookup - /// translates through their ITLB entries, nor does a cached fetch - /// outlive what [`Self::fetched_through`] learnt of it. The block - /// table's entries stay: they hold for a frame, whatever maps it. - pub(super) fn forget_spaces(&mut self, halves: core::ops::RangeInclusive, cause: usize) { - self.forget_contexts(halves, cause); - self.advance_translation_generation(); - } - - /// Forget the contexts of `halves` that translate `asid`: what a TLBI of - /// one process leaves of the others', which their ITLB entries stay good - /// for. - pub(super) fn forget_asid(&mut self, halves: core::ops::RangeInclusive, asid: u16) { - self.mirrors.table_switch.forget(); - for half in halves { - self.statistics.lookup_forgets[0] += 1; - self.spaces[half].retain(|space| !same_asid(space, asid)); - self.recent[half] = [None; RECENT]; - } - self.advance_table_generation(); - } - - /// A TLBI of everything of some regimes reached nothing of `regime`'s - /// ([`mmu::tlbi::Scope::reach`] answered [`mmu::tlbi::Reach::Nothing`] - /// for the context the PE translates in): the contexts of other - /// regimes go, which it may have reached, and `regime`'s stay. - fn forget_other_regimes(&mut self, regime: mmu::Regime) { - self.mirrors.table_switch.forget(); - let mut forgot = false; - for half in 0..2 { - if self.spaces[half].len() == 0 { - continue; - } - if self.spaces[half].iter().all(|space| space.regime != regime) { - self.forget_contexts(half..=half, 1); - forgot = true; - continue; - } - if self.spaces[half].retain(|space| space.regime == regime) != 0 { - self.statistics.lookup_forgets[1] += 1; - self.recent[half] = [None; RECENT]; - forgot = true; - } - } - let source = if forgot { - ItlbSource::AllForgot - } else { - ItlbSource::AllKept - }; - self.statistics.itlb_sources[source as usize] += 1; - self.advance_translation_generation(); - } - - /// [`Self::forget_spaces`] for a caller that advances the generation. - pub(super) fn forget_contexts( - &mut self, - halves: core::ops::RangeInclusive, - cause: usize, - ) { - // Native switches name contexts by number. - self.mirrors.table_switch.forget(); - let upper_stays = !halves.contains(&1); - for half in halves { - self.refill_after(half); - self.statistics.lookup_forgets[cause] += 1; - self.forget_kept_records(half); - self.spaces[half].clear(); - self.recent[half] = [None; RECENT]; - // The upper half's live contexts may hold lower-half global - // pages (`itlb_context`), which TLBIs by VA must still reach - // through what the lower half's fetches recorded. - let keep_filter = half == 0 && upper_stays && self.spaces[1].len() != 0; - if !keep_filter { - self.clear_fetched_leaves(half); - } - self.private_fetches[half] = false; - if half == 0 { - self.lower_globals = NO_GLOBALS; - } - } - } - - /// Clear `half`'s filter of the leaves its fetches translated through - /// ([`Self::fetched_through`]): a TLBI by VA then reaches none of its - /// lookup entries until a fetch, or a kept entry's verification - /// (`tlbi_keep.rs`), records one again. - pub(super) fn clear_fetched_leaves(&mut self, half: usize) { - // Bits are inserted with a fetched size and only cleared here. - if core::mem::take(&mut self.fetched_sizes[half]) != 0 { - let filter = &mut self.fetched_leaves[half]; - match &mut self.fetched_words[half] { - Some(words) => { - for word in words.drain(..) { - filter[word as usize] = 0; - } - } - words @ None => { - filter.fill(0); - *words = Some(Vec::new()); - } - } - } - } - - /// A fetch in `half` translated through a leaf of `size` bytes. The - /// upper half's contexts leave out the ASID until a fetch of it is - /// non-global ([`Self::half_inputs`]): the first such fetch forgets - /// them, as their entries may name blocks of another ASID's page. - pub(super) fn fetched_through(&mut self, half: usize, pc: u64, size: u64, global: bool) { - if half == 1 && !global && !self.private_fetches[1] { - self.forget_spaces(1..=1, 3); - } - let leaf = size.next_power_of_two(); - let filter = &mut self.fetched_leaves[half]; - if filter.is_empty() { - *filter = vec![0; FETCHED_LEAVES / 64]; - } - let words = &mut self.fetched_words[half]; - for (word, bit) in fetched_leaf_bits(pc & !(leaf - 1), leaf) { - if filter[word] == 0 { - match words { - Some(set) if set.len() < FETCHED_WORDS => set.push(word as u32), - _ => *words = None, - } - } - filter[word] |= bit; - } - self.fetched_sizes[half] |= leaf; - self.private_fetches[half] |= !global; - if half == 0 && global { - let (first, last) = self.lower_globals; - self.lower_globals = (first.min(pc), last.max(pc.saturating_add(size))); - } - } - - /// Whether a fetch of `half` translated through the leaf of `size` bytes - /// at `base`, or through one that shares its filter bits. - fn leaf_fetched(&self, half: usize, base: u64, size: u64) -> bool { - fetched_leaf_bits(base, size) - .iter() - .all(|&(word, bit)| self.fetched_leaves[half][word] & bit != 0) - } - - /// The span of `half` a TLBI of `first..=last` can reach of what it - /// fetched: the leaves around them that fetches translated through, at - /// each size such leaves had. - fn fetched_span(&self, half: usize, first: u64, last: u64) -> Option<(u64, u64)> { - const UPPER: u64 = !0 << 55; - let (low, high) = [(0, !UPPER), (UPPER, u64::MAX)][half]; - if last < low || first > high { - return None; - } - let (first, last) = (first.max(low), last.min(high)); - let mut span: Option<(u64, u64)> = None; - let mut sizes = self.fetched_sizes[half]; - while sizes != 0 { - let size = sizes.isolate_lowest_one(); - sizes &= sizes - 1; - let (start, end) = (first & !(size - 1), last | (size - 1)); - let leaves = (end - start) / size; - let fetched = leaves >= SCANNED_LEAVES - || (0..=leaves).any(|leaf| self.leaf_fetched(half, start + leaf * size, size)); - if fetched { - span = Some(span.map_or((start, end), |(lowest, highest)| { - (lowest.min(start), highest.max(end)) - })); - } - } - span - } - - /// Drop the cached fetches of the pages a TLBI reaches in the current - /// translation: all of them if it reaches more than the cache holds. - fn forget_fetches(&mut self, reach: mmu::tlbi::Reach) { - let (first, last) = match reach { - mmu::tlbi::Reach::Nothing => return, - mmu::tlbi::Reach::All => return self.refresh_translations(), - mmu::tlbi::Reach::Containing(address) => (address, address), - mmu::tlbi::Reach::Overlapping { first, last } => (first, last), - }; - for half in 0..2 { - let Some((first, last)) = self.fetched_span(half, first, last) else { - continue; - }; - if (last - first) / FETCH_PAGE >= FETCH_CACHE as u64 { - return self.refresh_translations(); - } - for page in (first..=last).step_by(FETCH_PAGE as usize) { - let slot = (page / FETCH_PAGE) as usize % FETCH_CACHE; - if self.fetch[slot].is_some_and(|entry| (first..=last).contains(&entry.page)) { - self.fetch[slot] = None; - } - } - } - } - - /// Drop the ITLB entries of the pages a TLBI by VA reaches - /// ([`Self::fetched_span`]), as Arm `TLBIMatch` selects TLB entries: - /// - without an ASID (VAAE1, VAALE1, RVAAE1, RVAALE1 and their IS/OS - /// forms, and every upper-half span): those of every context; - /// - with `asid` (VAE1, VALE1, RVAE1, RVALE1 and their IS/OS forms) in - /// the lower half: those of `asid`'s contexts, and in any context - /// those whose walk ended in a global leaf - /// ([`chain::LookupEntry::is_global_page`]), which match every ASID. - /// A non-global entry of another ASID stays. A context's ASID is the - /// one its regime's TCR.A1 selects from TTBR0 or TTBR1 - /// ([`mmu::current_asid`]), both of which its key holds, with the - /// 8 high bits ignored as for TCR.AS=0 (more entries go, never - /// fewer). - /// - /// A process's exit reaches its own pages this way and leaves the other - /// processes' private pages. The ITLB finds the entries of the span's - /// pages in every context from its index of where each granule's went - /// (`chain::LookupTable`). Contexts stay: the hot pages of one that went - /// would each cost an exit on every PE that runs them. The block table's - /// entries stay too: a page translated anew finds them again by its - /// frame. - pub(super) fn forget_lookups(&mut self, reach: mmu::tlbi::Reach, asid: Option) { - let (first, last) = match reach { - mmu::tlbi::Reach::Nothing => return, - mmu::tlbi::Reach::All => return self.forget_spaces(0..=1, 1), - mmu::tlbi::Reach::Containing(address) => (address, address), - mmu::tlbi::Reach::Overlapping { first, last } => (first, last), - }; - for half in 0..2 { - let Some((first, last)) = self.fetched_span(half, first, last) else { - continue; - }; - let scoped = asid.filter(|_| half == 0); - let every = &self.spaces; - let spaces = &every[half]; - let (ghosts, statistics) = (&mut self.itlb_ghosts, &mut self.statistics); - let dropped = &mut self.dropped_refills; - let forget = |entry: &chain::LookupEntry| { - let source = match scoped { - None => Some(ItlbSource::DropEvery), - Some(_) if entry.is_global_page() => Some(ItlbSource::DropEvery), - Some(asid) => spaces - .live(entry.key) - .is_some_and(|space| same_asid(space, asid)) - .then_some(ItlbSource::DropAsid), - }; - let Some(source) = source else { - return false; - }; - statistics.itlb_drops[1] += 1; - statistics.itlb_sources[source as usize] += 1; - if source == ItlbSource::DropEvery { - let every = match (half, scoped) { - (1, _) => ItlbSource::DropUpper, - (_, None) => ItlbSource::DropNoAsid, - _ => ItlbSource::DropGlobal, - }; - statistics.itlb_sources[every as usize] += 1; - } - super::compilation::note_itlb_ghost(ghosts, entry, ItlbMiss::Forgotten); - // A lower-half global page's entry is in an upper-half - // context (`itlb_context`). - if every.iter().any(|spaces| spaces.live(entry.key).is_some()) { - Self::keep_dropped( - dropped, - |number| every.iter().any(|spaces| spaces.live(number).is_some()), - entry.key, - entry.pc, - ); - } - true - }; - if self.itlb.forget_range_where(first..=last, forget) { - self.statistics.lookup_forgets[2] += 1; - } - } - } - - /// A translation control changed: cached fetch translations go, and - /// of the host's shadow what the new controls translate differently - /// ([`Host::set_regime`]). Lookup contexts are keyed by the controls' - /// values ([`contexts::Key`]), so a return to earlier ones finds theirs - /// again. - pub(super) fn controls_changed(&mut self) { - self.derived_changed(); - self.mirrors.table_switch.forget(); - self.permissions_changed(); - } - - /// TCR changed the layout of translation ([`Self::layout_written`]): - /// everything that translates goes, as after any control: fetch - /// translations, lookup contexts, the code page and device reads, and - /// the host's shadow follows the new controls. - pub(super) fn layout_changed(&mut self) { - self.advance_translation_generation(); - self.statistics.translation_changes += 1; - self.sync_host_regime(step_timing::SyncSource::Translation); - } - - /// Translation changed, but nothing derived from System registers: - /// an SPRR_PERM write, which XNU makes around its writes to protected - /// data and at thread switches, thousands of times a second. - pub(super) fn permissions_changed(&mut self) { - self.mirrors.close(SPRR_PERM_MIRROR); - self.refresh_translations(); - self.statistics.translation_changes += 1; - self.sync_host_regime(step_timing::SyncSource::Translation); - } - - /// Anything about translation may have changed: every lookup context - /// goes too, and the whole shadow. - pub(super) fn translations_changed(&mut self) { - self.forget_contexts(0..=1, 3); - self.host.invalidate_translations(); - self.controls_changed(); - } - - /// The host's answers to [`Host::fetch_permitted`] changed: every later - /// fetch translates and asks again, and no cached, looked-up or chained - /// transfer enters a block of another page before it has. - pub fn fetch_permissions_changed(&mut self) { - self.forget_spaces(0..=1, 3); - } - - /// A TLBI: the fetch translations `reach` names go, and the host drops - /// what it names of its shadow. Of the lookup table, which - /// holds every context's entries, it drops what `everywhere` names: the - /// entries at its VAs, or the contexts of the halves non-global entries - /// were fetched through, or every context. No control changed, so the - /// regime and what derives from System registers stay. - pub(super) fn tlb_maintained( - &mut self, - reach: mmu::tlbi::Reach, - everywhere: mmu::tlbi::Everywhere, - asid: Option, - ) { - self.mirrors.close_code_page(); - self.forget_device_reads(); - let mut whole = None; - match everywhere { - mmu::tlbi::Everywhere::Addresses(addresses) - | mmu::tlbi::Everywhere::AsidAddresses(addresses, _) => { - // Canonical memory's kept TLBs refresh on the generation. - if self.canonical_memory_serves() { - self.refresh_translations(); - } else { - self.forget_fetches(reach); - } - self.forget_lookups(addresses, asid); - } - mmu::tlbi::Everywhere::NonGlobal(_) => { - let last = usize::from(self.private_fetches[1]); - match asid { - Some(asid) => self.forget_asid(0..=last, asid), - None => self.forget_spaces(0..=last, 0), - } - } - // The forms without an address. One that reaches nothing of the - // regime the PE translates in reaches no entry of it - // (`Scope::reach`, `Scope::covers`). - mmu::tlbi::Everywhere::All if reach == mmu::tlbi::Reach::Nothing => { - self.forget_other_regimes(self.cpu.tlbi_current().regime); - } - mmu::tlbi::Everywhere::All => { - // Mail's whole invalidations count as received too - // (`itlb_drops`' mail_all tells them apart). - let source = match self.applying_mail { - true => ItlbSource::AllReceived, - false => ItlbSource::AllLocal, - }; - self.statistics.itlb_sources[source as usize] += 1; - let started = self.whole_tlbi_clock(); - let live = - !self.fill_log.is_empty() || self.spaces.iter().any(|spaces| spaces.len() != 0); - if self.tlbi_keep.on { - // `--tlbi-keep on`: kept, and verified before any use. - self.keep_spaces(); - } else { - self.forget_spaces(0..=1, 1); - } - if !self.applying_mail { - whole = Some((started, live)); - } - } - } - self.statistics.tlb_maintenance += 1; - if reach != mmu::tlbi::Reach::All { - self.statistics.scoped_maintenance += 1; - } - let forgot = match whole { - Some(_) => self.whole_tlbi_clock(), - None => 0, - }; - self.host.invalidate_reach(reach, everywhere); - // A local TLBI of everything: its PC, whether the ITLB held - // anything, and, under step timing, the time of the engine's and - // the host's parts. - if let Some((started, live)) = whole { - let done = self.whole_tlbi_clock(); - self.statistics.whole_tlbi_sites.add(self.cpu.pc, 1); - self.note_whole_tlbi_trigger(); - let times = &mut self.statistics.whole_tlbi_times; - times[0] += u64::from(live); - times[1] += forgot.wrapping_sub(started); - times[2] += done.wrapping_sub(forgot); - } - } - - /// What came before this PE's own TLBI of everything: whether TTBR0_EL1 - /// changed since its previous one and, under step timing, one in - /// [`WHOLE_TLBI_SAMPLE_EVERY`] sampled ([`WholeTlbiTrigger`]). Reads - /// registers only. - fn note_whole_tlbi_trigger(&mut self) { - let ttbr0 = self.cpu.read(SystemRegister::TTBR0_EL1); - let switched = self.whole_tlbis != 0 && ttbr0 != self.whole_tlbi_ttbr0; - let sample = (self.step_timing.is_some() - && self.whole_tlbis.is_multiple_of(WHOLE_TLBI_SAMPLE_EVERY)) - .then(|| { - [ - self.cpu.pc, - self.cpu.state.x[16], - self.cpu.state.x[30], - self.whole_tlbi_ttbr0, - ttbr0, - ] - }); - self.statistics.whole_tlbi_trigger.note(switched, sample); - self.whole_tlbi_ttbr0 = ttbr0; - self.whole_tlbis += 1; - } - - /// The counter, for the times of a TLBI of everything, while step - /// timing is on; zero otherwise. A guest flushes everything often, and - /// timing it is profiling, which normal runs do not pay for - /// (`system_access_samples_the_counter_and_interrupts_only_when_needed`). - fn whole_tlbi_clock(&mut self) -> u64 { - match self.step_timing { - Some(_) => self.host.counter(), - None => 0, - } - } - - /// A TTBR0 write, which changes the translation of the lower half - /// alone: the regime's new controls tell the host so - /// ([`Host::set_regime`]), which keeps the upper half's shadow. Lookup - /// contexts are keyed by its value, as by every control's. - pub(super) fn table_base_changed(&mut self) { - self.advance_table_generation(); - self.statistics.table_base_changes += 1; - self.sync_host_regime(step_timing::SyncSource::TableBase); - } - - /// Forget the blocks compiled from the page holding `physical`, which an - /// IC IVAU made stale, and their lookup entries, which every address - /// space mapping the frame shares: a later fetch compiles the page - /// again. Their code stays installed until its part is reclaimed. - pub(super) fn invalidate_code_page(&mut self, physical: u64) { - self.invalidate_single_code_page(physical); - // An HLE composite installed inside a 16 KiB guest leaf may cross one - // 4 KiB fetch boundary; retire any HLE block on the preceding 4 KiB - // subpage of the same 16 KiB granule. - if self.hle_enabled() && (physical & (16 * 1024 - 1)) >= FETCH_PAGE { - let prev = (physical & !(FETCH_PAGE - 1)) - FETCH_PAGE; - let has_hle = { - let code = Arc::clone(&self.code); - let cache = code.page_at(prev, board::LockSite::Invalidate); - cache - .index - .page(prev) - .any(|slot| code.blocks.get(slot).is_some_and(|b| b.hle.is_some())) - }; - if has_hle { - self.invalidate_single_code_page(prev); - } - } - } - - fn invalidate_single_code_page(&mut self, physical: u64) { - let frame = frame_number(physical); - let code = Arc::clone(&self.code); - let mut cache = code.page_at(physical, board::LockSite::Invalidate); - // The page's blocks leave the index, so no detach finds them as - // sources again: their links out are cut now. - let page: Vec = cache.index.page(physical).collect(); - for &slot in &page { - self.note_gone(&mut cache, slot, churn::Gone::Invalidated); - } - self.unlink_sources(&page); - // A paired frame pushed in one of them fails from here on. - if !page.is_empty() { - code.blocks.advance_epoch(); - } - code.cache_at(board::LockSite::Invalidate) - .targets - .forget_frames(frame..=frame, |_| true); - let forgot = cache.index.forget_page(physical & !(FETCH_PAGE - 1)); - drop(cache); - // Every PE's jump cache on a shared board still names its blocks. - if forgot || self.code_hub.is_some() { - self.forget_code_page_here(physical); - } else { - self.forget_page_caches(physical); - } - } - - /// Another PE's IC IVAU of the page holding `physical`. On a shared - /// board the poster forgot the page already, but this PE may have read - /// the old bytes before the write and published their block after that - /// forget: a compile runs outside, so the post did not wait for it. It - /// reads its mail only after it published, so forgetting the page again - /// here takes such a block away. - pub(super) fn invalidate_posted_code_page(&mut self, physical: u64) { - self.invalidate_code_page(physical); - } - - /// Forget this PE's caches of the page holding `physical`, and its jump - /// cache. - fn forget_code_page_here(&mut self, physical: u64) { - self.forget_page_caches(physical); - // The jump cache holds no generation per page. - self.code_generation += 1; - self.statistics.code_invalidations += 1; - } - - /// Forget this PE's stored page, waiting direct exit and known key of - /// the page holding `physical`. - fn forget_page_caches(&mut self, physical: u64) { - self.forget_stored_page(physical & !(FETCH_PAGE - 1)); - // A forgotten block's exit waits for no block of its page. - if self.direct_exit.is_some_and(|(block, ..)| { - (self.code.blocks[block].physical ^ physical) & !(FETCH_PAGE - 1) == 0 - }) { - self.direct_exit = None; - } - self.forget_known_key(physical & !(FETCH_PAGE - 1)); - } - - /// Make room in the code arena: reclaim its oldest part, or discard - /// every block on a host whose arena is one part. - pub(super) fn reclaim_code(&mut self) { - // A ring reclaims its parts as installs fill it. - if self.code.arena.is_some() { - return; - } - self.lookup_dispatchers = Default::default(); - match self.host.reclaim_code() { - Some(range) => self.evict_code(range), - None => self.discard_code(Discard::Arena), - } - } - - /// Make room in the host's own arena for a leaf. With the board's - /// arena holding the blocks, the host's holds only leaves: its oldest - /// part goes with the leaves in it. - pub(super) fn reclaim_leaves(&mut self) { - if self.code.arena.is_none() { - return self.reclaim_code(); - } - match self.host.reclaim_code() { - Some(range) => self - .scalable_leaves - .retain(|_, leaf| !range.contains(&leaf.code.0)), - None => { - self.host.discard_code(); - self.scalable_leaves.clear(); - } - } - } - - /// Release local code owners under pressure before allocating compilation - /// input and recovery metadata: the oldest arena part's blocks, or every - /// block on a host whose arena is one part. - /// - /// Memory another machine or the shared store holds stays low however - /// much this one releases, so within one stretch of pressure a machine - /// reclaims again only once it holds as many blocks as it did at its - /// last reclaim: its growth stays bounded, and it does not release code - /// before every block it installs. A machine holding fewer than - /// [`MEMORY_RELEASE_BLOCKS`] keeps them: what they free would not - /// relieve the heap. - pub(super) fn reclaim_for_memory(&mut self) { - // A ring's blocks are bounded by its bytes. - if self.code.arena.is_some() || !self.host.memory_low() { - self.reclaimed_at = None; - return; - } - let live = self.code.blocks.live(); - if live < self.memory_release_blocks.max(1) - || self.reclaimed_at.is_some_and(|held| live < held) - { - return; - } - self.reclaimed_at = Some(live); - self.statistics.code_releases += 1; - match self.host.release_oldest_code() { - Some(range) => self.evict_code(range), - None => self.discard_code(Discard::Memory), - } - } - - /// The grace slots this machine releases go to limbo under, and the PE - /// it is there: a machine that keeps its code alone has a grace of no - /// PE, so its slots are free again at once. - pub(super) fn grace(&self) -> (&board::Grace, Option) { - match &self.code_hub { - Some(hub) => (&hub.board.grace, Some(self.current)), - None => (&self.alone, None), - } - } - - /// Install native `bytes`: in the board's arena when it has one, else - /// in the host's. `retire` lets a full ring take away its oldest part's - /// code to make room, for a caller outside the board's lock: a block's - /// install ([`Self::place`]), which keeps its places until it publishes - /// ([`Self::release_places`]), so that their parts are not opened again - /// meanwhile. An install it makes for the block (a thunk) holds the - /// block's place, so it never waits for a grace or a part another - /// install holds: it finds the arena full instead. Without `retire` the - /// caller holds the board's lock from the take to its last write, and - /// the lock keeps the part, as no retirement ends without it. - pub(super) fn install_native( - &mut self, - bytes: &[u8], - retire: bool, - ) -> Result { - let stream = core::mem::replace(&mut self.install_stream, board::YOUNG); - let code = Arc::clone(&self.code); - let Some(arena) = &code.arena else { - return self.host.install(bytes); - }; - if bytes.len() > arena.part_bytes { - return Err(InstallError::Full); - } - #[cfg(debug_assertions)] - self.assert_portable(bytes); - // A part being retired takes a bounded step or a few at each install: - // not for a link's thunk, whose caller holds the code lock. - if retire { - self.retire_steps(self.retire_budget()); - } - let holding = !self.held_places.is_empty(); - loop { - let full = match arena.ring.take(stream, bytes.len(), 16) { - Ok(place) => { - let address = arena.address(place); - arena.write(address, bytes); - self.install_causes.window_bytes += bytes.len().next_multiple_of(16) as u64; - self.install_causes.window_pieces += 1; - self.host.serialize_code(); - if retire { - self.held_places.push(place); - } else { - arena.ring.release(place); - } - return Ok(NativeCode(address)); - } - Err(full) => full, - }; - if !retire { - return Err(InstallError::Full); - } - let (grace, skip) = self.grace(); - match arena.ring.advance(stream, full, grace, skip) { - board::Advance::Moved => {} - // A PE that waits on another's install while holding a - // place could be the one that install waits on. - board::Advance::Busy | board::Advance::Wait(_) if holding => { - return Err(InstallError::Full); - } - // The next part is still being taken away or written: help. - board::Advance::Busy => { - self.retire_steps(self.retire_budget()); - self.host.relax(); - } - board::Advance::Retire(part, _) => { - self.retire_part(part, churn::Gone::Ring); - } - board::Advance::Wait(snapshot) => self.wait_grace(&snapshot), - } - } - } - - /// Host counter ticks of retirement steps one install takes: half a - /// millisecond, so no PE stalls the guest count for a whole part. - fn retire_budget(&self) -> u64 { - (self.profile.counter_frequency / 2000).max(1) - } - - /// Code in the board's arena runs on every PE: it names none of this - /// PE's own data by address, only through its anchors, whose values - /// differ by PE ([`Self::anchors`]). - #[cfg(debug_assertions)] - fn assert_portable(&self, bytes: &[u8]) { - let anchors = self.anchors(); - let own = [ - anchors[Anchor::Control], - anchors[Anchor::Mirrors], - anchors[Anchor::Cells], - anchors[Anchor::Pointer], - anchors[Anchor::Memo], - anchors[Anchor::Count], - anchors[Anchor::StackZero], - anchors[Anchor::Amx], - &self.cpu.state as *const _ as u64, - ]; - for window in bytes.windows(8) { - let value = u64::from_le_bytes(window.try_into().expect("eight bytes")); - assert!( - value == 0 || !own.contains(&value), - "board code names PE {}'s own address {value:#x}", - self.current - ); - } - } - - /// Overwrite installed code at `code` with `bytes`. - pub(super) fn patch_native(&mut self, code: NativeCode, bytes: &[u8]) { - match &self.code.arena { - Some(arena) => { - arena.write(code.0, bytes); - self.host.serialize_code(); - } - None => self.host.patch(code, bytes), - } - } - - /// Replace the instruction at patch point `code`, which a core may be - /// running, in one store (`Host::patch_instruction`). - pub(super) fn patch_point(&mut self, code: NativeCode, instruction: [u8; chain::PATCH_BYTES]) { - match &self.code.arena { - Some(arena) => { - assert!(chain::patchable(code.0 as u64), "a patch point"); - arena.patch_point(code.0 as u64, instruction); - self.host.serialize_code(); - } - None => self.host.patch_instruction(code, instruction), - } - } - - /// Unlink the exits whose patch points and instructions are `unlinks`, - /// each in one store ([`Self::patch_point`]). In the board's arena the - /// writer serializes once after the last: no other core's fetch depends - /// on it, and this core runs none of them before it returns. - pub(super) fn unlink_points(&mut self, unlinks: Vec<(u64, [u8; chain::PATCH_BYTES])>) { - self.statistics.unlinks += unlinks.len() as u64; - let Some(arena) = &self.code.arena else { - for (point, instruction) in unlinks { - self.host - .patch_instruction(NativeCode(point as usize), instruction); - } - return; - }; - if unlinks.is_empty() { - return; - } - for (point, instruction) in unlinks { - assert!(chain::patchable(point), "a patch point"); - arena.patch_point(point, instruction); - } - self.host.serialize_code(); - } - - /// The generation of the arena part holding executable `address`, for - /// code that part's code jumps to: a thunk or a tail goes with the - /// block it serves ([`board::Ring::refer`]). - pub(super) fn stream_at(&self, address: u64) -> usize { - let arena = self.code.arena.as_ref(); - arena - .and_then(|arena| Some(arena.ring.kind(arena.part_of(address as usize)?))) - .unwrap_or(board::YOUNG) - } - - /// Code at `from` is about to jump to `to`, which the caller just - /// installed and still holds: `to`'s part stays while `from`'s does. - /// False when `to`'s part was chosen to go meanwhile: the caller makes - /// no jump, and its exit stays an exit to the engine. Under the board's - /// lock, or before `from`'s block is published. - #[must_use] - pub(super) fn note_reference(&self, from: u64, to: u64) -> bool { - if let Some(arena) = &self.code.arena - && let (Some(from), Some(to)) = - (arena.part_of(from as usize), arena.part_of(to as usize)) - && !arena.ring.refer(from, to) - { - board::Events::count(&self.code.events.refused); - return false; - } - true - } - - /// The places this PE's install took ([`Self::install_native`]) are - /// published or given up: their parts may be opened again. - pub(super) fn release_places(&mut self) { - if let Some(arena) = &self.code.arena { - for place in self.held_places.drain(..) { - arena.ring.release(place); - } - } - } - - /// A fetch found block `slot`: its part counts an entry, for the choice - /// of the tenured part to go ([`board::Ring::entered`]). The PE keeps - /// its counts and adds them to the ring's every [`ENTERED_BATCH`] - /// fetches, before each install (where the ring chooses) and when it - /// leaves its run loop: the hottest part's count is one line every PE's - /// fetches would write. The choice needs only the parts' order by - /// heat, which a batch of at most that many fetches per PE leaves. - pub(super) fn entered(&mut self, slot: usize) { - if self.step_timing.is_some() { - self.code.blocks.record(slot).fetched(); - } - let part = self.code.blocks[slot].part; - if part == board::NO_PART { - return; - } - let part = usize::from(part); - if self.entered_pending.len() <= part { - self.entered_pending.resize(part + 1, 0); - } - self.entered_pending[part] += 1; - self.entered_total += 1; - if self.entered_total >= ENTERED_BATCH { - self.flush_entered(); - } - } - - /// Add this PE's kept part entries to the ring's counts. - pub(super) fn flush_entered(&mut self) { - if self.entered_total == 0 { - return; - } - self.entered_total = 0; - let Some(arena) = &self.code.arena else { - return; - }; - for (part, count) in self.entered_pending.iter_mut().enumerate() { - if *count != 0 { - arena.ring.entered_by(part, core::mem::take(count)); - } - } - } - - /// The generation a block of `pc`, `physical` and `variant` goes to: - /// tenured when the ring took it away within a few turns - /// ([`churn::Churn::promotes`]). - pub(super) fn stream_for(&self, pc: u64, physical: u64, variant: VariantId) -> usize { - let Some(arena) = &self.code.arena else { - return board::YOUNG; - }; - let identity = churn::identity(pc, physical, variant.0); - let ring = &arena.ring; - if ring.young_parts != 0 - && self - .code - .ghosts - .promotes(identity, ring.generation(), ring.parts) - { - board::Events::count(&self.code.events.promoted); - board::TENURED - } else { - board::YOUNG - } - } - - /// The ring's current generation and parts, or zeros without a ring. - fn ring_position(&self) -> (u32, u32) { - self.code - .arena - .as_ref() - .map_or((0, 0), |arena| (arena.ring.generation(), arena.ring.parts)) - } - - /// Note that block `slot` leaves the index for `cause` - /// ([`churn::Churn::gone`]). Under the board's lock, `cache`. - pub(super) fn note_gone(&self, cache: &mut board::Shard, slot: usize, cause: churn::Gone) { - let block = &self.code.blocks[slot]; - let identity = churn::identity(block.pc, block.physical, block.variant.0); - let (generation, _) = self.ring_position(); - self.code.ghosts.gone( - &mut cache.churn, - identity, - block.source_hash, - generation, - cause, - ); - // A hole in a part that stays: its part may go early. - if cause == churn::Gone::Invalidated - && let Some(arena) = &self.code.arena - && let Some(part) = arena.part_of(block.code.0) - { - arena.ring.dropped(part); - } - } - - /// Note the install of block `slot`, before it enters the index - /// ([`churn::Churn::installed`]). Under the board's lock, `cache`. - pub(super) fn note_churn(&self, cache: &mut board::Shard, slot: usize) { - let blocks = &self.code.blocks; - let block = &blocks[slot]; - let shared = cache - .index - .sharing(blocks, block.pc, block.physical, block.variant); - // Its page runs at two addresses: its compiles keep their forms - // ([`super::rebase`]). - if shared == Some(true) { - self.code.rebases.note_shared(block.physical); - } - let identity = churn::identity(block.pc, block.physical, block.variant.0); - let (generation, parts) = self.ring_position(); - self.code.ghosts.installed( - &mut cache.churn, - identity, - block.source_hash, - generation, - shared, - parts, - ); - if let Some(arena) = &self.code.arena - && let Some(part) = arena.part_of(block.code.0) - { - arena.ring.installed(part); - } - } - - /// With every block slot given, move the board's ring on before its - /// parts are full, taking the oldest parts' blocks away and waiting for - /// their grace, until a slot is free. The caller installs its code again - /// after: its part may be one that went. A slot, if that freed one. - pub(super) fn retire_for_slot(&mut self) -> Option { - let code = Arc::clone(&self.code); - let arena = code.arena.as_ref()?; - for _ in 0..2 * arena.ring.parts { - if let Some(slot) = self.take_slot() { - return Some(slot); - } - let (grace, skip) = self.grace(); - let young = arena.ring.head(board::YOUNG); - match arena.ring.advance(board::YOUNG, young, grace, skip) { - board::Advance::Moved => {} - board::Advance::Busy => { - self.retire_steps(u64::MAX); - self.host.relax(); - } - board::Advance::Retire(part, _) => { - self.retire_part(part, churn::Gone::Slot); - // Short of slots: all of it now. - self.retire_steps(u64::MAX); - board::Events::count(&code.events.forced); - let snapshot = self.grace().0.snapshot(); - self.wait_grace(&snapshot); - } - board::Advance::Wait(snapshot) => self.wait_grace(&snapshot), - } - } - self.take_slot() - } - - /// Take away the code of the ring's `part`, which this - /// PE moved the ring past ([`board::Advance::Retire`]): its blocks go - /// as in a reclaim, and its probes, in steps the board's installs take - /// ([`Self::retire_steps`]); the part is reused once the last step is - /// done and every PE passed the grace taken after. - fn retire_part(&mut self, part: u32, cause: churn::Gone) { - let code = Arc::clone(&self.code); - let range = code - .arena - .as_ref() - .expect("a ring retires its parts") - .range(part); - let mut job = self.retirement(range, Some(part)); - job.cause = cause; - let mut held = code - .retiring - .lock() - .unwrap_or_else(|error| error.into_inner()); - // The ring moves on only once the last retirement ended, so none is - // left; one would be finished here first. - if let Some(mut left) = held.take() { - while !self.retire_step(&mut left) {} - self.finish_retirement(left); - } - *held = Some(job); - code.retire_pending.store(true, Ordering::Release); - drop(held); - self.retire_steps(self.retire_budget()); - } - - /// Take steps of the board's retirement under way, if no other PE is, - /// until it ends or `budget` host counter ticks passed. - pub(super) fn retire_steps(&mut self, budget: u64) { - if !self.code.retire_pending.load(Ordering::Acquire) { - return; - } - let code = Arc::clone(&self.code); - let Ok(mut held) = code.retiring.try_lock() else { - return; - }; - let started = self.host.counter(); - loop { - let Some(job) = held.as_mut() else { - return; - }; - if self.retire_step(job) { - break; - } - if self.host.counter().wrapping_sub(started) >= budget { - self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); - return; - } - } - let job = held.take().expect("a retirement that ended"); - code.retire_pending.store(false, Ordering::Release); - drop(held); - self.finish_retirement(job); - self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); - } - - /// A retirement of the blocks whose code lies in `range`. - fn retirement( - &mut self, - range: core::ops::Range, - part: Option, - ) -> board::Retirement { - let code = Arc::clone(&self.code); - let listed = code - .code_slots - .lock() - .unwrap_or_else(|error| error.into_inner()) - .take(&range); - // Without a list, every slot's record, read without the lock: the - // range takes no new block. - let evicted = listed.unwrap_or_else(|| { - code.blocks - .iter() - .filter(|&(slot, block)| { - code.blocks.record(slot).live() && range.contains(&block.code.0) - }) - .map(|(slot, _)| slot as u32) - .collect() - }); - let mut slots: Vec<(u64, u32)> = evicted - .iter() - .map(|&slot| { - ( - code.blocks[slot as usize].physical & !(FETCH_PAGE - 1), - slot, - ) - }) - .collect(); - slots.sort_unstable(); - code.code_slots - .lock() - .unwrap_or_else(|error| error.into_inner()) - .give_back(evicted); - board::Retirement { - part, - cause: match part { - Some(_) => churn::Gone::Ring, - None => churn::Gone::Other, - }, - cells: Some(range.start as u64), - range, - slots, - next: 0, - page: None, - pcs: Vec::new(), - ticks: 0, - steps: 0, - visits: 0, - step_visits: 0, - } - } - - /// One step of `job`, one hold of the code lock, of about - /// [`STEP_VISITS`] units of work: the phases of its pages in turn - /// ([`board::PageRetirement`]), and then its range's cells. Between - /// steps no lookup, link or index read reaches a block that left the - /// index, a block retires only once no link into it is left, and the - /// others are still whole. Whether the job is done. - pub(super) fn retire_step(&mut self, job: &mut board::Retirement) -> bool { - let started = board::timestamp(); - let code = Arc::clone(&self.code); - let mut visits = 0; - // The page under way, or the next: a step holds its index shard and - // goes on to later pages of the same shard only. - let frame = match &job.page { - Some(page) => Some(job.slots[page.start].0), - None => job.slots.get(job.next).map(|&(frame, _)| frame), - }; - if let Some(frame) = frame { - let shard = super::block_index::shard_of(frame); - let lock = &code.shards[shard]; - let mut cache = lock.at(board::LockSite::Evict); - loop { - let budget = match lock.wanted() { - true => YIELD_VISITS.min(code.step_visits), - false => code.step_visits, - }; - if visits >= budget { - break; - } - let left = budget - visits; - if job.page.is_none() { - if job.next >= job.slots.len() - || super::block_index::shard_of(job.slots[job.next].0) != shard - { - break; - } - let first = job.slots[job.next].0; - let end = job.next - + job.slots[job.next..].partition_point(|&(page, _)| page == first); - job.pcs.clear(); - job.page = Some(board::PageRetirement { - start: job.next, - end, - phase: board::PagePhase::Unindex(job.next), - }); - } - let page = job.page.as_mut().expect("a page under way"); - let frame = job.slots[page.start].0; - match page.phase { - board::PagePhase::Unindex(from) => { - let to = page.end.min(from + EVICT_STEP.min(left as usize)); - visits += self.unindex( - &mut cache, - frame, - &job.slots[from..to], - &mut job.pcs, - job.cause, - ); - page.phase = if to == page.end { - job.pcs.sort_unstable(); - job.pcs.dedup(); - board::PagePhase::Cut(0) - } else { - board::PagePhase::Unindex(to) - }; - } - board::PagePhase::Cut(from) => { - let (next, cut) = - self.cut_links_into(&mut cache, frame, &job.pcs, from, left as usize); - visits += cut; - page.phase = match next { - Some(next) => board::PagePhase::Cut(next), - None => board::PagePhase::Retire(page.start), - }; - } - board::PagePhase::Retire(from) => { - let to = page.end.min(from + EVICT_STEP.min(left as usize)); - self.retire_blocks(&job.slots[from..to]); - visits += (to - from) as u64; - if to == page.end { - job.next = page.end; - job.page = None; - } else { - page.phase = board::PagePhase::Retire(to); - } - } - } - } - } else if let Some(from) = job.cells { - // The exits in the range go, and with them their cells: no - // block in it is live now, so none links through a cell again. - let most = match code.cache.wanted() { - true => CELL_STEP.min(YIELD_VISITS as usize), - false => CELL_STEP, - } - .min(code.step_visits as usize); - job.cells = code - .cache_at(board::LockSite::Evict) - .targets - .release_some_cells(from..=job.range.end as u64 - 1, most); - visits = most as u64; - } - job.visits += visits; - job.step_visits = job.step_visits.max(visits); - job.ticks += board::timestamp().wrapping_sub(started); - job.steps += 1; - job.next >= job.slots.len() && job.page.is_none() && job.cells.is_none() - } - - /// The blocks `step` of the page at `frame` leave the index, the block - /// table and their links out, and this PE's jump cache and waiting - /// exit; their PCs go to `pcs`. They stay live: links into them are - /// cut next ([`Self::cut_links_into`]). Under the lock of the page's - /// index shard, `cache`, and the block table's for their entries. The - /// work it took, in [`STEP_VISITS`] units: a block each, a sixteenth of - /// the page's index list, and the cells looked at. - fn unindex( - &mut self, - cache: &mut board::Shard, - frame: u64, - step: &[(u64, u32)], - pcs: &mut Vec, - cause: churn::Gone, - ) -> u64 { - let code = Arc::clone(&self.code); - let blocks = &code.blocks; - let slots: Vec = step.iter().map(|&(_, slot)| slot).collect(); - // Only blocks still in the index leave a ghost: one an IC IVAU - // forgot has its own, and a lost install's key is the winner's. - for &slot in &slots { - let block = &blocks[slot as usize]; - if cache - .index - .get(blocks, block.pc, block.physical, block.variant) - == Some(slot as usize) - { - self.note_gone(cache, slot as usize, cause); - } - } - let (_, listed) = cache.index.page_part(frame, 0, 0); - let marked = mark(&mut cache.marked, blocks.len(), &slots); - cache - .index - .forget_marked(frame, |slot| bit_set(&marked, slot)); - unmark(&mut cache.marked, marked, &slots); - let mut visits = (slots.len() + listed / 16) as u64; - let mut unlinks = Vec::new(); - let mut table = code.cache_at(board::LockSite::Evict); - for &slot in &slots { - let block = &blocks[slot as usize]; - for key in block_keys(block) { - visits += table.targets.forget_block(block.pc, key, slot) as u64; - } - } - drop(table); - for &slot in &slots { - let block = &blocks[slot as usize]; - pcs.push(block.pc); - // No detach visits it once it left the index: its links out - // go now, and it links nothing again. - let record = blocks.record(slot as usize); - for (position, exit) in block.successors.iter().enumerate() { - if record.chained(position) { - record.set_linked(position, false, false); - unlinks.push( - chain::unlinked(exit.site, exit.slot.into()) - .expect("a linked exit's patch point"), - ); - } - } - let entry = &mut self.jump[(block.pc / INSTRUCTION) as usize % JUMP_CACHE]; - if entry.is_some_and(|entry| entry.block == slot as usize) { - *entry = None; - } - if self - .direct_exit - .is_some_and(|(waiting, ..)| waiting == slot as usize) - { - self.direct_exit = None; - } - } - self.unlink_points(unlinks); - visits - } - - /// Cut the links of the indexed blocks of the page at `frame`, from - /// position `from` of its list and at most `most` of them, into the - /// sorted `pcs`: those of blocks that left the index. A link names the - /// block a PC and variant have, so a link to any of the PCs goes (one - /// to a block compiled again there links again). Blocks indexed after - /// they left link to none of them. Under the lock of the page's index - /// shard, `cache`. Where the cut goes on, if blocks are left, and the - /// blocks visited. - fn cut_links_into( - &mut self, - cache: &mut board::Shard, - frame: u64, - pcs: &[u64], - from: usize, - most: usize, - ) -> (Option, u64) { - let code = Arc::clone(&self.code); - let blocks = &code.blocks; - let (sources, listed) = cache.index.page_part(frame, from, most); - let mut visited = 0; - let mut unlinks = Vec::new(); - for source in sources { - visited += 1; - let record = blocks.record(source); - for (position, exit) in blocks[source].successors.iter().enumerate() { - if record.chained(position) && pcs.binary_search(&exit.target.0).is_ok() { - record.set_linked(position, false, false); - // Linked, so its point is patchable and in reach. - unlinks.push( - chain::unlinked(exit.site, exit.slot.into()) - .expect("a linked exit's patch point"), - ); - } - } - } - // One store each, which a core running the exit may meet. - self.unlink_points(unlinks); - let next = from + visited; - ((next < listed).then_some(next), visited as u64) - } - - /// Retire the blocks of `step`, which nothing reaches but a core - /// already in one: their slots go once the retirement ends and its - /// grace passed. Under the lock of their page's index shard. - fn retire_blocks(&mut self, step: &[(u64, u32)]) { - let code = Arc::clone(&self.code); - let shared = self.code_hub.is_some(); - let now = self.host.counter(); - // Before any of them retires: a paired frame pushed in one of them - // fails from here on. - if !step.is_empty() { - code.blocks.advance_epoch(); - } - for slot in step.iter().map(|&(_, slot)| slot as usize) { - // On a shared board its rows stay until the slot takes its - // next block: another PE still inside its section may be - // running the block and fault in it. A machine alone runs - // none of it now. - let recovery = code.blocks.recovery(); - let bytes = match shared { - true => recovery.get(&slot).map(|owner| owner.code_bytes()), - false => recovery.remove(&slot).map(|owner| owner.code_bytes()), - } - .unwrap_or(0); - self.census_evicted(slot, bytes, now); - // Retired first: a PE adding its kept exits checks the block's - // incarnation and liveness, so it adds them here before the - // swap or by word after (but for one that checked just before). - code.blocks.retire(slot); - let taken = code.blocks.record(slot).taken.swap(0, Ordering::Relaxed); - if taken != 0 { - *self - .exit_words - .entry(code.blocks[slot].terminal) - .or_default() += u64::from(taken); - } - } - } - - /// The end of `job`, whose steps are done: its slots go once their - /// grace passed, and a ring part's probes and the part itself. - fn finish_retirement(&mut self, job: board::Retirement) { - let code = Arc::clone(&self.code); - let arena = job.part.and_then(|_| code.arena.as_ref()); - if let (Some(_), Some(part)) = (arena, job.part) { - code.cache_at(board::LockSite::Evict) - .dispatchers - .retain(|&(held, _)| held != part); - } - let slots: Vec = job.slots.iter().map(|&(_, slot)| slot).collect(); - let (grace, _) = self.grace(); - code.blocks.release(slots, grace.snapshot()); - if let (Some(arena), Some(part)) = (arena, job.part) { - arena.ring.retired(part, grace.snapshot()); - board::Events::count(&code.events.retired); - } - if !self.scalable_leaves.is_empty() { - self.scalable_leaves - .retain(|_, leaf| !job.range.contains(&leaf.code.0)); - } - if !job.slots.is_empty() { - self.statistics.code_evictions += 1; - } - code.events.retired(&job); - } - - /// Wait until `snapshot`'s grace passed, in rounds bounded by the host - /// counter; the board's first overrun is reported once. A PE inside - /// its section leaves it to wait ([`board::Board::wait`]); outside (a - /// compile), it holds nothing anyone waits on. - fn wait_grace(&mut self, snapshot: &board::Snapshot) { - let Some(hub) = self.code_hub.clone() else { - return; - }; - let events = &self.code.events; - board::Events::count(&events.grace_waits); - let ticks = (self.profile.counter_frequency / 10).max(1); - let pe = self.current; - let waited = if hub.board.grace.inside(pe) { - hub.board.wait(pe, snapshot, ticks, || self.host.counter()) - } else { - let start = self.host.counter(); - loop { - if hub.board.grace.passed(snapshot, None) { - break board::Waited::Passed; - } - if self.host.counter().wrapping_sub(start) >= ticks { - break board::Waited::Overdue { - first: hub.board.overdue(), - }; - } - self.host.relax(); - } - }; - if let board::Waited::Overdue { .. } = waited { - board::Events::count(&self.code.events.overdue); - } - if let board::Waited::Overdue { first: true } = waited { - let requirement = self.requirement(RequirementKind::Native( - "a code part's grace ran past its deadline: its reuse waits", - )); - self.degrade(requirement); - } - } - - /// What the board's machines share: every index entry and block table - /// entry goes, so no fetch, lookup or jump cache entry reaches a block - /// installed before; their code goes as the ring reaches its parts. - fn forget_shared_code(&mut self) { - let mut pages = self.code.every_page(board::LockSite::Discard); - pages.clear(); - self.code.cache_at(board::LockSite::Discard).targets.clear(); - drop(pages); - self.code.epoch.fetch_add(1, Ordering::AcqRel); - } - - /// What jump cache entries are valid in: this machine's code - /// generation and the board's epoch ([`Self::forget_shared_code`]). - pub(super) fn jump_generation(&self) -> u64 { - self.code_generation - .wrapping_add(self.code.epoch.load(Ordering::Acquire) << 40) - } - - /// Forget the blocks and leaves whose code lies in `range`, which the - /// host reclaimed. The other blocks of their pages stay: they chain into - /// them no more ([`Self::detach`]), and take an exit to the engine - /// there until it links them to the blocks compiled again. Only indexed - /// blocks are reached: one replaced in the index was detached then, - /// and the blocks of a page an IC IVAU forgot whole reach only each - /// other, with no lookup entry and in a code generation no jump cache - /// entry names since. Their slots are given again once the grace - /// passed ([`board::Blocks::release`]). - pub(super) fn evict_code(&mut self, range: core::ops::Range) { - // A host with nothing to release says so with an empty range, and - // while memory stays low that comes before every compile. - if range.is_empty() { - return; - } - let started = self.host.counter(); - let mut job = self.retirement(range, None); - while !self.retire_step(&mut job) {} - self.finish_retirement(job); - self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); - } - - /// Cut every chained exit of the blocks in `slots`, which leave the - /// index: under the board's lock. - fn unlink_sources(&mut self, slots: &[usize]) { - let code = Arc::clone(&self.code); - for &source in slots { - let record = code.blocks.record(source); - for (position, exit) in code.blocks[source].successors.iter().enumerate() { - if record.chained(position) { - record.set_linked(position, false, false); - // Linked, so its point is patchable and in reach. - let (point, instruction) = chain::unlinked(exit.site, exit.slot.into()) - .expect("a linked exit's patch point"); - self.patch_point(NativeCode(point as usize), instruction); - self.statistics.unlinks += 1; - } - } - } - } - - /// Make the blocks in the sorted `slots` unreachable: the indexed blocks - /// of their pages undo their links to their PCs (a link names the - /// block a PC and variant have, so any of the page's blocks of the PC - /// may be the one it reached), and their lookup and jump cache - /// entries go. Under the lock of their pages' index shard, `cache`, and - /// the block table's for their entries. - pub(super) fn detach(&mut self, cache: &mut board::Shard, slots: &[u32]) { - let blocks = &self.code.blocks; - let marked = mark(&mut cache.marked, blocks.len(), slots); - let detached = |slot: usize| bit_set(&marked, slot as u32); - let mut gone: Vec<(u64, u64)> = slots - .iter() - .map(|&slot| { - let block = &blocks[slot as usize]; - (block.physical & !(FETCH_PAGE - 1), block.pc) - }) - .collect(); - gone.sort_unstable(); - gone.dedup(); - let mut sources = core::mem::take(&mut cache.page_blocks); - let mut unlinks = Vec::new(); - for page in gone.chunk_by(|a, b| a.0 == b.0) { - sources.extend(cache.index.page(page[0].0)); - for &source in &sources { - if detached(source) { - continue; - } - let record = blocks.record(source); - for (position, exit) in blocks[source].successors.iter().enumerate() { - if record.chained(position) - && page.binary_search(&(page[0].0, exit.target.0)).is_ok() - { - record.set_linked(position, false, false); - // Linked, so its point is patchable and in reach. - let unlink = chain::unlinked(exit.site, exit.slot.into()) - .expect("a linked exit's patch point"); - unlinks.push(unlink); - } - } - } - sources.clear(); - } - cache.page_blocks = sources; - // One store each, which a core running the exit may meet. - self.unlink_points(unlinks); - // Lookup entries go by the frames their keys name, in runs. - let mut frames: Vec = gone.iter().map(|&(page, _)| frame_number(page)).collect(); - frames.dedup(); - let code = Arc::clone(&self.code); - let mut table = code.cache_at(board::LockSite::Install); - for run in frames.chunk_by(|a, b| a + 1 == *b) { - table - .targets - .forget_frames(run[0]..=run[run.len() - 1], |entry| { - detached(entry.block as usize) - }); - } - drop(table); - // A jump cache entry sits in its PC's slot alone. - for &(_, pc) in &gone { - let entry = &mut self.jump[(pc / INSTRUCTION) as usize % JUMP_CACHE]; - if entry.as_ref().is_some_and(|entry| detached(entry.block)) { - *entry = None; - } - } - unmark(&mut cache.marked, marked, slots); - } - - pub(super) fn discard_code(&mut self, cause: Discard) { - self.flush_exits(); - // A machine alone clears its records below: their exits are kept - // by word. A board's records stay, and their blocks' retirement - // adds them: kept here too they would count twice. - let shared = self.code_hub.is_some() || Arc::get_mut(&mut self.code).is_none(); - if !shared { - self.exit_words = self.exit_words(); - } - let code = Arc::clone(&self.code); - let counted = self.census.is_some() - || code - .census - .lock() - .unwrap_or_else(|error| error.into_inner()) - .is_some(); - if counted { - // In bounded steps of slots. - let now = self.host.counter(); - let slots = code.blocks.len(); - for step in (0..slots).step_by(EVICT_STEP) { - for slot in step..slots.min(step + EVICT_STEP) { - if code - .blocks - .try_record(slot) - .is_some_and(|record| record.live()) - { - let bytes = code - .blocks - .recovery() - .get(&slot) - .map_or(0, |owner| owner.code_bytes()); - self.census_evicted(slot, bytes, now); - } - } - } - } - drop(code); - self.host.discard_code(); - self.lookup_dispatchers = Default::default(); - self.direct_exit = None; - // A worker built on the hub's code holds it before it joins. - if self.code_hub.is_some() || Arc::get_mut(&mut self.code).is_none() { - // Other PEs run the board's code: it becomes unreachable now - // and goes as the ring reaches it. - self.forget_shared_code(); - self.pages.clear(); - self.code.known_keys.forget_all(); - self.scalable_leaves.clear(); - self.code_generation += 1; - self.statistics.code_discards[cause as usize] += 1; - return; - } - // The block table goes with the code; the ITLB, which names no - // block, keeps its translations. A running guest normally fills the - // chunks again after a discard: their storage goes back when - // freeing memory is the reason to discard. - let free = matches!(cause, Discard::Memory | Discard::Finished); - Arc::get_mut(&mut self.code) - .expect("a machine that keeps its code alone discards it") - .clear(free); - if free { - self.spare_pages = Vec::new(); - } - self.pages.clear(); - self.code.known_keys.forget_all(); - self.scalable_leaves.clear(); - self.code_generation += 1; - self.statistics.code_discards[cause as usize] += 1; - } - - /// Discard every installed block, freeing its metadata, as a run that - /// has ended does before work that needs the memory. - pub fn discard_blocks(&mut self) { - self.discard_code(Discard::Finished); - } -} +//! Invalidation and reclamation of compiled blocks when translation or code +//! changes. + +use super::*; + +/// Blocks [`Machine::stale_code`] copies under the board's lock at a time. +const STALE_STEP: usize = 128; + +/// Slots one step of an eviction or a discard's census takes under the +/// board's lock: tens of microseconds. +const EVICT_STEP: usize = 32; + +/// Units of work one step of a retirement takes under the board's lock +/// ([`Machine::retire_step`]): a block or an index entry visited, about a +/// cache miss or a few each. A launch measured 1024 at 116 us a step: each +/// of the other PEs' fetches, links and installs, one every ~50 us per PE, +/// that comes during a step waits for the rest of it, so the waits a +/// retirement causes grow with the square of its step (build of run +/// 20261111-025825: 1.2 s of `evict` holds, 4-7 s of waits per beat). At +/// 256 a sign-in measured 43 us a step against one acquisition every 37 us +/// per PE (run 20261111-100711: 2.1 M a beat over 8 PEs); an eighth of the +/// first keeps a step under that gap. +pub(super) const STEP_VISITS: u64 = 128; +/// The units a retirement step takes while another PE waits for the lock +/// ([`board::Code::wanted`]): a fetch, link or install waits for a few +/// microseconds of a step at most, not for all of it. Steps were 16.6 us +/// each in run 20261115-112116 (66 K a beat, 38% of the lock's holds), so +/// a holder found the lock held by one a tenth of the time and waited +/// about half a step: most of the 2.3 s waited a beat. +pub(super) const YIELD_VISITS: u64 = 16; + +/// Cells one step of an eviction releases under the board's lock. +const CELL_STEP: usize = 256; +/// The fetches a PE counts per ring part before it adds them to the ring's +/// shared counts ([`Machine::entered`]). +const ENTERED_BATCH: u32 = 64; + +/// What [`Machine::stale_code`] checks of a block, copied under the lock. +#[derive(Clone, Copy)] +struct StaleBlock { + pc: u64, + physical: u64, + code: usize, + source_bytes: usize, + source_hash: u64, + installer: u8, +} + +/// The word and bit of the two positions of the leaf of `size` bytes at +/// `base` in a filter of [`FETCHED_LEAVES`] bits. A base's low bits are clear, +/// so the size's exponent keeps leaves of one base apart. +fn fetched_leaf_bits(base: u64, size: u64) -> [(usize, u64); 2] { + let hash = (base | u64::from(size.trailing_zeros())).wrapping_mul(0x9e37_79b9_7f4a_7c15); + [hash >> 40, hash >> 16].map(|bits| { + let bit = bits as usize & (FETCHED_LEAVES - 1); + (bit / 64, 1 << (bit % 64)) + }) +} + +/// Whether `slot`'s bit is set in `bits`. +fn bit_set(bits: &[u64], slot: u32) -> bool { + bits.get(slot as usize / 64) + .is_some_and(|word| word & 1 << (slot % 64) != 0) +} + +/// `marked`, a bit per slot below `len`, with the bits of `slots` set, the +/// rest clear: what [`unmark`] takes back. +fn mark(marked: &mut Vec, len: usize, slots: &[u32]) -> Vec { + let mut marked = core::mem::take(marked); + let words = len.div_ceil(64); + if marked.len() < words { + marked.resize(words, 0); + } + for &slot in slots { + marked[slot as usize / 64] |= 1 << (slot % 64); + } + marked +} + +/// Clear the bits of `slots` in `marked` and keep it in `kept` for the next. +fn unmark(kept: &mut Vec, mut marked: Vec, slots: &[u32]) { + for &slot in slots { + marked[slot as usize / 64] &= !(1 << (slot % 64)); + } + *kept = marked; +} + +/// The block keys `block` may have entries under ([`Machine::block_key`]): +/// its frame and variant, with the guarded page's BT bit clear and set. +fn block_keys(block: &Block) -> [u64; 2] { + let state = (block.variant.0 + 1) << 1; + [state, state | 1].map(|state| chain::block_key(block.physical, state)) +} + +/// The frame number of the 4 KiB frame holding `physical`, as block keys +/// name it. +fn frame_number(physical: u64) -> u64 { + chain::key_frame(chain::block_key(physical, 1)) +} + +impl Machine { + /// Check the next [`STALE_CHECKS`] reachable compiled blocks against + /// the guest bytes they were compiled from, a sweep that goes on where + /// the last call stopped: a diagnostic of code changed without the IC + /// maintenance that would discard its blocks, bounded per call. + pub fn stale_code(&mut self) -> StaleCode { + let mut report = StaleCode::default(); + let mut bytes = Vec::new(); + let mut last = None; + // What each block's check needs, copied in bounded steps under the + // lock: the RAM reads and hashes run without it. + let mut checks = Vec::with_capacity(STALE_STEP); + while report.blocks < STALE_CHECKS { + checks.clear(); + { + let pages = self.code.every_page(board::LockSite::Report); + let step = STALE_STEP.min(STALE_CHECKS - report.blocks); + for (cursor, index) in pages.sweep(last.or(self.stale_cursor), step) { + let block = &self.code.blocks[index]; + checks.push(( + cursor, + StaleBlock { + pc: block.pc, + physical: block.physical, + code: block.code.0, + source_bytes: block.source_bytes(), + source_hash: block.source_hash, + installer: block.installer, + }, + )); + } + } + if checks.is_empty() { + break; + } + for &(cursor, block) in &checks { + self.check_stale(&mut report, &mut bytes, block); + last = Some(cursor); + } + } + // A sweep that reached the last block starts over next time. + self.stale_cursor = last.filter(|_| report.blocks == STALE_CHECKS); + report + } + + /// Check one block of [`Self::stale_code`] against its guest bytes. + fn check_stale(&mut self, report: &mut StaleCode, bytes: &mut Vec, block: StaleBlock) { + bytes.resize(block.source_bytes, 0); + report.blocks += 1; + if !self.host.read_ram(block.physical, bytes) { + return; + } + let raw = source_hash(bytes); + // A block's hash is of the bytes its compile admitted. + for word in bytes.as_chunks_mut::<4>().0 { + *word = self.admit(u32::from_le_bytes(*word)).to_le_bytes(); + } + let admitted = source_hash(bytes); + if admitted == block.source_hash && raw != admitted { + report.admitted += 1; + } + if admitted == block.source_hash { + return; + } + report.stale += 1; + if report.first.is_none() { + report.first = Some((block.pc, block.physical)); + let part = self.code.arena.as_ref().and_then(|arena| { + let offset = block.code.checked_sub(arena.window.exec)?; + Some((offset / arena.part_bytes) as u32) + }); + report.origin = Some(StaleOrigin { + pe: block.installer, + part, + noted: self + .parallel + .as_ref() + .map(|hub| hub.has_code(block.physical)), + }); + } + } + + /// An architectural cache epoch must never wrap back to an old permission. + pub(super) fn advance_translation_generation(&mut self) { + self.mirrors.table_switch.forget(); + self.refresh_translations(); + } + + /// [`Self::advance_translation_generation`] keeping the native TTBR0 + /// switch entries (`x86_64::table_switch`), for a TLBI that leaves + /// every lookup context and a permissions change. An entry names + /// nothing a translation holds: its lower context is the one of its + /// TTBR0 under the controls its upper context was made with (the two + /// halves' contexts are keyed by the same controls but TTBR0, and a + /// context's number is never given again), which the thunk checks, and + /// its host set, whose generation and class (the rights and the lower + /// half's TCR fields) the thunk checks too. What lookup contexts go + /// forgets them ([`Self::forget_contexts`]). + pub(super) fn refresh_translations(&mut self) { + self.mirrors.close_code_page(); + self.forget_device_reads(); + self.mirrors.transitions.contexts_moved(); + self.translation_generation = self + .translation_generation + .checked_add(1) + .expect("architectural translation generation exhausted"); + } + + /// What TTBR0 or its ASID selects may have changed. + pub(super) fn advance_table_generation(&mut self) { + self.mirrors.close_code_page(); + self.forget_device_reads(); + self.mirrors.transitions.contexts_moved(); + self.table_generation = self + .table_generation + .checked_add(1) + .expect("architectural table generation exhausted"); + } + + /// What `half`'s cached fetches and contexts last as long as: TTBR0 + /// selects the lower half's, and the upper half's once a fetch of it was + /// non-global, by its ASID ([`Self::half_inputs`]). + pub(super) fn fetch_epoch(&self, half: usize) -> FetchEpoch { + let table = half == 0 || self.private_fetches[1]; + ( + self.translation_generation, + if table { self.table_generation } else { 0 }, + ) + } + + /// The translations of the halves `halves` may have changed with no + /// control value showing it: their lookup contexts go, so no lookup + /// translates through their ITLB entries, nor does a cached fetch + /// outlive what [`Self::fetched_through`] learnt of it. The block + /// table's entries stay: they hold for a frame, whatever maps it. + pub(super) fn forget_spaces(&mut self, halves: core::ops::RangeInclusive, cause: usize) { + self.forget_contexts(halves, cause); + self.advance_translation_generation(); + } + + /// Forget the contexts of `halves` that translate `asid`: what a TLBI of + /// one process leaves of the others', which their ITLB entries stay good + /// for. + pub(super) fn forget_asid(&mut self, halves: core::ops::RangeInclusive, asid: u16) { + self.mirrors.table_switch.forget(); + for half in halves { + self.statistics.lookup_forgets[0] += 1; + self.spaces[half].retain(|space| !same_asid(space, asid)); + self.recent[half] = [None; RECENT]; + } + self.advance_table_generation(); + } + + /// A TLBI of everything of some regimes reached nothing of `regime`'s + /// ([`mmu::tlbi::Scope::reach`] answered [`mmu::tlbi::Reach::Nothing`] + /// for the context the PE translates in): the contexts of other + /// regimes go, which it may have reached, and `regime`'s stay. + fn forget_other_regimes(&mut self, regime: mmu::Regime) { + self.mirrors.table_switch.forget(); + let mut forgot = false; + for half in 0..2 { + if self.spaces[half].len() == 0 { + continue; + } + if self.spaces[half].iter().all(|space| space.regime != regime) { + self.forget_contexts(half..=half, 1); + forgot = true; + continue; + } + if self.spaces[half].retain(|space| space.regime == regime) != 0 { + self.statistics.lookup_forgets[1] += 1; + self.recent[half] = [None; RECENT]; + forgot = true; + } + } + let source = if forgot { + ItlbSource::AllForgot + } else { + ItlbSource::AllKept + }; + self.statistics.itlb_sources[source as usize] += 1; + self.advance_translation_generation(); + } + + /// [`Self::forget_spaces`] for a caller that advances the generation. + pub(super) fn forget_contexts( + &mut self, + halves: core::ops::RangeInclusive, + cause: usize, + ) { + // Native switches name contexts by number. + self.mirrors.table_switch.forget(); + let upper_stays = !halves.contains(&1); + for half in halves { + self.refill_after(half); + self.statistics.lookup_forgets[cause] += 1; + self.forget_kept_records(half); + self.spaces[half].clear(); + self.recent[half] = [None; RECENT]; + // The upper half's live contexts may hold lower-half global + // pages (`itlb_context`), which TLBIs by VA must still reach + // through what the lower half's fetches recorded. + let keep_filter = half == 0 && upper_stays && self.spaces[1].len() != 0; + if !keep_filter { + self.clear_fetched_leaves(half); + } + self.private_fetches[half] = false; + if half == 0 { + self.lower_globals = NO_GLOBALS; + } + } + } + + /// Clear `half`'s filter of the leaves its fetches translated through + /// ([`Self::fetched_through`]): a TLBI by VA then reaches none of its + /// lookup entries until a fetch, or a kept entry's verification + /// (`tlbi_keep.rs`), records one again. + pub(super) fn clear_fetched_leaves(&mut self, half: usize) { + // Bits are inserted with a fetched size and only cleared here. + if core::mem::take(&mut self.fetched_sizes[half]) != 0 { + let filter = &mut self.fetched_leaves[half]; + match &mut self.fetched_words[half] { + Some(words) => { + for word in words.drain(..) { + filter[word as usize] = 0; + } + } + words @ None => { + filter.fill(0); + *words = Some(Vec::new()); + } + } + } + } + + /// A fetch in `half` translated through a leaf of `size` bytes. The + /// upper half's contexts leave out the ASID until a fetch of it is + /// non-global ([`Self::half_inputs`]): the first such fetch forgets + /// them, as their entries may name blocks of another ASID's page. + pub(super) fn fetched_through(&mut self, half: usize, pc: u64, size: u64, global: bool) { + if half == 1 && !global && !self.private_fetches[1] { + self.forget_spaces(1..=1, 3); + } + let leaf = size.next_power_of_two(); + let filter = &mut self.fetched_leaves[half]; + if filter.is_empty() { + *filter = vec![0; FETCHED_LEAVES / 64]; + } + let words = &mut self.fetched_words[half]; + for (word, bit) in fetched_leaf_bits(pc & !(leaf - 1), leaf) { + if filter[word] == 0 { + match words { + Some(set) if set.len() < FETCHED_WORDS => set.push(word as u32), + _ => *words = None, + } + } + filter[word] |= bit; + } + self.fetched_sizes[half] |= leaf; + self.private_fetches[half] |= !global; + if half == 0 && global { + let (first, last) = self.lower_globals; + self.lower_globals = (first.min(pc), last.max(pc.saturating_add(size))); + } + } + + /// Whether a fetch of `half` translated through the leaf of `size` bytes + /// at `base`, or through one that shares its filter bits. + fn leaf_fetched(&self, half: usize, base: u64, size: u64) -> bool { + fetched_leaf_bits(base, size) + .iter() + .all(|&(word, bit)| self.fetched_leaves[half][word] & bit != 0) + } + + /// The span of `half` a TLBI of `first..=last` can reach of what it + /// fetched: the leaves around them that fetches translated through, at + /// each size such leaves had. + fn fetched_span(&self, half: usize, first: u64, last: u64) -> Option<(u64, u64)> { + const UPPER: u64 = !0 << 55; + let (low, high) = [(0, !UPPER), (UPPER, u64::MAX)][half]; + if last < low || first > high { + return None; + } + let (first, last) = (first.max(low), last.min(high)); + let mut span: Option<(u64, u64)> = None; + let mut sizes = self.fetched_sizes[half]; + while sizes != 0 { + let size = sizes.isolate_lowest_one(); + sizes &= sizes - 1; + let (start, end) = (first & !(size - 1), last | (size - 1)); + let leaves = (end - start) / size; + let fetched = leaves >= SCANNED_LEAVES + || (0..=leaves).any(|leaf| self.leaf_fetched(half, start + leaf * size, size)); + if fetched { + span = Some(span.map_or((start, end), |(lowest, highest)| { + (lowest.min(start), highest.max(end)) + })); + } + } + span + } + + /// Drop the cached fetches of the pages a TLBI reaches in the current + /// translation: all of them if it reaches more than the cache holds. + fn forget_fetches(&mut self, reach: mmu::tlbi::Reach) { + let (first, last) = match reach { + mmu::tlbi::Reach::Nothing => return, + mmu::tlbi::Reach::All => return self.refresh_translations(), + mmu::tlbi::Reach::Containing(address) => (address, address), + mmu::tlbi::Reach::Overlapping { first, last } => (first, last), + }; + for half in 0..2 { + let Some((first, last)) = self.fetched_span(half, first, last) else { + continue; + }; + if (last - first) / FETCH_PAGE >= FETCH_CACHE as u64 { + return self.refresh_translations(); + } + for page in (first..=last).step_by(FETCH_PAGE as usize) { + let slot = (page / FETCH_PAGE) as usize % FETCH_CACHE; + if self.fetch[slot].is_some_and(|entry| (first..=last).contains(&entry.page)) { + self.fetch[slot] = None; + } + } + } + } + + /// Drop the ITLB entries of the pages a TLBI by VA reaches + /// ([`Self::fetched_span`]), as Arm `TLBIMatch` selects TLB entries: + /// - without an ASID (VAAE1, VAALE1, RVAAE1, RVAALE1 and their IS/OS + /// forms, and every upper-half span): those of every context; + /// - with `asid` (VAE1, VALE1, RVAE1, RVALE1 and their IS/OS forms) in + /// the lower half: those of `asid`'s contexts, and in any context + /// those whose walk ended in a global leaf + /// ([`chain::LookupEntry::is_global_page`]), which match every ASID. + /// A non-global entry of another ASID stays. A context's ASID is the + /// one its regime's TCR.A1 selects from TTBR0 or TTBR1 + /// ([`mmu::current_asid`]), both of which its key holds, with the + /// 8 high bits ignored as for TCR.AS=0 (more entries go, never + /// fewer). + /// + /// A process's exit reaches its own pages this way and leaves the other + /// processes' private pages. The ITLB finds the entries of the span's + /// pages in every context from its index of where each granule's went + /// (`chain::LookupTable`). Contexts stay: the hot pages of one that went + /// would each cost an exit on every PE that runs them. The block table's + /// entries stay too: a page translated anew finds them again by its + /// frame. + pub(super) fn forget_lookups(&mut self, reach: mmu::tlbi::Reach, asid: Option) { + let (first, last) = match reach { + mmu::tlbi::Reach::Nothing => return, + mmu::tlbi::Reach::All => return self.forget_spaces(0..=1, 1), + mmu::tlbi::Reach::Containing(address) => (address, address), + mmu::tlbi::Reach::Overlapping { first, last } => (first, last), + }; + for half in 0..2 { + let Some((first, last)) = self.fetched_span(half, first, last) else { + continue; + }; + let scoped = asid.filter(|_| half == 0); + let every = &self.spaces; + let spaces = &every[half]; + let (ghosts, statistics) = (&mut self.itlb_ghosts, &mut self.statistics); + let dropped = &mut self.dropped_refills; + let forget = |entry: &chain::LookupEntry| { + let source = match scoped { + None => Some(ItlbSource::DropEvery), + Some(_) if entry.is_global_page() => Some(ItlbSource::DropEvery), + Some(asid) => spaces + .live(entry.key) + .is_some_and(|space| same_asid(space, asid)) + .then_some(ItlbSource::DropAsid), + }; + let Some(source) = source else { + return false; + }; + statistics.itlb_drops[1] += 1; + statistics.itlb_sources[source as usize] += 1; + if source == ItlbSource::DropEvery { + let every = match (half, scoped) { + (1, _) => ItlbSource::DropUpper, + (_, None) => ItlbSource::DropNoAsid, + _ => ItlbSource::DropGlobal, + }; + statistics.itlb_sources[every as usize] += 1; + } + super::compilation::note_itlb_ghost(ghosts, entry, ItlbMiss::Forgotten); + // A lower-half global page's entry is in an upper-half + // context (`itlb_context`). + if every.iter().any(|spaces| spaces.live(entry.key).is_some()) { + Self::keep_dropped( + dropped, + |number| every.iter().any(|spaces| spaces.live(number).is_some()), + entry.key, + entry.pc, + ); + } + true + }; + if self.itlb.forget_range_where(first..=last, forget) { + self.statistics.lookup_forgets[2] += 1; + } + } + } + + /// A translation control changed: cached fetch translations go, and + /// of the host's shadow what the new controls translate differently + /// ([`Host::set_regime`]). Lookup contexts are keyed by the controls' + /// values ([`contexts::Key`]), so a return to earlier ones finds theirs + /// again. + pub(super) fn controls_changed(&mut self) { + self.derived_changed(); + self.mirrors.table_switch.forget(); + self.permissions_changed(); + } + + /// TCR changed the layout of translation ([`Self::layout_written`]): + /// everything that translates goes, as after any control: fetch + /// translations, lookup contexts, the code page and device reads, and + /// the host's shadow follows the new controls. + pub(super) fn layout_changed(&mut self) { + self.advance_translation_generation(); + self.statistics.translation_changes += 1; + self.sync_host_regime(step_timing::SyncSource::Translation); + } + + /// Translation changed, but nothing derived from System registers: + /// an SPRR_PERM write, which XNU makes around its writes to protected + /// data and at thread switches, thousands of times a second. + pub(super) fn permissions_changed(&mut self) { + self.mirrors.close(SPRR_PERM_MIRROR); + self.refresh_translations(); + self.statistics.translation_changes += 1; + self.sync_host_regime(step_timing::SyncSource::Translation); + } + + /// Anything about translation may have changed: every lookup context + /// goes too, and the whole shadow. + pub(super) fn translations_changed(&mut self) { + self.forget_contexts(0..=1, 3); + self.host.invalidate_translations(); + self.controls_changed(); + } + + /// The host's answers to [`Host::fetch_permitted`] changed: every later + /// fetch translates and asks again, and no cached, looked-up or chained + /// transfer enters a block of another page before it has. + pub fn fetch_permissions_changed(&mut self) { + self.forget_spaces(0..=1, 3); + } + + /// A TLBI: the fetch translations `reach` names go, and the host drops + /// what it names of its shadow. Of the lookup table, which + /// holds every context's entries, it drops what `everywhere` names: the + /// entries at its VAs, or the contexts of the halves non-global entries + /// were fetched through, or every context. No control changed, so the + /// regime and what derives from System registers stay. + pub(super) fn tlb_maintained( + &mut self, + reach: mmu::tlbi::Reach, + everywhere: mmu::tlbi::Everywhere, + asid: Option, + ) { + self.mirrors.close_code_page(); + self.forget_device_reads(); + let mut whole = None; + match everywhere { + mmu::tlbi::Everywhere::Addresses(addresses) + | mmu::tlbi::Everywhere::AsidAddresses(addresses, _) => { + // Canonical memory's kept TLBs refresh on the generation. + if self.canonical_memory_serves() { + self.refresh_translations(); + } else { + self.forget_fetches(reach); + } + self.forget_lookups(addresses, asid); + } + mmu::tlbi::Everywhere::NonGlobal(_) => { + let last = usize::from(self.private_fetches[1]); + match asid { + Some(asid) => self.forget_asid(0..=last, asid), + None => self.forget_spaces(0..=last, 0), + } + } + // The forms without an address. One that reaches nothing of the + // regime the PE translates in reaches no entry of it + // (`Scope::reach`, `Scope::covers`). + mmu::tlbi::Everywhere::All if reach == mmu::tlbi::Reach::Nothing => { + self.forget_other_regimes(self.cpu.tlbi_current().regime); + } + mmu::tlbi::Everywhere::All => { + // Mail's whole invalidations count as received too + // (`itlb_drops`' mail_all tells them apart). + let source = match self.applying_mail { + true => ItlbSource::AllReceived, + false => ItlbSource::AllLocal, + }; + self.statistics.itlb_sources[source as usize] += 1; + let started = self.whole_tlbi_clock(); + let live = + !self.fill_log.is_empty() || self.spaces.iter().any(|spaces| spaces.len() != 0); + if self.tlbi_keep.on { + // `--tlbi-keep on`: kept, and verified before any use. + self.keep_spaces(); + } else { + self.forget_spaces(0..=1, 1); + } + if !self.applying_mail { + whole = Some((started, live)); + } + } + } + self.statistics.tlb_maintenance += 1; + if reach != mmu::tlbi::Reach::All { + self.statistics.scoped_maintenance += 1; + } + let forgot = match whole { + Some(_) => self.whole_tlbi_clock(), + None => 0, + }; + self.host.invalidate_reach(reach, everywhere); + // A local TLBI of everything: its PC, whether the ITLB held + // anything, and, under step timing, the time of the engine's and + // the host's parts. + if let Some((started, live)) = whole { + let done = self.whole_tlbi_clock(); + self.statistics.whole_tlbi_sites.add(self.cpu.pc, 1); + self.note_whole_tlbi_trigger(); + let times = &mut self.statistics.whole_tlbi_times; + times[0] += u64::from(live); + times[1] += forgot.wrapping_sub(started); + times[2] += done.wrapping_sub(forgot); + } + } + + /// What came before this PE's own TLBI of everything: whether TTBR0_EL1 + /// changed since its previous one and, under step timing, one in + /// [`WHOLE_TLBI_SAMPLE_EVERY`] sampled ([`WholeTlbiTrigger`]). Reads + /// registers only. + fn note_whole_tlbi_trigger(&mut self) { + let ttbr0 = self.cpu.read(SystemRegister::TTBR0_EL1); + let switched = self.whole_tlbis != 0 && ttbr0 != self.whole_tlbi_ttbr0; + let sample = (self.step_timing.is_some() + && self.whole_tlbis.is_multiple_of(WHOLE_TLBI_SAMPLE_EVERY)) + .then(|| { + [ + self.cpu.pc, + self.cpu.state.x[16], + self.cpu.state.x[30], + self.whole_tlbi_ttbr0, + ttbr0, + ] + }); + self.statistics.whole_tlbi_trigger.note(switched, sample); + self.whole_tlbi_ttbr0 = ttbr0; + self.whole_tlbis += 1; + } + + /// The counter, for the times of a TLBI of everything, while step + /// timing is on; zero otherwise. A guest flushes everything often, and + /// timing it is profiling, which normal runs do not pay for + /// (`system_access_samples_the_counter_and_interrupts_only_when_needed`). + fn whole_tlbi_clock(&mut self) -> u64 { + match self.step_timing { + Some(_) => self.host.counter(), + None => 0, + } + } + + /// A TTBR0 write, which changes the translation of the lower half + /// alone: the regime's new controls tell the host so + /// ([`Host::set_regime`]), which keeps the upper half's shadow. Lookup + /// contexts are keyed by its value, as by every control's. + pub(super) fn table_base_changed(&mut self) { + self.advance_table_generation(); + self.statistics.table_base_changes += 1; + self.sync_host_regime(step_timing::SyncSource::TableBase); + } + + /// Forget the blocks compiled from the page holding `physical`, which an + /// IC IVAU made stale, and their lookup entries, which every address + /// space mapping the frame shares: a later fetch compiles the page + /// again. Their code stays installed until its part is reclaimed. + pub(super) fn invalidate_code_page(&mut self, physical: u64) { + self.invalidate_single_code_page(physical); + if self.hle_enabled() + && ((self.cpu.regime_tcr() >> 14) & 0b11) == 0b10 + { + const GRANULE_16K: u64 = 16384; + let base = physical & !(GRANULE_16K - 1); + let this = physical & !(FETCH_PAGE - 1); + for sub in (base..base + GRANULE_16K).step_by(FETCH_PAGE as usize) { + if sub != this { + self.invalidate_single_code_page(sub); + } + } + } + } + + fn invalidate_single_code_page(&mut self, physical: u64) { + let frame = frame_number(physical); + let code = Arc::clone(&self.code); + let mut cache = code.page_at(physical, board::LockSite::Invalidate); + // The page's blocks leave the index, so no detach finds them as + // sources again: their links out are cut now. + let page: Vec = cache.index.page(physical).collect(); + for &slot in &page { + self.note_gone(&mut cache, slot, churn::Gone::Invalidated); + } + self.unlink_sources(&page); + // A paired frame pushed in one of them fails from here on. + if !page.is_empty() { + code.blocks.advance_epoch(); + } + code.cache_at(board::LockSite::Invalidate) + .targets + .forget_frames(frame..=frame, |_| true); + let forgot = cache.index.forget_page(physical & !(FETCH_PAGE - 1)); + drop(cache); + // Every PE's jump cache on a shared board still names its blocks. + if forgot || self.code_hub.is_some() { + self.forget_code_page_here(physical); + } else { + self.forget_page_caches(physical); + } + } + + /// Another PE's IC IVAU of the page holding `physical`. On a shared + /// board the poster forgot the page already, but this PE may have read + /// the old bytes before the write and published their block after that + /// forget: a compile runs outside, so the post did not wait for it. It + /// reads its mail only after it published, so forgetting the page again + /// here takes such a block away. + pub(super) fn invalidate_posted_code_page(&mut self, physical: u64) { + self.invalidate_code_page(physical); + } + + /// Forget this PE's caches of the page holding `physical`, and its jump + /// cache. + fn forget_code_page_here(&mut self, physical: u64) { + self.forget_page_caches(physical); + // The jump cache holds no generation per page. + self.code_generation += 1; + self.statistics.code_invalidations += 1; + } + + /// Forget this PE's stored page, waiting direct exit and known key of + /// the page holding `physical`. + fn forget_page_caches(&mut self, physical: u64) { + self.forget_stored_page(physical & !(FETCH_PAGE - 1)); + // A forgotten block's exit waits for no block of its page. + if self.direct_exit.is_some_and(|(block, ..)| { + (self.code.blocks[block].physical ^ physical) & !(FETCH_PAGE - 1) == 0 + }) { + self.direct_exit = None; + } + self.forget_known_key(physical & !(FETCH_PAGE - 1)); + } + + /// Make room in the code arena: reclaim its oldest part, or discard + /// every block on a host whose arena is one part. + pub(super) fn reclaim_code(&mut self) { + // A ring reclaims its parts as installs fill it. + if self.code.arena.is_some() { + return; + } + self.lookup_dispatchers = Default::default(); + match self.host.reclaim_code() { + Some(range) => self.evict_code(range), + None => self.discard_code(Discard::Arena), + } + } + + /// Make room in the host's own arena for a leaf. With the board's + /// arena holding the blocks, the host's holds only leaves: its oldest + /// part goes with the leaves in it. + pub(super) fn reclaim_leaves(&mut self) { + if self.code.arena.is_none() { + return self.reclaim_code(); + } + match self.host.reclaim_code() { + Some(range) => self + .scalable_leaves + .retain(|_, leaf| !range.contains(&leaf.code.0)), + None => { + self.host.discard_code(); + self.scalable_leaves.clear(); + } + } + } + + /// Release local code owners under pressure before allocating compilation + /// input and recovery metadata: the oldest arena part's blocks, or every + /// block on a host whose arena is one part. + /// + /// Memory another machine or the shared store holds stays low however + /// much this one releases, so within one stretch of pressure a machine + /// reclaims again only once it holds as many blocks as it did at its + /// last reclaim: its growth stays bounded, and it does not release code + /// before every block it installs. A machine holding fewer than + /// [`MEMORY_RELEASE_BLOCKS`] keeps them: what they free would not + /// relieve the heap. + pub(super) fn reclaim_for_memory(&mut self) { + // A ring's blocks are bounded by its bytes. + if self.code.arena.is_some() || !self.host.memory_low() { + self.reclaimed_at = None; + return; + } + let live = self.code.blocks.live(); + if live < self.memory_release_blocks.max(1) + || self.reclaimed_at.is_some_and(|held| live < held) + { + return; + } + self.reclaimed_at = Some(live); + self.statistics.code_releases += 1; + match self.host.release_oldest_code() { + Some(range) => self.evict_code(range), + None => self.discard_code(Discard::Memory), + } + } + + /// The grace slots this machine releases go to limbo under, and the PE + /// it is there: a machine that keeps its code alone has a grace of no + /// PE, so its slots are free again at once. + pub(super) fn grace(&self) -> (&board::Grace, Option) { + match &self.code_hub { + Some(hub) => (&hub.board.grace, Some(self.current)), + None => (&self.alone, None), + } + } + + /// Install native `bytes`: in the board's arena when it has one, else + /// in the host's. `retire` lets a full ring take away its oldest part's + /// code to make room, for a caller outside the board's lock: a block's + /// install ([`Self::place`]), which keeps its places until it publishes + /// ([`Self::release_places`]), so that their parts are not opened again + /// meanwhile. An install it makes for the block (a thunk) holds the + /// block's place, so it never waits for a grace or a part another + /// install holds: it finds the arena full instead. Without `retire` the + /// caller holds the board's lock from the take to its last write, and + /// the lock keeps the part, as no retirement ends without it. + pub(super) fn install_native( + &mut self, + bytes: &[u8], + retire: bool, + ) -> Result { + let stream = core::mem::replace(&mut self.install_stream, board::YOUNG); + let code = Arc::clone(&self.code); + let Some(arena) = &code.arena else { + return self.host.install(bytes); + }; + if bytes.len() > arena.part_bytes { + return Err(InstallError::Full); + } + #[cfg(debug_assertions)] + self.assert_portable(bytes); + // A part being retired takes a bounded step or a few at each install: + // not for a link's thunk, whose caller holds the code lock. + if retire { + self.retire_steps(self.retire_budget()); + } + let holding = !self.held_places.is_empty(); + loop { + let full = match arena.ring.take(stream, bytes.len(), 16) { + Ok(place) => { + let address = arena.address(place); + arena.write(address, bytes); + self.install_causes.window_bytes += bytes.len().next_multiple_of(16) as u64; + self.install_causes.window_pieces += 1; + self.host.serialize_code(); + if retire { + self.held_places.push(place); + } else { + arena.ring.release(place); + } + return Ok(NativeCode(address)); + } + Err(full) => full, + }; + if !retire { + return Err(InstallError::Full); + } + let (grace, skip) = self.grace(); + match arena.ring.advance(stream, full, grace, skip) { + board::Advance::Moved => {} + // A PE that waits on another's install while holding a + // place could be the one that install waits on. + board::Advance::Busy | board::Advance::Wait(_) if holding => { + return Err(InstallError::Full); + } + // The next part is still being taken away or written: help. + board::Advance::Busy => { + self.retire_steps(self.retire_budget()); + self.host.relax(); + } + board::Advance::Retire(part, _) => { + self.retire_part(part, churn::Gone::Ring); + } + board::Advance::Wait(snapshot) => self.wait_grace(&snapshot), + } + } + } + + /// Host counter ticks of retirement steps one install takes: half a + /// millisecond, so no PE stalls the guest count for a whole part. + fn retire_budget(&self) -> u64 { + (self.profile.counter_frequency / 2000).max(1) + } + + /// Code in the board's arena runs on every PE: it names none of this + /// PE's own data by address, only through its anchors, whose values + /// differ by PE ([`Self::anchors`]). + #[cfg(debug_assertions)] + fn assert_portable(&self, bytes: &[u8]) { + let anchors = self.anchors(); + let own = [ + anchors[Anchor::Control], + anchors[Anchor::Mirrors], + anchors[Anchor::Cells], + anchors[Anchor::Pointer], + anchors[Anchor::Memo], + anchors[Anchor::Count], + anchors[Anchor::StackZero], + anchors[Anchor::Amx], + &self.cpu.state as *const _ as u64, + ]; + for window in bytes.windows(8) { + let value = u64::from_le_bytes(window.try_into().expect("eight bytes")); + assert!( + value == 0 || !own.contains(&value), + "board code names PE {}'s own address {value:#x}", + self.current + ); + } + } + + /// Overwrite installed code at `code` with `bytes`. + pub(super) fn patch_native(&mut self, code: NativeCode, bytes: &[u8]) { + match &self.code.arena { + Some(arena) => { + arena.write(code.0, bytes); + self.host.serialize_code(); + } + None => self.host.patch(code, bytes), + } + } + + /// Replace the instruction at patch point `code`, which a core may be + /// running, in one store (`Host::patch_instruction`). + pub(super) fn patch_point(&mut self, code: NativeCode, instruction: [u8; chain::PATCH_BYTES]) { + match &self.code.arena { + Some(arena) => { + assert!(chain::patchable(code.0 as u64), "a patch point"); + arena.patch_point(code.0 as u64, instruction); + self.host.serialize_code(); + } + None => self.host.patch_instruction(code, instruction), + } + } + + /// Unlink the exits whose patch points and instructions are `unlinks`, + /// each in one store ([`Self::patch_point`]). In the board's arena the + /// writer serializes once after the last: no other core's fetch depends + /// on it, and this core runs none of them before it returns. + pub(super) fn unlink_points(&mut self, unlinks: Vec<(u64, [u8; chain::PATCH_BYTES])>) { + self.statistics.unlinks += unlinks.len() as u64; + let Some(arena) = &self.code.arena else { + for (point, instruction) in unlinks { + self.host + .patch_instruction(NativeCode(point as usize), instruction); + } + return; + }; + if unlinks.is_empty() { + return; + } + for (point, instruction) in unlinks { + assert!(chain::patchable(point), "a patch point"); + arena.patch_point(point, instruction); + } + self.host.serialize_code(); + } + + /// The generation of the arena part holding executable `address`, for + /// code that part's code jumps to: a thunk or a tail goes with the + /// block it serves ([`board::Ring::refer`]). + pub(super) fn stream_at(&self, address: u64) -> usize { + let arena = self.code.arena.as_ref(); + arena + .and_then(|arena| Some(arena.ring.kind(arena.part_of(address as usize)?))) + .unwrap_or(board::YOUNG) + } + + /// Code at `from` is about to jump to `to`, which the caller just + /// installed and still holds: `to`'s part stays while `from`'s does. + /// False when `to`'s part was chosen to go meanwhile: the caller makes + /// no jump, and its exit stays an exit to the engine. Under the board's + /// lock, or before `from`'s block is published. + #[must_use] + pub(super) fn note_reference(&self, from: u64, to: u64) -> bool { + if let Some(arena) = &self.code.arena + && let (Some(from), Some(to)) = + (arena.part_of(from as usize), arena.part_of(to as usize)) + && !arena.ring.refer(from, to) + { + board::Events::count(&self.code.events.refused); + return false; + } + true + } + + /// The places this PE's install took ([`Self::install_native`]) are + /// published or given up: their parts may be opened again. + pub(super) fn release_places(&mut self) { + if let Some(arena) = &self.code.arena { + for place in self.held_places.drain(..) { + arena.ring.release(place); + } + } + } + + /// A fetch found block `slot`: its part counts an entry, for the choice + /// of the tenured part to go ([`board::Ring::entered`]). The PE keeps + /// its counts and adds them to the ring's every [`ENTERED_BATCH`] + /// fetches, before each install (where the ring chooses) and when it + /// leaves its run loop: the hottest part's count is one line every PE's + /// fetches would write. The choice needs only the parts' order by + /// heat, which a batch of at most that many fetches per PE leaves. + pub(super) fn entered(&mut self, slot: usize) { + if self.step_timing.is_some() { + self.code.blocks.record(slot).fetched(); + } + let part = self.code.blocks[slot].part; + if part == board::NO_PART { + return; + } + let part = usize::from(part); + if self.entered_pending.len() <= part { + self.entered_pending.resize(part + 1, 0); + } + self.entered_pending[part] += 1; + self.entered_total += 1; + if self.entered_total >= ENTERED_BATCH { + self.flush_entered(); + } + } + + /// Add this PE's kept part entries to the ring's counts. + pub(super) fn flush_entered(&mut self) { + if self.entered_total == 0 { + return; + } + self.entered_total = 0; + let Some(arena) = &self.code.arena else { + return; + }; + for (part, count) in self.entered_pending.iter_mut().enumerate() { + if *count != 0 { + arena.ring.entered_by(part, core::mem::take(count)); + } + } + } + + /// The generation a block of `pc`, `physical` and `variant` goes to: + /// tenured when the ring took it away within a few turns + /// ([`churn::Churn::promotes`]). + pub(super) fn stream_for(&self, pc: u64, physical: u64, variant: VariantId) -> usize { + let Some(arena) = &self.code.arena else { + return board::YOUNG; + }; + let identity = churn::identity(pc, physical, variant.0); + let ring = &arena.ring; + if ring.young_parts != 0 + && self + .code + .ghosts + .promotes(identity, ring.generation(), ring.parts) + { + board::Events::count(&self.code.events.promoted); + board::TENURED + } else { + board::YOUNG + } + } + + /// The ring's current generation and parts, or zeros without a ring. + fn ring_position(&self) -> (u32, u32) { + self.code + .arena + .as_ref() + .map_or((0, 0), |arena| (arena.ring.generation(), arena.ring.parts)) + } + + /// Note that block `slot` leaves the index for `cause` + /// ([`churn::Churn::gone`]). Under the board's lock, `cache`. + pub(super) fn note_gone(&self, cache: &mut board::Shard, slot: usize, cause: churn::Gone) { + let block = &self.code.blocks[slot]; + let identity = churn::identity(block.pc, block.physical, block.variant.0); + let (generation, _) = self.ring_position(); + self.code.ghosts.gone( + &mut cache.churn, + identity, + block.source_hash, + generation, + cause, + ); + // A hole in a part that stays: its part may go early. + if cause == churn::Gone::Invalidated + && let Some(arena) = &self.code.arena + && let Some(part) = arena.part_of(block.code.0) + { + arena.ring.dropped(part); + } + } + + /// Note the install of block `slot`, before it enters the index + /// ([`churn::Churn::installed`]). Under the board's lock, `cache`. + pub(super) fn note_churn(&self, cache: &mut board::Shard, slot: usize) { + let blocks = &self.code.blocks; + let block = &blocks[slot]; + let shared = cache + .index + .sharing(blocks, block.pc, block.physical, block.variant); + // Its page runs at two addresses: its compiles keep their forms + // ([`super::rebase`]). + if shared == Some(true) { + self.code.rebases.note_shared(block.physical); + } + let identity = churn::identity(block.pc, block.physical, block.variant.0); + let (generation, parts) = self.ring_position(); + self.code.ghosts.installed( + &mut cache.churn, + identity, + block.source_hash, + generation, + shared, + parts, + ); + if let Some(arena) = &self.code.arena + && let Some(part) = arena.part_of(block.code.0) + { + arena.ring.installed(part); + } + } + + /// With every block slot given, move the board's ring on before its + /// parts are full, taking the oldest parts' blocks away and waiting for + /// their grace, until a slot is free. The caller installs its code again + /// after: its part may be one that went. A slot, if that freed one. + pub(super) fn retire_for_slot(&mut self) -> Option { + let code = Arc::clone(&self.code); + let arena = code.arena.as_ref()?; + for _ in 0..2 * arena.ring.parts { + if let Some(slot) = self.take_slot() { + return Some(slot); + } + let (grace, skip) = self.grace(); + let young = arena.ring.head(board::YOUNG); + match arena.ring.advance(board::YOUNG, young, grace, skip) { + board::Advance::Moved => {} + board::Advance::Busy => { + self.retire_steps(u64::MAX); + self.host.relax(); + } + board::Advance::Retire(part, _) => { + self.retire_part(part, churn::Gone::Slot); + // Short of slots: all of it now. + self.retire_steps(u64::MAX); + board::Events::count(&code.events.forced); + let snapshot = self.grace().0.snapshot(); + self.wait_grace(&snapshot); + } + board::Advance::Wait(snapshot) => self.wait_grace(&snapshot), + } + } + self.take_slot() + } + + /// Take away the code of the ring's `part`, which this + /// PE moved the ring past ([`board::Advance::Retire`]): its blocks go + /// as in a reclaim, and its probes, in steps the board's installs take + /// ([`Self::retire_steps`]); the part is reused once the last step is + /// done and every PE passed the grace taken after. + fn retire_part(&mut self, part: u32, cause: churn::Gone) { + let code = Arc::clone(&self.code); + let range = code + .arena + .as_ref() + .expect("a ring retires its parts") + .range(part); + let mut job = self.retirement(range, Some(part)); + job.cause = cause; + let mut held = code + .retiring + .lock() + .unwrap_or_else(|error| error.into_inner()); + // The ring moves on only once the last retirement ended, so none is + // left; one would be finished here first. + if let Some(mut left) = held.take() { + while !self.retire_step(&mut left) {} + self.finish_retirement(left); + } + *held = Some(job); + code.retire_pending.store(true, Ordering::Release); + drop(held); + self.retire_steps(self.retire_budget()); + } + + /// Take steps of the board's retirement under way, if no other PE is, + /// until it ends or `budget` host counter ticks passed. + pub(super) fn retire_steps(&mut self, budget: u64) { + if !self.code.retire_pending.load(Ordering::Acquire) { + return; + } + let code = Arc::clone(&self.code); + let Ok(mut held) = code.retiring.try_lock() else { + return; + }; + let started = self.host.counter(); + loop { + let Some(job) = held.as_mut() else { + return; + }; + if self.retire_step(job) { + break; + } + if self.host.counter().wrapping_sub(started) >= budget { + self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); + return; + } + } + let job = held.take().expect("a retirement that ended"); + code.retire_pending.store(false, Ordering::Release); + drop(held); + self.finish_retirement(job); + self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); + } + + /// A retirement of the blocks whose code lies in `range`. + fn retirement( + &mut self, + range: core::ops::Range, + part: Option, + ) -> board::Retirement { + let code = Arc::clone(&self.code); + let listed = code + .code_slots + .lock() + .unwrap_or_else(|error| error.into_inner()) + .take(&range); + // Without a list, every slot's record, read without the lock: the + // range takes no new block. + let evicted = listed.unwrap_or_else(|| { + code.blocks + .iter() + .filter(|&(slot, block)| { + code.blocks.record(slot).live() && range.contains(&block.code.0) + }) + .map(|(slot, _)| slot as u32) + .collect() + }); + let mut slots: Vec<(u64, u32)> = evicted + .iter() + .map(|&slot| { + ( + code.blocks[slot as usize].physical & !(FETCH_PAGE - 1), + slot, + ) + }) + .collect(); + slots.sort_unstable(); + code.code_slots + .lock() + .unwrap_or_else(|error| error.into_inner()) + .give_back(evicted); + board::Retirement { + part, + cause: match part { + Some(_) => churn::Gone::Ring, + None => churn::Gone::Other, + }, + cells: Some(range.start as u64), + range, + slots, + next: 0, + page: None, + pcs: Vec::new(), + ticks: 0, + steps: 0, + visits: 0, + step_visits: 0, + } + } + + /// One step of `job`, one hold of the code lock, of about + /// [`STEP_VISITS`] units of work: the phases of its pages in turn + /// ([`board::PageRetirement`]), and then its range's cells. Between + /// steps no lookup, link or index read reaches a block that left the + /// index, a block retires only once no link into it is left, and the + /// others are still whole. Whether the job is done. + pub(super) fn retire_step(&mut self, job: &mut board::Retirement) -> bool { + let started = board::timestamp(); + let code = Arc::clone(&self.code); + let mut visits = 0; + // The page under way, or the next: a step holds its index shard and + // goes on to later pages of the same shard only. + let frame = match &job.page { + Some(page) => Some(job.slots[page.start].0), + None => job.slots.get(job.next).map(|&(frame, _)| frame), + }; + if let Some(frame) = frame { + let shard = super::block_index::shard_of(frame); + let lock = &code.shards[shard]; + let mut cache = lock.at(board::LockSite::Evict); + loop { + let budget = match lock.wanted() { + true => YIELD_VISITS.min(code.step_visits), + false => code.step_visits, + }; + if visits >= budget { + break; + } + let left = budget - visits; + if job.page.is_none() { + if job.next >= job.slots.len() + || super::block_index::shard_of(job.slots[job.next].0) != shard + { + break; + } + let first = job.slots[job.next].0; + let end = job.next + + job.slots[job.next..].partition_point(|&(page, _)| page == first); + job.pcs.clear(); + job.page = Some(board::PageRetirement { + start: job.next, + end, + phase: board::PagePhase::Unindex(job.next), + }); + } + let page = job.page.as_mut().expect("a page under way"); + let frame = job.slots[page.start].0; + match page.phase { + board::PagePhase::Unindex(from) => { + let to = page.end.min(from + EVICT_STEP.min(left as usize)); + visits += self.unindex( + &mut cache, + frame, + &job.slots[from..to], + &mut job.pcs, + job.cause, + ); + page.phase = if to == page.end { + job.pcs.sort_unstable(); + job.pcs.dedup(); + board::PagePhase::Cut(0) + } else { + board::PagePhase::Unindex(to) + }; + } + board::PagePhase::Cut(from) => { + let (next, cut) = + self.cut_links_into(&mut cache, frame, &job.pcs, from, left as usize); + visits += cut; + page.phase = match next { + Some(next) => board::PagePhase::Cut(next), + None => board::PagePhase::Retire(page.start), + }; + } + board::PagePhase::Retire(from) => { + let to = page.end.min(from + EVICT_STEP.min(left as usize)); + self.retire_blocks(&job.slots[from..to]); + visits += (to - from) as u64; + if to == page.end { + job.next = page.end; + job.page = None; + } else { + page.phase = board::PagePhase::Retire(to); + } + } + } + } + } else if let Some(from) = job.cells { + // The exits in the range go, and with them their cells: no + // block in it is live now, so none links through a cell again. + let most = match code.cache.wanted() { + true => CELL_STEP.min(YIELD_VISITS as usize), + false => CELL_STEP, + } + .min(code.step_visits as usize); + job.cells = code + .cache_at(board::LockSite::Evict) + .targets + .release_some_cells(from..=job.range.end as u64 - 1, most); + visits = most as u64; + } + job.visits += visits; + job.step_visits = job.step_visits.max(visits); + job.ticks += board::timestamp().wrapping_sub(started); + job.steps += 1; + job.next >= job.slots.len() && job.page.is_none() && job.cells.is_none() + } + + /// The blocks `step` of the page at `frame` leave the index, the block + /// table and their links out, and this PE's jump cache and waiting + /// exit; their PCs go to `pcs`. They stay live: links into them are + /// cut next ([`Self::cut_links_into`]). Under the lock of the page's + /// index shard, `cache`, and the block table's for their entries. The + /// work it took, in [`STEP_VISITS`] units: a block each, a sixteenth of + /// the page's index list, and the cells looked at. + fn unindex( + &mut self, + cache: &mut board::Shard, + frame: u64, + step: &[(u64, u32)], + pcs: &mut Vec, + cause: churn::Gone, + ) -> u64 { + let code = Arc::clone(&self.code); + let blocks = &code.blocks; + let slots: Vec = step.iter().map(|&(_, slot)| slot).collect(); + // Only blocks still in the index leave a ghost: one an IC IVAU + // forgot has its own, and a lost install's key is the winner's. + for &slot in &slots { + let block = &blocks[slot as usize]; + if cache + .index + .get(blocks, block.pc, block.physical, block.variant) + == Some(slot as usize) + { + self.note_gone(cache, slot as usize, cause); + } + } + let (_, listed) = cache.index.page_part(frame, 0, 0); + let marked = mark(&mut cache.marked, blocks.len(), &slots); + cache + .index + .forget_marked(frame, |slot| bit_set(&marked, slot)); + unmark(&mut cache.marked, marked, &slots); + let mut visits = (slots.len() + listed / 16) as u64; + let mut unlinks = Vec::new(); + let mut table = code.cache_at(board::LockSite::Evict); + for &slot in &slots { + let block = &blocks[slot as usize]; + for key in block_keys(block) { + visits += table.targets.forget_block(block.pc, key, slot) as u64; + } + } + drop(table); + for &slot in &slots { + let block = &blocks[slot as usize]; + pcs.push(block.pc); + // No detach visits it once it left the index: its links out + // go now, and it links nothing again. + let record = blocks.record(slot as usize); + for (position, exit) in block.successors.iter().enumerate() { + if record.chained(position) { + record.set_linked(position, false, false); + unlinks.push( + chain::unlinked(exit.site, exit.slot.into()) + .expect("a linked exit's patch point"), + ); + } + } + let entry = &mut self.jump[(block.pc / INSTRUCTION) as usize % JUMP_CACHE]; + if entry.is_some_and(|entry| entry.block == slot as usize) { + *entry = None; + } + if self + .direct_exit + .is_some_and(|(waiting, ..)| waiting == slot as usize) + { + self.direct_exit = None; + } + } + self.unlink_points(unlinks); + visits + } + + /// Cut the links of the indexed blocks of the page at `frame`, from + /// position `from` of its list and at most `most` of them, into the + /// sorted `pcs`: those of blocks that left the index. A link names the + /// block a PC and variant have, so a link to any of the PCs goes (one + /// to a block compiled again there links again). Blocks indexed after + /// they left link to none of them. Under the lock of the page's index + /// shard, `cache`. Where the cut goes on, if blocks are left, and the + /// blocks visited. + fn cut_links_into( + &mut self, + cache: &mut board::Shard, + frame: u64, + pcs: &[u64], + from: usize, + most: usize, + ) -> (Option, u64) { + let code = Arc::clone(&self.code); + let blocks = &code.blocks; + let (sources, listed) = cache.index.page_part(frame, from, most); + let mut visited = 0; + let mut unlinks = Vec::new(); + for source in sources { + visited += 1; + let record = blocks.record(source); + for (position, exit) in blocks[source].successors.iter().enumerate() { + if record.chained(position) && pcs.binary_search(&exit.target.0).is_ok() { + record.set_linked(position, false, false); + // Linked, so its point is patchable and in reach. + unlinks.push( + chain::unlinked(exit.site, exit.slot.into()) + .expect("a linked exit's patch point"), + ); + } + } + } + // One store each, which a core running the exit may meet. + self.unlink_points(unlinks); + let next = from + visited; + ((next < listed).then_some(next), visited as u64) + } + + /// Retire the blocks of `step`, which nothing reaches but a core + /// already in one: their slots go once the retirement ends and its + /// grace passed. Under the lock of their page's index shard. + fn retire_blocks(&mut self, step: &[(u64, u32)]) { + let code = Arc::clone(&self.code); + let shared = self.code_hub.is_some(); + let now = self.host.counter(); + // Before any of them retires: a paired frame pushed in one of them + // fails from here on. + if !step.is_empty() { + code.blocks.advance_epoch(); + } + for slot in step.iter().map(|&(_, slot)| slot as usize) { + // On a shared board its rows stay until the slot takes its + // next block: another PE still inside its section may be + // running the block and fault in it. A machine alone runs + // none of it now. + let recovery = code.blocks.recovery(); + let bytes = match shared { + true => recovery.get(&slot).map(|owner| owner.code_bytes()), + false => recovery.remove(&slot).map(|owner| owner.code_bytes()), + } + .unwrap_or(0); + self.census_evicted(slot, bytes, now); + // Retired first: a PE adding its kept exits checks the block's + // incarnation and liveness, so it adds them here before the + // swap or by word after (but for one that checked just before). + code.blocks.retire(slot); + let taken = code.blocks.record(slot).taken.swap(0, Ordering::Relaxed); + if taken != 0 { + *self + .exit_words + .entry(code.blocks[slot].terminal) + .or_default() += u64::from(taken); + } + } + } + + /// The end of `job`, whose steps are done: its slots go once their + /// grace passed, and a ring part's probes and the part itself. + fn finish_retirement(&mut self, job: board::Retirement) { + let code = Arc::clone(&self.code); + let arena = job.part.and_then(|_| code.arena.as_ref()); + if let (Some(_), Some(part)) = (arena, job.part) { + code.cache_at(board::LockSite::Evict) + .dispatchers + .retain(|&(held, _)| held != part); + } + let slots: Vec = job.slots.iter().map(|&(_, slot)| slot).collect(); + let (grace, _) = self.grace(); + code.blocks.release(slots, grace.snapshot()); + if let (Some(arena), Some(part)) = (arena, job.part) { + arena.ring.retired(part, grace.snapshot()); + board::Events::count(&code.events.retired); + } + if !self.scalable_leaves.is_empty() { + self.scalable_leaves + .retain(|_, leaf| !job.range.contains(&leaf.code.0)); + } + if !job.slots.is_empty() { + self.statistics.code_evictions += 1; + } + code.events.retired(&job); + } + + /// Wait until `snapshot`'s grace passed, in rounds bounded by the host + /// counter; the board's first overrun is reported once. A PE inside + /// its section leaves it to wait ([`board::Board::wait`]); outside (a + /// compile), it holds nothing anyone waits on. + fn wait_grace(&mut self, snapshot: &board::Snapshot) { + let Some(hub) = self.code_hub.clone() else { + return; + }; + let events = &self.code.events; + board::Events::count(&events.grace_waits); + let ticks = (self.profile.counter_frequency / 10).max(1); + let pe = self.current; + let waited = if hub.board.grace.inside(pe) { + hub.board.wait(pe, snapshot, ticks, || self.host.counter()) + } else { + let start = self.host.counter(); + loop { + if hub.board.grace.passed(snapshot, None) { + break board::Waited::Passed; + } + if self.host.counter().wrapping_sub(start) >= ticks { + break board::Waited::Overdue { + first: hub.board.overdue(), + }; + } + self.host.relax(); + } + }; + if let board::Waited::Overdue { .. } = waited { + board::Events::count(&self.code.events.overdue); + } + if let board::Waited::Overdue { first: true } = waited { + let requirement = self.requirement(RequirementKind::Native( + "a code part's grace ran past its deadline: its reuse waits", + )); + self.degrade(requirement); + } + } + + /// What the board's machines share: every index entry and block table + /// entry goes, so no fetch, lookup or jump cache entry reaches a block + /// installed before; their code goes as the ring reaches its parts. + fn forget_shared_code(&mut self) { + let mut pages = self.code.every_page(board::LockSite::Discard); + pages.clear(); + self.code.cache_at(board::LockSite::Discard).targets.clear(); + drop(pages); + self.code.epoch.fetch_add(1, Ordering::AcqRel); + } + + /// What jump cache entries are valid in: this machine's code + /// generation and the board's epoch ([`Self::forget_shared_code`]). + pub(super) fn jump_generation(&self) -> u64 { + self.code_generation + .wrapping_add(self.code.epoch.load(Ordering::Acquire) << 40) + } + + /// Forget the blocks and leaves whose code lies in `range`, which the + /// host reclaimed. The other blocks of their pages stay: they chain into + /// them no more ([`Self::detach`]), and take an exit to the engine + /// there until it links them to the blocks compiled again. Only indexed + /// blocks are reached: one replaced in the index was detached then, + /// and the blocks of a page an IC IVAU forgot whole reach only each + /// other, with no lookup entry and in a code generation no jump cache + /// entry names since. Their slots are given again once the grace + /// passed ([`board::Blocks::release`]). + pub(super) fn evict_code(&mut self, range: core::ops::Range) { + // A host with nothing to release says so with an empty range, and + // while memory stays low that comes before every compile. + if range.is_empty() { + return; + } + let started = self.host.counter(); + let mut job = self.retirement(range, None); + while !self.retire_step(&mut job) {} + self.finish_retirement(job); + self.install_causes.evict_ticks += self.host.counter().wrapping_sub(started); + } + + /// Cut every chained exit of the blocks in `slots`, which leave the + /// index: under the board's lock. + fn unlink_sources(&mut self, slots: &[usize]) { + let code = Arc::clone(&self.code); + for &source in slots { + let record = code.blocks.record(source); + for (position, exit) in code.blocks[source].successors.iter().enumerate() { + if record.chained(position) { + record.set_linked(position, false, false); + // Linked, so its point is patchable and in reach. + let (point, instruction) = chain::unlinked(exit.site, exit.slot.into()) + .expect("a linked exit's patch point"); + self.patch_point(NativeCode(point as usize), instruction); + self.statistics.unlinks += 1; + } + } + } + } + + /// Make the blocks in the sorted `slots` unreachable: the indexed blocks + /// of their pages undo their links to their PCs (a link names the + /// block a PC and variant have, so any of the page's blocks of the PC + /// may be the one it reached), and their lookup and jump cache + /// entries go. Under the lock of their pages' index shard, `cache`, and + /// the block table's for their entries. + pub(super) fn detach(&mut self, cache: &mut board::Shard, slots: &[u32]) { + let blocks = &self.code.blocks; + let marked = mark(&mut cache.marked, blocks.len(), slots); + let detached = |slot: usize| bit_set(&marked, slot as u32); + let mut gone: Vec<(u64, u64)> = slots + .iter() + .map(|&slot| { + let block = &blocks[slot as usize]; + (block.physical & !(FETCH_PAGE - 1), block.pc) + }) + .collect(); + gone.sort_unstable(); + gone.dedup(); + let mut sources = core::mem::take(&mut cache.page_blocks); + let mut unlinks = Vec::new(); + for page in gone.chunk_by(|a, b| a.0 == b.0) { + sources.extend(cache.index.page(page[0].0)); + for &source in &sources { + if detached(source) { + continue; + } + let record = blocks.record(source); + for (position, exit) in blocks[source].successors.iter().enumerate() { + if record.chained(position) + && page.binary_search(&(page[0].0, exit.target.0)).is_ok() + { + record.set_linked(position, false, false); + // Linked, so its point is patchable and in reach. + let unlink = chain::unlinked(exit.site, exit.slot.into()) + .expect("a linked exit's patch point"); + unlinks.push(unlink); + } + } + } + sources.clear(); + } + cache.page_blocks = sources; + // One store each, which a core running the exit may meet. + self.unlink_points(unlinks); + // Lookup entries go by the frames their keys name, in runs. + let mut frames: Vec = gone.iter().map(|&(page, _)| frame_number(page)).collect(); + frames.dedup(); + let code = Arc::clone(&self.code); + let mut table = code.cache_at(board::LockSite::Install); + for run in frames.chunk_by(|a, b| a + 1 == *b) { + table + .targets + .forget_frames(run[0]..=run[run.len() - 1], |entry| { + detached(entry.block as usize) + }); + } + drop(table); + // A jump cache entry sits in its PC's slot alone. + for &(_, pc) in &gone { + let entry = &mut self.jump[(pc / INSTRUCTION) as usize % JUMP_CACHE]; + if entry.as_ref().is_some_and(|entry| detached(entry.block)) { + *entry = None; + } + } + unmark(&mut cache.marked, marked, slots); + } + + pub(super) fn discard_code(&mut self, cause: Discard) { + self.flush_exits(); + // A machine alone clears its records below: their exits are kept + // by word. A board's records stay, and their blocks' retirement + // adds them: kept here too they would count twice. + let shared = self.code_hub.is_some() || Arc::get_mut(&mut self.code).is_none(); + if !shared { + self.exit_words = self.exit_words(); + } + let code = Arc::clone(&self.code); + let counted = self.census.is_some() + || code + .census + .lock() + .unwrap_or_else(|error| error.into_inner()) + .is_some(); + if counted { + // In bounded steps of slots. + let now = self.host.counter(); + let slots = code.blocks.len(); + for step in (0..slots).step_by(EVICT_STEP) { + for slot in step..slots.min(step + EVICT_STEP) { + if code + .blocks + .try_record(slot) + .is_some_and(|record| record.live()) + { + let bytes = code + .blocks + .recovery() + .get(&slot) + .map_or(0, |owner| owner.code_bytes()); + self.census_evicted(slot, bytes, now); + } + } + } + } + drop(code); + self.host.discard_code(); + self.lookup_dispatchers = Default::default(); + self.direct_exit = None; + // A worker built on the hub's code holds it before it joins. + if self.code_hub.is_some() || Arc::get_mut(&mut self.code).is_none() { + // Other PEs run the board's code: it becomes unreachable now + // and goes as the ring reaches it. + self.forget_shared_code(); + self.pages.clear(); + self.code.known_keys.forget_all(); + self.scalable_leaves.clear(); + self.code_generation += 1; + self.statistics.code_discards[cause as usize] += 1; + return; + } + // The block table goes with the code; the ITLB, which names no + // block, keeps its translations. A running guest normally fills the + // chunks again after a discard: their storage goes back when + // freeing memory is the reason to discard. + let free = matches!(cause, Discard::Memory | Discard::Finished); + Arc::get_mut(&mut self.code) + .expect("a machine that keeps its code alone discards it") + .clear(free); + if free { + self.spare_pages = Vec::new(); + } + self.pages.clear(); + self.code.known_keys.forget_all(); + self.scalable_leaves.clear(); + self.code_generation += 1; + self.statistics.code_discards[cause as usize] += 1; + } + + /// Discard every installed block, freeing its metadata, as a run that + /// has ended does before work that needs the memory. + pub fn discard_blocks(&mut self) { + self.discard_code(Discard::Finished); + } +} diff --git a/crates/stela-engine/src/machine/engine/compilation.rs b/crates/stela-engine/src/machine/engine/compilation.rs index 99da470a1a..2de0dfcbc6 100644 --- a/crates/stela-engine/src/machine/engine/compilation.rs +++ b/crates/stela-engine/src/machine/engine/compilation.rs @@ -2224,9 +2224,19 @@ impl Machine { if index == THREAD_POINTER_WRITE { return register_read::thread_switch_thunk(pc, rt, cell, &THREAD_SWITCH); } - if pointer_key(register) { - let words = x86_64_pointer::TAG_WORDS; - return register_read::key_write_thunk(pc, rt, cell, pointer::TAGS, words); + if let Some(index) = pointer_key_index(register) { + let tag = Place::new( + Anchor::Pointer, + core::mem::offset_of!(pointer::PointerService, tags) + usize::from(index) * 8, + ); + return register_read::key_write_thunk( + pc, + rt, + cell, + tag, + pointer::DIRTY_KEYS, + index, + ); } register_read::stored_write_thunk(pc, rt, cell, written) } diff --git a/crates/stela-engine/src/machine/engine/hle.rs b/crates/stela-engine/src/machine/engine/hle.rs index 20f7e4ac71..3c21f8cf8a 100644 --- a/crates/stela-engine/src/machine/engine/hle.rs +++ b/crates/stela-engine/src/machine/engine/hle.rs @@ -1,400 +1,408 @@ -//! HLE's engine glue ([`crate::hle`]): a machine's configuration and -//! counts, the match of a function at its entry as the engine compiles it, -//! before any stored, shared or rebased block is looked for -//! ([`Machine::hle_compile`], called from `compile_window`), and the -//! install of a composite block in the translated block's place. -//! -//! Only an EL0 compile of an ordinary variant matches: not single-step, -//! translated, DIT-timed or streaming, with FP enabled and no alignment -//! checks. A match whose function crosses its fetch page, starts at a -//! device site, holds a host breakpoint or trace point, or holds a word the -//! chip runs as another (`Machine::admit`) is refused, and so is one whose -//! first instruction does not compile alone or whose composite cannot be -//! laid out: each is translated as before. -//! -//! A composite (`stela_compiler::x86_64::hle::compose`) is the routine's -//! fast path, then the function's first instruction compiled alone, which -//! the fast path bails to. It is installed as an ordinary block of one -//! instruction at the entry's PC and fetch page, so an IC IVAU of any byte -//! of the function retires it, and it is never stored, offered or rebased. -//! Its block holds a [`Mark`]: where its fast path ends. -//! -//! A guest access's fault inside the fast path ([`Machine::hle_fault`]) -//! puts the PC back at the entry with the guest state the fast path found, -//! which it has not changed, and the next step runs the entry's first -//! instruction alone ([`Machine::take_hle_bypass`]): the original takes the -//! fault itself, with the ESR, FAR, ELR and state it would have without -//! HLE. -use super::*; -use crate::hle::{Config, Id, PREFIX_BYTES, Refusal, Signature, Statistics}; -use core::num::NonZeroU8; -use stela_compiler::x86_64::hle::{self as composite, Request}; - -/// A machine's HLE: its configuration, what it did, the bytes of a -/// candidate function longer than the compile's window, the mark of the -/// composite it is installing, for its block ([`Self::installing`]), and -/// the entry whose original the next step runs ([`Self::bypass`]). -#[derive(Default)] -pub(super) struct State { - config: Config, - statistics: Statistics, - scratch: Vec, - /// While a composite installs: the mark its block takes, as - /// `installing_stub` marks a device stub's. - pub(super) installing: Option, - /// The entry of the composite whose fast path faulted: a step there - /// next runs its first instruction alone. - bypass: Option, -} - -/// What a composite block holds of its composite: the length of its fast -/// path, in [`composite::PREFIX_ALIGN`] units, which a fault's offset is -/// compared with. One byte, with a niche for `None`, so a [`Block`] stays -/// within its bound. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) struct Mark { - prefix_units: NonZeroU8, -} - -impl Mark { - fn new(prefix_end: u32) -> Self { - let units = prefix_end / composite::PREFIX_ALIGN; - assert!( - prefix_end.is_multiple_of(composite::PREFIX_ALIGN), - "a fast path ends at a multiple of its alignment" - ); - Self { - prefix_units: u8::try_from(units) - .ok() - .and_then(NonZeroU8::new) - .expect("a fast path of 1 to 255 units"), - } - } - - /// Where the fast path ends and the original's first instruction - /// starts, in the block's code. - pub(super) fn prefix_end(self) -> usize { - usize::from(self.prefix_units.get()) * composite::PREFIX_ALIGN as usize - } -} - -const _: () = assert!(size_of::>() == 1); -const _: () = assert!(composite::MAX_PREFIX_BYTES / composite::PREFIX_ALIGN <= u8::MAX as u32); - -/// A function [`Machine::hle_compile`] accepted: the routine that replaces -/// it and the offset of its exit `ret`. -struct Site { - routine: Id, - exit: u64, -} - -/// Whether a block of `variant`, compiled at `el`, may be replaced. -fn replaceable(variant: Variant, el: u8) -> bool { - el == 0 - && !variant.single - && !variant.translated - && !variant.timing - && variant.scalable != Some(true) - && variant.fp - && !variant.checks.alignment -} - -impl Machine { - /// Match the functions `config` enables in the blocks compiled from now - /// on. A boot sets it once, before its PEs run. - pub fn set_hle(&mut self, config: Config) { - self.hle.config = config; - } - - pub fn hle_statistics(&self) -> Statistics { - self.hle.statistics - } - - /// Whether HLE may replace any function: a routine with a signature is - /// enabled. - pub fn hle_enabled(&self) -> bool { - self.hle.config.enabled != 0 - } - - /// The signatures HLE matches against. - pub fn hle_signatures(&self) -> usize { - self.hle.config.table.len() - } - - /// The contiguous mapped span holding `pc`: the guest leaf size clamped - /// to 16 KiB (XNU's EL0 granule) when larger than [`FETCH_PAGE`], else - /// [`FETCH_PAGE`] (4 KiB). A function fitting inside one guest leaf is - /// physically contiguous with uniform permissions, so a function like - /// macOS `libsystem_platform`'s `__platform_memmove` that crosses a 4 KiB - /// fetch boundary inside a 16 KiB page can still be matched safely. - fn hle_span(&self, pc: u64) -> u64 { - self.cached_fetch(pc) - .map(|walk| walk.size.clamp(FETCH_PAGE, 16 * 1024)) - .unwrap_or(FETCH_PAGE) - } - - /// At the compile of the block at `pc` (`physical`) from the raw bytes - /// `source`, its window's first: whether an enabled signature's - /// function starts there and may be replaced, and its composite - /// installed if so. `Ok(None)` leaves the compile to translate it. - /// - /// A compile reads a first window ([`FIRST_WINDOW_BYTES`]) and, when its - /// block may run past it, the whole one: the second read looks no more, - /// so a function is matched (and refused) once per compile. - pub(super) fn hle_compile( - &mut self, - pc: u64, - physical: u64, - variant: Variant, - source: &[u8], - ) -> Result, Stop> { - if self.hle.config.enabled == 0 || source.len() > FIRST_WINDOW_BYTES { - return Ok(None); - } - let span = self.hle_span(pc); - let offset = pc & (span - 1); - let mut head = [0u8; PREFIX_BYTES]; - match source.first_chunk::() { - Some(bytes) => head = *bytes, - None if span > FETCH_PAGE - && offset + PREFIX_BYTES as u64 <= span - && self.host.read_ram(physical, &mut head) => {} - None => return Ok(None), - } - if !replaceable(variant, self.cpu.pstate.el) { - return Ok(None); - } - let table = self.hle.config.table.clone(); - for (index, signature) in crate::hle::find(&table, self.hle.config.enabled, &head) { - let length = signature.length() as u64; - if offset + length > span { - self.hle.statistics.refuse(Refusal::CrossesPage); - continue; - } - if !self.hle_matches(physical, source, signature) { - continue; - } - self.hle.statistics.matched += 1; - self.hle.statistics.matched_signatures |= 1 << index; - let refusal = if self.device_site(physical) { - Some(Refusal::DeviceSite) - } else if self - .breakpoints - .iter() - .chain(&self.traces) - .any(|stop| (pc..pc + length).contains(stop)) - { - Some(Refusal::Breakpoint) - } else if !self.hle_admitted() { - Some(Refusal::Admitted) - } else { - None - }; - if let Some(refusal) = refusal { - self.hle.statistics.refuse(refusal); - return Ok(None); - } - let site = Site { - routine: signature.id(), - exit: signature.exit(), - }; - return self.install_hle(pc, physical, variant, source, site); - } - Ok(None) - } - - /// The offset of the first word after the first of `source`, the bytes - /// at `pc` (`physical`), where an enabled signature's function starts: - /// where a compile there could install a composite. Tier 2 - /// ([`super::tier2`]) ends a superblock before it, so no branch of the - /// superblock lands inside on the original's words instead of reaching - /// the composite. Every match counts, refused or not; nothing is - /// counted. `None` with HLE off. - pub(super) fn hle_entry_after( - &mut self, - pc: u64, - physical: u64, - source: &[u8], - ) -> Option { - if self.hle.config.enabled == 0 { - return None; - } - let (table, enabled) = (self.hle.config.table.clone(), self.hle.config.enabled); - (INSTRUCTION as usize..source.len()) - .step_by(INSTRUCTION as usize) - .find(|&offset| { - let at = pc + offset as u64; - let span = self.hle_span(at); - // A prefix past its mapped leaf span is a function that crosses - // it, which no compile replaces. - if (at & (span - 1)) + PREFIX_BYTES as u64 > span { - return false; - } - let mut head = [0; PREFIX_BYTES]; - match source.get(offset..offset + PREFIX_BYTES) { - Some(bytes) => head.copy_from_slice(bytes), - None if self.host.read_ram(physical + offset as u64, &mut head) => {} - None => return false, - } - crate::hle::find(&table, enabled, &head).any(|(_, signature)| { - self.hle_matches(physical + offset as u64, &source[offset..], signature) - }) - }) - } - - /// Whether `signature`'s function starts at `physical`: from `source` - /// when it holds the whole function, else from RAM. The function's - /// bytes are left in the scratch buffer either way. - fn hle_matches(&mut self, physical: u64, source: &[u8], signature: &Signature) -> bool { - let mut function = core::mem::take(&mut self.hle.scratch); - function.clear(); - let read = match source.get(..signature.length()) { - Some(bytes) => { - function.extend_from_slice(bytes); - true - } - None => { - function.resize(signature.length(), 0); - self.host.read_ram(physical, &mut function) - } - }; - let matches = read && signature.matches(&function); - self.hle.scratch = function; - matches - } - - /// Whether the chip runs every word of the function in the scratch - /// buffer as itself: one it lacks is UDF or a NOP there - /// (`Chip::admit`), where the bytes the signature checked would trap or - /// run. - fn hle_admitted(&self) -> bool { - let (words, _) = self.hle.scratch.as_chunks::<4>(); - words.iter().all(|word| { - let word = u32::from_le_bytes(*word); - self.admit(word) == word - }) - } - - /// Install the composite of `site`'s routine at the function entry - /// `pc` (`physical`), as [`Self::install_device_stub`] installs a stub: - /// the entry's first word, admitted, compiled alone in `variant` as the - /// bail, the composite laid out in front of it, and the block of that - /// one instruction installed with its [`Mark`]. `source` is the - /// compile's raw window, which `compile_window` admits only after this. - /// `Ok(None)` when the first word does not compile alone (counted as - /// [`Refusal::Bail`]) or the composite cannot be laid out - /// ([`Refusal::Compose`]). - fn install_hle( - &mut self, - pc: u64, - physical: u64, - variant: Variant, - source: &[u8], - site: Site, - ) -> Result, Stop> { - let preparation = self.preparation(variant); - let mut first: [u8; INSTRUCTION as usize] = source[..INSTRUCTION as usize] - .try_into() - .expect("a window holds its first word"); - preparation.admit(&mut first); - let bail = match preparation.prepare(&first, pc, first.len()) { - Ok(Prepared::Block { - compiled, input: 4, .. - }) => compiled, - _ => { - self.hle.statistics.refuse(Refusal::Bail); - return Ok(None); - } - }; - let request = Request { - routine: site.routine, - pc: GuestAddress(pc), - exit: GuestAddress(pc + site.exit), - max_bytes: self.hle.config.max_bytes, - // The fast path's vectors are the widest the PE compiles for. - target: preparation.description().target, - }; - let Ok(composite) = composite::compose(request, bail) else { - self.hle.statistics.refuse(Refusal::Compose); - return Ok(None); - }; - let mark = Mark::new(composite.prefix_end); - let emission = Arc::new(super::stored::Emission::new( - first.to_vec(), - composite.block, - preparation, - )); - self.hle.installing = Some(mark); - let installed = self.install( - pc, - physical, - variant, - &first, - recovery::Template::compiled(emission), - ); - self.hle.installing = None; - let fetched = installed?; - self.hle.statistics.installed += 1; - Ok(Some(fetched)) - } - - /// `fault`, in block `index`'s code after `chained_retired` instructions - /// of the run's earlier blocks, entered with `chained_btype` by a link: - /// when the block is a composite and the fault one of a guest access in - /// its fast path, settle the run as `native_fault` does at the block's - /// first instruction with none of it retired, which is the guest state - /// the fast path found (it writes no guest register or frame field - /// before it can no longer fault), put the PC at the entry and have the - /// next step there run the original's first instruction alone. `None` - /// for any other fault: one in the bail's code is the original's own, - /// settled by its rows, and any other trap in a fast path stops the PE - /// as `native_fault` stops for a fault no row covers. - /// - /// A guest access's fault is one `native_fault` takes at a guest access - /// site: a #PF of a plain read or write (no fetch, reserved-bit or key - /// error code), or a #GP or #SS of a non-canonical address, as a fast - /// path's address that passed its range check can be on a host whose - /// placement's limit lies past its canonical range. - pub(super) fn hle_fault( - &mut self, - index: usize, - fault: &NativeFault, - chained_retired: u64, - chained_btype: Option, - ) -> Option { - let block = self.code.blocks.get(index)?; - let (entry, mark) = (block.pc, block.hle?); - let access = match fault.trap { - 14 => { - fault.error_code & !0b111 == 0 && !matches!(fault.cause, FaultCause::InvalidOpcode) - } - 12 | 13 => fault.error_code == 0 && matches!(fault.cause, FaultCause::NonCanonical), - _ => false, - }; - if fault.offset >= mark.prefix_end() - || fault.origin != NativeFaultOrigin::Exception - || !access - { - return None; - } - let mut staged = self.cpu.state.clone(); - stela_compiler::x86_64::pinned::settle(&fault.registers, &mut staged); - self.cpu.state = staged; - self.cpu.retired = self.cpu.retired.wrapping_add(chained_retired); - self.cpu.pc = entry; - if let Some(btype) = chained_btype { - self.cpu.pstate.btype = btype; - } - self.hle.bypass = Some(entry); - self.hle.statistics.bypassed += 1; - Some(Ok(())) - } - - /// Whether the step at `pc` runs the original's first instruction alone - /// after its composite's fast path faulted there. Every step that - /// fetches takes the bypass, so one left when an interrupt moved the PC - /// elsewhere does not outlive that step. - pub(super) fn take_hle_bypass(&mut self, pc: u64) -> bool { - self.hle.bypass.take() == Some(pc) - } -} +//! HLE's engine glue ([`crate::hle`]): a machine's configuration and +//! counts, the match of a function at its entry as the engine compiles it, +//! before any stored, shared or rebased block is looked for +//! ([`Machine::hle_compile`], called from `compile_window`), and the +//! install of a composite block in the translated block's place. +//! +//! Only an EL0 compile of an ordinary variant matches: not single-step, +//! translated, DIT-timed or streaming, with FP enabled and no alignment +//! checks. A match whose function crosses its fetch page, starts at a +//! device site, holds a host breakpoint or trace point, or holds a word the +//! chip runs as another (`Machine::admit`) is refused, and so is one whose +//! first instruction does not compile alone or whose composite cannot be +//! laid out: each is translated as before. +//! +//! A composite (`stela_compiler::x86_64::hle::compose`) is the routine's +//! fast path, then the function's first instruction compiled alone, which +//! the fast path bails to. It is installed as an ordinary block of one +//! instruction at the entry's PC and fetch page, so an IC IVAU of any byte +//! of the function retires it, and it is never stored, offered or rebased. +//! Its block holds a [`Mark`]: where its fast path ends. +//! +//! A guest access's fault inside the fast path ([`Machine::hle_fault`]) +//! puts the PC back at the entry with the guest state the fast path found, +//! which it has not changed, and the next step runs the entry's first +//! instruction alone ([`Machine::take_hle_bypass`]): the original takes the +//! fault itself, with the ESR, FAR, ELR and state it would have without +//! HLE. +use super::*; +use crate::hle::{Config, Id, PREFIX_BYTES, Refusal, Signature, Statistics}; +use core::num::NonZeroU8; +use stela_compiler::x86_64::hle::{self as composite, Request}; + +/// A machine's HLE: its configuration, what it did, the bytes of a +/// candidate function longer than the compile's window, the mark of the +/// composite it is installing, for its block ([`Self::installing`]), and +/// the entry whose original the next step runs ([`Self::bypass`]). +#[derive(Default)] +pub(super) struct State { + config: Config, + statistics: Statistics, + scratch: Vec, + /// While a composite installs: the mark its block takes, as + /// `installing_stub` marks a device stub's. + pub(super) installing: Option, + /// The entry of the composite whose fast path faulted: a step there + /// next runs its first instruction alone. + bypass: Option, +} + +/// What a composite block holds of its composite: the length of its fast +/// path, in [`composite::PREFIX_ALIGN`] units, which a fault's offset is +/// compared with. One byte, with a niche for `None`, so a [`Block`] stays +/// within its bound. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Mark { + prefix_units: NonZeroU8, +} + +impl Mark { + fn new(prefix_end: u32) -> Self { + let units = prefix_end / composite::PREFIX_ALIGN; + assert!( + prefix_end.is_multiple_of(composite::PREFIX_ALIGN), + "a fast path ends at a multiple of its alignment" + ); + Self { + prefix_units: u8::try_from(units) + .ok() + .and_then(NonZeroU8::new) + .expect("a fast path of 1 to 255 units"), + } + } + + /// Where the fast path ends and the original's first instruction + /// starts, in the block's code. + pub(super) fn prefix_end(self) -> usize { + usize::from(self.prefix_units.get()) * composite::PREFIX_ALIGN as usize + } +} + +const _: () = assert!(size_of::>() == 1); +const _: () = assert!(composite::MAX_PREFIX_BYTES / composite::PREFIX_ALIGN <= u8::MAX as u32); + +/// A function [`Machine::hle_compile`] accepted: the routine that replaces +/// it and the offset of its exit `ret`. +struct Site { + routine: Id, + exit: u64, +} + +/// Whether a block of `variant`, compiled at `el`, may be replaced. +fn replaceable(variant: Variant, el: u8) -> bool { + el == 0 + && !variant.single + && !variant.translated + && !variant.timing + && variant.scalable != Some(true) + && variant.fp + && !variant.checks.alignment +} + +impl Machine { + /// Match the functions `config` enables in the blocks compiled from now + /// on. A boot sets it once, before its PEs run. + pub fn set_hle(&mut self, config: Config) { + self.hle.config = config; + } + + pub fn hle_statistics(&self) -> Statistics { + self.hle.statistics + } + + /// Whether HLE may replace any function: a routine with a signature is + /// enabled. + pub fn hle_enabled(&self) -> bool { + self.hle.config.enabled != 0 + } + + /// The signatures HLE matches against. + pub fn hle_signatures(&self) -> usize { + self.hle.config.table.len() + } + + /// The contiguous mapped span holding `pc`: the guest leaf size clamped + /// to 16 KiB (XNU's EL0 granule) when larger than [`FETCH_PAGE`], else + /// [`FETCH_PAGE`] (4 KiB). A function fitting inside one guest leaf is + /// physically contiguous with uniform permissions, so a function like + /// macOS `libsystem_platform`'s `__platform_memmove` that crosses a 4 KiB + /// fetch boundary inside a 16 KiB page can still be matched safely. + fn hle_span(&self, pc: u64) -> u64 { + self.cached_fetch(pc) + .map(|walk| walk.size.clamp(FETCH_PAGE, 16 * 1024)) + .unwrap_or(FETCH_PAGE) + } + + /// At the compile of the block at `pc` (`physical`) from the raw bytes + /// `source`, its window's first: whether an enabled signature's + /// function starts there and may be replaced, and its composite + /// installed if so. `Ok(None)` leaves the compile to translate it. + /// + /// A compile reads a first window ([`FIRST_WINDOW_BYTES`]) and, when its + /// block may run past it, the whole one: the second read looks no more, + /// so a function is matched (and refused) once per compile. + pub(super) fn hle_compile( + &mut self, + pc: u64, + physical: u64, + variant: Variant, + source: &[u8], + ) -> Result, Stop> { + if self.hle.config.enabled == 0 || source.len() > FIRST_WINDOW_BYTES { + return Ok(None); + } + let span = self.hle_span(pc); + let offset = pc & (span - 1); + let mut head = [0u8; PREFIX_BYTES]; + match source.first_chunk::() { + Some(bytes) => head = *bytes, + None if span > FETCH_PAGE + && offset + PREFIX_BYTES as u64 <= span + && self.host.read_ram(physical, &mut head) => {} + None => return Ok(None), + } + if !replaceable(variant, self.cpu.pstate.el) { + return Ok(None); + } + let table = self.hle.config.table.clone(); + for (index, signature) in crate::hle::find(&table, self.hle.config.enabled, &head) { + let lead = signature.lead() as u64; + let length = signature.length() as u64; + if offset < lead || (offset - lead) + length > span { + self.hle.statistics.refuse(Refusal::CrossesPage); + continue; + } + if !self.hle_matches(physical, source, signature) { + continue; + } + self.hle.statistics.matched += 1; + self.hle.statistics.matched_signatures |= 1 << index; + let window_start = pc - lead; + let refusal = if self.device_site(physical) { + Some(Refusal::DeviceSite) + } else if self + .breakpoints + .iter() + .chain(&self.traces) + .any(|stop| (window_start..window_start + length).contains(stop)) + { + Some(Refusal::Breakpoint) + } else if !self.hle_admitted_from(signature.code_start()) { + Some(Refusal::Admitted) + } else { + None + }; + if let Some(refusal) = refusal { + self.hle.statistics.refuse(refusal); + return Ok(None); + } + let site = Site { + routine: signature.id(), + exit: signature.exit(), + }; + return self.install_hle(pc, physical, variant, source, site); + } + Ok(None) + } + + /// The offset of the first word after the first of `source`, the bytes + /// at `pc` (`physical`), where an enabled signature's function starts: + /// where a compile there could install a composite. Tier 2 + /// ([`super::tier2`]) ends a superblock before it, so no branch of the + /// superblock lands inside on the original's words instead of reaching + /// the composite. Every match counts, refused or not; nothing is + /// counted. `None` with HLE off. + pub(super) fn hle_entry_after( + &mut self, + pc: u64, + physical: u64, + source: &[u8], + ) -> Option { + if self.hle.config.enabled == 0 { + return None; + } + let (table, enabled) = (self.hle.config.table.clone(), self.hle.config.enabled); + (INSTRUCTION as usize..source.len()) + .step_by(INSTRUCTION as usize) + .find(|&offset| { + let at = pc + offset as u64; + let span = self.hle_span(at); + // A prefix past its mapped leaf span is a function that crosses + // it, which no compile replaces. + let hle_page = span; + let page_off = at & (hle_page - 1); + if page_off + PREFIX_BYTES as u64 > hle_page { + return false; + } + let mut head = [0; PREFIX_BYTES]; + match source.get(offset..offset + PREFIX_BYTES) { + Some(bytes) => head.copy_from_slice(bytes), + None if self.host.read_ram(physical + offset as u64, &mut head) => {} + None => return false, + } + crate::hle::find(&table, enabled, &head).any(|(_, signature)| { + let lead = signature.lead() as u64; + let length = signature.length() as u64; + page_off >= lead + && (page_off - lead) + length <= hle_page + && self.hle_matches(physical + offset as u64, &source[offset..], signature) + }) + }) + } + + /// Whether `signature`'s function starts at `physical`: from `source` + /// when it holds the whole function, else from RAM. The function's + /// bytes are left in the scratch buffer either way. + fn hle_matches(&mut self, physical: u64, source: &[u8], signature: &Signature) -> bool { + let lead = signature.lead() as u64; + let Some(start) = physical.checked_sub(lead) else { return false; }; + let mut function = core::mem::take(&mut self.hle.scratch); + function.clear(); + let read = if lead == 0 { + match source.get(..signature.length()) { + Some(bytes) => { function.extend_from_slice(bytes); true } + None => { + function.resize(signature.length(), 0); + self.host.read_ram(physical, &mut function) + } + } + } else { + function.resize(signature.length(), 0); + self.host.read_ram(start, &mut function) + }; + let matches = read && signature.matches(&function); + self.hle.scratch = function; + matches + } + + fn hle_admitted_from(&self, code_start: usize) -> bool { + let (words, _) = self.hle.scratch[code_start..].as_chunks::<4>(); + words.iter().all(|word| { + let word = u32::from_le_bytes(*word); + self.admit(word) == word + }) + } + + /// Install the composite of `site`'s routine at the function entry + /// `pc` (`physical`), as [`Self::install_device_stub`] installs a stub: + /// the entry's first word, admitted, compiled alone in `variant` as the + /// bail, the composite laid out in front of it, and the block of that + /// one instruction installed with its [`Mark`]. `source` is the + /// compile's raw window, which `compile_window` admits only after this. + /// `Ok(None)` when the first word does not compile alone (counted as + /// [`Refusal::Bail`]) or the composite cannot be laid out + /// ([`Refusal::Compose`]). + fn install_hle( + &mut self, + pc: u64, + physical: u64, + variant: Variant, + source: &[u8], + site: Site, + ) -> Result, Stop> { + let preparation = self.preparation(variant); + let mut first: [u8; INSTRUCTION as usize] = source[..INSTRUCTION as usize] + .try_into() + .expect("a window holds its first word"); + preparation.admit(&mut first); + let bail = match preparation.prepare(&first, pc, first.len()) { + Ok(Prepared::Block { + compiled, input: 4, .. + }) => compiled, + _ => { + self.hle.statistics.refuse(Refusal::Bail); + return Ok(None); + } + }; + let request = Request { + routine: site.routine, + pc: GuestAddress(pc), + exit: GuestAddress(pc + site.exit), + max_bytes: self.hle.config.max_bytes, + // The fast path's vectors are the widest the PE compiles for. + target: preparation.description().target, + }; + let Ok(composite) = composite::compose(request, bail) else { + self.hle.statistics.refuse(Refusal::Compose); + return Ok(None); + }; + let mark = Mark::new(composite.prefix_end); + let emission = Arc::new(super::stored::Emission::new( + first.to_vec(), + composite.block, + preparation, + )); + self.hle.installing = Some(mark); + let installed = self.install( + pc, + physical, + variant, + &first, + recovery::Template::compiled(emission), + ); + self.hle.installing = None; + let fetched = installed?; + self.hle.statistics.installed += 1; + Ok(Some(fetched)) + } + + /// `fault`, in block `index`'s code after `chained_retired` instructions + /// of the run's earlier blocks, entered with `chained_btype` by a link: + /// when the block is a composite and the fault one of a guest access in + /// its fast path, settle the run as `native_fault` does at the block's + /// first instruction with none of it retired, which is the guest state + /// the fast path found (it writes no guest register or frame field + /// before it can no longer fault), put the PC at the entry and have the + /// next step there run the original's first instruction alone. `None` + /// for any other fault: one in the bail's code is the original's own, + /// settled by its rows, and any other trap in a fast path stops the PE + /// as `native_fault` stops for a fault no row covers. + /// + /// A guest access's fault is one `native_fault` takes at a guest access + /// site: a #PF of a plain read or write (no fetch, reserved-bit or key + /// error code), or a #GP or #SS of a non-canonical address, as a fast + /// path's address that passed its range check can be on a host whose + /// placement's limit lies past its canonical range. + pub(super) fn hle_fault( + &mut self, + index: usize, + fault: &NativeFault, + chained_retired: u64, + chained_btype: Option, + ) -> Option { + let block = self.code.blocks.get(index)?; + let (entry, mark) = (block.pc, block.hle?); + let access = match fault.trap { + 14 => { + fault.error_code & !0b111 == 0 && !matches!(fault.cause, FaultCause::InvalidOpcode) + } + 12 | 13 => fault.error_code == 0 && matches!(fault.cause, FaultCause::NonCanonical), + _ => false, + }; + if fault.offset >= mark.prefix_end() + || fault.origin != NativeFaultOrigin::Exception + || !access + { + return None; + } + let mut staged = self.cpu.state.clone(); + stela_compiler::x86_64::pinned::settle(&fault.registers, &mut staged); + self.cpu.state = staged; + self.cpu.retired = self.cpu.retired.wrapping_add(chained_retired); + self.cpu.pc = entry; + if let Some(btype) = chained_btype { + self.cpu.pstate.btype = btype; + } + self.hle.bypass = Some(entry); + self.hle.statistics.bypassed += 1; + Some(Ok(())) + } + + /// Whether the step at `pc` runs the original's first instruction alone + /// after its composite's fast path faulted there. Every step that + /// fetches takes the bypass, so one left when an interrupt moved the PC + /// elsewhere does not outlive that step. + pub(super) fn take_hle_bypass(&mut self, pc: u64) -> bool { + self.hle.bypass.take() == Some(pc) + } +} diff --git a/crates/stela-engine/src/machine/engine/mirrors.rs b/crates/stela-engine/src/machine/engine/mirrors.rs index 82d77a5598..8b5ff24ae8 100644 --- a/crates/stela-engine/src/machine/engine/mirrors.rs +++ b/crates/stela-engine/src/machine/engine/mirrors.rs @@ -1,1042 +1,1042 @@ -//! System register reads that native code completes from mirror cells. - -use super::*; - -/// The System registers whose MRS native code completes from a mirror -/// cell (`x86_64::register_read`): reads without side effects whose result -/// and plainness follow from System registers and PSTATE alone, so a read -/// the engine found plain stays plain, with the same value, until derived -/// state may change ([`Machine::derived_changed`]). They are the thread -/// pointers, Apple's GL2 thread pointer and GXF status, the GL1 exception -/// registers a guarded level saves and restores ([`GUARDED_MIRRORS`]), -/// SPRR_PERM_EL0 ([`SPRR_PERM_MIRROR`]) and DAIF; and the virtual count and -/// Apple's alias of it, whose cells hold the offset they subtract from the -/// clock's count ([`COUNT_MIRRORS`]); CurrentEL and MPIDR_EL1, which each -/// state's cell answers for good; and the cycle and instruction counters a -/// kernel reads around each exception to charge threads, which a transition -/// brings up to date ([`COUNTER_MIRRORS`]). -pub(super) const MIRRORED: [Encoding; 15] = { - use registers::encodings::{ - ASPSR_GL1, CNTVCT_ALIAS_EL0, CURRENT_EL, DAIF, ELR_GL1, GXF_STATUS_EL1, MPIDR_EL1, - SPRR_PERM_EL0, SPSR_GL1, TPIDR_EL1, TPIDR_EL2, TPIDR_GL2, - }; - use stela_compiler::aarch64::system::registers::CNTVCT_EL0; - [ - TPIDR_EL1, - TPIDR_EL2, - TPIDR_GL2, - GXF_STATUS_EL1, - SPSR_GL1, - ASPSR_GL1, - ELR_GL1, - CURRENT_EL, - super::super::pmu::PMC[0], - super::super::pmu::PMC[1], - MPIDR_EL1, - SPRR_PERM_EL0, - CNTVCT_EL0, - CNTVCT_ALIAS_EL0, - DAIF, - ] -}; - -/// Rt 31 in MRS: XZR, which discards the value. -pub(super) const ZERO_REGISTER: u8 = 31; - -/// MRS's L bit (21), which makes an MSR (register) word the MRS of the -/// same register and Xt. -pub(super) const MRS_READ: u32 = 1 << 21; - -/// The registers read other than [`MIRRORED`] ones that get a cell of their -/// own the first time code naming them is installed -/// ([`Machine::stored_cell`]), which reads the register's live storage: the -/// ones a kernel reads around each exception and thread switch, FPCR and -/// FPSR, and the core counters a sampler reads in bursts -/// ([`Devices::register_storage`]). When there are more, the rest take System -/// exits. Cells go to registers in the order code naming them is first -/// installed, which for a kernel is boot's, so there are cells for every -/// register a boot reads: macOS reads over 64 before its first process, and -/// its processes' every MRS of TPIDRRO_EL0, their thread pointer, then took -/// an exit, over 100,000 a second on each PE running them. -pub(super) const STORED_CELLS: usize = 256; - -/// The user thread pointers, which every board's stored cells number first -/// (`numbering::Numbering`), before any code is installed: their cells then -/// lie at the same place in every boot, so the blocks that read them inside -/// themselves (`regime_state::inline_mirrored_reads`) translate alike, and -/// none of a boot's other registers takes their place. -pub(super) const USER_THREAD_POINTERS: [Encoding; 2] = [ - registers::encodings::TPIDRRO_EL0, - registers::encodings::TPIDR_EL0, -]; - -/// The cells of the [`MIRRORED`] registers, in its order, and the -/// [`STORED_CELLS`]: native code reads those of the PE's EL and GXF state, -/// the bank of `banks` that `state` names. A read's value and plainness -/// follow from System registers and PSTATE, of which an exception entry or -/// return, GENTER or GEXIT changes these and the masks alone: each state -/// keeps its cells, which it finds again ([`Mirrors::transition`]). Only -/// SP_EL0 follows SPSel, whose thunks read `selected`, PSTATE.SP while native -/// code runs, which can change it -/// (`x86_64::register_read::stack_select_thunk`). -/// Anything else that changes derived state closes every cell of every bank. -/// The last of them says whether writes of the masks complete natively -/// ([`MASK_WRITES`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) struct Mirrors { - pub(super) banks: [[register_read::Cell; CELLS]; MIRROR_STATES], - state: usize, - /// A bit per bank that was the PE's since cells last closed, which only - /// those can hold open. - entered: u8, - pub(super) selected: u64, - /// PSTATE.DIT, UAO and SSBS as their registers read, in - /// [`PSTATE_FIELDS`] order, while native code runs: their reads and - /// writes complete here ([`pstate_field`]). - pub(super) fields: [u64; 3], - /// What a native ISR_EL1 read checks - /// (`x86_64::register_read::interrupt_status_thunk`): `readable` the - /// count before which time alone leaves the interrupt lines of the last - /// step as they were (0 while the read is not the lines' alone), - /// `value` the interrupt epoch they reflect - /// ([`Machine::refresh_interrupt_status`]). - pub(super) interrupt_status: register_read::Cell, - /// What a native timer write that lowers the EL2 virtual timer's output - /// leaves waiting (`x86_64::register_read::TimerPlaces::quiet`): open - /// with [`GuestState::pending`] as the step set it but for a FIQ that - /// channel alone raised ([`Machine::refresh_timer_quiet`]). - pub(super) timer_quiet: register_read::Cell, - /// What a native DSB checks (`x86_64::register_read::barrier_thunk`): - /// open while this PE has no maintenance outstanding, whatever its - /// state or derived state ([`Machine::open_barrier`]). - pub(super) barrier: register_read::Cell, - /// What native SEVL and WFE complete on - /// (`x86_64::register_read::send_event_thunk`, `event_wait_thunk`): open - /// on the PE's event register as native code is entered - /// ([`Machine::enter_events`]). Neither depends on any System register - /// or the PE's state: SEVL never traps, and a WFE that finds the event - /// register set clears it and completes before any trap check (Arm - /// `Hint_WFE`); one that finds it clear exits for the engine to wait. - pub(super) events: register_read::Cell, - /// What native CLREX completes on - /// (`x86_64::register_read::clear_exclusive_thunk`): open as native - /// code is entered while the engine holds no monitor of its own and - /// traces none ([`Machine::enter_events`]), its `value` the PE's - /// reservation word (`Cpu::reservation_word`), which a held canonical - /// reservation makes nonzero. CLREX never traps, so nothing else - /// decides it. - pub(super) exclusive: register_read::Cell, - /// The records native GENTER and GEXIT complete from - /// (`x86_64::transition`), indexed by `state`, which they move. - pub(super) transitions: transition::Table, - /// The count before which time alone changes no interrupt line, as the - /// last step at EL2 found it (0 elsewhere): native GEXIT unmasks only - /// before it ([`Machine::refresh_interrupt_status`]). - pub(super) lines_until: u64, - /// The thread switches native TPIDR_EL1 writes made since native code - /// was entered, which the engine takes when it returns - /// ([`Machine::take_thread_switches`]). - pub(super) switches: register_read::SwitchLog, - /// Nonzero while the engine holds an exclusive monitor of its own - /// (`Cpu::monitor`), set as native code is entered: native ERET then - /// leaves clearing it to the engine. A canonical reservation has its - /// own word, which the exclusive service keeps (`Record::reservation`). - pub(super) monitor: u64, - /// The performance monitor's cycle counter as native code is entered - /// ([`Machine::enter_cycles`]), from which a cycle counter read computes - /// the count where only its cell's value went stale. - pub(super) cycles: register_read::CycleCounter, - /// The performance monitor's instruction counter as native code is - /// entered ([`Machine::enter_cycles`]), from which an instruction - /// counter read computes the count where only its cell's value went - /// stale. - pub(super) instructions: register_read::InstructionCounter, - /// What native WFEs counted of their spins since native code was - /// entered, which the engine takes when it returns - /// ([`Machine::take_event_spins`]). - pub(super) spin: register_read::EventSpin, - /// The event stream native WFEs sample, as the engine published it - /// ([`Machine::enter_events`]) and they moved it. - pub(super) stream: register_read::EventStream, - /// The board's fast-IPI table as this PE's native IPI writes use it, - /// all 0 until the engine installs one ([`Machine::enter_fast_ipi`]), - /// and the PEs they found halted, which the engine wakes when native - /// code returns ([`Machine::take_fast_ipi_wakes`]). - pub(super) fast_ipi: register_read::FastIpi, - /// The plain device reads native device sites complete again - /// ([`DEVICE_READ_KEY`]), a slot per site. - pub(super) device_reads: [register_read::DeviceRead; register_read::DEVICE_READS], - /// The TTBR0 values a native MSR TTBR0 switches to - /// (`x86_64::table_switch`), and the switches it made since the engine - /// last settled them ([`Machine::settle_native_switches`]). - pub(super) table_switch: table_switch::Table, -} - -/// Where native code finds the cell at `index` of the PE's state. -pub(super) const fn cell_place(index: usize) -> Place { - Place::new(Anchor::Cells, index * size_of::()) -} - -/// Where native code finds [`Mirrors::selected`]. -pub(super) const SELECTED: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, selected)); - -/// Where native code finds [`Mirrors::interrupt_status`]. -pub(super) const INTERRUPT_STATUS: Place = - Place::new(Anchor::Mirrors, offset_of!(Mirrors, interrupt_status)); - -/// Where native code finds [`Mirrors::barrier`]. -pub(super) const BARRIER: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, barrier)); - -/// Where native code finds [`Mirrors::events`]. -pub(super) const EVENTS: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, events)); - -/// Where native code finds [`Mirrors::exclusive`]. -pub(super) const CLEAR_EXCLUSIVE: Place = - Place::new(Anchor::Mirrors, offset_of!(Mirrors, exclusive)); - -/// MRS ISR_EL1 to Xt, Rt in bits 4:0. -pub(super) const READ_INTERRUPT_STATUS: u32 = 0xd538_c100; - -/// Xt of the MRS ISR_EL1 `word`, if it is one. -pub(super) fn interrupt_status_read(word: u32) -> Option { - (word & !31 == READ_INTERRUPT_STATUS).then_some((word & 31) as u8) -} - -/// The cell of MSR SPSel, open once one completed plainly in the state: -/// its `value` is the address of the stack SPSel 1 selects there. -pub(super) const STACK_SELECT: usize = MASK_WRITES + 1 + WRITTEN.len(); - -/// The cell of IC IVAU (`x86_64::register_read::code_page_thunk`), open -/// from one's completion until something could make another do more: code -/// compiled, a translation changed or the DSB that ends the kernel's run of -/// lines. Its `value` is an address in the page. -pub(super) const CODE_PAGE: usize = STACK_SELECT + 1; - -/// The cell of MSR PAN (`x86_64::register_read::pan_thunk`), open once one -/// completed plainly in the state on a host that keeps PAN in RFLAGS.AC. -pub(super) const PAN_WRITES: usize = CODE_PAGE + 1; - -/// The cell of MSR TTBR0_EL1 (`x86_64::register_read::unchanged_write_thunk`), -/// open on the storage a plain write reached: a write of the value the -/// register holds completes natively and changes nothing, any other exits. -/// A kernel rewrites the same table base at most switches into a thread of -/// the address space it already runs. -pub(super) const TABLE_BASE_KEPT: usize = PAN_WRITES + 1; - -/// TTBR0_EL1 (TTBR0_EL2 at EL2 with E2H). -pub(super) const TABLE_BASE: Encoding = Encoding::new(3, 0, 2, 0, 0); - -/// The cells of the EL2 virtual timer's compare and control -/// (`x86_64::register_read::timer_thunk`), whose `value`s are the addresses -/// of CNTHV_CVAL_EL2's and CNTHV_CTL_EL2's storage. An access of CNTV_TVAL, -/// CNTV_CVAL or CNTV_CTL that completes plainly opens both, only where -/// such an access always reaches that channel with no offset: at EL2, -/// outside a guarded level, with HCR_EL2.E2H set (Arm `AArch64_CNTV_*` -/// redirect to CNTHV_*), on a chip whose one timer bank counts the system -/// count unscaled (before the M3: `timer::agt`). No CNTHCTL_EL2 trap applies -/// at EL2. -pub(super) const TIMER_COMPARE: usize = TABLE_BASE_KEPT + 1; -pub(super) const TIMER_CONTROL: usize = TIMER_COMPARE + 1; - -/// Where native timer accesses find the channel and the engine's words. -pub(super) const TIMER: register_read::TimerPlaces = register_read::TimerPlaces { - compare: cell_place(TIMER_COMPARE), - control: cell_place(TIMER_CONTROL), - lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), - interrupt_status: INTERRUPT_STATUS, - count: Place::new(Anchor::Count, 0), - quiet: Place::new(Anchor::Mirrors, offset_of!(Mirrors, timer_quiet)), -}; - -/// MSR CNTV_TVAL_EL0, CNTV_CTL_EL0 and CNTV_CVAL_EL0, and MRS -/// CNTV_CTL_EL0, with Rt in bits 4:0. -const TIMER_VALUE_WRITE: u32 = 0xd51b_e300; -const TIMER_CONTROL_WRITE: u32 = 0xd51b_e320; -const TIMER_COMPARE_WRITE: u32 = 0xd51b_e340; -const TIMER_CONTROL_READ: u32 = 0xd53b_e320; - -/// What a native timer access of `word` does, and Rt, if `word` is one: -/// [`TimerWord`]. -pub(super) fn timer_word(word: u32) -> Option<(TimerWord, u8)> { - let access = match word & !31 { - TIMER_VALUE_WRITE => TimerWord::Value, - TIMER_CONTROL_WRITE => TimerWord::ControlWrite, - TIMER_COMPARE_WRITE => TimerWord::Compare, - TIMER_CONTROL_READ => TimerWord::ControlRead, - _ => return None, - }; - Some((access, (word & 31) as u8)) -} - -/// The timer accesses native code completes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum TimerWord { - Value, - Compare, - ControlWrite, - ControlRead, -} - -/// The cell that says the cycle counter's read is plain in the state -/// (`x86_64::register_read::cycle_counter_thunk`): it opens with the -/// counter's own cell ([`COUNTER_MIRRORS`]) and closes only with every cell, -/// as plainness follows from System registers and PSTATE alone, while a -/// native transition closes the counter's cell because its value, the -/// count, went stale. -pub(super) const CYCLES_PLAIN: usize = TIMER_CONTROL + 1; - -/// Where native code finds [`Mirrors::cycles`]. -pub(super) const CYCLES: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, cycles)); - -/// The cell that says the instruction counter's read is plain in the state -/// (`x86_64::register_read::instruction_counter_thunk`), as -/// [`CYCLES_PLAIN`] is the cycle counter's. -pub(super) const INSTRUCTIONS_PLAIN: usize = CYCLES_PLAIN + 1; - -/// Where native code finds [`Mirrors::instructions`]. -pub(super) const INSTRUCTION_COUNTER: Place = - Place::new(Anchor::Mirrors, offset_of!(Mirrors, instructions)); - -/// The cells of MSR SPRR_PERM_EL0 and MSR SPRR_PERM_EL1 -/// (`x86_64::register_read::unchanged_write_thunk`), open on the storage a -/// plain write reached in the state: a write of the value the register -/// holds completes natively and changes nothing (no access changes, as the -/// engine's own write of it finds), any other exits. A kernel writes the -/// user permissions at each return to a thread and the kernel ones around -/// each write of protected data, mostly with the value they hold. A write -/// whose model refused it closes them ([`Machine::register_refused`]). -pub(super) const PERMISSION_KEPT: [usize; 2] = [INSTRUCTIONS_PLAIN + 1, INSTRUCTIONS_PLAIN + 2]; - -/// The [`PERMISSION_KEPT`] cell of the MSR `word`, and Rt, if it writes -/// SPRR_PERM_EL0 or SPRR_PERM_EL1. -pub(super) fn permission_write_word(word: u32) -> Option<(usize, u8)> { - const MSR_SPRR_PERM_EL0: u32 = 0xd51e_f1a0; - const MSR_SPRR_PERM_EL1: u32 = 0xd51e_f1c0; - let kept = match word & !31 { - MSR_SPRR_PERM_EL0 => PERMISSION_KEPT[0], - MSR_SPRR_PERM_EL1 => PERMISSION_KEPT[1], - _ => return None, - }; - Some((kept, (word & 31) as u8)) -} - -/// The cell open where a WFE that finds the event register clear waits, -/// taking no trap, and other PEs run meanwhile on cores of their own, any of -/// which may set it: there native WFE spins for the register -/// (`x86_64::register_read::event_wait_thunk`). A WFE that waits in the -/// engine opens it ([`Machine::wait`]); the trap controls are System -/// registers, whose change closes every cell. -pub(super) const EVENT_WAITS: usize = PERMISSION_KEPT[1] + 1; - -/// Where native WFE finds the event register and what ends its spin. -pub(super) const EVENT_WAIT: register_read::EventWaitPlaces = register_read::EventWaitPlaces { - events: EVENTS, - waits: cell_place(EVENT_WAITS), - monitor: Place::new(Anchor::Mirrors, offset_of!(Mirrors, monitor)), - control: Place::new(Anchor::Control, 0), - lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), - count: Place::new(Anchor::Count, 0), - spin: Place::new(Anchor::Mirrors, offset_of!(Mirrors, spin)), - stream: Place::new(Anchor::Mirrors, offset_of!(Mirrors, stream)), -}; - -/// The cell open where MSR IPI_RR_LOCAL, IPI_RR_GLOBAL and IPI_SR -/// complete plainly through the board, taking no trap -/// (`x86_64::register_read::fast_ipi_request_thunk`, `fast_ipi_status_thunk`): -/// a board fast-IPI write the engine completed opens it -/// ([`Machine::board_register`]). The traps (EL0, HCR_EL2.TIDCP, HACR_EL2) -/// follow from PSTATE and System registers, whose change closes every cell. -pub(super) const FAST_IPI_WRITES: usize = EVENT_WAITS + 1; - -/// Where native fast-IPI writes find their words. -pub(super) const FAST_IPI: register_read::FastIpiPlaces = register_read::FastIpiPlaces { - cell: cell_place(FAST_IPI_WRITES), - ipi: Place::new(Anchor::Mirrors, offset_of!(Mirrors, fast_ipi)), - control: Place::new(Anchor::Control, 0), - interrupt_status: INTERRUPT_STATUS, -}; - -/// The cell whose `value` is the key ([`register_read::device_read_key`]) -/// native device reads of the state match -/// (`x86_64::register_read::device_read_thunk`): open on the PE's device -/// read generation once the engine kept a plain device read in the state -/// ([`Machine::keep_device_read`]). A translation that may have changed -/// moves the generation ([`Machine::forget_device_reads`]); any other change -/// of derived state closes every cell. -pub(super) const DEVICE_READ_KEY: usize = FAST_IPI_WRITES + 1; - -/// Where native device reads find theirs. -pub(super) const DEVICE_READ: register_read::DeviceReadPlaces = register_read::DeviceReadPlaces { - reads: Place::new(Anchor::Mirrors, offset_of!(Mirrors, device_reads)), - key: cell_place(DEVICE_READ_KEY), - count: Place::new(Anchor::Count, 0), -}; - -/// The cell of the first of the [`STORED_WRITES`]. -const STORED_WRITE_CELLS: usize = DEVICE_READ_KEY + 1; - -/// The IMPLEMENTATION DEFINED registers that a store completes writes of -/// that get a cell of their own the first time code naming them is installed -/// ([`Machine::stored_write_cell`]), open on the register's value once a -/// write completes plainly. A kernel writes them around each thread switch. -/// When there are more, the rest take System exits. Numbers go in install -/// order and never free, and boot installs writes of dozens of tuning, -/// control and counter registers (26A434 XNU alone writes over 40 stored -/// ones) before the first thread switch, so room for the ones a kernel -/// writes at every switch (thread keys, SPRR's field registers) must -/// outlast those. -pub(super) const STORED_WRITES: usize = 128; - -const CELLS: usize = STORED_WRITE_CELLS + STORED_WRITES; - -/// The cell of `stored_writes[index]`. -pub(super) const fn stored_write_cell(index: usize) -> usize { - STORED_WRITE_CELLS + index -} - -/// The cell of the mask writes (`x86_64::register_read::mask_thunk`), open -/// once one completed plainly in the state. -pub(super) const MASK_WRITES: usize = MIRRORED.len() + STORED_CELLS; - -/// The registers whose MSR native code completes, which a kernel writes -/// around each exception and whose writes change nothing else: a cell each, -/// after [`MASK_WRITES`], that a plain write opens on the storage it reached -/// (FPSR's lives in the frame, so names none). They stay open as reads do. -/// A PAC key's halves also close the keys to PAC thunks, which then reopen -/// together (`Machine::open_pointers`). TPIDR_EL1's also update its open -/// read cells in every state and log the thread switch for the engine's -/// diagnostics ([`THREAD_SWITCH`]). FPCR's lives in the frame too: the -/// compiled FP operations read it there at run time. -pub(super) const WRITTEN: [(Encoding, SystemRegister); 19] = [ - (Encoding::new(3, 0, 4, 0, 1), SystemRegister::ELR_EL1), - (Encoding::new(3, 0, 4, 0, 0), SystemRegister::SPSR_EL1), - (STACK_ZERO, SystemRegister::SP_EL0), - (Encoding::new(3, 3, 4, 4, 1), SystemRegister::FPSR), - (registers::encodings::FPCR, SystemRegister::FPCR), - (registers::encodings::TPIDR_EL0, SystemRegister::TPIDR_EL0), - ( - registers::encodings::TPIDRRO_EL0, - SystemRegister::TPIDRRO_EL0, - ), - (Encoding::new(3, 0, 2, 1, 0), SystemRegister::APIAKeyLo_EL1), - (Encoding::new(3, 0, 2, 1, 1), SystemRegister::APIAKeyHi_EL1), - (Encoding::new(3, 0, 2, 1, 2), SystemRegister::APIBKeyLo_EL1), - (Encoding::new(3, 0, 2, 1, 3), SystemRegister::APIBKeyHi_EL1), - (Encoding::new(3, 0, 2, 2, 0), SystemRegister::APDAKeyLo_EL1), - (Encoding::new(3, 0, 2, 2, 1), SystemRegister::APDAKeyHi_EL1), - (Encoding::new(3, 0, 2, 2, 2), SystemRegister::APDBKeyLo_EL1), - (Encoding::new(3, 0, 2, 2, 3), SystemRegister::APDBKeyHi_EL1), - (Encoding::new(3, 0, 2, 3, 0), SystemRegister::APGAKeyLo_EL1), - (Encoding::new(3, 0, 2, 3, 1), SystemRegister::APGAKeyHi_EL1), - (CONTEXT_ID, SystemRegister::CONTEXTIDR_EL1), - (registers::encodings::TPIDR_EL1, SystemRegister::TPIDR_EL1), -]; - -/// The [`WRITTEN`] index of TPIDR_EL1, the kernel's thread pointer. -pub(super) const THREAD_POINTER_WRITE: usize = WRITTEN.len() - 1; - -/// The [`MIRRORED`] index of TPIDR_EL1. -pub(super) const THREAD_POINTER_MIRROR: usize = 0; -const _: () = assert!(matches!( - MIRRORED[THREAD_POINTER_MIRROR], - registers::encodings::TPIDR_EL1 -)); - -/// Where a native TPIDR_EL1 write finds the register's read cells and the -/// switch log (`x86_64::register_read::thread_switch_thunk`). -pub(super) const THREAD_SWITCH: register_read::ThreadSwitch = register_read::ThreadSwitch { - reads: Place::new( - Anchor::Mirrors, - offset_of!(Mirrors, banks) + THREAD_POINTER_MIRROR * size_of::(), - ), - stride: size_of::<[register_read::Cell; CELLS]>(), - banks: MIRROR_STATES, - log: Place::new(Anchor::Mirrors, offset_of!(Mirrors, switches)), -}; - -/// CONTEXTIDR_EL1 (CONTEXTIDR_EL2 at EL2 with E2H), which a kernel writes -/// at each thread or address space switch: only debug and trace read it, -/// context-aware breakpoints live from its storage, and it is not part of -/// the prediction context (`PredictionContext`). -pub(super) const CONTEXT_ID: Encoding = Encoding::new(3, 0, 13, 0, 1); - -/// SP_EL0, plain only with SP_ELx selected. -pub(super) const STACK_ZERO: Encoding = Encoding::new(3, 0, 4, 1, 0); - -impl Default for Mirrors { - fn default() -> Self { - let cell = register_read::Cell::default(); - Self { - banks: [[cell; CELLS]; MIRROR_STATES], - state: 0, - entered: 1, - selected: 0, - fields: [0; 3], - interrupt_status: register_read::Cell::default(), - timer_quiet: register_read::Cell::default(), - barrier: register_read::Cell::default(), - events: register_read::Cell::default(), - exclusive: register_read::Cell::default(), - transitions: transition::Table::default(), - lines_until: 0, - switches: register_read::SwitchLog::default(), - monitor: 0, - cycles: register_read::CycleCounter::default(), - instructions: register_read::InstructionCounter::default(), - spin: register_read::EventSpin::default(), - stream: register_read::EventStream::default(), - fast_ipi: register_read::FastIpi::default(), - device_reads: [register_read::DeviceRead::default(); register_read::DEVICE_READS], - table_switch: table_switch::Table::default(), - } - } -} - -/// Where native transitions find the mirrors' words. -pub(super) const TRANSITIONS: transition::Places = transition::Places { - state: Place::new(Anchor::Mirrors, offset_of!(Mirrors, state)), - table: Place::new(Anchor::Mirrors, offset_of!(Mirrors, transitions)), - selected: SELECTED, - fields: Place::new(Anchor::Mirrors, offset_of!(Mirrors, fields)), - field_bits: [ - PSTATE_FIELDS[0].1 as u32, - PSTATE_FIELDS[1].1 as u32, - PSTATE_FIELDS[2].1 as u32, - ], - interrupt_status: INTERRUPT_STATUS, - lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), - count: Place::new(Anchor::Count, 0), - monitor: Place::new(Anchor::Mirrors, offset_of!(Mirrors, monitor)), - pointer_tags: super::pointer::TAGS, - pointer_generation: Place::new( - Anchor::Pointer, - offset_of!(super::pointer::PointerService, generation), - ), - cycles: CYCLES, - instructions: INSTRUCTION_COUNTER, - cr3: stela_compiler::x86_64::table_switch::Cr3::Register, -}; -const _: () = assert!(size_of::() == size_of::()); - -/// The places a native TTBR0 switch writes besides the host's -/// (`x86_64::table_switch::Places`): its table, the chain's lookup -/// contexts and salts, the transition records' contexts generation, and the -/// code-page and device-read cells of every state, which a TTBR0 change -/// closes ([`Machine::advance_table_generation`]). -pub(super) fn table_switch_places( - cr3: Option, - isolate: bool, -) -> table_switch::Places { - let cell = |state: usize, index: usize| { - Place::new( - Anchor::Mirrors, - offset_of!(Mirrors, banks) + (state * CELLS + index) * size_of::(), - ) - }; - table_switch::Places { - table: Place::new(Anchor::Mirrors, offset_of!(Mirrors, table_switch)), - contexts: Place::new(Anchor::Control, offset_of!(chain::ChainControl, contexts)), - salts: Place::new(Anchor::Control, offset_of!(chain::ChainControl, salts)), - contexts_generation: Place::new( - Anchor::Mirrors, - offset_of!(Mirrors, transitions) + offset_of!(transition::Table, contexts_generation), - ), - closes: (0..MIRROR_STATES) - .flat_map(|state| [cell(state, CODE_PAGE), cell(state, DEVICE_READ_KEY)]) - .collect(), - cr3, - isolate, - } -} - -/// The PSTATE fields with registers of their own that a kernel saves and -/// restores around each exception, which only the engine reads besides -/// MRS: DIT, UAO and SSBS, by encoding and register bit. A plain MRS or MSR -/// of one opens a stored cell on its [`Mirrors::fields`] word, which -/// [`Mirrors::enter`] and [`Mirrors::leave`] keep with PSTATE around native -/// code. A write takes the field's bit alone, as the register's do. -pub(super) const PSTATE_FIELDS: [(Encoding, u64); 3] = [ - (Encoding::new(3, 3, 4, 2, 5), 1 << 24), - (Encoding::new(3, 0, 4, 2, 4), 1 << 23), - (Encoding::new(3, 3, 4, 2, 6), 1 << 12), -]; - -/// The [`PSTATE_FIELDS`] index and bit of `encoding`, if it is one. -pub(super) fn pstate_field(encoding: Encoding) -> Option<(usize, u64)> { - PSTATE_FIELDS - .iter() - .position(|&(field, _)| field == encoding) - .map(|index| (index, PSTATE_FIELDS[index].1)) -} - -/// The cell of `WRITTEN[index]`. -pub(super) const fn written_cell(index: usize) -> usize { - MASK_WRITES + 1 + index -} - -/// The ELs and GXF states, `Mirrors::banks` per [`mirror_state`]. -pub(super) const MIRROR_STATES: usize = 8; -const _: () = assert!(MIRROR_STATES == transition::STATES); - -pub(super) fn mirror_state(el: u8, guarded: bool) -> usize { - usize::from(el) | usize::from(guarded) << 2 -} - -impl Mirrors { - /// The cells of the PE's state, at what [`Anchor::Cells`] holds. - pub(super) fn cells(&self) -> &[register_read::Cell; CELLS] { - &self.banks[self.state] - } - - /// The state native code left current, which a native transition may - /// have moved: its cells may hold open values from now on. - pub(super) fn native_state(&mut self) -> usize { - self.state &= MIRROR_STATES - 1; - self.entered |= 1 << self.state; - self.state - } - - /// Native code is entered with PSTATE `pstate`. - pub(super) fn enter(&mut self, pstate: Pstate) { - let bit = |set: bool, index: usize| if set { PSTATE_FIELDS[index].1 } else { 0 }; - self.fields = [bit(pstate.dit, 0), bit(pstate.uao, 1), bit(pstate.ssbs, 2)]; - } - - /// Native code returned: `pstate` takes the fields it wrote. - pub(super) fn leave(&self, pstate: &mut Pstate) { - let [dit, uao, ssbs] = self.fields.map(|word| word != 0); - (pstate.dit, pstate.uao, pstate.ssbs) = (dit, uao, ssbs); - } - - /// The address native code reads and writes field `index` at. - pub(super) fn field_storage(&self, index: usize) -> u64 { - &self.fields[index] as *const u64 as u64 - } - - /// The PE is in state `to`: native code reads its cells. - pub(super) fn transition(&mut self, to: usize) { - self.state = to; - self.entered |= 1 << to; - } - - /// Close every cell. A closed cell keeps no value a mispredicted native - /// read could use (FEAT_CSV3's System register rule). - pub(super) fn close_all(&mut self) { - for (state, cells) in self.banks.iter_mut().enumerate() { - if self.entered >> state & 1 != 0 { - *cells = [register_read::Cell::default(); CELLS]; - } - } - self.entered = 1 << self.state; - } - - /// The open cells [`Self::close_all`] would close. - pub(super) fn open_cells(&self) -> u64 { - self.banks - .iter() - .enumerate() - .filter(|&(state, _)| self.entered >> state & 1 != 0) - .flat_map(|(_, cells)| cells) - .filter(|cell| cell.readable != 0) - .count() as u64 - } - - /// Whether every cell is closed. - #[cfg(test)] - pub(super) fn closed(&self) -> bool { - self.banks.iter().flatten().all(|cell| cell.readable == 0) - } - - /// The register of cell `index` now holds `value`, as its open cells - /// in every state read it. - pub(super) fn update(&mut self, index: usize, value: u64) { - for cells in &mut self.banks { - if cells[index].readable != 0 { - cells[index].value = value; - } - } - } - - /// IC IVAU of `address` completed: its page's lines need no other. - pub(super) fn open_code_page(&mut self, address: u64) { - self[CODE_PAGE] = register_read::Cell { - readable: 1, - value: address, - }; - // The DSB that ends the run of lines closes the cell again. - self.barrier = register_read::Cell::default(); - } - - /// Another IC IVAU of the page could do more. - pub(super) fn close_code_page(&mut self) { - self.close(CODE_PAGE); - } - - /// Close the cells of one register in every state. - pub(super) fn close(&mut self, index: usize) { - for cells in &mut self.banks { - cells[index] = register_read::Cell::default(); - } - } -} - -/// System registers whose writes leave the derived caches intact. -/// Exception registers and thread pointers are read when used. TTBR0 -/// changes translation, and its write still synchronizes the host regime. -/// CONTEXTIDR changes only live debug matches, which read it when checked. -pub(super) fn stored(register: SystemRegister) -> bool { - use SystemRegister::*; - matches!( - register, - TTBR0_EL1 - | TTBR0_EL2 - | CONTEXTIDR_EL1 - | CONTEXTIDR_EL2 - | ELR_EL1 - | ELR_EL2 - | SPSR_EL1 - | SPSR_EL2 - | ESR_EL1 - | ESR_EL2 - | FAR_EL1 - | FAR_EL2 - | PAR_EL1 - | TPIDR_EL0 - | TPIDRRO_EL0 - | TPIDR_EL1 - | TPIDR_EL2 - ) -} - -/// Whether `register` is half of a PAC key. -pub(super) fn pointer_key(register: SystemRegister) -> bool { - use SystemRegister::*; - matches!( - register, - APIAKeyLo_EL1 - | APIAKeyHi_EL1 - | APIBKeyLo_EL1 - | APIBKeyHi_EL1 - | APDAKeyLo_EL1 - | APDAKeyHi_EL1 - | APDBKeyLo_EL1 - | APDBKeyHi_EL1 - | APGAKeyLo_EL1 - | APGAKeyHi_EL1 - ) -} - -/// Whether a generated read that ends with `register`'s value is the plain -/// read of its storage, which a cell may point at: only state those reads -/// return as stored, never a view composed from it. -pub(super) fn reads_storage(register: SystemRegister) -> bool { - use SystemRegister::*; - stored(register) - || matches!( - register, - SP_EL0 - | HCR_EL2 - | SCTLR_EL1 - | SCTLR_EL2 - | TCR_EL1 - | TCR_EL2 - | TTBR1_EL1 - | TTBR1_EL2 - | VBAR_EL1 - | VBAR_EL2 - | CPTR_EL2 - | CPACR_EL1 - ) -} - -/// Whether MRS of `encoding` can have a stored cell of its own storage: not -/// the ID space, whose reads are few, nor the IMPLEMENTATION DEFINED one, -/// which Apple's state answers. -pub(super) fn storable(encoding: Encoding) -> bool { - !(encoding.op0() == 3 && matches!(encoding.crn(), 0 | 11 | 15)) -} - -impl core::ops::Index for Mirrors { - type Output = register_read::Cell; - fn index(&self, index: usize) -> &Self::Output { - &self.banks[self.state][index] - } -} - -impl core::ops::IndexMut for Mirrors { - fn index_mut(&mut self, index: usize) -> &mut Self::Output { - &mut self.banks[self.state][index] - } -} - -/// The [`MIRRORED`] index of DAIF. -pub(super) const DAIF_MIRROR: usize = MIRRORED.len() - 1; -const _: () = assert!(matches!(MIRRORED[DAIF_MIRROR], registers::encodings::DAIF)); -/// The [`MIRRORED`] indices of CNTVCT_EL0 and CNTVCT_ALIAS_EL0, count -/// reads completed natively whenever the host's counter is its TSC's -/// ([`Host::tsc_counter`]). -pub(super) const COUNT_MIRRORS: [usize; 2] = [DAIF_MIRROR - 2, DAIF_MIRROR - 1]; -const _: () = assert!(matches!( - MIRRORED[COUNT_MIRRORS[0]], - stela_compiler::aarch64::system::registers::CNTVCT_EL0 -)); -const _: () = assert!(matches!( - MIRRORED[COUNT_MIRRORS[1]], - registers::encodings::CNTVCT_ALIAS_EL0 -)); - -/// The [`MIRRORED`] indices of SPSR_GL1, ASPSR_GL1 and ELR_GL1, which a -/// guarded level reads when it is entered and writes before it leaves. Their -/// cells open only in a guarded level, where they are plain, on the bank's -/// storage: reads and writes both go there, as GENTER and an exception -/// taken to the level do ([`registers::guarded_storage`]). -pub(super) const GUARDED_MIRRORS: [usize; 3] = [4, 5, 6]; -const _: () = assert!(matches!( - [ - MIRRORED[GUARDED_MIRRORS[0]], - MIRRORED[GUARDED_MIRRORS[1]], - MIRRORED[GUARDED_MIRRORS[2]] - ], - [ - registers::encodings::SPSR_GL1, - registers::encodings::ASPSR_GL1, - registers::encodings::ELR_GL1 - ] -)); - -/// The [`MIRRORED`] indices of the cycle and instruction counters. They -/// move at every instruction but no read depends on it: between transitions -/// they read the count of the last one, as exceptions are what a kernel -/// charges to threads, and later reads never go back. Exactly: a read -/// opens its cell on the count it took, and native reads in that state -/// answer that value until the cell closes: at the next native entry where -/// native reads compute the count (`Machine::enter_cycles`), at an -/// exception entry or return there (the engine's takes the count anew, -/// `cells_moved`; a native one closes it, the record's `close`), or at a -/// change of derived state. So a computed counter's value is at most one -/// native run old; where native code cannot compute it (a degraded read, -/// the cycle counter on a host without a TSC), until a transition. -pub(super) const COUNTER_MIRRORS: [usize; 2] = [8, 9]; -const _: () = assert!(COUNTER_MIRRORS[0] == 8); - -/// MRS X0 of `encoding`. -pub(super) fn read_word(encoding: Encoding) -> u32 { - 0xd530_0000 - | u32::from(encoding.op0() & 1) << 19 - | u32::from(encoding.op1()) << 16 - | u32::from(encoding.crn()) << 12 - | u32::from(encoding.crm()) << 8 - | u32::from(encoding.op2()) << 5 -} - -/// The [`MIRRORED`] index of SPRR_PERM_EL0, which dyld and JIT runtimes -/// write around each write to their protected pages and read back at once. -/// An SPRR_PERM write keeps derived state ([`Machine::permissions_changed`]) -/// but closes these cells; a write of SPRR_PERM_EL0 itself reopens the one -/// open before it ([`Machine::permission_write`]). -pub(super) const SPRR_PERM_MIRROR: usize = COUNT_MIRRORS[0] - 1; -const _: () = assert!(matches!( - MIRRORED[SPRR_PERM_MIRROR], - registers::encodings::SPRR_PERM_EL0 -)); - -/// MRS DAIF's value for PSTATE's D, A, I and F masks: bits 9:6. -pub(super) fn daif_register(daif: u8) -> u64 { - u64::from(daif) << DAIF_REGISTER_SHIFT -} - -pub(super) const DAIF_REGISTER_SHIFT: u32 = 6; - -/// The index in [`WRITTEN`] of a write of `access`. -pub(super) fn written(access: RegisterAccess) -> Option { - if access.direction() != Direction::Write { - return None; - } - let encoding = access.encoding(); - WRITTEN.iter().position(|&(written, _)| written == encoding) -} - -/// The [`MIRRORED`] index of a read of `access`, other than to XZR. -pub(super) fn mirrored(access: RegisterAccess) -> Option { - if access.direction() != Direction::Read || access.rt() == ZERO_REGISTER { - return None; - } - MIRRORED - .iter() - .position(|&encoding| encoding == access.encoding()) -} - -/// The [`GUARDED_MIRRORS`] index of a write of `access`. -pub(super) fn guarded_written(access: RegisterAccess) -> Option { - if access.direction() != Direction::Write { - return None; - } - let encoding = access.encoding(); - GUARDED_MIRRORS - .into_iter() - .find(|&index| MIRRORED[index] == encoding) -} - -/// The MSR `word` at `pc` of a [`GUARDED_MIRRORS`] register: its index and Xt. -pub(super) fn guarded_written_register(pc: u64, word: u32) -> Option<(usize, u8)> { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) => Some((guarded_written(access)?, access.rt())), - _ => None, - } -} - -/// The MSR `word` at `pc` of a [`WRITTEN`] register: its index and Xt. -pub(super) fn written_register(pc: u64, word: u32) -> Option<(usize, u8)> { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) => Some((written(access)?, access.rt())), - _ => None, - } -} - -/// Xt of the MSR TTBR0_EL1 `word` at `pc`, if it is one. -pub(super) fn table_base_write(pc: u64, word: u32) -> Option { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) - if access.encoding() == TABLE_BASE && access.direction() == Direction::Write => - { - Some(access.rt()) - } - _ => None, - } -} - -/// The selection the MSR SPSel `word` writes, if it is one. -pub(super) fn stack_select(word: u32) -> Option { - match word { - 0xd500_40bf => Some(false), - 0xd500_41bf => Some(true), - _ => None, - } -} - -/// The immediate of the MSR PAN `word`, if it is one. -pub(super) fn pan_write(word: u32) -> Option { - const MSR_PAN: u32 = 0xd500_409f; - const IMMEDIATE: u32 = 1 << 8; - (word & !IMMEDIATE == MSR_PAN).then_some(word & IMMEDIATE != 0) -} - -/// Whether `word` at `pc` is a DSB that only completes maintenance. -pub(super) fn data_barrier(pc: u64, word: u32) -> bool { - let decoded = block::decode_system_mode_instruction(GuestAddress(pc), word); - matches!( - decoded - .ok() - .flatten() - .map(|instruction| instruction.operation), - Some(SystemOperation::Synchronization( - Synchronization::DataCompletion { nxs: false, .. } - )) - ) -} - -/// Whether `word` at `pc` is CLREX. -pub(super) fn clear_exclusive(pc: u64, word: u32) -> bool { - matches!( - block::decode_system_mode_instruction(GuestAddress(pc), word) - .ok() - .flatten() - .map(|instruction| instruction.operation), - Some(SystemOperation::Exclusive(Ok( - stela_compiler::aarch64::exclusive::Operand::Clear - ))) - ) -} - -/// Whether `word` at `pc` is SEVL (true) or WFE without a timeout (false), -/// if it is one. -pub(super) fn event_instruction(pc: u64, word: u32) -> Option { - use stela_compiler::aarch64::system::synchronization::WaitKind; - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::SendEvent { local: true } => Some(true), - SystemOperation::Wait { - kind: WaitKind::Event, - timeout_register: None, - } => Some(false), - _ => None, - } -} - -/// The fast-IPI register MSR `word` at `pc` writes, and Rt, if it writes -/// one native code completes: IPI_RR_LOCAL, IPI_RR_GLOBAL or IPI_SR. -pub(super) fn fast_ipi_write( - pc: u64, - word: u32, -) -> Option<(crate::machine::fast_ipi::Register, u8)> { - use crate::machine::fast_ipi::Register; - let access = msr_access(pc, word)?; - let register = Register::decode(access.encoding())?; - (register != Register::Countdown).then_some((register, access.rt())) -} - -/// Xt of the IC IVAU `word`, if it is one. -pub(super) fn code_page_invalidation(word: u32) -> Option { - const IC_IVAU: u32 = 0xd50b_7520; - (word & !31 == IC_IVAU).then_some((word & 31) as u8) -} - -/// The MSR `word` at `pc`, if it writes a register. -pub(super) fn msr_access(pc: u64, word: u32) -> Option { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) if access.direction() == Direction::Write => Some(access), - _ => None, - } -} - -/// The MRS `word` at `pc`, if it reads to a register. -pub(super) fn mrs_access(pc: u64, word: u32) -> Option { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) - if access.direction() == Direction::Read && access.rt() != ZERO_REGISTER => - { - Some(access) - } - _ => None, - } -} - -/// The [`MIRRORED`] index and Xt of `word` at `pc` if it is MRS of a -/// mirrored register to Xt, other than XZR. -pub(super) fn mirrored_read(pc: u64, word: u32) -> Option<(usize, u8)> { - let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; - match instruction.operation { - SystemOperation::Register(access) => Some((mirrored(access)?, access.rt())), - _ => None, - } -} - -/// Whether `word` at `pc` is a DC ZVA that blocks compiled for `system` -/// complete natively, inside a block as well as at its end. -pub(super) fn zeroes_natively(pc: u64, word: u32, system: NativeSystem) -> bool { - system.zero_block.is_some() - && block::decode_system_mode_instruction(GuestAddress(pc), word) - .ok() - .flatten() - .is_some_and(|instruction| zero_block::operand(&instruction).is_some()) -} - -/// Whether `word` at `pc` is a System instruction blocks compiled for -/// `system` complete natively: DC ZVA, one of its DC clean operations or an -/// exclusive of one register. -pub(super) fn completes_natively(pc: u64, word: u32, system: NativeSystem) -> bool { - block::decode_system_mode_instruction(GuestAddress(pc), word) - .ok() - .flatten() - .is_some_and(|instruction| { - system.zero_block.is_some() && zero_block::operand(&instruction).is_some() - || cache_clean::operand(&instruction) - .is_some_and(|(operation, _)| system.cache_clean.contains(operation)) - || system.exclusive && native_exclusive::operand(&instruction).is_some() - }) -} +//! System register reads that native code completes from mirror cells. + +use super::*; + +/// The System registers whose MRS native code completes from a mirror +/// cell (`x86_64::register_read`): reads without side effects whose result +/// and plainness follow from System registers and PSTATE alone, so a read +/// the engine found plain stays plain, with the same value, until derived +/// state may change ([`Machine::derived_changed`]). They are the thread +/// pointers, Apple's GL2 thread pointer and GXF status, the GL1 exception +/// registers a guarded level saves and restores ([`GUARDED_MIRRORS`]), +/// SPRR_PERM_EL0 ([`SPRR_PERM_MIRROR`]) and DAIF; and the virtual count and +/// Apple's alias of it, whose cells hold the offset they subtract from the +/// clock's count ([`COUNT_MIRRORS`]); CurrentEL and MPIDR_EL1, which each +/// state's cell answers for good; and the cycle and instruction counters a +/// kernel reads around each exception to charge threads, which a transition +/// brings up to date ([`COUNTER_MIRRORS`]). +pub(super) const MIRRORED: [Encoding; 15] = { + use registers::encodings::{ + ASPSR_GL1, CNTVCT_ALIAS_EL0, CURRENT_EL, DAIF, ELR_GL1, GXF_STATUS_EL1, MPIDR_EL1, + SPRR_PERM_EL0, SPSR_GL1, TPIDR_EL1, TPIDR_EL2, TPIDR_GL2, + }; + use stela_compiler::aarch64::system::registers::CNTVCT_EL0; + [ + TPIDR_EL1, + TPIDR_EL2, + TPIDR_GL2, + GXF_STATUS_EL1, + SPSR_GL1, + ASPSR_GL1, + ELR_GL1, + CURRENT_EL, + super::super::pmu::PMC[0], + super::super::pmu::PMC[1], + MPIDR_EL1, + SPRR_PERM_EL0, + CNTVCT_EL0, + CNTVCT_ALIAS_EL0, + DAIF, + ] +}; + +/// Rt 31 in MRS: XZR, which discards the value. +pub(super) const ZERO_REGISTER: u8 = 31; + +/// MRS's L bit (21), which makes an MSR (register) word the MRS of the +/// same register and Xt. +pub(super) const MRS_READ: u32 = 1 << 21; + +/// The registers read other than [`MIRRORED`] ones that get a cell of their +/// own the first time code naming them is installed +/// ([`Machine::stored_cell`]), which reads the register's live storage: the +/// ones a kernel reads around each exception and thread switch, FPCR and +/// FPSR, and the core counters a sampler reads in bursts +/// ([`Devices::register_storage`]). When there are more, the rest take System +/// exits. Cells go to registers in the order code naming them is first +/// installed, which for a kernel is boot's, so there are cells for every +/// register a boot reads: macOS reads over 64 before its first process, and +/// its processes' every MRS of TPIDRRO_EL0, their thread pointer, then took +/// an exit, over 100,000 a second on each PE running them. +pub(super) const STORED_CELLS: usize = 256; + +/// The user thread pointers, which every board's stored cells number first +/// (`numbering::Numbering`), before any code is installed: their cells then +/// lie at the same place in every boot, so the blocks that read them inside +/// themselves (`regime_state::inline_mirrored_reads`) translate alike, and +/// none of a boot's other registers takes their place. +pub(super) const USER_THREAD_POINTERS: [Encoding; 2] = [ + registers::encodings::TPIDRRO_EL0, + registers::encodings::TPIDR_EL0, +]; + +/// The cells of the [`MIRRORED`] registers, in its order, and the +/// [`STORED_CELLS`]: native code reads those of the PE's EL and GXF state, +/// the bank of `banks` that `state` names. A read's value and plainness +/// follow from System registers and PSTATE, of which an exception entry or +/// return, GENTER or GEXIT changes these and the masks alone: each state +/// keeps its cells, which it finds again ([`Mirrors::transition`]). Only +/// SP_EL0 follows SPSel, whose thunks read `selected`, PSTATE.SP while native +/// code runs, which can change it +/// (`x86_64::register_read::stack_select_thunk`). +/// Anything else that changes derived state closes every cell of every bank. +/// The last of them says whether writes of the masks complete natively +/// ([`MASK_WRITES`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Mirrors { + pub(super) banks: [[register_read::Cell; CELLS]; MIRROR_STATES], + state: usize, + /// A bit per bank that was the PE's since cells last closed, which only + /// those can hold open. + entered: u8, + pub(super) selected: u64, + /// PSTATE.DIT, UAO and SSBS as their registers read, in + /// [`PSTATE_FIELDS`] order, while native code runs: their reads and + /// writes complete here ([`pstate_field`]). + pub(super) fields: [u64; 3], + /// What a native ISR_EL1 read checks + /// (`x86_64::register_read::interrupt_status_thunk`): `readable` the + /// count before which time alone leaves the interrupt lines of the last + /// step as they were (0 while the read is not the lines' alone), + /// `value` the interrupt epoch they reflect + /// ([`Machine::refresh_interrupt_status`]). + pub(super) interrupt_status: register_read::Cell, + /// What a native timer write that lowers the EL2 virtual timer's output + /// leaves waiting (`x86_64::register_read::TimerPlaces::quiet`): open + /// with [`GuestState::pending`] as the step set it but for a FIQ that + /// channel alone raised ([`Machine::refresh_timer_quiet`]). + pub(super) timer_quiet: register_read::Cell, + /// What a native DSB checks (`x86_64::register_read::barrier_thunk`): + /// open while this PE has no maintenance outstanding, whatever its + /// state or derived state ([`Machine::open_barrier`]). + pub(super) barrier: register_read::Cell, + /// What native SEVL and WFE complete on + /// (`x86_64::register_read::send_event_thunk`, `event_wait_thunk`): open + /// on the PE's event register as native code is entered + /// ([`Machine::enter_events`]). Neither depends on any System register + /// or the PE's state: SEVL never traps, and a WFE that finds the event + /// register set clears it and completes before any trap check (Arm + /// `Hint_WFE`); one that finds it clear exits for the engine to wait. + pub(super) events: register_read::Cell, + /// What native CLREX completes on + /// (`x86_64::register_read::clear_exclusive_thunk`): open as native + /// code is entered while the engine holds no monitor of its own and + /// traces none ([`Machine::enter_events`]), its `value` the PE's + /// reservation word (`Cpu::reservation_word`), which a held canonical + /// reservation makes nonzero. CLREX never traps, so nothing else + /// decides it. + pub(super) exclusive: register_read::Cell, + /// The records native GENTER and GEXIT complete from + /// (`x86_64::transition`), indexed by `state`, which they move. + pub(super) transitions: transition::Table, + /// The count before which time alone changes no interrupt line, as the + /// last step at EL2 found it (0 elsewhere): native GEXIT unmasks only + /// before it ([`Machine::refresh_interrupt_status`]). + pub(super) lines_until: u64, + /// The thread switches native TPIDR_EL1 writes made since native code + /// was entered, which the engine takes when it returns + /// ([`Machine::take_thread_switches`]). + pub(super) switches: register_read::SwitchLog, + /// Nonzero while the engine holds an exclusive monitor of its own + /// (`Cpu::monitor`), set as native code is entered: native ERET then + /// leaves clearing it to the engine. A canonical reservation has its + /// own word, which the exclusive service keeps (`Record::reservation`). + pub(super) monitor: u64, + /// The performance monitor's cycle counter as native code is entered + /// ([`Machine::enter_cycles`]), from which a cycle counter read computes + /// the count where only its cell's value went stale. + pub(super) cycles: register_read::CycleCounter, + /// The performance monitor's instruction counter as native code is + /// entered ([`Machine::enter_cycles`]), from which an instruction + /// counter read computes the count where only its cell's value went + /// stale. + pub(super) instructions: register_read::InstructionCounter, + /// What native WFEs counted of their spins since native code was + /// entered, which the engine takes when it returns + /// ([`Machine::take_event_spins`]). + pub(super) spin: register_read::EventSpin, + /// The event stream native WFEs sample, as the engine published it + /// ([`Machine::enter_events`]) and they moved it. + pub(super) stream: register_read::EventStream, + /// The board's fast-IPI table as this PE's native IPI writes use it, + /// all 0 until the engine installs one ([`Machine::enter_fast_ipi`]), + /// and the PEs they found halted, which the engine wakes when native + /// code returns ([`Machine::take_fast_ipi_wakes`]). + pub(super) fast_ipi: register_read::FastIpi, + /// The plain device reads native device sites complete again + /// ([`DEVICE_READ_KEY`]), a slot per site. + pub(super) device_reads: [register_read::DeviceRead; register_read::DEVICE_READS], + /// The TTBR0 values a native MSR TTBR0 switches to + /// (`x86_64::table_switch`), and the switches it made since the engine + /// last settled them ([`Machine::settle_native_switches`]). + pub(super) table_switch: table_switch::Table, +} + +/// Where native code finds the cell at `index` of the PE's state. +pub(super) const fn cell_place(index: usize) -> Place { + Place::new(Anchor::Cells, index * size_of::()) +} + +/// Where native code finds [`Mirrors::selected`]. +pub(super) const SELECTED: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, selected)); + +/// Where native code finds [`Mirrors::interrupt_status`]. +pub(super) const INTERRUPT_STATUS: Place = + Place::new(Anchor::Mirrors, offset_of!(Mirrors, interrupt_status)); + +/// Where native code finds [`Mirrors::barrier`]. +pub(super) const BARRIER: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, barrier)); + +/// Where native code finds [`Mirrors::events`]. +pub(super) const EVENTS: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, events)); + +/// Where native code finds [`Mirrors::exclusive`]. +pub(super) const CLEAR_EXCLUSIVE: Place = + Place::new(Anchor::Mirrors, offset_of!(Mirrors, exclusive)); + +/// MRS ISR_EL1 to Xt, Rt in bits 4:0. +pub(super) const READ_INTERRUPT_STATUS: u32 = 0xd538_c100; + +/// Xt of the MRS ISR_EL1 `word`, if it is one. +pub(super) fn interrupt_status_read(word: u32) -> Option { + (word & !31 == READ_INTERRUPT_STATUS).then_some((word & 31) as u8) +} + +/// The cell of MSR SPSel, open once one completed plainly in the state: +/// its `value` is the address of the stack SPSel 1 selects there. +pub(super) const STACK_SELECT: usize = MASK_WRITES + 1 + WRITTEN.len(); + +/// The cell of IC IVAU (`x86_64::register_read::code_page_thunk`), open +/// from one's completion until something could make another do more: code +/// compiled, a translation changed or the DSB that ends the kernel's run of +/// lines. Its `value` is an address in the page. +pub(super) const CODE_PAGE: usize = STACK_SELECT + 1; + +/// The cell of MSR PAN (`x86_64::register_read::pan_thunk`), open once one +/// completed plainly in the state on a host that keeps PAN in RFLAGS.AC. +pub(super) const PAN_WRITES: usize = CODE_PAGE + 1; + +/// The cell of MSR TTBR0_EL1 (`x86_64::register_read::unchanged_write_thunk`), +/// open on the storage a plain write reached: a write of the value the +/// register holds completes natively and changes nothing, any other exits. +/// A kernel rewrites the same table base at most switches into a thread of +/// the address space it already runs. +pub(super) const TABLE_BASE_KEPT: usize = PAN_WRITES + 1; + +/// TTBR0_EL1 (TTBR0_EL2 at EL2 with E2H). +pub(super) const TABLE_BASE: Encoding = Encoding::new(3, 0, 2, 0, 0); + +/// The cells of the EL2 virtual timer's compare and control +/// (`x86_64::register_read::timer_thunk`), whose `value`s are the addresses +/// of CNTHV_CVAL_EL2's and CNTHV_CTL_EL2's storage. An access of CNTV_TVAL, +/// CNTV_CVAL or CNTV_CTL that completes plainly opens both, only where +/// such an access always reaches that channel with no offset: at EL2, +/// outside a guarded level, with HCR_EL2.E2H set (Arm `AArch64_CNTV_*` +/// redirect to CNTHV_*), on a chip whose one timer bank counts the system +/// count unscaled (before the M3: `timer::agt`). No CNTHCTL_EL2 trap applies +/// at EL2. +pub(super) const TIMER_COMPARE: usize = TABLE_BASE_KEPT + 1; +pub(super) const TIMER_CONTROL: usize = TIMER_COMPARE + 1; + +/// Where native timer accesses find the channel and the engine's words. +pub(super) const TIMER: register_read::TimerPlaces = register_read::TimerPlaces { + compare: cell_place(TIMER_COMPARE), + control: cell_place(TIMER_CONTROL), + lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), + interrupt_status: INTERRUPT_STATUS, + count: Place::new(Anchor::Count, 0), + quiet: Place::new(Anchor::Mirrors, offset_of!(Mirrors, timer_quiet)), +}; + +/// MSR CNTV_TVAL_EL0, CNTV_CTL_EL0 and CNTV_CVAL_EL0, and MRS +/// CNTV_CTL_EL0, with Rt in bits 4:0. +const TIMER_VALUE_WRITE: u32 = 0xd51b_e300; +const TIMER_CONTROL_WRITE: u32 = 0xd51b_e320; +const TIMER_COMPARE_WRITE: u32 = 0xd51b_e340; +const TIMER_CONTROL_READ: u32 = 0xd53b_e320; + +/// What a native timer access of `word` does, and Rt, if `word` is one: +/// [`TimerWord`]. +pub(super) fn timer_word(word: u32) -> Option<(TimerWord, u8)> { + let access = match word & !31 { + TIMER_VALUE_WRITE => TimerWord::Value, + TIMER_CONTROL_WRITE => TimerWord::ControlWrite, + TIMER_COMPARE_WRITE => TimerWord::Compare, + TIMER_CONTROL_READ => TimerWord::ControlRead, + _ => return None, + }; + Some((access, (word & 31) as u8)) +} + +/// The timer accesses native code completes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum TimerWord { + Value, + Compare, + ControlWrite, + ControlRead, +} + +/// The cell that says the cycle counter's read is plain in the state +/// (`x86_64::register_read::cycle_counter_thunk`): it opens with the +/// counter's own cell ([`COUNTER_MIRRORS`]) and closes only with every cell, +/// as plainness follows from System registers and PSTATE alone, while a +/// native transition closes the counter's cell because its value, the +/// count, went stale. +pub(super) const CYCLES_PLAIN: usize = TIMER_CONTROL + 1; + +/// Where native code finds [`Mirrors::cycles`]. +pub(super) const CYCLES: Place = Place::new(Anchor::Mirrors, offset_of!(Mirrors, cycles)); + +/// The cell that says the instruction counter's read is plain in the state +/// (`x86_64::register_read::instruction_counter_thunk`), as +/// [`CYCLES_PLAIN`] is the cycle counter's. +pub(super) const INSTRUCTIONS_PLAIN: usize = CYCLES_PLAIN + 1; + +/// Where native code finds [`Mirrors::instructions`]. +pub(super) const INSTRUCTION_COUNTER: Place = + Place::new(Anchor::Mirrors, offset_of!(Mirrors, instructions)); + +/// The cells of MSR SPRR_PERM_EL0 and MSR SPRR_PERM_EL1 +/// (`x86_64::register_read::unchanged_write_thunk`), open on the storage a +/// plain write reached in the state: a write of the value the register +/// holds completes natively and changes nothing (no access changes, as the +/// engine's own write of it finds), any other exits. A kernel writes the +/// user permissions at each return to a thread and the kernel ones around +/// each write of protected data, mostly with the value they hold. A write +/// whose model refused it closes them ([`Machine::register_refused`]). +pub(super) const PERMISSION_KEPT: [usize; 2] = [INSTRUCTIONS_PLAIN + 1, INSTRUCTIONS_PLAIN + 2]; + +/// The [`PERMISSION_KEPT`] cell of the MSR `word`, and Rt, if it writes +/// SPRR_PERM_EL0 or SPRR_PERM_EL1. +pub(super) fn permission_write_word(word: u32) -> Option<(usize, u8)> { + const MSR_SPRR_PERM_EL0: u32 = 0xd51e_f1a0; + const MSR_SPRR_PERM_EL1: u32 = 0xd51e_f1c0; + let kept = match word & !31 { + MSR_SPRR_PERM_EL0 => PERMISSION_KEPT[0], + MSR_SPRR_PERM_EL1 => PERMISSION_KEPT[1], + _ => return None, + }; + Some((kept, (word & 31) as u8)) +} + +/// The cell open where a WFE that finds the event register clear waits, +/// taking no trap, and other PEs run meanwhile on cores of their own, any of +/// which may set it: there native WFE spins for the register +/// (`x86_64::register_read::event_wait_thunk`). A WFE that waits in the +/// engine opens it ([`Machine::wait`]); the trap controls are System +/// registers, whose change closes every cell. +pub(super) const EVENT_WAITS: usize = PERMISSION_KEPT[1] + 1; + +/// Where native WFE finds the event register and what ends its spin. +pub(super) const EVENT_WAIT: register_read::EventWaitPlaces = register_read::EventWaitPlaces { + events: EVENTS, + waits: cell_place(EVENT_WAITS), + monitor: Place::new(Anchor::Mirrors, offset_of!(Mirrors, monitor)), + control: Place::new(Anchor::Control, 0), + lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), + count: Place::new(Anchor::Count, 0), + spin: Place::new(Anchor::Mirrors, offset_of!(Mirrors, spin)), + stream: Place::new(Anchor::Mirrors, offset_of!(Mirrors, stream)), +}; + +/// The cell open where MSR IPI_RR_LOCAL, IPI_RR_GLOBAL and IPI_SR +/// complete plainly through the board, taking no trap +/// (`x86_64::register_read::fast_ipi_request_thunk`, `fast_ipi_status_thunk`): +/// a board fast-IPI write the engine completed opens it +/// ([`Machine::board_register`]). The traps (EL0, HCR_EL2.TIDCP, HACR_EL2) +/// follow from PSTATE and System registers, whose change closes every cell. +pub(super) const FAST_IPI_WRITES: usize = EVENT_WAITS + 1; + +/// Where native fast-IPI writes find their words. +pub(super) const FAST_IPI: register_read::FastIpiPlaces = register_read::FastIpiPlaces { + cell: cell_place(FAST_IPI_WRITES), + ipi: Place::new(Anchor::Mirrors, offset_of!(Mirrors, fast_ipi)), + control: Place::new(Anchor::Control, 0), + interrupt_status: INTERRUPT_STATUS, +}; + +/// The cell whose `value` is the key ([`register_read::device_read_key`]) +/// native device reads of the state match +/// (`x86_64::register_read::device_read_thunk`): open on the PE's device +/// read generation once the engine kept a plain device read in the state +/// ([`Machine::keep_device_read`]). A translation that may have changed +/// moves the generation ([`Machine::forget_device_reads`]); any other change +/// of derived state closes every cell. +pub(super) const DEVICE_READ_KEY: usize = FAST_IPI_WRITES + 1; + +/// Where native device reads find theirs. +pub(super) const DEVICE_READ: register_read::DeviceReadPlaces = register_read::DeviceReadPlaces { + reads: Place::new(Anchor::Mirrors, offset_of!(Mirrors, device_reads)), + key: cell_place(DEVICE_READ_KEY), + count: Place::new(Anchor::Count, 0), +}; + +/// The cell of the first of the [`STORED_WRITES`]. +const STORED_WRITE_CELLS: usize = DEVICE_READ_KEY + 1; + +/// The IMPLEMENTATION DEFINED registers that a store completes writes of +/// that get a cell of their own the first time code naming them is installed +/// ([`Machine::stored_write_cell`]), open on the register's value once a +/// write completes plainly. A kernel writes them around each thread switch. +/// When there are more, the rest take System exits. Numbers go in install +/// order and never free, and boot installs writes of dozens of tuning, +/// control and counter registers (26A434 XNU alone writes over 40 stored +/// ones) before the first thread switch, so room for the ones a kernel +/// writes at every switch (thread keys, SPRR's field registers) must +/// outlast those. +pub(super) const STORED_WRITES: usize = 128; + +const CELLS: usize = STORED_WRITE_CELLS + STORED_WRITES; + +/// The cell of `stored_writes[index]`. +pub(super) const fn stored_write_cell(index: usize) -> usize { + STORED_WRITE_CELLS + index +} + +/// The cell of the mask writes (`x86_64::register_read::mask_thunk`), open +/// once one completed plainly in the state. +pub(super) const MASK_WRITES: usize = MIRRORED.len() + STORED_CELLS; + +/// The registers whose MSR native code completes, which a kernel writes +/// around each exception and whose writes change nothing else: a cell each, +/// after [`MASK_WRITES`], that a plain write opens on the storage it reached +/// (FPSR's lives in the frame, so names none). They stay open as reads do. +/// A PAC key's halves also close the keys to PAC thunks, which then reopen +/// together (`Machine::open_pointers`). TPIDR_EL1's also update its open +/// read cells in every state and log the thread switch for the engine's +/// diagnostics ([`THREAD_SWITCH`]). FPCR's lives in the frame too: the +/// compiled FP operations read it there at run time. +pub(super) const WRITTEN: [(Encoding, SystemRegister); 19] = [ + (Encoding::new(3, 0, 4, 0, 1), SystemRegister::ELR_EL1), + (Encoding::new(3, 0, 4, 0, 0), SystemRegister::SPSR_EL1), + (STACK_ZERO, SystemRegister::SP_EL0), + (Encoding::new(3, 3, 4, 4, 1), SystemRegister::FPSR), + (registers::encodings::FPCR, SystemRegister::FPCR), + (registers::encodings::TPIDR_EL0, SystemRegister::TPIDR_EL0), + ( + registers::encodings::TPIDRRO_EL0, + SystemRegister::TPIDRRO_EL0, + ), + (Encoding::new(3, 0, 2, 1, 0), SystemRegister::APIAKeyLo_EL1), + (Encoding::new(3, 0, 2, 1, 1), SystemRegister::APIAKeyHi_EL1), + (Encoding::new(3, 0, 2, 1, 2), SystemRegister::APIBKeyLo_EL1), + (Encoding::new(3, 0, 2, 1, 3), SystemRegister::APIBKeyHi_EL1), + (Encoding::new(3, 0, 2, 2, 0), SystemRegister::APDAKeyLo_EL1), + (Encoding::new(3, 0, 2, 2, 1), SystemRegister::APDAKeyHi_EL1), + (Encoding::new(3, 0, 2, 2, 2), SystemRegister::APDBKeyLo_EL1), + (Encoding::new(3, 0, 2, 2, 3), SystemRegister::APDBKeyHi_EL1), + (Encoding::new(3, 0, 2, 3, 0), SystemRegister::APGAKeyLo_EL1), + (Encoding::new(3, 0, 2, 3, 1), SystemRegister::APGAKeyHi_EL1), + (CONTEXT_ID, SystemRegister::CONTEXTIDR_EL1), + (registers::encodings::TPIDR_EL1, SystemRegister::TPIDR_EL1), +]; + +/// The [`WRITTEN`] index of TPIDR_EL1, the kernel's thread pointer. +pub(super) const THREAD_POINTER_WRITE: usize = WRITTEN.len() - 1; + +/// The [`MIRRORED`] index of TPIDR_EL1. +pub(super) const THREAD_POINTER_MIRROR: usize = 0; +const _: () = assert!(matches!( + MIRRORED[THREAD_POINTER_MIRROR], + registers::encodings::TPIDR_EL1 +)); + +/// Where a native TPIDR_EL1 write finds the register's read cells and the +/// switch log (`x86_64::register_read::thread_switch_thunk`). +pub(super) const THREAD_SWITCH: register_read::ThreadSwitch = register_read::ThreadSwitch { + reads: Place::new( + Anchor::Mirrors, + offset_of!(Mirrors, banks) + THREAD_POINTER_MIRROR * size_of::(), + ), + stride: size_of::<[register_read::Cell; CELLS]>(), + banks: MIRROR_STATES, + log: Place::new(Anchor::Mirrors, offset_of!(Mirrors, switches)), +}; + +/// CONTEXTIDR_EL1 (CONTEXTIDR_EL2 at EL2 with E2H), which a kernel writes +/// at each thread or address space switch: only debug and trace read it, +/// context-aware breakpoints live from its storage, and it is not part of +/// the prediction context (`PredictionContext`). +pub(super) const CONTEXT_ID: Encoding = Encoding::new(3, 0, 13, 0, 1); + +/// SP_EL0, plain only with SP_ELx selected. +pub(super) const STACK_ZERO: Encoding = Encoding::new(3, 0, 4, 1, 0); + +impl Default for Mirrors { + fn default() -> Self { + let cell = register_read::Cell::default(); + Self { + banks: [[cell; CELLS]; MIRROR_STATES], + state: 0, + entered: 1, + selected: 0, + fields: [0; 3], + interrupt_status: register_read::Cell::default(), + timer_quiet: register_read::Cell::default(), + barrier: register_read::Cell::default(), + events: register_read::Cell::default(), + exclusive: register_read::Cell::default(), + transitions: transition::Table::default(), + lines_until: 0, + switches: register_read::SwitchLog::default(), + monitor: 0, + cycles: register_read::CycleCounter::default(), + instructions: register_read::InstructionCounter::default(), + spin: register_read::EventSpin::default(), + stream: register_read::EventStream::default(), + fast_ipi: register_read::FastIpi::default(), + device_reads: [register_read::DeviceRead::default(); register_read::DEVICE_READS], + table_switch: table_switch::Table::default(), + } + } +} + +/// Where native transitions find the mirrors' words. +pub(super) const TRANSITIONS: transition::Places = transition::Places { + state: Place::new(Anchor::Mirrors, offset_of!(Mirrors, state)), + table: Place::new(Anchor::Mirrors, offset_of!(Mirrors, transitions)), + selected: SELECTED, + fields: Place::new(Anchor::Mirrors, offset_of!(Mirrors, fields)), + field_bits: [ + PSTATE_FIELDS[0].1 as u32, + PSTATE_FIELDS[1].1 as u32, + PSTATE_FIELDS[2].1 as u32, + ], + interrupt_status: INTERRUPT_STATUS, + lines_until: Place::new(Anchor::Mirrors, offset_of!(Mirrors, lines_until)), + count: Place::new(Anchor::Count, 0), + monitor: Place::new(Anchor::Mirrors, offset_of!(Mirrors, monitor)), + pointer_tags: super::pointer::TAGS, + pointer_generation: Place::new( + Anchor::Pointer, + offset_of!(super::pointer::PointerService, generation), + ), + cycles: CYCLES, + instructions: INSTRUCTION_COUNTER, + cr3: stela_compiler::x86_64::table_switch::Cr3::Register, +}; +const _: () = assert!(size_of::() == size_of::()); + +/// The places a native TTBR0 switch writes besides the host's +/// (`x86_64::table_switch::Places`): its table, the chain's lookup +/// contexts and salts, the transition records' contexts generation, and the +/// code-page and device-read cells of every state, which a TTBR0 change +/// closes ([`Machine::advance_table_generation`]). +pub(super) fn table_switch_places( + cr3: Option, + isolate: bool, +) -> table_switch::Places { + let cell = |state: usize, index: usize| { + Place::new( + Anchor::Mirrors, + offset_of!(Mirrors, banks) + (state * CELLS + index) * size_of::(), + ) + }; + table_switch::Places { + table: Place::new(Anchor::Mirrors, offset_of!(Mirrors, table_switch)), + contexts: Place::new(Anchor::Control, offset_of!(chain::ChainControl, contexts)), + salts: Place::new(Anchor::Control, offset_of!(chain::ChainControl, salts)), + contexts_generation: Place::new( + Anchor::Mirrors, + offset_of!(Mirrors, transitions) + offset_of!(transition::Table, contexts_generation), + ), + closes: (0..MIRROR_STATES) + .flat_map(|state| [cell(state, CODE_PAGE), cell(state, DEVICE_READ_KEY)]) + .collect(), + cr3, + isolate, + } +} + +/// The PSTATE fields with registers of their own that a kernel saves and +/// restores around each exception, which only the engine reads besides +/// MRS: DIT, UAO and SSBS, by encoding and register bit. A plain MRS or MSR +/// of one opens a stored cell on its [`Mirrors::fields`] word, which +/// [`Mirrors::enter`] and [`Mirrors::leave`] keep with PSTATE around native +/// code. A write takes the field's bit alone, as the register's do. +pub(super) const PSTATE_FIELDS: [(Encoding, u64); 3] = [ + (Encoding::new(3, 3, 4, 2, 5), 1 << 24), + (Encoding::new(3, 0, 4, 2, 4), 1 << 23), + (Encoding::new(3, 3, 4, 2, 6), 1 << 12), +]; + +/// The [`PSTATE_FIELDS`] index and bit of `encoding`, if it is one. +pub(super) fn pstate_field(encoding: Encoding) -> Option<(usize, u64)> { + PSTATE_FIELDS + .iter() + .position(|&(field, _)| field == encoding) + .map(|index| (index, PSTATE_FIELDS[index].1)) +} + +/// The cell of `WRITTEN[index]`. +pub(super) const fn written_cell(index: usize) -> usize { + MASK_WRITES + 1 + index +} + +/// The ELs and GXF states, `Mirrors::banks` per [`mirror_state`]. +pub(super) const MIRROR_STATES: usize = 8; +const _: () = assert!(MIRROR_STATES == transition::STATES); + +pub(super) fn mirror_state(el: u8, guarded: bool) -> usize { + usize::from(el) | usize::from(guarded) << 2 +} + +impl Mirrors { + /// The cells of the PE's state, at what [`Anchor::Cells`] holds. + pub(super) fn cells(&self) -> &[register_read::Cell; CELLS] { + &self.banks[self.state] + } + + /// The state native code left current, which a native transition may + /// have moved: its cells may hold open values from now on. + pub(super) fn native_state(&mut self) -> usize { + self.state &= MIRROR_STATES - 1; + self.entered |= 1 << self.state; + self.state + } + + /// Native code is entered with PSTATE `pstate`. + pub(super) fn enter(&mut self, pstate: Pstate) { + let bit = |set: bool, index: usize| if set { PSTATE_FIELDS[index].1 } else { 0 }; + self.fields = [bit(pstate.dit, 0), bit(pstate.uao, 1), bit(pstate.ssbs, 2)]; + } + + /// Native code returned: `pstate` takes the fields it wrote. + pub(super) fn leave(&self, pstate: &mut Pstate) { + let [dit, uao, ssbs] = self.fields.map(|word| word != 0); + (pstate.dit, pstate.uao, pstate.ssbs) = (dit, uao, ssbs); + } + + /// The address native code reads and writes field `index` at. + pub(super) fn field_storage(&self, index: usize) -> u64 { + &self.fields[index] as *const u64 as u64 + } + + /// The PE is in state `to`: native code reads its cells. + pub(super) fn transition(&mut self, to: usize) { + self.state = to; + self.entered |= 1 << to; + } + + /// Close every cell. A closed cell keeps no value a mispredicted native + /// read could use (FEAT_CSV3's System register rule). + pub(super) fn close_all(&mut self) { + for (state, cells) in self.banks.iter_mut().enumerate() { + if self.entered >> state & 1 != 0 { + *cells = [register_read::Cell::default(); CELLS]; + } + } + self.entered = 1 << self.state; + } + + /// The open cells [`Self::close_all`] would close. + pub(super) fn open_cells(&self) -> u64 { + self.banks + .iter() + .enumerate() + .filter(|&(state, _)| self.entered >> state & 1 != 0) + .flat_map(|(_, cells)| cells) + .filter(|cell| cell.readable != 0) + .count() as u64 + } + + /// Whether every cell is closed. + #[cfg(test)] + pub(super) fn closed(&self) -> bool { + self.banks.iter().flatten().all(|cell| cell.readable == 0) + } + + /// The register of cell `index` now holds `value`, as its open cells + /// in every state read it. + pub(super) fn update(&mut self, index: usize, value: u64) { + for cells in &mut self.banks { + if cells[index].readable != 0 { + cells[index].value = value; + } + } + } + + /// IC IVAU of `address` completed: its page's lines need no other. + pub(super) fn open_code_page(&mut self, address: u64) { + self[CODE_PAGE] = register_read::Cell { + readable: 1, + value: address, + }; + // The DSB that ends the run of lines closes the cell again. + self.barrier = register_read::Cell::default(); + } + + /// Another IC IVAU of the page could do more. + pub(super) fn close_code_page(&mut self) { + self.close(CODE_PAGE); + } + + /// Close the cells of one register in every state. + pub(super) fn close(&mut self, index: usize) { + for cells in &mut self.banks { + cells[index] = register_read::Cell::default(); + } + } +} + +/// System registers whose writes leave the derived caches intact. +/// Exception registers and thread pointers are read when used. TTBR0 +/// changes translation, and its write still synchronizes the host regime. +/// CONTEXTIDR changes only live debug matches, which read it when checked. +pub(super) fn stored(register: SystemRegister) -> bool { + use SystemRegister::*; + matches!( + register, + TTBR0_EL1 + | TTBR0_EL2 + | CONTEXTIDR_EL1 + | CONTEXTIDR_EL2 + | ELR_EL1 + | ELR_EL2 + | SPSR_EL1 + | SPSR_EL2 + | ESR_EL1 + | ESR_EL2 + | FAR_EL1 + | FAR_EL2 + | PAR_EL1 + | TPIDR_EL0 + | TPIDRRO_EL0 + | TPIDR_EL1 + | TPIDR_EL2 + ) +} + +/// The PAC key tag index (`0..=4`) for half of a PAC key, if `register` is one. +pub(super) fn pointer_key_index(register: SystemRegister) -> Option { + use SystemRegister::*; + match register { + APIAKeyLo_EL1 | APIAKeyHi_EL1 => Some(0), + APIBKeyLo_EL1 | APIBKeyHi_EL1 => Some(1), + APDAKeyLo_EL1 | APDAKeyHi_EL1 => Some(2), + APDBKeyLo_EL1 | APDBKeyHi_EL1 => Some(3), + APGAKeyLo_EL1 | APGAKeyHi_EL1 => Some(4), + _ => None, + } +} + +/// Whether `register` is half of a PAC key. +pub(super) fn pointer_key(register: SystemRegister) -> bool { + pointer_key_index(register).is_some() +} + +/// Whether a generated read that ends with `register`'s value is the plain +/// read of its storage, which a cell may point at: only state those reads +/// return as stored, never a view composed from it. +pub(super) fn reads_storage(register: SystemRegister) -> bool { + use SystemRegister::*; + stored(register) + || matches!( + register, + SP_EL0 + | HCR_EL2 + | SCTLR_EL1 + | SCTLR_EL2 + | TCR_EL1 + | TCR_EL2 + | TTBR1_EL1 + | TTBR1_EL2 + | VBAR_EL1 + | VBAR_EL2 + | CPTR_EL2 + | CPACR_EL1 + ) +} + +/// Whether MRS of `encoding` can have a stored cell of its own storage: not +/// the ID space, whose reads are few, nor the IMPLEMENTATION DEFINED one, +/// which Apple's state answers. +pub(super) fn storable(encoding: Encoding) -> bool { + !(encoding.op0() == 3 && matches!(encoding.crn(), 0 | 11 | 15)) +} + +impl core::ops::Index for Mirrors { + type Output = register_read::Cell; + fn index(&self, index: usize) -> &Self::Output { + &self.banks[self.state][index] + } +} + +impl core::ops::IndexMut for Mirrors { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.banks[self.state][index] + } +} + +/// The [`MIRRORED`] index of DAIF. +pub(super) const DAIF_MIRROR: usize = MIRRORED.len() - 1; +const _: () = assert!(matches!(MIRRORED[DAIF_MIRROR], registers::encodings::DAIF)); +/// The [`MIRRORED`] indices of CNTVCT_EL0 and CNTVCT_ALIAS_EL0, count +/// reads completed natively whenever the host's counter is its TSC's +/// ([`Host::tsc_counter`]). +pub(super) const COUNT_MIRRORS: [usize; 2] = [DAIF_MIRROR - 2, DAIF_MIRROR - 1]; +const _: () = assert!(matches!( + MIRRORED[COUNT_MIRRORS[0]], + stela_compiler::aarch64::system::registers::CNTVCT_EL0 +)); +const _: () = assert!(matches!( + MIRRORED[COUNT_MIRRORS[1]], + registers::encodings::CNTVCT_ALIAS_EL0 +)); + +/// The [`MIRRORED`] indices of SPSR_GL1, ASPSR_GL1 and ELR_GL1, which a +/// guarded level reads when it is entered and writes before it leaves. Their +/// cells open only in a guarded level, where they are plain, on the bank's +/// storage: reads and writes both go there, as GENTER and an exception +/// taken to the level do ([`registers::guarded_storage`]). +pub(super) const GUARDED_MIRRORS: [usize; 3] = [4, 5, 6]; +const _: () = assert!(matches!( + [ + MIRRORED[GUARDED_MIRRORS[0]], + MIRRORED[GUARDED_MIRRORS[1]], + MIRRORED[GUARDED_MIRRORS[2]] + ], + [ + registers::encodings::SPSR_GL1, + registers::encodings::ASPSR_GL1, + registers::encodings::ELR_GL1 + ] +)); + +/// The [`MIRRORED`] indices of the cycle and instruction counters. They +/// move at every instruction but no read depends on it: between transitions +/// they read the count of the last one, as exceptions are what a kernel +/// charges to threads, and later reads never go back. Exactly: a read +/// opens its cell on the count it took, and native reads in that state +/// answer that value until the cell closes: at the next native entry where +/// native reads compute the count (`Machine::enter_cycles`), at an +/// exception entry or return there (the engine's takes the count anew, +/// `cells_moved`; a native one closes it, the record's `close`), or at a +/// change of derived state. So a computed counter's value is at most one +/// native run old; where native code cannot compute it (a degraded read, +/// the cycle counter on a host without a TSC), until a transition. +pub(super) const COUNTER_MIRRORS: [usize; 2] = [8, 9]; +const _: () = assert!(COUNTER_MIRRORS[0] == 8); + +/// MRS X0 of `encoding`. +pub(super) fn read_word(encoding: Encoding) -> u32 { + 0xd530_0000 + | u32::from(encoding.op0() & 1) << 19 + | u32::from(encoding.op1()) << 16 + | u32::from(encoding.crn()) << 12 + | u32::from(encoding.crm()) << 8 + | u32::from(encoding.op2()) << 5 +} + +/// The [`MIRRORED`] index of SPRR_PERM_EL0, which dyld and JIT runtimes +/// write around each write to their protected pages and read back at once. +/// An SPRR_PERM write keeps derived state ([`Machine::permissions_changed`]) +/// but closes these cells; a write of SPRR_PERM_EL0 itself reopens the one +/// open before it ([`Machine::permission_write`]). +pub(super) const SPRR_PERM_MIRROR: usize = COUNT_MIRRORS[0] - 1; +const _: () = assert!(matches!( + MIRRORED[SPRR_PERM_MIRROR], + registers::encodings::SPRR_PERM_EL0 +)); + +/// MRS DAIF's value for PSTATE's D, A, I and F masks: bits 9:6. +pub(super) fn daif_register(daif: u8) -> u64 { + u64::from(daif) << DAIF_REGISTER_SHIFT +} + +pub(super) const DAIF_REGISTER_SHIFT: u32 = 6; + +/// The index in [`WRITTEN`] of a write of `access`. +pub(super) fn written(access: RegisterAccess) -> Option { + if access.direction() != Direction::Write { + return None; + } + let encoding = access.encoding(); + WRITTEN.iter().position(|&(written, _)| written == encoding) +} + +/// The [`MIRRORED`] index of a read of `access`, other than to XZR. +pub(super) fn mirrored(access: RegisterAccess) -> Option { + if access.direction() != Direction::Read || access.rt() == ZERO_REGISTER { + return None; + } + MIRRORED + .iter() + .position(|&encoding| encoding == access.encoding()) +} + +/// The [`GUARDED_MIRRORS`] index of a write of `access`. +pub(super) fn guarded_written(access: RegisterAccess) -> Option { + if access.direction() != Direction::Write { + return None; + } + let encoding = access.encoding(); + GUARDED_MIRRORS + .into_iter() + .find(|&index| MIRRORED[index] == encoding) +} + +/// The MSR `word` at `pc` of a [`GUARDED_MIRRORS`] register: its index and Xt. +pub(super) fn guarded_written_register(pc: u64, word: u32) -> Option<(usize, u8)> { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) => Some((guarded_written(access)?, access.rt())), + _ => None, + } +} + +/// The MSR `word` at `pc` of a [`WRITTEN`] register: its index and Xt. +pub(super) fn written_register(pc: u64, word: u32) -> Option<(usize, u8)> { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) => Some((written(access)?, access.rt())), + _ => None, + } +} + +/// Xt of the MSR TTBR0_EL1 `word` at `pc`, if it is one. +pub(super) fn table_base_write(pc: u64, word: u32) -> Option { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) + if access.encoding() == TABLE_BASE && access.direction() == Direction::Write => + { + Some(access.rt()) + } + _ => None, + } +} + +/// The selection the MSR SPSel `word` writes, if it is one. +pub(super) fn stack_select(word: u32) -> Option { + match word { + 0xd500_40bf => Some(false), + 0xd500_41bf => Some(true), + _ => None, + } +} + +/// The immediate of the MSR PAN `word`, if it is one. +pub(super) fn pan_write(word: u32) -> Option { + const MSR_PAN: u32 = 0xd500_409f; + const IMMEDIATE: u32 = 1 << 8; + (word & !IMMEDIATE == MSR_PAN).then_some(word & IMMEDIATE != 0) +} + +/// Whether `word` at `pc` is a DSB that only completes maintenance. +pub(super) fn data_barrier(pc: u64, word: u32) -> bool { + let decoded = block::decode_system_mode_instruction(GuestAddress(pc), word); + matches!( + decoded + .ok() + .flatten() + .map(|instruction| instruction.operation), + Some(SystemOperation::Synchronization( + Synchronization::DataCompletion { nxs: false, .. } + )) + ) +} + +/// Whether `word` at `pc` is CLREX. +pub(super) fn clear_exclusive(pc: u64, word: u32) -> bool { + matches!( + block::decode_system_mode_instruction(GuestAddress(pc), word) + .ok() + .flatten() + .map(|instruction| instruction.operation), + Some(SystemOperation::Exclusive(Ok( + stela_compiler::aarch64::exclusive::Operand::Clear + ))) + ) +} + +/// Whether `word` at `pc` is SEVL (true) or WFE without a timeout (false), +/// if it is one. +pub(super) fn event_instruction(pc: u64, word: u32) -> Option { + use stela_compiler::aarch64::system::synchronization::WaitKind; + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::SendEvent { local: true } => Some(true), + SystemOperation::Wait { + kind: WaitKind::Event, + timeout_register: None, + } => Some(false), + _ => None, + } +} + +/// The fast-IPI register MSR `word` at `pc` writes, and Rt, if it writes +/// one native code completes: IPI_RR_LOCAL, IPI_RR_GLOBAL or IPI_SR. +pub(super) fn fast_ipi_write( + pc: u64, + word: u32, +) -> Option<(crate::machine::fast_ipi::Register, u8)> { + use crate::machine::fast_ipi::Register; + let access = msr_access(pc, word)?; + let register = Register::decode(access.encoding())?; + (register != Register::Countdown).then_some((register, access.rt())) +} + +/// Xt of the IC IVAU `word`, if it is one. +pub(super) fn code_page_invalidation(word: u32) -> Option { + const IC_IVAU: u32 = 0xd50b_7520; + (word & !31 == IC_IVAU).then_some((word & 31) as u8) +} + +/// The MSR `word` at `pc`, if it writes a register. +pub(super) fn msr_access(pc: u64, word: u32) -> Option { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) if access.direction() == Direction::Write => Some(access), + _ => None, + } +} + +/// The MRS `word` at `pc`, if it reads to a register. +pub(super) fn mrs_access(pc: u64, word: u32) -> Option { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) + if access.direction() == Direction::Read && access.rt() != ZERO_REGISTER => + { + Some(access) + } + _ => None, + } +} + +/// The [`MIRRORED`] index and Xt of `word` at `pc` if it is MRS of a +/// mirrored register to Xt, other than XZR. +pub(super) fn mirrored_read(pc: u64, word: u32) -> Option<(usize, u8)> { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) => Some((mirrored(access)?, access.rt())), + _ => None, + } +} + +/// Whether `word` at `pc` is a DC ZVA that blocks compiled for `system` +/// complete natively, inside a block as well as at its end. +pub(super) fn zeroes_natively(pc: u64, word: u32, system: NativeSystem) -> bool { + system.zero_block.is_some() + && block::decode_system_mode_instruction(GuestAddress(pc), word) + .ok() + .flatten() + .is_some_and(|instruction| zero_block::operand(&instruction).is_some()) +} + +/// Whether `word` at `pc` is a System instruction blocks compiled for +/// `system` complete natively: DC ZVA, one of its DC clean operations or an +/// exclusive of one register. +pub(super) fn completes_natively(pc: u64, word: u32, system: NativeSystem) -> bool { + block::decode_system_mode_instruction(GuestAddress(pc), word) + .ok() + .flatten() + .is_some_and(|instruction| { + system.zero_block.is_some() && zero_block::operand(&instruction).is_some() + || cache_clean::operand(&instruction) + .is_some_and(|(operation, _)| system.cache_clean.contains(operation)) + || system.exclusive && native_exclusive::operand(&instruction).is_some() + }) +} diff --git a/crates/stela-engine/src/machine/engine/parallel/tests.rs b/crates/stela-engine/src/machine/engine/parallel/tests.rs index 225815ab79..089c9da779 100644 --- a/crates/stela-engine/src/machine/engine/parallel/tests.rs +++ b/crates/stela-engine/src/machine/engine/parallel/tests.rs @@ -1,4807 +1,4809 @@ -use super::super::LocalRegisters; -use super::*; -use core::sync::atomic::AtomicUsize; - -struct Kicks(Arc); -impl Kick for Kicks { - fn kick(&self, _pe: usize) { - self.0.fetch_add(1, Ordering::Relaxed); - } -} - -fn hub(pes: usize) -> (Arc, Arc) { - let kicks = Arc::new(AtomicUsize::new(0)); - let hub = Hub::new(pes, Kicks(Arc::clone(&kicks))); - for pe in 0..pes { - hub.set_live(pe, true); - } - // Every PE but the first, which a test's machine may be, runs a block - // (`Hub::enter_active`): a broadcast waits for it. - for pe in 1..pes { - assert!(hub.enter_active(pe)); - } - (hub, kicks) -} - -fn tlbi(kind: crate::machine::system::TlbiKind, operand: u64) -> Maintenance { - use crate::machine::system::{Regime, Tlbi, TlbiAttr, TlbiLevel}; - Maintenance::Tlb(tlbi::Scope::new( - &Tlbi { - kind, - regime: Regime::EL10, - vmid: None, - broadcast: Broadcast::ISH, - level: TlbiLevel::Any, - attr: TlbiAttr::AllAttr, - operand, - }, - tlbi::Context::default(), - )) -} - -/// A TLBI of another context leaves its mail for the PE's next read, and -/// neither interrupts it nor waits for it. -#[test] -fn a_tlbi_passes_by_a_pe_translating_another_context() { - use crate::machine::system::TlbiKind::{ASID, VA, VAA}; - const ASID_5: u64 = 5 << 48; - let (hub, _) = hub(2); - let inbox = &hub.inboxes[1]; - let word = context_word(mmu::Regime::El10, 7); - let epoch = || inbox.chain.interrupt_epoch().load(Ordering::Relaxed); - assert_eq!( - hub.broadcast(0, &[tlbi(ASID, ASID_5)]).len(), - 1, - "unpublished" - ); - inbox.translating.store(word, Ordering::Relaxed); - let interrupts = epoch(); - let passes = [ASID_5, ASID_5 | 0x1234]; - for (kind, operand) in [ASID, VA].into_iter().zip(passes) { - assert!(hub.broadcast(0, &[tlbi(kind, operand)]).is_empty()); - } - assert_eq!(epoch(), interrupts); - assert!(hub.pending(1)); - assert_eq!(hub.take(1).unwrap().maintenance.len(), 3); - assert_eq!( - hub.broadcast(0, &[tlbi(ASID, 7 << 48)]).len(), - 1, - "its context" - ); - assert_eq!( - hub.broadcast(0, &[tlbi(VAA, 0x1234)]).len(), - 1, - "every ASID" - ); - assert!(inbox.lower_globals.widen(0x123_0000, 0x123_ffff)); - assert!(!inbox.lower_globals.widen(0x123_4000, 0x123_7fff)); - assert_eq!( - hub.broadcast(0, &[tlbi(VA, ASID_5 | 0x1234)]).len(), - 1, - "its global page" - ); - assert!(hub.broadcast(0, &[tlbi(VA, ASID_5 | 0x4321)]).is_empty()); -} - -/// What a PE translates is published before its next mail read. -#[test] -fn a_pe_publishes_the_context_it_translates() { - use super::super::tests::machine; - let mut machine = machine(&[0xd503_201f]); - let (hub, _) = hub(1); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - assert_eq!( - hub.inboxes[0].translating.load(Ordering::Relaxed), - ANY_CONTEXT - ); - machine.sync_host_regime(super::super::step_timing::SyncSource::Other); - let controls = machine.cpu.controls(machine.cpu.regime()); - assert_eq!( - hub.inboxes[0].translating.load(Ordering::Relaxed), - context_word(controls.regime, mmu::current_asid(&controls)) - ); -} - -#[test] -fn duplicate_safe_attachment_refuses_without_replacing_the_live_owner() { - use super::super::tests::{BASE, board}; - use crate::machine::NoDevices; - use stela_contracts::identity::Identity; - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut first = board(&[], NoDevices, identities.clone()); - let mut second = board(&[], NoDevices, identities); - let (hub, _) = hub(1); - first.enter_parallel(Arc::clone(&hub)).unwrap(); - let epoch = first.attached.as_ref().unwrap().epoch; - let untouched = second.chain.snapshot(); - assert_eq!( - second.enter_parallel(Arc::clone(&hub)), - Err(ParallelAdmissionError::PeOwned { pe: 0 }) - ); - assert!(second.parallel.is_none() && second.attached.is_none()); - assert_eq!(second.chain.snapshot(), untouched); - assert_eq!( - first.enter_parallel(Arc::clone(&hub)), - Err(ParallelAdmissionError::MachineAttached) - ); - first.chain.finish(17); - hub.interrupt(0); - assert_eq!(first.chain.account().0, 17); - let pending = first.chain.snapshot(); - assert_ne!(pending.interrupt_epoch, pending.observed_interrupt_epoch); - assert_eq!(pending.quiet, stela_compiler::x86_64::chain::Quiet(0)); - drop(first); - second.enter_parallel(Arc::clone(&hub)).unwrap(); - assert!(second.attached.as_ref().unwrap().epoch > epoch); - assert_eq!(second.cpu.pc, BASE); -} - -#[test] -fn an_interrupt_borrow_survives_detach_and_reuse_without_a_raw_pointer_lease() { - use std::sync::mpsc; - let (hub, _) = hub(1); - let weak = Arc::downgrade(&hub.inboxes[0].chain); - let (attached, mut control) = Attached::new(&hub, 0, false).unwrap(); - control.initialize(11, 14, [12, 13], [0xffff, 0xfff]); - control.begin(9, 99); - let (ready_tx, ready_rx) = mpsc::channel(); - let (resume_tx, resume_rx) = mpsc::channel(); - let foreign = Arc::clone(&hub); - let reader = std::thread::spawn(move || { - let chain = &foreign.inboxes[0].chain; - ready_tx.send(()).unwrap(); - resume_rx.recv().unwrap(); - chain.notify(); - }); - ready_rx.recv().unwrap(); - drop(attached); - assert_ne!( - hub.inboxes[0].owner.load(Ordering::Acquire), - 0, - "the control owner retains the claim" - ); - drop(control); - assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), 0); - assert!( - weak.upgrade().is_some(), - "hub retains the physical allocation" - ); - let (next, mut control) = Attached::new(&hub, 0, false).unwrap(); - control.initialize(21, 24, [22, 23], [0xffff, 0xfff]); - control.begin(2, 77); - resume_tx.send(()).unwrap(); - reader.join().unwrap(); - let snapshot = control.snapshot(); - assert_eq!( - ( - control.account().budget(), - control.account().retired(), - snapshot.hits, - snapshot.linked - ), - (77, 0, 0, 0) - ); - assert_eq!( - (snapshot.block, snapshot.table, snapshot.contexts), - (2, 21, [22, 23]) - ); - assert_ne!(snapshot.interrupt_epoch, snapshot.observed_interrupt_epoch); - assert_eq!(snapshot.quiet, stela_compiler::x86_64::chain::Quiet(0)); - assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), next.epoch); - drop(control); - drop(next); - drop(hub); - assert!( - weak.upgrade().is_none(), - "last hub/owner releases the allocation" - ); -} - -#[test] -fn a_populated_machine_keeps_its_code_as_it_adopts_a_hub_control() { - use super::super::tests::{BASE, machine}; - use stela_compiler::block::ExitKind; - let mut machine = machine(&[0x9100_0400, 0x1400_0002, 0, 0x9100_0400, 0x17ff_fffc]); - let direct = |next_pc| super::super::NativeExit::Exit { - next_pc, - kind: ExitKind::Direct as u64, - }; - machine.host.exits = vec![direct(BASE + 12), direct(BASE), direct(BASE + 12)]; - machine.step().unwrap(); - machine.step().unwrap(); - machine.step().unwrap(); - assert_eq!(machine.statistics.links, 2); - let (blocks, installed) = (machine.code.blocks.len(), machine.host.installed.len()); - let contexts = machine.chain.contexts(); - let old_address = machine.chain.address(); - let old_storage = machine.chain.weak_storage(); - let (hub, _) = hub(1); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - assert_ne!(machine.chain.address(), old_address); - assert!(old_storage.upgrade().is_none()); - // Code finds the control through the frame, which the next entry sets. - assert_eq!(machine.chain.contexts(), contexts); - assert_eq!( - (machine.code.blocks.len(), machine.host.installed.len()), - (blocks, installed) - ); - assert_eq!( - machine.anchors()[stela_compiler::Anchor::Control], - machine.chain.address() - ); -} - -#[test] -fn repeated_owner_reuse_keeps_remote_epoch_writes_disjoint() { - use core::sync::atomic::AtomicBool; - use std::sync::Barrier; - let (hub, _) = hub(1); - let started = Arc::new(Barrier::new(2)); - let done = Arc::new(AtomicBool::new(false)); - let foreign = Arc::clone(&hub); - let worker_started = Arc::clone(&started); - let worker_done = Arc::clone(&done); - let interrupt = std::thread::spawn(move || { - worker_started.wait(); - while !worker_done.load(Ordering::Acquire) { - foreign.interrupt(0); - } - }); - started.wait(); - let mut last = 0; - for index in 0..1000 { - let (attached, mut control) = Attached::new(&hub, 0, false).unwrap(); - assert!(attached.epoch > last); - last = attached.epoch; - control.initialize(index, index + 3, [index + 1, index + 2], [0xffff, 0xfff]); - control.begin(index as usize, 31); - let state = control.snapshot(); - assert_eq!( - (state.block, state.table, state.itlb, state.contexts), - (index, index, index + 3, [index + 1, index + 2]) - ); - drop(attached); - drop(control); - } - done.store(true, Ordering::Release); - interrupt.join().unwrap(); - assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), 0); -} - -#[test] -fn parallel_pes_refuse_independent_idle_leaps() { - use super::super::tests::{BASE, board}; - use {crate::machine::engine::NoDevices, stela_contracts::identity::Identity}; - - let identities = (0..2) - .map(|pe| Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000 | pe << 8, - clock: None, - caches: None, - }) - .collect::>(); - let mut home = board(&[], NoDevices, identities.clone()); - let prepared = board(&[], NoDevices, identities); - let mut worker = home - .worker_profile() - .start(prepared.cpu, prepared.host, prepared.devices, 1) - .unwrap(); - assert!(Arc::ptr_eq(&home.admit_table, &worker.admit_table)); - home.set_idle_skip(true).unwrap(); - let (hub, _) = hub(2); - home.enter_parallel(Arc::clone(&hub)).unwrap(); - worker - .start_parallel(hub, home.cpu.core_locks.clone(), BASE) - .unwrap(); - for machine in [&mut home, &mut worker] { - assert!(!machine.idle_skip); - assert_eq!( - machine.set_idle_skip(true), - Err("idle skipping requires all PEs to share one scheduler") - ); - assert!(!machine.idle_skip); - machine.set_idle_skip(false).unwrap(); - machine.host.now = 1000; - } - assert_eq!(home.now(), worker.now()); - home.host.now = 2000; - worker.host.now = 2000; - assert_eq!(home.now(), worker.now()); -} - -#[test] -fn edited_cpu_profile_keeps_its_own_admission_policy() { - use super::super::tests::machine_on; - use crate::machine::{identification, registers::encodings::ID_AA64ISAR1_EL1}; - use stela_contracts::Chip; - - const SMMLA: u32 = 0x4e9b_a781; - let chip = Chip::AppleM2; - let mut home = machine_on(chip, &[]); - assert_eq!(home.admit_table.admit(SMMLA), SMMLA); - home.profile.fixed = - identification::derive(chip, home.target, true, identification::Speculation::NONE); - for (register, value) in &mut home.profile.fixed { - if *register == ID_AA64ISAR1_EL1 { - *value &= !(0xf << 52); - } - } - let worker = home.worker_profile(); - assert!(!Arc::ptr_eq(&home.admit_table, &worker.admit_table)); - assert_eq!(worker.admit_table.admit(SMMLA), 0); -} - -#[test] -fn source_observation_uses_only_the_attached_owner_and_remains_stale() { - use super::super::tests::{BASE, board}; - use crate::machine::engine::NoDevices; - use stela_contracts::identity::Identity; - - let identities = (0..2) - .map(|pe| Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000 | pe << 8, - clock: None, - caches: None, - }) - .collect::>(); - let mut home = board(&[], NoDevices, identities.clone()); - let prepared = board(&[], NoDevices, identities); - let mut worker = Machine::new_at( - prepared.cpu, - prepared.host, - prepared.devices, - prepared.profile, - prepared.target, - 1, - ) - .unwrap(); - let (hub, kicks) = hub(2); - home.enter_parallel(Arc::clone(&hub)).unwrap(); - worker - .start_parallel(Arc::clone(&hub), home.cpu.core_locks.clone(), BASE) - .unwrap(); - let reads = worker.host.counter_reads; - worker.observe_parallel_source(SourcePhase::SliceEnter); - assert_eq!( - worker.host.counter_reads, reads, - "disabled path reads no counter" - ); - assert_eq!(hub.source_observation(1), None, "default off"); - hub.set_source_observations(true); - worker.cpu.pc = BASE + 4; - worker.cpu.state.sp = 0x8000; - worker.cpu.state.x[29] = 0x8010; - worker.cpu.state.x[30] = BASE + 8; - worker.cpu.pstate.daif = 3; - worker.host.now = 1000; - let before = worker.cpu.state.clone(); - let counts = worker.counts(); - let sent = kicks.load(Ordering::Relaxed); - worker.observe_parallel_source(SourcePhase::BroadcastEnter); - let first = hub.source_observation(1).unwrap(); - assert_eq!(first.sequence, 2); - assert_eq!( - first.source, - MaterializedSource { - host_counter: 1000, - phase: SourcePhase::BroadcastEnter, - pc: BASE + 4, - sp: 0x8000, - fp: 0x8010, - lr: BASE + 8, - el: 2, - daif: 3, - } - ); - assert_eq!(worker.cpu.state, before); - assert_eq!(worker.counts(), counts); - assert_eq!(kicks.load(Ordering::Relaxed), sent); - assert_eq!(hub.source_observation(0), None); - assert_eq!(hub.source_observation(2), None); - assert_eq!(hub.source_observation(usize::MAX), None); - - // A caller cannot select another slot: attachment is private and - // publication refuses a mismatched current-PE image. - worker.current = 0; - worker.observe_parallel_source(SourcePhase::SliceExit); - assert_eq!(hub.source_observation(0), None); - assert_eq!(hub.source_observation(1), Some(first)); - worker.current = 1; - worker.cpu.pc = BASE + 16; - worker.host.now = 2000; - assert_eq!( - hub.source_observation(1), - Some(first), - "no implicit refresh" - ); - worker.observe_parallel_source(SourcePhase::SliceExit); - let second = hub.source_observation(1).unwrap(); - assert_eq!(second.sequence, 4); - assert_eq!(second.source.pc, BASE + 16); - assert_eq!(second.source.host_counter, 2000); - hub.set_source_observations(false); - worker.observe_parallel_source(SourcePhase::ParkEnter); - assert_eq!(hub.source_observation(1), None); - hub.set_source_observations(true); - assert_eq!(hub.source_observation(1), Some(second)); - - // Real boundary hooks publish once at entry and once on return, not - // on each wait-loop spin. A PE that stops reading mail needs not - // acknowledge what was posted to it. - home.post(Maintenance::Code(None)); - home.send_outgoing(); - hub.set_live(1, false); - home.complete_maintenance().unwrap(); - let broadcast = hub.source_observation(0).unwrap(); - assert_eq!(broadcast.sequence, 4); - assert_eq!(broadcast.source.phase, SourcePhase::BroadcastExit); - home.device_transfer(0).unwrap(); - let dma = hub.source_observation(0).unwrap(); - assert_eq!(dma.sequence, 8); - assert_eq!(dma.source.phase, SourcePhase::DeviceAdvanceExit); - assert_eq!(hub.source_observation(1), Some(second)); - - drop(worker); - assert_eq!(hub.source_observation(1), None, "detached owner"); - let (_new_owner, _control) = Attached::new(&hub, 1, false).unwrap(); - assert_eq!(hub.source_observation(1), None, "replacement has no copy"); -} - -/// A machine of PE 0 of two in `hub`, running `words`. -fn first_of_two( - words: &[u32], - hub: &Arc, -) -> Machine { - use stela_contracts::identity::Identity; - let identities = (0..2) - .map(|pe| Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000 | pe << 8, - clock: None, - caches: None, - }) - .collect::>(); - let mut machine = super::super::tests::board(words, crate::machine::NoDevices, identities); - machine.enter_parallel(Arc::clone(hub)).unwrap(); - machine -} - -#[test] -fn broadcast_profile_counts_posts_and_completion_waits_for_the_attached_owner() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[0xd503_201f], &hub); - // Unobserved, a post reads no clock; the completion reads its two. - let reads = machine.host.counter_reads; - machine.post(Maintenance::Code(None)); - assert_eq!(machine.host.counter_reads, reads); - machine.send_outgoing(); - hub.set_live(1, false); - machine.complete_maintenance().unwrap(); - assert_eq!(machine.host.counter_reads - reads, 2); - assert!(hub.broadcast_profile(0).is_none()); - - hub.set_source_observations(true); - hub.set_live(1, true); - let reads = machine.host.counter_reads; - machine.post(Maintenance::Code(Some(0x4000))); - machine.post(Maintenance::Code(Some(0x4000))); - machine.send_outgoing(); - hub.set_live(1, false); - machine.complete_maintenance().unwrap(); - // A clock for the posts, and the completion's two and its two source - // observations; accounting adds no native notification. - assert_eq!(machine.host.counter_reads - reads, 5); - let observed = hub.broadcast_profile(0).unwrap(); - let code = observed.kinds[BroadcastKind::Code.index()]; - assert_eq!( - (code.started, code.completed, code.recipients, code.polls), - (2, 2, 2, 0) - ); - let completion = observed.kinds[BroadcastKind::Completion.index()]; - assert_eq!( - ( - completion.started, - completion.completed, - completion.recipients - ), - (1, 1, 1) - ); - assert_eq!((observed.active, observed.dropped_updates), (None, false)); - // PE 1 posted nothing. - let idle = hub.broadcast_profile(1).unwrap(); - assert!(idle.kinds.iter().all(|counts| counts.started == 0)); - - // With nothing posted, a completion waits for nothing. - let reads = machine.host.counter_reads; - machine.complete_maintenance().unwrap(); - assert_eq!(machine.host.counter_reads, reads); - - hub.set_live(1, true); - let attached = machine.attached.take().unwrap(); - machine.post(Maintenance::Code(None)); - machine.send_outgoing(); - hub.set_live(1, false); - machine.complete_maintenance().unwrap(); - assert_eq!(hub.broadcast_profile(0), Some(observed)); - machine.attached = Some(attached); -} - -/// A PE waiting for others' acknowledgements answers the host at each turn -/// of the wait: a processor that waits on this one, as a TLB shootdown -/// does, gets its answer, so the two waits cannot deadlock. -#[test] -fn a_completion_wait_answers_the_host_each_turn() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.send_outgoing(); - let other = Arc::clone(&hub); - // PE 1 acknowledges only once this one has relaxed three times. - machine.host.on_relax = Some(Box::new(move |turns| { - if turns == 3 { - let mail = other.take(1).expect("posted mail"); - other.acknowledge(1, mail.serial); - } - })); - machine.complete_maintenance().unwrap(); - assert_eq!(machine.host.relaxes, 3); -} - -/// A wait for a PE that does not apply posted maintenance past its bound -/// is reported once, naming that PE and where it is, and goes on: it ends -/// normally once the PE applies the maintenance. -#[test] -fn a_completion_wait_past_its_bound_is_reported_once_and_goes_on() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.send_outgoing(); - let limit = machine.profile.counter_frequency / super::MAINTENANCE_WAIT_DIVISOR; - // Each turn reads the counter a step later: the bound passes at about - // the eighth turn, and PE 1 applies at the 40th. - machine.host.counter_step = limit / 8; - let other = Arc::clone(&hub); - machine.host.on_relax = Some(Box::new(move |turns| { - if turns == 40 { - let mail = other.take(1).expect("posted mail"); - other.acknowledge(1, mail.serial); - } - })); - let degraded = machine.statistics.degraded; - machine.complete_maintenance().unwrap(); - assert_eq!(machine.host.relaxes, 40, "waited until PE 1 applied"); - assert!(machine.posted.is_empty()); - assert_eq!(machine.statistics.degraded, degraded + 1); - let reports = machine.take_unmodeled(); - assert_eq!(reports.len(), 1, "once: {reports:?}"); - let RequirementKind::MaintenanceOverrun { - pe, - serial, - unapplied, - state, - ticks, - } = reports[0].kind - else { - panic!("expected a maintenance overrun, got {:?}", reports[0].kind); - }; - assert_eq!( - (pe, serial, unapplied, state), - (1, 1, 1, super::super::PeState::Running) - ); - assert!((limit..2 * limit).contains(&ticks), "{ticks} of {limit}"); - assert!( - reports[0] - .to_string() - .contains("maintenance overrun: PE 1 (running)") - ); - - // A wait within its bound reports nothing. - machine.host.on_relax = None; - machine.host.counter_step = 0; - machine.post(Maintenance::Code(Some(0x8000))); - machine.send_outgoing(); - let mail = hub.take(1).expect("posted mail"); - hub.acknowledge(1, mail.serial); - machine.complete_maintenance().unwrap(); - assert!(machine.take_unmodeled().is_empty()); -} - -#[test] -fn maintenance_waits_for_the_dsb_and_reaches_a_pe_in_one_piece_of_mail() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.post(Maintenance::Code(Some(0x8000))); - assert!(hub.take(1).is_none()); - - machine.send_outgoing(); - hub.set_live(1, false); - machine.complete_maintenance().unwrap(); - let mail = hub.take(1).unwrap(); - assert_eq!(mail.maintenance.len(), 2); - assert_eq!(mail.serial, 1); -} - -#[test] -fn a_broadcast_passes_by_a_pe_outside_its_run() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - // PE 0 runs a block. - assert!(hub.enter_active(0)); - let posted = hub.broadcast(1, &[Maintenance::Code(None)]); - assert!(!hub.applied(&mut posted.clone())); - machine.outside_run(|_| assert!(hub.applied(&mut posted.clone()))); - assert!(!hub.applied(&mut posted.clone())); - hub.leave_active(0); -} - -#[test] -fn a_full_list_of_maintenance_goes_out_without_a_dsb() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - for page in 0..OUTGOING as u64 { - machine.post(Maintenance::Code(Some(page << 14))); - } - assert_eq!(hub.take(1).unwrap().maintenance.len(), OUTGOING); -} - -#[test] -fn a_page_invalidation_the_pe_has_yet_to_read_covers_the_same_page_again() { - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.post(Maintenance::Code(Some(0x4000))); - machine.post(Maintenance::Code(Some(0x8000))); - machine.post(Maintenance::Code(None)); - machine.post(Maintenance::Code(Some(0xc000))); - machine.send_outgoing(); - let mail = hub.take(1).unwrap(); - let pages: Vec<_> = mail - .maintenance - .iter() - .map(|maintenance| match maintenance { - Maintenance::Code(page) => *page, - _ => unreachable!(), - }) - .collect(); - assert_eq!(pages, [Some(0x4000), Some(0x8000), None]); - // The PE's acknowledgment of this mail is the one waited for. - assert_eq!((mail.serial, machine.posted.as_slice()), (1, &[(1, 1)][..])); -} - -/// A PE that reads no mail for a long time, asleep or powered down, holds -/// at most [`MAIL_TLB_SCOPES`] TLB scopes and [`MAIL_SCOPES`] code pages: -/// past them, scopes that merge with none of the last kept ones and code -/// pages make one invalidation of everything of that kind. -#[test] -fn mail_for_a_pe_that_does_not_read_it_stays_bounded() { - use crate::machine::system::TlbiKind::ASID; - let (hub, _) = hub(2); - for page in 0..10_000u64 { - hub.broadcast( - 0, - &[ - tlbi(ASID, (page % 200) << 48), - Maintenance::Code(Some(page << 14)), - ], - ); - } - let mail = hub.take(1).unwrap(); - let count = - |kind: fn(&Maintenance) -> bool| mail.maintenance.iter().filter(|m| kind(m)).count(); - assert!( - mail.maintenance.len() <= MAIL_TLB_SCOPES + MAIL_SCOPES + 2, - "{}", - mail.maintenance.len() - ); - assert_eq!(count(|m| matches!(m, Maintenance::TlbAll)), 1); - assert_eq!(count(|m| matches!(m, Maintenance::Code(None))), 1); - // What follows a whole invalidation is covered by it. - assert_eq!(count(|m| matches!(m, Maintenance::Tlb(_))), 0); - assert_eq!(count(|m| matches!(m, Maintenance::Code(Some(_)))), 0); -} - -/// A run of TLBIs by page, as XNU's and SPTM's loops send them, merges -/// into one range a sleeping PE applies at once: no invalidation of -/// everything, and the kernel's contexts outlive it. -/// A PE counts how long its TLB mail waited, from the first post it had -/// not read to the read, and how long its native run, when one was going, -/// took of that to return; then the apply. Later posts of the same mail -/// keep the first's time. -#[test] -fn a_pe_times_its_tlb_mail_from_the_first_post_to_the_read() { - use super::super::reports::MailWait; - use crate::machine::system::TlbiKind::VAA; - let clock = Arc::new(AtomicUsize::new(1)); - let hub = Hub::new(2, Ticks(Arc::clone(&clock))); - for pe in 0..2 { - hub.set_live(pe, true); - } - // NOP. - let mut machine = first_of_two(&[0xd503_201f], &hub); - let waits = |machine: &Machine<_, _>| machine.statistics.mail_waits; - // Mail read between runs: all of its wait is the engine's. - hub.broadcast(1, &[tlbi(VAA, 0x10_0000)]); - hub.broadcast(1, &[tlbi(VAA, 0x10_0001)]); - machine.read_mail().unwrap(); - let counted = waits(&machine); - assert_eq!(counted[MailWait::Count as usize], 1); - assert!(counted[MailWait::Latency as usize] >= 2); - assert_eq!(counted[MailWait::Native as usize], 0); - assert_eq!( - counted[MailWait::Exit as usize], - counted[MailWait::Latency as usize] - ); - assert!(counted[MailWait::Apply as usize] >= 1); - assert_eq!( - counted[MailWait::Longest as usize], - counted[MailWait::Latency as usize] - ); - // Mail posted while a native run goes on: its return counts apart. - let pc = machine.cpu.pc; - let Ok(super::super::Fetched::Block(index)) = machine.fetch_block(pc, false) else { - panic!("a block"); - }; - hub.broadcast(1, &[tlbi(VAA, 0x20_0000)]); - machine.host.exits = vec![super::super::NativeExit::Exit { - next_pc: pc + 4, - kind: stela_compiler::block::ExitKind::Fallthrough as u64, - }]; - let budget = machine.chain_budget(); - machine.execute(index, budget).unwrap(); - machine.read_mail().unwrap(); - let after = waits(&machine); - assert_eq!(after[MailWait::Count as usize], 2); - let native = after[MailWait::Native as usize]; - assert!(native >= 1); - assert!(native < after[MailWait::Latency as usize] - counted[MailWait::Latency as usize]); - // Nothing waits after the read. - machine.read_mail().unwrap(); - assert_eq!(waits(&machine), after); -} - -#[test] -fn a_run_of_tlbis_by_page_merges_into_one_range() { - use crate::machine::system::TlbiKind::{VA, VAA}; - let (hub, _) = hub(2); - for page in 0..10_000u64 { - hub.broadcast(0, &[tlbi(VAA, 0x10_0000 + page)]); - } - // Pages of one ASID in the upper half, one apart: another range. - for page in 0..100u64 { - hub.broadcast(0, &[tlbi(VA, 7 << 48 | (0xfff_ff00_0000 + 2 * page))]); - } - let mail = hub.take(1).unwrap(); - assert_eq!(mail.merged, 10_000 - 1 + 100 - 1); - let [Maintenance::Tlb(lower), Maintenance::Tlb(upper)] = mail.maintenance[..] else { - panic!("two ranges: {:?}", mail.maintenance); - }; - assert_eq!( - lower.span(), - Some((0x1_0000_0000, 0x1_0000_0000 + 9_999 * 0x1000)) - ); - assert_eq!(lower.named_asid(), None); - let upper_first = mmu::tlbi::canonical(0xfff_ff00_0000 << 12); - assert_eq!( - upper.span(), - Some((upper_first, upper_first + 198 * 0x1000)) - ); - assert_eq!(upper.named_asid(), Some(7)); -} - -/// Pages of two processes at the same VAs (the shared cache's) stay two -/// ranges, one per ASID, rather than one of every ASID that would drop -/// those VAs in every process's lookup contexts; a page of every ASID -/// merges with neither. A full mailbox may merge them all the same. -#[test] -fn mail_merges_tlbis_of_different_asids_only_when_full() { - use crate::machine::system::TlbiKind::{VA, VAA}; - let (first, _) = hub(2); - for page in 0..8u64 { - for asid in [7u64, 8] { - first.broadcast(0, &[tlbi(VA, asid << 48 | (0x18_0000 + page))]); - } - } - first.broadcast(0, &[tlbi(VAA, 0x18_0004)]); - let mail = first.take(1).unwrap(); - let scopes: Vec<_> = mail - .maintenance - .iter() - .map(|posted| match posted { - Maintenance::Tlb(scope) => (scope.named_asid(), scope.span()), - other => panic!("{other:?}"), - }) - .collect(); - let range = Some((0x1_8000_0000, 0x1_8000_0000 + 7 * 0x1000)); - assert_eq!( - scopes, - [ - (Some(7), range), - (Some(8), range), - (None, Some((0x1_8000_4000, 0x1_8000_4000))) - ] - ); - assert_eq!(mail.merged, 2 * 7); - // Past the kept scopes, any of the last ones takes the next. - let (hub, _) = hub(2); - for page in 0..super::MAIL_TLB_SCOPES as u64 { - hub.broadcast(0, &[tlbi(VAA, 0x10_0000 + 32 * page)]); - } - hub.broadcast(0, &[tlbi(VA, 7 << 48 | 0x10_0001)]); - let mail = hub.take(1).unwrap(); - assert_eq!(mail.maintenance.len(), super::MAIL_TLB_SCOPES); -} - -/// Whatever TLBIs a PE's mail keeps or merges, every entry one of them -/// removes, the kept scopes remove: by [`tlbi::Scope::covers`], and by -/// what the PE's ITLB and shadow apply ([`tlbi::Scope::everywhere`], -/// [`tlbi::Scope::reach`], [`tlbi::Scope::named_asid`]). -#[test] -fn merged_mail_removes_every_entry_its_tlbis_remove() { - use crate::machine::system::TlbiKind::{RVA, RVAA, VA, VAA}; - let mut seed = 0x1234_5678_9abc_def0u64; - let mut next = move || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - seed - }; - for round in 0..40 { - let mut mail = Mail::default(); - // Half the rounds for a PE with global pages around the lower - // half's third place, which merges go around. - let globals = (round / 3 % 2 == 1).then_some(Globals { - first: 2 << 36, - last: (3 << 36) - 1, - leaf: 0x4000, - }); - let mut sent = Vec::new(); - let count = [20, 300, 2000][round % 3]; - for _ in 0..count { - let draw = next(); - let asid = (draw >> 8) % 4; - // Pages of four places in each half, 4 KiB apart. - let place = (draw >> 16) % 4; - let upper = if draw >> 20 & 1 != 0 { - 0xf_ffff_0000_0000 - } else { - 0 - }; - let page = upper | place << 24 | ((draw >> 24) % 64); - let kind = [VA, VAA, RVA, RVAA][(draw % 4) as usize]; - let operand = match kind { - // TG 4 KiB, SCALE 0, NUM 1: four pages from BaseADDR. - RVA | RVAA => { - let base = (canonical_page(page) >> 12) & ((1 << 37) - 1); - asid << 48 | 1 << 46 | 1 << 39 | base - } - _ => asid << 48 | page & ((1 << 44) - 1), - }; - let Maintenance::Tlb(scope) = tlbi(kind, operand) else { - unreachable!() - }; - sent.push(scope); - mail.keep(Maintenance::Tlb(scope), globals); - } - let all = mail - .maintenance - .iter() - .any(|kept| matches!(kept, Maintenance::TlbAll)); - let kept: Vec = mail - .maintenance - .iter() - .filter_map(|kept| match kept { - Maintenance::Tlb(scope) => Some(*scope), - _ => None, - }) - .collect(); - assert!(kept.len() <= MAIL_TLB_SCOPES); - assert_eq!(kept.len() + mail.merged as usize, sent.len(), "{all}"); - // Entries at and around every sent page, of every size and ASID. - for scope in &sent { - let (first, last) = scope.span().unwrap(); - for address in [first, last, first.wrapping_sub(0x1000), last + 0x1000] { - for (size_bits, granule_bits, level) in [(12, 12, 3), (14, 14, 3), (21, 12, 2)] { - for asid in [None, Some(0), Some(1), Some(3)] { - let entry = tlbi::Entry { - regime: mmu::Regime::El10, - vmid: None, - asid, - address: address & ((1 << 56) - 1), - size_bits, - granule_bits, - level, - stage1: true, - stage2: false, - table: false, - }; - if !scope.covers(&entry) { - continue; - } - assert!( - all || kept.iter().any(|kept| kept.covers(&entry)), - "{scope:?} removes {entry:x?}, no kept scope does" - ); - } - } - } - // What the ITLB and shadow apply: a span holding the sent one, - // of its ASID or of every ASID. - let holds = |kept: &tlbi::Scope| { - let (kept_first, kept_last) = kept.span().unwrap(); - kept_first <= first - && last <= kept_last - && kept - .named_asid() - .is_none_or(|asid| scope.named_asid() == Some(asid)) - }; - assert!(all || kept.iter().any(holds), "{scope:?}"); - } - } -} - -/// The canonical VA of 4 KiB page number `page`. -fn canonical_page(page: u64) -> u64 { - mmu::tlbi::canonical(page << 12) -} - -/// A process's TLBIs by page below and above a PE's global pages (its -/// image and stacks, its heaps, around the shared cache) never merge into -/// one range across them while a merge on one side can take them, full -/// mailbox or not: the PE's shared pages' entries outlive them. Every sent -/// scope is still held by a kept one of its ASID, and the mailbox keeps no -/// more scopes than before. -#[test] -fn a_mailbox_merges_no_scope_across_the_pes_global_pages() { - use crate::machine::system::TlbiKind::VA; - const GLOBALS: Globals = Globals { - first: 0x1_8000_0000, - last: 0x2_7fff_ffff, - leaf: 0x4000, - }; - const BELOW: u64 = 0x1_0000_0000; - const ABOVE: u64 = 0x6_0000_0000; - let mut mail = Mail::default(); - let mut sent = Vec::new(); - // Bursts above, each followed by one page below: the last kept scopes - // are all above when the page below comes. - for n in 0..4 * MAIL_TLB_SCOPES as u64 { - let va = if n % 20 == 19 { - BELOW + n * 0x10_0000 - } else { - ABOVE + n * 0x10_0000 - }; - let Maintenance::Tlb(scope) = tlbi(VA, 9 << 48 | va >> 12) else { - unreachable!() - }; - sent.push(scope); - mail.keep(Maintenance::Tlb(scope), Some(GLOBALS)); - } - let kept: Vec = mail - .maintenance - .iter() - .map(|kept| match kept { - Maintenance::Tlb(scope) => *scope, - other => panic!("{other:?}"), - }) - .collect(); - assert_eq!(kept.len(), MAIL_TLB_SCOPES); - assert_eq!(kept.len() + mail.merged as usize, sent.len()); - for scope in &kept { - let (first, last) = scope.span().unwrap(); - assert!(last < GLOBALS.first || first > GLOBALS.last, "{scope:x?}"); - assert_eq!(scope.named_asid(), Some(9)); - } - for scope in &sent { - let (first, last) = scope.span().unwrap(); - assert!( - kept.iter().any(|kept| { - let (kept_first, kept_last) = kept.span().unwrap(); - kept_first <= first && last <= kept_last - }), - "{scope:x?}" - ); - } - // Without global pages, or when every merge bridges them, the - // narrowest merge of the last kept scopes takes the page, as before. - let mut mail = Mail::default(); - for n in 0..MAIL_TLB_SCOPES as u64 { - mail.keep( - tlbi(VA, 9 << 48 | (ABOVE + n * 0x10_0000) >> 12), - Some(GLOBALS), - ); - } - mail.keep(tlbi(VA, 9 << 48 | BELOW >> 12), Some(GLOBALS)); - assert_eq!(mail.maintenance.len(), MAIL_TLB_SCOPES); - assert_eq!(mail.merged, 1); - // Until full, merges reach at most three granules across, global pages - // or not, and runs of pages among global pages merge as before. - let mut mail = Mail::default(); - for va in [0x1_7fff_f000, 0x1_8000_4000, 0x1_8000_5000, 0x1_8000_8000] { - mail.keep(tlbi(VA, 9 << 48 | va >> 12), Some(GLOBALS)); - } - assert_eq!((mail.maintenance.len(), mail.merged), (1, 3)); -} - -/// A merge bridges a PE's global pages at the granule of the smallest -/// global leaf it took: of 4 KiB leaves, the merge of TLBIs of the pages at -/// 0x1000 and 0x3000 takes in the global page at 0x2000, which neither TLBI -/// reaches; of 16 KiB leaves, both TLBIs reach the leaf that holds all -/// three, and the merge adds nothing. -#[test] -fn a_merge_bridges_global_pages_at_the_pes_smallest_global_leaf() { - let span = GlobalSpan::new(); - assert!(span.now().is_none()); - assert!(span.widen(0, 0x3fff)); - let large = span.now(); - assert_eq!(large.map(|globals| globals.leaf), Some(0x4000)); - for (held, new) in [(0x1000, 0x3000), (0x3000, 0x1000), (0, 0x4000)] { - assert!( - !bridges(large, (held, held), (new, new)), - "{held:#x} {new:#x}" - ); - } - // A 16 KiB global leaf between the two TLBIs' leaves is a bridge. - assert!(!bridges(large, (0, 0), (0x8000, 0x8000))); - assert!(span.widen(0x4000, 0x7fff)); - assert!(bridges(span.now(), (0, 0), (0x8000, 0x8000))); - // A 4 KiB leaf narrows the granule: the page between two pages of one - // 16 KiB granule is a bridge, and pages side by side still are not. - assert!(!span.widen(0x2000, 0x2fff)); - let small = span.now(); - assert_eq!(small.map(|globals| globals.leaf), Some(0x1000)); - assert!(bridges(small, (0x1000, 0x1000), (0x3000, 0x3000))); - assert!(bridges(small, (0x3000, 0x3000), (0x1000, 0x1000))); - assert!(!bridges(small, (0x1000, 0x1000), (0x2000, 0x2000))); - assert!(!bridges(small, (0x1000, 0x1ff8), (0x2000, 0x2008))); - assert!(!bridges(None, (0x1000, 0x1000), (0x3000, 0x3000))); -} - -/// Another PE's TLBI by VA or range reaches this PE through its mail and -/// drops the ITLB entries it covers alone: a global page's for any ASID, -/// a page of an ASID for that ASID or every ASID. A page remapped behind -/// such a TLBI translates anew at the PE's next fetch. -#[test] -fn a_tlbi_another_pe_broadcasts_drops_the_pages_it_covers_alone() { - use super::super::tests::{ - BASE, CODE_ASID, SPACES_TABLES, asid_code_pages, page_descriptor, va_operand, write_entry, - }; - use crate::machine::system::TlbiKind::{RVA, VA, VAA}; - const RET: u32 = 0xd65f_03c0; - const MOVZ: u32 = 0xd280_0020; // movz x0, #1 - const PAGES: u64 = 16; - let (hub, _) = hub(2); - let mut machine = first_of_two(&[RET], &hub); - asid_code_pages(&mut machine, PAGES as usize, 8); - let page = |n: u64| BASE + n * 0x1000; - let fetch_all = |machine: &mut Machine<_, _>| { - for n in 0..PAGES { - assert!(matches!( - machine.fetch_block(page(n), false), - Ok(super::super::Fetched::Block(_)) - )); - } - }; - let held = |machine: &Machine<_, _>| -> Vec { - (0..PAGES) - .filter(|&n| machine.current_key(page(n)).is_some()) - .collect() - }; - let other = CODE_ASID + 1; - // TG 4 KiB, SCALE 0, NUM 1: four pages. - let four = |asid, va| va_operand(asid, va) | 1 << 46 | 1 << 39; - let cases: [(_, u64, &[u64]); 7] = [ - (VA, va_operand(other, page(3)), &[3]), - (VA, va_operand(other, page(9)), &[]), - (VA, va_operand(CODE_ASID, page(10)), &[10]), - (VAA, va_operand(0, page(11)), &[11]), - (RVA, four(other, page(4)), &[4, 5, 6, 7]), - (RVA, four(other, page(12)), &[]), - (RVA, four(CODE_ASID, page(12)), &[12, 13, 14, 15]), - ]; - for (kind, operand, gone) in cases { - fetch_all(&mut machine); - assert_eq!(held(&machine), (0..PAGES).collect::>()); - hub.broadcast(1, &[tlbi(kind, operand)]); - machine.read_mail().unwrap(); - let kept: Vec = (0..PAGES).filter(|n| !gone.contains(n)).collect(); - assert_eq!(held(&machine), kept, "{kind:?} {operand:#x}"); - } - machine.host.ram[0x1000..0x1004].copy_from_slice(&MOVZ.to_le_bytes()); - machine.host.ram[0x1004..0x1008].copy_from_slice(&RET.to_le_bytes()); - fetch_all(&mut machine); - let [_, _, l3] = SPACES_TABLES[0]; - write_entry( - &mut machine, - l3 + 3 * 8, - page_descriptor(BASE + 0x1000, false), - ); - hub.broadcast(1, &[tlbi(VA, va_operand(other, page(3)))]); - machine.read_mail().unwrap(); - let Ok(super::super::Fetched::Block(block)) = machine.fetch_block(page(3), false) else { - panic!("a block"); - }; - assert_eq!(machine.code.blocks[block].physical, BASE + 0x1000); -} - -/// Counter benchmark: a PE runs a loop over global pages (a shared cache's) -/// while another PE's process sends TLBIs by page of its own pages below and -/// above them, past what the first PE's mailbox keeps: the PE reads them at -/// each round's start. No merge of the mailbox reaches across the PE's -/// global pages, so no round drops, refills or fills one, or exits for one. -/// (`cargo test -p stela-engine --lib itlb_bench -- --nocapture` prints the -/// counts.) -#[test] -fn itlb_bench_a_full_mailbox_leaves_a_pes_shared_pages() { - use super::super::tests::{BASE, asid_code_pages, dispatched, va_operand}; - use super::super::{FetchPath, ItlbSource}; - use crate::machine::system::TlbiKind::VA; - const RET: u32 = 0xd65f_03c0; - const PAGES: u64 = 64; - const ROUNDS: u64 = 20; - const BELOW: u64 = 0x1_0000_0000; - const ABOVE: u64 = 0x40_0000_0000; - let (hub, _) = hub(2); - let mut machine = first_of_two(&[RET], &hub); - asid_code_pages(&mut machine, PAGES as usize, PAGES as usize); - let page = |n: u64| BASE + n * 0x1000; - let round = |machine: &mut Machine<_, _>| { - machine.read_mail().unwrap(); - let mut exits = 0; - for n in 0..PAGES { - if !dispatched(machine, page(n)) { - exits += 1; - assert!(matches!( - machine.fetch_block(page(n), false), - Ok(super::super::Fetched::Block(_)) - )); - } - } - exits - }; - let warm = round(&mut machine); - let counts = |machine: &Machine<_, _>| { - let statistics = &machine.statistics; - [ - statistics.itlb_drops[1], - statistics.itlb_sources[ItlbSource::DropGlobal as usize], - statistics.itlb[0], - statistics.itlb_sources[ItlbSource::Refilled as usize], - statistics.fetch_paths[FetchPath::ItlbMiss as usize], - statistics.lookup_forgets[2], - ] - }; - let before = counts(&machine); - let sends = MAIL_TLB_SCOPES as u64 + 64; - let mut exits = 0; - for round_number in 0..ROUNDS { - // ASID 9's pages, 1 MiB apart: bursts above, then one below. - for n in 0..sends { - let at = (round_number * sends + n) * 0x10_0000; - let va = if n % 20 == 19 { BELOW + at } else { ABOVE + at }; - hub.broadcast(1, &[tlbi(VA, va_operand(9, va))]); - } - exits += round(&mut machine); - } - let after = counts(&machine); - let [drops, global, fills, refilled, misses, reached] = - [0, 1, 2, 3, 4, 5].map(|n| after[n] - before[n]); - eprintln!( - "ITLB bench, two PEs, {PAGES} shared pages x {ROUNDS} rounds, {sends} TLBI VALE1IS \ - of another process a round: warm-up exits {warm}; then exits {exits}, drop_tlbi \ - {drops}, drop_global {global}, ITLB fills {fills}, refilled {refilled}, fetch \ - itlb_miss {misses}, forget_va {reached}", - ); - assert_eq!([drops, global, fills, refilled, misses, exits], [0; 6]); -} - -#[test] -fn an_ic_ivau_reaches_other_pes_only_for_compiled_pages_once_per_dsb() { - const PAGE: u64 = 0x4000_0000; - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - // No PE compiled from it: the IC IVAU of each line stops here. - machine.post_code_page(PAGE); - assert!(machine.outgoing.is_empty()); - // The next lines of a page add nothing to its first one. - hub.compiling(PAGE + 0x100); - machine.post_code_page(PAGE + 0x40); - machine.post_code_page(PAGE + 0x80); - assert_eq!(machine.outgoing.len(), 1); - // A DSB ends the run: what follows may have been written since. - machine.send_outgoing(); - let mail = hub.take(1).unwrap(); - hub.acknowledge(1, mail.serial); - machine.complete_maintenance().unwrap(); - machine.post_code_page(PAGE + 0x40); - assert_eq!(machine.outgoing.len(), 1); -} - -#[test] -fn maintenance_posted_to_another_pe_completes_at_the_next_dsb() { - let (hub, _) = hub(2); - // DSB ISH. - let mut machine = first_of_two(&[0xd503_3b9f], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.send_outgoing(); - assert_eq!(machine.posted, [(1, 1)]); - // PE 1 reads its mail at its next return to the engine. - let mail = hub.take(1).unwrap(); - hub.acknowledge(1, mail.serial); - machine.host.exits = vec![super::super::NativeExit::Exit { - next_pc: super::super::tests::BASE, - kind: stela_compiler::block::ExitKind::System as u64, - }]; - machine.step().unwrap(); - assert!(machine.posted.is_empty()); - assert_eq!(machine.cpu.pc, super::super::tests::BASE + 4); - // A PE outside its run loop reads its mail before it runs again: the - // completion does not wait for it. - machine.post(Maintenance::Code(None)); - hub.set_outside(1, true); - machine.complete_maintenance().unwrap(); - assert!(machine.posted.is_empty()); - assert!(hub.take(1).is_some()); -} - -#[test] -fn notification_after_drain_survives_native_budget_reset() { - use super::super::tests::machine; - let mut machine = machine(&[0xd503_201f]); - let (hub, _) = hub(1); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - hub.post(0, |mail| mail.event = true); - machine.read_mail().unwrap(); - let drained = machine.chain.snapshot(); - assert_eq!(drained.interrupt_epoch, drained.observed_interrupt_epoch); - assert_eq!( - drained.quiet, - stela_compiler::x86_64::chain::Quiet::default() - ); - // This is the old lost-notification window: the owner has drained, - // then a peer posts before the owner initializes its next budget. - hub.post(0, |mail| mail.event = true); - machine.chain.begin(0, 4096); - let entered = machine.chain.snapshot(); - assert_eq!(machine.chain.account().budget(), 4096); - assert_ne!(entered.interrupt_epoch, entered.observed_interrupt_epoch); - assert_eq!(entered.observed_interrupt_epoch, drained.interrupt_epoch); - assert_eq!(entered.quiet, stela_compiler::x86_64::chain::Quiet(0)); - machine.read_mail().unwrap(); - let next = machine.chain.snapshot(); - assert_eq!(next.interrupt_epoch, next.observed_interrupt_epoch); - assert_eq!(next.quiet, stela_compiler::x86_64::chain::Quiet::default()); -} - -#[test] -fn epoch_exhaustion_is_sticky_across_drain_detach_and_reuse() { - use super::super::tests::machine; - let mut machine = machine(&[0xd503_201f]); - let (hub, _) = hub(1); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - hub.inboxes[0] - .chain - .interrupt_epoch() - .store(u64::MAX - 1, Ordering::Relaxed); - hub.post(0, |mail| mail.event = true); - machine.read_mail().unwrap(); - hub.interrupt(0); - let exhausted = machine.chain.snapshot(); - assert_eq!(exhausted.interrupt_epoch, u64::MAX); - assert_eq!(exhausted.observed_interrupt_epoch, u64::MAX - 1); - assert_eq!(exhausted.quiet, stela_compiler::x86_64::chain::Quiet(0)); - drop(machine); - let (_, mut next) = Attached::new(&hub, 0, false).unwrap(); - next.initialize(11, 14, [12, 13], [0xffff, 0xfff]); - next.acknowledge_interrupt(u64::MAX); - next.begin(0, 4096); - let reused = next.snapshot(); - assert_eq!(reused.interrupt_epoch, u64::MAX); - assert_eq!(reused.observed_interrupt_epoch, u64::MAX - 1); - assert_eq!(reused.quiet, stela_compiler::x86_64::chain::Quiet(0)); -} - -#[test] -fn mail_reaches_running_pes_and_kicks_only_a_sleeping_one() { - let (hub, kicks) = hub(3); - hub.event(0); - assert_eq!(kicks.load(Ordering::Relaxed), 0, "no PE sleeps"); - assert!(hub.take(0).is_none(), "SEV reaches the others"); - assert!(hub.take(1).is_some_and(|mail| mail.event)); - // A PE that sleeps halts only without mail, and mail kicks it. - let mut halts = 0; - hub.sleep(1, hub.lines_epoch(1), true, || halts += 1); - assert_eq!(halts, 1); - hub.sleep(2, hub.lines_epoch(2), true, || halts += 1); - assert_eq!(halts, 1, "PE 2 has mail"); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - hub.start(1, 0x8000); - assert_eq!(kicks.load(Ordering::Relaxed), 1); -} - -#[test] -fn a_broadcast_is_applied_once_every_running_pe_acknowledged_it() { - let (hub, kicks) = hub(3); - let (attached, mut control) = Attached::new(&hub, 1, false).unwrap(); - control.begin(0, 4096); - let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); - assert_eq!(posted, [(1, 1), (2, 1)]); - assert!(!hub.applied(&mut posted)); - // The running PE leaves native code at its next chained transfer. - drop(attached); - assert_eq!(control.account().budget(), 4096); - let interrupted = control.snapshot(); - assert_ne!( - interrupted.interrupt_epoch, - interrupted.observed_interrupt_epoch - ); - let mail = hub.take(1).unwrap(); - assert_eq!((mail.maintenance.len(), mail.serial), (1, 1)); - hub.acknowledge(1, mail.serial); - assert!(!hub.applied(&mut posted)); - assert_eq!(posted, [(2, 1)]); - // A PE that sleeps is neither woken nor waited for: it reads its - // mail before it runs again. - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - assert!(hub.applied(&mut posted)); - assert_eq!(kicks.load(Ordering::Relaxed), 0); - hub.inboxes[2].sleeping.store(false, Ordering::SeqCst); - assert!(hub.take(2).is_some_and(|mail| mail.serial == 1)); - // A PE that no longer reads mail holds no broadcast up. - let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); - hub.set_live(2, false); - hub.acknowledge(1, 2); - assert!(hub.applied(&mut posted)); - // Serials keep counting after a take. - assert_eq!(hub.broadcast(0, &[Maintenance::Code(None)]), [(1, 3)]); -} - -#[test] -fn a_host_call_ends_a_run_and_wakes_a_sleeping_pe() { - let (hub, kicks) = hub(2); - let (attached, control) = Attached::new(&hub, 1, false).unwrap(); - hub.call_host(1); - let interrupted = control.snapshot(); - assert_ne!( - interrupted.interrupt_epoch, - interrupted.observed_interrupt_epoch - ); - assert_eq!(kicks.load(Ordering::Relaxed), 0); - assert!(hub.take_host_call(1)); - assert!(!hub.take_host_call(1), "taken once"); - drop(attached); - // A sleep does not start over a call, and a sleeper is woken for one. - hub.call_host(1); - let mut halted = false; - hub.sleep(1, 0, true, || halted = true); - assert!(!halted); - assert!(hub.take_host_call(1)); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - hub.call_host(1); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - hub.inboxes[1].sleeping.store(false, Ordering::SeqCst); -} - -/// Host work for an idle core calls a PE that sleeps waiting for an -/// interrupt, never the one skipped and never one asleep in WFE; with none, -/// nobody is called. -#[test] -fn host_work_for_an_idle_core_calls_a_pe_that_sleeps_waiting_for_an_interrupt() { - let (hub, kicks) = hub(3); - // Nobody sleeps. - assert!(!hub.call_sleeping_server(0)); - // PE 0 sleeps serving, but is skipped; PE 2 sleeps in WFE. - hub.inboxes[0].sleeping.store(true, Ordering::SeqCst); - hub.inboxes[0].serves.store(true, Ordering::SeqCst); - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - assert!(!hub.call_sleeping_server(0)); - assert_eq!(kicks.load(Ordering::Relaxed), 0); - assert!(!hub.take_host_call(0) && !hub.take_host_call(2)); - // PE 2 now waits for an interrupt: it is called and woken. - hub.inboxes[2].serves.store(true, Ordering::SeqCst); - assert!(hub.call_sleeping_server(0)); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - assert!(!hub.take_host_call(0)); - assert!(hub.take_host_call(2), "its wait ends as for a host call"); - for pe in [0, 2] { - hub.inboxes[pe].sleeping.store(false, Ordering::SeqCst); - hub.inboxes[pe].serves.store(false, Ordering::SeqCst); - } -} - -/// A line change publishes the receiver's pins before it moves the -/// receiver's epoch, so a running receiver reads them at once; a sleeping -/// one is kicked only after the producer releases the board lock, which no -/// other PE then waits behind. -#[test] -fn a_line_notification_publishes_pins_first_and_kicks_after_the_unlock() { - #[derive(Default)] - struct Latched(Lines); - impl Devices for Latched { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, pe: usize, _: u64) -> Lines { - if pe == 1 { self.0 } else { Lines::default() } - } - fn pins(&mut self, pe: usize) -> Option { - Some(self.lines(pe, 0)) - } - } - struct ReadPins { - worker: Arc>>>, - observed: Arc>>, - } - impl Kick for ReadPins { - fn kick(&self, pe: usize) { - // The kick follows the unlock. Latched pins are lockless. - let mut worker = self.worker.lock().unwrap(); - let worker = worker.as_mut().unwrap(); - assert!(worker.board.devices.try_lock().is_ok()); - let lines = worker.lines(pe, 0); - self.observed.lock().unwrap().push(lines); - } - } - let worker = Arc::new(Mutex::new(None)); - let observed = Arc::new(Mutex::new(Vec::new())); - let hub = Hub::new( - 2, - ReadPins { - worker: Arc::clone(&worker), - observed: Arc::clone(&observed), - }, - ); - for pe in 0..2 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Latched::default(), Arc::clone(&hub)); - *worker.lock().unwrap() = Some(home.worker()); - let changes = [ - Lines { - irq: true, - fiq: false, - }, - Lines { - irq: false, - fiq: true, - }, - Lines::default(), - ]; - for lines in changes { - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - home.serve(|devices| devices.0 = lines); - } - worker.lock().unwrap().take(); - assert_eq!(*observed.lock().unwrap(), changes); -} - -/// A write of 1 requests a restart, of 2 starts PE 1 at 0x800 and of 3 -/// leaves bytes for the host; any other value sets the DMA deadline, 0 -/// clearing it. Also raises PE 1's IRQ from count `irq_at`. -#[derive(Default)] -struct Pending { - reset: Option, - dma: Option, - irq_at: Option, - starts: Vec, - service: bool, - register_calls: usize, - /// Each release of the board's lock: what its call waited and held. - released: Vec<(u64, u64)>, -} - -/// The one IMPLEMENTATION DEFINED register [`Pending`] serves. -const SERVED: Encoding = Encoding::new(3, 5, 15, 0, 1); - -impl Devices for Pending { - fn lock_released(&mut self, waited: u64, held: u64) { - self.released.push((waited, held)); - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, value: u64, _: u64) -> Result<(), DeviceError> { - match value { - 1 => { - self.reset = Some(Reset { - transition: stela_contracts::bus::Transition::Restart, - reason: "test".into(), - }) - } - 2 => self.starts.push(Start { - cpu: 1, - address: 0x800, - }), - 3 => self.service = true, - 0 => self.dma = None, - deadline => self.dma = Some(deadline), - } - Ok(()) - } - fn lines(&mut self, pe: usize, now: u64) -> Lines { - Lines { - irq: pe == 1 && self.irq_at.is_some_and(|at| now >= at), - ..Lines::default() - } - } - fn deadline(&mut self, now: u64) -> Option { - self.irq_at.filter(|&at| at > now) - } - fn take_reset(&mut self) -> Option { - self.reset.take() - } - fn take_start(&mut self) -> Option { - self.starts.pop() - } - fn dma_deadline(&self) -> Option { - self.dma - } - fn take_host_service(&mut self) -> bool { - core::mem::take(&mut self.service) - } - fn system_register( - &mut self, - _: usize, - encoding: Encoding, - _: Option, - _: u64, - ) -> Option> { - self.register_calls += 1; - (encoding == SERVED).then_some(Ok(7)) - } - fn serves_register(&self, encoding: Encoding) -> bool { - encoding == SERVED - } -} - -/// Counts its clock's reads: each board lock reads it once when taken and -/// once when released. -struct Ticks(Arc); -impl Kick for Ticks { - fn kick(&self, _pe: usize) {} - fn ticks(&self) -> u64 { - self.0.fetch_add(1, Ordering::SeqCst) as u64 - } -} - -/// Counts the host work releases of the devices' lock run -/// ([`Kick::released`]). -struct Releases(Arc); -impl Kick for Releases { - fn kick(&self, _pe: usize) {} - fn released(&self) -> bool { - self.0.fetch_add(1, Ordering::SeqCst); - false - } - fn release_due(&self) -> bool { - true - } -} - -/// The host work a release of the devices' lock leaves runs only on a PE -/// outside its run loop or asleep, where no broadcast waits for it: one -/// inside its loop, or a call that names no PE, leaves it for later, so a -/// slow host device never keeps a running PE from its mail. -#[test] -fn released_host_work_runs_only_outside_the_run_loop() { - let released = Arc::new(AtomicUsize::new(0)); - let hub = Hub::new(2, Releases(Arc::clone(&released))); - for pe in 0..2 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - released.store(0, Ordering::SeqCst); - let mut worker = home.worker(); - - // Inside its run loop: the access takes the lock and leaves the work. - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(released.load(Ordering::SeqCst), 0, "inside the run loop"); - // A call that names no PE leaves it too. - home.with(|_| ()); - assert_eq!(released.load(Ordering::SeqCst), 0, "no PE named"); - - // Outside its run loop, as a device site's access runs, it does it. - hub.set_outside(1, true); - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(released.load(Ordering::SeqCst), 1, "outside"); - hub.set_outside(1, false); - - // Asleep, as a halted PE serving the host, it does it. - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(released.load(Ordering::SeqCst), 2, "asleep"); - hub.inboxes[1].sleeping.store(false, Ordering::SeqCst); - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(released.load(Ordering::SeqCst), 2, "inside again"); -} - -/// What follows a write, [`Devices::settle_write`]: the lock, the DMA -/// under it, the call and the lock after, in that order, from one board -/// lock. -#[test] -fn a_shared_board_settles_a_write_under_one_lock() { - use super::super::{LockedMemory, Memory}; - use crate::machine::mmu::MemoryLocks; - const LOCK: MemoryLocks = [Some((0x1000, 0x1fff)), None, None, None]; - const AFTER: MemoryLocks = [Some((0x1000, 0x2fff)), None, None, None]; - #[derive(Default)] - struct Settling { - steps: Vec<&'static str>, - } - impl Devices for Settling { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - fn memory_lock(&self) -> MemoryLocks { - if self.steps.contains(&"transfer") { - AFTER - } else { - LOCK - } - } - fn transfer( - &mut self, - cpu: usize, - memory: &mut dyn Memory, - _: u64, - ) -> Result<(), DeviceError> { - assert_eq!(cpu, 1); - assert!(memory.write(0x800, &[1])); - assert!(!memory.write(0x1800, &[1]), "the lock before the DMA"); - self.steps.push("transfer"); - Ok(()) - } - } - /// RAM below 0x4000 that refuses writes the lock covers. - struct Locked(MemoryLocks); - impl Memory for Locked { - fn read(&mut self, _: u64, _: &mut [u8]) -> bool { - true - } - fn write(&mut self, physical: u64, _: &[u8]) -> bool { - !self - .0 - .into_iter() - .flatten() - .any(|(first, last)| (first..=last).contains(&physical)) - } - } - impl LockedMemory for Locked { - fn under(&mut self, lock: MemoryLocks) -> &mut dyn Memory { - self.0 = lock; - self - } - } - let reads = Arc::new(AtomicUsize::new(0)); - let hub = Hub::new(2, Ticks(Arc::clone(&reads))); - let mut worker = SharedDevices::new(Settling::default(), hub).worker(); - let before = reads.load(Ordering::SeqCst); - let settled = worker.settle_write(1, 0, &mut Locked([None; 4])); - assert_eq!(reads.load(Ordering::SeqCst) - before, 2, "one lock"); - assert!(settled.transfer.is_ok() && settled.call.is_none()); - assert_eq!((settled.lock, settled.after), (LOCK, AFTER)); - assert_eq!(worker.with(|devices| devices.steps.clone()), ["transfer"]); -} - -/// A handle counts the ticks its calls waited for the board's lock, once. -#[test] -fn a_handle_counts_the_ticks_it_waited_for_the_lock() { - let reads = Arc::new(AtomicUsize::new(0)); - let hub = Hub::new(2, Ticks(reads)); - let home = SharedDevices::new(Pending::default(), hub); - let mut worker = home.worker(); - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(worker.take_lock_wait(), 0, "uncontended"); - let board = Arc::clone(&home.board); - let held = board.devices.lock().unwrap(); - let waiter = std::thread::spawn(move || { - worker.write(1, 0, 4, 0, 0).unwrap(); - (worker.take_lock_wait(), worker.take_lock_wait()) - }); - // Bounded: the waiter blocks on the lock within five seconds. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while board.waits[Call::Access as usize].load(Ordering::Relaxed) == 0 { - assert!( - std::time::Instant::now() < deadline, - "the waiter never waited" - ); - std::thread::yield_now(); - } - drop(held); - let (waited, again) = waiter.join().unwrap(); - assert!(waited > 0); - assert_eq!(again, 0); -} - -/// Each call tells the devices, before it releases the board's lock, the -/// ticks it waited for it and held it, as the lock's own counts have them, -/// so a model can count them against what the call touched. -#[test] -fn each_call_tells_the_devices_its_lock_wait_and_hold() { - let reads = Arc::new(AtomicUsize::new(0)); - let hub = Hub::new(2, Ticks(reads)); - let home = SharedDevices::new(Pending::default(), hub); - let mut worker = home.worker(); - worker.write(1, 0, 4, 0, 0).unwrap(); - let released = |home: &SharedDevices| home.with(|d| d.released.clone()); - let access = |home: &SharedDevices| home.lock_times()[Call::Access as usize].held; - let held = access(&home); - assert!(held > 0); - assert_eq!(released(&home).last(), Some(&(0, held)), "uncontended"); - let board = Arc::clone(&home.board); - let locked = board.devices.lock().unwrap(); - let waiter = std::thread::spawn(move || { - worker.write(1, 0, 4, 0, 0).unwrap(); - worker.take_lock_wait() - }); - // Bounded: the waiter blocks on the lock within five seconds. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while board.waits[Call::Access as usize].load(Ordering::Relaxed) == 0 { - assert!( - std::time::Instant::now() < deadline, - "the waiter never waited" - ); - std::thread::yield_now(); - } - drop(locked); - let waited = waiter.join().unwrap(); - assert!(waited > 0); - let all = released(&home); - assert_eq!( - all.last(), - Some(&(waited, access(&home) - held)), - "its own wait" - ); -} - -#[test] -fn only_the_registers_the_devices_serve_reach_them() { - let (hub, _) = hub(2); - let mut worker = SharedDevices::new(Pending::default(), hub).worker(); - assert_eq!(worker.system_register(1, SERVED, None, 0), Some(Ok(7))); - let other = Encoding::new(3, 6, 15, 1, 0); - assert_eq!(worker.system_register(1, other, Some(1), 0), None); - assert!(worker.serves_register(SERVED) && !worker.serves_register(other)); - assert_eq!(worker.with(|devices| devices.register_calls), 1); -} - -/// A fast-IPI write (IPI_RR_GLOBAL_EL1) moves only device lines: the -/// step reads them again, and nothing derived from the PE's registers goes. -#[test] -fn a_fast_ipi_write_keeps_what_derives_from_the_pes_registers() { - use super::super::tests::board; - use stela_contracts::identity::Identity; - const MSR: u32 = 0xd51d_f029; // msr s3_5_c15_c0_1, x9 - let (hub, _) = hub(2); - let worker = SharedDevices::new(Pending::default(), hub).worker(); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut machine = board(&[MSR], worker, identities); - machine.native_system(); - assert!(machine.native_system.is_some()); - machine.device_lines = Some((Lines::default(), u64::MAX, machine.current)); - let pc = machine.cpu.pc; - machine.cpu.state.x[9] = 1 << 16; - machine.system_instruction(MSR).unwrap(); - assert_eq!(machine.cpu.pc, pc + 4); - assert_eq!(machine.devices.with(|devices| devices.register_calls), 1); - assert_eq!(machine.device_lines, None, "lines are read again"); - assert!(machine.native_system.is_some(), "derived state stays"); -} - -/// A board whose PEs signal each other with a word each, as Apple's fast -/// IPIs do: a write of `SERVED` sets the word of the PE its value names -/// through the PE's own handle, without the lock, unless the value has bit -/// 8 set, which takes the lock and raises it there. -#[derive(Default)] -struct Signalling { - words: Arc<[AtomicU64; 2]>, - /// Each CPU's deferred-request flag, which only native completion reads. - armed: Arc<[AtomicBool; 2]>, - signalled: u64, - register_calls: usize, - /// The SoC sleeps ([`Devices::waits_on_host`]). - asleep: bool, -} - -struct SignalWords { - words: Arc<[AtomicU64; 2]>, - pe: usize, -} - -impl LocalRegisters for SignalWords { - fn register(&self, _: Encoding, _: Option) -> Option { - None - } - fn storage(&self, _: Encoding) -> Option { - None - } - fn send(&self, encoding: Encoding, value: u64) -> Option> { - if encoding != SERVED || value & 1 << 8 != 0 { - return None; - } - let target = (value & 1) as usize; - Some((self.words[target].swap(1, Ordering::AcqRel) == 0).then_some(target)) - } - fn fiq(&self) -> bool { - self.words[self.pe].load(Ordering::Acquire) != 0 - } -} - -impl Devices for Signalling { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, pe: usize, _: u64) -> Lines { - self.pins(pe).unwrap() - } - /// No latched line: the FIQ is each PE's word ([`Devices::own_fiq`]). - fn pins(&mut self, _: usize) -> Option { - Some(Lines::default()) - } - fn fast_ipi_words(&self) -> Vec { - (0..2) - .map(|pe| crate::machine::fast_ipi::Word { - cluster: 0, - cpu: pe as u8, - status: self.words[pe].as_ptr() as u64, - armed: self.armed[pe].as_ptr() as u64, - }) - .collect() - } - fn take_signalled(&mut self, pe: usize) -> bool { - let raised = self.signalled & 1 << pe != 0; - self.signalled &= !(1 << pe); - raised - } - fn system_register( - &mut self, - _: usize, - _: Encoding, - write: Option, - _: u64, - ) -> Option> { - self.register_calls += 1; - let target = (write? & 1) as usize; - if self.words[target].swap(1, Ordering::AcqRel) == 0 { - self.signalled |= 1 << target; - } - Some(Ok(0)) - } - fn serves_register(&self, encoding: Encoding) -> bool { - encoding == SERVED - } - fn waits_on_host(&self) -> bool { - self.asleep - } - fn local_registers(&self, pe: usize) -> Option> { - Some(Arc::new(SignalWords { - words: Arc::clone(&self.words), - pe, - })) - } -} - -/// A signal its handle completes takes no lock and wakes its target, which -/// reads the FIQ live from its own word, never in its lines; one the board -/// raises under the lock wakes the target through the call's notification. -#[test] -fn a_signal_without_the_lock_wakes_its_target_and_raises_its_fiq() { - let (hub, kicks) = hub(2); - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - let mut sender = home.worker(); - let mut target = home.worker(); - // Each handle takes its PE's registers once, under the lock. - sender.local_registers_of(0); - target.local_registers_of(1); - let calls = |devices: &SharedDevices| devices.with(|board| board.register_calls); - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - let board = Arc::clone(&home.board); - let held = board.devices.lock().unwrap(); - // The lock is held elsewhere: the send must not need it. - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - drop(held); - assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); - assert_eq!(kicks.load(Ordering::Relaxed), 1, "the sleeping target"); - assert!(target.own_fiq(1) && !target.lines(1, 0).fiq); - assert!(!sender.own_fiq(0)); - assert_eq!(calls(&home), 0); - // Pending already: no line changes, no wake. - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - // Held low while the SoC sleeps, as the latched pins are. - board.asleep.store(true, Ordering::Release); - assert!(!target.own_fiq(1)); - board.asleep.store(false, Ordering::Release); - // Under the lock: the call's notification wakes the target, though its - // latched pins did not change. - home.with(|devices| devices.words[1].store(0, Ordering::Release)); - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - assert_eq!( - sender.system_register(0, SERVED, Some(1 << 8 | 1), 0), - Some(Ok(0)) - ); - assert_eq!(calls(&home), 1); - assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); - assert_eq!(kicks.load(Ordering::Relaxed), 2); - assert!(target.own_fiq(1)); -} - -/// A PE's own FIQ is read live at every look past its cached lines: an -/// acknowledgement between the cache fill and the next look delivers no -/// FIQ, and a send between them is not lost, while the cache holds. -#[test] -fn a_pes_own_fiq_is_read_live_past_its_cached_lines() { - use super::super::tests::board; - use stela_contracts::identity::Identity; - struct Own { - word: Arc, - queries: usize, - } - impl Devices for Own { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - self.queries += 1; - Lines::default() - } - fn own_fiq(&mut self, _: usize) -> bool { - self.word.load(Ordering::SeqCst) - } - } - let word = Arc::new(AtomicBool::new(true)); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let devices = Own { - word: Arc::clone(&word), - queries: 0, - }; - let mut machine = board(&[], devices, identities); - assert!(machine.device_lines_of(0, 0).fiq); - word.store(false, Ordering::SeqCst); - assert!(!machine.device_lines_of(0, 1).fiq, "acknowledged: no FIQ"); - word.store(true, Ordering::SeqCst); - assert!(machine.device_lines_of(0, 2).fiq, "sent: not lost"); - assert_eq!(machine.devices.queries, 1, "the cached lines held"); -} - -/// The board's frozen fast-IPI table names each PE's own word and the -/// hub's counters for it: a request completed by it raises the target's -/// FIQ, tells it, and has a halted target woken through the board. -#[test] -fn the_fast_ipi_table_completes_a_request_through_the_hubs_words() { - use crate::machine::fast_ipi::{Register, Sent}; - let (hub, kicks) = hub(2); - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - let mut target = home.worker(); - let table = home.fast_ipi_table().expect("a table"); - assert!(Arc::ptr_eq(&table, &target.fast_ipi_table().unwrap())); - let entry = *table.target(0, 1).unwrap(); - assert_eq!(entry.lines, hub.inboxes[1].lines.as_ptr() as u64); - assert_eq!(entry.sleeping, hub.inboxes[1].sleeping.as_ptr() as u64); - assert_eq!(entry.interrupt, hub.inboxes[1].chain.control()); - assert_eq!(entry.pe, 1); - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - let interrupt = hub.inboxes[1] - .chain - .interrupt_epoch() - .load(Ordering::SeqCst); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - assert_eq!(table.send(0, Register::RequestLocal, 1), Sent::Wake(1)); - assert!(target.own_fiq(1) && !target.lines(1, 0).fiq); - assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch + 1); - assert_eq!( - hub.inboxes[1] - .chain - .interrupt_epoch() - .load(Ordering::SeqCst), - interrupt + 1 - ); - assert_eq!(kicks.load(Ordering::Relaxed), 0, "the engine wakes it"); - target.wake_signalled(1); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - // The engine's own path then finds it pending and changes nothing. - assert_eq!(table.send(0, Register::RequestLocal, 1), Sent::Done); - assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch + 1); -} - -/// A board that signals CPUs by number, which may name one no PE runs: a -/// write of `SERVED` with bit 8 clear completes on the sender's handle for -/// the CPU its low byte names; with bit 8 set it raises that CPU under the -/// lock. -struct Numbered { - raised: Vec, -} - -struct NumberedHandle; - -impl LocalRegisters for NumberedHandle { - fn register(&self, _: Encoding, _: Option) -> Option { - None - } - fn storage(&self, _: Encoding) -> Option { - None - } - fn send(&self, encoding: Encoding, value: u64) -> Option> { - (encoding == SERVED && value & 1 << 8 == 0).then_some(Some((value & 0xff) as usize)) - } -} - -impl Devices for Numbered { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - fn latched_pins(&mut self, _: usize) -> Option { - Some(Lines::default()) - } - fn take_signalled(&mut self, pe: usize) -> bool { - self.raised.get_mut(pe).is_some_and(core::mem::take) - } - fn system_register( - &mut self, - _: usize, - _: Encoding, - write: Option, - _: u64, - ) -> Option> { - self.raised[(write? & 0xff) as usize] = true; - Some(Ok(0)) - } - fn serves_register(&self, encoding: Encoding) -> bool { - encoding == SERVED - } - fn local_registers(&self, _: usize) -> Option> { - Some(Arc::new(NumberedHandle)) - } -} - -/// A signal without the lock to a CPU the board has but no PE runs is -/// refused (the engine reports it once and goes on) and wakes no one; it -/// does not index past the PEs. One to a PE still wakes it. -#[test] -fn a_signal_to_a_cpu_without_a_pe_is_refused_and_dropped() { - let (hub, kicks) = hub(2); - let home = SharedDevices::new( - Numbered { - raised: vec![false; 8], - }, - Arc::clone(&hub), - ); - let mut sender = home.worker(); - for pe in 0..2 { - hub.inboxes[pe].sleeping.store(true, Ordering::SeqCst); - } - let epochs = |hub: &Hub| -> Vec { - hub.inboxes - .iter() - .map(|inbox| inbox.lines.load(Ordering::SeqCst)) - .collect() - }; - let before = epochs(&hub); - assert!(matches!( - sender.system_register(0, SERVED, Some(5), 0), - Some(Err(_)) - )); - assert_eq!(kicks.load(Ordering::Relaxed), 0); - assert_eq!(epochs(&hub), before); - let woken = |home: &SharedDevices| { - home.board.woken[Call::Register as usize].load(Ordering::Relaxed) - }; - assert_eq!(woken(&home), 0); - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - assert_eq!(woken(&home), 1, "counted in DEVICE WAKES register="); -} - -/// A PE numbered past 63 whose FIQ a locked call raised is told and woken -/// as any other: the board keeps a raise for every PE. -#[test] -fn a_locked_signal_wakes_a_pe_past_63() { - let (hub, kicks) = hub(70); - let home = SharedDevices::new( - Numbered { - raised: vec![false; 70], - }, - Arc::clone(&hub), - ); - let mut sender = home.worker(); - hub.inboxes[66].sleeping.store(true, Ordering::SeqCst); - let epoch = hub.inboxes[66].lines.load(Ordering::SeqCst); - assert_eq!( - sender.system_register(0, SERVED, Some(1 << 8 | 66), 0), - Some(Ok(0)) - ); - assert_ne!(hub.inboxes[66].lines.load(Ordering::SeqCst), epoch); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - assert!(!home.with(|devices| devices.raised[66]), "taken once"); -} - -/// A signal still pending when the SoC wakes reaches its PE: its FIQ was -/// held low while the SoC slept, so the PE, asleep in WFI, is told and woken -/// when the SoC's sleep ends, though no latched pin changed. -#[test] -fn a_signal_pending_when_the_soc_wakes_wakes_its_target() { - let (hub, kicks) = hub(2); - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - let mut sender = home.worker(); - let mut target = home.worker(); - home.with(|devices| devices.asleep = true); - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - assert!(!target.own_fiq(1), "held low while the SoC sleeps"); - // The target looked at its lines and sleeps again. - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - let before = kicks.load(Ordering::Relaxed); - home.with(|devices| devices.asleep = false); - assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); - assert_eq!(kicks.load(Ordering::Relaxed), before + 1); - assert!(target.own_fiq(1)); -} - -/// Invariant: a shared board publishes only latched pins, never a PE's own -/// signal word, so a PE that clears its word without the lock never reads -/// a stale FIQ that an unrelated locked call published while the word was -/// set (`Board::publish` and `Held::notify` use `latched_pins`). -#[test] -fn a_signal_cleared_without_the_lock_leaves_no_stale_published_fiq() { - let (hub, _) = hub(2); - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - let mut sender = home.worker(); - let mut target = home.worker(); - let words = home.with(|devices| Arc::clone(&devices.words)); - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - assert!(target.own_fiq(1)); - // Unrelated calls under the lock while the word is set: each release - // publishes every PE's pins, and a write notifies the others. - home.with(|_| ()); - sender.write(0, 0, 4, 0, 0).unwrap(); - assert_eq!( - home.board.pins[1].load(Ordering::Acquire), - shared_devices::pack(Some(Lines::default())) - ); - // The target acknowledges on its own word. - words[1].store(0, Ordering::Release); - assert!(!target.own_fiq(1) && !target.lines(1, 0).fiq); -} - -/// No lost wake-up: a PE that saw no FIQ and halts (`Hub::sleep`) is kicked -/// by a send that races with its halting, in every interleaving the -/// rounds reach. Each halt is bounded: a lost wake-up fails the test. -#[test] -fn a_signal_racing_with_a_halt_always_wakes_the_target() { - struct Flag(Arc); - impl Kick for Flag { - fn kick(&self, _: usize) { - self.0.store(true, Ordering::SeqCst); - } - } - const ROUNDS: usize = 2_000; - let kicked = Arc::new(AtomicBool::new(false)); - let hub = Hub::new(2, Flag(Arc::clone(&kicked))); - for pe in 0..2 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); - let mut sender = home.worker(); - let mut target = home.worker(); - let words = home.with(|devices| Arc::clone(&devices.words)); - let start = std::sync::Barrier::new(2); - let done = std::sync::Barrier::new(2); - let lost = AtomicBool::new(false); - std::thread::scope(|scope| { - scope.spawn(|| { - for round in 0..ROUNDS { - start.wait(); - // Vary where the send lands against the target's halt. - for _ in 0..(round * 7) % 64 { - core::hint::spin_loop(); - } - assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); - done.wait(); - } - }); - for _ in 0..ROUNDS { - start.wait(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - loop { - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - if target.own_fiq(1) { - break; - } - hub.sleep(1, epoch, true, || { - while !kicked.swap(false, Ordering::SeqCst) { - if std::time::Instant::now() > deadline { - lost.store(true, Ordering::SeqCst); - return; - } - std::thread::yield_now(); - } - }); - if lost.load(Ordering::SeqCst) { - break; - } - } - words[1].store(0, Ordering::Release); - kicked.store(false, Ordering::SeqCst); - done.wait(); - } - }); - assert!( - !lost.load(Ordering::SeqCst), - "a send left its target halted" - ); -} - -/// `cargo test -p stela-engine --release --lib signal_send_costs -- -/// --ignored --nocapture`: ns per signal sent through the board, under the -/// devices' lock (as every fast IPI was) or through the sender's handle, -/// alone and while another thread takes the lock for 2 us in every 4 us as -/// device accesses do. The target's word is cleared after each send, so -/// every send raises a line and bumps the target's epoch (no kick: it -/// does not sleep). -#[test] -#[ignore = "manual: opt-in"] -fn signal_send_costs() { - const SENDS: u32 = 200_000; - for contended in [false, true] { - for locked in [true, false] { - let (hub, _) = hub(2); - let home = SharedDevices::new(Signalling::default(), hub); - let mut sender = home.worker(); - sender.local_registers_of(0); - let words = home.with(|devices| Arc::clone(&devices.words)); - let value = if locked { 1 << 8 | 1 } else { 1 }; - let stop = AtomicBool::new(false); - let ns = std::thread::scope(|scope| { - if contended { - scope.spawn(|| { - while !stop.load(Ordering::Relaxed) { - home.with(|_| { - let until = - std::time::Instant::now() + std::time::Duration::from_micros(2); - while std::time::Instant::now() < until { - core::hint::spin_loop(); - } - }); - let until = - std::time::Instant::now() + std::time::Duration::from_micros(2); - while std::time::Instant::now() < until { - core::hint::spin_loop(); - } - } - }); - } - let started = std::time::Instant::now(); - for _ in 0..SENDS { - sender.system_register(0, SERVED, Some(value), 0); - words[1].store(0, Ordering::Release); - } - let ns = started.elapsed().as_nanos() / u128::from(SENDS); - stop.store(true, Ordering::Relaxed); - ns - }); - std::println!("SIGNAL contended={contended} locked={locked} ns_per_send={ns}"); - } - } -} - -#[test] -fn bytes_for_the_host_wake_one_sleeping_pe_and_reach_one_machine_once() { - let (hub, kicks) = hub(3); - let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - // With no PE asleep, the next to wait takes it, and none halts - // meanwhile. - worker.write(1, 0, 4, 3, 0).unwrap(); - assert_eq!(kicks.load(Ordering::Relaxed), 0); - let mut halts = 0; - hub.sleep(2, hub.lines_epoch(2), true, || halts += 1); - assert_eq!(halts, 0, "the service is due"); - let mut home = home; - assert!(home.take_host_service()); - assert!(!worker.take_host_service(), "taken once"); - // One PE asleep waiting for an interrupt wakes for it, and a request - // already due wakes none. - for pe in [1, 2] { - hub.inboxes[pe].serves.store(true, Ordering::SeqCst); - hub.inboxes[pe].sleeping.store(true, Ordering::SeqCst); - } - worker.write(1, 0, 4, 3, 0).unwrap(); - worker.write(1, 0, 4, 3, 0).unwrap(); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - assert!(worker.take_host_service()); -} - -#[test] -fn the_home_machine_sees_any_pes_reset_and_dma_without_the_lock() { - let (hub, _) = hub(2); - let mut home = SharedDevices::new( - Pending { - dma: Some(7), - ..Pending::default() - }, - Arc::clone(&hub), - ); - let mut worker = home.worker(); - assert_eq!(home.dma_deadline(), Some(7), "as the board was made"); - worker.write(1, 0, 4, 90, 0).unwrap(); - assert_eq!( - (home.dma_deadline(), worker.dma_deadline()), - (Some(90), None) - ); - // Home at work outside its run loop: the other PEs take its DMA, which - // a wake would not get it to before that work ends; asleep, it is woken. - hub.set_outside(0, true); - assert_eq!(worker.dma_deadline(), Some(90)); - hub.inboxes[0].sleeping.store(true, Ordering::SeqCst); - assert_eq!(worker.dma_deadline(), None); - hub.inboxes[0].sleeping.store(false, Ordering::SeqCst); - hub.set_outside(0, false); - assert_eq!(worker.dma_deadline(), None); - worker.write(1, 0, 4, 0, 0).unwrap(); - assert_eq!(home.dma_deadline(), None); - hub.set_outside(0, true); - assert_eq!(worker.dma_deadline(), None, "no DMA, none to take"); - hub.set_outside(0, false); - // A reset another PE's access requested reaches the home machine - // once, and never the worker. - worker.write(1, 0, 4, 1, 0).unwrap(); - assert!(worker.take_reset().is_none()); - assert!( - home.take_reset() - .is_some_and(|reset| reset.reason == "test") - ); - assert!(home.take_reset().is_none()); - // A start reaches whichever machine asks first, once. - home.write(0, 0, 4, 2, 0).unwrap(); - worker.write(1, 0, 4, 2, 0).unwrap(); - let start = worker.take_start().unwrap(); - assert_eq!((start.cpu, start.address), (1, 0x800)); - assert!(home.take_start().is_some()); - assert!(home.take_start().is_none() && worker.take_start().is_none()); - assert_eq!(home.waits(), [0; Call::ALL.len()]); -} - -#[test] -fn only_the_home_machine_advances_the_devices_with_time_and_tells_the_others() { - let (hub, _) = hub(2); - let mut home = SharedDevices::new( - Pending { - irq_at: Some(20), - ..Pending::default() - }, - Arc::clone(&hub), - ); - let mut worker = home.worker(); - assert_eq!(worker.deadline(10), None, "the worker waits to be told"); - assert_eq!(home.deadline(10), Some(20)); - let epoch = hub.lines_epoch(1); - assert_eq!(home.deadline(25), None); - assert_eq!(hub.lines_epoch(1), epoch + 1, "PE 1's IRQ rose"); - assert!(worker.lines(1, 25).irq); - // Asking again changes nothing. - home.deadline(30); - assert_eq!(hub.lines_epoch(1), epoch + 1); - // A call from a PE whose counter read lagged cannot undo that advance. - assert!(!home.lines_and_deadline(0, 10).0.irq); - assert_eq!(hub.lines_epoch(1), epoch + 1); - assert!(worker.lines(1, 10).irq); -} - -/// Latched pins: PE 1's IRQ rises once an advance with time reaches -/// `irq_at`; counts the advances. -#[derive(Default)] -struct Timed { - irq_at: u64, - raised: bool, - advances: usize, -} - -impl Devices for Timed { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, pe: usize, now: u64) -> Lines { - self.deadline(now); - self.pins(pe).unwrap_or_default() - } - fn pins(&mut self, pe: usize) -> Option { - Some(Lines { - irq: pe == 1 && self.raised, - ..Lines::default() - }) - } - fn deadline(&mut self, now: u64) -> Option { - self.advances += 1; - self.raised |= now >= self.irq_at; - (!self.raised).then_some(self.irq_at) - } -} - -#[test] -fn a_pe_advances_the_devices_once_their_deadline_passed_while_home_is_outside() { - let (hub, _) = hub(2); - let mut home = SharedDevices::new( - Timed { - irq_at: 20, - ..Timed::default() - }, - Arc::clone(&hub), - ); - let mut worker = home.worker(); - assert_eq!(home.deadline(10), Some(20)); - let epoch = hub.lines_epoch(1); - let advances = |home: &SharedDevices| home.with(|devices| devices.advances); - // Home runs: it advances the devices itself, so the worker does not. - let before = advances(&home); - assert_eq!(worker.deadline(25), None); - assert_eq!(advances(&home), before); - let (lines, until) = worker.lines_and_deadline(1, 25); - assert!(!lines.irq); - assert!(until.is_some_and(|until| until > 25), "looks again later"); - // Home leaves its run loop: the worker, awake past the deadline, brings - // the devices up to its count and tells every PE what changed. - hub.set_outside(0, true); - assert_eq!(worker.deadline(15), None, "not yet due"); - assert_eq!(advances(&home), before); - assert_eq!(worker.deadline(25), None, "it still waits for no device"); - assert_eq!(advances(&home), before + 1); - assert_eq!(hub.lines_epoch(1), epoch + 1, "PE 1's IRQ rose"); - assert!(worker.lines(1, 25).irq); - // Nothing more is due: no PE advances them again. - assert_eq!(worker.deadline(40), None); - assert!(worker.lines_and_deadline(1, 40).0.irq); - assert_eq!(advances(&home), before + 1); - // While another call holds the devices, the worker leaves them. - home.with(|devices| { - devices.raised = false; - devices.irq_at = 50; - }); - hub.set_outside(0, false); - assert_eq!(home.deadline(45), Some(50)); - hub.set_outside(0, true); - let held = home.board.devices.lock().unwrap_or_else(|e| e.into_inner()); - assert_eq!(worker.deadline(60), None); - drop(held); - assert_eq!(advances(&home), before + 2); - assert_eq!(worker.deadline(60), None); - assert_eq!(advances(&home), before + 3); - assert!(worker.lines(1, 60).irq); -} - -/// The host ticks from the first wake that kicks a sleeping PE to the end -/// of its sleep are counted; a sleep nobody kicked, and a later kick in -/// the same sleep, add nothing. -#[test] -fn a_kicked_sleep_counts_its_wake_latency() { - struct Ticking(AtomicU64); - impl Kick for Ticking { - fn kick(&self, _pe: usize) {} - fn ticks(&self) -> u64 { - self.0.fetch_add(10, Ordering::Relaxed) + 10 - } - } - let hub = Hub::new(2, Ticking(AtomicU64::new(0))); - let epoch = hub.lines_epoch(1); - // Kicked at tick 10 (and again at 20), awake at 30. - hub.sleep(1, epoch, true, || { - hub.wake(1); - hub.wake(1); - }); - hub.sleep(1, epoch, true, || {}); - assert_eq!(hub.take_wake_latency(), (1, 20, 20)); - assert_eq!(hub.take_wake_latency(), (0, 0, 0)); - // A wake of a PE that does not sleep kicks nothing and counts nothing. - hub.wake(1); - hub.sleep(1, epoch, true, || {}); - assert_eq!(hub.take_wake_latency(), (0, 0, 0)); -} - -/// A signal armed for a PE that comes due by itself (an Apple deferred fast -/// IPI) bounds how long that PE's machine trusts its lines, and once due -/// the PE advances the devices itself, while home runs its own loop: it -/// fires then, not at home's next advance, which can be milliseconds on. -#[test] -fn a_pe_fires_its_own_due_signal_without_waiting_for_home() { - struct Own(Arc); - impl LocalRegisters for Own { - fn register(&self, _: Encoding, _: Option) -> Option { - None - } - fn storage(&self, _: Encoding) -> Option { - None - } - fn deadline(&self) -> Option { - let due = self.0.load(Ordering::SeqCst); - (due != 0).then_some(due) - } - } - /// PE 1's IRQ rises once an advance passes the armed count. - struct Deferred { - due: Arc, - raised: bool, - advanced_by: Vec, - } - impl Devices for Deferred { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn local_registers(&self, _: usize) -> Option> { - Some(Arc::new(Own(Arc::clone(&self.due)))) - } - fn lines_and_deadline(&mut self, cpu: usize, now: u64) -> (Lines, Option) { - self.advanced_by.push(cpu); - let due = self.due.load(Ordering::SeqCst); - if due != 0 && now >= due { - self.due.store(0, Ordering::SeqCst); - self.raised = true; - } - (self.pins(cpu).unwrap_or_default(), None) - } - fn lines(&mut self, cpu: usize, now: u64) -> Lines { - self.lines_and_deadline(cpu, now).0 - } - fn pins(&mut self, pe: usize) -> Option { - Some(Lines { - irq: pe == 1 && self.raised, - ..Lines::default() - }) - } - } - let (hub, _) = hub(2); - let due = Arc::new(AtomicU64::new(0)); - let home = SharedDevices::new( - Deferred { - due: Arc::clone(&due), - raised: false, - advanced_by: Vec::new(), - }, - Arc::clone(&hub), - ); - let mut worker = home.worker(); - let advanced = |home: &SharedDevices| { - home.with(|devices| core::mem::take(&mut devices.advanced_by)) - }; - advanced(&home); - // Nothing armed: the worker looks again in its usual time. - let look = worker.lines_and_deadline(1, 10).1.unwrap() - 10; - // Armed for count 50: the worker trusts its lines no later than that - // and advances nothing before. - due.store(50, Ordering::SeqCst); - assert_eq!(worker.own_deadline(1), Some(50)); - let (lines, until) = worker.lines_and_deadline(1, 20); - assert_eq!((lines.irq, until), (false, Some(50.min(20 + look)))); - assert!(advanced(&home).is_empty()); - // Due, with home in its run loop: the worker advances them as PE 1 and - // reads its IRQ at once. - assert!(!hub.home_outside()); - let (lines, _) = worker.lines_and_deadline(1, 50); - assert!(lines.irq); - assert_eq!(advanced(&home), [1]); - assert_eq!(worker.own_deadline(1), None); -} - -#[test] -fn a_pe_without_a_machine_waits_for_its_first_start() { - let (hub, _) = hub(2); - hub.event(0); - hub.start(1, 0x1000); - let mut halts = 0; - assert_eq!(hub.first_start(1, || halts += 1), 0x1000); - assert_eq!(halts, 0); -} - -/// A call looks only at the PEs whose pins the devices say may have -/// changed: the others' pins are neither read nor published, and the PE -/// whose line rose is told once and reads it without the lock. -#[test] -fn a_call_looks_only_at_the_pes_whose_pins_changed() { - #[derive(Default)] - struct Masked { - pins: [Lines; 4], - changed: u64, - reads: [usize; 4], - } - impl Devices for Masked { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write( - &mut self, - _: usize, - _: u64, - _: u8, - value: u64, - _: u64, - ) -> Result<(), DeviceError> { - let pins = &mut self.pins[value as usize]; - if !pins.irq { - pins.irq = true; - self.changed |= 1 << value; - } - Ok(()) - } - fn lines(&mut self, pe: usize, _: u64) -> Lines { - self.pins[pe] - } - fn pins(&mut self, pe: usize) -> Option { - Some(self.pins[pe]) - } - fn latched_pins(&mut self, pe: usize) -> Option { - self.reads[pe] += 1; - Some(self.pins[pe]) - } - fn take_pins_changed(&mut self) -> u64 { - core::mem::take(&mut self.changed) - } - } - let (hub, _) = hub(4); - let home = SharedDevices::new(Masked::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - let told: Vec = (0..4) - .map(|pe| hub.inboxes[pe].lines.load(Ordering::SeqCst)) - .collect(); - worker.write(1, 0, 4, 2, 0).unwrap(); - let reads = home.with(|devices| core::mem::take(&mut devices.reads)); - // PE 1 updates its own; PE 2 is read to tell it and to publish it. - assert_eq!((reads[0], reads[1], reads[3]), (0, 1, 0), "{reads:?}"); - assert!(reads[2] >= 1, "{reads:?}"); - let now: Vec = (0..4) - .map(|pe| hub.inboxes[pe].lines.load(Ordering::SeqCst)) - .collect(); - assert_eq!(now, [told[0], told[1], told[2] + 1, told[3]]); - assert!(worker.lines(2, 0).irq, "published for a lock-free read"); - // A call that changed no pins reads none of the others'. - worker.write(1, 0, 4, 2, 0).unwrap(); - let reads = home.with(|devices| devices.reads); - assert_eq!((reads[0], reads[2], reads[3]), (0, 0, 0), "{reads:?}"); -} - -/// A write and its settlement take the board's lock once: one release -/// publishes, and another PE whose line the write raised is told once. The -/// copy the settlement deferred runs after that release, and the transfer -/// that publishes what it came to follows it. -#[test] -fn a_write_settles_under_one_lock_and_tells_another_pe_once() { - use super::super::tests::board; - use super::super::{Memory, UnlockedDma}; - use core::cell::Cell; - use stela_contracts::identity::Identity; - type Log = Arc>>; - struct Copy(Log); - impl UnlockedDma for Copy { - fn run(self: Box, _: &mut dyn Memory) { - self.0.lock().unwrap().push("copy"); - } - } - struct Raising { - log: Log, - irq: bool, - copies: usize, - left: Vec>, - publishes: Cell, - } - impl Devices for Raising { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, cpu: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - assert_eq!(cpu, 0); - self.log.lock().unwrap().push("write"); - self.irq = true; - Ok(()) - } - fn lines(&mut self, pe: usize, _: u64) -> Lines { - Lines { - irq: pe == 1 && self.irq, - ..Lines::default() - } - } - fn transfer(&mut self, _: usize, _: &mut dyn Memory, _: u64) -> Result<(), DeviceError> { - self.log.lock().unwrap().push("transfer"); - if self.copies != 0 { - self.copies -= 1; - self.left.push(Box::new(Copy(Arc::clone(&self.log)))); - } - Ok(()) - } - fn take_unlocked(&mut self) -> Vec> { - core::mem::take(&mut self.left) - } - fn dma_deadline(&self) -> Option { - // Read once by each release's publication. - self.publishes.set(self.publishes.get() + 1); - None - } - } - let (hub, _) = hub(2); - let log: Log = Arc::default(); - let devices = Raising { - log: Arc::clone(&log), - irq: false, - copies: 1, - left: Vec::new(), - publishes: Cell::new(0), - }; - let worker = SharedDevices::new(devices, Arc::clone(&hub)).worker(); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut machine = board(&[], worker, identities); - let publishes = |machine: &mut Machine<_, SharedDevices>| { - machine.devices.with(|devices| devices.publishes.replace(0)) - }; - publishes(&mut machine); - let told = hub.inboxes[1].lines.load(Ordering::SeqCst); - let (devices, processors) = machine.processor_write_parts(); - let written = devices - .write_settled(0, 0x30, 4, 1, 0, processors) - .expect("a plain write"); - assert_eq!(written.written, Ok(())); - assert!( - written - .settled - .is_some_and(|settled| settled.transfer.is_ok()) - ); - assert_eq!( - *log.lock().unwrap(), - ["write", "transfer", "copy", "transfer"] - ); - // The write's lock and the copy's publishing transfer: two releases, - // past the one of the call that counted last. - assert_eq!(publishes(&mut machine), 1 + 2); - assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), told + 1); - // Without a copy, one lock in all; PE 1's line is already up. - log.lock().unwrap().clear(); - let (devices, processors) = machine.processor_write_parts(); - assert!( - devices - .write_settled(0, 0x30, 4, 1, 0, processors) - .is_some_and(|written| written.written.is_ok()) - ); - assert_eq!(*log.lock().unwrap(), ["write", "transfer"]); - assert_eq!(publishes(&mut machine), 1 + 1); - assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), told + 1); -} - -#[test] -fn a_shared_board_classifies_and_serves_a_scalar_access_in_one_call() { - use super::super::tests::board; - use stela_contracts::identity::Identity; - const CANONICAL: u64 = 0x10; - const SAMPLER: u64 = 0x20; - #[derive(Default)] - struct Classified { - reads: usize, - writes: usize, - } - impl Devices for Classified { - fn pc_sample_target(&self, physical: u64, _: u8) -> Option { - (physical == SAMPLER).then_some(1) - } - fn requires_canonical_read(&self, _: usize, physical: u64, _: DeviceReadShape) -> bool { - physical == CANONICAL - } - fn requires_canonical_write(&self, _: usize, physical: u64, _: u8) -> bool { - physical == CANONICAL - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - self.reads += 1; - Ok(7) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - self.writes += 1; - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - } - let (hub, _) = hub(2); - let mut worker = SharedDevices::new(Classified::default(), hub).worker(); - assert_eq!(worker.read_scalar(1, 0x30, 4, 0), ScalarRead::Served(Ok(7))); - assert_eq!( - worker.read_scalar(1, CANONICAL, 4, 0), - ScalarRead::Canonical - ); - assert_eq!(worker.read_scalar(1, SAMPLER, 4, 0), ScalarRead::Sample(1)); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut machine = board(&[], worker, identities); - let (devices, processors) = machine.processor_write_parts(); - assert!( - devices - .write_settled(0, CANONICAL, 4, 1, 0, processors) - .is_none() - ); - let (devices, processors) = machine.processor_write_parts(); - let written = devices - .write_settled(0, 0x30, 4, 1, 0, processors) - .expect("a plain write"); - assert_eq!(written.written, Ok(())); - assert!( - written - .settled - .is_some_and(|settled| settled.transfer.is_ok()) - ); - // Only the plain accesses reached the registers. - assert_eq!( - machine - .devices - .with(|devices| (devices.reads, devices.writes)), - (1, 1) - ); -} - -#[test] -fn board_grace_follows_run_loop_flags() { - let (hub, _) = hub(2); - let grace = &hub.board.grace; - assert!(!grace.inside(0) && !grace.inside(1)); - // Entering the run loop enters the section; parking leaves it. - hub.set_outside(0, false); - hub.set_outside(1, false); - assert!(grace.inside(0) && grace.inside(1)); - let snapshot = grace.snapshot(); - assert!(!grace.passed(&snapshot, None)); - hub.set_parked(1, true); - assert!(!grace.inside(1)); - assert!(!grace.passed(&snapshot, None), "PE 0 has not moved on"); - // A loop top passes; parked and outside together stay outside. - hub.pass(0); - assert!(grace.passed(&snapshot, None)); - hub.set_outside(1, true); - hub.set_parked(1, false); - assert!(!grace.inside(1)); - hub.pass(1); - hub.set_outside(1, false); - assert!(grace.inside(1)); - // A PE that was outside at the snapshot never holds it up. - hub.set_outside(0, true); - let snapshot = grace.snapshot(); - hub.pass(1); - assert!(grace.passed(&snapshot, None)); -} - -#[test] -fn board_wait_runs_out_and_reports_once() { - use super::super::board::Waited; - let (hub, _) = hub(2); - hub.set_outside(0, false); - hub.set_outside(1, false); - let snapshot = hub.board.grace.snapshot(); - let mut now = 0u64; - let mut counter = || { - now += 10; - now - }; - // PE 1 stays inside: PE 0's wait ends at its deadline, back inside. - assert_eq!( - hub.board.wait(0, &snapshot, 100, &mut counter), - Waited::Overdue { first: true } - ); - assert!(hub.board.grace.inside(0)); - assert_eq!( - hub.board.wait(0, &snapshot, 100, &mut counter), - Waited::Overdue { first: false } - ); - hub.pass(1); - assert_eq!( - hub.board.wait(0, &snapshot, 100, &mut counter), - Waited::Passed - ); -} - -/// A PE that slept through hundreds of other PEs' TLBIs by page, of many -/// processes' pages scattered over the lower half, keeps its kernel -/// translations: its mail merges them into lower-half ranges instead of an -/// invalidation of everything, so the wake path's pages stay in its ITLB. -#[test] -fn a_sleeping_pe_keeps_its_kernel_translations_through_a_pile_of_page_tlbis() { - use crate::machine::system::TlbiKind::VA; - const KERNEL: u64 = 0xffff_fe00_1000_0000; - let (hub, _) = hub(2); - let mut machine = first_of_two(&[], &hub); - let el = machine.cpu.pstate.el; - let variant = machine.current_variant(false, false); - let contexts = machine.contexts(el, variant); - machine.chain.set_contexts(contexts); - for page in 0..32 { - let pc = KERNEL + page * FETCH_PAGE; - machine.fetched_through(1, pc, FETCH_PAGE, true); - machine.translate_page(pc, stela_compiler::x86_64::chain::block_key(page << 12, 2)); - } - let mut seed = 0x9e37_79b9_7f4a_7c15u64; - for _ in 0..600 { - seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); - let (asid, page) = ((seed >> 56) % 200 + 1, (seed >> 20) & 0xff_ffff); - hub.broadcast(1, &[tlbi(VA, asid << 48 | page)]); - } - machine.read_mail().unwrap(); - assert_eq!(machine.statistics.itlb_drops[4], 0, "no whole invalidation"); - assert!(machine.statistics.itlb_sources[super::super::ItlbSource::MailMerged as usize] > 0); - assert_eq!(machine.contexts(el, variant), contexts); - for page in 0..32 { - assert!(machine.current_key(KERNEL + page * FETCH_PAGE).is_some()); - } -} - -#[test] -fn passive_registers_are_read_without_the_devices_lock() { - use super::super::PassiveRegisters; - struct Word(AtomicU64); - impl PassiveRegisters for Word { - fn read(&self, physical: u64, bytes: u8) -> Option { - (physical == 0x40 && bytes == 8).then(|| self.0.load(Ordering::Relaxed)) - } - } - #[derive(Default)] - struct Counted { - word: Option>, - reads: usize, - } - impl Devices for Counted { - fn passive_registers(&self) -> Option> { - self.word - .as_ref() - .map(|word| Arc::clone(word) as Arc) - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - self.reads += 1; - Ok(3) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - } - let word = Arc::new(Word(AtomicU64::new(9))); - let (hub, _) = hub(2); - let home = SharedDevices::new( - Counted { - word: Some(Arc::clone(&word)), - reads: 0, - }, - hub, - ); - let mut worker = home.worker(); - // While another call holds the devices' lock, the passive word reads. - let held = home.board.lock(Call::Other); - assert_eq!(worker.read_scalar(1, 0x40, 8, 0), ScalarRead::Served(Ok(9))); - word.0.store(11, Ordering::Relaxed); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(11)); - drop(held); - // Any other width or address takes the lock to the model. - assert_eq!(worker.read_scalar(1, 0x40, 4, 0), ScalarRead::Served(Ok(3))); - assert_eq!(worker.read_scalar(1, 0x48, 8, 0), ScalarRead::Served(Ok(3))); - assert_eq!(home.with(|devices| devices.reads), 2); - // A word read without its cell is not kept for native code. - assert_eq!( - worker.read_scalar(1, 0x40, 8, 0), - ScalarRead::Served(Ok(11)) - ); - assert!(worker.take_plain_read().is_none()); -} - -/// A passive word served from its own cell is a plain read whose epoch is -/// the cell: native code's read (`device_read_thunk`) holds exactly while -/// the cell still has the value the engine read, at any count, and a write -/// of another value ends it. -#[test] -fn passive_words_are_kept_for_native_reads_while_they_hold_their_value() { - use super::super::PassiveRegisters; - struct Cell(Arc); - impl PassiveRegisters for Cell { - fn read(&self, physical: u64, bytes: u8) -> Option { - self.word(physical, bytes) - .map(|word| word.load(Ordering::Acquire)) - } - fn word(&self, physical: u64, bytes: u8) -> Option> { - (physical == 0x40 && bytes == 8).then(|| Arc::clone(&self.0)) - } - } - #[derive(Default)] - struct Board { - cell: Option>, - } - impl Devices for Board { - fn passive_registers(&self) -> Option> { - self.cell - .as_ref() - .map(|cell| Arc::clone(cell) as Arc) - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(3) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - } - let word = Arc::new(AtomicU64::new(9)); - let cell = Arc::new(Cell(Arc::clone(&word))); - let (hub, _) = hub(2); - let home = SharedDevices::new(Board { cell: Some(cell) }, hub); - let mut worker = home.worker(); - assert_eq!(worker.read_scalar(1, 0x40, 8, 5), ScalarRead::Served(Ok(9))); - let plain = worker.take_plain_read().expect("kept"); - assert!(Arc::ptr_eq(&plain.epoch, &word)); - assert_eq!((plain.seen, plain.value, plain.until), (9, 9, u64::MAX)); - // What the native read checks: the epoch word against what it saw. - assert_eq!(plain.epoch.load(Ordering::Acquire), plain.seen); - word.store(10, Ordering::Release); - assert_ne!(plain.epoch.load(Ordering::Acquire), plain.seen); - // The next read keeps the new value; another width keeps nothing. - assert_eq!( - worker.read_scalar(1, 0x40, 8, 5), - ScalarRead::Served(Ok(10)) - ); - assert_eq!(worker.take_plain_read().map(|plain| plain.value), Some(10)); - assert_eq!(worker.read_scalar(1, 0x40, 4, 5), ScalarRead::Served(Ok(3))); - assert!(worker.take_plain_read().is_none()); -} - -#[test] -fn plain_reads_are_served_again_without_the_lock_while_their_epoch_holds() { - /// A model at 0x40 whose 8-byte read is plain, and a bump of its epoch - /// on every write, as a bus moves it. - #[derive(Default)] - struct Plain { - epoch: Arc, - value: u64, - reads: usize, - } - impl Devices for Plain { - fn plain_epoch(&self, physical: u64, bytes: u8) -> Option<(Arc, u64)> { - (physical == 0x40 && bytes == 8) - .then(|| (Arc::clone(&self.epoch), self.epoch.load(Ordering::SeqCst))) - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - self.reads += 1; - Ok(self.value) - } - fn write( - &mut self, - _: usize, - _: u64, - _: u8, - value: u64, - _: u64, - ) -> Result<(), DeviceError> { - self.epoch.fetch_add(1, Ordering::SeqCst); - self.value = value; - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - } - let (hub, _) = hub(2); - let home = SharedDevices::new(Plain::default(), hub); - let mut worker = home.worker(); - let reads = |home: &SharedDevices| home.with(|devices| devices.reads); - // Each plain read it serves is native code's to serve again. - let plain = |worker: &mut SharedDevices| { - worker.take_plain_read().map(|read| { - ( - read.epoch.load(Ordering::SeqCst), - read.seen, - read.value, - read.until, - ) - }) - }; - assert_eq!(worker.read_scalar(1, 0x40, 8, 0), ScalarRead::Served(Ok(0))); - assert_eq!(plain(&mut worker), Some((0, 0, 0, u64::MAX))); - assert_eq!(plain(&mut worker), None); - assert_eq!(reads(&home), 1); - // Served again while another call holds the devices' lock. - let held = home.board.lock(Call::Other); - assert_eq!(worker.read_scalar(1, 0x40, 8, 1), ScalarRead::Served(Ok(0))); - assert_eq!(plain(&mut worker), Some((0, 0, 0, u64::MAX))); - drop(held); - assert_eq!(reads(&home), 1); - // A write by another PE moves the epoch: the next read reaches the model. - let mut other = home.worker(); - other.write(0, 0x40, 8, 5, 2).unwrap(); - assert_eq!(worker.read_scalar(1, 0x40, 8, 3), ScalarRead::Served(Ok(5))); - assert_eq!(worker.read_scalar(1, 0x40, 8, 4), ScalarRead::Served(Ok(5))); - assert_eq!(reads(&home), 2); - // Other reads, and any read once a device deadline passed, reach it. - assert_eq!(worker.read_scalar(1, 0x48, 8, 5), ScalarRead::Served(Ok(5))); - assert_eq!(plain(&mut worker), None); - assert_eq!(worker.read_scalar(1, 0x40, 4, 5), ScalarRead::Served(Ok(5))); - assert_eq!(plain(&mut worker), None); - assert_eq!(reads(&home), 4); - home.board.time.store(6, Ordering::Release); - assert_eq!(worker.read_scalar(1, 0x40, 8, 6), ScalarRead::Served(Ok(5))); - assert_eq!(reads(&home), 5); - // Kept with the deadline it found. - assert_eq!(plain(&mut worker), Some((1, 1, 5, 6))); -} - -/// The copies a transfer leaves ([`Devices::take_unlocked`]) run on the PE -/// that settled the write, after it released the devices' lock, each once, -/// with PEs settling at once; and what each came to is published by a -/// transfer on that PE before its call returns, with no other PE or tick -/// coming by (otherwise a completion can wait for an idle home machine). -#[test] -fn transfers_leave_their_copies_to_run_outside_the_lock() { - use super::super::{LockedMemory, Memory, UnlockedDma}; - use crate::machine::mmu::MemoryLocks; - use std::sync::OnceLock; - type Shared = Arc>>>; - struct Copy { - board: Shared, - address: u64, - ran: Arc, - alone: Arc, - } - impl UnlockedDma for Copy { - fn run(self: Box, memory: &mut dyn Memory) { - let board = self.board.get().expect("the board is built"); - // Free unless another PE took it since: checked while one runs. - if self.alone.load(Ordering::SeqCst) { - assert!(board.devices.try_lock().is_ok(), "outside the lock"); - } - assert!(memory.write(self.address, &[1])); - self.ran.fetch_add(1, Ordering::SeqCst); - } - } - /// A device whose write starts a copy and whose transfer publishes - /// every copy that ran. - struct Copying { - board: Shared, - deferred: bool, - wants: [bool; 4], - left: Vec>, - ran: Arc, - published: usize, - alone: Arc, - } - impl Devices for Copying { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, cpu: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - self.wants[cpu] = true; - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } - fn defer_dma(&mut self) { - self.deferred = true; - } - fn take_unlocked(&mut self) -> Vec> { - core::mem::take(&mut self.left) - } - fn transfer(&mut self, cpu: usize, _: &mut dyn Memory, _: u64) -> Result<(), DeviceError> { - assert!(self.deferred, "a shared board defers its copies"); - self.published = self.ran.load(Ordering::SeqCst); - if core::mem::take(&mut self.wants[cpu]) { - self.left.push(Box::new(Copy { - board: Arc::clone(&self.board), - address: cpu as u64, - ran: Arc::clone(&self.ran), - alone: Arc::clone(&self.alone), - })); - } - Ok(()) - } - } - /// RAM that counts each PE's byte. - struct Counted(Arc<[AtomicUsize; 4]>); - impl Memory for Counted { - fn read(&mut self, _: u64, _: &mut [u8]) -> bool { - true - } - fn write(&mut self, physical: u64, _: &[u8]) -> bool { - self.0[physical as usize].fetch_add(1, Ordering::SeqCst); - true - } - } - impl LockedMemory for Counted { - fn under(&mut self, _: MemoryLocks) -> &mut dyn Memory { - self - } - } - let board: Shared = Arc::new(OnceLock::new()); - let ran = Arc::new(AtomicUsize::new(0)); - let alone = Arc::new(AtomicBool::new(true)); - let devices = Copying { - board: Arc::clone(&board), - deferred: false, - wants: [false; 4], - left: Vec::new(), - ran: Arc::clone(&ran), - published: 0, - alone: Arc::clone(&alone), - }; - let hub = Hub::new(4, Ticks(Arc::new(AtomicUsize::new(0)))); - let home = SharedDevices::new(devices, hub); - assert!(board.set(Arc::clone(&home.board)).is_ok()); - let written = Arc::new([const { AtomicUsize::new(0) }; 4]); - // One PE, every other one idle: the copy ran and its result is - // published before the call returns. - let mut first = home.worker(); - first.write(1, 0, 4, 0, 0).unwrap(); - assert!( - first - .settle_write(1, 0, &mut Counted(Arc::clone(&written))) - .transfer - .is_ok() - ); - assert_eq!(ran.load(Ordering::SeqCst), 1, "before the call returned"); - assert_eq!( - home.with(|devices| devices.published), - 1, - "published at once" - ); - alone.store(false, Ordering::SeqCst); - written[1].store(0, Ordering::SeqCst); - ran.store(0, Ordering::SeqCst); - const ROUNDS: usize = 200; - let threads: Vec<_> = (1..4) - .map(|cpu| { - let mut worker = home.worker(); - let written = Arc::clone(&written); - std::thread::spawn(move || { - for _ in 0..ROUNDS { - worker.write(cpu, 0, 4, 0, 0).unwrap(); - let settled = worker.settle_write(cpu, 0, &mut Counted(Arc::clone(&written))); - assert!(settled.transfer.is_ok()); - } - }) - }) - .collect(); - for thread in threads { - thread.join().unwrap(); - } - assert_eq!(ran.load(Ordering::SeqCst), 3 * ROUNDS); - for cpu in 1..4 { - assert_eq!(written[cpu].load(Ordering::SeqCst), ROUNDS, "PE {cpu}"); - } - assert_eq!( - home.with(|devices| (devices.left.len(), devices.published)), - (0, 3 * ROUNDS), - "every copy published by its own call" - ); -} - -/// A PE gone parallel runs on its hub control, with the board's stamped -/// cells and stamps of the board's table: an exit out of the page whose -/// cell its cell probes named often gets a stamped cell and a stamped tail, -/// and its stamps are counted. -#[test] -fn a_parallel_pe_promotes_the_exits_its_cell_probes_named() { - use super::super::tests::{NATIVE_CODE_STRIDE, machine}; - use stela_compiler::block::ExitKind; - const ADD: u32 = 0x9100_0400; // add x0, x0, #1 - const RET: u32 = 0xd65f_03c0; - let mut words = vec![0; 1026]; - words[0] = 0x1400_0400; // b .+0x1000 - words[1024] = ADD; - words[1025] = RET; - let mut machine = machine(&words); - let base = machine.cpu.pc; - let far = base + 0x1000; - let exit = |next_pc, kind: ExitKind| super::super::NativeExit::Exit { - next_pc, - kind: kind as u64, - }; - machine.host.exits = vec![exit(far, ExitKind::Direct), exit(base, ExitKind::Return)]; - let (hub, _) = hub(1); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - machine.step().unwrap(); - machine.step().unwrap(); - let first = &machine.code.blocks[0]; - let code = &machine.host.installed[first.code.0 / NATIVE_CODE_STRIDE - 1]; - let site = chain::direct_patch((first.code.0 + code.len() - chain::DIRECT_EXIT_BYTES) as u64); - let (address, cells, stamps_held) = { - let mut cache = machine.code.cache(); - let number = cache.targets.site_cell_number(site).expect("a cell"); - assert!(number as usize >= chain::STAMPED_CELLS); - let control = machine.chain.snapshot(); - ( - cache.targets.cell_address(number), - cache.targets.stamped_cells(), - cache.targets.holds_stamps(control.stamps), - ) - }; - let control = machine.chain.snapshot(); - let patches = machine.host.patches.len(); - // The samples its cell probes take of the exit's cell. - for _ in 0..super::super::scheduler::HOT_SAMPLES { - machine.cell_samples.push(address); - } - machine.promote_hot_exits(); - assert_eq!(machine.host.patches.len(), patches + 2, "a stamped tail"); - assert_eq!( - machine.host.patches[patches].1.len(), - chain::STAMPED_TAIL_BYTES - ); - let number = machine.code.cache().targets.site_cell_number(site); - assert!(number.is_some_and(|number| (number as usize) < chain::STAMPED_CELLS)); - assert_eq!(machine.statistics.stamped_tails, 1); - assert_eq!(machine.statistics.stamped_in_use, 1); - assert_eq!(control.cells, cells, "the board's stamped cells"); - assert!(stamps_held, "stamps of the board's table"); - // What the stamped tails count is read from the PE's own stamps. - assert_eq!(machine.chain.stamp_counts(), [0; chain::STAMP_COUNTS]); -} - -/// A PE's jump cache holds across native entries (`chain::lookup_tail`): -/// its entries name the contexts and ITLB drop epoch they were filled -/// under, which the tails compare, so an entry stays until its table entry -/// changes. -#[test] -fn the_jump_cache_holds_across_native_entries() { - let mut machine = super::super::tests::machine(&[0xd65f_03c0]); - let stamps = machine.chain.stamps().0; - assert_ne!(stamps, 0, "every PE's control has stamps before it runs"); - let pc = 0xffff_fe00_0000_1234_u64; - let at = chain::jump_entry(stamps, pc) as *mut u64; - // SAFETY: the PC word of an entry of the PE's live jump cache; no - // native code runs meanwhile. - unsafe { at.write(pc) }; - machine.chain.begin(0, 16); - machine.chain.begin(0, 16); - // SAFETY: as above. - assert_eq!(unsafe { at.read() }, pc); -} - -/// A PE that joins a board other than the one it was made on takes stamps -/// of the board's table, not of its first board's, which goes. -#[test] -fn a_pe_that_joins_the_board_takes_stamps_of_its_table() { - use super::super::board; - use super::super::tests::machine; - let mut memory = vec![0u8; 4 * 4096]; - let window = super::super::CodeWindow { - exec: memory.as_mut_ptr() as usize, - write: memory.as_mut_ptr() as usize, - bytes: memory.len(), - }; - let arena = || { - Arc::new(board::Code::new( - board::slot_capacity(Some(window.bytes)), - chain::MIN_LOOKUP_ENTRIES, - Some(window), - )) - }; - let shared = arena(); - let (hub, _) = hub(2); - hub.share_code(&shared); - let mut second = machine(&[0xd65f_03c0]); - second.code = arena(); - second.attach_stamps(); - let (_attached, control) = Attached::new(&hub, 1, false).unwrap(); - second.join_code(&hub); - assert!(Arc::ptr_eq(&second.code, &shared)); - second.adopt_parallel_control(control); - let control = second.chain.snapshot(); - let mut cache = shared.cache(); - assert_eq!(control.cells, cache.targets.stamped_cells()); - assert!(cache.targets.holds_stamps(control.stamps)); -} - -/// A WFE of a PE that is not home ends inside the scheduler's entry when -/// its next own wake is within the halt-poll: at its event stream edge, or -/// earlier on another PE's SEV, with mail that came during the spin read -/// before the guest runs again. A wake past the poll, and the home PE, -/// take the wait passes. -#[test] -fn a_short_wfe_completes_in_its_exit_without_the_wait_passes() { - use super::super::tests::{BASE, FakeHost, machine}; - use crate::machine::NoDevices; - use crate::machine::system::Register as SystemRegister; - use crate::machine::system::TlbiKind::VAA; - const WFE: u32 = 0xd503_205f; - let start = |events: u64| { - let (hub, _) = hub(2); - let mut machine = machine(&[]); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - hub.home.store(1, Ordering::Relaxed); - machine.host.counter_step = 1; - machine.idle_poll = 300; - // CNTHCTL_EL2.EVNTEN with EVNTI `events`: edges 2^(events+1) apart. - machine - .cpu - .registers - .set(SystemRegister::CNTHCTL_EL2, 0, 1 << 2 | events << 4); - (hub, machine) - }; - let wfe = |machine: &mut Machine| { - machine.cpu.pc = BASE; - machine.system_instruction(WFE).unwrap(); - machine.schedule() - }; - // Edges 128 counts apart: the spin reaches the next one. - let (_hub, mut machine) = start(6); - let edge = crate::machine::timer::next_event(&machine.cpu, machine.host.now).unwrap(); - wfe(&mut machine).unwrap(); - assert!(machine.waiting.is_none() && !machine.cpu.event); - assert_eq!(machine.cpu.pc, BASE + 4); - let statistics = &machine.statistics; - assert_eq!((statistics.waits, statistics.short_waits), (1, 1)); - assert_eq!(statistics.halt_ticks, 0); - assert!(machine.host.timers.is_empty(), "no halt was armed"); - assert!(machine.host.now >= edge && machine.host.now < edge + 100); - // Another PE's TLBI and SEV during the spin: both are read in it and - // the SEV ends the WFE before the edge. - let (hub, mut machine) = start(7); - let edge = crate::machine::timer::next_event(&machine.cpu, machine.host.now).unwrap(); - let sender = Arc::clone(&hub); - machine.host.on_relax = Some(Box::new(move |turn| { - if turn == 3 { - sender.broadcast(1, &[tlbi(VAA, 0x1234)]); - sender.event(1); - } - })); - wfe(&mut machine).unwrap(); - assert!(machine.waiting.is_none()); - assert!(!hub.pending(0), "the mail was read"); - assert_eq!(machine.statistics.short_waits, 1); - assert!(machine.host.now < edge, "the SEV ended it"); - // Edges 65536 counts apart, past the poll: the wait passes take it. - let (_hub, mut machine) = start(15); - wfe(&mut machine).unwrap(); - assert!(machine.waiting.is_none()); - assert_eq!(machine.statistics.short_waits, 0); - assert!(machine.statistics.waits > 0); - // The home PE always takes the passes. - let (hub, mut machine) = start(6); - hub.home.store(0, Ordering::Relaxed); - wfe(&mut machine).unwrap(); - assert_eq!(machine.statistics.short_waits, 0); - // Under step timing the spin, and a pass's poll, are idle time; only - // under it. - assert!(machine.host.idle_marks.is_empty()); - for home in [1, 0] { - let (hub, mut machine) = start(6); - hub.home.store(home, Ordering::Relaxed); - machine.set_step_timing(true); - wfe(&mut machine).unwrap(); - let marks = &machine.host.idle_marks; - assert!( - !marks.is_empty() && marks.len() % 2 == 0, - "{home} {marks:?}" - ); - assert!( - marks.chunks(2).all(|pair| pair == [true, false]), - "{home} {marks:?}" - ); - } -} - -/// A WFE that spins on its Exclusives monitor, as XNU's ticket waiters do, -/// keeps its PE's guest work through the wait passes, so the shared count -/// waits for it if the host keeps it from them; a store to its granule ends -/// the wait. A WFE with no monitor armed holds nothing. -#[test] -fn a_wfe_spinning_on_its_monitor_keeps_guest_work_through_its_wait() { - use super::super::tests::{BASE, machine}; - use crate::machine::cpu::{RESERVATION_GRANULE, Reservation}; - const WFE: u32 = 0xd503_205f; - const GRANULE: u64 = BASE + 0x800; - let wait = |monitor: bool| { - let (hub, _) = hub(2); - let mut machine = machine(&[]); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - hub.home.store(1, Ordering::Relaxed); - machine.host.counter_step = 1; - if monitor { - let mut bytes = [0; RESERVATION_GRANULE as usize]; - assert!(machine.host.read_ram(GRANULE, &mut bytes)); - machine.cpu.monitor = Some(Reservation { - granule: GRANULE, - bytes, - }); - } - machine.cpu.pc = BASE; - machine.system_instruction(WFE).unwrap(); - let _ = machine.schedule(); - (hub, machine) - }; - let (_hub, mut machine) = wait(true); - assert!(machine.waiting.is_some(), "nothing woke it"); - assert!(machine.clock.has_guest_work(), "a spinner has guest work"); - // In the kernel its spin is timed from its first pass, and later - // passes keep that start. - let started = machine.clock.spin_started(); - assert!(started.is_some(), "a kernel spin publishes its start"); - let _ = machine.schedule(); - assert_eq!(machine.clock.spin_started(), started); - // Another core's store to the granule (the ticket's turn) wakes it. - assert!(machine.host.write_ram(GRANULE, &[1])); - let _ = machine.schedule(); - assert!(machine.waiting.is_none()); - assert_eq!(machine.cpu.pc, BASE + 4); - assert!(machine.clock.has_guest_work()); - let (_hub, machine) = wait(false); - assert!(machine.waiting.is_some()); - assert!(!machine.clock.has_guest_work(), "a plain WFE holds nothing"); - assert_eq!(machine.clock.spin_started(), None); -} - -/// A device whose IRQ rises at `irq_at`, which a write sets; counts its -/// advances where reading the count takes no lock. -struct Armed { - irq_at: u64, - advances: Arc, -} - -impl Devices for Armed { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, value: u64, _: u64) -> Result<(), DeviceError> { - self.irq_at = value; - Ok(()) - } - fn lines(&mut self, _: usize, now: u64) -> Lines { - Lines { - irq: now >= self.irq_at, - ..Lines::default() - } - } - fn deadline(&mut self, now: u64) -> Option { - self.advances.fetch_add(1, Ordering::Relaxed); - (now < self.irq_at).then_some(self.irq_at) - } -} - -/// The home machine's wait pass advances the devices once: the deadline -/// its cached lines came with stands in for a second advance, until -/// another PE's call reaches the devices, such as one that arms an earlier -/// deadline, which the next pass then sees. -#[test] -fn home_reuses_its_lines_deadline_until_another_pe_reaches_the_devices() { - use super::super::tests::board; - use stela_contracts::identity::Identity; - let (hub, _) = hub(2); - let count = Arc::new(AtomicUsize::new(0)); - let home = SharedDevices::new( - Armed { - irq_at: 100, - advances: Arc::clone(&count), - }, - hub, - ); - let mut worker = home.worker(); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut machine = board(&[], home, identities); - let advances = |_: &Machine<_, SharedDevices>| count.load(Ordering::Relaxed); - assert!(!machine.device_lines_of(0, 10).irq); - let before = advances(&machine); - assert_eq!(machine.next_deadline(10), Some(100)); - assert_eq!(machine.next_deadline(20), Some(100)); - assert_eq!(advances(&machine), before, "no second advance"); - // PE 1 arms an earlier deadline: the next pass asks the devices. - worker.write(1, 0x30, 4, 50, 20).unwrap(); - assert_eq!(machine.next_deadline(20), Some(50)); - assert_eq!(advances(&machine), before + 1); - // Past the cached deadline the devices are asked again too. - machine.device_lines = None; - assert!(!machine.device_lines_of(0, 30).irq); - let before = advances(&machine); - assert_eq!(machine.next_deadline(40), Some(50)); - assert_eq!(advances(&machine), before); - assert_eq!(machine.next_deadline(60), None); - assert_eq!(advances(&machine), before + 1); -} - -/// Quiescent maintenance: the post-then-entry order. Mail posted while a -/// PE is between blocks counts as applied at once, and the PE's next entry -/// finds it and does not enter until it has read it. -#[test] -fn mail_posted_between_blocks_is_applied_at_once_and_blocks_the_next_entry() { - let (hub, _) = hub(2); - hub.leave_active(1); - let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); - assert_eq!(posted.len(), 1, "reached and interrupted"); - assert!( - hub.applied(&mut posted), - "a PE between blocks is not waited for" - ); - assert!(!hub.enter_active(1), "the entry finds the mail"); - assert_eq!(hub.inboxes[1].active.load(Ordering::SeqCst) & 1, 0); - let mail = hub.take(1).unwrap(); - hub.acknowledge(1, mail.serial); - assert!(hub.enter_active(1), "read, it enters"); -} - -/// The entry-then-post order: a PE running a block is waited for until it -/// applies the mail or leaves the block, whichever is first. -#[test] -fn mail_posted_while_a_pe_runs_a_block_waits_for_it_to_apply_or_leave() { - let (hub, _) = hub(3); - let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); - assert_eq!(posted.len(), 2); - assert!(!hub.applied(&mut posted)); - // PE 1 applies it while it runs; PE 2 leaves its block without it. - let mail = hub.take(1).unwrap(); - hub.acknowledge(1, mail.serial); - assert!(!hub.applied(&mut posted)); - assert_eq!(posted, [(2, 1)]); - hub.leave_active(2); - assert!(hub.applied(&mut posted)); - // Left without reading it, PE 2 reads it before its next block. - assert!(!hub.enter_active(2)); - let mail = hub.take(2).unwrap(); - hub.acknowledge(2, mail.serial); - assert!(hub.enter_active(2)); -} - -/// A broadcast's DSB does not wait for a PE between blocks, however long -/// it stays there (fetching, compiling, scheduling): the wait takes no -/// turn at all, and the mail stays for the PE's next entry. -#[test] -fn a_completion_does_not_wait_for_a_pe_between_blocks() { - let (hub, _) = hub(2); - hub.leave_active(1); - let mut machine = first_of_two(&[], &hub); - machine.post(Maintenance::Code(Some(0x4000))); - machine.send_outgoing(); - machine.complete_maintenance().unwrap(); - assert_eq!(machine.host.relaxes, 0, "no turn of the wait"); - assert!(machine.posted.is_empty()); - assert!(hub.pending(1)); - assert!(!hub.enter_active(1)); -} - -/// A machine that mail reached after its fetch does not run what it -/// fetched: it reads the mail first and fetches again, so it never runs -/// a block the mail retired. -#[test] -fn a_machine_reads_mail_that_came_after_its_fetch_before_it_runs_the_block() { - use super::super::tests::BASE; - use stela_compiler::block::ExitKind; - let (hub, _) = hub(2); - // NOP; NOP. - let mut machine = first_of_two(&[0xd503_201f, 0xd503_201f], &hub); - let exit = |next_pc| super::super::NativeExit::Exit { - next_pc, - kind: ExitKind::Direct as u64, - }; - // The block runs once and comes back to itself: it stays installed. - machine.host.exits = vec![exit(BASE), exit(BASE + 8)]; - machine.step().unwrap(); - assert_eq!(machine.cpu.pc, BASE); - // PE 1 discards every block while PE 0 is between blocks; PE 0's next - // fetch still finds the old block. - let mut posted = hub.broadcast(1, &[Maintenance::Code(None)]); - let posted_serial = posted[0].1; - assert!(hub.applied(&mut posted)); - machine.step().unwrap(); - assert_eq!(machine.cpu.pc, BASE, "nothing ran"); - assert_eq!(machine.host.exits.len(), 1); - assert_eq!(hub.inboxes[0].active.load(Ordering::SeqCst) & 1, 0); - // Its schedule reads the mail, and the next step runs a fresh block. - machine.read_mail().unwrap(); - assert!(!hub.pending(0)); - assert_eq!(hub.inboxes[0].applied.load(Ordering::SeqCst), posted_serial); - machine.step().unwrap(); - assert_eq!(machine.cpu.pc, BASE + 8); - assert!(machine.host.exits.is_empty()); - assert_eq!(hub.inboxes[0].active.load(Ordering::SeqCst) & 1, 0); -} - -/// Racing posts against a PE that enters and leaves blocks: whenever the -/// broadcaster has counted a post as applied, the PE, inside any block it -/// runs, has applied it. Bounded by counts, not by time. -#[test] -fn a_pe_inside_a_block_has_applied_every_post_counted_as_applied() { - const POSTS: u64 = 5_000; - let (hub, _) = hub(2); - hub.leave_active(1); - let required = AtomicU64::new(0); - let done = AtomicBool::new(false); - std::thread::scope(|scope| { - scope.spawn(|| { - let mut applied = 0; - let mut entries = 0u64; - while !done.load(Ordering::SeqCst) { - if let Some(mail) = hub.take(1) { - applied = mail.serial; - hub.acknowledge(1, mail.serial); - continue; - } - if hub.enter_active(1) { - entries += 1; - assert!(required.load(Ordering::SeqCst) <= applied); - for _ in 0..(entries % 16) { - core::hint::spin_loop(); - } - assert!(required.load(Ordering::SeqCst) <= applied); - hub.leave_active(1); - } - } - }); - for page in 1..=POSTS { - let mut posted = hub.broadcast(0, &[Maintenance::Code(Some(page << 14))]); - let serial = posted[0].1; - while !hub.applied(&mut posted) { - std::thread::yield_now(); - } - required.store(serial, Ordering::SeqCst); - } - done.store(true, Ordering::SeqCst); - }); -} - -/// A DSB completes natively while this PE has no maintenance outstanding, -/// in any state and across derived state changes, and exits to the engine -/// once a post or an open code page cell leaves it something to complete; -/// the engine's DSB completes that and reopens the native path. -#[test] -fn native_dsb_completes_only_without_outstanding_maintenance() { - use super::super::mirrors::{BARRIER, CODE_PAGE}; - use super::super::tests::{BASE, FakeHost}; - use super::super::transitions::tests::run_native; - use crate::machine::NoDevices; - use crate::machine::exception::Pstate; - use stela_compiler::x86_64::register_read; - use stela_compiler::{GuestAddress, block::ExitKind}; - const DSB_ISH: u32 = 0xd503_3b9f; - let (hub, _) = hub(2); - let mut machine = first_of_two(&[DSB_ISH], &hub); - machine.cpu.pstate = Pstate::reset(1); - let thunk = register_read::barrier_thunk(GuestAddress(BASE), BARRIER); - let native = |machine: &mut Machine| { - let exit = run_native(machine, &thunk.code); - if exit == (BASE + 4, ExitKind::Fallthrough as u64) { - true - } else { - assert_eq!(exit, (BASE, ExitKind::System as u64)); - false - } - }; - let engine = |machine: &mut Machine| { - machine.cpu.pc = BASE; - machine.system_instruction(DSB_ISH).unwrap(); - assert_eq!(machine.cpu.pc, BASE + 4); - }; - assert!(!native(&mut machine), "no DSB completed yet"); - engine(&mut machine); - assert!(native(&mut machine)); - // Neither derived state nor the PE's state decides it. - machine.derived_changed(); - assert!(native(&mut machine), "derived state changed"); - machine.cpu.pstate.el = 0; - assert!(native(&mut machine), "at EL0"); - machine.cpu.pstate.el = 1; - // Maintenance while the other PE runs no block goes at once, and it - // will read it before it runs one: the DSB has nothing to complete. - hub.leave_active(1); - machine.post(Maintenance::Code(None)); - assert!(machine.outgoing.is_empty() && machine.posted.is_empty()); - assert!(hub.take(1).is_some()); - assert!(native(&mut machine), "nobody to wait for"); - // Maintenance while it runs a block: the DSB must send it and wait. - assert!(hub.enter_active(1)); - machine.post(Maintenance::Code(None)); - assert!(!native(&mut machine), "maintenance posted"); - assert!(hub.take(1).is_none(), "kept for the DSB"); - hub.set_live(1, false); - engine(&mut machine); - assert!(machine.outgoing.is_empty() && machine.posted.is_empty()); - assert!(native(&mut machine)); - hub.set_live(1, true); - // A code page cell the DSB that ends the run of lines must close. - machine.mirrors.open_code_page(0x4000); - assert!(!native(&mut machine), "code page cell open"); - engine(&mut machine); - assert_eq!(machine.mirrors[CODE_PAGE].readable, 0); - assert!(native(&mut machine)); -} - -/// Host work a guest exit's device call left (a storage doorbell's disk -/// step) goes to a PE that sleeps waiting for an interrupt, and the caller -/// goes on with its guest; a PE asleep in WFE is not woken for it, and with -/// no PE to take it the caller does the work itself. -#[test] -fn released_host_work_goes_to_a_pe_that_sleeps_waiting_for_an_interrupt() { - #[derive(Default)] - struct Work { - kicked: Mutex>, - due: AtomicBool, - done: AtomicUsize, - } - struct Released(Arc); - impl Kick for Released { - fn kick(&self, pe: usize) { - self.0.kicked.lock().unwrap().push(pe); - } - fn released(&self) -> bool { - if self.0.due.swap(false, Ordering::SeqCst) { - self.0.done.fetch_add(1, Ordering::SeqCst); - } - false - } - fn release_due(&self) -> bool { - self.0.due.load(Ordering::SeqCst) - } - } - let work = Arc::new(Work::default()); - let hub = Hub::new(3, Released(Arc::clone(&work))); - for pe in 0..3 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - // PE 1 is in a guest exit; PE 2 sleeps in WFE. - hub.inboxes[1].outside.store(true, Ordering::SeqCst); - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - work.due.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work.done.load(Ordering::SeqCst), 1, "the caller did it"); - assert!(work.kicked.lock().unwrap().is_empty()); - assert!(!hub.service.load(Ordering::SeqCst)); - let releases = |home: &SharedDevices| { - let times = home.lock_times()[Call::Access as usize]; - (times.stepped, times.handed) - }; - assert_eq!(releases(&home), (1, 0), "counted as done on the caller"); - assert_eq!(home.board.released[1].load(Ordering::SeqCst), 0, "no ticks"); - // PE 2 now sleeps waiting for an interrupt: it is woken for the work. - hub.inboxes[2].serves.store(true, Ordering::SeqCst); - work.due.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work.done.load(Ordering::SeqCst), 1, "the caller went on"); - assert!(work.due.load(Ordering::SeqCst), "left for the service"); - assert_eq!(*work.kicked.lock().unwrap(), [2]); - assert!(hub.take_service()); - assert_eq!(releases(&home), (1, 1), "counted as handed off"); -} - -/// Released host work that only starts commands (a doorbell write) runs -/// on the releasing PE at once, even with a PE asleep to take it: its wake -/// would cost more, and the command would start only after it. -#[test] -fn released_work_that_only_starts_commands_runs_on_the_releasing_pe() { - #[derive(Default)] - struct Work { - kicked: Mutex>, - due: AtomicBool, - inline: AtomicBool, - done: AtomicUsize, - } - struct Released(Arc); - impl Kick for Released { - fn kick(&self, pe: usize) { - self.0.kicked.lock().unwrap().push(pe); - } - fn released(&self) -> bool { - if self.0.due.swap(false, Ordering::SeqCst) { - self.0.done.fetch_add(1, Ordering::SeqCst); - } - false - } - fn release_due(&self) -> bool { - self.0.due.load(Ordering::SeqCst) - } - fn release_inline(&self) -> bool { - self.0.inline.load(Ordering::SeqCst) - } - } - let work = Arc::new(Work::default()); - let hub = Hub::new(3, Released(Arc::clone(&work))); - for pe in 0..3 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - let releases = |home: &SharedDevices| { - let times = home.lock_times()[Call::Access as usize]; - (times.stepped, times.handed) - }; - // PE 1 is in a guest exit; PE 2 sleeps waiting for an interrupt. - hub.inboxes[1].outside.store(true, Ordering::SeqCst); - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - hub.inboxes[2].serves.store(true, Ordering::SeqCst); - work.due.store(true, Ordering::SeqCst); - work.inline.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work.done.load(Ordering::SeqCst), 1, "started on the caller"); - assert!(work.kicked.lock().unwrap().is_empty(), "no PE woken"); - assert!(!hub.service.load(Ordering::SeqCst)); - assert_eq!(releases(&home), (1, 0)); - // Work that also takes completions still goes to the sleeping PE. - work.due.store(true, Ordering::SeqCst); - work.inline.store(false, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work.done.load(Ordering::SeqCst), 1); - assert_eq!(*work.kicked.lock().unwrap(), [2]); - assert_eq!(releases(&home), (1, 1)); -} - -/// A host interrupt a busy PE took at its release (a host disk's completion -/// signal) wakes a PE that sleeps waiting for an interrupt, at that release -/// on the model clock rather than at the busy PE's slice end; with none -/// asleep the busy PE leaves it to the host's service, and work its own -/// release handed on already is not handed twice. -#[test] -fn a_busy_pes_completion_signal_wakes_a_sleeping_pe_at_its_release() { - #[derive(Default)] - struct Signals { - kicked: Mutex>, - signal: AtomicBool, - due: AtomicBool, - now: AtomicU64, - } - struct Signalled(Arc); - impl Kick for Signalled { - fn kick(&self, pe: usize) { - let now = self.0.now.load(Ordering::SeqCst); - self.0.kicked.lock().unwrap().push((pe, now)); - } - fn ticks(&self) -> u64 { - self.0.now.load(Ordering::SeqCst) - } - fn release_due(&self) -> bool { - self.0.due.load(Ordering::SeqCst) - } - fn signal_due(&self) -> bool { - self.0.signal.swap(false, Ordering::SeqCst) - } - } - let signals = Arc::new(Signals::default()); - let hub = Hub::new(3, Signalled(Arc::clone(&signals))); - for pe in 0..3 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - let handed = |home: &SharedDevices| { - let times = home.lock_times()[Call::Access as usize]; - (times.handed, times.signals) - }; - // PE 1 runs its guest; nobody sleeps: the signal waits for the service. - signals.now.store(1_000, Ordering::SeqCst); - signals.signal.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 1_000), Ok(0)); - assert!(signals.kicked.lock().unwrap().is_empty()); - assert!(!hub.service.load(Ordering::SeqCst)); - // PE 2 sleeps waiting for an interrupt: the next signal wakes it at the - // release that took it, at 2_500, not at PE 1's slice end. - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - hub.inboxes[2].serves.store(true, Ordering::SeqCst); - signals.now.store(2_500, Ordering::SeqCst); - signals.signal.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 2_500), Ok(0)); - assert_eq!(*signals.kicked.lock().unwrap(), [(2, 2_500)]); - assert!(hub.take_service()); - assert_eq!(handed(&home), (0, 1)); - // A release that handed its own work on already wakes nobody twice. - hub.inboxes[1].outside.store(true, Ordering::SeqCst); - signals.due.store(true, Ordering::SeqCst); - signals.signal.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 3_000), Ok(0)); - assert_eq!(signals.kicked.lock().unwrap().len(), 2); - assert_eq!(handed(&home), (1, 1)); -} - -/// With no PE asleep, a release outside the run loop takes a completion -/// signal's step itself, once for the signal; a stream of signals gets at -/// most one step a release, none at a release that did its own host work -/// already, and none from a PE inside its run loop. -#[test] -fn a_stream_of_signals_gets_at_most_one_step_a_release() { - #[derive(Default)] - struct Signals { - kicked: Mutex>, - due: AtomicBool, - released: AtomicUsize, - stepped: AtomicUsize, - } - struct Stream(Arc); - impl Kick for Stream { - fn kick(&self, pe: usize) { - self.0.kicked.lock().unwrap().push(pe); - } - fn released(&self) -> bool { - self.0.due.store(false, Ordering::SeqCst); - self.0.released.fetch_add(1, Ordering::SeqCst); - false - } - fn release_due(&self) -> bool { - self.0.due.load(Ordering::SeqCst) - } - // A new signal comes before every release. - fn signal_due(&self) -> bool { - true - } - fn signal_step(&self) -> bool { - self.0.stepped.fetch_add(1, Ordering::SeqCst); - false - } - } - let signals = Arc::new(Signals::default()); - let hub = Hub::new(3, Stream(Arc::clone(&signals))); - for pe in 0..3 { - hub.set_live(pe, true); - } - let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); - let mut worker = home.worker(); - let steps = |home: &SharedDevices| { - let times = home.lock_times()[Call::Access as usize]; - (times.stepped, times.signals, times.signal_steps) - }; - let work = |signals: &Signals| { - ( - signals.released.load(Ordering::SeqCst), - signals.stepped.load(Ordering::SeqCst), - ) - }; - // PE 1 runs in its loop: it leaves the signal to the host's service. - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work(&signals), (0, 0)); - // In a guest exit with nobody asleep, each release steps once. - hub.inboxes[1].outside.store(true, Ordering::SeqCst); - for release in 1..=3 { - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work(&signals), (0, release)); - } - assert_eq!(steps(&home), (0, 0, 3)); - // A release that did its own host work takes no signal step too. - signals.due.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work(&signals), (1, 3)); - assert_eq!(steps(&home), (1, 0, 3)); - // A PE asleep to take it is woken instead. - hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); - hub.inboxes[2].serves.store(true, Ordering::SeqCst); - assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); - assert_eq!(work(&signals), (1, 3)); - assert_eq!(*signals.kicked.lock().unwrap(), [2]); - assert_eq!(steps(&home), (1, 1, 3)); -} - -/// A core whose halt waits on a doorbell never polls before it halts; any -/// other polls as Linux's haltpoll governor fits it, at most `most`. -#[test] -fn the_halt_poll_is_none_on_a_doorbell_and_bounded_elsewhere() { - let most = 200; - for (poll, blocked) in [(0, 10), (200, 10), (100, 1000), (0, 1000)] { - assert_eq!(idle_poll_after(poll, blocked, most, true), 0); - } - // A short wait that halted doubles the poll, to at least a quarter. - assert_eq!(idle_poll_after(0, 10, most, false), 50); - assert_eq!(idle_poll_after(50, 10, most, false), 100); - assert_eq!(idle_poll_after(200, 10, most, false), 200); - // Long waits halve it, and below a quarter it stops. - assert_eq!(idle_poll_after(200, 1000, most, false), 100); - assert_eq!(idle_poll_after(50, 1000, most, false), 0); -} - -/// A WFE that waits in the engine, taking no trap, opens its state's cell -/// for native WFE to spin in, only with PEs on cores of their own; one that -/// traps opens none, and a change of derived state closes it. What native -/// spins counted reaches the PE's levels as native code returns. -#[test] -fn engine_waits_open_native_event_spins_only_where_other_pes_run() { - use super::super::mirrors::{EVENT_WAITS, mirror_state}; - use super::super::tests::{BASE, machine}; - use crate::machine::exception::Pstate; - use crate::machine::system::Register as SystemRegister; - use stela_compiler::x86_64::register_read::EventSpin; - const WFE: u32 = 0xd503_205f; - const HCR_TWE: u64 = 1 << 14; - let el1 = mirror_state(1, false); - let mut machine = machine(&[WFE]); - machine.cpu.pstate = Pstate::reset(1); - machine.derived_changed(); - let wait = |machine: &mut Machine<_, _>| { - machine.waiting = None; - machine.cpu.pc = BASE; - machine.system_instruction(WFE).unwrap(); - }; - wait(&mut machine); - assert!(machine.waiting.is_some()); - assert_eq!( - machine.mirrors.banks[el1][EVENT_WAITS].readable, 0, - "serialized" - ); - let (hub, _) = hub(1); - machine.enter_parallel(hub).unwrap(); - wait(&mut machine); - assert!(machine.waiting.is_some()); - assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 1); - machine.derived_changed(); - assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 0); - let hcr = machine.cpu.read(SystemRegister::HCR_EL2); - machine - .cpu - .registers - .set(SystemRegister::HCR_EL2, 0, hcr | HCR_TWE); - machine.derived_changed(); - wait(&mut machine); - assert!(machine.waiting.is_none()); - assert_eq!(machine.cpu.pstate.el, 2, "trapped"); - assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 0); - - machine.set_step_timing(true); - machine.mirrors.spin = EventSpin { - completed: 2, - missed: 3, - held: 1, - counts: 96, - start: 7, - turns: 9, - streamed: 4, - }; - machine.take_event_spins(); - let levels = machine.step_timing().unwrap().levels; - assert_eq!( - [ - levels.wfe_spun, - levels.wfe_spin_missed, - levels.wfe_held, - levels.wfe_spin_counts, - levels.wfe_streamed - ], - [2, 3, 1, 96, 4] - ); - assert_eq!(machine.mirrors.spin, EventSpin::default()); -} - -/// With the board's fast-IPI table named to native code, a plain fast-IPI -/// write the engine completes opens its state's cell for native writes, -/// which a change of derived state closes; the PEs native requests found -/// halted are woken through the board when native code returns. -#[test] -fn plain_fast_ipi_writes_open_native_ones_and_native_wakes_reach_the_board() { - use super::super::mirrors::{FAST_IPI_WRITES, mirror_state}; - use super::super::tests::board; - use stela_contracts::identity::Identity; - const MSR: u32 = 0xd51d_f029; // msr s3_5_c15_c0_1, x9 - let (hub, kicks) = hub(2); - let worker = SharedDevices::new(Signalling::default(), Arc::clone(&hub)).worker(); - let identities = vec![Identity { - midr: 0x611f_0320, - mpidr: 0x8000_0000, - clock: None, - caches: None, - }]; - let mut machine = board(&[MSR], worker, identities); - let state = mirror_state(machine.cpu.pstate.el, machine.cpu.pstate.guarded); - let write = |machine: &mut Machine<_, _>| { - let pc = machine.cpu.pc; - machine.cpu.state.x[9] = 1; - machine.system_instruction(MSR).unwrap(); - assert_eq!(machine.cpu.pc, pc + 4); - machine.cpu.pc = pc; - }; - write(&mut machine); - assert_eq!( - machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 0, - "no table named" - ); - assert_eq!(machine.enter_fast_ipi(), Some(())); - let ipi = machine.mirrors.fast_ipi; - let table = machine.devices.fast_ipi_table().unwrap(); - assert_eq!((ipi.base, ipi.pe), (table.base(), 0)); - assert_eq!(ipi.status, table.target(0, 0).unwrap().status); - write(&mut machine); - assert_eq!(machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 1); - machine.derived_changed(); - assert_eq!(machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 0); - hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); - machine.mirrors.fast_ipi.wakes = 1 << 1; - machine.take_fast_ipi_wakes(); - assert_eq!(kicks.load(Ordering::Relaxed), 1); - assert_eq!(machine.mirrors.fast_ipi.wakes, 0); -} - -/// A register a read leaves plain, as an event register whose last event the -/// read took: the device that raises events at 0x50 moves its epoch, as a -/// bus does, before the event is there to read at 0x40. -#[derive(Default)] -struct Events { - epoch: Arc, - pending: u64, - raised: u64, - reads: usize, -} -impl Devices for Events { - fn plain_epoch(&self, physical: u64, bytes: u8) -> Option<(Arc, u64)> { - (physical == 0x40 && bytes == 4 && self.pending == 0) - .then(|| (Arc::clone(&self.epoch), self.epoch.load(Ordering::SeqCst))) - } - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - self.reads += 1; - if self.pending == 0 { - return Ok(0); - } - // Taking an event changes the model: the epoch moves first. - self.epoch.fetch_add(1, Ordering::SeqCst); - self.pending -= 1; - Ok(self.raised - self.pending) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - self.epoch.fetch_add(1, Ordering::SeqCst); - self.pending += 1; - self.raised += 1; - Ok(()) - } - fn lines(&mut self, _: usize, _: u64) -> Lines { - Lines::default() - } -} - -/// The read that takes the last event leaves the next read served without -/// the lock; an event raised since reaches the next read. -#[test] -fn a_read_that_leaves_its_register_plain_serves_the_next_read_without_the_lock() { - let (hub, _) = hub(2); - let home = SharedDevices::new(Events::default(), hub); - let mut worker = home.worker(); - let mut other = home.worker(); - let reads = |home: &SharedDevices| home.with(|devices| devices.reads); - other.write(0, 0x50, 4, 0, 0).unwrap(); - assert_eq!(worker.read_scalar(1, 0x40, 4, 1), ScalarRead::Served(Ok(1))); - // The claim and the read after it under the same lock. - assert_eq!(reads(&home), 2); - assert_eq!(worker.read_scalar(1, 0x40, 4, 2), ScalarRead::Served(Ok(0))); - assert_eq!(reads(&home), 2, "served without the devices"); - // An event raised since moved the epoch: the next read takes it. - other.write(0, 0x50, 4, 0, 3).unwrap(); - assert_eq!(worker.read_scalar(1, 0x40, 4, 4), ScalarRead::Served(Ok(2))); - // Two pending: the first claim leaves the register not plain. - other.write(0, 0x50, 4, 0, 5).unwrap(); - other.write(0, 0x50, 4, 0, 5).unwrap(); - let before = reads(&home); - assert_eq!(worker.read_scalar(1, 0x40, 4, 6), ScalarRead::Served(Ok(3))); - assert_eq!(reads(&home), before + 1); - assert_eq!(worker.read_scalar(1, 0x40, 4, 7), ScalarRead::Served(Ok(4))); - assert_eq!(worker.read_scalar(1, 0x40, 4, 8), ScalarRead::Served(Ok(0))); - assert_eq!(reads(&home), before + 3); -} - -/// Events raised on one core while another reads: no event is lost or -/// taken twice, and a read that began after a raise returned never finds -/// none while that event is untaken. -#[test] -fn events_raised_while_their_register_is_served_plain_are_never_lost_or_late() { - const EVENTS: u64 = 20_000; - let (hub, _) = hub(2); - let home = SharedDevices::new(Events::default(), hub); - let raised = Arc::new(AtomicU64::new(0)); - let mut raiser = home.worker(); - let mut reader = home.worker(); - let raising = { - let raised = Arc::clone(&raised); - std::thread::spawn(move || { - for _ in 0..EVENTS { - raiser.write(0, 0x50, 4, 0, 0).unwrap(); - raised.fetch_add(1, Ordering::SeqCst); - } - }) - }; - let mut taken = 0u64; - while taken < EVENTS { - let before = raised.load(Ordering::SeqCst); - match reader.read_scalar(1, 0x40, 4, 0) { - ScalarRead::Served(Ok(0)) => assert!( - taken >= before, - "a read found none with {} raised before it untaken", - before - taken - ), - ScalarRead::Served(Ok(event)) => { - taken += 1; - assert_eq!(event, taken, "events are taken once, in order"); - } - other => panic!("{other:?}"), - } - } - raising.join().unwrap(); - assert_eq!(reader.read_scalar(1, 0x40, 4, 0), ScalarRead::Served(Ok(0))); - assert_eq!(home.with(|devices| devices.pending), 0); -} - -/// Counts its kicks and reads a counter the test moves, as a host's -/// doorbells and its 24 MHz count do. -struct Served { - kicks: Arc, - host: Arc, -} -impl Kick for Served { - fn kick(&self, _pe: usize) { - self.kicks.fetch_add(1, Ordering::SeqCst); - } - fn count(&self) -> Option { - Some(self.host.load(Ordering::SeqCst)) - } -} - -/// A counter frequency at which the stall limit is 1200 counts. -const SERVED_FREQUENCY: u64 = 24_000; -const SERVED_STALL: u64 = SERVED_FREQUENCY * super::super::clock::STALL_MILLIS / 1000; - -type Clock = super::super::clock::Clock; - -/// Two PEs on a hub whose shared count follows a host counter from 1000, -/// each with its own reader; both run. -fn serving_pair() -> (Arc, Arc, Arc, Clock, Clock) { - let kicks = Arc::new(AtomicUsize::new(0)); - let host = Arc::new(AtomicU64::new(1000)); - let hub = Hub::new( - 2, - Served { - kicks: Arc::clone(&kicks), - host: Arc::clone(&host), - }, - ); - for pe in 0..2 { - hub.set_live(pe, true); - } - Clock::default().seed(&hub.clock, 1000, SERVED_FREQUENCY); - let (mut first, mut second) = (Clock::default(), Clock::default()); - first.attach(Arc::clone(&hub.clock), 0); - second.attach(Arc::clone(&hub.clock), 1); - (hub, kicks, host, first, second) -} - -/// The reported shape: PE 1's guest waits for an interrupt and its core -/// serves the host in a part that takes seconds, while PE 0 runs and sends -/// it a fast IPI. The IPI kicks its core at once, the service sees it at -/// its next part, and the count PE 0 reads goes on at most a stall limit -/// past the IPI however long the part takes: PE 0's XNU never sees PE 1 -/// leave an IPI unanswered for longer. Once PE 1 looks again, the count -/// goes on from there and the held time is lag the slew repays. -#[test] -fn an_ipi_to_a_pe_that_serves_the_host_kicks_it_and_holds_the_count_for_it() { - let (hub, kicks, host, mut first, mut second) = serving_pair(); - first.idle(|| 1000, 0, None); - first.busy(|| 1000, 0, None); - second.idle(|| 1000, 0, None); - // PE 1 starts a service turn with nothing pending. - let epoch = hub.lines_epoch(1); - assert_eq!(hub.set_serving(1, Some(epoch)), None); - let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); - assert_eq!(watch.pending(1000), None); - // A wake with no guest work for it (a SEV, which a WFI does not take) - // neither kicks nor marks it. - hub.event(0); - assert_eq!(kicks.load(Ordering::SeqCst), 0); - // PE 0's fast IPI at host 2000: one kick, and the turn's next look - // finds it. - host.store(2000, Ordering::SeqCst); - hub.lines_changed_unwoken(1); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 1, "the serving PE is kicked"); - assert_eq!(watch.pending(2000), Some(super::Pending::Lines)); - // A second IPI meanwhile kicks it no more. - hub.lines_changed_unwoken(1); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 1); - // PE 1 stays out for five seconds of host time; PE 0 runs and marks - // its progress every 10 counts. - let ipi = 2000; - let mut retired = 0; - let end = 2000 + 5 * SERVED_FREQUENCY; - for now in (2010..end).step_by(10) { - retired += 100; - first.mark(|| now, retired, None); - let count = first.read(|| now); - assert!(count <= ipi + SERVED_STALL, "at {now}: count {count}"); - } - assert_eq!( - first.read(|| end), - ipi + SERVED_STALL, - "held a stall limit on" - ); - assert_eq!( - watch.waited(end), - Some((super::Pending::Lines, Some(end - ipi))), - "the wait is measured from the first wake" - ); - // PE 1 is back in its loop: the count goes on from where it held. - assert_eq!(hub.set_serving(1, None), Some(epoch)); - second.idle(|| end, 0, None); - first.mark(|| end + 10, retired + 100, None); - assert_eq!(first.read(|| end + 10), ipi + SERVED_STALL + 10); - assert_eq!(hub.clock.take_stalled(), end - (ipi + SERVED_STALL)); - // A PE that neither serves nor sleeps is not kicked: it reads its - // lines at its next return to the engine. - hub.lines_changed_unwoken(1); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 1); -} - -/// PE 1's own timer comes due while it serves: the service sees it at its -/// next part, and the count holds a stall limit past the deadline, as for -/// an IPI. Its next wait pass clears the mark. -#[test] -fn a_timer_due_on_a_pe_that_serves_the_host_ends_its_service_and_holds_the_count() { - let (hub, kicks, _host, mut first, mut second) = serving_pair(); - first.idle(|| 1000, 0, None); - first.busy(|| 1000, 0, None); - second.idle(|| 1000, 0, None); - let deadline = 3000; - second.serving(Some(deadline)); - let epoch = hub.lines_epoch(1); - hub.set_serving(1, Some(epoch)); - let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, Some(deadline)); - assert_eq!(watch.pending(2999), None); - assert_eq!(watch.pending(3000), Some(super::Pending::Timer)); - assert_eq!(watch.waited(3500), Some((super::Pending::Timer, Some(500)))); - // Before its deadline it holds nothing; past it a stall limit on. - let mut retired = 0; - for now in (1010..10_000).step_by(10) { - retired += 100; - first.mark(|| now, retired, None); - assert_eq!( - first.read(|| now), - now.min(deadline + SERVED_STALL), - "at {now}" - ); - } - assert_eq!( - kicks.load(Ordering::SeqCst), - 0, - "its own timer needs no kick" - ); - hub.set_serving(1, None); - second.look(|| 10_000); - first.mark(|| 10_010, retired + 100, None); - assert_eq!(first.read(|| 10_010), deadline + SERVED_STALL + 10); -} - -/// A line change for a serving PE that accepts no line (it runs with IRQ -/// and FIQ masked) is no guest work: no kick, no mark, its service goes -/// on. A host call ends the service but holds no count: no guest waits -/// for it. -#[test] -fn only_guest_work_a_serving_pe_would_take_holds_the_count() { - let (hub, kicks, host, mut first, mut second) = serving_pair(); - first.idle(|| 1000, 0, None); - first.busy(|| 1000, 0, None); - second.idle(|| 1000, 0, None); - let epoch = hub.lines_epoch(1); - hub.set_accepts(1, Lines::default()); - hub.set_serving(1, Some(epoch)); - let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); - host.store(2000, Ordering::SeqCst); - hub.lines_changed_unwoken(1); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 0, "not kicked"); - assert_eq!(watch.pending(2000), None, "its service goes on"); - hub.inboxes[1].host_call.store(true, Ordering::SeqCst); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 1, "a host call kicks it"); - assert_eq!( - watch.waited(2100), - Some((super::Pending::HostCall, Some(100))) - ); - let mut retired = 0; - for now in (2010..10_000).step_by(10) { - retired += 100; - first.mark(|| now, retired, None); - assert_eq!(first.read(|| now), now, "nothing holds the count"); - } - hub.set_serving(1, None); - // Accepting the FIQ alone, a line change is guest work again. - hub.inboxes[1].host_call.store(false, Ordering::SeqCst); - let epoch = hub.lines_epoch(1); - hub.set_accepts( - 1, - Lines { - irq: false, - fiq: true, - }, - ); - hub.set_serving(1, Some(epoch)); - host.store(10_000, Ordering::SeqCst); - hub.lines_changed_unwoken(1); - hub.wake(1); - assert_eq!(kicks.load(Ordering::SeqCst), 2); - for now in (10_000..20_000).step_by(10) { - retired += 100; - first.mark(|| now, retired, None); - } - assert_eq!(first.read(|| 20_000), 10_000 + SERVED_STALL); -} - -/// Guest work already there when a PE begins to serve marks the count, as -/// a wake would, without kicking its own core; a forwarded access waits -/// only for the home machine, a stop only for the others. -#[test] -fn guest_work_before_a_service_begins_marks_the_count_without_a_kick() { - let (hub, kicks, host, _first, mut second) = serving_pair(); - second.idle(|| 1000, 0, None); - let epoch = hub.lines_epoch(1); - host.store(1500, Ordering::SeqCst); - hub.lines_changed_unwoken(1); - hub.set_serving(1, Some(epoch)); - assert_eq!(kicks.load(Ordering::SeqCst), 0); - let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); - assert_eq!(watch.waited(1600), Some((super::Pending::Lines, Some(100)))); - hub.set_serving(1, None); - let epoch = hub.lines_epoch(1); - hub.requested.store(true, Ordering::SeqCst); - assert_eq!(hub.guest_pending(1, epoch), None, "PE 1 is not home"); - assert_eq!( - hub.guest_pending(0, hub.lines_epoch(0)), - Some(super::Pending::Forward) - ); - hub.requested.store(false, Ordering::SeqCst); - hub.stopped.store(true, Ordering::SeqCst); - assert_eq!(hub.guest_pending(1, epoch), Some(super::Pending::Stop)); - assert_eq!( - hub.guest_pending(0, hub.lines_epoch(0)), - None, - "home runs on" - ); -} - -/// A serving PE's line changes are guest work only while it takes a line: -/// running with IRQ and FIQ masked it takes none, waiting it is woken by -/// either. -#[test] -fn a_serving_pe_waits_for_a_line_change_only_while_it_takes_a_line() { - use super::super::tests::serving_timer; - use crate::machine::exception::{DAIF_F, DAIF_I}; - struct NoKick; - impl Kick for NoKick { - fn kick(&self, _pe: usize) {} - } - for (daif, wait, expected) in [ - (DAIF_I | DAIF_F, false, None), - (DAIF_I, false, Some(super::Pending::Lines)), - (0, false, Some(super::Pending::Lines)), - (DAIF_I | DAIF_F, true, Some(super::Pending::Lines)), - ] { - let mut machine = serving_timer(0, 0, daif); - let hub = Hub::new(1, NoKick); - hub.set_live(0, true); - machine.enter_parallel(Arc::clone(&hub)).unwrap(); - if wait { - machine.system_instruction(0xd503_207f).unwrap(); // wfi - assert!(machine.waiting.is_some()); - } - let pending = machine.serve_host(|machine| { - let watch = machine.guest_watch(); - hub.lines_changed_unwoken(0); - watch.pending(machine.host.now) - }); - assert_eq!(pending, expected, "DAIF {daif:#x}, waiting {wait}"); - } -} - -/// Registers at [`OWN`] served under their own lock: a read gives how many -/// writes came before it; a write of 1 raises PE 1's IRQ and of 0 lowers -/// it, each change queued for the board. -const OWN: u64 = 0x9000; - -#[derive(Default)] -struct OwnRegisters { - writes: AtomicU64, - queued: std::sync::Mutex>, -} - -impl super::super::OwnLockRegisters for OwnRegisters { - fn serves(&self, physical: u64) -> bool { - (OWN..OWN + 0x100).contains(&physical) - } - fn read(&self, _: usize, _: u64, _: u8, _: u64) -> super::super::OwnLockAccess { - super::super::OwnLockAccess { - result: Ok(self.writes.load(Ordering::SeqCst)), - queued: false, - } - } - fn write( - &self, - _: usize, - _: u64, - _: u8, - value: u64, - _: u64, - ) -> super::super::OwnLockAccess<()> { - self.writes.fetch_add(1, Ordering::SeqCst); - self.queued.lock().unwrap().push(value == 1); - super::super::OwnLockAccess { - result: Ok(()), - queued: true, - } - } -} - -/// A board whose only interrupt is [`OwnRegisters`]'s, to PE 1. -struct OwnBoard { - own: Arc, - irq: bool, - deliveries: usize, -} - -impl Devices for OwnBoard { - fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { - Ok(0) - } - fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { - Ok(()) - } - fn lines(&mut self, pe: usize, _: u64) -> Lines { - Lines { - irq: pe == 1 && self.irq, - ..Lines::default() - } - } - fn own_lock_registers(&self) -> Option> { - Some(Arc::clone(&self.own) as Arc) - } - fn deliver_own(&mut self) -> Result { - let queued = core::mem::take(&mut *self.own.queued.lock().unwrap()); - let Some(&last) = queued.last() else { - return Ok(false); - }; - self.irq = last; - self.deliveries += 1; - Ok(true) - } -} - -fn own_board() -> (SharedDevices, Arc) { - let (hub, _) = hub(2); - let own = Arc::new(OwnRegisters::default()); - let home = SharedDevices::new( - OwnBoard { - own: Arc::clone(&own), - irq: false, - deliveries: 0, - }, - hub, - ); - (home, own) -} - -/// An access under its device's own lock that changes no line takes no -/// board lock: it completes while another PE holds the board. One that -/// queues a line change waits for the board, which hands the change on and -/// tells the PE it reached before the access completes. -#[test] -fn an_own_lock_access_takes_the_board_only_to_hand_on_a_line_change() { - let (home, own) = own_board(); - let mut worker = home.worker(); - let board = Arc::clone(&home.board); - let hub = Arc::clone(home.hub()); - let held = board.devices.lock().unwrap(); - let (sent, received) = std::sync::mpsc::channel(); - let waiter = std::thread::spawn(move || { - let read = worker.read_scalar(0, OWN, 4, 10); - sent.send(matches!(read, ScalarRead::Served(Ok(0)))) - .unwrap(); - let written = worker.write_own(0, OWN + 4, 4, 1, 20); - sent.send(written == Some(Ok(()))).unwrap(); - worker - }); - let bound = std::time::Duration::from_secs(5); - assert_eq!( - received.recv_timeout(bound), - Ok(true), - "read beside the held board" - ); - // Bounded: the write queues its change within five seconds, then waits. - let deadline = std::time::Instant::now() + bound; - while own.writes.load(Ordering::SeqCst) == 0 { - assert!(std::time::Instant::now() < deadline, "the write never ran"); - std::thread::yield_now(); - } - assert!( - received - .recv_timeout(std::time::Duration::from_millis(50)) - .is_err(), - "the write waits for the board to hand its change on" - ); - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - drop(held); - assert_eq!(received.recv_timeout(bound), Ok(true)); - let mut worker = waiter.join().unwrap(); - assert!( - hub.inboxes[1].lines.load(Ordering::SeqCst) > epoch, - "PE 1 told" - ); - assert_eq!( - home.with(|devices| (devices.irq, devices.deliveries)), - (true, 1) - ); - // A read changes nothing on the board; a lowering write hands on again. - assert!(matches!( - worker.read_scalar(0, OWN, 4, 30), - ScalarRead::Served(Ok(1)) - )); - assert_eq!(worker.write(0, OWN + 4, 4, 0, 40), Ok(())); - assert_eq!( - home.with(|devices| (devices.irq, devices.deliveries)), - (false, 2) - ); - // Another address takes the board's own path. - assert_eq!(worker.write_own(0, 0x40, 4, 1, 50), None); -} - -/// Every hold of the board's lock begins by handing on what own-lock -/// accesses queued, and tells the PEs it reached, whatever its call: a -/// change queued before any other call is seen by that call. -#[test] -fn every_board_hold_hands_on_queued_line_changes_first() { - let (home, own) = own_board(); - let hub = Arc::clone(home.hub()); - // Queued by the device directly, as an access that has not reached - // the board yet would leave it. - own.queued.lock().unwrap().push(true); - let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); - assert_eq!( - home.with(|devices| (devices.irq, devices.deliveries)), - (true, 1) - ); - assert!( - hub.inboxes[1].lines.load(Ordering::SeqCst) > epoch, - "PE 1 told" - ); - // Nothing waits now: a hold hands on nothing. - assert_eq!(home.with(|devices| devices.deliveries), 1); -} +use super::super::LocalRegisters; +use super::*; +use core::sync::atomic::AtomicUsize; + +struct Kicks(Arc); +impl Kick for Kicks { + fn kick(&self, _pe: usize) { + self.0.fetch_add(1, Ordering::Relaxed); + } +} + +fn hub(pes: usize) -> (Arc, Arc) { + let kicks = Arc::new(AtomicUsize::new(0)); + let hub = Hub::new(pes, Kicks(Arc::clone(&kicks))); + for pe in 0..pes { + hub.set_live(pe, true); + } + // Every PE but the first, which a test's machine may be, runs a block + // (`Hub::enter_active`): a broadcast waits for it. + for pe in 1..pes { + assert!(hub.enter_active(pe)); + } + (hub, kicks) +} + +fn tlbi(kind: crate::machine::system::TlbiKind, operand: u64) -> Maintenance { + use crate::machine::system::{Regime, Tlbi, TlbiAttr, TlbiLevel}; + Maintenance::Tlb(tlbi::Scope::new( + &Tlbi { + kind, + regime: Regime::EL10, + vmid: None, + broadcast: Broadcast::ISH, + level: TlbiLevel::Any, + attr: TlbiAttr::AllAttr, + operand, + }, + tlbi::Context::default(), + )) +} + +/// A TLBI of another context leaves its mail for the PE's next read, and +/// neither interrupts it nor waits for it. +#[test] +fn a_tlbi_passes_by_a_pe_translating_another_context() { + use crate::machine::system::TlbiKind::{ASID, VA, VAA}; + const ASID_5: u64 = 5 << 48; + let (hub, _) = hub(2); + let inbox = &hub.inboxes[1]; + let word = context_word(mmu::Regime::El10, 7); + let epoch = || inbox.chain.interrupt_epoch().load(Ordering::Relaxed); + assert_eq!( + hub.broadcast(0, &[tlbi(ASID, ASID_5)]).len(), + 1, + "unpublished" + ); + inbox.translating.store(word, Ordering::Relaxed); + let interrupts = epoch(); + let passes = [ASID_5, ASID_5 | 0x1234]; + for (kind, operand) in [ASID, VA].into_iter().zip(passes) { + assert!(hub.broadcast(0, &[tlbi(kind, operand)]).is_empty()); + } + assert_eq!(epoch(), interrupts); + assert!(hub.pending(1)); + assert_eq!(hub.take(1).unwrap().maintenance.len(), 3); + assert_eq!( + hub.broadcast(0, &[tlbi(ASID, 7 << 48)]).len(), + 1, + "its context" + ); + assert_eq!( + hub.broadcast(0, &[tlbi(VAA, 0x1234)]).len(), + 1, + "every ASID" + ); + assert!(inbox.lower_globals.widen(0x123_0000, 0x123_ffff)); + assert!(!inbox.lower_globals.widen(0x123_4000, 0x123_7fff)); + assert_eq!( + hub.broadcast(0, &[tlbi(VA, ASID_5 | 0x1234)]).len(), + 1, + "its global page" + ); + assert!(hub.broadcast(0, &[tlbi(VA, ASID_5 | 0x4321)]).is_empty()); +} + +/// What a PE translates is published before its next mail read. +#[test] +fn a_pe_publishes_the_context_it_translates() { + use super::super::tests::machine; + let mut machine = machine(&[0xd503_201f]); + let (hub, _) = hub(1); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + assert_eq!( + hub.inboxes[0].translating.load(Ordering::Relaxed), + ANY_CONTEXT + ); + machine.sync_host_regime(super::super::step_timing::SyncSource::Other); + let controls = machine.cpu.controls(machine.cpu.regime()); + assert_eq!( + hub.inboxes[0].translating.load(Ordering::Relaxed), + context_word(controls.regime, mmu::current_asid(&controls)) + ); +} + +#[test] +fn duplicate_safe_attachment_refuses_without_replacing_the_live_owner() { + use super::super::tests::{BASE, board}; + use crate::machine::NoDevices; + use stela_contracts::identity::Identity; + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut first = board(&[], NoDevices, identities.clone()); + let mut second = board(&[], NoDevices, identities); + let (hub, _) = hub(1); + first.enter_parallel(Arc::clone(&hub)).unwrap(); + let epoch = first.attached.as_ref().unwrap().epoch; + let untouched = second.chain.snapshot(); + assert_eq!( + second.enter_parallel(Arc::clone(&hub)), + Err(ParallelAdmissionError::PeOwned { pe: 0 }) + ); + assert!(second.parallel.is_none() && second.attached.is_none()); + assert_eq!(second.chain.snapshot(), untouched); + assert_eq!( + first.enter_parallel(Arc::clone(&hub)), + Err(ParallelAdmissionError::MachineAttached) + ); + first.chain.finish(17); + hub.interrupt(0); + assert_eq!(first.chain.account().0, 17); + let pending = first.chain.snapshot(); + assert_ne!(pending.interrupt_epoch, pending.observed_interrupt_epoch); + assert_eq!(pending.quiet, stela_compiler::x86_64::chain::Quiet(0)); + drop(first); + second.enter_parallel(Arc::clone(&hub)).unwrap(); + assert!(second.attached.as_ref().unwrap().epoch > epoch); + assert_eq!(second.cpu.pc, BASE); +} + +#[test] +fn an_interrupt_borrow_survives_detach_and_reuse_without_a_raw_pointer_lease() { + use std::sync::mpsc; + let (hub, _) = hub(1); + let weak = Arc::downgrade(&hub.inboxes[0].chain); + let (attached, mut control) = Attached::new(&hub, 0, false).unwrap(); + control.initialize(11, 14, [12, 13], [0xffff, 0xfff]); + control.begin(9, 99); + let (ready_tx, ready_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + let foreign = Arc::clone(&hub); + let reader = std::thread::spawn(move || { + let chain = &foreign.inboxes[0].chain; + ready_tx.send(()).unwrap(); + resume_rx.recv().unwrap(); + chain.notify(); + }); + ready_rx.recv().unwrap(); + drop(attached); + assert_ne!( + hub.inboxes[0].owner.load(Ordering::Acquire), + 0, + "the control owner retains the claim" + ); + drop(control); + assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), 0); + assert!( + weak.upgrade().is_some(), + "hub retains the physical allocation" + ); + let (next, mut control) = Attached::new(&hub, 0, false).unwrap(); + control.initialize(21, 24, [22, 23], [0xffff, 0xfff]); + control.begin(2, 77); + resume_tx.send(()).unwrap(); + reader.join().unwrap(); + let snapshot = control.snapshot(); + assert_eq!( + ( + control.account().budget(), + control.account().retired(), + snapshot.hits, + snapshot.linked + ), + (77, 0, 0, 0) + ); + assert_eq!( + (snapshot.block, snapshot.table, snapshot.contexts), + (2, 21, [22, 23]) + ); + assert_ne!(snapshot.interrupt_epoch, snapshot.observed_interrupt_epoch); + assert_eq!(snapshot.quiet, stela_compiler::x86_64::chain::Quiet(0)); + assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), next.epoch); + drop(control); + drop(next); + drop(hub); + assert!( + weak.upgrade().is_none(), + "last hub/owner releases the allocation" + ); +} + +#[test] +fn a_populated_machine_keeps_its_code_as_it_adopts_a_hub_control() { + use super::super::tests::{BASE, machine}; + use stela_compiler::block::ExitKind; + let mut machine = machine(&[0x9100_0400, 0x1400_0002, 0, 0x9100_0400, 0x17ff_fffc]); + let direct = |next_pc| super::super::NativeExit::Exit { + next_pc, + kind: ExitKind::Direct as u64, + }; + machine.host.exits = vec![direct(BASE + 12), direct(BASE), direct(BASE + 12)]; + machine.step().unwrap(); + machine.step().unwrap(); + machine.step().unwrap(); + assert_eq!(machine.statistics.links, 2); + let (blocks, installed) = (machine.code.blocks.len(), machine.host.installed.len()); + let contexts = machine.chain.contexts(); + let old_address = machine.chain.address(); + let old_storage = machine.chain.weak_storage(); + let (hub, _) = hub(1); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + assert_ne!(machine.chain.address(), old_address); + assert!(old_storage.upgrade().is_none()); + // Code finds the control through the frame, which the next entry sets. + assert_eq!(machine.chain.contexts(), contexts); + assert_eq!( + (machine.code.blocks.len(), machine.host.installed.len()), + (blocks, installed) + ); + assert_eq!( + machine.anchors()[stela_compiler::Anchor::Control], + machine.chain.address() + ); +} + +#[test] +fn repeated_owner_reuse_keeps_remote_epoch_writes_disjoint() { + use core::sync::atomic::AtomicBool; + use std::sync::Barrier; + let (hub, _) = hub(1); + let started = Arc::new(Barrier::new(2)); + let done = Arc::new(AtomicBool::new(false)); + let foreign = Arc::clone(&hub); + let worker_started = Arc::clone(&started); + let worker_done = Arc::clone(&done); + let interrupt = std::thread::spawn(move || { + worker_started.wait(); + while !worker_done.load(Ordering::Acquire) { + foreign.interrupt(0); + } + }); + started.wait(); + let mut last = 0; + for index in 0..1000 { + let (attached, mut control) = Attached::new(&hub, 0, false).unwrap(); + assert!(attached.epoch > last); + last = attached.epoch; + control.initialize(index, index + 3, [index + 1, index + 2], [0xffff, 0xfff]); + control.begin(index as usize, 31); + let state = control.snapshot(); + assert_eq!( + (state.block, state.table, state.itlb, state.contexts), + (index, index, index + 3, [index + 1, index + 2]) + ); + drop(attached); + drop(control); + } + done.store(true, Ordering::Release); + interrupt.join().unwrap(); + assert_eq!(hub.inboxes[0].owner.load(Ordering::Acquire), 0); +} + +#[test] +fn parallel_pes_refuse_independent_idle_leaps() { + use super::super::tests::{BASE, board}; + use {crate::machine::engine::NoDevices, stela_contracts::identity::Identity}; + + let identities = (0..2) + .map(|pe| Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000 | pe << 8, + clock: None, + caches: None, + }) + .collect::>(); + let mut home = board(&[], NoDevices, identities.clone()); + let prepared = board(&[], NoDevices, identities); + let mut worker = home + .worker_profile() + .start(prepared.cpu, prepared.host, prepared.devices, 1) + .unwrap(); + assert!(Arc::ptr_eq(&home.admit_table, &worker.admit_table)); + home.set_idle_skip(true).unwrap(); + let (hub, _) = hub(2); + home.enter_parallel(Arc::clone(&hub)).unwrap(); + worker + .start_parallel(hub, home.cpu.core_locks.clone(), BASE) + .unwrap(); + for machine in [&mut home, &mut worker] { + assert!(!machine.idle_skip); + assert_eq!( + machine.set_idle_skip(true), + Err("idle skipping requires all PEs to share one scheduler") + ); + assert!(!machine.idle_skip); + machine.set_idle_skip(false).unwrap(); + machine.host.now = 1000; + } + assert_eq!(home.now(), worker.now()); + home.host.now = 2000; + worker.host.now = 2000; + assert_eq!(home.now(), worker.now()); +} + +#[test] +fn edited_cpu_profile_keeps_its_own_admission_policy() { + use super::super::tests::machine_on; + use crate::machine::{identification, registers::encodings::ID_AA64ISAR1_EL1}; + use stela_contracts::Chip; + + const SMMLA: u32 = 0x4e9b_a781; + let chip = Chip::AppleM2; + let mut home = machine_on(chip, &[]); + assert_eq!(home.admit_table.admit(SMMLA), SMMLA); + home.profile.fixed = + identification::derive(chip, home.target, true, identification::Speculation::NONE); + for (register, value) in &mut home.profile.fixed { + if *register == ID_AA64ISAR1_EL1 { + *value &= !(0xf << 52); + } + } + let worker = home.worker_profile(); + assert!(!Arc::ptr_eq(&home.admit_table, &worker.admit_table)); + assert_eq!(worker.admit_table.admit(SMMLA), 0); +} + +#[test] +fn source_observation_uses_only_the_attached_owner_and_remains_stale() { + use super::super::tests::{BASE, board}; + use crate::machine::engine::NoDevices; + use stela_contracts::identity::Identity; + + let identities = (0..2) + .map(|pe| Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000 | pe << 8, + clock: None, + caches: None, + }) + .collect::>(); + let mut home = board(&[], NoDevices, identities.clone()); + let prepared = board(&[], NoDevices, identities); + let mut worker = Machine::new_at( + prepared.cpu, + prepared.host, + prepared.devices, + prepared.profile, + prepared.target, + 1, + ) + .unwrap(); + let (hub, kicks) = hub(2); + home.enter_parallel(Arc::clone(&hub)).unwrap(); + worker + .start_parallel(Arc::clone(&hub), home.cpu.core_locks.clone(), BASE) + .unwrap(); + let reads = worker.host.counter_reads; + worker.observe_parallel_source(SourcePhase::SliceEnter); + assert_eq!( + worker.host.counter_reads, reads, + "disabled path reads no counter" + ); + assert_eq!(hub.source_observation(1), None, "default off"); + hub.set_source_observations(true); + worker.cpu.pc = BASE + 4; + worker.cpu.state.sp = 0x8000; + worker.cpu.state.x[29] = 0x8010; + worker.cpu.state.x[30] = BASE + 8; + worker.cpu.pstate.daif = 3; + worker.host.now = 1000; + let before = worker.cpu.state.clone(); + let counts = worker.counts(); + let sent = kicks.load(Ordering::Relaxed); + worker.observe_parallel_source(SourcePhase::BroadcastEnter); + let first = hub.source_observation(1).unwrap(); + assert_eq!(first.sequence, 2); + assert_eq!( + first.source, + MaterializedSource { + host_counter: 1000, + phase: SourcePhase::BroadcastEnter, + pc: BASE + 4, + sp: 0x8000, + fp: 0x8010, + lr: BASE + 8, + el: 2, + daif: 3, + } + ); + assert_eq!(worker.cpu.state, before); + assert_eq!(worker.counts(), counts); + assert_eq!(kicks.load(Ordering::Relaxed), sent); + assert_eq!(hub.source_observation(0), None); + assert_eq!(hub.source_observation(2), None); + assert_eq!(hub.source_observation(usize::MAX), None); + + // A caller cannot select another slot: attachment is private and + // publication refuses a mismatched current-PE image. + worker.current = 0; + worker.observe_parallel_source(SourcePhase::SliceExit); + assert_eq!(hub.source_observation(0), None); + assert_eq!(hub.source_observation(1), Some(first)); + worker.current = 1; + worker.cpu.pc = BASE + 16; + worker.host.now = 2000; + assert_eq!( + hub.source_observation(1), + Some(first), + "no implicit refresh" + ); + worker.observe_parallel_source(SourcePhase::SliceExit); + let second = hub.source_observation(1).unwrap(); + assert_eq!(second.sequence, 4); + assert_eq!(second.source.pc, BASE + 16); + assert_eq!(second.source.host_counter, 2000); + hub.set_source_observations(false); + worker.observe_parallel_source(SourcePhase::ParkEnter); + assert_eq!(hub.source_observation(1), None); + hub.set_source_observations(true); + assert_eq!(hub.source_observation(1), Some(second)); + + // Real boundary hooks publish once at entry and once on return, not + // on each wait-loop spin. A PE that stops reading mail needs not + // acknowledge what was posted to it. + home.post(Maintenance::Code(None)); + home.send_outgoing(); + hub.set_live(1, false); + home.complete_maintenance().unwrap(); + let broadcast = hub.source_observation(0).unwrap(); + assert_eq!(broadcast.sequence, 4); + assert_eq!(broadcast.source.phase, SourcePhase::BroadcastExit); + home.device_transfer(0).unwrap(); + let dma = hub.source_observation(0).unwrap(); + assert_eq!(dma.sequence, 8); + assert_eq!(dma.source.phase, SourcePhase::DeviceAdvanceExit); + assert_eq!(hub.source_observation(1), Some(second)); + + drop(worker); + assert_eq!(hub.source_observation(1), None, "detached owner"); + let (_new_owner, _control) = Attached::new(&hub, 1, false).unwrap(); + assert_eq!(hub.source_observation(1), None, "replacement has no copy"); +} + +/// A machine of PE 0 of two in `hub`, running `words`. +fn first_of_two( + words: &[u32], + hub: &Arc, +) -> Machine { + use stela_contracts::identity::Identity; + let identities = (0..2) + .map(|pe| Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000 | pe << 8, + clock: None, + caches: None, + }) + .collect::>(); + let mut machine = super::super::tests::board(words, crate::machine::NoDevices, identities); + machine.enter_parallel(Arc::clone(hub)).unwrap(); + machine +} + +#[test] +fn broadcast_profile_counts_posts_and_completion_waits_for_the_attached_owner() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[0xd503_201f], &hub); + // Unobserved, a post reads no clock; the completion reads its two. + let reads = machine.host.counter_reads; + machine.post(Maintenance::Code(None)); + assert_eq!(machine.host.counter_reads, reads); + machine.send_outgoing(); + hub.set_live(1, false); + machine.complete_maintenance().unwrap(); + assert_eq!(machine.host.counter_reads - reads, 2); + assert!(hub.broadcast_profile(0).is_none()); + + hub.set_source_observations(true); + hub.set_live(1, true); + let reads = machine.host.counter_reads; + machine.post(Maintenance::Code(Some(0x4000))); + machine.post(Maintenance::Code(Some(0x4000))); + machine.send_outgoing(); + hub.set_live(1, false); + machine.complete_maintenance().unwrap(); + // A clock for the posts, and the completion's two and its two source + // observations; accounting adds no native notification. + assert_eq!(machine.host.counter_reads - reads, 5); + let observed = hub.broadcast_profile(0).unwrap(); + let code = observed.kinds[BroadcastKind::Code.index()]; + assert_eq!( + (code.started, code.completed, code.recipients, code.polls), + (2, 2, 2, 0) + ); + let completion = observed.kinds[BroadcastKind::Completion.index()]; + assert_eq!( + ( + completion.started, + completion.completed, + completion.recipients + ), + (1, 1, 1) + ); + assert_eq!((observed.active, observed.dropped_updates), (None, false)); + // PE 1 posted nothing. + let idle = hub.broadcast_profile(1).unwrap(); + assert!(idle.kinds.iter().all(|counts| counts.started == 0)); + + // With nothing posted, a completion waits for nothing. + let reads = machine.host.counter_reads; + machine.complete_maintenance().unwrap(); + assert_eq!(machine.host.counter_reads, reads); + + hub.set_live(1, true); + let attached = machine.attached.take().unwrap(); + machine.post(Maintenance::Code(None)); + machine.send_outgoing(); + hub.set_live(1, false); + machine.complete_maintenance().unwrap(); + assert_eq!(hub.broadcast_profile(0), Some(observed)); + machine.attached = Some(attached); +} + +/// A PE waiting for others' acknowledgements answers the host at each turn +/// of the wait: a processor that waits on this one, as a TLB shootdown +/// does, gets its answer, so the two waits cannot deadlock. +#[test] +fn a_completion_wait_answers_the_host_each_turn() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.send_outgoing(); + let other = Arc::clone(&hub); + // PE 1 acknowledges only once this one has relaxed three times. + machine.host.on_relax = Some(Box::new(move |turns| { + if turns == 3 { + let mail = other.take(1).expect("posted mail"); + other.acknowledge(1, mail.serial); + } + })); + machine.complete_maintenance().unwrap(); + assert_eq!(machine.host.relaxes, 3); +} + +/// A wait for a PE that does not apply posted maintenance past its bound +/// is reported once, naming that PE and where it is, and goes on: it ends +/// normally once the PE applies the maintenance. +#[test] +fn a_completion_wait_past_its_bound_is_reported_once_and_goes_on() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.send_outgoing(); + let limit = machine.profile.counter_frequency / super::MAINTENANCE_WAIT_DIVISOR; + // Each turn reads the counter a step later: the bound passes at about + // the eighth turn, and PE 1 applies at the 40th. + machine.host.counter_step = limit / 8; + let other = Arc::clone(&hub); + machine.host.on_relax = Some(Box::new(move |turns| { + if turns == 40 { + let mail = other.take(1).expect("posted mail"); + other.acknowledge(1, mail.serial); + } + })); + let degraded = machine.statistics.degraded; + machine.complete_maintenance().unwrap(); + assert_eq!(machine.host.relaxes, 40, "waited until PE 1 applied"); + assert!(machine.posted.is_empty()); + assert_eq!(machine.statistics.degraded, degraded + 1); + let reports = machine.take_unmodeled(); + assert_eq!(reports.len(), 1, "once: {reports:?}"); + let RequirementKind::MaintenanceOverrun { + pe, + serial, + unapplied, + state, + ticks, + } = reports[0].kind + else { + panic!("expected a maintenance overrun, got {:?}", reports[0].kind); + }; + assert_eq!( + (pe, serial, unapplied, state), + (1, 1, 1, super::super::PeState::Running) + ); + assert!((limit..2 * limit).contains(&ticks), "{ticks} of {limit}"); + assert!( + reports[0] + .to_string() + .contains("maintenance overrun: PE 1 (running)") + ); + + // A wait within its bound reports nothing. + machine.host.on_relax = None; + machine.host.counter_step = 0; + machine.post(Maintenance::Code(Some(0x8000))); + machine.send_outgoing(); + let mail = hub.take(1).expect("posted mail"); + hub.acknowledge(1, mail.serial); + machine.complete_maintenance().unwrap(); + assert!(machine.take_unmodeled().is_empty()); +} + +#[test] +fn maintenance_waits_for_the_dsb_and_reaches_a_pe_in_one_piece_of_mail() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.post(Maintenance::Code(Some(0x8000))); + assert!(hub.take(1).is_none()); + + machine.send_outgoing(); + hub.set_live(1, false); + machine.complete_maintenance().unwrap(); + let mail = hub.take(1).unwrap(); + assert_eq!(mail.maintenance.len(), 2); + assert_eq!(mail.serial, 1); +} + +#[test] +fn a_broadcast_passes_by_a_pe_outside_its_run() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + // PE 0 runs a block. + assert!(hub.enter_active(0)); + let posted = hub.broadcast(1, &[Maintenance::Code(None)]); + assert!(!hub.applied(&mut posted.clone())); + machine.outside_run(|_| assert!(hub.applied(&mut posted.clone()))); + assert!(!hub.applied(&mut posted.clone())); + hub.leave_active(0); +} + +#[test] +fn a_full_list_of_maintenance_goes_out_without_a_dsb() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + for page in 0..OUTGOING as u64 { + machine.post(Maintenance::Code(Some(page << 14))); + } + assert_eq!(hub.take(1).unwrap().maintenance.len(), OUTGOING); +} + +#[test] +fn a_page_invalidation_the_pe_has_yet_to_read_covers_the_same_page_again() { + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.post(Maintenance::Code(Some(0x4000))); + machine.post(Maintenance::Code(Some(0x8000))); + machine.post(Maintenance::Code(None)); + machine.post(Maintenance::Code(Some(0xc000))); + machine.send_outgoing(); + let mail = hub.take(1).unwrap(); + let pages: Vec<_> = mail + .maintenance + .iter() + .map(|maintenance| match maintenance { + Maintenance::Code(page) => *page, + _ => unreachable!(), + }) + .collect(); + assert_eq!(pages, [Some(0x4000), Some(0x8000), None]); + // The PE's acknowledgment of this mail is the one waited for. + assert_eq!((mail.serial, machine.posted.as_slice()), (1, &[(1, 1)][..])); +} + +/// A PE that reads no mail for a long time, asleep or powered down, holds +/// at most [`MAIL_TLB_SCOPES`] TLB scopes and [`MAIL_SCOPES`] code pages: +/// past them, scopes that merge with none of the last kept ones and code +/// pages make one invalidation of everything of that kind. +#[test] +fn mail_for_a_pe_that_does_not_read_it_stays_bounded() { + use crate::machine::system::TlbiKind::ASID; + let (hub, _) = hub(2); + for page in 0..10_000u64 { + hub.broadcast( + 0, + &[ + tlbi(ASID, (page % 200) << 48), + Maintenance::Code(Some(page << 14)), + ], + ); + } + let mail = hub.take(1).unwrap(); + let count = + |kind: fn(&Maintenance) -> bool| mail.maintenance.iter().filter(|m| kind(m)).count(); + assert!( + mail.maintenance.len() <= MAIL_TLB_SCOPES + MAIL_SCOPES + 2, + "{}", + mail.maintenance.len() + ); + assert_eq!(count(|m| matches!(m, Maintenance::TlbAll)), 1); + assert_eq!(count(|m| matches!(m, Maintenance::Code(None))), 1); + // What follows a whole invalidation is covered by it. + assert_eq!(count(|m| matches!(m, Maintenance::Tlb(_))), 0); + assert_eq!(count(|m| matches!(m, Maintenance::Code(Some(_)))), 0); +} + +/// A run of TLBIs by page, as XNU's and SPTM's loops send them, merges +/// into one range a sleeping PE applies at once: no invalidation of +/// everything, and the kernel's contexts outlive it. +/// A PE counts how long its TLB mail waited, from the first post it had +/// not read to the read, and how long its native run, when one was going, +/// took of that to return; then the apply. Later posts of the same mail +/// keep the first's time. +#[test] +fn a_pe_times_its_tlb_mail_from_the_first_post_to_the_read() { + use super::super::reports::MailWait; + use crate::machine::system::TlbiKind::VAA; + let clock = Arc::new(AtomicUsize::new(1)); + let hub = Hub::new(2, Ticks(Arc::clone(&clock))); + for pe in 0..2 { + hub.set_live(pe, true); + } + // NOP. + let mut machine = first_of_two(&[0xd503_201f], &hub); + let waits = |machine: &Machine<_, _>| machine.statistics.mail_waits; + // Mail read between runs: all of its wait is the engine's. + hub.broadcast(1, &[tlbi(VAA, 0x10_0000)]); + hub.broadcast(1, &[tlbi(VAA, 0x10_0001)]); + machine.read_mail().unwrap(); + let counted = waits(&machine); + assert_eq!(counted[MailWait::Count as usize], 1); + assert!(counted[MailWait::Latency as usize] >= 2); + assert_eq!(counted[MailWait::Native as usize], 0); + assert_eq!( + counted[MailWait::Exit as usize], + counted[MailWait::Latency as usize] + ); + assert!(counted[MailWait::Apply as usize] >= 1); + assert_eq!( + counted[MailWait::Longest as usize], + counted[MailWait::Latency as usize] + ); + // Mail posted while a native run goes on: its return counts apart. + let pc = machine.cpu.pc; + let Ok(super::super::Fetched::Block(index)) = machine.fetch_block(pc, false) else { + panic!("a block"); + }; + hub.broadcast(1, &[tlbi(VAA, 0x20_0000)]); + machine.host.exits = vec![super::super::NativeExit::Exit { + next_pc: pc + 4, + kind: stela_compiler::block::ExitKind::Fallthrough as u64, + }]; + let budget = machine.chain_budget(); + machine.execute(index, budget).unwrap(); + machine.read_mail().unwrap(); + let after = waits(&machine); + assert_eq!(after[MailWait::Count as usize], 2); + let native = after[MailWait::Native as usize]; + assert!(native >= 1); + assert!(native < after[MailWait::Latency as usize] - counted[MailWait::Latency as usize]); + // Nothing waits after the read. + machine.read_mail().unwrap(); + assert_eq!(waits(&machine), after); +} + +#[test] +fn a_run_of_tlbis_by_page_merges_into_one_range() { + use crate::machine::system::TlbiKind::{VA, VAA}; + let (hub, _) = hub(2); + for page in 0..10_000u64 { + hub.broadcast(0, &[tlbi(VAA, 0x10_0000 + page)]); + } + // Pages of one ASID in the upper half, one apart: another range. + for page in 0..100u64 { + hub.broadcast(0, &[tlbi(VA, 7 << 48 | (0xfff_ff00_0000 + 2 * page))]); + } + let mail = hub.take(1).unwrap(); + assert_eq!(mail.merged, 10_000 - 1 + 100 - 1); + let [Maintenance::Tlb(lower), Maintenance::Tlb(upper)] = mail.maintenance[..] else { + panic!("two ranges: {:?}", mail.maintenance); + }; + assert_eq!( + lower.span(), + Some((0x1_0000_0000, 0x1_0000_0000 + 9_999 * 0x1000)) + ); + assert_eq!(lower.named_asid(), None); + let upper_first = mmu::tlbi::canonical(0xfff_ff00_0000 << 12); + assert_eq!( + upper.span(), + Some((upper_first, upper_first + 198 * 0x1000)) + ); + assert_eq!(upper.named_asid(), Some(7)); +} + +/// Pages of two processes at the same VAs (the shared cache's) stay two +/// ranges, one per ASID, rather than one of every ASID that would drop +/// those VAs in every process's lookup contexts; a page of every ASID +/// merges with neither. A full mailbox may merge them all the same. +#[test] +fn mail_merges_tlbis_of_different_asids_only_when_full() { + use crate::machine::system::TlbiKind::{VA, VAA}; + let (first, _) = hub(2); + for page in 0..8u64 { + for asid in [7u64, 8] { + first.broadcast(0, &[tlbi(VA, asid << 48 | (0x18_0000 + page))]); + } + } + first.broadcast(0, &[tlbi(VAA, 0x18_0004)]); + let mail = first.take(1).unwrap(); + let scopes: Vec<_> = mail + .maintenance + .iter() + .map(|posted| match posted { + Maintenance::Tlb(scope) => (scope.named_asid(), scope.span()), + other => panic!("{other:?}"), + }) + .collect(); + let range = Some((0x1_8000_0000, 0x1_8000_0000 + 7 * 0x1000)); + assert_eq!( + scopes, + [ + (Some(7), range), + (Some(8), range), + (None, Some((0x1_8000_4000, 0x1_8000_4000))) + ] + ); + assert_eq!(mail.merged, 2 * 7); + // Past the kept scopes, any of the last ones takes the next. + let (hub, _) = hub(2); + for page in 0..super::MAIL_TLB_SCOPES as u64 { + hub.broadcast(0, &[tlbi(VAA, 0x10_0000 + 32 * page)]); + } + hub.broadcast(0, &[tlbi(VA, 7 << 48 | 0x10_0001)]); + let mail = hub.take(1).unwrap(); + assert_eq!(mail.maintenance.len(), super::MAIL_TLB_SCOPES); +} + +/// Whatever TLBIs a PE's mail keeps or merges, every entry one of them +/// removes, the kept scopes remove: by [`tlbi::Scope::covers`], and by +/// what the PE's ITLB and shadow apply ([`tlbi::Scope::everywhere`], +/// [`tlbi::Scope::reach`], [`tlbi::Scope::named_asid`]). +#[test] +fn merged_mail_removes_every_entry_its_tlbis_remove() { + use crate::machine::system::TlbiKind::{RVA, RVAA, VA, VAA}; + let mut seed = 0x1234_5678_9abc_def0u64; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for round in 0..40 { + let mut mail = Mail::default(); + // Half the rounds for a PE with global pages around the lower + // half's third place, which merges go around. + let globals = (round / 3 % 2 == 1).then_some(Globals { + first: 2 << 36, + last: (3 << 36) - 1, + leaf: 0x4000, + }); + let mut sent = Vec::new(); + let count = [20, 300, 2000][round % 3]; + for _ in 0..count { + let draw = next(); + let asid = (draw >> 8) % 4; + // Pages of four places in each half, 4 KiB apart. + let place = (draw >> 16) % 4; + let upper = if draw >> 20 & 1 != 0 { + 0xf_ffff_0000_0000 + } else { + 0 + }; + let page = upper | place << 24 | ((draw >> 24) % 64); + let kind = [VA, VAA, RVA, RVAA][(draw % 4) as usize]; + let operand = match kind { + // TG 4 KiB, SCALE 0, NUM 1: four pages from BaseADDR. + RVA | RVAA => { + let base = (canonical_page(page) >> 12) & ((1 << 37) - 1); + asid << 48 | 1 << 46 | 1 << 39 | base + } + _ => asid << 48 | page & ((1 << 44) - 1), + }; + let Maintenance::Tlb(scope) = tlbi(kind, operand) else { + unreachable!() + }; + sent.push(scope); + mail.keep(Maintenance::Tlb(scope), globals); + } + let all = mail + .maintenance + .iter() + .any(|kept| matches!(kept, Maintenance::TlbAll)); + let kept: Vec = mail + .maintenance + .iter() + .filter_map(|kept| match kept { + Maintenance::Tlb(scope) => Some(*scope), + _ => None, + }) + .collect(); + assert!(kept.len() <= MAIL_TLB_SCOPES); + assert_eq!(kept.len() + mail.merged as usize, sent.len(), "{all}"); + // Entries at and around every sent page, of every size and ASID. + for scope in &sent { + let (first, last) = scope.span().unwrap(); + for address in [first, last, first.wrapping_sub(0x1000), last + 0x1000] { + for (size_bits, granule_bits, level) in [(12, 12, 3), (14, 14, 3), (21, 12, 2)] { + for asid in [None, Some(0), Some(1), Some(3)] { + let entry = tlbi::Entry { + regime: mmu::Regime::El10, + vmid: None, + asid, + address: address & ((1 << 56) - 1), + size_bits, + granule_bits, + level, + stage1: true, + stage2: false, + table: false, + }; + if !scope.covers(&entry) { + continue; + } + assert!( + all || kept.iter().any(|kept| kept.covers(&entry)), + "{scope:?} removes {entry:x?}, no kept scope does" + ); + } + } + } + // What the ITLB and shadow apply: a span holding the sent one, + // of its ASID or of every ASID. + let holds = |kept: &tlbi::Scope| { + let (kept_first, kept_last) = kept.span().unwrap(); + kept_first <= first + && last <= kept_last + && kept + .named_asid() + .is_none_or(|asid| scope.named_asid() == Some(asid)) + }; + assert!(all || kept.iter().any(holds), "{scope:?}"); + } + } +} + +/// The canonical VA of 4 KiB page number `page`. +fn canonical_page(page: u64) -> u64 { + mmu::tlbi::canonical(page << 12) +} + +/// A process's TLBIs by page below and above a PE's global pages (its +/// image and stacks, its heaps, around the shared cache) never merge into +/// one range across them while a merge on one side can take them, full +/// mailbox or not: the PE's shared pages' entries outlive them. Every sent +/// scope is still held by a kept one of its ASID, and the mailbox keeps no +/// more scopes than before. +#[test] +fn a_mailbox_merges_no_scope_across_the_pes_global_pages() { + use crate::machine::system::TlbiKind::VA; + const GLOBALS: Globals = Globals { + first: 0x1_8000_0000, + last: 0x2_7fff_ffff, + leaf: 0x4000, + }; + const BELOW: u64 = 0x1_0000_0000; + const ABOVE: u64 = 0x6_0000_0000; + let mut mail = Mail::default(); + let mut sent = Vec::new(); + // Bursts above, each followed by one page below: the last kept scopes + // are all above when the page below comes. + for n in 0..4 * MAIL_TLB_SCOPES as u64 { + let va = if n % 20 == 19 { + BELOW + n * 0x10_0000 + } else { + ABOVE + n * 0x10_0000 + }; + let Maintenance::Tlb(scope) = tlbi(VA, 9 << 48 | va >> 12) else { + unreachable!() + }; + sent.push(scope); + mail.keep(Maintenance::Tlb(scope), Some(GLOBALS)); + } + let kept: Vec = mail + .maintenance + .iter() + .map(|kept| match kept { + Maintenance::Tlb(scope) => *scope, + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(kept.len(), MAIL_TLB_SCOPES); + assert_eq!(kept.len() + mail.merged as usize, sent.len()); + for scope in &kept { + let (first, last) = scope.span().unwrap(); + assert!(last < GLOBALS.first || first > GLOBALS.last, "{scope:x?}"); + assert_eq!(scope.named_asid(), Some(9)); + } + for scope in &sent { + let (first, last) = scope.span().unwrap(); + assert!( + kept.iter().any(|kept| { + let (kept_first, kept_last) = kept.span().unwrap(); + kept_first <= first && last <= kept_last + }), + "{scope:x?}" + ); + } + // Without global pages, or when every merge bridges them, the + // narrowest merge of the last kept scopes takes the page, as before. + let mut mail = Mail::default(); + for n in 0..MAIL_TLB_SCOPES as u64 { + mail.keep( + tlbi(VA, 9 << 48 | (ABOVE + n * 0x10_0000) >> 12), + Some(GLOBALS), + ); + } + mail.keep(tlbi(VA, 9 << 48 | BELOW >> 12), Some(GLOBALS)); + assert_eq!(mail.maintenance.len(), MAIL_TLB_SCOPES); + assert_eq!(mail.merged, 1); + // Until full, merges reach at most three granules across, global pages + // or not, and runs of pages among global pages merge as before. + let mut mail = Mail::default(); + for va in [0x1_7fff_f000, 0x1_8000_4000, 0x1_8000_5000, 0x1_8000_8000] { + mail.keep(tlbi(VA, 9 << 48 | va >> 12), Some(GLOBALS)); + } + assert_eq!((mail.maintenance.len(), mail.merged), (1, 3)); +} + +/// A merge bridges a PE's global pages at the granule of the smallest +/// global leaf it took: of 4 KiB leaves, the merge of TLBIs of the pages at +/// 0x1000 and 0x3000 takes in the global page at 0x2000, which neither TLBI +/// reaches; of 16 KiB leaves, both TLBIs reach the leaf that holds all +/// three, and the merge adds nothing. +#[test] +fn a_merge_bridges_global_pages_at_the_pes_smallest_global_leaf() { + let span = GlobalSpan::new(); + assert!(span.now().is_none()); + assert!(span.widen(0, 0x3fff)); + let large = span.now(); + assert_eq!(large.map(|globals| globals.leaf), Some(0x4000)); + for (held, new) in [(0x1000, 0x3000), (0x3000, 0x1000), (0, 0x4000)] { + assert!( + !bridges(large, (held, held), (new, new)), + "{held:#x} {new:#x}" + ); + } + // A 16 KiB global leaf between the two TLBIs' leaves is a bridge. + assert!(!bridges(large, (0, 0), (0x8000, 0x8000))); + assert!(span.widen(0x4000, 0x7fff)); + assert!(bridges(span.now(), (0, 0), (0x8000, 0x8000))); + // A 4 KiB leaf narrows the granule: the page between two pages of one + // 16 KiB granule is a bridge, and pages side by side still are not. + assert!(!span.widen(0x2000, 0x2fff)); + let small = span.now(); + assert_eq!(small.map(|globals| globals.leaf), Some(0x1000)); + assert!(bridges(small, (0x1000, 0x1000), (0x3000, 0x3000))); + assert!(bridges(small, (0x3000, 0x3000), (0x1000, 0x1000))); + assert!(!bridges(small, (0x1000, 0x1000), (0x2000, 0x2000))); + assert!(!bridges(small, (0x1000, 0x1ff8), (0x2000, 0x2008))); + assert!(!bridges(None, (0x1000, 0x1000), (0x3000, 0x3000))); +} + +/// Another PE's TLBI by VA or range reaches this PE through its mail and +/// drops the ITLB entries it covers alone: a global page's for any ASID, +/// a page of an ASID for that ASID or every ASID. A page remapped behind +/// such a TLBI translates anew at the PE's next fetch. +#[test] +fn a_tlbi_another_pe_broadcasts_drops_the_pages_it_covers_alone() { + use super::super::tests::{ + BASE, CODE_ASID, SPACES_TABLES, asid_code_pages, page_descriptor, va_operand, write_entry, + }; + use crate::machine::system::TlbiKind::{RVA, VA, VAA}; + const RET: u32 = 0xd65f_03c0; + const MOVZ: u32 = 0xd280_0020; // movz x0, #1 + const PAGES: u64 = 16; + let (hub, _) = hub(2); + let mut machine = first_of_two(&[RET], &hub); + asid_code_pages(&mut machine, PAGES as usize, 8); + let page = |n: u64| BASE + n * 0x1000; + let fetch_all = |machine: &mut Machine<_, _>| { + for n in 0..PAGES { + assert!(matches!( + machine.fetch_block(page(n), false), + Ok(super::super::Fetched::Block(_)) + )); + } + }; + let held = |machine: &Machine<_, _>| -> Vec { + (0..PAGES) + .filter(|&n| machine.current_key(page(n)).is_some()) + .collect() + }; + let other = CODE_ASID + 1; + // TG 4 KiB, SCALE 0, NUM 1: four pages. + let four = |asid, va| va_operand(asid, va) | 1 << 46 | 1 << 39; + let cases: [(_, u64, &[u64]); 7] = [ + (VA, va_operand(other, page(3)), &[3]), + (VA, va_operand(other, page(9)), &[]), + (VA, va_operand(CODE_ASID, page(10)), &[10]), + (VAA, va_operand(0, page(11)), &[11]), + (RVA, four(other, page(4)), &[4, 5, 6, 7]), + (RVA, four(other, page(12)), &[]), + (RVA, four(CODE_ASID, page(12)), &[12, 13, 14, 15]), + ]; + for (kind, operand, gone) in cases { + fetch_all(&mut machine); + assert_eq!(held(&machine), (0..PAGES).collect::>()); + hub.broadcast(1, &[tlbi(kind, operand)]); + machine.read_mail().unwrap(); + let kept: Vec = (0..PAGES).filter(|n| !gone.contains(n)).collect(); + assert_eq!(held(&machine), kept, "{kind:?} {operand:#x}"); + } + machine.host.ram[0x1000..0x1004].copy_from_slice(&MOVZ.to_le_bytes()); + machine.host.ram[0x1004..0x1008].copy_from_slice(&RET.to_le_bytes()); + fetch_all(&mut machine); + let [_, _, l3] = SPACES_TABLES[0]; + write_entry( + &mut machine, + l3 + 3 * 8, + page_descriptor(BASE + 0x1000, false), + ); + hub.broadcast(1, &[tlbi(VA, va_operand(other, page(3)))]); + machine.read_mail().unwrap(); + let Ok(super::super::Fetched::Block(block)) = machine.fetch_block(page(3), false) else { + panic!("a block"); + }; + assert_eq!(machine.code.blocks[block].physical, BASE + 0x1000); +} + +/// Counter benchmark: a PE runs a loop over global pages (a shared cache's) +/// while another PE's process sends TLBIs by page of its own pages below and +/// above them, past what the first PE's mailbox keeps: the PE reads them at +/// each round's start. No merge of the mailbox reaches across the PE's +/// global pages, so no round drops, refills or fills one, or exits for one. +/// (`cargo test -p stela-engine --lib itlb_bench -- --nocapture` prints the +/// counts.) +#[test] +fn itlb_bench_a_full_mailbox_leaves_a_pes_shared_pages() { + use super::super::tests::{BASE, asid_code_pages, dispatched, va_operand}; + use super::super::{FetchPath, ItlbSource}; + use crate::machine::system::TlbiKind::VA; + const RET: u32 = 0xd65f_03c0; + const PAGES: u64 = 64; + const ROUNDS: u64 = 20; + const BELOW: u64 = 0x1_0000_0000; + const ABOVE: u64 = 0x40_0000_0000; + let (hub, _) = hub(2); + let mut machine = first_of_two(&[RET], &hub); + asid_code_pages(&mut machine, PAGES as usize, PAGES as usize); + let page = |n: u64| BASE + n * 0x1000; + let round = |machine: &mut Machine<_, _>| { + machine.read_mail().unwrap(); + let mut exits = 0; + for n in 0..PAGES { + if !dispatched(machine, page(n)) { + exits += 1; + assert!(matches!( + machine.fetch_block(page(n), false), + Ok(super::super::Fetched::Block(_)) + )); + } + } + exits + }; + let warm = round(&mut machine); + let counts = |machine: &Machine<_, _>| { + let statistics = &machine.statistics; + [ + statistics.itlb_drops[1], + statistics.itlb_sources[ItlbSource::DropGlobal as usize], + statistics.itlb[0], + statistics.itlb_sources[ItlbSource::Refilled as usize], + statistics.fetch_paths[FetchPath::ItlbMiss as usize], + statistics.lookup_forgets[2], + ] + }; + let before = counts(&machine); + let sends = MAIL_TLB_SCOPES as u64 + 64; + let mut exits = 0; + for round_number in 0..ROUNDS { + // ASID 9's pages, 1 MiB apart: bursts above, then one below. + for n in 0..sends { + let at = (round_number * sends + n) * 0x10_0000; + let va = if n % 20 == 19 { BELOW + at } else { ABOVE + at }; + hub.broadcast(1, &[tlbi(VA, va_operand(9, va))]); + } + exits += round(&mut machine); + } + let after = counts(&machine); + let [drops, global, fills, refilled, misses, reached] = + [0, 1, 2, 3, 4, 5].map(|n| after[n] - before[n]); + eprintln!( + "ITLB bench, two PEs, {PAGES} shared pages x {ROUNDS} rounds, {sends} TLBI VALE1IS \ + of another process a round: warm-up exits {warm}; then exits {exits}, drop_tlbi \ + {drops}, drop_global {global}, ITLB fills {fills}, refilled {refilled}, fetch \ + itlb_miss {misses}, forget_va {reached}", + ); + assert_eq!([drops, global, fills, refilled, misses, exits], [0; 6]); +} + +#[test] +fn an_ic_ivau_reaches_other_pes_only_for_compiled_pages_once_per_dsb() { + const PAGE: u64 = 0x4000_0000; + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + // No PE compiled from it: the IC IVAU of each line stops here. + machine.post_code_page(PAGE); + assert!(machine.outgoing.is_empty()); + // The next lines of a page add nothing to its first one. + hub.compiling(PAGE + 0x100); + machine.post_code_page(PAGE + 0x40); + machine.post_code_page(PAGE + 0x80); + assert_eq!(machine.outgoing.len(), 1); + // A DSB ends the run: what follows may have been written since. + machine.send_outgoing(); + let mail = hub.take(1).unwrap(); + hub.acknowledge(1, mail.serial); + machine.complete_maintenance().unwrap(); + machine.post_code_page(PAGE + 0x40); + assert_eq!(machine.outgoing.len(), 1); +} + +#[test] +fn maintenance_posted_to_another_pe_completes_at_the_next_dsb() { + let (hub, _) = hub(2); + // DSB ISH. + let mut machine = first_of_two(&[0xd503_3b9f], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.send_outgoing(); + assert_eq!(machine.posted, [(1, 1)]); + // PE 1 reads its mail at its next return to the engine. + let mail = hub.take(1).unwrap(); + hub.acknowledge(1, mail.serial); + machine.host.exits = vec![super::super::NativeExit::Exit { + next_pc: super::super::tests::BASE, + kind: stela_compiler::block::ExitKind::System as u64, + }]; + machine.step().unwrap(); + assert!(machine.posted.is_empty()); + assert_eq!(machine.cpu.pc, super::super::tests::BASE + 4); + // A PE outside its run loop reads its mail before it runs again: the + // completion does not wait for it. + machine.post(Maintenance::Code(None)); + hub.set_outside(1, true); + machine.complete_maintenance().unwrap(); + assert!(machine.posted.is_empty()); + assert!(hub.take(1).is_some()); +} + +#[test] +fn notification_after_drain_survives_native_budget_reset() { + use super::super::tests::machine; + let mut machine = machine(&[0xd503_201f]); + let (hub, _) = hub(1); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + hub.post(0, |mail| mail.event = true); + machine.read_mail().unwrap(); + let drained = machine.chain.snapshot(); + assert_eq!(drained.interrupt_epoch, drained.observed_interrupt_epoch); + assert_eq!( + drained.quiet, + stela_compiler::x86_64::chain::Quiet::default() + ); + // This is the old lost-notification window: the owner has drained, + // then a peer posts before the owner initializes its next budget. + hub.post(0, |mail| mail.event = true); + machine.chain.begin(0, 4096); + let entered = machine.chain.snapshot(); + assert_eq!(machine.chain.account().budget(), 4096); + assert_ne!(entered.interrupt_epoch, entered.observed_interrupt_epoch); + assert_eq!(entered.observed_interrupt_epoch, drained.interrupt_epoch); + assert_eq!(entered.quiet, stela_compiler::x86_64::chain::Quiet(0)); + machine.read_mail().unwrap(); + let next = machine.chain.snapshot(); + assert_eq!(next.interrupt_epoch, next.observed_interrupt_epoch); + assert_eq!(next.quiet, stela_compiler::x86_64::chain::Quiet::default()); +} + +#[test] +fn epoch_exhaustion_is_sticky_across_drain_detach_and_reuse() { + use super::super::tests::machine; + let mut machine = machine(&[0xd503_201f]); + let (hub, _) = hub(1); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + hub.inboxes[0] + .chain + .interrupt_epoch() + .store(u64::MAX - 1, Ordering::Relaxed); + hub.post(0, |mail| mail.event = true); + machine.read_mail().unwrap(); + hub.interrupt(0); + let exhausted = machine.chain.snapshot(); + assert_eq!(exhausted.interrupt_epoch, u64::MAX); + assert_eq!(exhausted.observed_interrupt_epoch, u64::MAX - 1); + assert_eq!(exhausted.quiet, stela_compiler::x86_64::chain::Quiet(0)); + drop(machine); + let (_, mut next) = Attached::new(&hub, 0, false).unwrap(); + next.initialize(11, 14, [12, 13], [0xffff, 0xfff]); + next.acknowledge_interrupt(u64::MAX); + next.begin(0, 4096); + let reused = next.snapshot(); + assert_eq!(reused.interrupt_epoch, u64::MAX); + assert_eq!(reused.observed_interrupt_epoch, u64::MAX - 1); + assert_eq!(reused.quiet, stela_compiler::x86_64::chain::Quiet(0)); +} + +#[test] +fn mail_reaches_running_pes_and_kicks_only_a_sleeping_one() { + let (hub, kicks) = hub(3); + hub.event(0); + assert_eq!(kicks.load(Ordering::Relaxed), 0, "no PE sleeps"); + assert!(hub.take(0).is_none(), "SEV reaches the others"); + assert!(hub.take(1).is_some_and(|mail| mail.event)); + // A PE that sleeps halts only without mail, and mail kicks it. + let mut halts = 0; + hub.sleep(1, hub.lines_epoch(1), true, || halts += 1); + assert_eq!(halts, 1); + hub.sleep(2, hub.lines_epoch(2), true, || halts += 1); + assert_eq!(halts, 1, "PE 2 has mail"); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + hub.start(1, 0x8000); + assert_eq!(kicks.load(Ordering::Relaxed), 1); +} + +#[test] +fn a_broadcast_is_applied_once_every_running_pe_acknowledged_it() { + let (hub, kicks) = hub(3); + let (attached, mut control) = Attached::new(&hub, 1, false).unwrap(); + control.begin(0, 4096); + let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); + assert_eq!(posted, [(1, 1), (2, 1)]); + assert!(!hub.applied(&mut posted)); + // The running PE leaves native code at its next chained transfer. + drop(attached); + assert_eq!(control.account().budget(), 4096); + let interrupted = control.snapshot(); + assert_ne!( + interrupted.interrupt_epoch, + interrupted.observed_interrupt_epoch + ); + let mail = hub.take(1).unwrap(); + assert_eq!((mail.maintenance.len(), mail.serial), (1, 1)); + hub.acknowledge(1, mail.serial); + assert!(!hub.applied(&mut posted)); + assert_eq!(posted, [(2, 1)]); + // A PE that sleeps is neither woken nor waited for: it reads its + // mail before it runs again. + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + assert!(hub.applied(&mut posted)); + assert_eq!(kicks.load(Ordering::Relaxed), 0); + hub.inboxes[2].sleeping.store(false, Ordering::SeqCst); + assert!(hub.take(2).is_some_and(|mail| mail.serial == 1)); + // A PE that no longer reads mail holds no broadcast up. + let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); + hub.set_live(2, false); + hub.acknowledge(1, 2); + assert!(hub.applied(&mut posted)); + // Serials keep counting after a take. + assert_eq!(hub.broadcast(0, &[Maintenance::Code(None)]), [(1, 3)]); +} + +#[test] +fn a_host_call_ends_a_run_and_wakes_a_sleeping_pe() { + let (hub, kicks) = hub(2); + let (attached, control) = Attached::new(&hub, 1, false).unwrap(); + hub.call_host(1); + let interrupted = control.snapshot(); + assert_ne!( + interrupted.interrupt_epoch, + interrupted.observed_interrupt_epoch + ); + assert_eq!(kicks.load(Ordering::Relaxed), 0); + assert!(hub.take_host_call(1)); + assert!(!hub.take_host_call(1), "taken once"); + drop(attached); + // A sleep does not start over a call, and a sleeper is woken for one. + hub.call_host(1); + let mut halted = false; + hub.sleep(1, 0, true, || halted = true); + assert!(!halted); + assert!(hub.take_host_call(1)); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + hub.call_host(1); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + hub.inboxes[1].sleeping.store(false, Ordering::SeqCst); +} + +/// Host work for an idle core calls a PE that sleeps waiting for an +/// interrupt, never the one skipped and never one asleep in WFE; with none, +/// nobody is called. +#[test] +fn host_work_for_an_idle_core_calls_a_pe_that_sleeps_waiting_for_an_interrupt() { + let (hub, kicks) = hub(3); + // Nobody sleeps. + assert!(!hub.call_sleeping_server(0)); + // PE 0 sleeps serving, but is skipped; PE 2 sleeps in WFE. + hub.inboxes[0].sleeping.store(true, Ordering::SeqCst); + hub.inboxes[0].serves.store(true, Ordering::SeqCst); + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + assert!(!hub.call_sleeping_server(0)); + assert_eq!(kicks.load(Ordering::Relaxed), 0); + assert!(!hub.take_host_call(0) && !hub.take_host_call(2)); + // PE 2 now waits for an interrupt: it is called and woken. + hub.inboxes[2].serves.store(true, Ordering::SeqCst); + assert!(hub.call_sleeping_server(0)); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + assert!(!hub.take_host_call(0)); + assert!(hub.take_host_call(2), "its wait ends as for a host call"); + for pe in [0, 2] { + hub.inboxes[pe].sleeping.store(false, Ordering::SeqCst); + hub.inboxes[pe].serves.store(false, Ordering::SeqCst); + } +} + +/// A line change publishes the receiver's pins before it moves the +/// receiver's epoch, so a running receiver reads them at once; a sleeping +/// one is kicked only after the producer releases the board lock, which no +/// other PE then waits behind. +#[test] +fn a_line_notification_publishes_pins_first_and_kicks_after_the_unlock() { + #[derive(Default)] + struct Latched(Lines); + impl Devices for Latched { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, pe: usize, _: u64) -> Lines { + if pe == 1 { self.0 } else { Lines::default() } + } + fn pins(&mut self, pe: usize) -> Option { + Some(self.lines(pe, 0)) + } + } + struct ReadPins { + worker: Arc>>>, + observed: Arc>>, + } + impl Kick for ReadPins { + fn kick(&self, pe: usize) { + // The kick follows the unlock. Latched pins are lockless. + let mut worker = self.worker.lock().unwrap(); + let worker = worker.as_mut().unwrap(); + assert!(worker.board.devices.try_lock().is_ok()); + let lines = worker.lines(pe, 0); + self.observed.lock().unwrap().push(lines); + } + } + let worker = Arc::new(Mutex::new(None)); + let observed = Arc::new(Mutex::new(Vec::new())); + let hub = Hub::new( + 2, + ReadPins { + worker: Arc::clone(&worker), + observed: Arc::clone(&observed), + }, + ); + for pe in 0..2 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Latched::default(), Arc::clone(&hub)); + *worker.lock().unwrap() = Some(home.worker()); + let changes = [ + Lines { + irq: true, + fiq: false, + }, + Lines { + irq: false, + fiq: true, + }, + Lines::default(), + ]; + for lines in changes { + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + home.serve(|devices| devices.0 = lines); + } + worker.lock().unwrap().take(); + assert_eq!(*observed.lock().unwrap(), changes); +} + +/// A write of 1 requests a restart, of 2 starts PE 1 at 0x800 and of 3 +/// leaves bytes for the host; any other value sets the DMA deadline, 0 +/// clearing it. Also raises PE 1's IRQ from count `irq_at`. +#[derive(Default)] +struct Pending { + reset: Option, + dma: Option, + irq_at: Option, + starts: Vec, + service: bool, + register_calls: usize, + /// Each release of the board's lock: what its call waited and held. + released: Vec<(u64, u64)>, +} + +/// The one IMPLEMENTATION DEFINED register [`Pending`] serves. +const SERVED: Encoding = Encoding::new(3, 5, 15, 0, 1); + +impl Devices for Pending { + fn lock_released(&mut self, waited: u64, held: u64) { + self.released.push((waited, held)); + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, value: u64, _: u64) -> Result<(), DeviceError> { + match value { + 1 => { + self.reset = Some(Reset { + transition: stela_contracts::bus::Transition::Restart, + reason: "test".into(), + }) + } + 2 => self.starts.push(Start { + cpu: 1, + address: 0x800, + }), + 3 => self.service = true, + 0 => self.dma = None, + deadline => self.dma = Some(deadline), + } + Ok(()) + } + fn lines(&mut self, pe: usize, now: u64) -> Lines { + Lines { + irq: pe == 1 && self.irq_at.is_some_and(|at| now >= at), + ..Lines::default() + } + } + fn deadline(&mut self, now: u64) -> Option { + self.irq_at.filter(|&at| at > now) + } + fn take_reset(&mut self) -> Option { + self.reset.take() + } + fn take_start(&mut self) -> Option { + self.starts.pop() + } + fn dma_deadline(&self) -> Option { + self.dma + } + fn take_host_service(&mut self) -> bool { + core::mem::take(&mut self.service) + } + fn system_register( + &mut self, + _: usize, + encoding: Encoding, + _: Option, + _: u64, + ) -> Option> { + self.register_calls += 1; + (encoding == SERVED).then_some(Ok(7)) + } + fn serves_register(&self, encoding: Encoding) -> bool { + encoding == SERVED + } +} + +/// Counts its clock's reads: each board lock reads it once when taken and +/// once when released. +struct Ticks(Arc); +impl Kick for Ticks { + fn kick(&self, _pe: usize) {} + fn ticks(&self) -> u64 { + self.0.fetch_add(1, Ordering::SeqCst) as u64 + } +} + +/// Counts the host work releases of the devices' lock run +/// ([`Kick::released`]). +struct Releases(Arc); +impl Kick for Releases { + fn kick(&self, _pe: usize) {} + fn released(&self) -> bool { + self.0.fetch_add(1, Ordering::SeqCst); + false + } + fn release_due(&self) -> bool { + true + } +} + +/// The host work a release of the devices' lock leaves runs only on a PE +/// outside its run loop or asleep, where no broadcast waits for it: one +/// inside its loop, or a call that names no PE, leaves it for later, so a +/// slow host device never keeps a running PE from its mail. +#[test] +fn released_host_work_runs_only_outside_the_run_loop() { + let released = Arc::new(AtomicUsize::new(0)); + let hub = Hub::new(2, Releases(Arc::clone(&released))); + for pe in 0..2 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + released.store(0, Ordering::SeqCst); + let mut worker = home.worker(); + + // Inside its run loop: the access takes the lock and leaves the work. + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 0, "inside the run loop"); + // A call that names no PE leaves it too. + home.with(|_| ()); + assert_eq!(released.load(Ordering::SeqCst), 0, "no PE named"); + + // Outside its run loop, as a device site's access runs, it does it. + hub.set_outside(1, true); + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 1, "outside"); + hub.set_outside(1, false); + + // Asleep, as a halted PE serving the host, it does it. + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 2, "asleep"); + hub.inboxes[1].sleeping.store(false, Ordering::SeqCst); + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 2, "inside again"); +} + +/// What follows a write, [`Devices::settle_write`]: the lock, the DMA +/// under it, the call and the lock after, in that order, from one board +/// lock. +#[test] +fn a_shared_board_settles_a_write_under_one_lock() { + use super::super::{LockedMemory, Memory}; + use crate::machine::mmu::MemoryLocks; + const LOCK: MemoryLocks = [Some((0x1000, 0x1fff)), None, None, None]; + const AFTER: MemoryLocks = [Some((0x1000, 0x2fff)), None, None, None]; + #[derive(Default)] + struct Settling { + steps: Vec<&'static str>, + } + impl Devices for Settling { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + fn memory_lock(&self) -> MemoryLocks { + if self.steps.contains(&"transfer") { + AFTER + } else { + LOCK + } + } + fn transfer( + &mut self, + cpu: usize, + memory: &mut dyn Memory, + _: u64, + ) -> Result<(), DeviceError> { + assert_eq!(cpu, 1); + assert!(memory.write(0x800, &[1])); + assert!(!memory.write(0x1800, &[1]), "the lock before the DMA"); + self.steps.push("transfer"); + Ok(()) + } + } + /// RAM below 0x4000 that refuses writes the lock covers. + struct Locked(MemoryLocks); + impl Memory for Locked { + fn read(&mut self, _: u64, _: &mut [u8]) -> bool { + true + } + fn write(&mut self, physical: u64, _: &[u8]) -> bool { + !self + .0 + .into_iter() + .flatten() + .any(|(first, last)| (first..=last).contains(&physical)) + } + } + impl LockedMemory for Locked { + fn under(&mut self, lock: MemoryLocks) -> &mut dyn Memory { + self.0 = lock; + self + } + } + let reads = Arc::new(AtomicUsize::new(0)); + let hub = Hub::new(2, Ticks(Arc::clone(&reads))); + let mut worker = SharedDevices::new(Settling::default(), hub).worker(); + let before = reads.load(Ordering::SeqCst); + let settled = worker.settle_write(1, 0, &mut Locked([None; 4])); + assert_eq!(reads.load(Ordering::SeqCst) - before, 2, "one lock"); + assert!(settled.transfer.is_ok() && settled.call.is_none()); + assert_eq!((settled.lock, settled.after), (LOCK, AFTER)); + assert_eq!(worker.with(|devices| devices.steps.clone()), ["transfer"]); +} + +/// A handle counts the ticks its calls waited for the board's lock, once. +#[test] +fn a_handle_counts_the_ticks_it_waited_for_the_lock() { + let reads = Arc::new(AtomicUsize::new(0)); + let hub = Hub::new(2, Ticks(reads)); + let home = SharedDevices::new(Pending::default(), hub); + let mut worker = home.worker(); + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(worker.take_lock_wait(), 0, "uncontended"); + let board = Arc::clone(&home.board); + let held = board.devices.lock().unwrap(); + let waiter = std::thread::spawn(move || { + worker.write(1, 0, 4, 0, 0).unwrap(); + (worker.take_lock_wait(), worker.take_lock_wait()) + }); + // Bounded: the waiter blocks on the lock within five seconds. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while board.waits[Call::Access as usize].load(Ordering::Relaxed) == 0 { + assert!( + std::time::Instant::now() < deadline, + "the waiter never waited" + ); + std::thread::yield_now(); + } + drop(held); + let (waited, again) = waiter.join().unwrap(); + assert!(waited > 0); + assert_eq!(again, 0); +} + +/// Each call tells the devices, before it releases the board's lock, the +/// ticks it waited for it and held it, as the lock's own counts have them, +/// so a model can count them against what the call touched. +#[test] +fn each_call_tells_the_devices_its_lock_wait_and_hold() { + let reads = Arc::new(AtomicUsize::new(0)); + let hub = Hub::new(2, Ticks(reads)); + let home = SharedDevices::new(Pending::default(), hub); + let mut worker = home.worker(); + worker.write(1, 0, 4, 0, 0).unwrap(); + let released = |home: &SharedDevices| home.with(|d| d.released.clone()); + let access = |home: &SharedDevices| home.lock_times()[Call::Access as usize].held; + let held = access(&home); + assert!(held > 0); + assert_eq!(released(&home).last(), Some(&(0, held)), "uncontended"); + let board = Arc::clone(&home.board); + let locked = board.devices.lock().unwrap(); + let waiter = std::thread::spawn(move || { + worker.write(1, 0, 4, 0, 0).unwrap(); + worker.take_lock_wait() + }); + // Bounded: the waiter blocks on the lock within five seconds. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while board.waits[Call::Access as usize].load(Ordering::Relaxed) == 0 { + assert!( + std::time::Instant::now() < deadline, + "the waiter never waited" + ); + std::thread::yield_now(); + } + drop(locked); + let waited = waiter.join().unwrap(); + assert!(waited > 0); + let all = released(&home); + assert_eq!( + all.last(), + Some(&(waited, access(&home) - held)), + "its own wait" + ); +} + +#[test] +fn only_the_registers_the_devices_serve_reach_them() { + let (hub, _) = hub(2); + let mut worker = SharedDevices::new(Pending::default(), hub).worker(); + assert_eq!(worker.system_register(1, SERVED, None, 0), Some(Ok(7))); + let other = Encoding::new(3, 6, 15, 1, 0); + assert_eq!(worker.system_register(1, other, Some(1), 0), None); + assert!(worker.serves_register(SERVED) && !worker.serves_register(other)); + assert_eq!(worker.with(|devices| devices.register_calls), 1); +} + +/// A fast-IPI write (IPI_RR_GLOBAL_EL1) moves only device lines: the +/// step reads them again, and nothing derived from the PE's registers goes. +#[test] +fn a_fast_ipi_write_keeps_what_derives_from_the_pes_registers() { + use super::super::tests::board; + use stela_contracts::identity::Identity; + const MSR: u32 = 0xd51d_f029; // msr s3_5_c15_c0_1, x9 + let (hub, _) = hub(2); + let worker = SharedDevices::new(Pending::default(), hub).worker(); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut machine = board(&[MSR], worker, identities); + machine.native_system(); + assert!(machine.native_system.is_some()); + machine.device_lines = Some((Lines::default(), u64::MAX, machine.current)); + let pc = machine.cpu.pc; + machine.cpu.state.x[9] = 1 << 16; + machine.system_instruction(MSR).unwrap(); + assert_eq!(machine.cpu.pc, pc + 4); + assert_eq!(machine.devices.with(|devices| devices.register_calls), 1); + assert_eq!(machine.device_lines, None, "lines are read again"); + assert!(machine.native_system.is_some(), "derived state stays"); +} + +/// A board whose PEs signal each other with a word each, as Apple's fast +/// IPIs do: a write of `SERVED` sets the word of the PE its value names +/// through the PE's own handle, without the lock, unless the value has bit +/// 8 set, which takes the lock and raises it there. +#[derive(Default)] +struct Signalling { + words: Arc<[AtomicU64; 2]>, + /// Each CPU's deferred-request flag, which only native completion reads. + armed: Arc<[AtomicBool; 2]>, + signalled: u64, + register_calls: usize, + /// The SoC sleeps ([`Devices::waits_on_host`]). + asleep: bool, +} + +struct SignalWords { + words: Arc<[AtomicU64; 2]>, + pe: usize, +} + +impl LocalRegisters for SignalWords { + fn register(&self, _: Encoding, _: Option) -> Option { + None + } + fn storage(&self, _: Encoding) -> Option { + None + } + fn send(&self, encoding: Encoding, value: u64) -> Option> { + if encoding != SERVED || value & 1 << 8 != 0 { + return None; + } + let target = (value & 1) as usize; + Some((self.words[target].swap(1, Ordering::AcqRel) == 0).then_some(target)) + } + fn fiq(&self) -> bool { + self.words[self.pe].load(Ordering::Acquire) != 0 + } +} + +impl Devices for Signalling { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, pe: usize, _: u64) -> Lines { + self.pins(pe).unwrap() + } + /// No latched line: the FIQ is each PE's word ([`Devices::own_fiq`]). + fn pins(&mut self, _: usize) -> Option { + Some(Lines::default()) + } + fn fast_ipi_words(&self) -> Vec { + (0..2) + .map(|pe| crate::machine::fast_ipi::Word { + cluster: 0, + cpu: pe as u8, + status: self.words[pe].as_ptr() as u64, + armed: self.armed[pe].as_ptr() as u64, + }) + .collect() + } + fn take_signalled(&mut self, pe: usize) -> bool { + let raised = self.signalled & 1 << pe != 0; + self.signalled &= !(1 << pe); + raised + } + fn system_register( + &mut self, + _: usize, + _: Encoding, + write: Option, + _: u64, + ) -> Option> { + self.register_calls += 1; + let target = (write? & 1) as usize; + if self.words[target].swap(1, Ordering::AcqRel) == 0 { + self.signalled |= 1 << target; + } + Some(Ok(0)) + } + fn serves_register(&self, encoding: Encoding) -> bool { + encoding == SERVED + } + fn waits_on_host(&self) -> bool { + self.asleep + } + fn local_registers(&self, pe: usize) -> Option> { + Some(Arc::new(SignalWords { + words: Arc::clone(&self.words), + pe, + })) + } +} + +/// A signal its handle completes takes no lock and wakes its target, which +/// reads the FIQ live from its own word, never in its lines; one the board +/// raises under the lock wakes the target through the call's notification. +#[test] +fn a_signal_without_the_lock_wakes_its_target_and_raises_its_fiq() { + let (hub, kicks) = hub(2); + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + let mut sender = home.worker(); + let mut target = home.worker(); + // Each handle takes its PE's registers once, under the lock. + sender.local_registers_of(0); + target.local_registers_of(1); + let calls = |devices: &SharedDevices| devices.with(|board| board.register_calls); + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + let board = Arc::clone(&home.board); + let held = board.devices.lock().unwrap(); + // The lock is held elsewhere: the send must not need it. + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + drop(held); + assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); + assert_eq!(kicks.load(Ordering::Relaxed), 1, "the sleeping target"); + assert!(target.own_fiq(1) && !target.lines(1, 0).fiq); + assert!(!sender.own_fiq(0)); + assert_eq!(calls(&home), 0); + // Pending already: no line changes, no wake. + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + // Held low while the SoC sleeps, as the latched pins are. + board.asleep.store(true, Ordering::Release); + assert!(!target.own_fiq(1)); + board.asleep.store(false, Ordering::Release); + // Under the lock: the call's notification wakes the target, though its + // latched pins did not change. + home.with(|devices| devices.words[1].store(0, Ordering::Release)); + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + assert_eq!( + sender.system_register(0, SERVED, Some(1 << 8 | 1), 0), + Some(Ok(0)) + ); + assert_eq!(calls(&home), 1); + assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); + assert_eq!(kicks.load(Ordering::Relaxed), 2); + assert!(target.own_fiq(1)); +} + +/// A PE's own FIQ is read live at every look past its cached lines: an +/// acknowledgement between the cache fill and the next look delivers no +/// FIQ, and a send between them is not lost, while the cache holds. +#[test] +fn a_pes_own_fiq_is_read_live_past_its_cached_lines() { + use super::super::tests::board; + use stela_contracts::identity::Identity; + struct Own { + word: Arc, + queries: usize, + } + impl Devices for Own { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + self.queries += 1; + Lines::default() + } + fn own_fiq(&mut self, _: usize) -> bool { + self.word.load(Ordering::SeqCst) + } + } + let word = Arc::new(AtomicBool::new(true)); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let devices = Own { + word: Arc::clone(&word), + queries: 0, + }; + let mut machine = board(&[], devices, identities); + assert!(machine.device_lines_of(0, 0).fiq); + word.store(false, Ordering::SeqCst); + assert!(!machine.device_lines_of(0, 1).fiq, "acknowledged: no FIQ"); + word.store(true, Ordering::SeqCst); + assert!(machine.device_lines_of(0, 2).fiq, "sent: not lost"); + assert_eq!(machine.devices.queries, 1, "the cached lines held"); +} + +/// The board's frozen fast-IPI table names each PE's own word and the +/// hub's counters for it: a request completed by it raises the target's +/// FIQ, tells it, and has a halted target woken through the board. +#[test] +fn the_fast_ipi_table_completes_a_request_through_the_hubs_words() { + use crate::machine::fast_ipi::{Register, Sent}; + let (hub, kicks) = hub(2); + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + let mut target = home.worker(); + let table = home.fast_ipi_table().expect("a table"); + assert!(Arc::ptr_eq(&table, &target.fast_ipi_table().unwrap())); + let entry = *table.target(0, 1).unwrap(); + assert_eq!(entry.lines, hub.inboxes[1].lines.as_ptr() as u64); + assert_eq!(entry.sleeping, hub.inboxes[1].sleeping.as_ptr() as u64); + assert_eq!(entry.interrupt, hub.inboxes[1].chain.control()); + assert_eq!(entry.pe, 1); + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + let interrupt = hub.inboxes[1] + .chain + .interrupt_epoch() + .load(Ordering::SeqCst); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + assert_eq!(table.send(0, Register::RequestLocal, 1), Sent::Wake(1)); + assert!(target.own_fiq(1) && !target.lines(1, 0).fiq); + assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch + 1); + assert_eq!( + hub.inboxes[1] + .chain + .interrupt_epoch() + .load(Ordering::SeqCst), + interrupt + 1 + ); + assert_eq!(kicks.load(Ordering::Relaxed), 0, "the engine wakes it"); + target.wake_signalled(1); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + // The engine's own path then finds it pending and changes nothing. + assert_eq!(table.send(0, Register::RequestLocal, 1), Sent::Done); + assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch + 1); +} + +/// A board that signals CPUs by number, which may name one no PE runs: a +/// write of `SERVED` with bit 8 clear completes on the sender's handle for +/// the CPU its low byte names; with bit 8 set it raises that CPU under the +/// lock. +struct Numbered { + raised: Vec, +} + +struct NumberedHandle; + +impl LocalRegisters for NumberedHandle { + fn register(&self, _: Encoding, _: Option) -> Option { + None + } + fn storage(&self, _: Encoding) -> Option { + None + } + fn send(&self, encoding: Encoding, value: u64) -> Option> { + (encoding == SERVED && value & 1 << 8 == 0).then_some(Some((value & 0xff) as usize)) + } +} + +impl Devices for Numbered { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + fn latched_pins(&mut self, _: usize) -> Option { + Some(Lines::default()) + } + fn take_signalled(&mut self, pe: usize) -> bool { + self.raised.get_mut(pe).is_some_and(core::mem::take) + } + fn system_register( + &mut self, + _: usize, + _: Encoding, + write: Option, + _: u64, + ) -> Option> { + self.raised[(write? & 0xff) as usize] = true; + Some(Ok(0)) + } + fn serves_register(&self, encoding: Encoding) -> bool { + encoding == SERVED + } + fn local_registers(&self, _: usize) -> Option> { + Some(Arc::new(NumberedHandle)) + } +} + +/// A signal without the lock to a CPU the board has but no PE runs is +/// refused (the engine reports it once and goes on) and wakes no one; it +/// does not index past the PEs. One to a PE still wakes it. +#[test] +fn a_signal_to_a_cpu_without_a_pe_is_refused_and_dropped() { + let (hub, kicks) = hub(2); + let home = SharedDevices::new( + Numbered { + raised: vec![false; 8], + }, + Arc::clone(&hub), + ); + let mut sender = home.worker(); + for pe in 0..2 { + hub.inboxes[pe].sleeping.store(true, Ordering::SeqCst); + } + let epochs = |hub: &Hub| -> Vec { + hub.inboxes + .iter() + .map(|inbox| inbox.lines.load(Ordering::SeqCst)) + .collect() + }; + let before = epochs(&hub); + assert!(matches!( + sender.system_register(0, SERVED, Some(5), 0), + Some(Err(_)) + )); + assert_eq!(kicks.load(Ordering::Relaxed), 0); + assert_eq!(epochs(&hub), before); + let woken = |home: &SharedDevices| { + home.board.woken[Call::Register as usize].load(Ordering::Relaxed) + }; + assert_eq!(woken(&home), 0); + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + assert_eq!(woken(&home), 1, "counted in DEVICE WAKES register="); +} + +/// A PE numbered past 63 whose FIQ a locked call raised is told and woken +/// as any other: the board keeps a raise for every PE. +#[test] +fn a_locked_signal_wakes_a_pe_past_63() { + let (hub, kicks) = hub(70); + let home = SharedDevices::new( + Numbered { + raised: vec![false; 70], + }, + Arc::clone(&hub), + ); + let mut sender = home.worker(); + hub.inboxes[66].sleeping.store(true, Ordering::SeqCst); + let epoch = hub.inboxes[66].lines.load(Ordering::SeqCst); + assert_eq!( + sender.system_register(0, SERVED, Some(1 << 8 | 66), 0), + Some(Ok(0)) + ); + assert_ne!(hub.inboxes[66].lines.load(Ordering::SeqCst), epoch); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + assert!(!home.with(|devices| devices.raised[66]), "taken once"); +} + +/// A signal still pending when the SoC wakes reaches its PE: its FIQ was +/// held low while the SoC slept, so the PE, asleep in WFI, is told and woken +/// when the SoC's sleep ends, though no latched pin changed. +#[test] +fn a_signal_pending_when_the_soc_wakes_wakes_its_target() { + let (hub, kicks) = hub(2); + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + let mut sender = home.worker(); + let mut target = home.worker(); + home.with(|devices| devices.asleep = true); + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + assert!(!target.own_fiq(1), "held low while the SoC sleeps"); + // The target looked at its lines and sleeps again. + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + let before = kicks.load(Ordering::Relaxed); + home.with(|devices| devices.asleep = false); + assert_ne!(hub.inboxes[1].lines.load(Ordering::SeqCst), epoch); + assert_eq!(kicks.load(Ordering::Relaxed), before + 1); + assert!(target.own_fiq(1)); +} + +/// Invariant: a shared board publishes only latched pins, never a PE's own +/// signal word, so a PE that clears its word without the lock never reads +/// a stale FIQ that an unrelated locked call published while the word was +/// set (`Board::publish` and `Held::notify` use `latched_pins`). +#[test] +fn a_signal_cleared_without_the_lock_leaves_no_stale_published_fiq() { + let (hub, _) = hub(2); + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + let mut sender = home.worker(); + let mut target = home.worker(); + let words = home.with(|devices| Arc::clone(&devices.words)); + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + assert!(target.own_fiq(1)); + // Unrelated calls under the lock while the word is set: each release + // publishes every PE's pins, and a write notifies the others. + home.with(|_| ()); + sender.write(0, 0, 4, 0, 0).unwrap(); + assert_eq!( + home.board.pins[1].load(Ordering::Acquire), + shared_devices::pack(Some(Lines::default())) + ); + // The target acknowledges on its own word. + words[1].store(0, Ordering::Release); + assert!(!target.own_fiq(1) && !target.lines(1, 0).fiq); +} + +/// No lost wake-up: a PE that saw no FIQ and halts (`Hub::sleep`) is kicked +/// by a send that races with its halting, in every interleaving the +/// rounds reach. Each halt is bounded: a lost wake-up fails the test. +#[test] +fn a_signal_racing_with_a_halt_always_wakes_the_target() { + struct Flag(Arc); + impl Kick for Flag { + fn kick(&self, _: usize) { + self.0.store(true, Ordering::SeqCst); + } + } + const ROUNDS: usize = 2_000; + let kicked = Arc::new(AtomicBool::new(false)); + let hub = Hub::new(2, Flag(Arc::clone(&kicked))); + for pe in 0..2 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Signalling::default(), Arc::clone(&hub)); + let mut sender = home.worker(); + let mut target = home.worker(); + let words = home.with(|devices| Arc::clone(&devices.words)); + let start = std::sync::Barrier::new(2); + let done = std::sync::Barrier::new(2); + let lost = AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + for round in 0..ROUNDS { + start.wait(); + // Vary where the send lands against the target's halt. + for _ in 0..(round * 7) % 64 { + core::hint::spin_loop(); + } + assert_eq!(sender.system_register(0, SERVED, Some(1), 0), Some(Ok(0))); + done.wait(); + } + }); + for _ in 0..ROUNDS { + start.wait(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + if target.own_fiq(1) { + break; + } + hub.sleep(1, epoch, true, || { + while !kicked.swap(false, Ordering::SeqCst) { + if std::time::Instant::now() > deadline { + lost.store(true, Ordering::SeqCst); + return; + } + std::thread::yield_now(); + } + }); + if lost.load(Ordering::SeqCst) { + break; + } + } + words[1].store(0, Ordering::Release); + kicked.store(false, Ordering::SeqCst); + done.wait(); + } + }); + assert!( + !lost.load(Ordering::SeqCst), + "a send left its target halted" + ); +} + +/// `cargo test -p stela-engine --release --lib signal_send_costs -- +/// --ignored --nocapture`: ns per signal sent through the board, under the +/// devices' lock (as every fast IPI was) or through the sender's handle, +/// alone and while another thread takes the lock for 2 us in every 4 us as +/// device accesses do. The target's word is cleared after each send, so +/// every send raises a line and bumps the target's epoch (no kick: it +/// does not sleep). +#[test] +#[ignore = "manual: opt-in"] +fn signal_send_costs() { + const SENDS: u32 = 200_000; + for contended in [false, true] { + for locked in [true, false] { + let (hub, _) = hub(2); + let home = SharedDevices::new(Signalling::default(), hub); + let mut sender = home.worker(); + sender.local_registers_of(0); + let words = home.with(|devices| Arc::clone(&devices.words)); + let value = if locked { 1 << 8 | 1 } else { 1 }; + let stop = AtomicBool::new(false); + let ns = std::thread::scope(|scope| { + if contended { + scope.spawn(|| { + while !stop.load(Ordering::Relaxed) { + home.with(|_| { + let until = + std::time::Instant::now() + std::time::Duration::from_micros(2); + while std::time::Instant::now() < until { + core::hint::spin_loop(); + } + }); + let until = + std::time::Instant::now() + std::time::Duration::from_micros(2); + while std::time::Instant::now() < until { + core::hint::spin_loop(); + } + } + }); + } + let started = std::time::Instant::now(); + for _ in 0..SENDS { + sender.system_register(0, SERVED, Some(value), 0); + words[1].store(0, Ordering::Release); + } + let ns = started.elapsed().as_nanos() / u128::from(SENDS); + stop.store(true, Ordering::Relaxed); + ns + }); + std::println!("SIGNAL contended={contended} locked={locked} ns_per_send={ns}"); + } + } +} + +#[test] +fn bytes_for_the_host_wake_one_sleeping_pe_and_reach_one_machine_once() { + let (hub, kicks) = hub(3); + let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + // With no PE asleep, the next to wait takes it, and none halts + // meanwhile. + worker.write(1, 0, 4, 3, 0).unwrap(); + assert_eq!(kicks.load(Ordering::Relaxed), 0); + let mut halts = 0; + hub.sleep(2, hub.lines_epoch(2), true, || halts += 1); + assert_eq!(halts, 0, "the service is due"); + let mut home = home; + assert!(home.take_host_service()); + assert!(!worker.take_host_service(), "taken once"); + // One PE asleep waiting for an interrupt wakes for it, and a request + // already due wakes none. + for pe in [1, 2] { + hub.inboxes[pe].serves.store(true, Ordering::SeqCst); + hub.inboxes[pe].sleeping.store(true, Ordering::SeqCst); + } + worker.write(1, 0, 4, 3, 0).unwrap(); + worker.write(1, 0, 4, 3, 0).unwrap(); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + assert!(worker.take_host_service()); +} + +#[test] +fn the_home_machine_sees_any_pes_reset_and_dma_without_the_lock() { + let (hub, _) = hub(2); + let mut home = SharedDevices::new( + Pending { + dma: Some(7), + ..Pending::default() + }, + Arc::clone(&hub), + ); + let mut worker = home.worker(); + assert_eq!(home.dma_deadline(), Some(7), "as the board was made"); + worker.write(1, 0, 4, 90, 0).unwrap(); + assert_eq!( + (home.dma_deadline(), worker.dma_deadline()), + (Some(90), None) + ); + // Home at work outside its run loop: the other PEs take its DMA, which + // a wake would not get it to before that work ends; asleep, it is woken. + hub.set_outside(0, true); + assert_eq!(worker.dma_deadline(), Some(90)); + hub.inboxes[0].sleeping.store(true, Ordering::SeqCst); + assert_eq!(worker.dma_deadline(), None); + hub.inboxes[0].sleeping.store(false, Ordering::SeqCst); + hub.set_outside(0, false); + assert_eq!(worker.dma_deadline(), None); + worker.write(1, 0, 4, 0, 0).unwrap(); + assert_eq!(home.dma_deadline(), None); + hub.set_outside(0, true); + assert_eq!(worker.dma_deadline(), None, "no DMA, none to take"); + hub.set_outside(0, false); + // A reset another PE's access requested reaches the home machine + // once, and never the worker. + worker.write(1, 0, 4, 1, 0).unwrap(); + assert!(worker.take_reset().is_none()); + assert!( + home.take_reset() + .is_some_and(|reset| reset.reason == "test") + ); + assert!(home.take_reset().is_none()); + // A start reaches whichever machine asks first, once. + home.write(0, 0, 4, 2, 0).unwrap(); + worker.write(1, 0, 4, 2, 0).unwrap(); + let start = worker.take_start().unwrap(); + assert_eq!((start.cpu, start.address), (1, 0x800)); + assert!(home.take_start().is_some()); + assert!(home.take_start().is_none() && worker.take_start().is_none()); + assert_eq!(home.waits(), [0; Call::ALL.len()]); +} + +#[test] +fn only_the_home_machine_advances_the_devices_with_time_and_tells_the_others() { + let (hub, _) = hub(2); + let mut home = SharedDevices::new( + Pending { + irq_at: Some(20), + ..Pending::default() + }, + Arc::clone(&hub), + ); + let mut worker = home.worker(); + assert_eq!(worker.deadline(10), None, "the worker waits to be told"); + assert_eq!(home.deadline(10), Some(20)); + let epoch = hub.lines_epoch(1); + assert_eq!(home.deadline(25), None); + assert_eq!(hub.lines_epoch(1), epoch + 1, "PE 1's IRQ rose"); + assert!(worker.lines(1, 25).irq); + // Asking again changes nothing. + home.deadline(30); + assert_eq!(hub.lines_epoch(1), epoch + 1); + // A call from a PE whose counter read lagged cannot undo that advance. + assert!(!home.lines_and_deadline(0, 10).0.irq); + assert_eq!(hub.lines_epoch(1), epoch + 1); + assert!(worker.lines(1, 10).irq); +} + +/// Latched pins: PE 1's IRQ rises once an advance with time reaches +/// `irq_at`; counts the advances. +#[derive(Default)] +struct Timed { + irq_at: u64, + raised: bool, + advances: usize, +} + +impl Devices for Timed { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, pe: usize, now: u64) -> Lines { + self.deadline(now); + self.pins(pe).unwrap_or_default() + } + fn pins(&mut self, pe: usize) -> Option { + Some(Lines { + irq: pe == 1 && self.raised, + ..Lines::default() + }) + } + fn deadline(&mut self, now: u64) -> Option { + self.advances += 1; + self.raised |= now >= self.irq_at; + (!self.raised).then_some(self.irq_at) + } +} + +#[test] +fn a_pe_advances_the_devices_once_their_deadline_passed_while_home_is_outside() { + let (hub, _) = hub(2); + let mut home = SharedDevices::new( + Timed { + irq_at: 20, + ..Timed::default() + }, + Arc::clone(&hub), + ); + let mut worker = home.worker(); + assert_eq!(home.deadline(10), Some(20)); + let epoch = hub.lines_epoch(1); + let advances = |home: &SharedDevices| home.with(|devices| devices.advances); + // Home runs: it advances the devices itself, so the worker does not. + let before = advances(&home); + assert_eq!(worker.deadline(25), None); + assert_eq!(advances(&home), before); + let (lines, until) = worker.lines_and_deadline(1, 25); + assert!(!lines.irq); + assert!(until.is_some_and(|until| until > 25), "looks again later"); + // Home leaves its run loop: the worker, awake past the deadline, brings + // the devices up to its count and tells every PE what changed. + hub.set_outside(0, true); + assert_eq!(worker.deadline(15), None, "not yet due"); + assert_eq!(advances(&home), before); + assert_eq!(worker.deadline(25), None, "it still waits for no device"); + assert_eq!(advances(&home), before + 1); + assert_eq!(hub.lines_epoch(1), epoch + 1, "PE 1's IRQ rose"); + assert!(worker.lines(1, 25).irq); + // Nothing more is due: no PE advances them again. + assert_eq!(worker.deadline(40), None); + assert!(worker.lines_and_deadline(1, 40).0.irq); + assert_eq!(advances(&home), before + 1); + // While another call holds the devices, the worker leaves them. + home.with(|devices| { + devices.raised = false; + devices.irq_at = 50; + }); + hub.set_outside(0, false); + assert_eq!(home.deadline(45), Some(50)); + hub.set_outside(0, true); + let held = home.board.devices.lock().unwrap_or_else(|e| e.into_inner()); + assert_eq!(worker.deadline(60), None); + drop(held); + assert_eq!(advances(&home), before + 2); + assert_eq!(worker.deadline(60), None); + assert_eq!(advances(&home), before + 3); + assert!(worker.lines(1, 60).irq); +} + +/// The host ticks from the first wake that kicks a sleeping PE to the end +/// of its sleep are counted; a sleep nobody kicked, and a later kick in +/// the same sleep, add nothing. +#[test] +fn a_kicked_sleep_counts_its_wake_latency() { + struct Ticking(AtomicU64); + impl Kick for Ticking { + fn kick(&self, _pe: usize) {} + fn ticks(&self) -> u64 { + self.0.fetch_add(10, Ordering::Relaxed) + 10 + } + } + let hub = Hub::new(2, Ticking(AtomicU64::new(0))); + let epoch = hub.lines_epoch(1); + // Kicked at tick 10 (and again at 20), awake at 30. + hub.sleep(1, epoch, true, || { + hub.wake(1); + hub.wake(1); + }); + hub.sleep(1, epoch, true, || {}); + assert_eq!(hub.take_wake_latency(), (1, 20, 20)); + assert_eq!(hub.take_wake_latency(), (0, 0, 0)); + // A wake of a PE that does not sleep kicks nothing and counts nothing. + hub.wake(1); + hub.sleep(1, epoch, true, || {}); + assert_eq!(hub.take_wake_latency(), (0, 0, 0)); +} + +/// A signal armed for a PE that comes due by itself (an Apple deferred fast +/// IPI) bounds how long that PE's machine trusts its lines, and once due +/// the PE advances the devices itself, while home runs its own loop: it +/// fires then, not at home's next advance, which can be milliseconds on. +#[test] +fn a_pe_fires_its_own_due_signal_without_waiting_for_home() { + struct Own(Arc); + impl LocalRegisters for Own { + fn register(&self, _: Encoding, _: Option) -> Option { + None + } + fn storage(&self, _: Encoding) -> Option { + None + } + fn deadline(&self) -> Option { + let due = self.0.load(Ordering::SeqCst); + (due != 0).then_some(due) + } + } + /// PE 1's IRQ rises once an advance passes the armed count. + struct Deferred { + due: Arc, + raised: bool, + advanced_by: Vec, + } + impl Devices for Deferred { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn local_registers(&self, _: usize) -> Option> { + Some(Arc::new(Own(Arc::clone(&self.due)))) + } + fn lines_and_deadline(&mut self, cpu: usize, now: u64) -> (Lines, Option) { + self.advanced_by.push(cpu); + let due = self.due.load(Ordering::SeqCst); + if due != 0 && now >= due { + self.due.store(0, Ordering::SeqCst); + self.raised = true; + } + (self.pins(cpu).unwrap_or_default(), None) + } + fn lines(&mut self, cpu: usize, now: u64) -> Lines { + self.lines_and_deadline(cpu, now).0 + } + fn pins(&mut self, pe: usize) -> Option { + Some(Lines { + irq: pe == 1 && self.raised, + ..Lines::default() + }) + } + } + let (hub, _) = hub(2); + let due = Arc::new(AtomicU64::new(0)); + let home = SharedDevices::new( + Deferred { + due: Arc::clone(&due), + raised: false, + advanced_by: Vec::new(), + }, + Arc::clone(&hub), + ); + let mut worker = home.worker(); + let advanced = |home: &SharedDevices| { + home.with(|devices| core::mem::take(&mut devices.advanced_by)) + }; + advanced(&home); + // Nothing armed: the worker looks again in its usual time. + let look = worker.lines_and_deadline(1, 10).1.unwrap() - 10; + // Armed for count 50: the worker trusts its lines no later than that + // and advances nothing before. + due.store(50, Ordering::SeqCst); + assert_eq!(worker.own_deadline(1), Some(50)); + let (lines, until) = worker.lines_and_deadline(1, 20); + assert_eq!((lines.irq, until), (false, Some(50.min(20 + look)))); + assert!(advanced(&home).is_empty()); + // Due, with home in its run loop: the worker advances them as PE 1 and + // reads its IRQ at once. + assert!(!hub.home_outside()); + let (lines, _) = worker.lines_and_deadline(1, 50); + assert!(lines.irq); + assert_eq!(advanced(&home), [1]); + assert_eq!(worker.own_deadline(1), None); +} + +#[test] +fn a_pe_without_a_machine_waits_for_its_first_start() { + let (hub, _) = hub(2); + hub.event(0); + hub.start(1, 0x1000); + let mut halts = 0; + assert_eq!(hub.first_start(1, || halts += 1), 0x1000); + assert_eq!(halts, 0); +} + +/// A call looks only at the PEs whose pins the devices say may have +/// changed: the others' pins are neither read nor published, and the PE +/// whose line rose is told once and reads it without the lock. +#[test] +fn a_call_looks_only_at_the_pes_whose_pins_changed() { + #[derive(Default)] + struct Masked { + pins: [Lines; 4], + changed: u64, + reads: [usize; 4], + } + impl Devices for Masked { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write( + &mut self, + _: usize, + _: u64, + _: u8, + value: u64, + _: u64, + ) -> Result<(), DeviceError> { + let pins = &mut self.pins[value as usize]; + if !pins.irq { + pins.irq = true; + self.changed |= 1 << value; + } + Ok(()) + } + fn lines(&mut self, pe: usize, _: u64) -> Lines { + self.pins[pe] + } + fn pins(&mut self, pe: usize) -> Option { + Some(self.pins[pe]) + } + fn latched_pins(&mut self, pe: usize) -> Option { + self.reads[pe] += 1; + Some(self.pins[pe]) + } + fn take_pins_changed(&mut self) -> u64 { + core::mem::take(&mut self.changed) + } + } + let (hub, _) = hub(4); + let home = SharedDevices::new(Masked::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + let told: Vec = (0..4) + .map(|pe| hub.inboxes[pe].lines.load(Ordering::SeqCst)) + .collect(); + worker.write(1, 0, 4, 2, 0).unwrap(); + let reads = home.with(|devices| core::mem::take(&mut devices.reads)); + // PE 1 updates its own; PE 2 is read to tell it and to publish it. + assert_eq!((reads[0], reads[1], reads[3]), (0, 1, 0), "{reads:?}"); + assert!(reads[2] >= 1, "{reads:?}"); + let now: Vec = (0..4) + .map(|pe| hub.inboxes[pe].lines.load(Ordering::SeqCst)) + .collect(); + assert_eq!(now, [told[0], told[1], told[2] + 1, told[3]]); + assert!(worker.lines(2, 0).irq, "published for a lock-free read"); + // A call that changed no pins reads none of the others'. + worker.write(1, 0, 4, 2, 0).unwrap(); + let reads = home.with(|devices| devices.reads); + assert_eq!((reads[0], reads[2], reads[3]), (0, 0, 0), "{reads:?}"); +} + +/// A write and its settlement take the board's lock once: one release +/// publishes, and another PE whose line the write raised is told once. The +/// copy the settlement deferred runs after that release, and the transfer +/// that publishes what it came to follows it. +#[test] +fn a_write_settles_under_one_lock_and_tells_another_pe_once() { + use super::super::tests::board; + use super::super::{Memory, UnlockedDma}; + use core::cell::Cell; + use stela_contracts::identity::Identity; + type Log = Arc>>; + struct Copy(Log); + impl UnlockedDma for Copy { + fn run(self: Box, _: &mut dyn Memory) { + self.0.lock().unwrap().push("copy"); + } + } + struct Raising { + log: Log, + irq: bool, + copies: usize, + left: Vec>, + publishes: Cell, + } + impl Devices for Raising { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, cpu: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + assert_eq!(cpu, 0); + self.log.lock().unwrap().push("write"); + self.irq = true; + Ok(()) + } + fn lines(&mut self, pe: usize, _: u64) -> Lines { + Lines { + irq: pe == 1 && self.irq, + ..Lines::default() + } + } + fn transfer(&mut self, _: usize, _: &mut dyn Memory, _: u64) -> Result<(), DeviceError> { + self.log.lock().unwrap().push("transfer"); + if self.copies != 0 { + self.copies -= 1; + self.left.push(Box::new(Copy(Arc::clone(&self.log)))); + } + Ok(()) + } + fn take_unlocked(&mut self) -> Vec> { + core::mem::take(&mut self.left) + } + fn dma_deadline(&self) -> Option { + // Read once by each release's publication. + self.publishes.set(self.publishes.get() + 1); + None + } + } + let (hub, _) = hub(2); + let log: Log = Arc::default(); + let devices = Raising { + log: Arc::clone(&log), + irq: false, + copies: 1, + left: Vec::new(), + publishes: Cell::new(0), + }; + let worker = SharedDevices::new(devices, Arc::clone(&hub)).worker(); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut machine = board(&[], worker, identities); + let publishes = |machine: &mut Machine<_, SharedDevices>| { + machine.devices.with(|devices| devices.publishes.replace(0)) + }; + publishes(&mut machine); + let told = hub.inboxes[1].lines.load(Ordering::SeqCst); + let (devices, processors) = machine.processor_write_parts(); + let written = devices + .write_settled(0, 0x30, 4, 1, 0, processors) + .expect("a plain write"); + assert_eq!(written.written, Ok(())); + assert!( + written + .settled + .is_some_and(|settled| settled.transfer.is_ok()) + ); + assert_eq!( + *log.lock().unwrap(), + ["write", "transfer", "copy", "transfer"] + ); + // The write's lock and the copy's publishing transfer: two releases, + // past the one of the call that counted last. + assert_eq!(publishes(&mut machine), 1 + 2); + assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), told + 1); + // Without a copy, one lock in all; PE 1's line is already up. + log.lock().unwrap().clear(); + let (devices, processors) = machine.processor_write_parts(); + assert!( + devices + .write_settled(0, 0x30, 4, 1, 0, processors) + .is_some_and(|written| written.written.is_ok()) + ); + assert_eq!(*log.lock().unwrap(), ["write", "transfer"]); + assert_eq!(publishes(&mut machine), 1 + 1); + assert_eq!(hub.inboxes[1].lines.load(Ordering::SeqCst), told + 1); +} + +#[test] +fn a_shared_board_classifies_and_serves_a_scalar_access_in_one_call() { + use super::super::tests::board; + use stela_contracts::identity::Identity; + const CANONICAL: u64 = 0x10; + const SAMPLER: u64 = 0x20; + #[derive(Default)] + struct Classified { + reads: usize, + writes: usize, + } + impl Devices for Classified { + fn pc_sample_target(&self, physical: u64, _: u8) -> Option { + (physical == SAMPLER).then_some(1) + } + fn requires_canonical_read(&self, _: usize, physical: u64, _: DeviceReadShape) -> bool { + physical == CANONICAL + } + fn requires_canonical_write(&self, _: usize, physical: u64, _: u8) -> bool { + physical == CANONICAL + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + self.reads += 1; + Ok(7) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + self.writes += 1; + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + } + let (hub, _) = hub(2); + let mut worker = SharedDevices::new(Classified::default(), hub).worker(); + assert_eq!(worker.read_scalar(1, 0x30, 4, 0), ScalarRead::Served(Ok(7))); + assert_eq!( + worker.read_scalar(1, CANONICAL, 4, 0), + ScalarRead::Canonical + ); + assert_eq!(worker.read_scalar(1, SAMPLER, 4, 0), ScalarRead::Sample(1)); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut machine = board(&[], worker, identities); + let (devices, processors) = machine.processor_write_parts(); + assert!( + devices + .write_settled(0, CANONICAL, 4, 1, 0, processors) + .is_none() + ); + let (devices, processors) = machine.processor_write_parts(); + let written = devices + .write_settled(0, 0x30, 4, 1, 0, processors) + .expect("a plain write"); + assert_eq!(written.written, Ok(())); + assert!( + written + .settled + .is_some_and(|settled| settled.transfer.is_ok()) + ); + // Only the plain accesses reached the registers. + assert_eq!( + machine + .devices + .with(|devices| (devices.reads, devices.writes)), + (1, 1) + ); +} + +#[test] +fn board_grace_follows_run_loop_flags() { + let (hub, _) = hub(2); + let grace = &hub.board.grace; + assert!(!grace.inside(0) && !grace.inside(1)); + // Entering the run loop enters the section; parking leaves it. + hub.set_outside(0, false); + hub.set_outside(1, false); + assert!(grace.inside(0) && grace.inside(1)); + let snapshot = grace.snapshot(); + assert!(!grace.passed(&snapshot, None)); + hub.set_parked(1, true); + assert!(!grace.inside(1)); + assert!(!grace.passed(&snapshot, None), "PE 0 has not moved on"); + // A loop top passes; parked and outside together stay outside. + hub.pass(0); + assert!(grace.passed(&snapshot, None)); + hub.set_outside(1, true); + hub.set_parked(1, false); + assert!(!grace.inside(1)); + hub.pass(1); + hub.set_outside(1, false); + assert!(grace.inside(1)); + // A PE that was outside at the snapshot never holds it up. + hub.set_outside(0, true); + let snapshot = grace.snapshot(); + hub.pass(1); + assert!(grace.passed(&snapshot, None)); +} + +#[test] +fn board_wait_runs_out_and_reports_once() { + use super::super::board::Waited; + let (hub, _) = hub(2); + hub.set_outside(0, false); + hub.set_outside(1, false); + let snapshot = hub.board.grace.snapshot(); + let mut now = 0u64; + let mut counter = || { + now += 10; + now + }; + // PE 1 stays inside: PE 0's wait ends at its deadline, back inside. + assert_eq!( + hub.board.wait(0, &snapshot, 100, &mut counter), + Waited::Overdue { first: true } + ); + assert!(hub.board.grace.inside(0)); + assert_eq!( + hub.board.wait(0, &snapshot, 100, &mut counter), + Waited::Overdue { first: false } + ); + hub.pass(1); + assert_eq!( + hub.board.wait(0, &snapshot, 100, &mut counter), + Waited::Passed + ); +} + +/// A PE that slept through hundreds of other PEs' TLBIs by page, of many +/// processes' pages scattered over the lower half, keeps its kernel +/// translations: its mail merges them into lower-half ranges instead of an +/// invalidation of everything, so the wake path's pages stay in its ITLB. +#[test] +fn a_sleeping_pe_keeps_its_kernel_translations_through_a_pile_of_page_tlbis() { + use crate::machine::system::TlbiKind::VA; + const KERNEL: u64 = 0xffff_fe00_1000_0000; + let (hub, _) = hub(2); + let mut machine = first_of_two(&[], &hub); + let el = machine.cpu.pstate.el; + let variant = machine.current_variant(false, false); + let contexts = machine.contexts(el, variant); + machine.chain.set_contexts(contexts); + for page in 0..32 { + let pc = KERNEL + page * FETCH_PAGE; + machine.fetched_through(1, pc, FETCH_PAGE, true); + machine.translate_page(pc, stela_compiler::x86_64::chain::block_key(page << 12, 2)); + } + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + for _ in 0..600 { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + let (asid, page) = ((seed >> 56) % 200 + 1, (seed >> 20) & 0xff_ffff); + hub.broadcast(1, &[tlbi(VA, asid << 48 | page)]); + } + machine.read_mail().unwrap(); + assert_eq!(machine.statistics.itlb_drops[4], 0, "no whole invalidation"); + assert!(machine.statistics.itlb_sources[super::super::ItlbSource::MailMerged as usize] > 0); + assert_eq!(machine.contexts(el, variant), contexts); + for page in 0..32 { + assert!(machine.current_key(KERNEL + page * FETCH_PAGE).is_some()); + } +} + +#[test] +fn passive_registers_are_read_without_the_devices_lock() { + use super::super::PassiveRegisters; + struct Word(AtomicU64); + impl PassiveRegisters for Word { + fn read(&self, physical: u64, bytes: u8) -> Option { + (physical == 0x40 && bytes == 8).then(|| self.0.load(Ordering::Relaxed)) + } + } + #[derive(Default)] + struct Counted { + word: Option>, + reads: usize, + } + impl Devices for Counted { + fn passive_registers(&self) -> Option> { + self.word + .as_ref() + .map(|word| Arc::clone(word) as Arc) + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + self.reads += 1; + Ok(3) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + } + let word = Arc::new(Word(AtomicU64::new(9))); + let (hub, _) = hub(2); + let home = SharedDevices::new( + Counted { + word: Some(Arc::clone(&word)), + reads: 0, + }, + hub, + ); + let mut worker = home.worker(); + // While another call holds the devices' lock, the passive word reads. + let held = home.board.lock(Call::Other); + assert_eq!(worker.read_scalar(1, 0x40, 8, 0), ScalarRead::Served(Ok(9))); + word.0.store(11, Ordering::Relaxed); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(11)); + drop(held); + // Any other width or address takes the lock to the model. + assert_eq!(worker.read_scalar(1, 0x40, 4, 0), ScalarRead::Served(Ok(3))); + assert_eq!(worker.read_scalar(1, 0x48, 8, 0), ScalarRead::Served(Ok(3))); + assert_eq!(home.with(|devices| devices.reads), 2); + // A word read without its cell is not kept for native code. + assert_eq!( + worker.read_scalar(1, 0x40, 8, 0), + ScalarRead::Served(Ok(11)) + ); + assert!(worker.take_plain_read().is_none()); +} + +/// A passive word served from its own cell is a plain read whose epoch is +/// the cell: native code's read (`device_read_thunk`) holds exactly while +/// the cell still has the value the engine read, at any count, and a write +/// of another value ends it. +#[test] +fn passive_words_are_kept_for_native_reads_while_they_hold_their_value() { + use super::super::PassiveRegisters; + struct Cell(Arc); + impl PassiveRegisters for Cell { + fn read(&self, physical: u64, bytes: u8) -> Option { + self.word(physical, bytes) + .map(|word| word.load(Ordering::Acquire)) + } + fn word(&self, physical: u64, bytes: u8) -> Option> { + (physical == 0x40 && bytes == 8).then(|| Arc::clone(&self.0)) + } + } + #[derive(Default)] + struct Board { + cell: Option>, + } + impl Devices for Board { + fn passive_registers(&self) -> Option> { + self.cell + .as_ref() + .map(|cell| Arc::clone(cell) as Arc) + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(3) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + } + let word = Arc::new(AtomicU64::new(9)); + let cell = Arc::new(Cell(Arc::clone(&word))); + let (hub, _) = hub(2); + let home = SharedDevices::new(Board { cell: Some(cell) }, hub); + let mut worker = home.worker(); + assert_eq!(worker.read_scalar(1, 0x40, 8, 5), ScalarRead::Served(Ok(9))); + let plain = worker.take_plain_read().expect("kept"); + assert!(Arc::ptr_eq(&plain.epoch, &word)); + assert_eq!((plain.seen, plain.value, plain.until), (9, 9, u64::MAX)); + // What the native read checks: the epoch word against what it saw. + assert_eq!(plain.epoch.load(Ordering::Acquire), plain.seen); + word.store(10, Ordering::Release); + assert_ne!(plain.epoch.load(Ordering::Acquire), plain.seen); + // The next read keeps the new value; another width keeps nothing. + assert_eq!( + worker.read_scalar(1, 0x40, 8, 5), + ScalarRead::Served(Ok(10)) + ); + assert_eq!(worker.take_plain_read().map(|plain| plain.value), Some(10)); + assert_eq!(worker.read_scalar(1, 0x40, 4, 5), ScalarRead::Served(Ok(3))); + assert!(worker.take_plain_read().is_none()); +} + +#[test] +fn plain_reads_are_served_again_without_the_lock_while_their_epoch_holds() { + /// A model at 0x40 whose 8-byte read is plain, and a bump of its epoch + /// on every write, as a bus moves it. + #[derive(Default)] + struct Plain { + epoch: Arc, + value: u64, + reads: usize, + } + impl Devices for Plain { + fn plain_epoch(&self, physical: u64, bytes: u8) -> Option<(Arc, u64)> { + (physical == 0x40 && bytes == 8) + .then(|| (Arc::clone(&self.epoch), self.epoch.load(Ordering::SeqCst))) + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + self.reads += 1; + Ok(self.value) + } + fn write( + &mut self, + _: usize, + _: u64, + _: u8, + value: u64, + _: u64, + ) -> Result<(), DeviceError> { + self.epoch.fetch_add(1, Ordering::SeqCst); + self.value = value; + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + } + let (hub, _) = hub(2); + let home = SharedDevices::new(Plain::default(), hub); + let mut worker = home.worker(); + let reads = |home: &SharedDevices| home.with(|devices| devices.reads); + // Each plain read it serves is native code's to serve again. + let plain = |worker: &mut SharedDevices| { + worker.take_plain_read().map(|read| { + ( + read.epoch.load(Ordering::SeqCst), + read.seen, + read.value, + read.until, + ) + }) + }; + assert_eq!(worker.read_scalar(1, 0x40, 8, 0), ScalarRead::Served(Ok(0))); + assert_eq!(plain(&mut worker), Some((0, 0, 0, u64::MAX))); + assert_eq!(plain(&mut worker), None); + assert_eq!(reads(&home), 1); + // Served again while another call holds the devices' lock. + let held = home.board.lock(Call::Other); + assert_eq!(worker.read_scalar(1, 0x40, 8, 1), ScalarRead::Served(Ok(0))); + assert_eq!(plain(&mut worker), Some((0, 0, 0, u64::MAX))); + drop(held); + assert_eq!(reads(&home), 1); + // A write by another PE moves the epoch: the next read reaches the model. + let mut other = home.worker(); + other.write(0, 0x40, 8, 5, 2).unwrap(); + assert_eq!(worker.read_scalar(1, 0x40, 8, 3), ScalarRead::Served(Ok(5))); + assert_eq!(worker.read_scalar(1, 0x40, 8, 4), ScalarRead::Served(Ok(5))); + assert_eq!(reads(&home), 2); + // Other reads, and any read once a device deadline passed, reach it. + assert_eq!(worker.read_scalar(1, 0x48, 8, 5), ScalarRead::Served(Ok(5))); + assert_eq!(plain(&mut worker), None); + assert_eq!(worker.read_scalar(1, 0x40, 4, 5), ScalarRead::Served(Ok(5))); + assert_eq!(plain(&mut worker), None); + assert_eq!(reads(&home), 4); + home.board.time.store(6, Ordering::Release); + assert_eq!(worker.read_scalar(1, 0x40, 8, 6), ScalarRead::Served(Ok(5))); + assert_eq!(reads(&home), 5); + // Kept with the deadline it found. + assert_eq!(plain(&mut worker), Some((1, 1, 5, 6))); +} + +/// The copies a transfer leaves ([`Devices::take_unlocked`]) run on the PE +/// that settled the write, after it released the devices' lock, each once, +/// with PEs settling at once; and what each came to is published by a +/// transfer on that PE before its call returns, with no other PE or tick +/// coming by (otherwise a completion can wait for an idle home machine). +#[test] +fn transfers_leave_their_copies_to_run_outside_the_lock() { + use super::super::{LockedMemory, Memory, UnlockedDma}; + use crate::machine::mmu::MemoryLocks; + use std::sync::OnceLock; + type Shared = Arc>>>; + struct Copy { + board: Shared, + address: u64, + ran: Arc, + alone: Arc, + } + impl UnlockedDma for Copy { + fn run(self: Box, memory: &mut dyn Memory) { + let board = self.board.get().expect("the board is built"); + // Free unless another PE took it since: checked while one runs. + if self.alone.load(Ordering::SeqCst) { + assert!(board.devices.try_lock().is_ok(), "outside the lock"); + } + assert!(memory.write(self.address, &[1])); + self.ran.fetch_add(1, Ordering::SeqCst); + } + } + /// A device whose write starts a copy and whose transfer publishes + /// every copy that ran. + struct Copying { + board: Shared, + deferred: bool, + wants: [bool; 4], + left: Vec>, + ran: Arc, + published: usize, + alone: Arc, + } + impl Devices for Copying { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, cpu: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + self.wants[cpu] = true; + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } + fn defer_dma(&mut self) { + self.deferred = true; + } + fn take_unlocked(&mut self) -> Vec> { + core::mem::take(&mut self.left) + } + fn transfer(&mut self, cpu: usize, _: &mut dyn Memory, _: u64) -> Result<(), DeviceError> { + assert!(self.deferred, "a shared board defers its copies"); + self.published = self.ran.load(Ordering::SeqCst); + if core::mem::take(&mut self.wants[cpu]) { + self.left.push(Box::new(Copy { + board: Arc::clone(&self.board), + address: cpu as u64, + ran: Arc::clone(&self.ran), + alone: Arc::clone(&self.alone), + })); + } + Ok(()) + } + } + /// RAM that counts each PE's byte. + struct Counted(Arc<[AtomicUsize; 4]>); + impl Memory for Counted { + fn read(&mut self, _: u64, _: &mut [u8]) -> bool { + true + } + fn write(&mut self, physical: u64, _: &[u8]) -> bool { + self.0[physical as usize].fetch_add(1, Ordering::SeqCst); + true + } + } + impl LockedMemory for Counted { + fn under(&mut self, _: MemoryLocks) -> &mut dyn Memory { + self + } + } + let board: Shared = Arc::new(OnceLock::new()); + let ran = Arc::new(AtomicUsize::new(0)); + let alone = Arc::new(AtomicBool::new(true)); + let devices = Copying { + board: Arc::clone(&board), + deferred: false, + wants: [false; 4], + left: Vec::new(), + ran: Arc::clone(&ran), + published: 0, + alone: Arc::clone(&alone), + }; + let hub = Hub::new(4, Ticks(Arc::new(AtomicUsize::new(0)))); + let home = SharedDevices::new(devices, hub); + assert!(board.set(Arc::clone(&home.board)).is_ok()); + let written = Arc::new([const { AtomicUsize::new(0) }; 4]); + // One PE, every other one idle: the copy ran and its result is + // published before the call returns. + let mut first = home.worker(); + first.write(1, 0, 4, 0, 0).unwrap(); + assert!( + first + .settle_write(1, 0, &mut Counted(Arc::clone(&written))) + .transfer + .is_ok() + ); + assert_eq!(ran.load(Ordering::SeqCst), 1, "before the call returned"); + assert_eq!( + home.with(|devices| devices.published), + 1, + "published at once" + ); + alone.store(false, Ordering::SeqCst); + written[1].store(0, Ordering::SeqCst); + ran.store(0, Ordering::SeqCst); + const ROUNDS: usize = 200; + let threads: Vec<_> = (1..4) + .map(|cpu| { + let mut worker = home.worker(); + let written = Arc::clone(&written); + std::thread::spawn(move || { + for _ in 0..ROUNDS { + worker.write(cpu, 0, 4, 0, 0).unwrap(); + let settled = worker.settle_write(cpu, 0, &mut Counted(Arc::clone(&written))); + assert!(settled.transfer.is_ok()); + } + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(ran.load(Ordering::SeqCst), 3 * ROUNDS); + for cpu in 1..4 { + assert_eq!(written[cpu].load(Ordering::SeqCst), ROUNDS, "PE {cpu}"); + } + assert_eq!( + home.with(|devices| (devices.left.len(), devices.published)), + (0, 3 * ROUNDS), + "every copy published by its own call" + ); +} + +/// A PE gone parallel runs on its hub control, with the board's stamped +/// cells and stamps of the board's table: an exit out of the page whose +/// cell its cell probes named often gets a stamped cell and a stamped tail, +/// and its stamps are counted. +#[test] +fn a_parallel_pe_promotes_the_exits_its_cell_probes_named() { + use super::super::tests::{NATIVE_CODE_STRIDE, machine}; + use stela_compiler::block::ExitKind; + const ADD: u32 = 0x9100_0400; // add x0, x0, #1 + const RET: u32 = 0xd65f_03c0; + let mut words = vec![0; 1026]; + words[0] = 0x1400_0400; // b .+0x1000 + words[1024] = ADD; + words[1025] = RET; + let mut machine = machine(&words); + let base = machine.cpu.pc; + let far = base + 0x1000; + let exit = |next_pc, kind: ExitKind| super::super::NativeExit::Exit { + next_pc, + kind: kind as u64, + }; + machine.host.exits = vec![exit(far, ExitKind::Direct), exit(base, ExitKind::Return)]; + let (hub, _) = hub(1); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + machine.step().unwrap(); + machine.step().unwrap(); + let first = &machine.code.blocks[0]; + let code = &machine.host.installed[first.code.0 / NATIVE_CODE_STRIDE - 1]; + let site = chain::direct_patch((first.code.0 + code.len() - chain::DIRECT_EXIT_BYTES) as u64); + let (address, cells, stamps_held) = { + let mut cache = machine.code.cache(); + let number = cache.targets.site_cell_number(site).expect("a cell"); + assert!(number as usize >= chain::STAMPED_CELLS); + let control = machine.chain.snapshot(); + ( + cache.targets.cell_address(number), + cache.targets.stamped_cells(), + cache.targets.holds_stamps(control.stamps), + ) + }; + let control = machine.chain.snapshot(); + let patches = machine.host.patches.len(); + // The samples its cell probes take of the exit's cell. + for _ in 0..super::super::scheduler::HOT_SAMPLES { + machine.cell_samples.push(address); + } + machine.promote_hot_exits(); + assert_eq!(machine.host.patches.len(), patches + 2, "a stamped tail"); + assert_eq!( + machine.host.patches[patches].1.len(), + chain::STAMPED_TAIL_BYTES + ); + let number = machine.code.cache().targets.site_cell_number(site); + assert!(number.is_some_and(|number| (number as usize) < chain::STAMPED_CELLS)); + assert_eq!(machine.statistics.stamped_tails, 1); + assert_eq!(machine.statistics.stamped_in_use, 1); + assert_eq!(control.cells, cells, "the board's stamped cells"); + assert!(stamps_held, "stamps of the board's table"); + // What the stamped tails count is read from the PE's own stamps. + assert_eq!(machine.chain.stamp_counts(), [0; chain::STAMP_COUNTS]); +} + +/// A PE's jump cache holds across native entries (`chain::lookup_tail`): +/// its entries name the contexts and ITLB drop epoch they were filled +/// under, which the tails compare, so an entry stays until its table entry +/// changes. +#[test] +fn the_jump_cache_holds_across_native_entries() { + let mut machine = super::super::tests::machine(&[0xd65f_03c0]); + let stamps = machine.chain.stamps().0; + assert_ne!(stamps, 0, "every PE's control has stamps before it runs"); + let pc = 0xffff_fe00_0000_1234_u64; + let at = chain::jump_entry(stamps, pc) as *mut u64; + // SAFETY: the PC word of an entry of the PE's live jump cache; no + // native code runs meanwhile. + unsafe { at.write(pc) }; + machine.chain.begin(0, 16); + machine.chain.begin(0, 16); + // SAFETY: as above. + assert_eq!(unsafe { at.read() }, pc); +} + +/// A PE that joins a board other than the one it was made on takes stamps +/// of the board's table, not of its first board's, which goes. +#[test] +fn a_pe_that_joins_the_board_takes_stamps_of_its_table() { + use super::super::board; + use super::super::tests::machine; + let mut memory = vec![0u8; 4 * 4096]; + let window = super::super::CodeWindow { + exec: memory.as_mut_ptr() as usize, + write: memory.as_mut_ptr() as usize, + bytes: memory.len(), + }; + let arena = || { + Arc::new(board::Code::new( + board::slot_capacity(Some(window.bytes)), + chain::MIN_LOOKUP_ENTRIES, + Some(window), + )) + }; + let shared = arena(); + let (hub, _) = hub(2); + hub.share_code(&shared); + let mut second = machine(&[0xd65f_03c0]); + second.code = arena(); + second.attach_stamps(); + let (_attached, control) = Attached::new(&hub, 1, false).unwrap(); + second.join_code(&hub); + assert!(Arc::ptr_eq(&second.code, &shared)); + second.adopt_parallel_control(control); + let control = second.chain.snapshot(); + let mut cache = shared.cache(); + assert_eq!(control.cells, cache.targets.stamped_cells()); + assert!(cache.targets.holds_stamps(control.stamps)); +} + +/// A WFE of a PE that is not home ends inside the scheduler's entry when +/// its next own wake is within the halt-poll: at its event stream edge, or +/// earlier on another PE's SEV, with mail that came during the spin read +/// before the guest runs again. A wake past the poll, and the home PE, +/// take the wait passes. +#[test] +fn a_short_wfe_completes_in_its_exit_without_the_wait_passes() { + use super::super::tests::{BASE, FakeHost, machine}; + use crate::machine::NoDevices; + use crate::machine::system::Register as SystemRegister; + use crate::machine::system::TlbiKind::VAA; + const WFE: u32 = 0xd503_205f; + let start = |events: u64| { + let (hub, _) = hub(2); + let mut machine = machine(&[]); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + hub.home.store(1, Ordering::Relaxed); + machine.host.counter_step = 1; + machine.idle_poll = 300; + // CNTHCTL_EL2.EVNTEN with EVNTI `events`: edges 2^(events+1) apart. + machine + .cpu + .registers + .set(SystemRegister::CNTHCTL_EL2, 0, 1 << 2 | events << 4); + (hub, machine) + }; + let wfe = |machine: &mut Machine| { + machine.cpu.pc = BASE; + machine.system_instruction(WFE).unwrap(); + machine.schedule() + }; + // Edges 128 counts apart: the spin reaches the next one. + let (_hub, mut machine) = start(6); + let edge = crate::machine::timer::next_event(&machine.cpu, machine.host.now).unwrap(); + wfe(&mut machine).unwrap(); + assert!(machine.waiting.is_none() && !machine.cpu.event); + assert_eq!(machine.cpu.pc, BASE + 4); + let statistics = &machine.statistics; + assert_eq!((statistics.waits, statistics.short_waits), (1, 1)); + assert_eq!(statistics.halt_ticks, 0); + assert!(machine.host.timers.is_empty(), "no halt was armed"); + assert!(machine.host.now >= edge && machine.host.now < edge + 100); + // Another PE's TLBI and SEV during the spin: both are read in it and + // the SEV ends the WFE before the edge. + let (hub, mut machine) = start(7); + let edge = crate::machine::timer::next_event(&machine.cpu, machine.host.now).unwrap(); + let sender = Arc::clone(&hub); + machine.host.on_relax = Some(Box::new(move |turn| { + if turn == 3 { + sender.broadcast(1, &[tlbi(VAA, 0x1234)]); + sender.event(1); + } + })); + wfe(&mut machine).unwrap(); + assert!(machine.waiting.is_none()); + assert!(!hub.pending(0), "the mail was read"); + assert_eq!(machine.statistics.short_waits, 1); + assert!(machine.host.now < edge, "the SEV ended it"); + // Edges 65536 counts apart, past the poll: the wait passes take it. + let (_hub, mut machine) = start(15); + wfe(&mut machine).unwrap(); + assert!(machine.waiting.is_none()); + assert_eq!(machine.statistics.short_waits, 0); + assert!(machine.statistics.waits > 0); + // The home PE always takes the passes. + let (hub, mut machine) = start(6); + hub.home.store(0, Ordering::Relaxed); + wfe(&mut machine).unwrap(); + assert_eq!(machine.statistics.short_waits, 0); + // Under step timing the spin, and a pass's poll, are idle time; only + // under it. + assert!(machine.host.idle_marks.is_empty()); + for home in [1, 0] { + let (hub, mut machine) = start(6); + hub.home.store(home, Ordering::Relaxed); + machine.set_step_timing(true); + wfe(&mut machine).unwrap(); + let marks = &machine.host.idle_marks; + assert!( + !marks.is_empty() && marks.len() % 2 == 0, + "{home} {marks:?}" + ); + assert!( + marks.chunks(2).all(|pair| pair == [true, false]), + "{home} {marks:?}" + ); + } +} + +/// A WFE that spins on its Exclusives monitor, as XNU's ticket waiters do, +/// keeps its PE's guest work through the wait passes, so the shared count +/// waits for it if the host keeps it from them; a store to its granule ends +/// the wait. A WFE with no monitor armed holds nothing. +#[test] +fn a_wfe_spinning_on_its_monitor_keeps_guest_work_through_its_wait() { + use super::super::tests::{BASE, machine}; + use crate::machine::cpu::{RESERVATION_GRANULE, Reservation}; + const WFE: u32 = 0xd503_205f; + const GRANULE: u64 = BASE + 0x800; + let wait = |monitor: bool| { + let (hub, _) = hub(2); + let mut machine = machine(&[]); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + hub.home.store(1, Ordering::Relaxed); + machine.host.counter_step = 1; + if monitor { + let mut bytes = [0; RESERVATION_GRANULE as usize]; + assert!(machine.host.read_ram(GRANULE, &mut bytes)); + machine.cpu.monitor = Some(Reservation { + granule: GRANULE, + bytes, + }); + } + machine.cpu.pc = BASE; + machine.system_instruction(WFE).unwrap(); + let _ = machine.schedule(); + (hub, machine) + }; + let (_hub, mut machine) = wait(true); + assert!(machine.waiting.is_some(), "nothing woke it"); + assert!(machine.clock.has_guest_work(), "a spinner has guest work"); + // In the kernel its spin is timed from its first pass, and later + // passes keep that start. + let started = machine.clock.spin_started(); + assert!(started.is_some(), "a kernel spin publishes its start"); + let _ = machine.schedule(); + assert_eq!(machine.clock.spin_started(), started); + // Another core's store to the granule (the ticket's turn) wakes it. + assert!(machine.host.write_ram(GRANULE, &[1])); + let _ = machine.schedule(); + assert!(machine.waiting.is_none()); + assert_eq!(machine.cpu.pc, BASE + 4); + assert!(machine.clock.has_guest_work()); + let (_hub, machine) = wait(false); + assert!(machine.waiting.is_some()); + assert!(!machine.clock.has_guest_work(), "a plain WFE holds nothing"); + assert_eq!(machine.clock.spin_started(), None); +} + +/// A device whose IRQ rises at `irq_at`, which a write sets; counts its +/// advances where reading the count takes no lock. +struct Armed { + irq_at: u64, + advances: Arc, +} + +impl Devices for Armed { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, value: u64, _: u64) -> Result<(), DeviceError> { + self.irq_at = value; + Ok(()) + } + fn lines(&mut self, _: usize, now: u64) -> Lines { + Lines { + irq: now >= self.irq_at, + ..Lines::default() + } + } + fn deadline(&mut self, now: u64) -> Option { + self.advances.fetch_add(1, Ordering::Relaxed); + (now < self.irq_at).then_some(self.irq_at) + } +} + +/// The home machine's wait pass advances the devices once: the deadline +/// its cached lines came with stands in for a second advance, until +/// another PE's call reaches the devices, such as one that arms an earlier +/// deadline, which the next pass then sees. +#[test] +fn home_reuses_its_lines_deadline_until_another_pe_reaches_the_devices() { + use super::super::tests::board; + use stela_contracts::identity::Identity; + let (hub, _) = hub(2); + let count = Arc::new(AtomicUsize::new(0)); + let home = SharedDevices::new( + Armed { + irq_at: 100, + advances: Arc::clone(&count), + }, + hub, + ); + let mut worker = home.worker(); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut machine = board(&[], home, identities); + let advances = |_: &Machine<_, SharedDevices>| count.load(Ordering::Relaxed); + assert!(!machine.device_lines_of(0, 10).irq); + let before = advances(&machine); + assert_eq!(machine.next_deadline(10), Some(100)); + assert_eq!(machine.next_deadline(20), Some(100)); + assert_eq!(advances(&machine), before, "no second advance"); + // PE 1 arms an earlier deadline: the next pass asks the devices. + worker.write(1, 0x30, 4, 50, 20).unwrap(); + assert_eq!(machine.next_deadline(20), Some(50)); + assert_eq!(advances(&machine), before + 1); + // Past the cached deadline the devices are asked again too. + machine.device_lines = None; + assert!(!machine.device_lines_of(0, 30).irq); + let before = advances(&machine); + assert_eq!(machine.next_deadline(40), Some(50)); + assert_eq!(advances(&machine), before); + assert_eq!(machine.next_deadline(60), None); + assert_eq!(advances(&machine), before + 1); +} + +/// Quiescent maintenance: the post-then-entry order. Mail posted while a +/// PE is between blocks counts as applied at once, and the PE's next entry +/// finds it and does not enter until it has read it. +#[test] +fn mail_posted_between_blocks_is_applied_at_once_and_blocks_the_next_entry() { + let (hub, _) = hub(2); + hub.leave_active(1); + let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); + assert_eq!(posted.len(), 1, "reached and interrupted"); + assert!( + hub.applied(&mut posted), + "a PE between blocks is not waited for" + ); + assert!(!hub.enter_active(1), "the entry finds the mail"); + assert_eq!(hub.inboxes[1].active.load(Ordering::SeqCst) & 1, 0); + let mail = hub.take(1).unwrap(); + hub.acknowledge(1, mail.serial); + assert!(hub.enter_active(1), "read, it enters"); +} + +/// The entry-then-post order: a PE running a block is waited for until it +/// applies the mail or leaves the block, whichever is first. +#[test] +fn mail_posted_while_a_pe_runs_a_block_waits_for_it_to_apply_or_leave() { + let (hub, _) = hub(3); + let mut posted = hub.broadcast(0, &[Maintenance::Code(None)]); + assert_eq!(posted.len(), 2); + assert!(!hub.applied(&mut posted)); + // PE 1 applies it while it runs; PE 2 leaves its block without it. + let mail = hub.take(1).unwrap(); + hub.acknowledge(1, mail.serial); + assert!(!hub.applied(&mut posted)); + assert_eq!(posted, [(2, 1)]); + hub.leave_active(2); + assert!(hub.applied(&mut posted)); + // Left without reading it, PE 2 reads it before its next block. + assert!(!hub.enter_active(2)); + let mail = hub.take(2).unwrap(); + hub.acknowledge(2, mail.serial); + assert!(hub.enter_active(2)); +} + +/// A broadcast's DSB does not wait for a PE between blocks, however long +/// it stays there (fetching, compiling, scheduling): the wait takes no +/// turn at all, and the mail stays for the PE's next entry. +#[test] +fn a_completion_does_not_wait_for_a_pe_between_blocks() { + let (hub, _) = hub(2); + hub.leave_active(1); + let mut machine = first_of_two(&[], &hub); + machine.post(Maintenance::Code(Some(0x4000))); + machine.send_outgoing(); + machine.complete_maintenance().unwrap(); + assert_eq!(machine.host.relaxes, 0, "no turn of the wait"); + assert!(machine.posted.is_empty()); + assert!(hub.pending(1)); + assert!(!hub.enter_active(1)); +} + +/// A machine that mail reached after its fetch does not run what it +/// fetched: it reads the mail first and fetches again, so it never runs +/// a block the mail retired. +#[test] +fn a_machine_reads_mail_that_came_after_its_fetch_before_it_runs_the_block() { + use super::super::tests::BASE; + use stela_compiler::block::ExitKind; + let (hub, _) = hub(2); + // NOP; NOP. + let mut machine = first_of_two(&[0xd503_201f, 0xd503_201f], &hub); + let exit = |next_pc| super::super::NativeExit::Exit { + next_pc, + kind: ExitKind::Direct as u64, + }; + // The block runs once and comes back to itself: it stays installed. + machine.host.exits = vec![exit(BASE), exit(BASE + 8)]; + machine.step().unwrap(); + assert_eq!(machine.cpu.pc, BASE); + // PE 1 discards every block while PE 0 is between blocks; PE 0's next + // fetch still finds the old block. + let mut posted = hub.broadcast(1, &[Maintenance::Code(None)]); + let posted_serial = posted[0].1; + assert!(hub.applied(&mut posted)); + machine.step().unwrap(); + assert_eq!(machine.cpu.pc, BASE, "nothing ran"); + assert_eq!(machine.host.exits.len(), 1); + assert_eq!(hub.inboxes[0].active.load(Ordering::SeqCst) & 1, 0); + // Its schedule reads the mail, and the next step runs a fresh block. + machine.read_mail().unwrap(); + assert!(!hub.pending(0)); + assert_eq!(hub.inboxes[0].applied.load(Ordering::SeqCst), posted_serial); + machine.step().unwrap(); + assert_eq!(machine.cpu.pc, BASE + 8); + assert!(machine.host.exits.is_empty()); + assert_eq!(hub.inboxes[0].active.load(Ordering::SeqCst) & 1, 0); +} + +/// Racing posts against a PE that enters and leaves blocks: whenever the +/// broadcaster has counted a post as applied, the PE, inside any block it +/// runs, has applied it. Bounded by counts, not by time. +#[test] +fn a_pe_inside_a_block_has_applied_every_post_counted_as_applied() { + const POSTS: u64 = 5_000; + let (hub, _) = hub(2); + hub.leave_active(1); + let required = AtomicU64::new(0); + let done = AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + let mut applied = 0; + let mut entries = 0u64; + while !done.load(Ordering::SeqCst) { + if let Some(mail) = hub.take(1) { + applied = mail.serial; + hub.acknowledge(1, mail.serial); + continue; + } + if hub.enter_active(1) { + entries += 1; + assert!(required.load(Ordering::SeqCst) <= applied); + for _ in 0..(entries % 16) { + core::hint::spin_loop(); + } + assert!(required.load(Ordering::SeqCst) <= applied); + hub.leave_active(1); + } + } + }); + for page in 1..=POSTS { + let mut posted = hub.broadcast(0, &[Maintenance::Code(Some(page << 14))]); + let serial = posted[0].1; + while !hub.applied(&mut posted) { + std::thread::yield_now(); + } + required.store(serial, Ordering::SeqCst); + } + done.store(true, Ordering::SeqCst); + }); +} + +/// A DSB completes natively while this PE has no maintenance outstanding, +/// in any state and across derived state changes, and exits to the engine +/// once a post or an open code page cell leaves it something to complete; +/// the engine's DSB completes that and reopens the native path. +#[test] +fn native_dsb_completes_only_without_outstanding_maintenance() { + use super::super::mirrors::{BARRIER, CODE_PAGE}; + use super::super::tests::{BASE, FakeHost}; + use super::super::transitions::tests::run_native; + use crate::machine::NoDevices; + use crate::machine::exception::Pstate; + use stela_compiler::x86_64::register_read; + use stela_compiler::{GuestAddress, block::ExitKind}; + const DSB_ISH: u32 = 0xd503_3b9f; + let (hub, _) = hub(2); + let mut machine = first_of_two(&[DSB_ISH], &hub); + machine.cpu.pstate = Pstate::reset(1); + let thunk = register_read::barrier_thunk(GuestAddress(BASE), BARRIER); + let native = |machine: &mut Machine| { + let exit = run_native(machine, &thunk.code); + if exit == (BASE + 4, ExitKind::Fallthrough as u64) { + true + } else { + assert_eq!(exit, (BASE, ExitKind::System as u64)); + false + } + }; + let engine = |machine: &mut Machine| { + machine.cpu.pc = BASE; + machine.system_instruction(DSB_ISH).unwrap(); + assert_eq!(machine.cpu.pc, BASE + 4); + }; + assert!(!native(&mut machine), "no DSB completed yet"); + engine(&mut machine); + assert!(native(&mut machine)); + // Neither derived state nor the PE's state decides it. + machine.derived_changed(); + assert!(native(&mut machine), "derived state changed"); + machine.cpu.pstate.el = 0; + assert!(native(&mut machine), "at EL0"); + machine.cpu.pstate.el = 1; + // Maintenance while the other PE runs no block goes at once, and it + // will read it before it runs one: the DSB has nothing to complete. + hub.leave_active(1); + machine.post(Maintenance::Code(None)); + assert!(machine.outgoing.is_empty() && machine.posted.is_empty()); + assert!(hub.take(1).is_some()); + assert!(native(&mut machine), "nobody to wait for"); + // Maintenance while it runs a block: the DSB must send it and wait. + assert!(hub.enter_active(1)); + machine.post(Maintenance::Code(None)); + assert!(!native(&mut machine), "maintenance posted"); + assert!(hub.take(1).is_none(), "kept for the DSB"); + hub.set_live(1, false); + engine(&mut machine); + assert!(machine.outgoing.is_empty() && machine.posted.is_empty()); + assert!(native(&mut machine)); + hub.set_live(1, true); + // A code page cell the DSB that ends the run of lines must close. + machine.mirrors.open_code_page(0x4000); + assert!(!native(&mut machine), "code page cell open"); + engine(&mut machine); + assert_eq!(machine.mirrors[CODE_PAGE].readable, 0); + assert!(native(&mut machine)); +} + +/// Host work a guest exit's device call left (a storage doorbell's disk +/// step) goes to a PE that sleeps waiting for an interrupt, and the caller +/// goes on with its guest; a PE asleep in WFE is not woken for it, and with +/// no PE to take it the caller does the work itself. +#[test] +fn released_host_work_goes_to_a_pe_that_sleeps_waiting_for_an_interrupt() { + #[derive(Default)] + struct Work { + kicked: Mutex>, + due: AtomicBool, + done: AtomicUsize, + } + struct Released(Arc); + impl Kick for Released { + fn kick(&self, pe: usize) { + self.0.kicked.lock().unwrap().push(pe); + } + fn released(&self) -> bool { + if self.0.due.swap(false, Ordering::SeqCst) { + self.0.done.fetch_add(1, Ordering::SeqCst); + } + false + } + fn release_due(&self) -> bool { + self.0.due.load(Ordering::SeqCst) + } + } + let work = Arc::new(Work::default()); + let hub = Hub::new(3, Released(Arc::clone(&work))); + for pe in 0..3 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + // PE 1 is in a guest exit; PE 2 sleeps in WFE. + hub.inboxes[1].outside.store(true, Ordering::SeqCst); + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + work.due.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work.done.load(Ordering::SeqCst), 1, "the caller did it"); + assert!(work.kicked.lock().unwrap().is_empty()); + assert!(!hub.service.load(Ordering::SeqCst)); + let releases = |home: &SharedDevices| { + let times = home.lock_times()[Call::Access as usize]; + (times.stepped, times.handed) + }; + assert_eq!(releases(&home), (1, 0), "counted as done on the caller"); + assert_eq!(home.board.released[1].load(Ordering::SeqCst), 0, "no ticks"); + // PE 2 now sleeps waiting for an interrupt: it is woken for the work. + hub.inboxes[2].serves.store(true, Ordering::SeqCst); + work.due.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work.done.load(Ordering::SeqCst), 1, "the caller went on"); + assert!(work.due.load(Ordering::SeqCst), "left for the service"); + assert_eq!(*work.kicked.lock().unwrap(), [2]); + assert!(hub.take_service()); + assert_eq!(releases(&home), (1, 1), "counted as handed off"); +} + +/// Released host work that only starts commands (a doorbell write) runs +/// on the releasing PE at once, even with a PE asleep to take it: its wake +/// would cost more, and the command would start only after it. +#[test] +fn released_work_that_only_starts_commands_runs_on_the_releasing_pe() { + #[derive(Default)] + struct Work { + kicked: Mutex>, + due: AtomicBool, + inline: AtomicBool, + done: AtomicUsize, + } + struct Released(Arc); + impl Kick for Released { + fn kick(&self, pe: usize) { + self.0.kicked.lock().unwrap().push(pe); + } + fn released(&self) -> bool { + if self.0.due.swap(false, Ordering::SeqCst) { + self.0.done.fetch_add(1, Ordering::SeqCst); + } + false + } + fn release_due(&self) -> bool { + self.0.due.load(Ordering::SeqCst) + } + fn release_inline(&self) -> bool { + self.0.inline.load(Ordering::SeqCst) + } + } + let work = Arc::new(Work::default()); + let hub = Hub::new(3, Released(Arc::clone(&work))); + for pe in 0..3 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + let releases = |home: &SharedDevices| { + let times = home.lock_times()[Call::Access as usize]; + (times.stepped, times.handed) + }; + // PE 1 is in a guest exit; PE 2 sleeps waiting for an interrupt. + hub.inboxes[1].outside.store(true, Ordering::SeqCst); + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + hub.inboxes[2].serves.store(true, Ordering::SeqCst); + work.due.store(true, Ordering::SeqCst); + work.inline.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work.done.load(Ordering::SeqCst), 1, "started on the caller"); + assert!(work.kicked.lock().unwrap().is_empty(), "no PE woken"); + assert!(!hub.service.load(Ordering::SeqCst)); + assert_eq!(releases(&home), (1, 0)); + // Work that also takes completions still goes to the sleeping PE. + work.due.store(true, Ordering::SeqCst); + work.inline.store(false, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work.done.load(Ordering::SeqCst), 1); + assert_eq!(*work.kicked.lock().unwrap(), [2]); + assert_eq!(releases(&home), (1, 1)); +} + +/// A host interrupt a busy PE took at its release (a host disk's completion +/// signal) wakes a PE that sleeps waiting for an interrupt, at that release +/// on the model clock rather than at the busy PE's slice end; with none +/// asleep the busy PE leaves it to the host's service, and work its own +/// release handed on already is not handed twice. +#[test] +fn a_busy_pes_completion_signal_wakes_a_sleeping_pe_at_its_release() { + #[derive(Default)] + struct Signals { + kicked: Mutex>, + signal: AtomicBool, + due: AtomicBool, + now: AtomicU64, + } + struct Signalled(Arc); + impl Kick for Signalled { + fn kick(&self, pe: usize) { + let now = self.0.now.load(Ordering::SeqCst); + self.0.kicked.lock().unwrap().push((pe, now)); + } + fn ticks(&self) -> u64 { + self.0.now.load(Ordering::SeqCst) + } + fn release_due(&self) -> bool { + self.0.due.load(Ordering::SeqCst) + } + fn signal_due(&self) -> bool { + self.0.signal.swap(false, Ordering::SeqCst) + } + } + let signals = Arc::new(Signals::default()); + let hub = Hub::new(3, Signalled(Arc::clone(&signals))); + for pe in 0..3 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + let handed = |home: &SharedDevices| { + let times = home.lock_times()[Call::Access as usize]; + (times.handed, times.signals) + }; + // PE 1 runs its guest; nobody sleeps: the signal waits for the service. + signals.now.store(1_000, Ordering::SeqCst); + signals.signal.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 1_000), Ok(0)); + assert!(signals.kicked.lock().unwrap().is_empty()); + assert!(!hub.service.load(Ordering::SeqCst)); + // PE 2 sleeps waiting for an interrupt: the next signal wakes it at the + // release that took it, at 2_500, not at PE 1's slice end. + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + hub.inboxes[2].serves.store(true, Ordering::SeqCst); + signals.now.store(2_500, Ordering::SeqCst); + signals.signal.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 2_500), Ok(0)); + assert_eq!(*signals.kicked.lock().unwrap(), [(2, 2_500)]); + assert!(hub.take_service()); + assert_eq!(handed(&home), (0, 1)); + // A release that handed its own work on already wakes nobody twice. + hub.inboxes[1].outside.store(true, Ordering::SeqCst); + signals.due.store(true, Ordering::SeqCst); + signals.signal.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 3_000), Ok(0)); + assert_eq!(signals.kicked.lock().unwrap().len(), 2); + assert_eq!(handed(&home), (1, 1)); +} + +/// With no PE asleep, a release outside the run loop takes a completion +/// signal's step itself, once for the signal; a stream of signals gets at +/// most one step a release, none at a release that did its own host work +/// already, and none from a PE inside its run loop. +#[test] +fn a_stream_of_signals_gets_at_most_one_step_a_release() { + #[derive(Default)] + struct Signals { + kicked: Mutex>, + due: AtomicBool, + released: AtomicUsize, + stepped: AtomicUsize, + } + struct Stream(Arc); + impl Kick for Stream { + fn kick(&self, pe: usize) { + self.0.kicked.lock().unwrap().push(pe); + } + fn released(&self) -> bool { + self.0.due.store(false, Ordering::SeqCst); + self.0.released.fetch_add(1, Ordering::SeqCst); + false + } + fn release_due(&self) -> bool { + self.0.due.load(Ordering::SeqCst) + } + // A new signal comes before every release. + fn signal_due(&self) -> bool { + true + } + fn signal_step(&self) -> bool { + self.0.stepped.fetch_add(1, Ordering::SeqCst); + false + } + } + let signals = Arc::new(Signals::default()); + let hub = Hub::new(3, Stream(Arc::clone(&signals))); + for pe in 0..3 { + hub.set_live(pe, true); + } + let home = SharedDevices::new(Pending::default(), Arc::clone(&hub)); + let mut worker = home.worker(); + let steps = |home: &SharedDevices| { + let times = home.lock_times()[Call::Access as usize]; + (times.stepped, times.signals, times.signal_steps) + }; + let work = |signals: &Signals| { + ( + signals.released.load(Ordering::SeqCst), + signals.stepped.load(Ordering::SeqCst), + ) + }; + // PE 1 runs in its loop: it leaves the signal to the host's service. + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work(&signals), (0, 0)); + // In a guest exit with nobody asleep, each release steps once. + hub.inboxes[1].outside.store(true, Ordering::SeqCst); + for release in 1..=3 { + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work(&signals), (0, release)); + } + assert_eq!(steps(&home), (0, 0, 3)); + // A release that did its own host work takes no signal step too. + signals.due.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work(&signals), (1, 3)); + assert_eq!(steps(&home), (1, 0, 3)); + // A PE asleep to take it is woken instead. + hub.inboxes[2].sleeping.store(true, Ordering::SeqCst); + hub.inboxes[2].serves.store(true, Ordering::SeqCst); + assert_eq!(worker.read(1, 0x40, 8, 0), Ok(0)); + assert_eq!(work(&signals), (1, 3)); + assert_eq!(*signals.kicked.lock().unwrap(), [2]); + assert_eq!(steps(&home), (1, 1, 3)); +} + +/// A core whose halt waits on a doorbell never polls before it halts; any +/// other polls as Linux's haltpoll governor fits it, at most `most`. +#[test] +fn the_halt_poll_is_none_on_a_doorbell_and_bounded_elsewhere() { + let most = 200; + for (poll, blocked) in [(0, 10), (200, 10), (100, 1000), (0, 1000)] { + assert_eq!(idle_poll_after(poll, blocked, most, true), 0); + } + // A short wait that halted doubles the poll, to at least a quarter. + assert_eq!(idle_poll_after(0, 10, most, false), 50); + assert_eq!(idle_poll_after(50, 10, most, false), 100); + assert_eq!(idle_poll_after(200, 10, most, false), 200); + // Long waits halve it, and below a quarter it stops. + assert_eq!(idle_poll_after(200, 1000, most, false), 100); + assert_eq!(idle_poll_after(50, 1000, most, false), 0); +} + +/// A WFE that waits in the engine, taking no trap, opens its state's cell +/// for native WFE to spin in, only with PEs on cores of their own; one that +/// traps opens none, and a change of derived state closes it. What native +/// spins counted reaches the PE's levels as native code returns. +#[test] +fn engine_waits_open_native_event_spins_only_where_other_pes_run() { + use super::super::mirrors::{EVENT_WAITS, mirror_state}; + use super::super::tests::{BASE, machine}; + use crate::machine::exception::Pstate; + use crate::machine::system::Register as SystemRegister; + use stela_compiler::x86_64::register_read::EventSpin; + const WFE: u32 = 0xd503_205f; + const HCR_TWE: u64 = 1 << 14; + let el1 = mirror_state(1, false); + let mut machine = machine(&[WFE]); + machine.cpu.pstate = Pstate::reset(1); + machine.derived_changed(); + let wait = |machine: &mut Machine<_, _>| { + machine.waiting = None; + machine.cpu.pc = BASE; + machine.system_instruction(WFE).unwrap(); + }; + wait(&mut machine); + assert!(machine.waiting.is_some()); + assert_eq!( + machine.mirrors.banks[el1][EVENT_WAITS].readable, 0, + "serialized" + ); + let (hub, _) = hub(1); + machine.enter_parallel(hub).unwrap(); + wait(&mut machine); + assert!(machine.waiting.is_some()); + assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 1); + machine.derived_changed(); + assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 0); + let hcr = machine.cpu.read(SystemRegister::HCR_EL2); + machine + .cpu + .registers + .set(SystemRegister::HCR_EL2, 0, hcr | HCR_TWE); + machine.derived_changed(); + wait(&mut machine); + assert!(machine.waiting.is_none()); + assert_eq!(machine.cpu.pstate.el, 2, "trapped"); + assert_eq!(machine.mirrors.banks[el1][EVENT_WAITS].readable, 0); + + machine.set_step_timing(true); + machine.mirrors.spin = EventSpin { + completed: 2, + missed: 3, + held: 1, + counts: 96, + start: 7, + turns: 9, + streamed: 4, + held_streak: 0, + held_completed: 0, + }; + machine.take_event_spins(); + let levels = machine.step_timing().unwrap().levels; + assert_eq!( + [ + levels.wfe_spun, + levels.wfe_spin_missed, + levels.wfe_held, + levels.wfe_spin_counts, + levels.wfe_streamed + ], + [2, 3, 1, 96, 4] + ); + assert_eq!(machine.mirrors.spin, EventSpin::default()); +} + +/// With the board's fast-IPI table named to native code, a plain fast-IPI +/// write the engine completes opens its state's cell for native writes, +/// which a change of derived state closes; the PEs native requests found +/// halted are woken through the board when native code returns. +#[test] +fn plain_fast_ipi_writes_open_native_ones_and_native_wakes_reach_the_board() { + use super::super::mirrors::{FAST_IPI_WRITES, mirror_state}; + use super::super::tests::board; + use stela_contracts::identity::Identity; + const MSR: u32 = 0xd51d_f029; // msr s3_5_c15_c0_1, x9 + let (hub, kicks) = hub(2); + let worker = SharedDevices::new(Signalling::default(), Arc::clone(&hub)).worker(); + let identities = vec![Identity { + midr: 0x611f_0320, + mpidr: 0x8000_0000, + clock: None, + caches: None, + }]; + let mut machine = board(&[MSR], worker, identities); + let state = mirror_state(machine.cpu.pstate.el, machine.cpu.pstate.guarded); + let write = |machine: &mut Machine<_, _>| { + let pc = machine.cpu.pc; + machine.cpu.state.x[9] = 1; + machine.system_instruction(MSR).unwrap(); + assert_eq!(machine.cpu.pc, pc + 4); + machine.cpu.pc = pc; + }; + write(&mut machine); + assert_eq!( + machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 0, + "no table named" + ); + assert_eq!(machine.enter_fast_ipi(), Some(())); + let ipi = machine.mirrors.fast_ipi; + let table = machine.devices.fast_ipi_table().unwrap(); + assert_eq!((ipi.base, ipi.pe), (table.base(), 0)); + assert_eq!(ipi.status, table.target(0, 0).unwrap().status); + write(&mut machine); + assert_eq!(machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 1); + machine.derived_changed(); + assert_eq!(machine.mirrors.banks[state][FAST_IPI_WRITES].readable, 0); + hub.inboxes[1].sleeping.store(true, Ordering::SeqCst); + machine.mirrors.fast_ipi.wakes = 1 << 1; + machine.take_fast_ipi_wakes(); + assert_eq!(kicks.load(Ordering::Relaxed), 1); + assert_eq!(machine.mirrors.fast_ipi.wakes, 0); +} + +/// A register a read leaves plain, as an event register whose last event the +/// read took: the device that raises events at 0x50 moves its epoch, as a +/// bus does, before the event is there to read at 0x40. +#[derive(Default)] +struct Events { + epoch: Arc, + pending: u64, + raised: u64, + reads: usize, +} +impl Devices for Events { + fn plain_epoch(&self, physical: u64, bytes: u8) -> Option<(Arc, u64)> { + (physical == 0x40 && bytes == 4 && self.pending == 0) + .then(|| (Arc::clone(&self.epoch), self.epoch.load(Ordering::SeqCst))) + } + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + self.reads += 1; + if self.pending == 0 { + return Ok(0); + } + // Taking an event changes the model: the epoch moves first. + self.epoch.fetch_add(1, Ordering::SeqCst); + self.pending -= 1; + Ok(self.raised - self.pending) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + self.epoch.fetch_add(1, Ordering::SeqCst); + self.pending += 1; + self.raised += 1; + Ok(()) + } + fn lines(&mut self, _: usize, _: u64) -> Lines { + Lines::default() + } +} + +/// The read that takes the last event leaves the next read served without +/// the lock; an event raised since reaches the next read. +#[test] +fn a_read_that_leaves_its_register_plain_serves_the_next_read_without_the_lock() { + let (hub, _) = hub(2); + let home = SharedDevices::new(Events::default(), hub); + let mut worker = home.worker(); + let mut other = home.worker(); + let reads = |home: &SharedDevices| home.with(|devices| devices.reads); + other.write(0, 0x50, 4, 0, 0).unwrap(); + assert_eq!(worker.read_scalar(1, 0x40, 4, 1), ScalarRead::Served(Ok(1))); + // The claim and the read after it under the same lock. + assert_eq!(reads(&home), 2); + assert_eq!(worker.read_scalar(1, 0x40, 4, 2), ScalarRead::Served(Ok(0))); + assert_eq!(reads(&home), 2, "served without the devices"); + // An event raised since moved the epoch: the next read takes it. + other.write(0, 0x50, 4, 0, 3).unwrap(); + assert_eq!(worker.read_scalar(1, 0x40, 4, 4), ScalarRead::Served(Ok(2))); + // Two pending: the first claim leaves the register not plain. + other.write(0, 0x50, 4, 0, 5).unwrap(); + other.write(0, 0x50, 4, 0, 5).unwrap(); + let before = reads(&home); + assert_eq!(worker.read_scalar(1, 0x40, 4, 6), ScalarRead::Served(Ok(3))); + assert_eq!(reads(&home), before + 1); + assert_eq!(worker.read_scalar(1, 0x40, 4, 7), ScalarRead::Served(Ok(4))); + assert_eq!(worker.read_scalar(1, 0x40, 4, 8), ScalarRead::Served(Ok(0))); + assert_eq!(reads(&home), before + 3); +} + +/// Events raised on one core while another reads: no event is lost or +/// taken twice, and a read that began after a raise returned never finds +/// none while that event is untaken. +#[test] +fn events_raised_while_their_register_is_served_plain_are_never_lost_or_late() { + const EVENTS: u64 = 20_000; + let (hub, _) = hub(2); + let home = SharedDevices::new(Events::default(), hub); + let raised = Arc::new(AtomicU64::new(0)); + let mut raiser = home.worker(); + let mut reader = home.worker(); + let raising = { + let raised = Arc::clone(&raised); + std::thread::spawn(move || { + for _ in 0..EVENTS { + raiser.write(0, 0x50, 4, 0, 0).unwrap(); + raised.fetch_add(1, Ordering::SeqCst); + } + }) + }; + let mut taken = 0u64; + while taken < EVENTS { + let before = raised.load(Ordering::SeqCst); + match reader.read_scalar(1, 0x40, 4, 0) { + ScalarRead::Served(Ok(0)) => assert!( + taken >= before, + "a read found none with {} raised before it untaken", + before - taken + ), + ScalarRead::Served(Ok(event)) => { + taken += 1; + assert_eq!(event, taken, "events are taken once, in order"); + } + other => panic!("{other:?}"), + } + } + raising.join().unwrap(); + assert_eq!(reader.read_scalar(1, 0x40, 4, 0), ScalarRead::Served(Ok(0))); + assert_eq!(home.with(|devices| devices.pending), 0); +} + +/// Counts its kicks and reads a counter the test moves, as a host's +/// doorbells and its 24 MHz count do. +struct Served { + kicks: Arc, + host: Arc, +} +impl Kick for Served { + fn kick(&self, _pe: usize) { + self.kicks.fetch_add(1, Ordering::SeqCst); + } + fn count(&self) -> Option { + Some(self.host.load(Ordering::SeqCst)) + } +} + +/// A counter frequency at which the stall limit is 1200 counts. +const SERVED_FREQUENCY: u64 = 24_000; +const SERVED_STALL: u64 = SERVED_FREQUENCY * super::super::clock::STALL_MILLIS / 1000; + +type Clock = super::super::clock::Clock; + +/// Two PEs on a hub whose shared count follows a host counter from 1000, +/// each with its own reader; both run. +fn serving_pair() -> (Arc, Arc, Arc, Clock, Clock) { + let kicks = Arc::new(AtomicUsize::new(0)); + let host = Arc::new(AtomicU64::new(1000)); + let hub = Hub::new( + 2, + Served { + kicks: Arc::clone(&kicks), + host: Arc::clone(&host), + }, + ); + for pe in 0..2 { + hub.set_live(pe, true); + } + Clock::default().seed(&hub.clock, 1000, SERVED_FREQUENCY); + let (mut first, mut second) = (Clock::default(), Clock::default()); + first.attach(Arc::clone(&hub.clock), 0); + second.attach(Arc::clone(&hub.clock), 1); + (hub, kicks, host, first, second) +} + +/// The reported shape: PE 1's guest waits for an interrupt and its core +/// serves the host in a part that takes seconds, while PE 0 runs and sends +/// it a fast IPI. The IPI kicks its core at once, the service sees it at +/// its next part, and the count PE 0 reads goes on at most a stall limit +/// past the IPI however long the part takes: PE 0's XNU never sees PE 1 +/// leave an IPI unanswered for longer. Once PE 1 looks again, the count +/// goes on from there and the held time is lag the slew repays. +#[test] +fn an_ipi_to_a_pe_that_serves_the_host_kicks_it_and_holds_the_count_for_it() { + let (hub, kicks, host, mut first, mut second) = serving_pair(); + first.idle(|| 1000, 0, None); + first.busy(|| 1000, 0, None); + second.idle(|| 1000, 0, None); + // PE 1 starts a service turn with nothing pending. + let epoch = hub.lines_epoch(1); + assert_eq!(hub.set_serving(1, Some(epoch)), None); + let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); + assert_eq!(watch.pending(1000), None); + // A wake with no guest work for it (a SEV, which a WFI does not take) + // neither kicks nor marks it. + hub.event(0); + assert_eq!(kicks.load(Ordering::SeqCst), 0); + // PE 0's fast IPI at host 2000: one kick, and the turn's next look + // finds it. + host.store(2000, Ordering::SeqCst); + hub.lines_changed_unwoken(1); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 1, "the serving PE is kicked"); + assert_eq!(watch.pending(2000), Some(super::Pending::Lines)); + // A second IPI meanwhile kicks it no more. + hub.lines_changed_unwoken(1); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 1); + // PE 1 stays out for five seconds of host time; PE 0 runs and marks + // its progress every 10 counts. + let ipi = 2000; + let mut retired = 0; + let end = 2000 + 5 * SERVED_FREQUENCY; + for now in (2010..end).step_by(10) { + retired += 100; + first.mark(|| now, retired, None); + let count = first.read(|| now); + assert!(count <= ipi + SERVED_STALL, "at {now}: count {count}"); + } + assert_eq!( + first.read(|| end), + ipi + SERVED_STALL, + "held a stall limit on" + ); + assert_eq!( + watch.waited(end), + Some((super::Pending::Lines, Some(end - ipi))), + "the wait is measured from the first wake" + ); + // PE 1 is back in its loop: the count goes on from where it held. + assert_eq!(hub.set_serving(1, None), Some(epoch)); + second.idle(|| end, 0, None); + first.mark(|| end + 10, retired + 100, None); + assert_eq!(first.read(|| end + 10), ipi + SERVED_STALL + 10); + assert_eq!(hub.clock.take_stalled(), end - (ipi + SERVED_STALL)); + // A PE that neither serves nor sleeps is not kicked: it reads its + // lines at its next return to the engine. + hub.lines_changed_unwoken(1); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 1); +} + +/// PE 1's own timer comes due while it serves: the service sees it at its +/// next part, and the count holds a stall limit past the deadline, as for +/// an IPI. Its next wait pass clears the mark. +#[test] +fn a_timer_due_on_a_pe_that_serves_the_host_ends_its_service_and_holds_the_count() { + let (hub, kicks, _host, mut first, mut second) = serving_pair(); + first.idle(|| 1000, 0, None); + first.busy(|| 1000, 0, None); + second.idle(|| 1000, 0, None); + let deadline = 3000; + second.serving(Some(deadline)); + let epoch = hub.lines_epoch(1); + hub.set_serving(1, Some(epoch)); + let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, Some(deadline)); + assert_eq!(watch.pending(2999), None); + assert_eq!(watch.pending(3000), Some(super::Pending::Timer)); + assert_eq!(watch.waited(3500), Some((super::Pending::Timer, Some(500)))); + // Before its deadline it holds nothing; past it a stall limit on. + let mut retired = 0; + for now in (1010..10_000).step_by(10) { + retired += 100; + first.mark(|| now, retired, None); + assert_eq!( + first.read(|| now), + now.min(deadline + SERVED_STALL), + "at {now}" + ); + } + assert_eq!( + kicks.load(Ordering::SeqCst), + 0, + "its own timer needs no kick" + ); + hub.set_serving(1, None); + second.look(|| 10_000); + first.mark(|| 10_010, retired + 100, None); + assert_eq!(first.read(|| 10_010), deadline + SERVED_STALL + 10); +} + +/// A line change for a serving PE that accepts no line (it runs with IRQ +/// and FIQ masked) is no guest work: no kick, no mark, its service goes +/// on. A host call ends the service but holds no count: no guest waits +/// for it. +#[test] +fn only_guest_work_a_serving_pe_would_take_holds_the_count() { + let (hub, kicks, host, mut first, mut second) = serving_pair(); + first.idle(|| 1000, 0, None); + first.busy(|| 1000, 0, None); + second.idle(|| 1000, 0, None); + let epoch = hub.lines_epoch(1); + hub.set_accepts(1, Lines::default()); + hub.set_serving(1, Some(epoch)); + let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); + host.store(2000, Ordering::SeqCst); + hub.lines_changed_unwoken(1); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 0, "not kicked"); + assert_eq!(watch.pending(2000), None, "its service goes on"); + hub.inboxes[1].host_call.store(true, Ordering::SeqCst); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 1, "a host call kicks it"); + assert_eq!( + watch.waited(2100), + Some((super::Pending::HostCall, Some(100))) + ); + let mut retired = 0; + for now in (2010..10_000).step_by(10) { + retired += 100; + first.mark(|| now, retired, None); + assert_eq!(first.read(|| now), now, "nothing holds the count"); + } + hub.set_serving(1, None); + // Accepting the FIQ alone, a line change is guest work again. + hub.inboxes[1].host_call.store(false, Ordering::SeqCst); + let epoch = hub.lines_epoch(1); + hub.set_accepts( + 1, + Lines { + irq: false, + fiq: true, + }, + ); + hub.set_serving(1, Some(epoch)); + host.store(10_000, Ordering::SeqCst); + hub.lines_changed_unwoken(1); + hub.wake(1); + assert_eq!(kicks.load(Ordering::SeqCst), 2); + for now in (10_000..20_000).step_by(10) { + retired += 100; + first.mark(|| now, retired, None); + } + assert_eq!(first.read(|| 20_000), 10_000 + SERVED_STALL); +} + +/// Guest work already there when a PE begins to serve marks the count, as +/// a wake would, without kicking its own core; a forwarded access waits +/// only for the home machine, a stop only for the others. +#[test] +fn guest_work_before_a_service_begins_marks_the_count_without_a_kick() { + let (hub, kicks, host, _first, mut second) = serving_pair(); + second.idle(|| 1000, 0, None); + let epoch = hub.lines_epoch(1); + host.store(1500, Ordering::SeqCst); + hub.lines_changed_unwoken(1); + hub.set_serving(1, Some(epoch)); + assert_eq!(kicks.load(Ordering::SeqCst), 0); + let watch = GuestWatch::new(Some(Arc::clone(&hub)), 1, epoch, None); + assert_eq!(watch.waited(1600), Some((super::Pending::Lines, Some(100)))); + hub.set_serving(1, None); + let epoch = hub.lines_epoch(1); + hub.requested.store(true, Ordering::SeqCst); + assert_eq!(hub.guest_pending(1, epoch), None, "PE 1 is not home"); + assert_eq!( + hub.guest_pending(0, hub.lines_epoch(0)), + Some(super::Pending::Forward) + ); + hub.requested.store(false, Ordering::SeqCst); + hub.stopped.store(true, Ordering::SeqCst); + assert_eq!(hub.guest_pending(1, epoch), Some(super::Pending::Stop)); + assert_eq!( + hub.guest_pending(0, hub.lines_epoch(0)), + None, + "home runs on" + ); +} + +/// A serving PE's line changes are guest work only while it takes a line: +/// running with IRQ and FIQ masked it takes none, waiting it is woken by +/// either. +#[test] +fn a_serving_pe_waits_for_a_line_change_only_while_it_takes_a_line() { + use super::super::tests::serving_timer; + use crate::machine::exception::{DAIF_F, DAIF_I}; + struct NoKick; + impl Kick for NoKick { + fn kick(&self, _pe: usize) {} + } + for (daif, wait, expected) in [ + (DAIF_I | DAIF_F, false, None), + (DAIF_I, false, Some(super::Pending::Lines)), + (0, false, Some(super::Pending::Lines)), + (DAIF_I | DAIF_F, true, Some(super::Pending::Lines)), + ] { + let mut machine = serving_timer(0, 0, daif); + let hub = Hub::new(1, NoKick); + hub.set_live(0, true); + machine.enter_parallel(Arc::clone(&hub)).unwrap(); + if wait { + machine.system_instruction(0xd503_207f).unwrap(); // wfi + assert!(machine.waiting.is_some()); + } + let pending = machine.serve_host(|machine| { + let watch = machine.guest_watch(); + hub.lines_changed_unwoken(0); + watch.pending(machine.host.now) + }); + assert_eq!(pending, expected, "DAIF {daif:#x}, waiting {wait}"); + } +} + +/// Registers at [`OWN`] served under their own lock: a read gives how many +/// writes came before it; a write of 1 raises PE 1's IRQ and of 0 lowers +/// it, each change queued for the board. +const OWN: u64 = 0x9000; + +#[derive(Default)] +struct OwnRegisters { + writes: AtomicU64, + queued: std::sync::Mutex>, +} + +impl super::super::OwnLockRegisters for OwnRegisters { + fn serves(&self, physical: u64) -> bool { + (OWN..OWN + 0x100).contains(&physical) + } + fn read(&self, _: usize, _: u64, _: u8, _: u64) -> super::super::OwnLockAccess { + super::super::OwnLockAccess { + result: Ok(self.writes.load(Ordering::SeqCst)), + queued: false, + } + } + fn write( + &self, + _: usize, + _: u64, + _: u8, + value: u64, + _: u64, + ) -> super::super::OwnLockAccess<()> { + self.writes.fetch_add(1, Ordering::SeqCst); + self.queued.lock().unwrap().push(value == 1); + super::super::OwnLockAccess { + result: Ok(()), + queued: true, + } + } +} + +/// A board whose only interrupt is [`OwnRegisters`]'s, to PE 1. +struct OwnBoard { + own: Arc, + irq: bool, + deliveries: usize, +} + +impl Devices for OwnBoard { + fn read(&mut self, _: usize, _: u64, _: u8, _: u64) -> Result { + Ok(0) + } + fn write(&mut self, _: usize, _: u64, _: u8, _: u64, _: u64) -> Result<(), DeviceError> { + Ok(()) + } + fn lines(&mut self, pe: usize, _: u64) -> Lines { + Lines { + irq: pe == 1 && self.irq, + ..Lines::default() + } + } + fn own_lock_registers(&self) -> Option> { + Some(Arc::clone(&self.own) as Arc) + } + fn deliver_own(&mut self) -> Result { + let queued = core::mem::take(&mut *self.own.queued.lock().unwrap()); + let Some(&last) = queued.last() else { + return Ok(false); + }; + self.irq = last; + self.deliveries += 1; + Ok(true) + } +} + +fn own_board() -> (SharedDevices, Arc) { + let (hub, _) = hub(2); + let own = Arc::new(OwnRegisters::default()); + let home = SharedDevices::new( + OwnBoard { + own: Arc::clone(&own), + irq: false, + deliveries: 0, + }, + hub, + ); + (home, own) +} + +/// An access under its device's own lock that changes no line takes no +/// board lock: it completes while another PE holds the board. One that +/// queues a line change waits for the board, which hands the change on and +/// tells the PE it reached before the access completes. +#[test] +fn an_own_lock_access_takes_the_board_only_to_hand_on_a_line_change() { + let (home, own) = own_board(); + let mut worker = home.worker(); + let board = Arc::clone(&home.board); + let hub = Arc::clone(home.hub()); + let held = board.devices.lock().unwrap(); + let (sent, received) = std::sync::mpsc::channel(); + let waiter = std::thread::spawn(move || { + let read = worker.read_scalar(0, OWN, 4, 10); + sent.send(matches!(read, ScalarRead::Served(Ok(0)))) + .unwrap(); + let written = worker.write_own(0, OWN + 4, 4, 1, 20); + sent.send(written == Some(Ok(()))).unwrap(); + worker + }); + let bound = std::time::Duration::from_secs(5); + assert_eq!( + received.recv_timeout(bound), + Ok(true), + "read beside the held board" + ); + // Bounded: the write queues its change within five seconds, then waits. + let deadline = std::time::Instant::now() + bound; + while own.writes.load(Ordering::SeqCst) == 0 { + assert!(std::time::Instant::now() < deadline, "the write never ran"); + std::thread::yield_now(); + } + assert!( + received + .recv_timeout(std::time::Duration::from_millis(50)) + .is_err(), + "the write waits for the board to hand its change on" + ); + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + drop(held); + assert_eq!(received.recv_timeout(bound), Ok(true)); + let mut worker = waiter.join().unwrap(); + assert!( + hub.inboxes[1].lines.load(Ordering::SeqCst) > epoch, + "PE 1 told" + ); + assert_eq!( + home.with(|devices| (devices.irq, devices.deliveries)), + (true, 1) + ); + // A read changes nothing on the board; a lowering write hands on again. + assert!(matches!( + worker.read_scalar(0, OWN, 4, 30), + ScalarRead::Served(Ok(1)) + )); + assert_eq!(worker.write(0, OWN + 4, 4, 0, 40), Ok(())); + assert_eq!( + home.with(|devices| (devices.irq, devices.deliveries)), + (false, 2) + ); + // Another address takes the board's own path. + assert_eq!(worker.write_own(0, 0x40, 4, 1, 50), None); +} + +/// Every hold of the board's lock begins by handing on what own-lock +/// accesses queued, and tells the PEs it reached, whatever its call: a +/// change queued before any other call is seen by that call. +#[test] +fn every_board_hold_hands_on_queued_line_changes_first() { + let (home, own) = own_board(); + let hub = Arc::clone(home.hub()); + // Queued by the device directly, as an access that has not reached + // the board yet would leave it. + own.queued.lock().unwrap().push(true); + let epoch = hub.inboxes[1].lines.load(Ordering::SeqCst); + assert_eq!( + home.with(|devices| (devices.irq, devices.deliveries)), + (true, 1) + ); + assert!( + hub.inboxes[1].lines.load(Ordering::SeqCst) > epoch, + "PE 1 told" + ); + // Nothing waits now: a hold hands on nothing. + assert_eq!(home.with(|devices| devices.deliveries), 1); +} diff --git a/crates/stela-engine/src/machine/engine/pointer.rs b/crates/stela-engine/src/machine/engine/pointer.rs index 08c8c61d76..d95b124c31 100644 --- a/crates/stela-engine/src/machine/engine/pointer.rs +++ b/crates/stela-engine/src/machine/engine/pointer.rs @@ -1,1366 +1,1544 @@ -//! The PAC results the engine computes, remembers and lets native code -//! complete (`x86_64::pointer`). -//! -//! A signing or authentication is a pure function of its key, the chip's -//! PAC version, the regime's TCR (Arm `AddPAC`, `Auth`) and its operands, -//! so [`PointerService`] remembers results in a memo tagged with the -//! generation of that key's inputs. It lives at a fixed host address: PAC -//! thunks read its memo and its tag words, and on a memo miss call -//! [`complete`] with it, which computes the result exactly as the engine's -//! exit would ([`PointerService::result`]) without leaving native code. -//! A key's tag word is nonzero only while the service is open and the key -//! was found enabled and untrapped under the current derived state, which -//! is what both paths require, or [`pointer::DISABLED`] while it was found -//! disabled, whose results [`complete`] gives and remembers under that word. -//! Native code reads a memo whatever the tag words: an empty one shared by -//! every service until a service needs its own. -use crate::pauth; -use alloc::{boxed::Box, vec, vec::Vec}; -use core::mem::offset_of; -use stela_compiler::{Anchor, Place, block::PointerAuthenticationKey, x86_64::pointer}; - -pub(super) mod census; - -/// The memo native code reads while its service has none: no entry's tag -/// matches a tag word, so every lookup misses ([`pointer::DISABLED`]). -/// Only read, through its address. -static EMPTY_MEMO: [core::sync::atomic::AtomicU64; pointer::MEMO_ENTRIES * 4] = - [const { core::sync::atomic::AtomicU64::new(0) }; pointer::MEMO_ENTRIES * 4]; - -/// The distinct keys (each with the version and TCR) whose memo -/// generations are kept: two per process (its IB and DB keys) for over a -/// hundred processes. The lists are kept most recent first, so the keys in -/// use are found in the first few entries. -pub(super) const POINTER_INPUTS_SEEN: usize = 256; - -/// What a PAC result depends on besides its operands: the five keys, the -/// chip's PAC version and the regime's TCR (Arm `AddPAC`, `Auth`). -#[derive(Clone, Copy, PartialEq, Eq)] -pub(super) struct PointerInputs { - pub(super) keys: [Option<[u64; 2]>; 5], - pub(super) version: pauth::Version, - pub(super) tcr: u64, -} - -/// What the results of one key depend on: its tag word's index, its value, -/// the chip's PAC version and the regime's TCR. Another key's value does -/// not change them, so a key's entries outlive changes of the others (a -/// process's own keys beside the kernel's, which stay). -#[derive(Clone, Copy, PartialEq, Eq)] -struct KeyInputs { - index: u8, - key: Option<[u64; 2]>, - version: pauth::Version, - tcr: u64, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum PointerOperation { - Sign, - Authenticate { combined: bool }, -} - -/// The [`pointer::MemoEntry`] kinds of the results native code does not -/// complete, plus 1 for a combined form: an authentication that failed -/// without a fault, and one that faults with the code in `value`. -const UNAUTHENTICATED: u64 = 3; -const FAULTED: u64 = 5; -/// The tag bits of an entry's kind. -const KIND: u64 = 0xf; - -/// A result: the value and whether it authenticated (signings always do), -/// or the PAC failure code of a faulting authentication. -pub(super) type PointerResult = Result<(u64, bool), u8>; - -/// The memo kind and value of an operation's result. -fn memo_result(operation: PointerOperation, result: PointerResult) -> (u64, u64) { - let combined = u64::from(operation == PointerOperation::Authenticate { combined: true }); - match (operation, result) { - (PointerOperation::Sign, Ok((value, _))) => (pointer::SIGNED, value), - (_, Ok((value, true))) => (pointer::AUTHENTICATED, value), - (_, Ok((value, false))) => (UNAUTHENTICATED + combined, value), - (_, Err(code)) => (FAULTED + combined, u64::from(code)), - } -} - -/// The memo index of a key. -pub(super) fn memo_key(key: stela_contracts::pauth::Key) -> u8 { - pointer::key_index(match key { - stela_contracts::pauth::Key::Ia => PointerAuthenticationKey::Ia, - stela_contracts::pauth::Key::Ib => PointerAuthenticationKey::Ib, - stela_contracts::pauth::Key::Da => PointerAuthenticationKey::Da, - stela_contracts::pauth::Key::Db => PointerAuthenticationKey::Db, - }) -} - -fn key_of(key: PointerAuthenticationKey) -> stela_contracts::pauth::Key { - match key { - PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, - PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, - PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, - PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, - } -} - -/// The engine's PAC context, memo and tag words, which native code reads. -pub(super) struct PointerService { - /// The keys, version and layout, while open. - context: Option, - /// The layouts of the most recent regime, kept across key changes. - layouts: Option, - /// Results, each tagged with the generation of its key's inputs when it - /// was computed; `generations[index]` is that of each key in `inputs`. - /// Allocated before the first usable native tag and kept at that - /// address for the owner. - memo: Option>, - inputs: Option, - pub(super) key_generations: [u64; pointer::TAG_WORDS], - /// The generation of the whole `inputs`, which native transitions - /// compare (`transition::check_pointer`): equal exactly when the key - /// generations, and so the tag words the engine reopens, are equal. - pub(super) generation: u64, - /// The whole inputs most recently seen, each with its key generations - /// and its generation, most recent first. - seen_inputs: Vec<(PointerInputs, [u64; pointer::TAG_WORDS], u64)>, - /// The generations of the most recent distinct key inputs, most recent - /// first, so entries stay valid across a return to an earlier key (EL0 - /// and EL1 keys, guarded levels, PE switches) and across changes of the - /// other keys. - seen: Vec<(KeyInputs, u64)>, - /// The last generation handed out; an evicted one is never reused. - generations: u64, - /// Each key's tag word for native code: zero until a PAC exit finds the - /// key enabled and untrapped under the current memo, and again whenever - /// derived state may have changed. - pub(super) tags: [u64; pointer::TAG_WORDS], - /// Instruction/data XPAC masks, independent of cryptographic key state. - pub(super) strips: [pointer::strip::Cell; 2], - /// [`SERVICE`]'s address, which blocks completing PAC instructions - /// inside themselves call through (`x86_64::pointer::inline`). - routine: u64, - /// Results computed since boot (the cipher ran): each is a memo miss, - /// of a block, a thunk or an engine exit. - pub(super) fills: u64, - /// Under `--profile`, what the memo missed and why ([`census`]). - pub(super) census: Option>, - /// What native code computes PAC results from where the cipher is the - /// host's AES rounds ([`cells`]): the open context's key schedules, - /// version and layouts. A function of the inputs alone, never of an - /// enable or trap: native transitions switch the tag words between - /// levels of one generation without the service. - pub(super) cipher: pointer::cipher::Cipher, -} - -/// The routine a thunk calls on a memo miss. -pub(super) const SERVICE: pointer::ServiceRoutine = complete; - -/// Where blocks find the service's tag words, strip cells and routine. -pub(super) const CELLS: pointer::inline::Cells = pointer::inline::Cells { - tags: offset_of!(PointerService, tags) as u32, - strips: offset_of!(PointerService, strips) as u32, - routine: offset_of!(PointerService, routine) as u32, - cipher: None, -}; - -/// Where native code finds the service's tag words. -pub(super) const TAGS: Place = Place::new(Anchor::Pointer, offset_of!(PointerService, tags)); - -/// Where native code finds the service's cipher. -const CIPHER: Place = Place::new(Anchor::Pointer, offset_of!(PointerService, cipher)); - -/// Whether native code for `target` computes PAC results itself -/// (`x86_64::pointer::cipher`): the target has AES-NI and the engine's -/// cipher is the AES rounds, which it is exactly where the host has AES-NI. -/// Otherwise it looks them up in the memo and calls the service on a miss. -pub(super) fn native_cipher(target: stela_compiler::TargetCpu) -> Option { - (target.supports(stela_compiler::TargetCpu::Aes) && pauth::keyed::native()).then_some(CIPHER) -} - -/// [`CELLS`] for blocks compiled for `target`, with the cipher where -/// [`native_cipher`] takes it. -pub(super) fn cells(target: stela_compiler::TargetCpu) -> pointer::inline::Cells { - pointer::inline::Cells { - cipher: native_cipher(target).map(|place| place.offset as u32), - ..CELLS - } -} - -/// Where native code finds the stripping cell of `data`. -pub(super) const fn strip_place(data: bool) -> Place { - Place::new( - Anchor::Pointer, - offset_of!(PointerService, strips) + data as usize * size_of::(), - ) -} - -impl PointerService { - pub(super) fn new() -> Self { - Self { - context: None, - layouts: None, - memo: None, - inputs: None, - key_generations: [0; pointer::TAG_WORDS], - generation: 0, - seen_inputs: Vec::new(), - seen: Vec::new(), - generations: 0, - tags: [0; pointer::TAG_WORDS], - strips: [pointer::strip::Cell::default(); 2], - routine: SERVICE as usize as u64, - fills: 0, - census: None, - cipher: pointer::cipher::Cipher::default(), - } - } - - /// Forget the context and close every key, as derived state changed. - pub(super) fn close(&mut self) { - self.context = None; - self.close_native(); - } - - fn close_native(&mut self) -> [bool; 2] { - self.tags = [0; pointer::TAG_WORDS]; - self.strips - .each_mut() - .map(|cell| core::mem::take(&mut cell.enabled) != 0) - } - - /// Derived state changed, now with `inputs`: every tag word and - /// stripping cell closes, and the context stays when it was made for - /// these inputs (else it is made anew, with their memo generation). - /// Returns which stripping cells were open, for the engine to reopen - /// with [`Self::reopen`]. - pub(super) fn revalidate(&mut self, inputs: PointerInputs) -> [bool; 2] { - let stripping = self.close_native(); - if self.context.is_none() || self.inputs != Some(inputs) { - self.open(inputs); - } - stripping - } - - /// Whether every key is closed to native code. - pub(super) fn tags_closed(&self) -> bool { - self.tags.iter().all(|&tag| tag == 0) - } - - /// Whether native code had anything open: a tag word or a stripping cell. - pub(super) fn any_open(&self) -> bool { - self.tags.iter().any(|&tag| tag != 0) || self.strips.iter().any(|cell| cell.enabled != 0) - } - - /// After [`Self::revalidate`], open `key`'s tag word as a PAC exit - /// would: [`pointer::DISABLED`] while its SCTLR enable is clear, else, - /// untrapped and present in the context, the memo's current tag. - pub(super) fn reopen( - &mut self, - key: stela_contracts::pauth::Key, - enabled: bool, - trapped: bool, - ) { - let index = memo_key(key); - let tag = if !enabled { - pointer::DISABLED - } else if !trapped - && self - .context - .as_ref() - .is_some_and(|context| context.has_key(key)) - { - self.native_tag(index) - } else { - 0 - }; - self.tags[usize::from(index)] = tag; - } - - /// After [`Self::revalidate`], open the generic key's tag word as a - /// PACGA exit would: untrapped and present in the context, the memo's - /// current tag. - pub(super) fn reopen_generic(&mut self, trapped: bool) { - let usable = !trapped - && self - .context - .as_ref() - .is_some_and(pauth::Context::has_generic_key); - self.tags[usize::from(pointer::GENERIC_KEY)] = if usable { - self.native_tag(pointer::GENERIC_KEY) - } else { - 0 - }; - } - - /// After [`Self::revalidate`], reopen the stripping cell of `data`. - pub(super) fn reopen_stripping(&mut self, data: bool) { - if let Some(keep) = self - .context - .as_ref() - .map(|context| context.stripping_masks(data)) - { - self.strips[usize::from(data)] = pointer::strip::Cell { - enabled: 1, - keep, - upper_extension: !keep[1], - }; - } - } - - pub(super) fn open_stripping(&mut self, context: &pauth::Context, data: bool) { - let keep = context.stripping_masks(data); - self.strips[usize::from(data)] = pointer::strip::Cell { - enabled: 1, - keep, - upper_extension: !keep[1], - }; - } - - pub(super) fn is_open(&self) -> bool { - self.context.is_some() - } - - /// Open the service with the current `inputs`. - pub(super) fn open(&mut self, inputs: PointerInputs) { - if self.inputs != Some(inputs) { - for (index, key) in inputs.keys.into_iter().enumerate() { - self.key_generations[index] = self.generation_of(KeyInputs { - index: index as u8, - key, - version: inputs.version, - tcr: inputs.tcr, - }); - } - let keys = self.key_generations; - self.generation = match self - .seen_inputs - .iter() - .position(|&(known, generations, _)| known == inputs && generations == keys) - { - Some(index) => self.seen_inputs.remove(index).2, - None => { - self.generations += 1; - self.generations - } - }; - self.seen_inputs.insert(0, (inputs, keys, self.generation)); - self.seen_inputs.truncate(POINTER_INPUTS_SEEN); - self.inputs = Some(inputs); - } - let [ia, ib, da, db, generic] = inputs.keys; - let mut keys = pauth::Keys::from_optional_words([ia, ib, da, db]); - if let Some(generic) = generic { - keys = keys.with_generic_words(generic); - } - let layouts = match self.layouts { - Some(layouts) if layouts.tcr() == inputs.tcr => layouts, - _ => *self.layouts.insert(pauth::Layouts::new(inputs.tcr)), - }; - let context = pauth::Context::new_with_version(0, keys, inputs.version) - .with_layouts(layouts) - .with_implementation_defined_cipher(); - for (index, schedule) in self.cipher.schedules.iter_mut().enumerate() { - *schedule = context.native_schedule(index).unwrap_or_default(); - } - let classic = inputs.version == pauth::Version::Classic; - // Instructions, then data, each by bit 55. - self.cipher.ranges = [false, true].map(|data| { - let extension = layouts.native(data); - [false, true].map(|upper| { - pointer::cipher::Range::new(extension[usize::from(upper)], upper, classic) - }) - }); - self.context = Some(context); - } - - /// A usable tag permits a thunk to dereference the memo anchor. A - /// closed or disabled tag is handled before that dereference. - fn native_tag(&mut self, key: u8) -> u64 { - if self.memo.is_none() { - self.allocate_memo(); - } - pointer::tag(self.key_generations[usize::from(key)], key, 0) - } - - #[cold] - fn allocate_memo(&mut self) { - self.memo = - Some(vec![pointer::MemoEntry::default(); pointer::MEMO_ENTRIES].into_boxed_slice()); - } - - /// What native code finds through [`Anchor::Pointer`] and - /// [`Anchor::Memo`] on its next entry: the memo, or the empty one. - pub(super) fn anchors(&self) -> (u64, u64) { - ( - self as *const Self as u64, - self.memo - .as_ref() - .map_or(EMPTY_MEMO.as_ptr() as u64, |memo| memo.as_ptr() as u64), - ) - } - - /// A disabled key's result, `pointer` unchanged (Arm `AddPAC`, `Auth`), - /// remembered under [`pointer::DISABLED`] for native code, whatever the - /// key: a signing's for signings, a success for both authentications. - fn disabled(&mut self, authenticate: bool, pointer: u64, modifier: u64) -> u64 { - if self.memo.is_none() { - self.allocate_memo(); - } - let kind = if authenticate { - pointer::AUTHENTICATED - } else { - pointer::SIGNED - }; - let memo = self.memo.as_mut().expect("memo allocated"); - pointer::insert( - memo, - pointer::MemoEntry { - pointer, - modifier, - tag: pointer::DISABLED | kind, - value: pointer, - }, - ); - pointer - } - - /// One signing or authentication with the open context, remembered - /// while its inputs stay the same, with `key` known enabled and - /// untrapped, which opens its tag word. The memo slot comes from the - /// pointer and modifier alone, so which slot is touched never depends on - /// a key. A signing whose result strips back to its pointer also - /// remembers that authenticating the result with the same key and - /// modifier succeeds with that pointer (Arm `Auth` recomputes the PAC of - /// the stripped pointer), which answers the epilogue of a signed frame; - /// a success answers both the combined and the plain authentication. - /// `None` when the service is closed or the context lacks the key. - pub(super) fn result( - &mut self, - operation: PointerOperation, - key: stela_contracts::pauth::Key, - pointer: u64, - modifier: u64, - ) -> Option { - if !self.context.as_ref()?.has_key(key) { - return None; - } - let index = memo_key(key); - self.tags[usize::from(index)] = self.native_tag(index); - if let Some(result) = self.remembered(operation, key, pointer, modifier) { - return Some(result); - } - self.computed(operation, key, pointer, modifier) - } - - /// [`Self::result`] past its memo lookup, which a thunk's miss has - /// already made: the cipher's result, remembered. `None` when the - /// service is closed. - fn computed( - &mut self, - operation: PointerOperation, - key: stela_contracts::pauth::Key, - pointer: u64, - modifier: u64, - ) -> Option { - let index = memo_key(key); - let context = self.context.as_ref()?; - let words = context.words(key)?; - self.fills += 1; - let result = match operation { - PointerOperation::Sign => Ok((context.sign_with(key, words, pointer, modifier), true)), - PointerOperation::Authenticate { combined } => { - match context.authenticate_with(key, words, pointer, modifier, combined) { - Ok(result) => Ok((result.pointer, result.authenticated)), - Err(failure) => Err(failure.code), - } - } - }; - let strips_back = match (operation, result) { - (PointerOperation::Sign, Ok((signed, _))) => { - (context.strip(key, signed) == pointer).then_some(signed) - } - _ => None, - }; - if let Some(census) = &mut self.census - && let Some(inputs) = self.inputs - && let Some(words) = inputs.keys[usize::from(index)] - { - let kind = match operation { - PointerOperation::Sign => census::SIGN, - PointerOperation::Authenticate { .. } => census::AUTHENTICATE, - }; - census.fill( - index, - words, - inputs.tcr, - kind, - pointer, - modifier, - strips_back, - ); - } - let tag = pointer::tag(self.key_generations[usize::from(index)], index, 0); - let memo = self.memo.as_mut()?; - let (kind, value) = memo_result(operation, result); - pointer::insert( - memo, - pointer::MemoEntry { - pointer, - modifier, - tag: tag | kind, - value, - }, - ); - if let Some(signed) = strips_back { - pointer::insert( - memo, - pointer::MemoEntry { - pointer: signed, - modifier, - tag: tag | pointer::AUTHENTICATED, - value: pointer, - }, - ); - } - Some(result) - } - - /// PACGA with the open context, remembered as [`Self::result`] does, - /// the key known untrapped. `None` when the context lacks the key. - pub(super) fn generic_code(&mut self, data: u64, modifier: u64) -> Option { - let key = pointer::GENERIC_KEY; - let code = self.context.as_ref()?.generic_code(data, modifier).ok()?; - self.fills += 1; - if let Some(census) = &mut self.census - && let Some(inputs) = self.inputs - && let Some(words) = inputs.keys[usize::from(key)] - { - census.fill( - key, - words, - inputs.tcr, - census::GENERIC, - data, - modifier, - None, - ); - } - let tag = self.native_tag(key); - let memo = self.memo.as_mut().expect("memo for open tag"); - pointer::insert( - memo, - pointer::MemoEntry { - pointer: data, - modifier, - tag: tag | pointer::SIGNED, - value: code, - }, - ); - self.tags[usize::from(key)] = tag; - Some(code) - } - - /// The memo generation of a key's `inputs`: the one they had if they - /// are among the [`POINTER_INPUTS_SEEN`] most recent distinct key - /// inputs, else a new one. A result depends only on its key's inputs - /// and its operands, so an entry of a reused generation is still exact. - fn generation_of(&mut self, inputs: KeyInputs) -> u64 { - let generation = match self.seen.iter().position(|&(known, _)| known == inputs) { - Some(index) => self.seen.remove(index).1, - None => { - self.generations += 1; - if let Some(census) = &mut self.census { - census.generations += 1; - } - self.generations - } - }; - self.seen.insert(0, (inputs, generation)); - self.seen.truncate(POINTER_INPUTS_SEEN); - generation - } - - /// The current memo's result of `operation` with `key` on these - /// operands, if it has one: a success answers both authentication forms. - pub(super) fn remembered( - &self, - operation: PointerOperation, - key: stela_contracts::pauth::Key, - pointer: u64, - modifier: u64, - ) -> Option { - let index = memo_key(key); - let tag = pointer::tag(self.key_generations[usize::from(index)], index, 0); - let first = pointer::slot(pointer, modifier); - let entry = *self.memo.as_ref()?[first..first + pointer::MEMO_WAYS] - .iter() - .find(|entry| { - entry.pointer == pointer && entry.modifier == modifier && entry.tag & !KIND == tag - })?; - let kind = entry.tag & KIND; - let combined = u64::from(operation == PointerOperation::Authenticate { combined: true }); - match operation { - PointerOperation::Sign => (kind == pointer::SIGNED).then_some(Ok((entry.value, true))), - PointerOperation::Authenticate { .. } => match kind { - pointer::AUTHENTICATED => Some(Ok((entry.value, true))), - kind if kind == UNAUTHENTICATED + combined => Some(Ok((entry.value, false))), - kind if kind == FAULTED + combined => Some(Err(entry.value as u8)), - _ => None, - }, - } - } -} - -translated_callee! { -/// A PAC thunk's memo miss (`x86_64::pointer::ServiceRoutine`): the result -/// of `request` on these operands while the requested key's tag word is -/// open, completed when it is a signing or a successful authentication, -/// and the pointer itself while the key is disabled. -/// A failed authentication is remembered for the exit the thunk then takes. -pub(super) fn complete( - service: u64, - request: u32, - pointer: u64, - modifier: u64, -) -> pointer::Completion { - // SAFETY: thunks pass the address of the machine's boxed service, which - // outlives every installed thunk; the engine does not touch it while - // native code runs. - let service = unsafe { &mut *(service as *mut PointerService) }; - let fills = service.fills; - let completion = complete_with(service, request, pointer, modifier); - if let Some(census) = &mut service.census { - census.native += service.fills - fills; - census.calls += 1; - } - completion -} -} - -/// [`complete`] of the service. -fn complete_with( - service: &mut PointerService, - request: u32, - pointer: u64, - modifier: u64, -) -> pointer::Completion { - if pointer::requests_generic_code(request) { - if service.tags[usize::from(pointer::GENERIC_KEY)] == 0 { - return pointer::Completion::default(); - } - return service.generic_code(pointer, modifier).map_or_else( - pointer::Completion::default, - |value| pointer::Completion { - completed: 1, - value, - }, - ); - } - let (key, authenticate, combined) = pointer::requested(request); - let key = key_of(key); - match service.tags[usize::from(memo_key(key))] { - 0 => return pointer::Completion::default(), - pointer::DISABLED => { - return pointer::Completion { - completed: 1, - value: service.disabled(authenticate, pointer, modifier), - }; - } - _ => {} - } - let operation = if authenticate { - PointerOperation::Authenticate { combined } - } else { - PointerOperation::Sign - }; - // The thunk missed the memo, and its open tag word says the context - // holds the key, so the result is computed at once. A failed - // authentication the memo held is computed and remembered again. - match service.computed(operation, key, pointer, modifier) { - Some(Ok((value, true))) => pointer::Completion { - completed: 1, - value, - }, - _ => pointer::Completion::default(), - } -} - -#[cfg(all( - test, - target_arch = "x86_64", - any(target_os = "linux", target_os = "macos") -))] -mod native_tests; - -#[cfg(all(test, target_arch = "x86_64", target_os = "linux"))] -mod cost; - -#[cfg(test)] -mod replay; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_memo_is_needed_only_for_a_usable_native_tag() { - use stela_contracts::pauth::Key; - - let mut owner = Box::new(PointerService::new()); - let (service, memo) = owner.anchors(); - let empty = EMPTY_MEMO.as_ptr() as u64; - assert_eq!(memo, empty); - let first = inputs(pauth::Version::Classic, 25 | 25 << 16); - let mut unavailable = first; - unavailable.keys = [None; 5]; - owner.open(unavailable); - owner.reopen(Key::Ia, false, true); - owner.reopen(Key::Ib, true, false); - owner.reopen_generic(false); - owner.reopen_stripping(true); - assert_eq!(owner.tags, [pointer::DISABLED, 0, 0, 0, 0]); - assert_eq!(owner.strips[1].enabled, 1); - assert_eq!(owner.result(PointerOperation::Sign, Key::Ib, 4, 8), None); - assert_eq!(owner.generic_code(4, 8), None); - assert_eq!(owner.anchors(), (service, empty)); - - owner.revalidate(first); - owner.reopen(Key::Ia, true, true); - owner.reopen_generic(true); - assert_eq!(owner.anchors(), (service, empty)); - owner.reopen(Key::Ia, true, false); - let memo = owner.anchors().1; - assert_ne!(memo, empty); - let tag = owner.tags[0]; - let result = owner.result(PointerOperation::Sign, Key::Ia, 4, 8).unwrap(); - owner.close(); - assert_eq!(owner.anchors(), (service, memo)); - owner.open(unavailable); - owner.revalidate(first); - owner.reopen(Key::Ia, true, false); - assert_eq!(owner.anchors(), (service, memo)); - assert_eq!(owner.tags[0], tag); - assert_eq!( - owner.remembered(PointerOperation::Sign, Key::Ia, 4, 8), - Some(result) - ); - - let mut other = Box::new(PointerService::new()); - other.open(first); - assert_eq!(other.anchors().1, empty); - other.reopen_generic(false); - assert_ne!(other.anchors().1, empty); - assert_ne!(other.anchors().1, memo); - } - - /// A disabled key's request completes with its pointer, from no key - /// and no cipher, and is remembered under the disabled word, which no - /// open or closed word's lookup takes; a closed key's is refused. - #[test] - fn disabled_keys_complete_with_their_pointer_for_native_code() { - use stela_contracts::pauth::Key; - - let mut service = Box::new(PointerService::new()); - let state = service.anchors().0; - let (data, modifier) = (0xffff_fe00_1234_5678, 0xffff_fe00_0000_8000); - let ib = u32::from(memo_key(Key::Ib)); - let authenticate = ib | pointer::REQUEST_AUTHENTICATE | pointer::REQUEST_COMBINED; - assert_eq!( - complete(state, ib, data, modifier), - pointer::Completion::default() - ); - service.reopen(Key::Ib, false, true); - assert_eq!( - service.tags[usize::from(memo_key(Key::Ib))], - pointer::DISABLED - ); - for (request, kind) in [ - (ib, pointer::SIGNED), - (authenticate, pointer::AUTHENTICATED), - ] { - assert_eq!( - complete(state, request, data, modifier), - pointer::Completion { - completed: 1, - value: data, - } - ); - assert_eq!( - service.memo.as_ref().unwrap()[pointer::slot(data, modifier)], - pointer::MemoEntry { - pointer: data, - modifier, - tag: pointer::DISABLED | kind, - value: data, - } - ); - } - assert_eq!(service.fills, 0); - assert_eq!( - service.anchors().1, - service.memo.as_ref().unwrap().as_ptr() as u64 - ); - } - - #[test] - fn fills_count_each_computed_result_once() { - use stela_contracts::pauth::Key; - - let mut service = Box::new(PointerService::new()); - service.open(inputs(pauth::Version::Classic, 25 | 25 << 16)); - assert_eq!(service.fills, 0); - let signed = service - .result(PointerOperation::Sign, Key::Ib, 0x1000, 0x20) - .unwrap(); - assert_eq!(service.fills, 1); - // A remembered signing, and the authentication its signing filled. - service.result(PointerOperation::Sign, Key::Ib, 0x1000, 0x20); - let (pointer, _) = signed.unwrap(); - let authenticate = PointerOperation::Authenticate { combined: false }; - service.result(authenticate, Key::Ib, pointer, 0x20); - assert_eq!(service.fills, 1); - service.result(PointerOperation::Sign, Key::Ib, 0x2000, 0x20); - service.generic_code(3, 4).unwrap(); - assert_eq!(service.fills, 3); - } - - #[test] - fn a_generic_code_opens_its_own_tag_and_completes_for_thunks() { - let mut service = Box::new(PointerService::new()); - let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); - input.keys[4] = Some([7, 9]); - service.open(input); - let state = service.anchors().0; - let form = pointer::Form::of( - stela_compiler::block::PointerAuthenticationOperation::GenericCode( - stela_compiler::block::pauth_memory::GenericCode { - destination: 1, - source: 2, - modifier: 3, - }, - ), - ) - .unwrap(); - let (data, modifier) = (0x1234, 0x5678); - // Closed, the service is not asked. - assert_eq!( - complete(state, form.request(), data, modifier), - pointer::Completion::default() - ); - let code = service.generic_code(data, modifier).unwrap(); - let tag = pointer::tag( - service.key_generations[usize::from(pointer::GENERIC_KEY)], - pointer::GENERIC_KEY, - 0, - ); - assert_eq!(service.tags[usize::from(pointer::GENERIC_KEY)], tag); - assert_eq!(service.tags[..4], [0; 4]); - assert_eq!( - service.memo.as_ref().unwrap()[pointer::slot(data, modifier)], - pointer::MemoEntry { - pointer: data, - modifier, - tag: tag | pointer::SIGNED, - value: code, - } - ); - // Open, a memo miss completes through it. - assert_eq!( - complete(state, form.request(), data, modifier), - pointer::Completion { - completed: 1, - value: code, - } - ); - service.reopen_generic(true); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - service.reopen_generic(false); - assert_eq!(service.tags[usize::from(pointer::GENERIC_KEY)], tag); - // Without the key nothing opens. - input.keys[4] = None; - service.close(); - service.open(input); - assert_eq!(service.generic_code(data, modifier), None); - service.reopen_generic(false); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - } - - #[test] - fn absent_keys_never_open_native_tags_or_reuse_a_known_key_generation() { - let mut service = PointerService::new(); - let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); - input.keys = [None; 5]; - service.open(input); - assert!( - service - .result( - PointerOperation::Sign, - stela_contracts::pauth::Key::Ia, - 0x4000, - 0x8000 - ) - .is_none() - ); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - let unknown_generation = service.generation; - input.keys[0] = Some([11, 21]); - service.close(); - service.open(input); - assert!( - service - .result( - PointerOperation::Sign, - stela_contracts::pauth::Key::Ia, - 0x4000, - 0x8000 - ) - .is_some() - ); - assert_ne!(service.generation, unknown_generation); - assert_eq!(service.tags[1..], [0; pointer::TAG_WORDS - 1]); - service.close(); - input.keys[0] = None; - service.open(input); - assert_eq!(service.generation, unknown_generation); - assert!( - service - .result( - PointerOperation::Sign, - stela_contracts::pauth::Key::Ia, - 0x4000, - 0x8000 - ) - .is_none() - ); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - } - - #[test] - fn stripping_cells_match_the_authoritative_layout_and_close_without_keys() { - let mut service = PointerService::new(); - for t0 in [0, 16, 17, 25, 39, 63] { - for t1 in [0, 16, 17, 25, 39, 63] { - for controls in 0..16u64 { - let tcr = t0 - | t1 << 16 - | (controls & 1) << 37 - | (controls & 2) << 37 - | (controls & 4) << 49 - | (controls & 8) << 49; - let context = - pauth::Context::new(0, pauth::Keys::from_optional_words([None; 4])) - .with_translation_regime(tcr); - for data in [false, true] { - service.open_stripping(&context, data); - assert!( - !service.is_open(), - "no cryptographic context or key is needed" - ); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - let cell = service.strips[usize::from(data)]; - assert_eq!(cell.enabled, 1); - for pointer in [0, u64::MAX, 1 << 55, 1 << 63, 0xdead_1234_5678_abcd] { - let upper = pointer & (1 << 55) != 0; - let keep = cell.keep[usize::from(upper)]; - let key = if data { - stela_contracts::pauth::Key::Da - } else { - stela_contracts::pauth::Key::Ia - }; - assert_eq!( - (pointer & keep) | if upper { cell.upper_extension } else { 0 }, - context.strip(key, pointer) - ); - } - } - service.close(); - assert!(service.strips.iter().all(|cell| cell.enabled == 0)); - } - } - } - } - - pub(super) fn inputs(version: pauth::Version, tcr: u64) -> PointerInputs { - let key = |index: u64| [0x1122_3344_5566_7788 ^ index, 0x99aa_bbcc_ddee_ff00 + index]; - PointerInputs { - keys: [key(1), key(2), key(3), key(4), key(5)].map(Some), - version, - tcr, - } - } - - fn request(key: PointerAuthenticationKey, operation: PointerOperation) -> u32 { - let mut request = u32::from(pointer::key_index(key)); - if let PointerOperation::Authenticate { combined } = operation { - request |= pointer::REQUEST_AUTHENTICATE; - if combined { - request |= pointer::REQUEST_COMBINED; - } - } - request - } - - /// The native completion answers exactly what the engine's exit - /// computes, for every key, form and version and for kernel and user - /// pointers, signed, corrupted and unsigned: it completes signings and - /// successful authentications, refuses the rest, and refuses everything - /// for a key whose tag word is closed. - #[test] - fn native_completions_equal_the_engine_results() { - use PointerAuthenticationKey as Key; - // T0SZ = T1SZ = 25 (39-bit VAs), TBI0 on. - let tcr = 25 | 25 << 16 | 1 << 37; - let operations = [ - PointerOperation::Sign, - PointerOperation::Authenticate { combined: false }, - PointerOperation::Authenticate { combined: true }, - ]; - for version in [ - pauth::Version::Classic, - pauth::Version::Enhanced, - pauth::Version::Faulting, - pauth::Version::FaultingCombined, - ] { - let inputs = inputs(version, tcr); - let mut native = Box::new(PointerService::new()); - let mut engine = PointerService::new(); - native.open(inputs); - engine.open(inputs); - let state = native.anchors().0; - for key in [Key::Ia, Key::Ib, Key::Da, Key::Db] { - let pauth_key = key_of(key); - let index = usize::from(pointer::key_index(key)); - for (step, base) in [0xffff_ff80_0012_3450_u64, 0x0000_0001_0000_8000] - .into_iter() - .enumerate() - { - let modifier = 0xffff_ff80_0040_0000 + step as u64 * 0x10; - let signed = engine.result(PointerOperation::Sign, pauth_key, base, modifier); - let Some(Ok((signed, true))) = signed else { - panic!("signing {base:#x}: {signed:?}"); - }; - for operand in [base, signed, signed ^ (1 << 50), signed ^ (1 << 62)] { - for operation in operations { - native.tags = [0; pointer::TAG_WORDS]; - let asked = complete(state, request(key, operation), operand, modifier); - assert_eq!(asked, pointer::Completion::default(), "a closed key"); - native.reopen(pauth_key, true, false); - assert_ne!(native.tags[index], 0); - let expected = engine.result(operation, pauth_key, operand, modifier); - let asked = complete(state, request(key, operation), operand, modifier); - let completed = match expected { - Some(Ok((value, true))) => pointer::Completion { - completed: 1, - value, - }, - _ => pointer::Completion::default(), - }; - assert_eq!(asked, completed, "{version:?} {key:?} {operation:?}"); - // The native call remembered what the exit then finds. - assert_eq!( - native.remembered(operation, pauth_key, operand, modifier), - expected - ); - } - } - } - } - } - } - - /// Memo misses of a modelled workload, run by hand: processes that each - /// have their own IB and DB keys (IA, DA and the generic key shared), - /// each running a call tree whose frames sign their return address - /// with IB and SP and authenticate it on return, with system calls into - /// a kernel whose frames use the kernel's IA and IB keys on the - /// thread's kernel stack while the process's DB key stays loaded; the - /// PE switches to the next process after each time slice. Prints the - /// cipher runs per PAC operation for each number of processes. - #[test] - #[ignore = "manual: opt-in"] - fn memo_replay_of_a_process_mix() { - extern crate std; - use stela_contracts::pauth::Key; - let tcr = 25 | 25 << 16; - let shared = |word: u64| Some([word, word.rotate_left(17)]); - let user = |process: u64| PointerInputs { - keys: [ - shared(1), - shared(0x100 + process), - shared(3), - shared(0x200 + process), - shared(5), - ], - version: pauth::Version::Classic, - tcr, - }; - let kernel = |process: u64| PointerInputs { - keys: [ - shared(9), - shared(10), - shared(3), - shared(0x200 + process), - shared(5), - ], - version: pauth::Version::Classic, - tcr, - }; - for processes in [2u64, 4, 8, 16, 32] { - let mut service = PointerService::new(); - let mut operations = 0u64; - // A frame: sign on entry, authenticate on return. - let mut frame = |service: &mut PointerService, key: Key, lr: u64, sp: u64| { - let signed = match service.result(PointerOperation::Sign, key, lr, sp) { - Some(Ok((signed, _))) => signed, - other => panic!("{other:?}"), - }; - service.result( - PointerOperation::Authenticate { combined: true }, - key, - signed, - sp, - ); - operations += 2; - }; - for slice in 0..4000u64 { - let process = slice % processes; - service.close(); - service.open(user(process)); - let code = 0x1_0000_0000 + process * 0x100_0000; - let stack = 0x16f_0000_0000 - process * 0x10_0000; - for call in 0..64u64 { - // A call tree: depth from the call number's low bits. - let depth = (call % 7) + 1; - for level in 0..depth { - let site = code + 0x40 * ((call * 7 + level * 13) % 97); - frame(&mut service, Key::Ib, site, stack - 0x60 * level); - } - if call % 16 == 15 { - service.close(); - service.open(kernel(process)); - let kernel_stack = 0xffff_fe10_0000_0000 + process * 0x4000; - for level in 0..5u64 { - let site = 0xffff_fe00_0800_0000 + 0x40 * (level * 11 + call % 3); - frame(&mut service, Key::Ib, site, kernel_stack - 0x80 * level); - frame( - &mut service, - Key::Ia, - site + 0x20, - kernel_stack - 0x80 * level, - ); - } - service.close(); - service.open(user(process)); - } - } - } - std::println!( - "REPLAY processes={processes} operations={operations} fills={} per_operation={:.4}", - service.fills, - service.fills as f64 / operations as f64 - ); - } - } - - /// What a memo miss costs, run by hand in a release build: a native - /// signing miss through the service routine, the cipher alone, and a - /// miss of the authentication form. Prints nanoseconds per call. - #[test] - #[ignore = "manual: opt-in"] - fn miss_path_timing() { - extern crate std; - use PointerAuthenticationKey as Key; - use std::time::Instant; - const CALLS: u64 = 1 << 20; - let tcr = 25 | 25 << 16 | 1 << 37; - let mut service = Box::new(PointerService::new()); - service.open(inputs(pauth::Version::Classic, tcr)); - let state = service.anchors().0; - service.reopen(stela_contracts::pauth::Key::Ib, true, false); - // Canonical upper pointers, which strip back from their signings. - let operand = |call: u64| { - ( - 0xffff_ff80_0800_0000 + call * 4, - 0xffff_fe10_0000_0000 - call * 16, - ) - }; - let sign = request(Key::Ib, PointerOperation::Sign); - let started = Instant::now(); - let mut sum = 0u64; - for call in 0..CALLS { - let (pointer, modifier) = operand(call); - sum = sum.wrapping_add(complete(state, sign, pointer, modifier).value); - } - let native = started.elapsed().as_nanos() as f64 / CALLS as f64; - let cipher = { - let context = service.context.as_ref().unwrap(); - let started = Instant::now(); - for call in 0..CALLS { - let (pointer, modifier) = operand(call + CALLS); - let signed = context.sign(stela_contracts::pauth::Key::Ib, pointer, modifier); - sum = sum.wrapping_add(signed.unwrap_or(0)); - } - started.elapsed().as_nanos() as f64 / CALLS as f64 - }; - let authenticate = request(Key::Ib, PointerOperation::Authenticate { combined: true }); - let started = Instant::now(); - for call in 0..CALLS { - let (pointer, modifier) = operand(call + 2 * CALLS); - sum = sum.wrapping_add(complete(state, authenticate, pointer, modifier).value); - } - let failed = started.elapsed().as_nanos() as f64 / CALLS as f64; - std::println!( - "MISS sign_through_service={native:.1}ns sign_alone={cipher:.1}ns auth_miss={failed:.1}ns fills={} ({sum:x})", - service.fills - ); - // Host instructions of one call, single-stepped under the trap flag. - #[cfg(target_os = "linux")] - { - let (pointer, modifier) = operand(3 * CALLS); - let miss = steps(|| { - core::hint::black_box(complete(state, sign, pointer, modifier)); - }); - let context = service.context.as_ref().unwrap(); - let (pointer, modifier) = operand(3 * CALLS + 1); - let alone = steps(|| { - let key = stela_contracts::pauth::Key::Ib; - core::hint::black_box(context.sign(key, pointer, modifier).ok()); - }); - let key = stela_contracts::pauth::Key::Ib; - let strip = steps(|| { - core::hint::black_box(context.strip(key, pointer)); - }); - let (pointer, modifier) = operand(3 * CALLS + 2); - let lookup = steps(|| { - core::hint::black_box(service.remembered( - PointerOperation::Sign, - key, - pointer, - modifier, - )); - }); - let memo = service.memo.as_mut().unwrap(); - let insert = steps(|| { - pointer::insert( - memo, - pointer::MemoEntry { - pointer, - modifier, - tag: 7, - value: 7, - }, - ); - }); - let tag = steps(|| { - core::hint::black_box(service.native_tag(1)); - }); - std::println!( - "MISS instructions sign_through_service={miss} sign_alone={alone} strip={strip} lookup={lookup} insert={insert} tag={tag}" - ); - } - } - - /// The instructions `run` executes, counted under the trap flag. - #[cfg(target_os = "linux")] - pub(super) fn steps(run: impl FnOnce()) -> usize { - use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; - #[repr(C)] - struct SigAction { - handler: usize, - mask: [u64; 16], - flags: i32, - restorer: usize, - } - unsafe extern "C" { - fn sigaction(signal: i32, action: *const SigAction, old: *mut SigAction) -> i32; - } - static STEPS: AtomicUsize = AtomicUsize::new(0); - extern "C" fn step(_: i32, _: *mut core::ffi::c_void, _: *mut core::ffi::c_void) { - STEPS.fetch_add(1, Relaxed); - } - STEPS.store(0, Relaxed); - let action = SigAction { - handler: step as extern "C" fn(i32, *mut core::ffi::c_void, *mut core::ffi::c_void) - as usize, - mask: [0; 16], - flags: 4, - restorer: 0, - }; - // SAFETY: a SIGTRAP handler that only counts; the trap flag is set - // around `run` alone. - unsafe { - sigaction(5, &action, core::ptr::null_mut()); - core::arch::asm!("pushfq", "or qword ptr [rsp], 0x100", "popfq"); - } - run(); - // SAFETY: as above. - unsafe { core::arch::asm!("pushfq", "and qword ptr [rsp], -257", "popfq") }; - STEPS.load(Relaxed) - } - - /// A key's entries outlive changes of the other keys: a process's keys - /// change on every switch while the kernel's stay, and the kernel's - /// results must still be found. - #[test] - fn a_keys_entries_outlive_changes_of_the_other_keys() { - use stela_contracts::pauth::Key; - let mut service = PointerService::new(); - let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); - service.open(input); - let fills = service.fills; - let signed = service.result(PointerOperation::Sign, Key::Ia, 0x4000, 0x8000); - assert_eq!(service.fills, fills + 1); - for process in 0..2 * POINTER_INPUTS_SEEN as u64 { - input.keys[1] = Some([process, !process]); - input.keys[2] = Some([process << 1, process]); - service.close(); - service.open(input); - assert_eq!( - service.result(PointerOperation::Sign, Key::Ia, 0x4000, 0x8000), - signed - ); - } - // Every signing was found again: the cipher ran once. - assert_eq!(service.fills, fills + 1); - // A key that changed has a new generation; its old entries miss. - let ib = service.key_generations[1]; - input.keys[1] = Some([7, 7]); - service.close(); - service.open(input); - assert_ne!(service.key_generations[1], ib); - } - - /// A return to earlier inputs finds their generation again; other inputs - /// get their own, and beyond the inputs kept a generation is new. - #[test] - fn generations_follow_the_inputs() { - let mut service = PointerService::new(); - let tcr = 25 | 25 << 16; - let (first, other) = ( - inputs(pauth::Version::Faulting, tcr), - inputs(pauth::Version::Classic, tcr), - ); - service.open(first); - let generation = service.generation; - service.open(other); - assert_ne!(service.generation, generation); - service.open(first); - assert_eq!(service.generation, generation); - for extra in 1..=POINTER_INPUTS_SEEN as u64 { - service.open(inputs(pauth::Version::Faulting, tcr + (extra << 32))); - } - service.open(first); - assert!(service.generation > generation); - service.close(); - assert!(!service.is_open()); - assert_eq!(service.tags, [0; pointer::TAG_WORDS]); - assert_eq!( - service.result( - PointerOperation::Sign, - stela_contracts::pauth::Key::Ia, - 1, - 2 - ), - None - ); - } -} +//! The PAC results the engine computes, remembers and lets native code +//! complete (`x86_64::pointer`). +//! +//! A signing or authentication is a pure function of its key, the chip's +//! PAC version, the regime's TCR (Arm `AddPAC`, `Auth`) and its operands, +//! so [`PointerService`] remembers results in a memo tagged with the +//! generation of that key's inputs. It lives at a fixed host address: PAC +//! thunks read its memo and its tag words, and on a memo miss call +//! [`complete`] with it, which computes the result exactly as the engine's +//! exit would ([`PointerService::result`]) without leaving native code. +//! A key's tag word is nonzero only while the service is open and the key +//! was found enabled and untrapped under the current derived state, which +//! is what both paths require, or [`pointer::DISABLED`] while it was found +//! disabled, whose results [`complete`] gives and remembers under that word. +//! Native code reads a memo whatever the tag words: an empty one shared by +//! every service until a service needs its own. +use crate::pauth; +use alloc::{boxed::Box, vec, vec::Vec}; +use core::mem::offset_of; +use stela_compiler::{Anchor, Place, block::PointerAuthenticationKey, x86_64::pointer}; + +pub(super) mod census; + +/// The memo native code reads while its service has none: no entry's tag +/// matches a tag word, so every lookup misses ([`pointer::DISABLED`]). +/// Only read, through its address. +static EMPTY_MEMO: [core::sync::atomic::AtomicU64; pointer::MEMO_ENTRIES * 4] = + [const { core::sync::atomic::AtomicU64::new(0) }; pointer::MEMO_ENTRIES * 4]; + +/// The distinct keys (each with the version and TCR) whose memo +/// generations are kept: two per process (its IB and DB keys) for over a +/// hundred processes. The lists are kept most recent first, so the keys in +/// use are found in the first few entries. +pub(super) const POINTER_INPUTS_SEEN: usize = 256; + +/// What a PAC result depends on besides its operands: the five keys, the +/// chip's PAC version and the regime's TCR (Arm `AddPAC`, `Auth`). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct PointerInputs { + pub(super) keys: [Option<[u64; 2]>; 5], + pub(super) version: pauth::Version, + pub(super) tcr: u64, +} + +/// What the results of one key depend on: its tag word's index, its value, +/// the chip's PAC version and the regime's TCR. Another key's value does +/// not change them, so a key's entries outlive changes of the others (a +/// process's own keys beside the kernel's, which stay). +#[derive(Clone, Copy, PartialEq, Eq)] +struct KeyInputs { + index: u8, + key: Option<[u64; 2]>, + version: pauth::Version, + tcr: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum PointerOperation { + Sign, + Authenticate { combined: bool }, +} + +/// The [`pointer::MemoEntry`] kinds of the results native code does not +/// complete, plus 1 for a combined form: an authentication that failed +/// without a fault, and one that faults with the code in `value`. +const UNAUTHENTICATED: u64 = 3; +const FAULTED: u64 = 5; +/// The tag bits of an entry's kind. +const KIND: u64 = 0xf; + +/// A result: the value and whether it authenticated (signings always do), +/// or the PAC failure code of a faulting authentication. +pub(super) type PointerResult = Result<(u64, bool), u8>; + +/// The memo kind and value of an operation's result. +fn memo_result(operation: PointerOperation, result: PointerResult) -> (u64, u64) { + let combined = u64::from(operation == PointerOperation::Authenticate { combined: true }); + match (operation, result) { + (PointerOperation::Sign, Ok((value, _))) => (pointer::SIGNED, value), + (_, Ok((value, true))) => (pointer::AUTHENTICATED, value), + (_, Ok((value, false))) => (UNAUTHENTICATED + combined, value), + (_, Err(code)) => (FAULTED + combined, u64::from(code)), + } +} + +/// The memo index of a key. +pub(super) fn memo_key(key: stela_contracts::pauth::Key) -> u8 { + pointer::key_index(match key { + stela_contracts::pauth::Key::Ia => PointerAuthenticationKey::Ia, + stela_contracts::pauth::Key::Ib => PointerAuthenticationKey::Ib, + stela_contracts::pauth::Key::Da => PointerAuthenticationKey::Da, + stela_contracts::pauth::Key::Db => PointerAuthenticationKey::Db, + }) +} + +fn key_of(key: PointerAuthenticationKey) -> stela_contracts::pauth::Key { + match key { + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, + } +} + +/// The engine's PAC context, memo and tag words, which native code reads. +pub(super) struct PointerService { + /// The keys, version and layout, while open. + context: Option, + /// The layouts of the most recent regime, kept across key changes. + layouts: Option, + /// Results, each tagged with the generation of its key's inputs when it + /// was computed; `generations[index]` is that of each key in `inputs`. + /// Allocated before the first usable native tag and kept at that + /// address for the owner. + memo: Option>, + inputs: Option, + pub(super) key_generations: [u64; pointer::TAG_WORDS], + /// The generation of the whole `inputs`, which native transitions + /// compare (`transition::check_pointer`): equal exactly when the key + /// generations, and so the tag words the engine reopens, are equal. + pub(super) generation: u64, + /// The whole inputs most recently seen, each with its key generations + /// and its generation, most recent first. + seen_inputs: Vec<(PointerInputs, [u64; pointer::TAG_WORDS], u64)>, + /// The generations of the most recent distinct key inputs, most recent + /// first, so entries stay valid across a return to an earlier key (EL0 + /// and EL1 keys, guarded levels, PE switches) and across changes of the + /// other keys. + seen: Vec<(KeyInputs, u64)>, + /// The last generation handed out; an evicted one is never reused. + generations: u64, + /// Each key's tag word for native code: zero until a PAC exit finds the + /// key enabled and untrapped under the current memo, and again whenever + /// derived state may have changed. + pub(super) tags: [u64; pointer::TAG_WORDS], + /// Instruction/data XPAC masks, independent of cryptographic key state. + pub(super) strips: [pointer::strip::Cell; 2], + /// [`SERVICE`]'s address, which blocks completing PAC instructions + /// inside themselves call through (`x86_64::pointer::inline`). + routine: u64, + /// Results computed since boot (the cipher ran): each is a memo miss, + /// of a block, a thunk or an engine exit. + pub(super) fills: u64, + /// Under `--profile`, what the memo missed and why ([`census`]). + pub(super) census: Option>, + /// What native code computes PAC results from where the cipher is the + /// host's AES rounds ([`cells`]): the open context's key schedules, + /// version and layouts. A function of the inputs alone, never of an + /// enable or trap: native transitions switch the tag words between + /// levels of one generation without the service. + pub(super) cipher: pointer::cipher::Cipher, + /// Bitmask of keys (`1 << index`) dirtied natively by `key_write_thunk`. + pub(super) dirty_keys: u64, + /// Bitmask of keys opened with non-DISABLED tags and valid storage addresses. + reopenable_mask: u64, + /// Live host addresses `[lo, hi]` of each key's storage words. + key_storage: [[u64; 2]; pointer::TAG_WORDS], +} + +/// The routine a thunk calls on a memo miss. +pub(super) const SERVICE: pointer::ServiceRoutine = complete; + +/// Where blocks find the service's tag words, strip cells and routine. +pub(super) const CELLS: pointer::inline::Cells = pointer::inline::Cells { + tags: offset_of!(PointerService, tags) as u32, + strips: offset_of!(PointerService, strips) as u32, + routine: offset_of!(PointerService, routine) as u32, + cipher: None, +}; + +/// Where native code finds the service's tag words. +pub(super) const TAGS: Place = Place::new(Anchor::Pointer, offset_of!(PointerService, tags)); + +/// Where native key-write thunks mark keys whose storage they updated. +pub(super) const DIRTY_KEYS: Place = + Place::new(Anchor::Pointer, offset_of!(PointerService, dirty_keys)); + +/// Where native code finds the service's cipher. +const CIPHER: Place = Place::new(Anchor::Pointer, offset_of!(PointerService, cipher)); + +/// Whether native code for `target` computes PAC results itself +/// (`x86_64::pointer::cipher`): the target has AES-NI and the engine's +/// cipher is the AES rounds, which it is exactly where the host has AES-NI. +/// Otherwise it looks them up in the memo and calls the service on a miss. +pub(super) fn native_cipher(target: stela_compiler::TargetCpu) -> Option { + (target.supports(stela_compiler::TargetCpu::Aes) && pauth::keyed::native()).then_some(CIPHER) +} + +/// [`CELLS`] for blocks compiled for `target`, with the cipher where +/// [`native_cipher`] takes it. +pub(super) fn cells(target: stela_compiler::TargetCpu) -> pointer::inline::Cells { + pointer::inline::Cells { + cipher: native_cipher(target).map(|place| place.offset as u32), + ..CELLS + } +} + +/// Where native code finds the stripping cell of `data`. +pub(super) const fn strip_place(data: bool) -> Place { + Place::new( + Anchor::Pointer, + offset_of!(PointerService, strips) + data as usize * size_of::(), + ) +} + +impl PointerService { + pub(super) fn new() -> Self { + Self { + context: None, + layouts: None, + memo: None, + inputs: None, + key_generations: [0; pointer::TAG_WORDS], + generation: 0, + seen_inputs: Vec::new(), + seen: Vec::new(), + generations: 0, + tags: [0; pointer::TAG_WORDS], + strips: [pointer::strip::Cell::default(); 2], + routine: SERVICE as usize as u64, + fills: 0, + census: None, + cipher: pointer::cipher::Cipher::default(), + dirty_keys: 0, + reopenable_mask: 0, + key_storage: [[0; 2]; pointer::TAG_WORDS], + } + } + + /// Forget the context and close every key, as derived state changed. + pub(super) fn close(&mut self) { + self.context = None; + self.close_native(); + } + + fn close_native(&mut self) -> [bool; 2] { + self.tags = [0; pointer::TAG_WORDS]; + self.dirty_keys = 0; + self.reopenable_mask = 0; + self.strips + .each_mut() + .map(|cell| core::mem::take(&mut cell.enabled) != 0) + } + + pub(super) fn set_key_storage(&mut self, storage: [[u64; 2]; pointer::TAG_WORDS]) { + self.key_storage = storage; + } + + fn mark_reopenable(&mut self, index: u8) { + let [lo, hi] = self.key_storage[usize::from(index)]; + if lo != 0 && hi != 0 { + self.reopenable_mask |= 1 << index; + } + } + + /// Derived state changed, now with `inputs`: every tag word and + /// stripping cell closes, and the context stays when it was made for + /// these inputs (else it is made anew, with their memo generation). + /// Returns which stripping cells were open, for the engine to reopen + /// with [`Self::reopen`]. + pub(super) fn revalidate(&mut self, inputs: PointerInputs) -> [bool; 2] { + let stripping = self.close_native(); + if self.context.is_none() || self.inputs != Some(inputs) { + self.open(inputs); + } + stripping + } + + /// Whether every key is closed to native code. + pub(super) fn tags_closed(&self) -> bool { + self.tags.iter().all(|&tag| tag == 0) + } + + /// Whether native code had anything open: a tag word or a stripping cell. + pub(super) fn any_open(&self) -> bool { + self.tags.iter().any(|&tag| tag != 0) || self.strips.iter().any(|cell| cell.enabled != 0) + } + + /// After [`Self::revalidate`], open `key`'s tag word as a PAC exit + /// would: [`pointer::DISABLED`] while its SCTLR enable is clear, else, + /// untrapped and present in the context, the memo's current tag. + pub(super) fn reopen( + &mut self, + key: stela_contracts::pauth::Key, + enabled: bool, + trapped: bool, + ) { + let index = memo_key(key); + let tag = if !enabled { + pointer::DISABLED + } else if !trapped + && self + .context + .as_ref() + .is_some_and(|context| context.has_key(key)) + { + self.mark_reopenable(index); + self.native_tag(index) + } else { + 0 + }; + self.tags[usize::from(index)] = tag; + } + + /// After [`Self::revalidate`], open the generic key's tag word as a + /// PACGA exit would: untrapped and present in the context, the memo's + /// current tag. + pub(super) fn reopen_generic(&mut self, trapped: bool) { + let usable = !trapped + && self + .context + .as_ref() + .is_some_and(pauth::Context::has_generic_key); + self.tags[usize::from(pointer::GENERIC_KEY)] = if usable { + self.mark_reopenable(pointer::GENERIC_KEY); + self.native_tag(pointer::GENERIC_KEY) + } else { + 0 + }; + } + + /// After [`Self::revalidate`], reopen the stripping cell of `data`. + pub(super) fn reopen_stripping(&mut self, data: bool) { + if let Some(keep) = self + .context + .as_ref() + .map(|context| context.stripping_masks(data)) + { + self.strips[usize::from(data)] = pointer::strip::Cell { + enabled: 1, + keep, + upper_extension: !keep[1], + }; + } + } + + pub(super) fn open_stripping(&mut self, context: &pauth::Context, data: bool) { + let keep = context.stripping_masks(data); + self.strips[usize::from(data)] = pointer::strip::Cell { + enabled: 1, + keep, + upper_extension: !keep[1], + }; + } + + pub(super) fn is_open(&self) -> bool { + self.context.is_some() + } + + fn record_inputs(&mut self, inputs: PointerInputs) { + let keys = self.key_generations; + self.generation = match self + .seen_inputs + .iter() + .position(|&(known, generations, _)| known == inputs && generations == keys) + { + Some(index) => self.seen_inputs.remove(index).2, + None => { + self.generations += 1; + self.generations + } + }; + self.seen_inputs.insert(0, (inputs, keys, self.generation)); + self.seen_inputs.truncate(POINTER_INPUTS_SEEN); + self.inputs = Some(inputs); + } + + /// Reopen a single key dirtied by native `key_write_thunk` in place, + /// reading live `[lo, hi]` from `key_storage[index]` and recomputing only + /// that key's schedule, generation, and tag word. + pub(super) fn refresh_dirty_key(&mut self, index: u8) -> bool { + let bit = 1u64 << index; + if self.dirty_keys & bit == 0 || self.reopenable_mask & bit == 0 { + return false; + } + let idx = usize::from(index); + let [lo_addr, hi_addr] = self.key_storage[idx]; + if lo_addr == 0 || hi_addr == 0 { + return false; + } + let Some(mut updated_inputs) = self.inputs else { + return false; + }; + if self.context.is_none() { + return false; + } + // SAFETY: `key_storage[index]` holds the PE's live key word addresses + // installed via `set_key_storage`, and only this PE runs on `self`. + let words = unsafe { + [ + (lo_addr as *const u64).read(), + (hi_addr as *const u64).read(), + ] + }; + updated_inputs.keys[idx] = Some(words); + self.key_generations[idx] = self.generation_of(KeyInputs { + index, + key: Some(words), + version: updated_inputs.version, + tcr: updated_inputs.tcr, + }); + self.record_inputs(updated_inputs); + let schedule = { + let context = self.context.as_mut().expect("checked above"); + context.set_key_words(idx, Some(words)); + context.native_schedule(idx).unwrap_or_default() + }; + self.cipher.schedules[idx] = schedule; + self.dirty_keys &= !bit; + self.tags[idx] = self.native_tag(index); + true + } + + /// Open the service with the current `inputs`. + pub(super) fn open(&mut self, inputs: PointerInputs) { + self.dirty_keys = 0; + if self.inputs != Some(inputs) { + for (index, key) in inputs.keys.into_iter().enumerate() { + self.key_generations[index] = self.generation_of(KeyInputs { + index: index as u8, + key, + version: inputs.version, + tcr: inputs.tcr, + }); + } + self.record_inputs(inputs); + } + let [ia, ib, da, db, generic] = inputs.keys; + let mut keys = pauth::Keys::from_optional_words([ia, ib, da, db]); + if let Some(generic) = generic { + keys = keys.with_generic_words(generic); + } + let layouts = match self.layouts { + Some(layouts) if layouts.tcr() == inputs.tcr => layouts, + _ => *self.layouts.insert(pauth::Layouts::new(inputs.tcr)), + }; + let context = pauth::Context::new_with_version(0, keys, inputs.version) + .with_layouts(layouts) + .with_implementation_defined_cipher(); + for (index, schedule) in self.cipher.schedules.iter_mut().enumerate() { + *schedule = context.native_schedule(index).unwrap_or_default(); + } + let classic = inputs.version == pauth::Version::Classic; + // Instructions, then data, each by bit 55. + self.cipher.ranges = [false, true].map(|data| { + let extension = layouts.native(data); + let select_bit63 = layouts.native_signing_select_bit63(data); + [false, true].map(|upper| { + pointer::cipher::Range::new( + extension[usize::from(upper)], + upper, + classic, + select_bit63, + ) + }) + }); + self.context = Some(context); + } + + /// A usable tag permits a thunk to dereference the memo anchor. A + /// closed or disabled tag is handled before that dereference. + fn native_tag(&mut self, key: u8) -> u64 { + if self.memo.is_none() { + self.allocate_memo(); + } + pointer::tag(self.key_generations[usize::from(key)], key, 0) + } + + #[cold] + fn allocate_memo(&mut self) { + self.memo = + Some(vec![pointer::MemoEntry::default(); pointer::MEMO_ENTRIES].into_boxed_slice()); + } + + /// What native code finds through [`Anchor::Pointer`] and + /// [`Anchor::Memo`] on its next entry: the memo, or the empty one. + pub(super) fn anchors(&self) -> (u64, u64) { + ( + self as *const Self as u64, + self.memo + .as_ref() + .map_or(EMPTY_MEMO.as_ptr() as u64, |memo| memo.as_ptr() as u64), + ) + } + + /// A disabled key's result, `pointer` unchanged (Arm `AddPAC`, `Auth`), + /// remembered under [`pointer::DISABLED`] for native code, whatever the + /// key: a signing's for signings, a success for both authentications. + fn disabled(&mut self, authenticate: bool, pointer: u64, modifier: u64) -> u64 { + if self.memo.is_none() { + self.allocate_memo(); + } + let kind = if authenticate { + pointer::AUTHENTICATED + } else { + pointer::SIGNED + }; + let memo = self.memo.as_mut().expect("memo allocated"); + pointer::insert( + memo, + pointer::MemoEntry { + pointer, + modifier, + tag: pointer::DISABLED | kind, + value: pointer, + }, + ); + pointer + } + + /// One signing or authentication with the open context, remembered + /// while its inputs stay the same, with `key` known enabled and + /// untrapped, which opens its tag word. The memo slot comes from the + /// pointer and modifier alone, so which slot is touched never depends on + /// a key. A signing whose result strips back to its pointer also + /// remembers that authenticating the result with the same key and + /// modifier succeeds with that pointer (Arm `Auth` recomputes the PAC of + /// the stripped pointer), which answers the epilogue of a signed frame; + /// a success answers both the combined and the plain authentication. + /// `None` when the service is closed or the context lacks the key. + pub(super) fn result( + &mut self, + operation: PointerOperation, + key: stela_contracts::pauth::Key, + pointer: u64, + modifier: u64, + ) -> Option { + if !self.context.as_ref()?.has_key(key) { + return None; + } + let index = memo_key(key); + self.mark_reopenable(index); + self.tags[usize::from(index)] = self.native_tag(index); + if let Some(result) = self.remembered(operation, key, pointer, modifier) { + return Some(result); + } + self.computed(operation, key, pointer, modifier) + } + + /// [`Self::result`] past its memo lookup, which a thunk's miss has + /// already made: the cipher's result, remembered. `None` when the + /// service is closed. + fn computed( + &mut self, + operation: PointerOperation, + key: stela_contracts::pauth::Key, + pointer: u64, + modifier: u64, + ) -> Option { + let index = memo_key(key); + let context = self.context.as_ref()?; + let words = context.words(key)?; + self.fills += 1; + let result = match operation { + PointerOperation::Sign => Ok((context.sign_with(key, words, pointer, modifier), true)), + PointerOperation::Authenticate { combined } => { + match context.authenticate_with(key, words, pointer, modifier, combined) { + Ok(result) => Ok((result.pointer, result.authenticated)), + Err(failure) => Err(failure.code), + } + } + }; + let strips_back = match (operation, result) { + (PointerOperation::Sign, Ok((signed, _))) => { + (context.strip(key, signed) == pointer).then_some(signed) + } + _ => None, + }; + if let Some(census) = &mut self.census + && let Some(inputs) = self.inputs + && let Some(words) = inputs.keys[usize::from(index)] + { + let kind = match operation { + PointerOperation::Sign => census::SIGN, + PointerOperation::Authenticate { .. } => census::AUTHENTICATE, + }; + census.fill( + index, + words, + inputs.tcr, + kind, + pointer, + modifier, + strips_back, + ); + } + let tag = pointer::tag(self.key_generations[usize::from(index)], index, 0); + let memo = self.memo.as_mut()?; + let (kind, value) = memo_result(operation, result); + pointer::insert( + memo, + pointer::MemoEntry { + pointer, + modifier, + tag: tag | kind, + value, + }, + ); + if let Some(signed) = strips_back { + pointer::insert( + memo, + pointer::MemoEntry { + pointer: signed, + modifier, + tag: tag | pointer::AUTHENTICATED, + value: pointer, + }, + ); + } + Some(result) + } + + /// PACGA with the open context, remembered as [`Self::result`] does, + /// the key known untrapped. `None` when the context lacks the key. + pub(super) fn generic_code(&mut self, data: u64, modifier: u64) -> Option { + let key = pointer::GENERIC_KEY; + let code = self.context.as_ref()?.generic_code(data, modifier).ok()?; + self.fills += 1; + if let Some(census) = &mut self.census + && let Some(inputs) = self.inputs + && let Some(words) = inputs.keys[usize::from(key)] + { + census.fill( + key, + words, + inputs.tcr, + census::GENERIC, + data, + modifier, + None, + ); + } + let tag = self.native_tag(key); + let memo = self.memo.as_mut().expect("memo for open tag"); + pointer::insert( + memo, + pointer::MemoEntry { + pointer: data, + modifier, + tag: tag | pointer::SIGNED, + value: code, + }, + ); + self.mark_reopenable(key); + self.tags[usize::from(key)] = tag; + Some(code) + } + + /// The memo generation of a key's `inputs`: the one they had if they + /// are among the [`POINTER_INPUTS_SEEN`] most recent distinct key + /// inputs, else a new one. A result depends only on its key's inputs + /// and its operands, so an entry of a reused generation is still exact. + fn generation_of(&mut self, inputs: KeyInputs) -> u64 { + let generation = match self.seen.iter().position(|&(known, _)| known == inputs) { + Some(index) => self.seen.remove(index).1, + None => { + self.generations += 1; + if let Some(census) = &mut self.census { + census.generations += 1; + } + self.generations + } + }; + self.seen.insert(0, (inputs, generation)); + self.seen.truncate(POINTER_INPUTS_SEEN); + generation + } + + /// The current memo's result of `operation` with `key` on these + /// operands, if it has one: a success answers both authentication forms. + pub(super) fn remembered( + &self, + operation: PointerOperation, + key: stela_contracts::pauth::Key, + pointer: u64, + modifier: u64, + ) -> Option { + let index = memo_key(key); + let tag = pointer::tag(self.key_generations[usize::from(index)], index, 0); + let first = pointer::slot(pointer, modifier); + let entry = *self.memo.as_ref()?[first..first + pointer::MEMO_WAYS] + .iter() + .find(|entry| { + entry.pointer == pointer && entry.modifier == modifier && entry.tag & !KIND == tag + })?; + let kind = entry.tag & KIND; + let combined = u64::from(operation == PointerOperation::Authenticate { combined: true }); + match operation { + PointerOperation::Sign => (kind == pointer::SIGNED).then_some(Ok((entry.value, true))), + PointerOperation::Authenticate { .. } => match kind { + pointer::AUTHENTICATED => Some(Ok((entry.value, true))), + kind if kind == UNAUTHENTICATED + combined => Some(Ok((entry.value, false))), + kind if kind == FAULTED + combined => Some(Err(entry.value as u8)), + _ => None, + }, + } + } +} + +translated_callee! { +/// A PAC thunk's memo miss (`x86_64::pointer::ServiceRoutine`): the result +/// of `request` on these operands while the requested key's tag word is +/// open, completed when it is a signing or a successful authentication, +/// and the pointer itself while the key is disabled. +/// A failed authentication is remembered for the exit the thunk then takes. +pub(super) fn complete( + service: u64, + request: u32, + pointer: u64, + modifier: u64, +) -> pointer::Completion { + // SAFETY: thunks pass the address of the machine's boxed service, which + // outlives every installed thunk; the engine does not touch it while + // native code runs. + let service = unsafe { &mut *(service as *mut PointerService) }; + let fills = service.fills; + let completion = complete_with(service, request, pointer, modifier); + if let Some(census) = &mut service.census { + census.native += service.fills - fills; + census.calls += 1; + } + completion +} +} + +/// [`complete`] of the service. +fn complete_with( + service: &mut PointerService, + request: u32, + pointer: u64, + modifier: u64, +) -> pointer::Completion { + if pointer::requests_generic_code(request) { + if service.tags[usize::from(pointer::GENERIC_KEY)] == 0 + && !service.refresh_dirty_key(pointer::GENERIC_KEY) + { + return pointer::Completion::default(); + } + return service.generic_code(pointer, modifier).map_or_else( + pointer::Completion::default, + |value| pointer::Completion { + completed: 1, + value, + }, + ); + } + let (key, authenticate, combined) = pointer::requested(request); + let key = key_of(key); + let index = memo_key(key); + match service.tags[usize::from(index)] { + 0 => { + if !service.refresh_dirty_key(index) { + return pointer::Completion::default(); + } + } + pointer::DISABLED => { + return pointer::Completion { + completed: 1, + value: service.disabled(authenticate, pointer, modifier), + }; + } + _ => {} + } + let operation = if authenticate { + PointerOperation::Authenticate { combined } + } else { + PointerOperation::Sign + }; + // The thunk missed the memo, and its open tag word says the context + // holds the key, so the result is computed at once. A failed + // authentication the memo held is computed and remembered again. + match service.computed(operation, key, pointer, modifier) { + Some(Ok((value, true))) => pointer::Completion { + completed: 1, + value, + }, + _ => pointer::Completion::default(), + } +} + +#[cfg(all( + test, + target_arch = "x86_64", + any(target_os = "linux", target_os = "macos") +))] +mod native_tests; + +#[cfg(all(test, target_arch = "x86_64", target_os = "linux"))] +mod cost; + +#[cfg(test)] +mod replay; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_memo_is_needed_only_for_a_usable_native_tag() { + use stela_contracts::pauth::Key; + + let mut owner = Box::new(PointerService::new()); + let (service, memo) = owner.anchors(); + let empty = EMPTY_MEMO.as_ptr() as u64; + assert_eq!(memo, empty); + let first = inputs(pauth::Version::Classic, 25 | 25 << 16); + let mut unavailable = first; + unavailable.keys = [None; 5]; + owner.open(unavailable); + owner.reopen(Key::Ia, false, true); + owner.reopen(Key::Ib, true, false); + owner.reopen_generic(false); + owner.reopen_stripping(true); + assert_eq!(owner.tags, [pointer::DISABLED, 0, 0, 0, 0]); + assert_eq!(owner.strips[1].enabled, 1); + assert_eq!(owner.result(PointerOperation::Sign, Key::Ib, 4, 8), None); + assert_eq!(owner.generic_code(4, 8), None); + assert_eq!(owner.anchors(), (service, empty)); + + owner.revalidate(first); + owner.reopen(Key::Ia, true, true); + owner.reopen_generic(true); + assert_eq!(owner.anchors(), (service, empty)); + owner.reopen(Key::Ia, true, false); + let memo = owner.anchors().1; + assert_ne!(memo, empty); + let tag = owner.tags[0]; + let result = owner.result(PointerOperation::Sign, Key::Ia, 4, 8).unwrap(); + owner.close(); + assert_eq!(owner.anchors(), (service, memo)); + owner.open(unavailable); + owner.revalidate(first); + owner.reopen(Key::Ia, true, false); + assert_eq!(owner.anchors(), (service, memo)); + assert_eq!(owner.tags[0], tag); + assert_eq!( + owner.remembered(PointerOperation::Sign, Key::Ia, 4, 8), + Some(result) + ); + + let mut other = Box::new(PointerService::new()); + other.open(first); + assert_eq!(other.anchors().1, empty); + other.reopen_generic(false); + assert_ne!(other.anchors().1, empty); + assert_ne!(other.anchors().1, memo); + } + + /// A disabled key's request completes with its pointer, from no key + /// and no cipher, and is remembered under the disabled word, which no + /// open or closed word's lookup takes; a closed key's is refused. + #[test] + fn disabled_keys_complete_with_their_pointer_for_native_code() { + use stela_contracts::pauth::Key; + + let mut service = Box::new(PointerService::new()); + let state = service.anchors().0; + let (data, modifier) = (0xffff_fe00_1234_5678, 0xffff_fe00_0000_8000); + let ib = u32::from(memo_key(Key::Ib)); + let authenticate = ib | pointer::REQUEST_AUTHENTICATE | pointer::REQUEST_COMBINED; + assert_eq!( + complete(state, ib, data, modifier), + pointer::Completion::default() + ); + service.reopen(Key::Ib, false, true); + assert_eq!( + service.tags[usize::from(memo_key(Key::Ib))], + pointer::DISABLED + ); + for (request, kind) in [ + (ib, pointer::SIGNED), + (authenticate, pointer::AUTHENTICATED), + ] { + assert_eq!( + complete(state, request, data, modifier), + pointer::Completion { + completed: 1, + value: data, + } + ); + assert_eq!( + service.memo.as_ref().unwrap()[pointer::slot(data, modifier)], + pointer::MemoEntry { + pointer: data, + modifier, + tag: pointer::DISABLED | kind, + value: data, + } + ); + } + assert_eq!(service.fills, 0); + assert_eq!( + service.anchors().1, + service.memo.as_ref().unwrap().as_ptr() as u64 + ); + } + + #[test] + fn fills_count_each_computed_result_once() { + use stela_contracts::pauth::Key; + + let mut service = Box::new(PointerService::new()); + service.open(inputs(pauth::Version::Classic, 25 | 25 << 16)); + assert_eq!(service.fills, 0); + let signed = service + .result(PointerOperation::Sign, Key::Ib, 0x1000, 0x20) + .unwrap(); + assert_eq!(service.fills, 1); + // A remembered signing, and the authentication its signing filled. + service.result(PointerOperation::Sign, Key::Ib, 0x1000, 0x20); + let (pointer, _) = signed.unwrap(); + let authenticate = PointerOperation::Authenticate { combined: false }; + service.result(authenticate, Key::Ib, pointer, 0x20); + assert_eq!(service.fills, 1); + service.result(PointerOperation::Sign, Key::Ib, 0x2000, 0x20); + service.generic_code(3, 4).unwrap(); + assert_eq!(service.fills, 3); + } + + #[test] + fn a_generic_code_opens_its_own_tag_and_completes_for_thunks() { + let mut service = Box::new(PointerService::new()); + let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); + input.keys[4] = Some([7, 9]); + service.open(input); + let state = service.anchors().0; + let form = pointer::Form::of( + stela_compiler::block::PointerAuthenticationOperation::GenericCode( + stela_compiler::block::pauth_memory::GenericCode { + destination: 1, + source: 2, + modifier: 3, + }, + ), + ) + .unwrap(); + let (data, modifier) = (0x1234, 0x5678); + // Closed, the service is not asked. + assert_eq!( + complete(state, form.request(), data, modifier), + pointer::Completion::default() + ); + let code = service.generic_code(data, modifier).unwrap(); + let tag = pointer::tag( + service.key_generations[usize::from(pointer::GENERIC_KEY)], + pointer::GENERIC_KEY, + 0, + ); + assert_eq!(service.tags[usize::from(pointer::GENERIC_KEY)], tag); + assert_eq!(service.tags[..4], [0; 4]); + assert_eq!( + service.memo.as_ref().unwrap()[pointer::slot(data, modifier)], + pointer::MemoEntry { + pointer: data, + modifier, + tag: tag | pointer::SIGNED, + value: code, + } + ); + // Open, a memo miss completes through it. + assert_eq!( + complete(state, form.request(), data, modifier), + pointer::Completion { + completed: 1, + value: code, + } + ); + service.reopen_generic(true); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + service.reopen_generic(false); + assert_eq!(service.tags[usize::from(pointer::GENERIC_KEY)], tag); + // Without the key nothing opens. + input.keys[4] = None; + service.close(); + service.open(input); + assert_eq!(service.generic_code(data, modifier), None); + service.reopen_generic(false); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + } + + #[test] + fn absent_keys_never_open_native_tags_or_reuse_a_known_key_generation() { + let mut service = PointerService::new(); + let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); + input.keys = [None; 5]; + service.open(input); + assert!( + service + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) + .is_none() + ); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + let unknown_generation = service.generation; + input.keys[0] = Some([11, 21]); + service.close(); + service.open(input); + assert!( + service + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) + .is_some() + ); + assert_ne!(service.generation, unknown_generation); + assert_eq!(service.tags[1..], [0; pointer::TAG_WORDS - 1]); + service.close(); + input.keys[0] = None; + service.open(input); + assert_eq!(service.generation, unknown_generation); + assert!( + service + .result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 0x4000, + 0x8000 + ) + .is_none() + ); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + } + + #[test] + fn stripping_cells_match_the_authoritative_layout_and_close_without_keys() { + let mut service = PointerService::new(); + for t0 in [0, 16, 17, 25, 39, 63] { + for t1 in [0, 16, 17, 25, 39, 63] { + for controls in 0..16u64 { + let tcr = t0 + | t1 << 16 + | (controls & 1) << 37 + | (controls & 2) << 37 + | (controls & 4) << 49 + | (controls & 8) << 49; + let context = + pauth::Context::new(0, pauth::Keys::from_optional_words([None; 4])) + .with_translation_regime(tcr); + for data in [false, true] { + service.open_stripping(&context, data); + assert!( + !service.is_open(), + "no cryptographic context or key is needed" + ); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + let cell = service.strips[usize::from(data)]; + assert_eq!(cell.enabled, 1); + for pointer in [0, u64::MAX, 1 << 55, 1 << 63, 0xdead_1234_5678_abcd] { + let upper = pointer & (1 << 55) != 0; + let keep = cell.keep[usize::from(upper)]; + let key = if data { + stela_contracts::pauth::Key::Da + } else { + stela_contracts::pauth::Key::Ia + }; + assert_eq!( + (pointer & keep) | if upper { cell.upper_extension } else { 0 }, + context.strip(key, pointer) + ); + } + } + service.close(); + assert!(service.strips.iter().all(|cell| cell.enabled == 0)); + } + } + } + } + + pub(super) fn inputs(version: pauth::Version, tcr: u64) -> PointerInputs { + let key = |index: u64| [0x1122_3344_5566_7788 ^ index, 0x99aa_bbcc_ddee_ff00 + index]; + PointerInputs { + keys: [key(1), key(2), key(3), key(4), key(5)].map(Some), + version, + tcr, + } + } + + fn request(key: PointerAuthenticationKey, operation: PointerOperation) -> u32 { + let mut request = u32::from(pointer::key_index(key)); + if let PointerOperation::Authenticate { combined } = operation { + request |= pointer::REQUEST_AUTHENTICATE; + if combined { + request |= pointer::REQUEST_COMBINED; + } + } + request + } + + /// The native completion answers exactly what the engine's exit + /// computes, for every key, form and version and for kernel and user + /// pointers, signed, corrupted and unsigned: it completes signings and + /// successful authentications, refuses the rest, and refuses everything + /// for a key whose tag word is closed. + #[test] + fn native_completions_equal_the_engine_results() { + use PointerAuthenticationKey as Key; + // T0SZ = T1SZ = 25 (39-bit VAs), TBI0 on. + let tcr = 25 | 25 << 16 | 1 << 37; + let operations = [ + PointerOperation::Sign, + PointerOperation::Authenticate { combined: false }, + PointerOperation::Authenticate { combined: true }, + ]; + for version in [ + pauth::Version::Classic, + pauth::Version::Enhanced, + pauth::Version::Faulting, + pauth::Version::FaultingCombined, + ] { + let inputs = inputs(version, tcr); + let mut native = Box::new(PointerService::new()); + let mut engine = PointerService::new(); + native.open(inputs); + engine.open(inputs); + let state = native.anchors().0; + for key in [Key::Ia, Key::Ib, Key::Da, Key::Db] { + let pauth_key = key_of(key); + let index = usize::from(pointer::key_index(key)); + for (step, base) in [0xffff_ff80_0012_3450_u64, 0x0000_0001_0000_8000] + .into_iter() + .enumerate() + { + let modifier = 0xffff_ff80_0040_0000 + step as u64 * 0x10; + let signed = engine.result(PointerOperation::Sign, pauth_key, base, modifier); + let Some(Ok((signed, true))) = signed else { + panic!("signing {base:#x}: {signed:?}"); + }; + for operand in [base, signed, signed ^ (1 << 50), signed ^ (1 << 62)] { + for operation in operations { + native.tags = [0; pointer::TAG_WORDS]; + let asked = complete(state, request(key, operation), operand, modifier); + assert_eq!(asked, pointer::Completion::default(), "a closed key"); + native.reopen(pauth_key, true, false); + assert_ne!(native.tags[index], 0); + let expected = engine.result(operation, pauth_key, operand, modifier); + let asked = complete(state, request(key, operation), operand, modifier); + let completed = match expected { + Some(Ok((value, true))) => pointer::Completion { + completed: 1, + value, + }, + _ => pointer::Completion::default(), + }; + assert_eq!(asked, completed, "{version:?} {key:?} {operation:?}"); + // The native call remembered what the exit then finds. + assert_eq!( + native.remembered(operation, pauth_key, operand, modifier), + expected + ); + } + } + } + } + } + } + + /// Memo misses of a modelled workload, run by hand: processes that each + /// have their own IB and DB keys (IA, DA and the generic key shared), + /// each running a call tree whose frames sign their return address + /// with IB and SP and authenticate it on return, with system calls into + /// a kernel whose frames use the kernel's IA and IB keys on the + /// thread's kernel stack while the process's DB key stays loaded; the + /// PE switches to the next process after each time slice. Prints the + /// cipher runs per PAC operation for each number of processes. + #[test] + #[ignore = "manual: opt-in"] + fn memo_replay_of_a_process_mix() { + extern crate std; + use stela_contracts::pauth::Key; + let tcr = 25 | 25 << 16; + let shared = |word: u64| Some([word, word.rotate_left(17)]); + let user = |process: u64| PointerInputs { + keys: [ + shared(1), + shared(0x100 + process), + shared(3), + shared(0x200 + process), + shared(5), + ], + version: pauth::Version::Classic, + tcr, + }; + let kernel = |process: u64| PointerInputs { + keys: [ + shared(9), + shared(10), + shared(3), + shared(0x200 + process), + shared(5), + ], + version: pauth::Version::Classic, + tcr, + }; + for processes in [2u64, 4, 8, 16, 32] { + let mut service = PointerService::new(); + let mut operations = 0u64; + // A frame: sign on entry, authenticate on return. + let mut frame = |service: &mut PointerService, key: Key, lr: u64, sp: u64| { + let signed = match service.result(PointerOperation::Sign, key, lr, sp) { + Some(Ok((signed, _))) => signed, + other => panic!("{other:?}"), + }; + service.result( + PointerOperation::Authenticate { combined: true }, + key, + signed, + sp, + ); + operations += 2; + }; + for slice in 0..4000u64 { + let process = slice % processes; + service.close(); + service.open(user(process)); + let code = 0x1_0000_0000 + process * 0x100_0000; + let stack = 0x16f_0000_0000 - process * 0x10_0000; + for call in 0..64u64 { + // A call tree: depth from the call number's low bits. + let depth = (call % 7) + 1; + for level in 0..depth { + let site = code + 0x40 * ((call * 7 + level * 13) % 97); + frame(&mut service, Key::Ib, site, stack - 0x60 * level); + } + if call % 16 == 15 { + service.close(); + service.open(kernel(process)); + let kernel_stack = 0xffff_fe10_0000_0000 + process * 0x4000; + for level in 0..5u64 { + let site = 0xffff_fe00_0800_0000 + 0x40 * (level * 11 + call % 3); + frame(&mut service, Key::Ib, site, kernel_stack - 0x80 * level); + frame( + &mut service, + Key::Ia, + site + 0x20, + kernel_stack - 0x80 * level, + ); + } + service.close(); + service.open(user(process)); + } + } + } + std::println!( + "REPLAY processes={processes} operations={operations} fills={} per_operation={:.4}", + service.fills, + service.fills as f64 / operations as f64 + ); + } + } + + /// What a memo miss costs, run by hand in a release build: a native + /// signing miss through the service routine, the cipher alone, and a + /// miss of the authentication form. Prints nanoseconds per call. + #[test] + #[ignore = "manual: opt-in"] + fn miss_path_timing() { + extern crate std; + use PointerAuthenticationKey as Key; + use std::time::Instant; + const CALLS: u64 = 1 << 20; + let tcr = 25 | 25 << 16 | 1 << 37; + let mut service = Box::new(PointerService::new()); + service.open(inputs(pauth::Version::Classic, tcr)); + let state = service.anchors().0; + service.reopen(stela_contracts::pauth::Key::Ib, true, false); + // Canonical upper pointers, which strip back from their signings. + let operand = |call: u64| { + ( + 0xffff_ff80_0800_0000 + call * 4, + 0xffff_fe10_0000_0000 - call * 16, + ) + }; + let sign = request(Key::Ib, PointerOperation::Sign); + let started = Instant::now(); + let mut sum = 0u64; + for call in 0..CALLS { + let (pointer, modifier) = operand(call); + sum = sum.wrapping_add(complete(state, sign, pointer, modifier).value); + } + let native = started.elapsed().as_nanos() as f64 / CALLS as f64; + let cipher = { + let context = service.context.as_ref().unwrap(); + let started = Instant::now(); + for call in 0..CALLS { + let (pointer, modifier) = operand(call + CALLS); + let signed = context.sign(stela_contracts::pauth::Key::Ib, pointer, modifier); + sum = sum.wrapping_add(signed.unwrap_or(0)); + } + started.elapsed().as_nanos() as f64 / CALLS as f64 + }; + let authenticate = request(Key::Ib, PointerOperation::Authenticate { combined: true }); + let started = Instant::now(); + for call in 0..CALLS { + let (pointer, modifier) = operand(call + 2 * CALLS); + sum = sum.wrapping_add(complete(state, authenticate, pointer, modifier).value); + } + let failed = started.elapsed().as_nanos() as f64 / CALLS as f64; + std::println!( + "MISS sign_through_service={native:.1}ns sign_alone={cipher:.1}ns auth_miss={failed:.1}ns fills={} ({sum:x})", + service.fills + ); + // Host instructions of one call, single-stepped under the trap flag. + #[cfg(target_os = "linux")] + { + let (pointer, modifier) = operand(3 * CALLS); + let miss = steps(|| { + core::hint::black_box(complete(state, sign, pointer, modifier)); + }); + let context = service.context.as_ref().unwrap(); + let (pointer, modifier) = operand(3 * CALLS + 1); + let alone = steps(|| { + let key = stela_contracts::pauth::Key::Ib; + core::hint::black_box(context.sign(key, pointer, modifier).ok()); + }); + let key = stela_contracts::pauth::Key::Ib; + let strip = steps(|| { + core::hint::black_box(context.strip(key, pointer)); + }); + let (pointer, modifier) = operand(3 * CALLS + 2); + let lookup = steps(|| { + core::hint::black_box(service.remembered( + PointerOperation::Sign, + key, + pointer, + modifier, + )); + }); + let memo = service.memo.as_mut().unwrap(); + let insert = steps(|| { + pointer::insert( + memo, + pointer::MemoEntry { + pointer, + modifier, + tag: 7, + value: 7, + }, + ); + }); + let tag = steps(|| { + core::hint::black_box(service.native_tag(1)); + }); + std::println!( + "MISS instructions sign_through_service={miss} sign_alone={alone} strip={strip} lookup={lookup} insert={insert} tag={tag}" + ); + } + } + + /// The instructions `run` executes, counted under the trap flag. + #[cfg(target_os = "linux")] + pub(super) fn steps(run: impl FnOnce()) -> usize { + use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + #[repr(C)] + struct SigAction { + handler: usize, + mask: [u64; 16], + flags: i32, + restorer: usize, + } + unsafe extern "C" { + fn sigaction(signal: i32, action: *const SigAction, old: *mut SigAction) -> i32; + } + static STEPS: AtomicUsize = AtomicUsize::new(0); + extern "C" fn step(_: i32, _: *mut core::ffi::c_void, _: *mut core::ffi::c_void) { + STEPS.fetch_add(1, Relaxed); + } + STEPS.store(0, Relaxed); + let action = SigAction { + handler: step as extern "C" fn(i32, *mut core::ffi::c_void, *mut core::ffi::c_void) + as usize, + mask: [0; 16], + flags: 4, + restorer: 0, + }; + // SAFETY: a SIGTRAP handler that only counts; the trap flag is set + // around `run` alone. + unsafe { + sigaction(5, &action, core::ptr::null_mut()); + core::arch::asm!("pushfq", "or qword ptr [rsp], 0x100", "popfq"); + } + run(); + // SAFETY: as above. + unsafe { core::arch::asm!("pushfq", "and qword ptr [rsp], -257", "popfq") }; + STEPS.load(Relaxed) + } + + /// A key's entries outlive changes of the other keys: a process's keys + /// change on every switch while the kernel's stay, and the kernel's + /// results must still be found. + #[test] + fn a_keys_entries_outlive_changes_of_the_other_keys() { + use stela_contracts::pauth::Key; + let mut service = PointerService::new(); + let mut input = inputs(pauth::Version::Classic, 25 | 25 << 16); + service.open(input); + let fills = service.fills; + let signed = service.result(PointerOperation::Sign, Key::Ia, 0x4000, 0x8000); + assert_eq!(service.fills, fills + 1); + for process in 0..2 * POINTER_INPUTS_SEEN as u64 { + input.keys[1] = Some([process, !process]); + input.keys[2] = Some([process << 1, process]); + service.close(); + service.open(input); + assert_eq!( + service.result(PointerOperation::Sign, Key::Ia, 0x4000, 0x8000), + signed + ); + } + // Every signing was found again: the cipher ran once. + assert_eq!(service.fills, fills + 1); + // A key that changed has a new generation; its old entries miss. + let ib = service.key_generations[1]; + input.keys[1] = Some([7, 7]); + service.close(); + service.open(input); + assert_ne!(service.key_generations[1], ib); + } + + /// A return to earlier inputs finds their generation again; other inputs + /// get their own, and beyond the inputs kept a generation is new. + #[test] + fn generations_follow_the_inputs() { + let mut service = PointerService::new(); + let tcr = 25 | 25 << 16; + let (first, other) = ( + inputs(pauth::Version::Faulting, tcr), + inputs(pauth::Version::Classic, tcr), + ); + service.open(first); + let generation = service.generation; + service.open(other); + assert_ne!(service.generation, generation); + service.open(first); + assert_eq!(service.generation, generation); + for extra in 1..=POINTER_INPUTS_SEEN as u64 { + service.open(inputs(pauth::Version::Faulting, tcr + (extra << 32))); + } + service.open(first); + assert!(service.generation > generation); + service.close(); + assert!(!service.is_open()); + assert_eq!(service.tags, [0; pointer::TAG_WORDS]); + assert_eq!( + service.result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ia, + 1, + 2 + ), + None + ); + } + + /// Opt 3: when native `key_write_thunk` zeroes a single key's tag and marks + /// its bit in `dirty_keys`, `complete_with` refreshes ONLY that key in place + /// from its live storage while preserving all other keys' tags and schedules. + #[test] + fn refresh_dirty_key_reopens_only_dirtied_key_in_place() { + use stela_contracts::pauth::Key; + + let tcr = 25 | 25 << 16 | 1 << 37; + let mut storage = [ + [0x1111_2222_3333_4444_u64, 0x5555_6666_7777_8888_u64], + [0x2222_3333_4444_5555_u64, 0x6666_7777_8888_9999_u64], + [0x3333_4444_5555_6666_u64, 0x7777_8888_9999_aaaa_u64], + [0x4444_5555_6666_7777_u64, 0x8888_9999_aaaa_bbbb_u64], + [0x5555_6666_7777_8888_u64, 0x9999_aaaa_bbbb_cccc_u64], + ]; + let mut service = Box::new(PointerService::new()); + let ptrs: [[u64; 2]; 5] = core::array::from_fn(|i| [ + &storage[i][0] as *const u64 as u64, + &storage[i][1] as *const u64 as u64, + ]); + service.set_key_storage(ptrs); + let init = PointerInputs { + keys: storage.map(Some), + version: pauth::Version::Enhanced, + tcr, + }; + service.open(init); + for key in [Key::Ia, Key::Ib, Key::Da, Key::Db] { + service.reopen(key, true, false); + } + service.reopen_generic(false); + let orig_tags = service.tags; + let orig_schedules = service.cipher.schedules; + assert!(orig_tags.iter().all(|&t| t != 0 && t != pointer::DISABLED)); + + // Simulate native `key_write_thunk` changing IB (index 1). + let new_ib = [0xaaaa_bbbb_cccc_dddd_u64, 0xeeee_ffff_0000_1111_u64]; + storage[1] = new_ib; + service.tags[1] = 0; + service.dirty_keys |= 1 << 1; + + // Other keys remain valid and untouched. + assert_eq!(service.tags[0], orig_tags[0]); + assert_eq!(service.tags[2], orig_tags[2]); + assert_eq!(service.tags[3], orig_tags[3]); + assert_eq!(service.tags[4], orig_tags[4]); + + let state = service.anchors().0; + let ptr = 0x0000_0001_2345_6780_u64; + let modifier = 0x0000_0002_3456_7890_u64; + let ib_sign = u32::from(memo_key(Key::Ib)); + let completion = complete(state, ib_sign, ptr, modifier); + + let expected = pauth::Context::new_with_version( + 0, + pauth::Keys::from_words(storage[0], new_ib, storage[2], storage[3]), + pauth::Version::Enhanced, + ) + .with_translation_regime(tcr) + .with_implementation_defined_cipher() + .sign(Key::Ib, ptr, modifier) + .unwrap(); + + assert_eq!( + completion, + pointer::Completion { + completed: 1, + value: expected, + } + ); + assert_eq!(service.dirty_keys, 0); + assert_ne!(service.tags[1], 0); + assert_ne!(service.tags[1], orig_tags[1]); + assert_eq!(service.tags[0], orig_tags[0]); + assert_eq!(service.tags[2], orig_tags[2]); + assert_eq!(service.tags[3], orig_tags[3]); + assert_eq!(service.tags[4], orig_tags[4]); + assert_ne!(service.cipher.schedules[1], orig_schedules[1]); + assert_eq!(service.cipher.schedules[0], orig_schedules[0]); + assert_eq!(service.cipher.schedules[2], orig_schedules[2]); + assert_eq!(service.cipher.schedules[3], orig_schedules[3]); + assert_eq!(service.cipher.schedules[4], orig_schedules[4]); + } +} diff --git a/crates/stela-engine/src/machine/engine/pointer/native_tests.rs b/crates/stela-engine/src/machine/engine/pointer/native_tests.rs index 57fe62341f..81cce7c5c0 100644 --- a/crates/stela-engine/src/machine/engine/pointer/native_tests.rs +++ b/crates/stela-engine/src/machine/engine/pointer/native_tests.rs @@ -1,903 +1,991 @@ -//! Native code given the service's cipher computes exactly what the -//! engine's exit computes ([`PointerService::result`] with the reference -//! cipher of the same keys), for every key, form and PAC version, under -//! TCRs with and without TBI and TBID, for EL0, EL1 and EL2 address -//! layouts, both key enables and a closed key: thunks and blocks complete -//! signings, successful authentications and PACGA without the service, and -//! leave the rest to it, which completes or refuses them as before. - -use super::*; -use alloc::format; -use stela_compiler::{ - GuestAddress, GuestState, TargetCpu, - block::{ - BlockProfile, CompilationPlan, ExitKind, Features, - PointerAuthenticationModifier as Modifier, PointerAuthenticationOperation as Operation, - }, - x86_64::{NativeSystem, block_entry, pinned, pointer::inline::Cells}, -}; - -/// Executable copies of native code, unmapped on drop. -struct Mapped { - page: *mut core::ffi::c_void, - bytes: usize, -} - -unsafe extern "C" { - fn mmap( - address: *mut core::ffi::c_void, - bytes: usize, - protection: i32, - flags: i32, - fd: i32, - offset: i64, - ) -> *mut core::ffi::c_void; - fn mprotect(address: *mut core::ffi::c_void, bytes: usize, protection: i32) -> i32; - fn munmap(address: *mut core::ffi::c_void, bytes: usize) -> i32; -} - -#[cfg(target_os = "macos")] -const MAP_ANONYMOUS: i32 = 0x1000; -#[cfg(target_os = "linux")] -const MAP_ANONYMOUS: i32 = 0x20; - -impl Mapped { - /// `body` entered as the engine enters native code - /// (`pinned::entered`). - fn new(body: &[u8]) -> Self { - let code = pinned::entered(body); - let bytes = code.len().next_multiple_of(4096); - // SAFETY: private anonymous memory, RX after the copy. - unsafe { - let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANONYMOUS, -1, 0); - assert_ne!(page as usize, usize::MAX); - core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); - assert_eq!(mprotect(page, bytes, 5), 0); - Self { page, bytes } - } - } - - /// Run it on `state`: the exit's PC and kind. - fn run(&self, state: &mut GuestState) -> (u64, u64) { - // SAFETY: the code is the block ABI's; it touches only `state`, what - // its anchors name (the service, its memo), and the stack, and calls - // the service. - let exit = unsafe { block_entry::enter(self.page.cast(), state, 0, 0) }; - (exit as u64, (exit >> 64) as u64) - } -} - -impl Drop for Mapped { - fn drop(&mut self) { - // SAFETY: mapped by `new`, no longer running. - unsafe { assert_eq!(munmap(self.page, self.bytes), 0) }; - } -} - -/// The cipher's place, or `None` on a host without AES-NI, whose tests -/// then have nothing to compare. -fn cipher() -> Option { - let place = native_cipher(TargetCpu::detect()); - if place.is_none() { - extern crate std; - std::eprintln!("no AES-NI: the native cipher is not used on this host"); - } - place -} - -/// TCRs of the regimes the engine runs: EL1&0 with 39- and 47-bit ranges, -/// TBI0 alone (macOS EL0 data), TBI0 with TBID0, both TBIs, neither (a -/// signing then selects by bit 63), and TBI1 with TBID1, as an EL2 host -/// regime may. -const TCRS: [u64; 6] = [ - 25 | 25 << 16 | 1 << 37, - 17 | 25 << 16 | 1 << 37 | 1 << 51, - 17 | 17 << 16 | 1 << 37 | 1 << 38, - 25 | 25 << 16, - 16 | 39 << 16 | 1 << 38 | 1 << 52, - 39 | 16 << 16 | 1 << 38, -]; - -const VERSIONS: [pauth::Version; 4] = [ - pauth::Version::Classic, - pauth::Version::Enhanced, - pauth::Version::Faulting, - pauth::Version::FaultingCombined, -]; - -/// Pointers of EL0 and of the kernel, tagged, all ones, zero and garbage, -/// before signing. -const POINTERS: [u64; 8] = [ - 0x0000_0001_0000_8000, - 0x0000_7fff_ffff_f000, - 0xffff_fe00_1234_5678, - 0xffff_ff80_0012_3450, - 0x5a00_0001_0000_8000, - u64::MAX, - 0, - 0x1234_5678_9abc_def0, -]; - -const KEYS: [PointerAuthenticationKey; 4] = [ - PointerAuthenticationKey::Ia, - PointerAuthenticationKey::Ib, - PointerAuthenticationKey::Da, - PointerAuthenticationKey::Db, -]; - -/// A thunk's form: a signing into X3, a plain authentication of X3, a -/// branch authentication of X3 (the combined form), each with X5 as the -/// modifier, or PACGA of X3 and X5 into X4. -#[derive(Clone, Copy, Debug)] -enum Kind { - Sign, - Authenticate, - Branch, - Generic, -} - -fn operation(kind: Kind, key: PointerAuthenticationKey) -> Operation { - let modifier = Modifier::Register(5); - match kind { - Kind::Sign => Operation::Sign { - key, - destination: 3, - modifier, - }, - Kind::Authenticate => Operation::Authenticate { - key, - destination: 3, - modifier, - }, - Kind::Branch => Operation::Branch { - key, - target: 3, - modifier, - link: false, - }, - Kind::Generic => Operation::GenericCode(stela_compiler::block::pauth_memory::GenericCode { - destination: 4, - source: 3, - modifier: 5, - }), - } -} - -/// A key's enable: open and enabled, disabled, or its tag word closed. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Enable { - Enabled, - Disabled, - Closed, -} - -const PC: u64 = 0x4000; - -/// Thunks compute what the engine computes: signings, successful -/// authentications and PACGA without a service call, failures and -/// non-canonical signings through it, as before. -#[test] -fn thunks_compute_what_the_engine_computes() { - let Some(cipher) = cipher() else { return }; - let mut thunks = Vec::new(); - for kind in [Kind::Sign, Kind::Authenticate, Kind::Branch] { - for key in KEYS { - let form = pointer::Form::of(operation(kind, key)).expect("a thunk form"); - let thunk = pointer::thunk( - form, - GuestAddress(PC), - TAGS, - SERVICE as usize as u64, - Some(cipher), - ); - thunks.push((kind, Some(key), Mapped::new(&thunk.code))); - } - } - let generic = - pointer::Form::of(operation(Kind::Generic, PointerAuthenticationKey::Ia)).unwrap(); - let thunk = pointer::thunk( - generic, - GuestAddress(PC), - TAGS, - SERVICE as usize as u64, - Some(cipher), - ); - thunks.push((Kind::Generic, None, Mapped::new(&thunk.code))); - let (mut computed, mut serviced) = (0u64, 0u64); - for tcr in TCRS { - for version in VERSIONS { - let inputs = super::tests::inputs(version, tcr); - let mut native = Box::new(PointerService::new()); - let mut engine = PointerService::new(); - native.open(inputs); - engine.open(inputs); - let mut state = GuestState::default(); - state.anchors[Anchor::Pointer] = native.anchors().0; - for (kind, key, code) in &thunks { - for enable in [Enable::Enabled, Enable::Disabled, Enable::Closed] { - if key.is_none() && enable == Enable::Disabled { - continue; - } - native.close_native(); - match (key, enable) { - (_, Enable::Closed) => {} - (Some(key), enable) => { - native.reopen(key_of(*key), enable == Enable::Enabled, false) - } - (None, _) => native.reopen_generic(false), - } - // The memo a usable tag word allocates. - state.anchors[Anchor::Memo] = native.anchors().1; - for (step, &base) in POINTERS.iter().enumerate() { - let modifier = 0xffff_fe10_0000_0000 ^ (step as u64) << 4 ^ tcr; - let mut operands = vec![base]; - if let Some(key) = key { - let signed = - engine.result(PointerOperation::Sign, key_of(*key), base, modifier); - if let Some(Ok((signed, _))) = signed { - operands.extend([signed, signed ^ 1 << 50, signed ^ 1 << 62]); - } - } - for operand in operands { - let expected = - expect(&mut engine, *kind, *key, enable, operand, modifier); - state.x[3] = operand; - state.x[4] = 0x4444; - state.x[5] = modifier; - let fills = native.fills; - let exit = code.run(&mut state); - let what = format!( - "{version:?} tcr={tcr:#x} {kind:?} {key:?} {enable:?} {operand:#x}" - ); - let destination = if matches!(kind, Kind::Generic) { 4 } else { 3 }; - match (expected, kind) { - (Some(value), Kind::Branch) => { - assert_eq!(exit, (value, ExitKind::Indirect as u64), "{what}"); - } - (Some(value), _) => { - assert_eq!( - exit, - (PC + 4, ExitKind::Fallthrough as u64), - "{what}" - ); - assert_eq!(state.x[destination], value, "{what}"); - } - (None, _) => { - assert_eq!( - exit, - (PC, ExitKind::PointerAuthentication as u64), - "{what}" - ); - assert_eq!(state.x[3], operand, "{what}"); - } - } - // Completions the cipher gives never reach - // the service. - let canonical = enable == Enable::Disabled - || native_completes(&native, *kind, *key, operand); - if expected.is_some() && canonical { - assert_eq!(native.fills, fills, "{what}: a service call"); - computed += 1; - } else if native.fills != fills { - serviced += 1; - } - } - } - } - } - } - } - // Both paths ran: the corrupted signings and the authentications of - // unsigned pointers among the operands fail, through the service. - assert!( - computed > 10_000 && serviced > 0, - "{computed} computed, {serviced} serviced" - ); -} - -/// Native transitions switch the tag words between two exception levels -/// of one memo generation whose enables differ (`transition::check_pointer` -/// copies the tag words the engine reopened for each), without the service. -/// Thunks and blocks compiled once then give, at each level, what the engine -/// gives there: the pointer unchanged where the key is disabled, its -/// signing or authentication where it is enabled, in any order of switches. -/// Before, a disabled key's zero layouts stayed after a switch to the level -/// where it is enabled, and an enabled key's layouts after a switch back, so -/// a process whose keys are disabled at EL0 got signed pointers. -#[test] -fn tag_words_switched_natively_keep_each_levels_enables() { - use stela_contracts::pauth::Key; - let Some(cipher) = cipher() else { return }; - let mut thunks = Vec::new(); - for kind in [Kind::Sign, Kind::Authenticate, Kind::Branch] { - for key in KEYS { - let form = pointer::Form::of(operation(kind, key)).unwrap(); - let thunk = pointer::thunk( - form, - GuestAddress(PC), - TAGS, - SERVICE as usize as u64, - Some(cipher), - ); - thunks.push((kind, key, Mapped::new(&thunk.code))); - } - } - for tcr in TCRS { - for version in VERSIONS { - let inputs = super::tests::inputs(version, tcr); - let mut native = Box::new(PointerService::new()); - let mut engine = PointerService::new(); - native.open(inputs); - engine.open(inputs); - // The kernel's level: every key enabled. The process's: IA and - // DA disabled (a process without arm64e's JOP keys), IB and DB - // enabled; then the reverse. - let level = |native: &mut PointerService, disabled: [bool; 4]| { - native.close_native(); - for (key, disabled) in [Key::Ia, Key::Ib, Key::Da, Key::Db] - .into_iter() - .zip(disabled) - { - native.reopen(key, !disabled, false); - } - native.tags - }; - let kernel = level(&mut native, [false; 4]); - let process = level(&mut native, [true, false, true, false]); - let other = level(&mut native, [false, true, false, true]); - let mut state = GuestState::default(); - state.anchors[Anchor::Pointer] = native.anchors().0; - state.anchors[Anchor::Memo] = native.anchors().1; - for (round, tags) in [kernel, process, kernel, other, process, other, kernel] - .into_iter() - .enumerate() - { - // As a native transition writes them. - native.tags = tags; - for (kind, key, code) in &thunks { - let index = usize::from(pointer::key_index(*key)); - let enable = if tags[index] == pointer::DISABLED { - Enable::Disabled - } else { - Enable::Enabled - }; - let pointer = POINTERS[round % 4]; - let modifier = 0x0000_0001_6fd0_0000 + round as u64 * 0x40; - let signed = match engine.result( - PointerOperation::Sign, - key_of(*key), - pointer, - modifier, - ) { - Some(Ok((signed, _))) => signed, - other => panic!("{other:?}"), - }; - let operand = if matches!(kind, Kind::Sign) { - pointer - } else { - signed - }; - let expected = - expect(&mut engine, *kind, Some(*key), enable, operand, modifier); - state.x[3] = operand; - state.x[5] = modifier; - let exit = code.run(&mut state); - let what = format!( - "{version:?} tcr={tcr:#x} round {round} {kind:?} {key:?} {enable:?}" - ); - match (expected, kind) { - (Some(value), Kind::Branch) => { - assert_eq!(exit, (value, ExitKind::Indirect as u64), "{what}") - } - (Some(value), _) => { - assert_eq!(exit, (PC + 4, ExitKind::Fallthrough as u64), "{what}"); - assert_eq!(state.x[3], value, "{what}"); - } - // A pointer outside the regime's range fails its - // authentication, at either level. - (None, _) => { - assert_eq!(exit, (PC, ExitKind::PointerAuthentication as u64), "{what}") - } - } - } - } - } - } -} - -/// What the engine's exit gives for `kind` on `operand`: the completed -/// value, or `None` for what the native code leaves to the engine. -fn expect( - engine: &mut PointerService, - kind: Kind, - key: Option, - enable: Enable, - operand: u64, - modifier: u64, -) -> Option { - match (enable, key) { - (Enable::Closed, _) => None, - (Enable::Disabled, _) => Some(operand), - (Enable::Enabled, None) => engine.generic_code(operand, modifier), - (Enable::Enabled, Some(key)) => { - let operation = match kind { - Kind::Sign => PointerOperation::Sign, - Kind::Authenticate => PointerOperation::Authenticate { combined: false }, - _ => PointerOperation::Authenticate { combined: true }, - }; - match engine.result(operation, key_of(key), operand, modifier) { - Some(Ok((value, true))) => Some(value), - _ => None, - } - } - } -} - -/// Whether the cipher alone answers `kind` on `operand`: PACGA, any -/// authentication, and a signing whose pointer is canonical in its layout. -fn native_completes( - service: &PointerService, - kind: Kind, - key: Option, - operand: u64, -) -> bool { - let (Kind::Sign, Some(key)) = (kind, key) else { - return true; - }; - let data = matches!( - key, - PointerAuthenticationKey::Da | PointerAuthenticationKey::Db - ); - let range = service.cipher.ranges[usize::from(data)][usize::from(operand & 1 << 55 != 0)]; - operand & range.extension == range.canonical -} - -/// Blocks given the cipher complete PAC instructions in line with the -/// engine's results and leave at the first one the engine does not -/// complete, its result unwritten. -#[test] -fn blocks_compute_what_the_engine_computes() { - use stela_contracts::pauth::Key; - let Some(cipher) = cipher() else { return }; - // PACIA X0, X1; AUTDB X2, X3; PACGA X4, X5, X6; PACDB X7, X8; - // AUTIB X9, X10; ADD X11, X11, #1. - const WORDS: [u32; 6] = [ - 0xdac1_0020, - 0xdac1_1c62, - 0x9ac6_30a4, - 0xdac1_0d07, - 0xdac1_1549, - 0x9100_056b, - ]; - let source: Vec = WORDS.iter().flat_map(|word| word.to_le_bytes()).collect(); - let options = stela_compiler::Options::new( - BlockProfile::new(Features::SYSTEM_MODE), - TargetCpu::detect(), - ) - .with_native_system(NativeSystem { - pointer: Some(cells(TargetCpu::detect())), - ..NativeSystem::NONE - }); - assert_eq!( - cells(TargetCpu::detect()).cipher, - Some(cipher.offset as u32) - ); - let block = CompilationPlan::new(&source, GuestAddress(PC), &options) - .unwrap() - .compile() - .unwrap(); - assert_eq!(block.source_bytes, source.len()); - let code = Mapped::new(&block.native.x86_64_code); - for tcr in TCRS { - for version in VERSIONS { - let inputs = super::tests::inputs(version, tcr); - let mut native = Box::new(PointerService::new()); - let mut engine = PointerService::new(); - native.open(inputs); - engine.open(inputs); - for key in [Key::Ia, Key::Ib, Key::Da, Key::Db] { - native.reopen(key, true, false); - } - native.reopen_generic(false); - let (service, memo) = native.anchors(); - let mut state = GuestState::default(); - state.anchors[Anchor::Pointer] = service; - state.anchors[Anchor::Memo] = memo; - for (step, &pointer) in POINTERS.iter().enumerate() { - let modifier = 0x0000_0001_6fd0_0000 + step as u64 * 0x30; - let signed = |engine: &mut PointerService, key| match engine.result( - PointerOperation::Sign, - key, - pointer, - modifier, - ) { - Some(Ok((signed, _))) => signed, - other => panic!("{other:?}"), - }; - let db = signed(&mut engine, Key::Db); - let ib = signed(&mut engine, Key::Ib); - // A corrupted IB signing every other step. - let ib = if step % 2 == 1 { ib ^ 1 << 52 } else { ib }; - let mut x = [0u64; 12]; - x[1] = modifier; - x[0] = pointer; - x[2] = db; - x[3] = modifier; - (x[4], x[5], x[6]) = (pointer, pointer ^ modifier, modifier); - (x[7], x[8]) = (pointer, modifier + 8); - (x[9], x[10]) = (ib, modifier); - state.x[..12].copy_from_slice(&x); - // The engine's results, in order, up to the first it does - // not complete. - let mut expected = x; - let mut stop = None; - let steps: [(usize, Option, PointerOperation, usize, usize); 5] = [ - (0, Some(Key::Ia), PointerOperation::Sign, 0, 1), - ( - 1, - Some(Key::Db), - PointerOperation::Authenticate { combined: false }, - 2, - 3, - ), - (2, None, PointerOperation::Sign, 4, 5), - (3, Some(Key::Db), PointerOperation::Sign, 7, 8), - ( - 4, - Some(Key::Ib), - PointerOperation::Authenticate { combined: false }, - 9, - 10, - ), - ]; - for (at, key, operation, target, from) in steps { - let result = match key { - Some(key) => { - match engine.result(operation, key, expected[target], expected[from]) { - Some(Ok((value, true))) => Some(value), - _ => None, - } - } - None => engine.generic_code(expected[from], expected[6]), - }; - match result { - Some(value) => { - let destination = if key.is_none() { 4 } else { target }; - expected[destination] = value; - } - None => { - stop = Some(at); - break; - } - } - } - let exit = code.run(&mut state); - let what = format!("{version:?} tcr={tcr:#x} {pointer:#x}"); - match stop { - Some(at) => assert_eq!( - exit, - (PC + 4 * at as u64, ExitKind::PointerAuthentication as u64), - "{what}" - ), - None => { - expected[11] += 1; - assert_eq!(exit.0, PC + 4 * WORDS.len() as u64, "{what}"); - } - } - assert_eq!(state.x[..12], expected, "{what}"); - } - } - } -} - -/// A block ending with RETA*, BRA* or BLRA* authenticates the target in -/// line and branches to it as RET, BR and BLR do, linking X30 for BLRA*, -/// with what the engine's exit gives: every instruction key, the register, -/// zero and SP modifiers, signed, corrupted and unsigned targets, enabled, -/// disabled and closed keys, every PAC version and regime, through the -/// cipher and through the memo. What the engine does not complete leaves at -/// the instruction with its PAC exit, X30 unchanged. -#[test] -fn blocks_complete_branch_forms_as_the_engine_does() { - use stela_compiler::x86_64::chain; - use stela_contracts::pauth::Key; - // (word, key, target register, modifier register: None for SP, exit). - let forms: [(u32, Key, usize, Option, ExitKind); 10] = [ - (0xd65f_0bff, Key::Ia, 30, None, ExitKind::Return), // retaa - (0xd65f_0fff, Key::Ib, 30, None, ExitKind::Return), // retab - (0xd71f_0865, Key::Ia, 3, Some(5), ExitKind::Indirect), // braa x3, x5 - (0xd71f_0c65, Key::Ib, 3, Some(5), ExitKind::Indirect), // brab x3, x5 - (0xd73f_0865, Key::Ia, 3, Some(5), ExitKind::Call), // blraa x3, x5 - (0xd73f_0c65, Key::Ib, 3, Some(5), ExitKind::Call), // blrab x3, x5 - (0xd61f_087f, Key::Ia, 3, Some(31), ExitKind::Indirect), // braaz x3 - (0xd63f_0c7f, Key::Ib, 3, Some(31), ExitKind::Call), // blrabz x3 - (0xd73f_0bc5, Key::Ia, 30, Some(5), ExitKind::Call), // blraa x30, x5 - (0xd73f_087e, Key::Ia, 3, Some(30), ExitKind::Call), // blraa x3, x30 - ]; - let host = cells(TargetCpu::detect()); - // Through the cipher where the host has it, and through the memo. - let paths: Vec<_> = [ - host.cipher.map(|_| host), - Some(Cells { - cipher: None, - ..host - }), - ] - .into_iter() - .flatten() - .collect(); - let mut checked = [0usize; 2]; - for cells in paths { - for (word, key, target, modifier_register, kind) in forms { - let options = stela_compiler::Options::new( - BlockProfile::new(Features::SYSTEM_MODE), - TargetCpu::detect(), - ) - .with_native_system(NativeSystem { - pointer: Some(cells), - ..NativeSystem::NONE - }); - let block = CompilationPlan::new(&word.to_le_bytes(), GuestAddress(PC), &options) - .unwrap() - .compile() - .unwrap(); - let code = &block.native.x86_64_code; - // The engine finds the exit to the target where RET and BR put - // theirs (a linked BLR's ends with its continuation). - let ending = chain::without_failures(code); - let ending = &ending[ending.len() - chain::DYNAMIC_EXIT_BYTES..]; - assert!( - kind == ExitKind::Call || chain::is_dynamic_exit(ending, kind), - "{word:#x}" - ); - let code = Mapped::new(code); - for tcr in TCRS { - for version in VERSIONS { - let inputs = super::tests::inputs(version, tcr); - let mut native = Box::new(PointerService::new()); - let mut engine = PointerService::new(); - native.open(inputs); - engine.open(inputs); - for enable in [Enable::Enabled, Enable::Disabled, Enable::Closed] { - native.close_native(); - if enable != Enable::Closed { - native.reopen(key, enable == Enable::Enabled, false); - } - let (service, memo) = native.anchors(); - let mut state = GuestState::default(); - state.anchors[Anchor::Pointer] = service; - state.anchors[Anchor::Memo] = memo; - for (step, &base) in POINTERS.iter().enumerate() { - let modifier = match modifier_register { - Some(31) => 0, - _ => 0xffff_fe10_0000_0000 ^ (step as u64) << 4 ^ tcr, - }; - let mut operands = vec![base]; - if let Some(Ok((signed, _))) = - engine.result(PointerOperation::Sign, key, base, modifier) - { - operands.extend([signed, signed ^ 1 << 50, signed ^ 1 << 62]); - } - for operand in operands { - let expected = match enable { - Enable::Closed => None, - Enable::Disabled => Some(operand), - Enable::Enabled => match engine.result( - PointerOperation::Authenticate { combined: true }, - key, - operand, - modifier, - ) { - Some(Ok((value, true))) => Some(value), - _ => None, - }, - }; - state.x = [0x7700; 31]; - match modifier_register { - None => state.sp = modifier, - Some(31) => state.sp = 0x5500, - Some(register) => state.x[register] = modifier, - } - state.x[target] = operand; - let before = state.x; - let exit = code.run(&mut state); - let what = format!( - "{word:#x} {version:?} tcr={tcr:#x} {enable:?} {operand:#x} cipher={:?}", - cells.cipher - ); - let mut after = before; - match expected { - Some(value) => { - assert_eq!(exit, (value, kind as u64), "{what}"); - if kind == ExitKind::Call { - after[30] = PC + 4; - } - checked[0] += 1; - } - None => { - assert_eq!( - exit, - (PC, ExitKind::PointerAuthentication as u64), - "{what}" - ); - checked[1] += 1; - } - } - assert_eq!(state.x, after, "{what}"); - } - } - } - } - } - } - } - assert!( - checked[0] > 1000 && checked[1] > 1000, - "{checked:?} completed and left" - ); -} - -/// The schedule native code runs gives what the engine's cipher gives. -#[test] -fn schedules_follow_the_keys_words() { - if cipher().is_none() { - return; - } - let mut service = PointerService::new(); - let inputs = super::tests::inputs(pauth::Version::Enhanced, TCRS[0]); - service.open(inputs); - let context = service.context.as_ref().unwrap(); - for (index, key) in [ - stela_contracts::pauth::Key::Ia, - stela_contracts::pauth::Key::Ib, - stela_contracts::pauth::Key::Da, - stela_contracts::pauth::Key::Db, - ] - .into_iter() - .enumerate() - { - let words = context.words(key).unwrap(); - assert_eq!(service.cipher.schedules[index][0], *words); - assert_eq!( - service.cipher.schedules[index], - pauth::keyed::schedule(words) - ); - } - // TCRS[0]: 39-bit ranges, TBI0 alone (for instructions too, without - // TBID0); FEAT_PAuth2's XOR. - let [instruction, data] = service.cipher.ranges; - assert_eq!(instruction, data); - assert_eq!( - data, - [ - pointer::cipher::Range::new(0x00ff_ff80_0000_0000, false, false), - pointer::cipher::Range::new(0xffff_ff80_0000_0000, true, false), - ] - ); - assert_eq!(data[1].authenticated, 0xff7f_ff80_0000_0000); - assert_eq!((data[1].signed, data[0].authenticated), (0, 0)); -} - -/// What a PAC operation costs natively, run by hand in a release build: an -/// IB signing (PACIB X3, X5) and its authentication, each through a thunk -/// that computes it, one that finds it in the memo (a hit on a warm memo, -/// the best case a lookup has) and one that misses the memo and calls the -/// service. Prints nanoseconds per run, with the entry around each run, -/// and host instructions per operation, single-stepped, past that entry. -#[test] -#[ignore = "manual: opt-in"] -fn native_cipher_timing() { - extern crate std; - use std::time::Instant; - const RUNS: u64 = 1 << 20; - let Some(cipher) = cipher() else { return }; - let tcr = 25 | 25 << 16 | 1 << 37; - let mut service = Box::new(PointerService::new()); - service.open(super::tests::inputs(pauth::Version::Classic, tcr)); - service.reopen(stela_contracts::pauth::Key::Ib, true, false); - let (anchor, memo) = service.anchors(); - let mut state = GuestState::default(); - state.anchors[Anchor::Pointer] = anchor; - state.anchors[Anchor::Memo] = memo; - let key = PointerAuthenticationKey::Ib; - let thunk = |kind, cipher| { - let form = pointer::Form::of(operation(kind, key)).unwrap(); - Mapped::new( - &pointer::thunk( - form, - GuestAddress(PC), - TAGS, - SERVICE as usize as u64, - cipher, - ) - .code, - ) - }; - let (computed_sign, computed_auth) = ( - thunk(Kind::Sign, Some(cipher)), - thunk(Kind::Authenticate, Some(cipher)), - ); - let memo_sign = thunk(Kind::Sign, None); - #[cfg(target_os = "linux")] - let memo_auth = thunk(Kind::Authenticate, None); - // The entry alone: a block of one ADD. - let add = 0x9100_056bu32.to_le_bytes(); - let options = stela_compiler::Options::new( - BlockProfile::new(Features::SYSTEM_MODE), - TargetCpu::detect(), - ) - .with_native_system(NativeSystem { - pointer: Some(cells(TargetCpu::detect())), - ..NativeSystem::NONE - }); - let empty = CompilationPlan::new(&add, GuestAddress(PC), &options) - .unwrap() - .compile() - .unwrap(); - let empty = Mapped::new(&empty.native.x86_64_code); - let operands = |run: u64| { - ( - 0xffff_ff80_0800_0000 + (run % 4096) * 4, - 0xffff_fe10_0000_0000 - run * 16, - ) - }; - let signed = |service: &mut PointerService, run| { - let (pointer, modifier) = operands(run); - match service.result( - PointerOperation::Sign, - stela_contracts::pauth::Key::Ib, - pointer, - modifier, - ) { - Some(Ok((signed, _))) => signed, - other => panic!("{other:?}"), - } - }; - let time = |code: &Mapped, state: &mut GuestState, operand: &dyn Fn(u64) -> (u64, u64)| { - let started = Instant::now(); - for run in 0..RUNS { - let (pointer, modifier) = operand(run); - state.x[3] = pointer; - state.x[5] = modifier; - core::hint::black_box(code.run(state)); - } - started.elapsed().as_nanos() as f64 / RUNS as f64 - }; - let fresh = |run: u64| operands(run + 7 * RUNS); - let entry = time(&empty, &mut state, &fresh); - let computed = time(&computed_sign, &mut state, &fresh); - let fills = service.fills; - let missed = time(&memo_sign, &mut state, &fresh); - let misses = service.fills - fills; - // A warm memo: one operand pair, found every time. - let same = |_| operands(1); - let _ = time(&memo_sign, &mut state, &same); - let hit = time(&memo_sign, &mut state, &same); - let pairs: Vec<(u64, u64)> = (0..4096) - .map(|run| (signed(&mut service, run), operands(run).1)) - .collect(); - let authentic = |run: u64| pairs[(run % 4096) as usize]; - let computed_authentication = time(&computed_auth, &mut state, &authentic); - std::println!( - "NATIVE ns_per_run entry={entry:.1} computed_sign={computed:.1} memo_hit_sign={hit:.1} memo_miss_sign={missed:.1} ({misses} service fills) computed_auth={computed_authentication:.1}" - ); - #[cfg(target_os = "linux")] - { - let count = |code: &Mapped, state: &mut GuestState, (pointer, modifier): (u64, u64)| { - state.x[3] = pointer; - state.x[5] = modifier; - super::tests::steps(|| { - core::hint::black_box(code.run(state)); - }) - }; - let base = count(&empty, &mut state, operands(1)); - let computed = count(&computed_sign, &mut state, operands(3 * RUNS)) - base; - let missed = count(&memo_sign, &mut state, operands(3 * RUNS + 1)) - base; - let hit = count(&memo_sign, &mut state, operands(1)) - base; - let computed_authentication = count(&computed_auth, &mut state, pairs[5]) - base; - let hit_authentication = count(&memo_auth, &mut state, pairs[4095]) - base; - std::println!( - "NATIVE instructions_past_entry computed_sign={computed} memo_hit_sign={hit} memo_miss_sign={missed} computed_auth={computed_authentication} memo_hit_auth={hit_authentication} (an ADD block's run: {base})" - ); - } -} +//! Native code given the service's cipher computes exactly what the +//! engine's exit computes ([`PointerService::result`] with the reference +//! cipher of the same keys), for every key, form and PAC version, under +//! TCRs with and without TBI and TBID, for EL0, EL1 and EL2 address +//! layouts, both key enables and a closed key: thunks and blocks complete +//! signings, successful authentications and PACGA without the service, and +//! leave the rest to it, which completes or refuses them as before. + +use super::*; +use alloc::format; +use stela_compiler::{ + GuestAddress, GuestState, TargetCpu, + block::{ + BlockProfile, CompilationPlan, ExitKind, Features, + PointerAuthenticationModifier as Modifier, PointerAuthenticationOperation as Operation, + }, + x86_64::{NativeSystem, block_entry, pinned, pointer::inline::Cells}, +}; + +/// Executable copies of native code, unmapped on drop. +struct Mapped { + page: *mut core::ffi::c_void, + bytes: usize, +} + +unsafe extern "C" { + fn mmap( + address: *mut core::ffi::c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut core::ffi::c_void; + fn mprotect(address: *mut core::ffi::c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut core::ffi::c_void, bytes: usize) -> i32; +} + +#[cfg(target_os = "macos")] +const MAP_ANONYMOUS: i32 = 0x1000; +#[cfg(target_os = "linux")] +const MAP_ANONYMOUS: i32 = 0x20; + +impl Mapped { + /// `body` entered as the engine enters native code + /// (`pinned::entered`). + fn new(body: &[u8]) -> Self { + let code = pinned::entered(body); + let bytes = code.len().next_multiple_of(4096); + // SAFETY: private anonymous memory, RX after the copy. + unsafe { + let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + assert_eq!(mprotect(page, bytes, 5), 0); + Self { page, bytes } + } + } + + /// Run it on `state`: the exit's PC and kind. + fn run(&self, state: &mut GuestState) -> (u64, u64) { + // SAFETY: the code is the block ABI's; it touches only `state`, what + // its anchors name (the service, its memo), and the stack, and calls + // the service. + let exit = unsafe { block_entry::enter(self.page.cast(), state, 0, 0) }; + (exit as u64, (exit >> 64) as u64) + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: mapped by `new`, no longer running. + unsafe { assert_eq!(munmap(self.page, self.bytes), 0) }; + } +} + +/// The cipher's place, or `None` on a host without AES-NI, whose tests +/// then have nothing to compare. +fn cipher() -> Option { + let place = native_cipher(TargetCpu::detect()); + if place.is_none() { + extern crate std; + std::eprintln!("no AES-NI: the native cipher is not used on this host"); + } + place +} + +/// TCRs of the regimes the engine runs: EL1&0 with 39- and 47-bit ranges, +/// TBI0 alone (macOS EL0 data), TBI0 with TBID0, both TBIs, neither (a +/// signing then selects by bit 63), and TBI1 with TBID1, as an EL2 host +/// regime may. +const TCRS: [u64; 6] = [ + 25 | 25 << 16 | 1 << 37, + 17 | 25 << 16 | 1 << 37 | 1 << 51, + 17 | 17 << 16 | 1 << 37 | 1 << 38, + 25 | 25 << 16, + 16 | 39 << 16 | 1 << 38 | 1 << 52, + 39 | 16 << 16 | 1 << 38, +]; + +const VERSIONS: [pauth::Version; 4] = [ + pauth::Version::Classic, + pauth::Version::Enhanced, + pauth::Version::Faulting, + pauth::Version::FaultingCombined, +]; + +/// Pointers of EL0 and of the kernel, tagged, all ones, zero and garbage, +/// before signing. +const POINTERS: [u64; 8] = [ + 0x0000_0001_0000_8000, + 0x0000_7fff_ffff_f000, + 0xffff_fe00_1234_5678, + 0xffff_ff80_0012_3450, + 0x5a00_0001_0000_8000, + u64::MAX, + 0, + 0x1234_5678_9abc_def0, +]; + +const KEYS: [PointerAuthenticationKey; 4] = [ + PointerAuthenticationKey::Ia, + PointerAuthenticationKey::Ib, + PointerAuthenticationKey::Da, + PointerAuthenticationKey::Db, +]; + +/// A thunk's form: a signing into X3, a plain authentication of X3, a +/// branch authentication of X3 (the combined form), each with X5 as the +/// modifier, or PACGA of X3 and X5 into X4. +#[derive(Clone, Copy, Debug)] +enum Kind { + Sign, + Authenticate, + Branch, + Generic, +} + +fn operation(kind: Kind, key: PointerAuthenticationKey) -> Operation { + let modifier = Modifier::Register(5); + match kind { + Kind::Sign => Operation::Sign { + key, + destination: 3, + modifier, + }, + Kind::Authenticate => Operation::Authenticate { + key, + destination: 3, + modifier, + }, + Kind::Branch => Operation::Branch { + key, + target: 3, + modifier, + link: false, + }, + Kind::Generic => Operation::GenericCode(stela_compiler::block::pauth_memory::GenericCode { + destination: 4, + source: 3, + modifier: 5, + }), + } +} + +/// A key's enable: open and enabled, disabled, or its tag word closed. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Enable { + Enabled, + Disabled, + Closed, +} + +const PC: u64 = 0x4000; + +/// Thunks compute what the engine computes: signings, successful +/// authentications and PACGA without a service call, failures and +/// non-canonical signings through it, as before. +#[test] +fn thunks_compute_what_the_engine_computes() { + let Some(cipher) = cipher() else { return }; + let mut thunks = Vec::new(); + for kind in [Kind::Sign, Kind::Authenticate, Kind::Branch] { + for key in KEYS { + let form = pointer::Form::of(operation(kind, key)).expect("a thunk form"); + let thunk = pointer::thunk( + form, + GuestAddress(PC), + TAGS, + SERVICE as usize as u64, + Some(cipher), + ); + thunks.push((kind, Some(key), Mapped::new(&thunk.code))); + } + } + let generic = + pointer::Form::of(operation(Kind::Generic, PointerAuthenticationKey::Ia)).unwrap(); + let thunk = pointer::thunk( + generic, + GuestAddress(PC), + TAGS, + SERVICE as usize as u64, + Some(cipher), + ); + thunks.push((Kind::Generic, None, Mapped::new(&thunk.code))); + let (mut computed, mut serviced) = (0u64, 0u64); + for tcr in TCRS { + for version in VERSIONS { + let inputs = super::tests::inputs(version, tcr); + let mut native = Box::new(PointerService::new()); + let mut engine = PointerService::new(); + native.open(inputs); + engine.open(inputs); + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = native.anchors().0; + for (kind, key, code) in &thunks { + for enable in [Enable::Enabled, Enable::Disabled, Enable::Closed] { + if key.is_none() && enable == Enable::Disabled { + continue; + } + native.close_native(); + match (key, enable) { + (_, Enable::Closed) => {} + (Some(key), enable) => { + native.reopen(key_of(*key), enable == Enable::Enabled, false) + } + (None, _) => native.reopen_generic(false), + } + // The memo a usable tag word allocates. + state.anchors[Anchor::Memo] = native.anchors().1; + for (step, &base) in POINTERS.iter().enumerate() { + let modifier = 0xffff_fe10_0000_0000 ^ (step as u64) << 4 ^ tcr; + let mut operands = vec![base]; + if let Some(key) = key { + let signed = + engine.result(PointerOperation::Sign, key_of(*key), base, modifier); + if let Some(Ok((signed, _))) = signed { + operands.extend([signed, signed ^ 1 << 50, signed ^ 1 << 62]); + } + } + for operand in operands { + let expected = + expect(&mut engine, *kind, *key, enable, operand, modifier); + state.x[3] = operand; + state.x[4] = 0x4444; + state.x[5] = modifier; + let fills = native.fills; + let exit = code.run(&mut state); + let what = format!( + "{version:?} tcr={tcr:#x} {kind:?} {key:?} {enable:?} {operand:#x}" + ); + let destination = if matches!(kind, Kind::Generic) { 4 } else { 3 }; + match (expected, kind) { + (Some(value), Kind::Branch) => { + assert_eq!(exit, (value, ExitKind::Indirect as u64), "{what}"); + } + (Some(value), _) => { + assert_eq!( + exit, + (PC + 4, ExitKind::Fallthrough as u64), + "{what}" + ); + assert_eq!(state.x[destination], value, "{what}"); + } + (None, _) => { + assert_eq!( + exit, + (PC, ExitKind::PointerAuthentication as u64), + "{what}" + ); + assert_eq!(state.x[3], operand, "{what}"); + } + } + // Completions the cipher gives never reach + // the service. + let canonical = enable == Enable::Disabled + || native_completes(&native, *kind, *key, operand); + if expected.is_some() && canonical { + assert_eq!(native.fills, fills, "{what}: a service call"); + computed += 1; + } else if native.fills != fills { + serviced += 1; + } + } + } + } + } + } + } + // Both paths ran: the corrupted signings and the authentications of + // unsigned pointers among the operands fail, through the service. + assert!( + computed > 10_000 && serviced > 0, + "{computed} computed, {serviced} serviced" + ); +} + +/// Native transitions switch the tag words between two exception levels +/// of one memo generation whose enables differ (`transition::check_pointer` +/// copies the tag words the engine reopened for each), without the service. +/// Thunks and blocks compiled once then give, at each level, what the engine +/// gives there: the pointer unchanged where the key is disabled, its +/// signing or authentication where it is enabled, in any order of switches. +/// Before, a disabled key's zero layouts stayed after a switch to the level +/// where it is enabled, and an enabled key's layouts after a switch back, so +/// a process whose keys are disabled at EL0 got signed pointers. +#[test] +fn tag_words_switched_natively_keep_each_levels_enables() { + use stela_contracts::pauth::Key; + let Some(cipher) = cipher() else { return }; + let mut thunks = Vec::new(); + for kind in [Kind::Sign, Kind::Authenticate, Kind::Branch] { + for key in KEYS { + let form = pointer::Form::of(operation(kind, key)).unwrap(); + let thunk = pointer::thunk( + form, + GuestAddress(PC), + TAGS, + SERVICE as usize as u64, + Some(cipher), + ); + thunks.push((kind, key, Mapped::new(&thunk.code))); + } + } + for tcr in TCRS { + for version in VERSIONS { + let inputs = super::tests::inputs(version, tcr); + let mut native = Box::new(PointerService::new()); + let mut engine = PointerService::new(); + native.open(inputs); + engine.open(inputs); + // The kernel's level: every key enabled. The process's: IA and + // DA disabled (a process without arm64e's JOP keys), IB and DB + // enabled; then the reverse. + let level = |native: &mut PointerService, disabled: [bool; 4]| { + native.close_native(); + for (key, disabled) in [Key::Ia, Key::Ib, Key::Da, Key::Db] + .into_iter() + .zip(disabled) + { + native.reopen(key, !disabled, false); + } + native.tags + }; + let kernel = level(&mut native, [false; 4]); + let process = level(&mut native, [true, false, true, false]); + let other = level(&mut native, [false, true, false, true]); + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = native.anchors().0; + state.anchors[Anchor::Memo] = native.anchors().1; + for (round, tags) in [kernel, process, kernel, other, process, other, kernel] + .into_iter() + .enumerate() + { + // As a native transition writes them. + native.tags = tags; + for (kind, key, code) in &thunks { + let index = usize::from(pointer::key_index(*key)); + let enable = if tags[index] == pointer::DISABLED { + Enable::Disabled + } else { + Enable::Enabled + }; + let pointer = POINTERS[round % 4]; + let modifier = 0x0000_0001_6fd0_0000 + round as u64 * 0x40; + let signed = match engine.result( + PointerOperation::Sign, + key_of(*key), + pointer, + modifier, + ) { + Some(Ok((signed, _))) => signed, + other => panic!("{other:?}"), + }; + let operand = if matches!(kind, Kind::Sign) { + pointer + } else { + signed + }; + let expected = + expect(&mut engine, *kind, Some(*key), enable, operand, modifier); + state.x[3] = operand; + state.x[5] = modifier; + let exit = code.run(&mut state); + let what = format!( + "{version:?} tcr={tcr:#x} round {round} {kind:?} {key:?} {enable:?}" + ); + match (expected, kind) { + (Some(value), Kind::Branch) => { + assert_eq!(exit, (value, ExitKind::Indirect as u64), "{what}") + } + (Some(value), _) => { + assert_eq!(exit, (PC + 4, ExitKind::Fallthrough as u64), "{what}"); + assert_eq!(state.x[3], value, "{what}"); + } + // A pointer outside the regime's range fails its + // authentication, at either level. + (None, _) => { + assert_eq!(exit, (PC, ExitKind::PointerAuthentication as u64), "{what}") + } + } + } + } + } + } +} + +/// What the engine's exit gives for `kind` on `operand`: the completed +/// value, or `None` for what the native code leaves to the engine. +fn expect( + engine: &mut PointerService, + kind: Kind, + key: Option, + enable: Enable, + operand: u64, + modifier: u64, +) -> Option { + match (enable, key) { + (Enable::Closed, _) => None, + (Enable::Disabled, _) => Some(operand), + (Enable::Enabled, None) => engine.generic_code(operand, modifier), + (Enable::Enabled, Some(key)) => { + let operation = match kind { + Kind::Sign => PointerOperation::Sign, + Kind::Authenticate => PointerOperation::Authenticate { combined: false }, + _ => PointerOperation::Authenticate { combined: true }, + }; + match engine.result(operation, key_of(key), operand, modifier) { + Some(Ok((value, true))) => Some(value), + _ => None, + } + } + } +} + +/// Whether the cipher alone answers `kind` on `operand`: PACGA, any +/// authentication, and a signing whose pointer is canonical in its layout. +fn native_completes( + service: &PointerService, + kind: Kind, + key: Option, + operand: u64, +) -> bool { + let (Kind::Sign, Some(key)) = (kind, key) else { + return true; + }; + let data = matches!( + key, + PointerAuthenticationKey::Da | PointerAuthenticationKey::Db + ); + let range = service.cipher.ranges[usize::from(data)][usize::from(operand & 1 << 55 != 0)]; + operand & range.extension == range.canonical +} + +/// Blocks given the cipher complete PAC instructions in line with the +/// engine's results and leave at the first one the engine does not +/// complete, its result unwritten. +#[test] +fn blocks_compute_what_the_engine_computes() { + use stela_contracts::pauth::Key; + let Some(cipher) = cipher() else { return }; + // PACIA X0, X1; AUTDB X2, X3; PACGA X4, X5, X6; PACDB X7, X8; + // AUTIB X9, X10; ADD X11, X11, #1. + const WORDS: [u32; 6] = [ + 0xdac1_0020, + 0xdac1_1c62, + 0x9ac6_30a4, + 0xdac1_0d07, + 0xdac1_1549, + 0x9100_056b, + ]; + let source: Vec = WORDS.iter().flat_map(|word| word.to_le_bytes()).collect(); + let options = stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::detect(), + ) + .with_native_system(NativeSystem { + pointer: Some(cells(TargetCpu::detect())), + ..NativeSystem::NONE + }); + assert_eq!( + cells(TargetCpu::detect()).cipher, + Some(cipher.offset as u32) + ); + let block = CompilationPlan::new(&source, GuestAddress(PC), &options) + .unwrap() + .compile() + .unwrap(); + assert_eq!(block.source_bytes, source.len()); + let code = Mapped::new(&block.native.x86_64_code); + for tcr in TCRS { + for version in VERSIONS { + let inputs = super::tests::inputs(version, tcr); + let mut native = Box::new(PointerService::new()); + let mut engine = PointerService::new(); + native.open(inputs); + engine.open(inputs); + for key in [Key::Ia, Key::Ib, Key::Da, Key::Db] { + native.reopen(key, true, false); + } + native.reopen_generic(false); + let (service, memo) = native.anchors(); + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = service; + state.anchors[Anchor::Memo] = memo; + for (step, &pointer) in POINTERS.iter().enumerate() { + let modifier = 0x0000_0001_6fd0_0000 + step as u64 * 0x30; + let signed = |engine: &mut PointerService, key| match engine.result( + PointerOperation::Sign, + key, + pointer, + modifier, + ) { + Some(Ok((signed, _))) => signed, + other => panic!("{other:?}"), + }; + let db = signed(&mut engine, Key::Db); + let ib = signed(&mut engine, Key::Ib); + // A corrupted IB signing every other step. + let ib = if step % 2 == 1 { ib ^ 1 << 52 } else { ib }; + let mut x = [0u64; 12]; + x[1] = modifier; + x[0] = pointer; + x[2] = db; + x[3] = modifier; + (x[4], x[5], x[6]) = (pointer, pointer ^ modifier, modifier); + (x[7], x[8]) = (pointer, modifier + 8); + (x[9], x[10]) = (ib, modifier); + state.x[..12].copy_from_slice(&x); + // The engine's results, in order, up to the first it does + // not complete. + let mut expected = x; + let mut stop = None; + let steps: [(usize, Option, PointerOperation, usize, usize); 5] = [ + (0, Some(Key::Ia), PointerOperation::Sign, 0, 1), + ( + 1, + Some(Key::Db), + PointerOperation::Authenticate { combined: false }, + 2, + 3, + ), + (2, None, PointerOperation::Sign, 4, 5), + (3, Some(Key::Db), PointerOperation::Sign, 7, 8), + ( + 4, + Some(Key::Ib), + PointerOperation::Authenticate { combined: false }, + 9, + 10, + ), + ]; + for (at, key, operation, target, from) in steps { + let result = match key { + Some(key) => { + match engine.result(operation, key, expected[target], expected[from]) { + Some(Ok((value, true))) => Some(value), + _ => None, + } + } + None => engine.generic_code(expected[from], expected[6]), + }; + match result { + Some(value) => { + let destination = if key.is_none() { 4 } else { target }; + expected[destination] = value; + } + None => { + stop = Some(at); + break; + } + } + } + let exit = code.run(&mut state); + let what = format!("{version:?} tcr={tcr:#x} {pointer:#x}"); + match stop { + Some(at) => assert_eq!( + exit, + (PC + 4 * at as u64, ExitKind::PointerAuthentication as u64), + "{what}" + ), + None => { + expected[11] += 1; + assert_eq!(exit.0, PC + 4 * WORDS.len() as u64, "{what}"); + } + } + assert_eq!(state.x[..12], expected, "{what}"); + } + } + } +} + +/// A block ending with RETA*, BRA* or BLRA* authenticates the target in +/// line and branches to it as RET, BR and BLR do, linking X30 for BLRA*, +/// with what the engine's exit gives: every instruction key, the register, +/// zero and SP modifiers, signed, corrupted and unsigned targets, enabled, +/// disabled and closed keys, every PAC version and regime, through the +/// cipher and through the memo. What the engine does not complete leaves at +/// the instruction with its PAC exit, X30 unchanged. +#[test] +fn blocks_complete_branch_forms_as_the_engine_does() { + use stela_compiler::x86_64::chain; + use stela_contracts::pauth::Key; + // (word, key, target register, modifier register: None for SP, exit). + let forms: [(u32, Key, usize, Option, ExitKind); 10] = [ + (0xd65f_0bff, Key::Ia, 30, None, ExitKind::Return), // retaa + (0xd65f_0fff, Key::Ib, 30, None, ExitKind::Return), // retab + (0xd71f_0865, Key::Ia, 3, Some(5), ExitKind::Indirect), // braa x3, x5 + (0xd71f_0c65, Key::Ib, 3, Some(5), ExitKind::Indirect), // brab x3, x5 + (0xd73f_0865, Key::Ia, 3, Some(5), ExitKind::Call), // blraa x3, x5 + (0xd73f_0c65, Key::Ib, 3, Some(5), ExitKind::Call), // blrab x3, x5 + (0xd61f_087f, Key::Ia, 3, Some(31), ExitKind::Indirect), // braaz x3 + (0xd63f_0c7f, Key::Ib, 3, Some(31), ExitKind::Call), // blrabz x3 + (0xd73f_0bc5, Key::Ia, 30, Some(5), ExitKind::Call), // blraa x30, x5 + (0xd73f_087e, Key::Ia, 3, Some(30), ExitKind::Call), // blraa x3, x30 + ]; + let host = cells(TargetCpu::detect()); + // Through the cipher where the host has it, and through the memo. + let paths: Vec<_> = [ + host.cipher.map(|_| host), + Some(Cells { + cipher: None, + ..host + }), + ] + .into_iter() + .flatten() + .collect(); + let mut checked = [0usize; 2]; + for cells in paths { + for (word, key, target, modifier_register, kind) in forms { + let options = stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::detect(), + ) + .with_native_system(NativeSystem { + pointer: Some(cells), + ..NativeSystem::NONE + }); + let block = CompilationPlan::new(&word.to_le_bytes(), GuestAddress(PC), &options) + .unwrap() + .compile() + .unwrap(); + let code = &block.native.x86_64_code; + // The engine finds the exit to the target where RET and BR put + // theirs (a linked BLR's ends with its continuation). + let ending = chain::without_failures(code); + let ending = &ending[ending.len() - chain::DYNAMIC_EXIT_BYTES..]; + assert!( + kind == ExitKind::Call || chain::is_dynamic_exit(ending, kind), + "{word:#x}" + ); + let code = Mapped::new(code); + for tcr in TCRS { + for version in VERSIONS { + let inputs = super::tests::inputs(version, tcr); + let mut native = Box::new(PointerService::new()); + let mut engine = PointerService::new(); + native.open(inputs); + engine.open(inputs); + for enable in [Enable::Enabled, Enable::Disabled, Enable::Closed] { + native.close_native(); + if enable != Enable::Closed { + native.reopen(key, enable == Enable::Enabled, false); + } + let (service, memo) = native.anchors(); + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = service; + state.anchors[Anchor::Memo] = memo; + for (step, &base) in POINTERS.iter().enumerate() { + let modifier = match modifier_register { + Some(31) => 0, + _ => 0xffff_fe10_0000_0000 ^ (step as u64) << 4 ^ tcr, + }; + let mut operands = vec![base]; + if let Some(Ok((signed, _))) = + engine.result(PointerOperation::Sign, key, base, modifier) + { + operands.extend([signed, signed ^ 1 << 50, signed ^ 1 << 62]); + } + for operand in operands { + let expected = match enable { + Enable::Closed => None, + Enable::Disabled => Some(operand), + Enable::Enabled => match engine.result( + PointerOperation::Authenticate { combined: true }, + key, + operand, + modifier, + ) { + Some(Ok((value, true))) => Some(value), + _ => None, + }, + }; + state.x = [0x7700; 31]; + match modifier_register { + None => state.sp = modifier, + Some(31) => state.sp = 0x5500, + Some(register) => state.x[register] = modifier, + } + state.x[target] = operand; + let before = state.x; + let exit = code.run(&mut state); + let what = format!( + "{word:#x} {version:?} tcr={tcr:#x} {enable:?} {operand:#x} cipher={:?}", + cells.cipher + ); + let mut after = before; + match expected { + Some(value) => { + assert_eq!(exit, (value, kind as u64), "{what}"); + if kind == ExitKind::Call { + after[30] = PC + 4; + } + checked[0] += 1; + } + None => { + assert_eq!( + exit, + (PC, ExitKind::PointerAuthentication as u64), + "{what}" + ); + checked[1] += 1; + } + } + assert_eq!(state.x, after, "{what}"); + } + } + } + } + } + } + } + assert!( + checked[0] > 1000 && checked[1] > 1000, + "{checked:?} completed and left" + ); +} + +/// The schedule native code runs gives what the engine's cipher gives. +#[test] +fn schedules_follow_the_keys_words() { + if cipher().is_none() { + return; + } + let mut service = PointerService::new(); + let inputs = super::tests::inputs(pauth::Version::Enhanced, TCRS[0]); + service.open(inputs); + let context = service.context.as_ref().unwrap(); + for (index, key) in [ + stela_contracts::pauth::Key::Ia, + stela_contracts::pauth::Key::Ib, + stela_contracts::pauth::Key::Da, + stela_contracts::pauth::Key::Db, + ] + .into_iter() + .enumerate() + { + let words = context.words(key).unwrap(); + assert_eq!(service.cipher.schedules[index][0], *words); + assert_eq!( + service.cipher.schedules[index], + pauth::keyed::schedule(words) + ); + } + // TCRS[0]: 39-bit ranges, TBI0 alone (for instructions too, without + // TBID0); FEAT_PAuth2's XOR. + let [instruction, data] = service.cipher.ranges; + assert_eq!(instruction, data); + assert_eq!( + data, + [ + pointer::cipher::Range::new(0x00ff_ff80_0000_0000, false, false, false), + pointer::cipher::Range::new(0xffff_ff80_0000_0000, true, false, false), + ] + ); + assert_eq!(data[1].authenticated, 0xff7f_ff80_0000_0000); + assert_eq!((data[1].signed, data[0].authenticated), (0, 0)); +} + +/// What a PAC operation costs natively, run by hand in a release build: an +/// IB signing (PACIB X3, X5) and its authentication, each through a thunk +/// that computes it, one that finds it in the memo (a hit on a warm memo, +/// the best case a lookup has) and one that misses the memo and calls the +/// service. Prints nanoseconds per run, with the entry around each run, +/// and host instructions per operation, single-stepped, past that entry. +#[test] +#[ignore = "manual: opt-in"] +fn native_cipher_timing() { + extern crate std; + use std::time::Instant; + const RUNS: u64 = 1 << 20; + let Some(cipher) = cipher() else { return }; + let tcr = 25 | 25 << 16 | 1 << 37; + let mut service = Box::new(PointerService::new()); + service.open(super::tests::inputs(pauth::Version::Classic, tcr)); + service.reopen(stela_contracts::pauth::Key::Ib, true, false); + let (anchor, memo) = service.anchors(); + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = anchor; + state.anchors[Anchor::Memo] = memo; + let key = PointerAuthenticationKey::Ib; + let thunk = |kind, cipher| { + let form = pointer::Form::of(operation(kind, key)).unwrap(); + Mapped::new( + &pointer::thunk( + form, + GuestAddress(PC), + TAGS, + SERVICE as usize as u64, + cipher, + ) + .code, + ) + }; + let (computed_sign, computed_auth) = ( + thunk(Kind::Sign, Some(cipher)), + thunk(Kind::Authenticate, Some(cipher)), + ); + let memo_sign = thunk(Kind::Sign, None); + #[cfg(target_os = "linux")] + let memo_auth = thunk(Kind::Authenticate, None); + // The entry alone: a block of one ADD. + let add = 0x9100_056bu32.to_le_bytes(); + let options = stela_compiler::Options::new( + BlockProfile::new(Features::SYSTEM_MODE), + TargetCpu::detect(), + ) + .with_native_system(NativeSystem { + pointer: Some(cells(TargetCpu::detect())), + ..NativeSystem::NONE + }); + let empty = CompilationPlan::new(&add, GuestAddress(PC), &options) + .unwrap() + .compile() + .unwrap(); + let empty = Mapped::new(&empty.native.x86_64_code); + let operands = |run: u64| { + ( + 0xffff_ff80_0800_0000 + (run % 4096) * 4, + 0xffff_fe10_0000_0000 - run * 16, + ) + }; + let signed = |service: &mut PointerService, run| { + let (pointer, modifier) = operands(run); + match service.result( + PointerOperation::Sign, + stela_contracts::pauth::Key::Ib, + pointer, + modifier, + ) { + Some(Ok((signed, _))) => signed, + other => panic!("{other:?}"), + } + }; + let time = |code: &Mapped, state: &mut GuestState, operand: &dyn Fn(u64) -> (u64, u64)| { + let started = Instant::now(); + for run in 0..RUNS { + let (pointer, modifier) = operand(run); + state.x[3] = pointer; + state.x[5] = modifier; + core::hint::black_box(code.run(state)); + } + started.elapsed().as_nanos() as f64 / RUNS as f64 + }; + let fresh = |run: u64| operands(run + 7 * RUNS); + let entry = time(&empty, &mut state, &fresh); + let computed = time(&computed_sign, &mut state, &fresh); + let fills = service.fills; + let missed = time(&memo_sign, &mut state, &fresh); + let misses = service.fills - fills; + // A warm memo: one operand pair, found every time. + let same = |_| operands(1); + let _ = time(&memo_sign, &mut state, &same); + let hit = time(&memo_sign, &mut state, &same); + let pairs: Vec<(u64, u64)> = (0..4096) + .map(|run| (signed(&mut service, run), operands(run).1)) + .collect(); + let authentic = |run: u64| pairs[(run % 4096) as usize]; + let computed_authentication = time(&computed_auth, &mut state, &authentic); + std::println!( + "NATIVE ns_per_run entry={entry:.1} computed_sign={computed:.1} memo_hit_sign={hit:.1} memo_miss_sign={missed:.1} ({misses} service fills) computed_auth={computed_authentication:.1}" + ); + #[cfg(target_os = "linux")] + { + let count = |code: &Mapped, state: &mut GuestState, (pointer, modifier): (u64, u64)| { + state.x[3] = pointer; + state.x[5] = modifier; + super::tests::steps(|| { + core::hint::black_box(code.run(state)); + }) + }; + let base = count(&empty, &mut state, operands(1)); + let computed = count(&computed_sign, &mut state, operands(3 * RUNS)) - base; + let missed = count(&memo_sign, &mut state, operands(3 * RUNS + 1)) - base; + let hit = count(&memo_sign, &mut state, operands(1)) - base; + let computed_authentication = count(&computed_auth, &mut state, pairs[5]) - base; + let hit_authentication = count(&memo_auth, &mut state, pairs[4095]) - base; + std::println!( + "NATIVE instructions_past_entry computed_sign={computed} memo_hit_sign={hit} memo_miss_sign={missed} computed_auth={computed_authentication} memo_hit_auth={hit_authentication} (an ADD block's run: {base})" + ); + } +} + +/// Opt 4: differential test of 10,000 random canonical and non-canonical +/// pointers across all 4 PAC versions and multiple TCR TBI/TBID configs +/// against `pauth::Context::sign`. +#[test] +fn non_canonical_signing_differential_matches_pauth_context() { + let Some(cipher) = cipher() else { return }; + let keys = [ + PointerAuthenticationKey::Ia, + PointerAuthenticationKey::Ib, + PointerAuthenticationKey::Da, + PointerAuthenticationKey::Db, + ]; + let thunks: alloc::vec::Vec<_> = keys + .iter() + .map(|&key| { + let form = pointer::Form::of(operation(Kind::Sign, key)).unwrap(); + Mapped::new( + &pointer::thunk( + form, + GuestAddress(PC), + TAGS, + SERVICE as usize as u64, + Some(cipher), + ) + .code, + ) + }) + .collect(); + + let mut services = alloc::vec::Vec::new(); + for &version in &VERSIONS { + for &tcr in &TCRS { + let mut service = Box::new(PointerService::new()); + service.open(super::tests::inputs(version, tcr)); + for &key in &keys { + service.reopen(key_of(key), true, false); + } + services.push((version, tcr, service)); + } + } + + let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next_u64 = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + + const SAMPLES: usize = 10_000; + for sample in 0..SAMPLES { + let svc_idx = sample % services.len(); + let key_idx = (sample / services.len()) % keys.len(); + let (version, tcr, ref mut service) = services[svc_idx]; + let key = keys[key_idx]; + let pauth_key = key_of(key); + let (anchor, memo) = service.anchors(); + + let raw = next_u64(); + let pointer = match sample % 4 { + 0 => raw & 0x0000_7fff_ffff_ffff, + 1 => raw | 0xffff_ff80_0000_0000, + 2 => (raw & !(1u64 << 55)) | ((sample as u64 & 4) << 53), + _ => raw, + }; + let modifier = next_u64(); + + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = anchor; + state.anchors[Anchor::Memo] = memo; + state.x[3] = pointer; + state.x[5] = modifier; + let exit = thunks[key_idx].run(&mut state); + assert_eq!(exit, (PC + 4, ExitKind::Fallthrough as u64)); + + let expected = service + .context + .as_ref() + .unwrap() + .sign(pauth_key, pointer, modifier) + .unwrap(); + assert_eq!( + state.x[3], expected, + "sample={sample} version={version:?} tcr={tcr:#x} key={key:?} ptr={pointer:#x}" + ); + } +} diff --git a/crates/stela-engine/src/machine/engine/pointer_authentication.rs b/crates/stela-engine/src/machine/engine/pointer_authentication.rs index 0fa58930b7..21ce0b80cf 100644 --- a/crates/stela-engine/src/machine/engine/pointer_authentication.rs +++ b/crates/stela-engine/src/machine/engine/pointer_authentication.rs @@ -1,831 +1,862 @@ -//! Pointer authentication with the guest's own keys, completed by the engine. - -use super::*; - -/// The APCTL bit that keeps the keys on above EL0 whatever SCTLR says. SPTM -/// 26A434 sets it at boot (`__text+0xb790`), and its context switch for a -/// process without JOP keys then clears SCTLR's enables (`__text+0x4a264`) -/// with signed returns of its own and the kernel's still to come, so those -/// enables can govern only EL0. SPTM clears the bit on entry, setting all -/// four enables instead (`__text+0x20e0`). -const APCTL_KERNEL_KEYS: u64 = 1 << 4; - -pub(super) const fn key_enable_bit(key: PointerAuthenticationKey) -> u64 { - 1 << match key { - PointerAuthenticationKey::Ia => 31, - PointerAuthenticationKey::Ib => 30, - PointerAuthenticationKey::Da => 27, - PointerAuthenticationKey::Db => 13, - } -} - -impl Machine { - /// SCTLR key enables for the current regime, overridden above EL0 by - /// APCTL. A single snapshot can reopen all four address keys. - pub(super) fn pointer_key_enables(&self) -> u64 { - let control = match self.cpu.pstate.el { - 1 => self.cpu.apple.apctl[0], - 2 => self.cpu.apple.apctl[1], - _ => 0, - }; - if control & APCTL_KERNEL_KEYS != 0 { - u64::MAX - } else { - self.cpu.regime_sctlr() - } - } - - pub(super) fn key_enabled(&self, key: PointerAuthenticationKey) -> bool { - self.pointer_key_enables() & key_enable_bit(key) != 0 - } - - /// The PAC keys as (low, high) words in APIA, APIB, APDA, APDB, APGA order. - pub(super) fn pointer_keys(&self) -> [Option<[u64; 2]>; 5] { - // The original T6000 LLB initializes C13/C14 keys and consumes them - // at EL2. They are not aliases of the architectural lower bank. EL0 - // in the host shares them, as the architectural keys serve every EL: - // 26A434 XNU at EL2 loads each thread's B keys there on a context - // switch (0xfffffe000bb9bd14) for its EL0 to use. - if self.cpu.pstate.el == 2 || self.cpu.pstate.el == 0 && self.cpu.in_host() { - return self.cpu.apple.pointer_keys.pairs(); - } - use SystemRegister as R; - let pair = |low, high| Some([self.cpu.read(low), self.cpu.read(high)]); - [ - pair(R::APIAKeyLo_EL1, R::APIAKeyHi_EL1), - pair(R::APIBKeyLo_EL1, R::APIBKeyHi_EL1), - pair(R::APDAKeyLo_EL1, R::APDAKeyHi_EL1), - pair(R::APDBKeyLo_EL1, R::APDBKeyHi_EL1), - pair(R::APGAKeyLo_EL1, R::APGAKeyHi_EL1), - ] - } - - /// The PAC algorithm version of the PE: FEAT_FPACCOMBINE, FEAT_FPAC, - /// FEAT_PAuth2 or the classic FEAT_PAuth insertion and error code (the - /// M1). A feature the PE has and the engine does not implement yet stops. - pub(super) fn pointer_version(&self) -> Result { - let has = |feature| { - self.cpu - .registers - .implemented(feature) - .map_err(|error| self.unsupported(RequirementKind::Native(error.reason()))) - }; - Ok(if has(Feature::FEAT_FPACCOMBINE)? { - pauth::Version::FaultingCombined - } else if has(Feature::FEAT_FPAC)? { - pauth::Version::Faulting - } else if has(Feature::FEAT_PAuth2)? { - pauth::Version::Enhanced - } else { - pauth::Version::Classic - }) - } - - /// The guest's PAC keys and the current regime's TCR layout, with the - /// chip's PAC version. - pub(super) fn pointer_context(&self) -> Result { - let [ia, ib, da, db, generic] = self.pointer_keys(); - let mut keys = pauth::Keys::from_optional_words([ia, ib, da, db]); - if let Some(generic) = generic { - keys = keys.with_generic_words(generic); - } - Ok( - pauth::Context::new_with_version(0, keys, self.pointer_version()?) - .with_translation_regime(self.cpu.regime_tcr()) - .with_implementation_defined_cipher(), - ) - } - - /// Whether HCR_EL2.API clear traps the use of an enabled key, or PACGA, - /// to EL2: from EL1, and from EL0 outside the host (Arm - /// `IsAPIAKeyEnabled` and the other key checks, `AddPACGA`). - pub(super) fn pointer_authentication_trapped(&self) -> bool { - let el = self.cpu.pstate.el; - (el == 1 || (el == 0 && !self.cpu.in_host())) && !self.cpu.hcr(HCR_API) - } - - /// Arm `TrapPACUse(EL2)`: EC 0x09 with ISS 0 at the instruction. - pub(super) fn pointer_authentication_trap(&mut self) -> Step { - let pc = self.cpu.pc; - self.take(Exception::synchronous(Class::PointerAuthenticationTrap, 0, pc).to(2)); - Ok(()) - } - - /// Complete one PAC instruction with the guest's own keys, laid out for - /// the current TCR. The algorithm is the software QARMA5 service as - /// FEAT_PAuth2 with FEAT_FPAC; Apple's hardware algorithm and AppleMode - /// diversification are not reproduced, so values are self-consistent - /// rather than equal to hardware's. A failed standalone AUT* takes the - /// PAC Fail exception (EC 0x1C) to the current EL, or from EL0 to EL1 or - /// the host's EL2 (Arm `AArch64_PACFailException`). - pub(super) fn pointer_authentication(&mut self, word: u32) -> Step { - if let Some(step) = self.implicit_pointer_authentication(word) { - return step; - } - let pc = self.cpu.pc; - let refuse = |machine: &Self, detail: String| { - Err(machine.unsupported(RequirementKind::Instruction { word, detail })) - }; - let instruction = match block::decode_pointer_authentication(GuestAddress(pc), word) { - Ok(Some(instruction)) => instruction, - _ => return refuse(self, "PAC exit at a word that is not PAC".into()), - }; - let link_register = self - .cpu - .registers - .implemented(Feature::FEAT_PAuth_LR) - .map_err(|error| self.unsupported(RequirementKind::Native(error.reason())))?; - // Without FEAT_PAuth_LR its hint-space form (PACM) is a NOP and the - // others are UNDEFINED. - if let PointerAuthenticationOperation::LinkRegister(form) = instruction.operation { - if !link_register { - return if word & 0xffff_f01f == 0xd503_201f { - self.next() - } else { - self.undefined() - }; - } - if form == block::pauth_lr::Instruction::Pacm { - self.cpu.pstate.pacm = self.cpu.pacm_enabled(); - self.pacm_written = true; - return self.next(); - } - let staged = pauth::lr_instruction::stage( - form, - pc, - self.cpu.state.x[..31].try_into().expect("31 registers"), - self.cpu.state.sp, - ); - return match staged { - Ok(pauth::lr_instruction::Staged::Pointer(operands)) => { - self.two_modifier_authentication(word, instruction, operands) - } - _ => refuse(self, "FEAT_PAuth_LR operands".into()), - }; - } - if link_register && self.cpu.pstate.pacm { - let operands = self.pacm_operands(instruction).map_err(|error| { - self.unsupported(RequirementKind::Instruction { - word, - detail: alloc::format!("invalid PACM operands: {error:?}"), - }) - })?; - if let Some(operands) = operands { - return self.two_modifier_authentication(word, instruction, operands); - } - } - let uses_key = match instruction.operation.required_key() { - Some(key) if !self.key_enabled(key) => { - return self.disabled_pointer_authentication(word, instruction); - } - Some(_) => true, - None => matches!( - instruction.operation, - PointerAuthenticationOperation::GenericCode(_) - ), - }; - if uses_key && self.pointer_authentication_trapped() { - return self.pointer_authentication_trap(); - } - if let Some(step) = self.register_pointer_authentication(instruction) { - return step; - } - let context = self.pointer_context()?; - if let PointerAuthenticationOperation::Strip { data, .. } = instruction.operation { - self.pointer.open_stripping(&context, data); - } - if let PointerAuthenticationOperation::Load(load) = instruction.operation { - return self.authenticated_load(word, Some(&context), load); - } - match crate::blocks::services::complete_pauth_with_memory( - &context, - &instruction, - &mut self.cpu.state, - None, - ) { - Ok((next, _)) => { - self.cpu.pstate.btype = self.pointer_branch_type(pc, instruction.operation); - self.cpu.pc = next.0; - Ok(()) - } - Err(crate::blocks::services::PauthFault::Authentication( - pauth::AuthenticationError::Failure { code }, - )) => { - self.take(Exception::synchronous( - Class::PointerAuthenticationFailure, - u32::from(code), - pc, - )); - Ok(()) - } - Err(fault) => refuse(self, fault.to_string()), - } - } - - /// PACIASP, PACIBSP, AUTIASP, AUTIBSP, RETAA, RETAB and the HINT-space - /// *1716 forms, whose operands are implicit (X30 and SP, or X17 and X16): - /// the kernel's prologues and epilogues. With the key enabled and its use - /// not trapped, each completes as the general path does (Arm `AddPAC`, - /// `Auth`; RETA* branches to the authenticated pointer and keeps X30 - /// signed) through [`Self::pointer_result`]. `None` leaves every other - /// case, and every form under PSTATE.PACM, to the general path. - pub(super) fn implicit_pointer_authentication(&mut self, word: u32) -> Option { - use PointerAuthenticationKey as Block; - use stela_contracts::pauth::Key; - #[derive(PartialEq)] - enum Form { - Sign, - Authenticate, - Return, - } - let (form, key, block_key, stack) = match word { - 0xd503_233f => (Form::Sign, Key::Ia, Block::Ia, true), - 0xd503_237f => (Form::Sign, Key::Ib, Block::Ib, true), - 0xd503_23bf => (Form::Authenticate, Key::Ia, Block::Ia, true), - 0xd503_23ff => (Form::Authenticate, Key::Ib, Block::Ib, true), - 0xd65f_0bff => (Form::Return, Key::Ia, Block::Ia, true), - 0xd65f_0fff => (Form::Return, Key::Ib, Block::Ib, true), - 0xd503_211f => (Form::Sign, Key::Ia, Block::Ia, false), - 0xd503_215f => (Form::Sign, Key::Ib, Block::Ib, false), - 0xd503_219f => (Form::Authenticate, Key::Ia, Block::Ia, false), - 0xd503_21df => (Form::Authenticate, Key::Ib, Block::Ib, false), - _ => return None, - }; - if self.cpu.pstate.pacm - || !self.key_enabled(block_key) - || self.pointer_authentication_trapped() - { - return None; - } - let (register, modifier) = if stack { - (30, self.cpu.state.sp) - } else { - (17, self.cpu.state.x[16]) - }; - let operation = match form { - Form::Sign => PointerOperation::Sign, - Form::Authenticate => PointerOperation::Authenticate { combined: false }, - Form::Return => PointerOperation::Authenticate { combined: true }, - }; - let pointer = self.cpu.state.x[register]; - let result = match self.pointer_result(operation, key, pointer, modifier) { - Ok(result) => result, - Err(stop) => return Some(Err(stop)), - }; - let pc = self.cpu.pc; - match result { - Ok((target, _)) if form == Form::Return => { - self.cpu.pstate.btype = 0; - self.cpu.pc = target; - } - Ok((value, _)) => { - self.cpu.pstate.btype = 0; - self.cpu.state.x[register] = value; - self.cpu.pc = pc + INSTRUCTION; - } - Err(code) => self.take(Exception::synchronous( - Class::PointerAuthenticationFailure, - u32::from(code), - pc, - )), - } - Some(Ok(())) - } - - /// PAC*, AUT*, BRA* and BLRA* with register, SP or zero modifiers, once - /// their key is known enabled and untrapped: each completes as the - /// general path does (Arm `AddPAC`, `Auth`; a branch authenticates as a - /// combined form, then links and branches) through - /// [`Self::pointer_result`], and PACGA through the same service. `None` - /// leaves forms naming register 31 to the general path. - pub(super) fn register_pointer_authentication( - &mut self, - instruction: PointerAuthentication, - ) -> Option { - use PointerAuthenticationModifier as Modifier; - use PointerAuthenticationOperation as Operation; - if let Operation::GenericCode(code) = instruction.operation { - return self.generic_pointer_code(code, instruction.next_pc.0); - } - let (operation, key, register, modifier) = match instruction.operation { - Operation::Sign { - key, - destination, - modifier, - } => (PointerOperation::Sign, key, destination, modifier), - Operation::Authenticate { - key, - destination, - modifier, - } => ( - PointerOperation::Authenticate { combined: false }, - key, - destination, - modifier, - ), - Operation::Branch { - key, - target, - modifier, - .. - } => ( - PointerOperation::Authenticate { combined: true }, - key, - target, - modifier, - ), - _ => return None, - }; - let modifier = match modifier { - Modifier::Register(31) => return None, - Modifier::Register(register) => self.cpu.state.x[usize::from(register)], - Modifier::StackPointer => self.cpu.state.sp, - Modifier::Zero => 0, - }; - if register == 31 { - return None; - } - let key = match key { - PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, - PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, - PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, - PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, - }; - let pc = self.cpu.pc; - let pointer = self.cpu.state.x[usize::from(register)]; - let result = match self.pointer_result(operation, key, pointer, modifier) { - Ok(result) => result, - Err(stop) => return Some(Err(stop)), - }; - match result { - Ok((value, _)) => { - self.cpu.pstate.btype = self.pointer_branch_type(pc, instruction.operation); - if let Operation::Branch { link, .. } = instruction.operation { - if link { - self.cpu.state.x[30] = instruction.next_pc.0; - } - self.cpu.pc = value; - } else { - self.cpu.state.x[usize::from(register)] = value; - self.cpu.pc = instruction.next_pc.0; - } - } - Err(code) => self.take(Exception::synchronous( - Class::PointerAuthenticationFailure, - u32::from(code), - pc, - )), - } - Some(Ok(())) - } - - /// PACGA, known untrapped, through the service, which opens the generic - /// key's tag word for thunks. `None` leaves an XZR source or destination - /// to the general path. - fn generic_pointer_code( - &mut self, - code: stela_compiler::block::pauth_memory::GenericCode, - next: u64, - ) -> Option { - if code.source == 31 || code.destination == 31 { - return None; - } - if let Err(stop) = self.open_pointers() { - return Some(Err(stop)); - } - let data = self.cpu.state.x[usize::from(code.source)]; - let modifier = match code.modifier { - 31 => self.cpu.state.sp, - register => self.cpu.state.x[usize::from(register)], - }; - let Some(value) = self.pointer.generic_code(data, modifier) else { - return Some(Err(self.unsupported(RequirementKind::Native( - "PAC generic key unavailable", - )))); - }; - self.cpu.pstate.btype = 0; - self.cpu.state.x[usize::from(code.destination)] = value; - self.cpu.pc = next; - Some(Ok(())) - } - - /// Open the service with the current keys, version and layout. A - /// context without an open tag word may predate keys native code wrote - /// (`register_read::key_write_thunk`). - fn open_pointers(&mut self) -> Result<(), Stop> { - if self.pointer.is_open() && self.pointer.tags_closed() { - if self.cpu.pstate.pacm { - self.pointer.close(); - } else { - self.revalidate_pointers(); - } - } - if !self.pointer.is_open() { - let inputs = PointerInputs { - keys: self.pointer_keys(), - version: self.pointer_version()?, - tcr: self.cpu.regime_tcr(), - }; - self.pointer.open(inputs); - } - Ok(()) - } - - /// One signing or authentication with the current keys, version and - /// layout (`pointer::PointerService::result`), the key known enabled - /// and untrapped. - pub(super) fn pointer_result( - &mut self, - operation: PointerOperation, - key: stela_contracts::pauth::Key, - pointer: u64, - modifier: u64, - ) -> Result { - self.open_pointers()?; - self.pointer - .result(operation, key, pointer, modifier) - .ok_or_else(|| { - self.unsupported(RequirementKind::Native(match operation { - PointerOperation::Sign => "PAC key unavailable for signing", - PointerOperation::Authenticate { .. } => { - "PAC key unavailable for authentication" - } - })) - }) - } - - /// The two-modifier operation PSTATE.PACM makes of a PAC*SP, AUT*SP, - /// RETA* or HINT-space *1716 instruction (Arm PACIA, AUTIA and RETAA - /// under FEAT_PAuth_LR): the signing forms take the instruction's PC as - /// the second modifier, the authenticating forms X16, and the *1716 - /// forms X15. - pub(super) fn pacm_operands( - &self, - instruction: PointerAuthentication, - ) -> Result, pauth::lr_instruction::StageError> { - let staged = pauth::conditional::stage( - instruction.operation, - instruction.instruction_pc.0, - self.cpu.state.x[..31] - .try_into() - .expect("31 architectural registers"), - self.cpu.state.sp, - crate::system::state::Pacm::One, - )?; - Ok(staged.map(|operands| pauth::lr_instruction::Operands { - key: operands.key, - action: operands.action, - pointer: operands.pointer, - modifier1: operands.first, - modifier2: operands - .second - .expect("PACM one selects the second modifier"), - destination: operands.destination, - implicit_bti: false, - instruction_pc: instruction.instruction_pc.0, - })) - } - - /// Arm AddPACIA2, AddPACIB2, AuthIA2 and AuthIB2 with the guest's keys: - /// with the key's SCTLR enable clear the pointer is unchanged, HCR_EL2.API - /// clear traps the use, a failed AUT* takes the PAC Fail exception - /// (FEAT_FPAC) and so does a failed RETA* (FEAT_FPACCOMBINE). - pub(super) fn two_modifier_authentication( - &mut self, - word: u32, - instruction: PointerAuthentication, - operands: pauth::lr_instruction::Operands, - ) -> Step { - use pauth::lr_instruction::{Action, Key}; - let pc = self.cpu.pc; - let (key, runtime_key) = match operands.key { - Key::Ia => ( - PointerAuthenticationKey::Ia, - stela_contracts::pauth::Key::Ia, - ), - Key::Ib => ( - PointerAuthenticationKey::Ib, - stela_contracts::pauth::Key::Ib, - ), - }; - if !self.key_enabled(key) { - return self.disabled_pointer_authentication(word, instruction); - } - if self.pointer_authentication_trapped() { - return self.pointer_authentication_trap(); - } - let context = self.pointer_context()?; - let refuse = |machine: &Self, detail: String| { - Err(machine.unsupported(RequirementKind::Instruction { word, detail })) - }; - let (pointer, m1, m2) = (operands.pointer, operands.modifier1, operands.modifier2); - let result = match operands.action { - Action::Sign => match context.sign_two_modifiers(runtime_key, pointer, m1, m2) { - Ok(signed) => Ok(signed), - Err(error) => return refuse(self, format!("{error:?}")), - }, - Action::Authenticate | Action::Return => { - let combined = operands.action == Action::Return; - match context.authenticate_two_modifiers(runtime_key, pointer, m1, m2, combined) { - Ok(Ok(result)) => Ok(result.pointer), - Ok(Err(pauth::AuthenticationError::Failure { code })) => Err(code), - Ok(Err(error)) => return refuse(self, format!("{error:?}")), - Err(error) => return refuse(self, format!("{error:?}")), - } - } - }; - let value = match result { - Ok(value) => value, - Err(code) => { - self.take(Exception::synchronous( - Class::PointerAuthenticationFailure, - u32::from(code), - pc, - )); - return Ok(()); - } - }; - self.cpu.pstate.btype = 0; - match operands.destination { - Some(31) => self.cpu.pc = instruction.next_pc.0, - Some(destination) => { - self.cpu.state.x[usize::from(destination)] = value; - self.cpu.pc = instruction.next_pc.0; - } - None => self.cpu.pc = value, - } - Ok(()) - } - - /// BTYPE after a completed PAC instruction at `pc`: BRA* and BLRA* set it - /// as BR and BLR do, every other form clears it. - pub(super) fn pointer_branch_type( - &mut self, - pc: u64, - operation: PointerAuthenticationOperation, - ) -> u8 { - match operation { - PointerAuthenticationOperation::Branch { target, link, .. } => { - self.indirect_branch_type(pc, target, link) - } - _ => 0, - } - } - - /// With the key's SCTLR enable clear, AddPAC and Auth return the pointer - /// unchanged (Arm ARM `AddPAC`, `Auth`). Until derived state changes, - /// the key's tag word lets PAC thunks complete its instructions the - /// same way (`x86_64::pointer::DISABLED`). - pub(super) fn disabled_pointer_authentication( - &mut self, - word: u32, - instruction: PointerAuthentication, - ) -> Step { - use PointerAuthenticationOperation as Operation; - if let Some(key) = instruction.operation.required_key() { - self.pointer.tags[usize::from(x86_64_pointer::key_index(key))] = - x86_64_pointer::DISABLED; - } - let next = instruction.next_pc.0; - self.cpu.pstate.btype = self.pointer_branch_type(self.cpu.pc, instruction.operation); - match instruction.operation { - Operation::Sign1716 { .. } - | Operation::Authenticate1716 { .. } - | Operation::SignIbSp - | Operation::AuthenticateIbSp - | Operation::Sign { .. } - | Operation::Authenticate { .. } => self.cpu.pc = next, - Operation::ReturnIbSp | Operation::ReturnIaSp => self.cpu.pc = self.cpu.state.x[30], - Operation::LinkRegister(form) if form.is_return() => { - self.cpu.pc = self.cpu.state.x[30]; - } - Operation::LinkRegister(_) => self.cpu.pc = next, - Operation::Branch { target, link, .. } => { - let destination = if target == 31 { - 0 - } else { - self.cpu.state.x[usize::from(target)] - }; - if link { - self.cpu.state.x[30] = next; - } - self.cpu.pc = destination; - } - Operation::Load(load) => return self.authenticated_load(word, None, load), - Operation::Strip { .. } | Operation::GenericCode(_) => { - unreachable!("XPAC and PACGA use no key that SCTLR disables") - } - } - Ok(()) - } - - /// LDRAA/LDRAB: authenticate the base, then read through the guest's - /// translation like any data load. Without a context the key is - /// disabled, and AuthDA/AuthDB return the base unchanged (Arm `Auth`). - pub(super) fn authenticated_load( - &mut self, - word: u32, - context: Option<&pauth::Context>, - load: stela_compiler::block::pauth_memory::Load, - ) -> Step { - let pc = self.cpu.pc; - let controls = self.cpu.controls(self.cpu.regime()); - let requester = self.cpu.requester(); - let sctlr = controls.sctlr; - let memory_controls = pauth::memory::Controls { - check_sp_alignment: if requester.el == 0 { - sctlr & (1 << 4) != 0 - } else { - sctlr & (1 << 3) != 0 - }, - privileged: requester.el != 0, - }; - enum LoadStop { - Alignment, - Fault(mmu::Fault), - Unsupported(mmu::Unsupported), - Device(u64), - } - // A RAM read has no side effects: the load is made, then checked - // against the watchpoints, and undone if one matches. - let before = self.cpu.state.clone(); - let loaded = core::cell::Cell::new(None); - let host = &mut self.host; - let result = pauth::memory::complete( - load, - memory_controls, - &mut self.cpu.state, - |key, pointer| { - let key = match key { - stela_compiler::block::pauth_memory::DataKey::A => { - stela_contracts::pauth::Key::Da - } - stela_compiler::block::pauth_memory::DataKey::B => { - stela_contracts::pauth::Key::Db - } - }; - match context { - Some(context) => context - .authenticate_operation(key, pointer, 0, true) - .map(|result| result.pointer), - None => Ok(pointer), - } - }, - |address| { - let shape = mmu::alignment::Shape { - kind: mmu::alignment::Kind::Plain, - bytes: 8, - pair: false, - }; - if mmu::alignment::before_translation(sctlr, address, shape) { - return Err(LoadStop::Alignment); - } - let translation = match mmu::translate( - &controls, - address, - Access::Read, - requester, - &mut RamTables(host), - ) { - Translated::Mapped(translation) => translation, - Translated::Fault(fault) => return Err(LoadStop::Fault(fault)), - Translated::Unsupported(unsupported) => { - return Err(LoadStop::Unsupported(unsupported)); - } - }; - let mut bytes = [0; 8]; - if (address & (FETCH_PAGE - 1)) > FETCH_PAGE - 8 { - return Err(LoadStop::Device(translation.physical)); - } - loaded.set(Some(address)); - if !host.read_ram(translation.physical, &mut bytes) { - return Err(LoadStop::Device(translation.physical)); - } - Ok(u64::from_le_bytes(bytes)) - }, - ); - match result { - Ok(_) => { - let access = loaded.get().map(|address| debug::Access { - address, - size: 8, - read: true, - write: false, - maintenance: false, - el: requester.el, - }); - if let Some(exception) = - access.and_then(|access| self.watchpoint_exception(&access, pc)) - { - self.cpu.state = before; - self.take(exception); - return Ok(()); - } - // Tag checked with writeback or a base other than SP - // (FEAT_MTE2), after the watchpoint. - if let Some(access) = access - && (load.writeback || load.base != 31) - && let tags::TagCheck::Failed(exception) = - self.tag_check(&access, requester, None)? - { - self.cpu.state = before; - self.take(exception); - return Ok(()); - } - self.cpu.pc = pc; - self.next() - } - Err(pauth::memory::Fault::Read { - address, - error: LoadStop::Fault(fault), - }) => self.data_abort(address, fault, false, false), - Err(pauth::memory::Fault::Read { - address, - error: LoadStop::Alignment, - }) => self.alignment_fault(address, false), - Err(pauth::memory::Fault::Read { - error: LoadStop::Unsupported(unsupported), - .. - }) => Err(self.unsupported(RequirementKind::Translation(unsupported))), - Err(pauth::memory::Fault::StackAlignment { .. }) => { - self.take(Exception::synchronous(Class::SpAlignment, 0, pc)); - Ok(()) - } - // FEAT_FPACCOMBINE: a failed authentication of the base faults - // as a standalone AUT does. - Err(pauth::memory::Fault::Authentication(pauth::AuthenticationError::Failure { - code, - })) => { - self.take(Exception::synchronous( - Class::PointerAuthenticationFailure, - u32::from(code), - pc, - )); - Ok(()) - } - Err(other) => Err(self.unsupported(RequirementKind::Instruction { - word, - detail: match other { - pauth::memory::Fault::Read { - error: LoadStop::Device(physical), - .. - } => format!("LDRA from non-RAM or page-crossing address (PA {physical:#x})"), - _ => "LDRA operands or authentication".into(), - }, - })), - } - } - - /// `pointer` without its PAC, laid out as an instruction address in the - /// current regime (Arm `XPACI`), for diagnostics such as return - /// addresses in frame records; unchanged without a PAC layout. - pub fn strip_instruction_pointer(&self, pointer: u64) -> u64 { - self.pointer_context() - .ok() - .map(|context| context.strip(stela_contracts::pauth::Key::Ia, pointer)) - .unwrap_or(pointer) - } - - /// ADDPT, SUBPT, MADDPT and MSUBPT (FEAT_CPA), UNDEFINED on a chip - /// without it. No Apple chip has FEAT_CPA2, so `EffectiveCPTA` and - /// `EffectiveCPTM` are 0 and `PointerAddCheck` and - /// `PointerMultiplyAddCheck` return the plain sum. - pub(super) fn checked_pointer( - &mut self, - operand: stela_compiler::aarch64::checked_pointer::Operand, - ) -> Step { - use stela_compiler::aarch64::checked_pointer::Kind; - match self.cpu.registers.implemented(Feature::FEAT_CPA) { - Ok(true) => {} - Ok(false) => return self.undefined(), - Err(error) => return Err(self.unsupported(RequirementKind::Native(error.reason()))), - } - let (base, change, subtract) = match operand.kind { - Kind::Offset { - base, - offset, - amount, - subtract, - } => (base, self.read_register(offset) << amount, subtract), - Kind::Product { - left, - right, - base, - subtract, - } => ( - base, - self.read_register(left) - .wrapping_mul(self.read_register(right)), - subtract, - ), - }; - let base = self.read_register(base); - let result = if subtract { - base.wrapping_sub(change) - } else { - base.wrapping_add(change) - }; - self.write_register(operand.destination, result); - self.next() - } -} +//! Pointer authentication with the guest's own keys, completed by the engine. + +use super::*; + +/// The APCTL bit that keeps the keys on above EL0 whatever SCTLR says. SPTM +/// 26A434 sets it at boot (`__text+0xb790`), and its context switch for a +/// process without JOP keys then clears SCTLR's enables (`__text+0x4a264`) +/// with signed returns of its own and the kernel's still to come, so those +/// enables can govern only EL0. SPTM clears the bit on entry, setting all +/// four enables instead (`__text+0x20e0`). +const APCTL_KERNEL_KEYS: u64 = 1 << 4; + +pub(super) const fn key_enable_bit(key: PointerAuthenticationKey) -> u64 { + 1 << match key { + PointerAuthenticationKey::Ia => 31, + PointerAuthenticationKey::Ib => 30, + PointerAuthenticationKey::Da => 27, + PointerAuthenticationKey::Db => 13, + } +} + +impl Machine { + /// SCTLR key enables for the current regime, overridden above EL0 by + /// APCTL. A single snapshot can reopen all four address keys. + pub(super) fn pointer_key_enables(&self) -> u64 { + let control = match self.cpu.pstate.el { + 1 => self.cpu.apple.apctl[0], + 2 => self.cpu.apple.apctl[1], + _ => 0, + }; + if control & APCTL_KERNEL_KEYS != 0 { + u64::MAX + } else { + self.cpu.regime_sctlr() + } + } + + pub(super) fn key_enabled(&self, key: PointerAuthenticationKey) -> bool { + self.pointer_key_enables() & key_enable_bit(key) != 0 + } + + /// The PAC keys as (low, high) words in APIA, APIB, APDA, APDB, APGA order. + pub(super) fn pointer_keys(&self) -> [Option<[u64; 2]>; 5] { + // The original T6000 LLB initializes C13/C14 keys and consumes them + // at EL2. They are not aliases of the architectural lower bank. EL0 + // in the host shares them, as the architectural keys serve every EL: + // 26A434 XNU at EL2 loads each thread's B keys there on a context + // switch (0xfffffe000bb9bd14) for its EL0 to use. + if self.cpu.pstate.el == 2 || self.cpu.pstate.el == 0 && self.cpu.in_host() { + return self.cpu.apple.pointer_keys.pairs(); + } + use SystemRegister as R; + let pair = |low, high| Some([self.cpu.read(low), self.cpu.read(high)]); + [ + pair(R::APIAKeyLo_EL1, R::APIAKeyHi_EL1), + pair(R::APIBKeyLo_EL1, R::APIBKeyHi_EL1), + pair(R::APDAKeyLo_EL1, R::APDAKeyHi_EL1), + pair(R::APDBKeyLo_EL1, R::APDBKeyHi_EL1), + pair(R::APGAKeyLo_EL1, R::APGAKeyHi_EL1), + ] + } + + /// The PAC algorithm version of the PE: FEAT_FPACCOMBINE, FEAT_FPAC, + /// FEAT_PAuth2 or the classic FEAT_PAuth insertion and error code (the + /// M1). A feature the PE has and the engine does not implement yet stops. + pub(super) fn pointer_version(&self) -> Result { + let has = |feature| { + self.cpu + .registers + .implemented(feature) + .map_err(|error| self.unsupported(RequirementKind::Native(error.reason()))) + }; + Ok(if has(Feature::FEAT_FPACCOMBINE)? { + pauth::Version::FaultingCombined + } else if has(Feature::FEAT_FPAC)? { + pauth::Version::Faulting + } else if has(Feature::FEAT_PAuth2)? { + pauth::Version::Enhanced + } else { + pauth::Version::Classic + }) + } + + /// The guest's PAC keys and the current regime's TCR layout, with the + /// chip's PAC version. + pub(super) fn pointer_context(&self) -> Result { + let [ia, ib, da, db, generic] = self.pointer_keys(); + let mut keys = pauth::Keys::from_optional_words([ia, ib, da, db]); + if let Some(generic) = generic { + keys = keys.with_generic_words(generic); + } + Ok( + pauth::Context::new_with_version(0, keys, self.pointer_version()?) + .with_translation_regime(self.cpu.regime_tcr()) + .with_implementation_defined_cipher(), + ) + } + + /// Whether HCR_EL2.API clear traps the use of an enabled key, or PACGA, + /// to EL2: from EL1, and from EL0 outside the host (Arm + /// `IsAPIAKeyEnabled` and the other key checks, `AddPACGA`). + pub(super) fn pointer_authentication_trapped(&self) -> bool { + let el = self.cpu.pstate.el; + (el == 1 || (el == 0 && !self.cpu.in_host())) && !self.cpu.hcr(HCR_API) + } + + /// Arm `TrapPACUse(EL2)`: EC 0x09 with ISS 0 at the instruction. + pub(super) fn pointer_authentication_trap(&mut self) -> Step { + let pc = self.cpu.pc; + self.take(Exception::synchronous(Class::PointerAuthenticationTrap, 0, pc).to(2)); + Ok(()) + } + + /// Complete one PAC instruction with the guest's own keys, laid out for + /// the current TCR. The algorithm is the software QARMA5 service as + /// FEAT_PAuth2 with FEAT_FPAC; Apple's hardware algorithm and AppleMode + /// diversification are not reproduced, so values are self-consistent + /// rather than equal to hardware's. A failed standalone AUT* takes the + /// PAC Fail exception (EC 0x1C) to the current EL, or from EL0 to EL1 or + /// the host's EL2 (Arm `AArch64_PACFailException`). + pub(super) fn pointer_authentication(&mut self, word: u32) -> Step { + if let Some(step) = self.implicit_pointer_authentication(word) { + return step; + } + let pc = self.cpu.pc; + let refuse = |machine: &Self, detail: String| { + Err(machine.unsupported(RequirementKind::Instruction { word, detail })) + }; + let instruction = match block::decode_pointer_authentication(GuestAddress(pc), word) { + Ok(Some(instruction)) => instruction, + _ => return refuse(self, "PAC exit at a word that is not PAC".into()), + }; + let link_register = self + .cpu + .registers + .implemented(Feature::FEAT_PAuth_LR) + .map_err(|error| self.unsupported(RequirementKind::Native(error.reason())))?; + // Without FEAT_PAuth_LR its hint-space form (PACM) is a NOP and the + // others are UNDEFINED. + if let PointerAuthenticationOperation::LinkRegister(form) = instruction.operation { + if !link_register { + return if word & 0xffff_f01f == 0xd503_201f { + self.next() + } else { + self.undefined() + }; + } + if form == block::pauth_lr::Instruction::Pacm { + self.cpu.pstate.pacm = self.cpu.pacm_enabled(); + self.pacm_written = true; + return self.next(); + } + let staged = pauth::lr_instruction::stage( + form, + pc, + self.cpu.state.x[..31].try_into().expect("31 registers"), + self.cpu.state.sp, + ); + return match staged { + Ok(pauth::lr_instruction::Staged::Pointer(operands)) => { + self.two_modifier_authentication(word, instruction, operands) + } + _ => refuse(self, "FEAT_PAuth_LR operands".into()), + }; + } + if link_register && self.cpu.pstate.pacm { + let operands = self.pacm_operands(instruction).map_err(|error| { + self.unsupported(RequirementKind::Instruction { + word, + detail: alloc::format!("invalid PACM operands: {error:?}"), + }) + })?; + if let Some(operands) = operands { + return self.two_modifier_authentication(word, instruction, operands); + } + } + let uses_key = match instruction.operation.required_key() { + Some(key) if !self.key_enabled(key) => { + return self.disabled_pointer_authentication(word, instruction); + } + Some(_) => true, + None => matches!( + instruction.operation, + PointerAuthenticationOperation::GenericCode(_) + ), + }; + if uses_key && self.pointer_authentication_trapped() { + return self.pointer_authentication_trap(); + } + if let Some(step) = self.register_pointer_authentication(instruction) { + return step; + } + let context = self.pointer_context()?; + if let PointerAuthenticationOperation::Strip { data, .. } = instruction.operation { + self.pointer.open_stripping(&context, data); + } + if let PointerAuthenticationOperation::Load(load) = instruction.operation { + return self.authenticated_load(word, Some(&context), load); + } + match crate::blocks::services::complete_pauth_with_memory( + &context, + &instruction, + &mut self.cpu.state, + None, + ) { + Ok((next, _)) => { + self.cpu.pstate.btype = self.pointer_branch_type(pc, instruction.operation); + self.cpu.pc = next.0; + Ok(()) + } + Err(crate::blocks::services::PauthFault::Authentication( + pauth::AuthenticationError::Failure { code }, + )) => { + self.take(Exception::synchronous( + Class::PointerAuthenticationFailure, + u32::from(code), + pc, + )); + Ok(()) + } + Err(fault) => refuse(self, fault.to_string()), + } + } + + /// PACIASP, PACIBSP, AUTIASP, AUTIBSP, RETAA, RETAB and the HINT-space + /// *1716 forms, whose operands are implicit (X30 and SP, or X17 and X16): + /// the kernel's prologues and epilogues. With the key enabled and its use + /// not trapped, each completes as the general path does (Arm `AddPAC`, + /// `Auth`; RETA* branches to the authenticated pointer and keeps X30 + /// signed) through [`Self::pointer_result`]. `None` leaves every other + /// case, and every form under PSTATE.PACM, to the general path. + pub(super) fn implicit_pointer_authentication(&mut self, word: u32) -> Option { + use PointerAuthenticationKey as Block; + use stela_contracts::pauth::Key; + #[derive(PartialEq)] + enum Form { + Sign, + Authenticate, + Return, + } + let (form, key, block_key, stack) = match word { + 0xd503_233f => (Form::Sign, Key::Ia, Block::Ia, true), + 0xd503_237f => (Form::Sign, Key::Ib, Block::Ib, true), + 0xd503_23bf => (Form::Authenticate, Key::Ia, Block::Ia, true), + 0xd503_23ff => (Form::Authenticate, Key::Ib, Block::Ib, true), + 0xd65f_0bff => (Form::Return, Key::Ia, Block::Ia, true), + 0xd65f_0fff => (Form::Return, Key::Ib, Block::Ib, true), + 0xd503_211f => (Form::Sign, Key::Ia, Block::Ia, false), + 0xd503_215f => (Form::Sign, Key::Ib, Block::Ib, false), + 0xd503_219f => (Form::Authenticate, Key::Ia, Block::Ia, false), + 0xd503_21df => (Form::Authenticate, Key::Ib, Block::Ib, false), + _ => return None, + }; + if self.cpu.pstate.pacm + || !self.key_enabled(block_key) + || self.pointer_authentication_trapped() + { + return None; + } + let (register, modifier) = if stack { + (30, self.cpu.state.sp) + } else { + (17, self.cpu.state.x[16]) + }; + let operation = match form { + Form::Sign => PointerOperation::Sign, + Form::Authenticate => PointerOperation::Authenticate { combined: false }, + Form::Return => PointerOperation::Authenticate { combined: true }, + }; + let pointer = self.cpu.state.x[register]; + let result = match self.pointer_result(operation, key, pointer, modifier) { + Ok(result) => result, + Err(stop) => return Some(Err(stop)), + }; + let pc = self.cpu.pc; + match result { + Ok((target, _)) if form == Form::Return => { + self.cpu.pstate.btype = 0; + self.cpu.pc = target; + } + Ok((value, _)) => { + self.cpu.pstate.btype = 0; + self.cpu.state.x[register] = value; + self.cpu.pc = pc + INSTRUCTION; + } + Err(code) => self.take(Exception::synchronous( + Class::PointerAuthenticationFailure, + u32::from(code), + pc, + )), + } + Some(Ok(())) + } + + /// PAC*, AUT*, BRA* and BLRA* with register, SP or zero modifiers, once + /// their key is known enabled and untrapped: each completes as the + /// general path does (Arm `AddPAC`, `Auth`; a branch authenticates as a + /// combined form, then links and branches) through + /// [`Self::pointer_result`], and PACGA through the same service. `None` + /// leaves forms naming register 31 to the general path. + pub(super) fn register_pointer_authentication( + &mut self, + instruction: PointerAuthentication, + ) -> Option { + use PointerAuthenticationModifier as Modifier; + use PointerAuthenticationOperation as Operation; + if let Operation::GenericCode(code) = instruction.operation { + return self.generic_pointer_code(code, instruction.next_pc.0); + } + let (operation, key, register, modifier) = match instruction.operation { + Operation::Sign { + key, + destination, + modifier, + } => (PointerOperation::Sign, key, destination, modifier), + Operation::Authenticate { + key, + destination, + modifier, + } => ( + PointerOperation::Authenticate { combined: false }, + key, + destination, + modifier, + ), + Operation::Branch { + key, + target, + modifier, + .. + } => ( + PointerOperation::Authenticate { combined: true }, + key, + target, + modifier, + ), + _ => return None, + }; + let modifier = match modifier { + Modifier::Register(31) => return None, + Modifier::Register(register) => self.cpu.state.x[usize::from(register)], + Modifier::StackPointer => self.cpu.state.sp, + Modifier::Zero => 0, + }; + if register == 31 { + return None; + } + let key = match key { + PointerAuthenticationKey::Ia => stela_contracts::pauth::Key::Ia, + PointerAuthenticationKey::Ib => stela_contracts::pauth::Key::Ib, + PointerAuthenticationKey::Da => stela_contracts::pauth::Key::Da, + PointerAuthenticationKey::Db => stela_contracts::pauth::Key::Db, + }; + let pc = self.cpu.pc; + let pointer = self.cpu.state.x[usize::from(register)]; + let result = match self.pointer_result(operation, key, pointer, modifier) { + Ok(result) => result, + Err(stop) => return Some(Err(stop)), + }; + match result { + Ok((value, _)) => { + self.cpu.pstate.btype = self.pointer_branch_type(pc, instruction.operation); + if let Operation::Branch { link, .. } = instruction.operation { + if link { + self.cpu.state.x[30] = instruction.next_pc.0; + } + self.cpu.pc = value; + } else { + self.cpu.state.x[usize::from(register)] = value; + self.cpu.pc = instruction.next_pc.0; + } + } + Err(code) => self.take(Exception::synchronous( + Class::PointerAuthenticationFailure, + u32::from(code), + pc, + )), + } + Some(Ok(())) + } + + /// PACGA, known untrapped, through the service, which opens the generic + /// key's tag word for thunks. `None` leaves an XZR source or destination + /// to the general path. + fn generic_pointer_code( + &mut self, + code: stela_compiler::block::pauth_memory::GenericCode, + next: u64, + ) -> Option { + if code.source == 31 || code.destination == 31 { + return None; + } + if let Err(stop) = self.open_pointers() { + return Some(Err(stop)); + } + let data = self.cpu.state.x[usize::from(code.source)]; + let modifier = match code.modifier { + 31 => self.cpu.state.sp, + register => self.cpu.state.x[usize::from(register)], + }; + let Some(value) = self.pointer.generic_code(data, modifier) else { + return Some(Err(self.unsupported(RequirementKind::Native( + "PAC generic key unavailable", + )))); + }; + self.cpu.pstate.btype = 0; + self.cpu.state.x[usize::from(code.destination)] = value; + self.cpu.pc = next; + Some(Ok(())) + } + + /// Live host addresses `[lo, hi]` of the five PAC key pairs in the + /// current bank (EL2/host bank vs EL1 architectural registers). + pub(super) fn pointer_key_storage(&self) -> [[u64; 2]; x86_64_pointer::TAG_WORDS] { + use SystemRegister as R; + let el2 = self.cpu.pstate.el == 2 || self.cpu.pstate.el == 0 && self.cpu.in_host(); + let pair = |lo, hi| { + if el2 { + let bank = &self.cpu.apple.pointer_keys; + let addr = |reg| { + crate::machine::pointer_keys::Register::architectural(reg) + .and_then(|key| bank.storage(key)) + .unwrap_or(0) + }; + [addr(lo), addr(hi)] + } else { + [ + self.cpu.registers.address(lo, 0).unwrap_or(0), + self.cpu.registers.address(hi, 0).unwrap_or(0), + ] + } + }; + [ + pair(R::APIAKeyLo_EL1, R::APIAKeyHi_EL1), + pair(R::APIBKeyLo_EL1, R::APIBKeyHi_EL1), + pair(R::APDAKeyLo_EL1, R::APDAKeyHi_EL1), + pair(R::APDBKeyLo_EL1, R::APDBKeyHi_EL1), + pair(R::APGAKeyLo_EL1, R::APGAKeyHi_EL1), + ] + } + + /// Open the service with the current keys, version and layout. A + /// context without an open tag word or with dirty keys may predate keys + /// native code wrote (`register_read::key_write_thunk`). + fn open_pointers(&mut self) -> Result<(), Stop> { + if self.pointer.is_open() && (self.pointer.tags_closed() || self.pointer.dirty_keys != 0) { + if self.cpu.pstate.pacm { + self.pointer.close(); + } else { + self.revalidate_pointers(); + } + } + if !self.pointer.is_open() { + let inputs = PointerInputs { + keys: self.pointer_keys(), + version: self.pointer_version()?, + tcr: self.cpu.regime_tcr(), + }; + self.pointer.set_key_storage(self.pointer_key_storage()); + self.pointer.open(inputs); + } + Ok(()) + } + + /// One signing or authentication with the current keys, version and + /// layout (`pointer::PointerService::result`), the key known enabled + /// and untrapped. + pub(super) fn pointer_result( + &mut self, + operation: PointerOperation, + key: stela_contracts::pauth::Key, + pointer: u64, + modifier: u64, + ) -> Result { + self.open_pointers()?; + self.pointer + .result(operation, key, pointer, modifier) + .ok_or_else(|| { + self.unsupported(RequirementKind::Native(match operation { + PointerOperation::Sign => "PAC key unavailable for signing", + PointerOperation::Authenticate { .. } => { + "PAC key unavailable for authentication" + } + })) + }) + } + + /// The two-modifier operation PSTATE.PACM makes of a PAC*SP, AUT*SP, + /// RETA* or HINT-space *1716 instruction (Arm PACIA, AUTIA and RETAA + /// under FEAT_PAuth_LR): the signing forms take the instruction's PC as + /// the second modifier, the authenticating forms X16, and the *1716 + /// forms X15. + pub(super) fn pacm_operands( + &self, + instruction: PointerAuthentication, + ) -> Result, pauth::lr_instruction::StageError> { + let staged = pauth::conditional::stage( + instruction.operation, + instruction.instruction_pc.0, + self.cpu.state.x[..31] + .try_into() + .expect("31 architectural registers"), + self.cpu.state.sp, + crate::system::state::Pacm::One, + )?; + Ok(staged.map(|operands| pauth::lr_instruction::Operands { + key: operands.key, + action: operands.action, + pointer: operands.pointer, + modifier1: operands.first, + modifier2: operands + .second + .expect("PACM one selects the second modifier"), + destination: operands.destination, + implicit_bti: false, + instruction_pc: instruction.instruction_pc.0, + })) + } + + /// Arm AddPACIA2, AddPACIB2, AuthIA2 and AuthIB2 with the guest's keys: + /// with the key's SCTLR enable clear the pointer is unchanged, HCR_EL2.API + /// clear traps the use, a failed AUT* takes the PAC Fail exception + /// (FEAT_FPAC) and so does a failed RETA* (FEAT_FPACCOMBINE). + pub(super) fn two_modifier_authentication( + &mut self, + word: u32, + instruction: PointerAuthentication, + operands: pauth::lr_instruction::Operands, + ) -> Step { + use pauth::lr_instruction::{Action, Key}; + let pc = self.cpu.pc; + let (key, runtime_key) = match operands.key { + Key::Ia => ( + PointerAuthenticationKey::Ia, + stela_contracts::pauth::Key::Ia, + ), + Key::Ib => ( + PointerAuthenticationKey::Ib, + stela_contracts::pauth::Key::Ib, + ), + }; + if !self.key_enabled(key) { + return self.disabled_pointer_authentication(word, instruction); + } + if self.pointer_authentication_trapped() { + return self.pointer_authentication_trap(); + } + let context = self.pointer_context()?; + let refuse = |machine: &Self, detail: String| { + Err(machine.unsupported(RequirementKind::Instruction { word, detail })) + }; + let (pointer, m1, m2) = (operands.pointer, operands.modifier1, operands.modifier2); + let result = match operands.action { + Action::Sign => match context.sign_two_modifiers(runtime_key, pointer, m1, m2) { + Ok(signed) => Ok(signed), + Err(error) => return refuse(self, format!("{error:?}")), + }, + Action::Authenticate | Action::Return => { + let combined = operands.action == Action::Return; + match context.authenticate_two_modifiers(runtime_key, pointer, m1, m2, combined) { + Ok(Ok(result)) => Ok(result.pointer), + Ok(Err(pauth::AuthenticationError::Failure { code })) => Err(code), + Ok(Err(error)) => return refuse(self, format!("{error:?}")), + Err(error) => return refuse(self, format!("{error:?}")), + } + } + }; + let value = match result { + Ok(value) => value, + Err(code) => { + self.take(Exception::synchronous( + Class::PointerAuthenticationFailure, + u32::from(code), + pc, + )); + return Ok(()); + } + }; + self.cpu.pstate.btype = 0; + match operands.destination { + Some(31) => self.cpu.pc = instruction.next_pc.0, + Some(destination) => { + self.cpu.state.x[usize::from(destination)] = value; + self.cpu.pc = instruction.next_pc.0; + } + None => self.cpu.pc = value, + } + Ok(()) + } + + /// BTYPE after a completed PAC instruction at `pc`: BRA* and BLRA* set it + /// as BR and BLR do, every other form clears it. + pub(super) fn pointer_branch_type( + &mut self, + pc: u64, + operation: PointerAuthenticationOperation, + ) -> u8 { + match operation { + PointerAuthenticationOperation::Branch { target, link, .. } => { + self.indirect_branch_type(pc, target, link) + } + _ => 0, + } + } + + /// With the key's SCTLR enable clear, AddPAC and Auth return the pointer + /// unchanged (Arm ARM `AddPAC`, `Auth`). Until derived state changes, + /// the key's tag word lets PAC thunks complete its instructions the + /// same way (`x86_64::pointer::DISABLED`). + pub(super) fn disabled_pointer_authentication( + &mut self, + word: u32, + instruction: PointerAuthentication, + ) -> Step { + use PointerAuthenticationOperation as Operation; + if let Some(key) = instruction.operation.required_key() { + self.pointer.tags[usize::from(x86_64_pointer::key_index(key))] = + x86_64_pointer::DISABLED; + } + let next = instruction.next_pc.0; + self.cpu.pstate.btype = self.pointer_branch_type(self.cpu.pc, instruction.operation); + match instruction.operation { + Operation::Sign1716 { .. } + | Operation::Authenticate1716 { .. } + | Operation::SignIbSp + | Operation::AuthenticateIbSp + | Operation::Sign { .. } + | Operation::Authenticate { .. } => self.cpu.pc = next, + Operation::ReturnIbSp | Operation::ReturnIaSp => self.cpu.pc = self.cpu.state.x[30], + Operation::LinkRegister(form) if form.is_return() => { + self.cpu.pc = self.cpu.state.x[30]; + } + Operation::LinkRegister(_) => self.cpu.pc = next, + Operation::Branch { target, link, .. } => { + let destination = if target == 31 { + 0 + } else { + self.cpu.state.x[usize::from(target)] + }; + if link { + self.cpu.state.x[30] = next; + } + self.cpu.pc = destination; + } + Operation::Load(load) => return self.authenticated_load(word, None, load), + Operation::Strip { .. } | Operation::GenericCode(_) => { + unreachable!("XPAC and PACGA use no key that SCTLR disables") + } + } + Ok(()) + } + + /// LDRAA/LDRAB: authenticate the base, then read through the guest's + /// translation like any data load. Without a context the key is + /// disabled, and AuthDA/AuthDB return the base unchanged (Arm `Auth`). + pub(super) fn authenticated_load( + &mut self, + word: u32, + context: Option<&pauth::Context>, + load: stela_compiler::block::pauth_memory::Load, + ) -> Step { + let pc = self.cpu.pc; + let controls = self.cpu.controls(self.cpu.regime()); + let requester = self.cpu.requester(); + let sctlr = controls.sctlr; + let memory_controls = pauth::memory::Controls { + check_sp_alignment: if requester.el == 0 { + sctlr & (1 << 4) != 0 + } else { + sctlr & (1 << 3) != 0 + }, + privileged: requester.el != 0, + }; + enum LoadStop { + Alignment, + Fault(mmu::Fault), + Unsupported(mmu::Unsupported), + Device(u64), + } + // A RAM read has no side effects: the load is made, then checked + // against the watchpoints, and undone if one matches. + let before = self.cpu.state.clone(); + let loaded = core::cell::Cell::new(None); + let host = &mut self.host; + let result = pauth::memory::complete( + load, + memory_controls, + &mut self.cpu.state, + |key, pointer| { + let key = match key { + stela_compiler::block::pauth_memory::DataKey::A => { + stela_contracts::pauth::Key::Da + } + stela_compiler::block::pauth_memory::DataKey::B => { + stela_contracts::pauth::Key::Db + } + }; + match context { + Some(context) => context + .authenticate_operation(key, pointer, 0, true) + .map(|result| result.pointer), + None => Ok(pointer), + } + }, + |address| { + let shape = mmu::alignment::Shape { + kind: mmu::alignment::Kind::Plain, + bytes: 8, + pair: false, + }; + if mmu::alignment::before_translation(sctlr, address, shape) { + return Err(LoadStop::Alignment); + } + let translation = match mmu::translate( + &controls, + address, + Access::Read, + requester, + &mut RamTables(host), + ) { + Translated::Mapped(translation) => translation, + Translated::Fault(fault) => return Err(LoadStop::Fault(fault)), + Translated::Unsupported(unsupported) => { + return Err(LoadStop::Unsupported(unsupported)); + } + }; + let mut bytes = [0; 8]; + if (address & (FETCH_PAGE - 1)) > FETCH_PAGE - 8 { + return Err(LoadStop::Device(translation.physical)); + } + loaded.set(Some(address)); + if !host.read_ram(translation.physical, &mut bytes) { + return Err(LoadStop::Device(translation.physical)); + } + Ok(u64::from_le_bytes(bytes)) + }, + ); + match result { + Ok(_) => { + let access = loaded.get().map(|address| debug::Access { + address, + size: 8, + read: true, + write: false, + maintenance: false, + el: requester.el, + }); + if let Some(exception) = + access.and_then(|access| self.watchpoint_exception(&access, pc)) + { + self.cpu.state = before; + self.take(exception); + return Ok(()); + } + // Tag checked with writeback or a base other than SP + // (FEAT_MTE2), after the watchpoint. + if let Some(access) = access + && (load.writeback || load.base != 31) + && let tags::TagCheck::Failed(exception) = + self.tag_check(&access, requester, None)? + { + self.cpu.state = before; + self.take(exception); + return Ok(()); + } + self.cpu.pc = pc; + self.next() + } + Err(pauth::memory::Fault::Read { + address, + error: LoadStop::Fault(fault), + }) => self.data_abort(address, fault, false, false), + Err(pauth::memory::Fault::Read { + address, + error: LoadStop::Alignment, + }) => self.alignment_fault(address, false), + Err(pauth::memory::Fault::Read { + error: LoadStop::Unsupported(unsupported), + .. + }) => Err(self.unsupported(RequirementKind::Translation(unsupported))), + Err(pauth::memory::Fault::StackAlignment { .. }) => { + self.take(Exception::synchronous(Class::SpAlignment, 0, pc)); + Ok(()) + } + // FEAT_FPACCOMBINE: a failed authentication of the base faults + // as a standalone AUT does. + Err(pauth::memory::Fault::Authentication(pauth::AuthenticationError::Failure { + code, + })) => { + self.take(Exception::synchronous( + Class::PointerAuthenticationFailure, + u32::from(code), + pc, + )); + Ok(()) + } + Err(other) => Err(self.unsupported(RequirementKind::Instruction { + word, + detail: match other { + pauth::memory::Fault::Read { + error: LoadStop::Device(physical), + .. + } => format!("LDRA from non-RAM or page-crossing address (PA {physical:#x})"), + _ => "LDRA operands or authentication".into(), + }, + })), + } + } + + /// `pointer` without its PAC, laid out as an instruction address in the + /// current regime (Arm `XPACI`), for diagnostics such as return + /// addresses in frame records; unchanged without a PAC layout. + pub fn strip_instruction_pointer(&self, pointer: u64) -> u64 { + self.pointer_context() + .ok() + .map(|context| context.strip(stela_contracts::pauth::Key::Ia, pointer)) + .unwrap_or(pointer) + } + + /// ADDPT, SUBPT, MADDPT and MSUBPT (FEAT_CPA), UNDEFINED on a chip + /// without it. No Apple chip has FEAT_CPA2, so `EffectiveCPTA` and + /// `EffectiveCPTM` are 0 and `PointerAddCheck` and + /// `PointerMultiplyAddCheck` return the plain sum. + pub(super) fn checked_pointer( + &mut self, + operand: stela_compiler::aarch64::checked_pointer::Operand, + ) -> Step { + use stela_compiler::aarch64::checked_pointer::Kind; + match self.cpu.registers.implemented(Feature::FEAT_CPA) { + Ok(true) => {} + Ok(false) => return self.undefined(), + Err(error) => return Err(self.unsupported(RequirementKind::Native(error.reason()))), + } + let (base, change, subtract) = match operand.kind { + Kind::Offset { + base, + offset, + amount, + subtract, + } => (base, self.read_register(offset) << amount, subtract), + Kind::Product { + left, + right, + base, + subtract, + } => ( + base, + self.read_register(left) + .wrapping_mul(self.read_register(right)), + subtract, + ), + }; + let base = self.read_register(base); + let result = if subtract { + base.wrapping_sub(change) + } else { + base.wrapping_add(change) + }; + self.write_register(operand.destination, result); + self.next() + } +} diff --git a/crates/stela-engine/src/machine/engine/regime_state.rs b/crates/stela-engine/src/machine/engine/regime_state.rs index 1d9a65693b..dd0d146ff2 100644 --- a/crates/stela-engine/src/machine/engine/regime_state.rs +++ b/crates/stela-engine/src/machine/engine/regime_state.rs @@ -174,6 +174,7 @@ impl Machine { version, tcr: self.cpu.regime_tcr(), }; + self.pointer.set_key_storage(self.pointer_key_storage()); let stripping = self.pointer.revalidate(inputs); let trapped = self.pointer_authentication_trapped(); let enables = self.pointer_key_enables(); diff --git a/crates/stela-engine/src/machine/engine/step_timing.rs b/crates/stela-engine/src/machine/engine/step_timing.rs index 5901e87e96..1c077949f0 100644 --- a/crates/stela-engine/src/machine/engine/step_timing.rs +++ b/crates/stela-engine/src/machine/engine/step_timing.rs @@ -1,3147 +1,3147 @@ -//! `--profile`: where a run's host time goes between translated blocks, by -//! phase of the engine's step loop and by the exit kind the engine handles. -//! The host supplies the clock ([`super::Host::profile_ticks`]); while off, -//! each phase boundary costs one branch. - -pub mod pc_samples; -mod regions; -pub use pc_samples::{BlockSample, NO_BLOCK, PcBlock, PcHit, PcSamples}; -pub use regions::{CodeRegion, block_regions, pointer_service_calls}; - -/// Words of a PE's PAC census (`Statistics` `pac_census`): cipher runs by -/// key (IA, IB, DA, DB, GA) and operation (signing, authentication, -/// PACGA), then by cause (new, here, other), then those of native code, -/// then new key generations. -pub const PAC_CENSUS_WORDS: usize = super::pointer::census::WORDS; - -/// A phase of the step loop ([`super::Machine::run_blocks`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(usize)] -pub enum Phase { - /// Choosing the PE to run, ending slices and waiting. - Schedule, - /// Due device work and interrupt delivery before each step. - Devices, - /// Finding the next block, compiling and installing it when new. - Fetch, - /// Translated code, chained blocks included. - Native, - /// Handling the exit translated code returned with, by kind. - Exit, -} - -impl Phase { - pub const COUNT: usize = Self::Exit as usize + 1; - pub const ALL: [Self; Self::COUNT] = [ - Self::Schedule, - Self::Devices, - Self::Fetch, - Self::Native, - Self::Exit, - ]; - - pub fn name(self) -> &'static str { - match self { - Self::Schedule => "schedule", - Self::Devices => "devices", - Self::Fetch => "fetch", - Self::Native => "native", - Self::Exit => "exit", - } - } -} - -/// The exits [`StepTiming::exits`] counts: each `ExitKind`, then native -/// faults by cause ([`fault_slot`]), then [`DEVICE_SITE_SLOT`], then the -/// native check faults by what the engine found ([`Check`]). -pub const EXIT_SLOTS: usize = CHECK_SLOTS + Check::COUNT; -/// [`StepTiming::exits`]' first native-fault slot. -const FAULT_SLOTS: usize = 13; -/// The slot of native faults that reached a device ([`fault_slot`]). -pub const DEVICE_FAULT_SLOT: usize = FAULT_SLOTS + 1; -/// The slot of native check faults (`FaultCause::NonCanonical` and -/// `InvalidOpcode`) whose outcome no [`Check`] names. -pub const CHECK_FAULT_SLOT: usize = FAULT_SLOTS + 2; -/// The slot of System exits at a device site's stub: device accesses the -/// engine completes (`Machine::complete_device_site`), not System -/// instructions. -pub const DEVICE_SITE_SLOT: usize = FAULT_SLOTS + 5; -/// [`StepTiming::exits`]' first [`Check`] slot. -const CHECK_SLOTS: usize = DEVICE_SITE_SLOT + 1; - -/// What the engine found at a native check fault, which takes the fault's -/// slot from [`CHECK_FAULT_SLOT`] ([`Check::slot`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(usize)] -pub enum Check { - /// A tagged address that translates under TBI, run again untagged by a - /// single-instruction block (`Machine::retry_untagged`). - Tagged, - /// An Alignment fault: SP alignment, SCTLR_ELx.A, or an atomic or - /// ordered access crossing its granule. - Alignment, - /// An address outside the native ranges whose translation faults: a - /// Data Abort. - Abort, - /// An untagged address the host does not map natively: the page runs in - /// the translated variant. - Translated, -} - -impl Check { - pub const COUNT: usize = Self::Translated as usize + 1; - - /// Its slot in [`StepTiming::exits`]. - pub const fn slot(self) -> usize { - CHECK_SLOTS + self as usize - } -} - -/// The [`SystemExits`] key of an exit at a device site's stub. No System -/// instruction has this word. -pub const DEVICE_SITE_KEY: u32 = u32::MAX; - -/// The [`SystemExits`] key of the System exit at instruction `word`: the -/// word without the registers it names, so one register's MRS from every -/// Xt counts together. -pub fn system_key(word: u32) -> u32 { - match word >> 24 { - // MRS, MSR, SYS, SYSL, hints and barriers: Rt. - 0xd5 => word & !0x1f, - // Exclusives: Rs, Rt2, Rn and Rt. - 0x08 | 0x48 | 0x88 | 0xc8 => word & !0x001f_7fff, - // LDTR and STTR forms: imm9, Rn and Rt. - 0x38 | 0x78 | 0xb8 | 0xf8 => word & !0x001f_f3ff, - _ => word, - } -} - -/// Whether [`SystemExits`] key `key` is a floating-point exit's word, which -/// the engine charges by the whole word next to the System keys; no System -/// key decodes as numerical FP. -pub fn numerical_key(key: u32) -> bool { - key != DEVICE_SITE_KEY - && matches!( - stela_compiler::aarch64::FloatingPointOperation::decode(key), - Some(Ok(_)) - ) -} - -/// Whether [`SystemExits`] key `key` is a pointer authentication exit's -/// word (an authenticated branch, return or load, or a PAC form a closed -/// key cell sent to the engine), which the report shows apart from the -/// System keys; no System key decodes as one. -pub fn pointer_key(key: u32) -> bool { - key != DEVICE_SITE_KEY - && matches!( - stela_compiler::block::decode_pointer_authentication( - stela_compiler::GuestAddress(0), - register_word(key) - ), - Ok(Some(_)) - ) -} - -/// The word of [`system_key`] `key` with its MRS, MSR, SYS, SYSL or hint -/// Rt set to 31, which the key cleared. -fn register_word(key: u32) -> u32 { - if key >> 24 == 0xd5 { key | 0x1f } else { key } -} - -/// Whether [`system_key`] `key` is a WFE, WFI, WFET or WFIT: of class -/// [`SystemClass::Wait`], found by one decode, without the name -/// [`SystemClass::of`] builds for it. -pub fn wait_key(key: u32) -> bool { - use stela_compiler::aarch64::system::synchronization::{Operation, decode}; - matches!(decode(register_word(key)), Some(Operation::Wait { .. })) -} - -/// A short name of [`system_key`] `key` for reports: the accessor's for -/// MRS, MSR, SYS and SYSL (`MRS_TPIDR_EL1`, `TLBI_VAE1IS`), else the -/// operation's kind and the key (`Exception.ExceptionReturn:0xd69f03e0`). -pub fn system_key_name(key: u32) -> alloc::string::String { - use stela_compiler::aarch64::system::registers::{self, Direction}; - if key == DEVICE_SITE_KEY { - return "device-site".into(); - } - if let Some(Ok(operation)) = stela_compiler::aarch64::FloatingPointOperation::decode(key) { - let debug = alloc::format!("{operation:?}"); - let kind = debug.split(['(', ' ', '{']).next().unwrap_or("FP"); - return alloc::format!("{kind}:{key:#010x}"); - } - if let Ok(Some(instruction)) = stela_compiler::block::decode_pointer_authentication( - stela_compiler::GuestAddress(0), - register_word(key), - ) { - let debug = alloc::format!("{:?}", instruction.operation); - let kind = debug.split(['(', ' ', '{']).next().unwrap_or("PAC"); - return alloc::format!("PAC.{kind}:{key:#010x}"); - } - let word = register_word(key); - let access = registers::decode(word) - .map(|access| (access, true)) - .or_else(|| registers::decode_sys(word).map(|access| (access, false))); - if let Some((access, register)) = access { - let read = access.direction() == Direction::Read; - let encoding = access.encoding(); - if let Some((accessor, _)) = crate::machine::system::Lookup::new().find(encoding, read) { - return accessor - .name - .replace("MSRregister", "MSR") - .replace(' ', "_"); - } - let kind = match (register, read) { - (true, true) => "MRS", - (true, false) => "MSR", - (false, true) => "SYSL", - (false, false) => "SYS", - }; - return alloc::format!( - "{kind}_S{}_{}_C{}_C{}_{}", - encoding.op0(), - encoding.op1(), - encoding.crn(), - encoding.crm(), - encoding.op2() - ); - } - let operation = stela_compiler::block::decode_system_mode_instruction( - stela_compiler::GuestAddress(0), - word, - ) - .ok() - .flatten() - .map(|instruction| alloc::format!("{:?}", instruction.operation)); - let kind = operation - .as_deref() - .and_then(|debug| debug.split([' ', '{', ')']).next()) - .unwrap_or("word") - .trim_end_matches('(') - .replace('(', "."); - alloc::format!("{kind}:{key:#010x}") -} - -/// What a System exit key does, for the per-class totals of `PES SYSTEM`, -/// which leave no key out: device sites; Apple's compression instructions; -/// barriers; TLB and cache maintenance and address translation (TLBI, IC, -/// DC, AT: SYS with CRn 7 or 8); waits (WFE, WFI); the generic timer's -/// registers (CRn 14); implementation-defined registers (CRn 15: Apple's -/// counters, IPIs and controls); the translation controls (SCTLR, CPACR, -/// TTBRn, TCR, MAIR, CONTEXTIDR: CRn 1, 2, 10, 13); exception entries and -/// returns and guarded-level transitions; and everything else. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SystemClass { - Device, - Compression, - Barrier, - Maintenance, - Wait, - Timer, - ImplementationDefined, - TranslationControl, - Transition, - Other, -} - -impl SystemClass { - pub const COUNT: usize = Self::Other as usize + 1; - pub const NAMES: [&'static str; Self::COUNT] = [ - "device", - "compression", - "barrier", - "maintenance", - "wait", - "timer", - "impdef", - "translation", - "transition", - "other", - ]; - - /// The class of System exit key `key`. - pub fn of(key: u32) -> Self { - use stela_compiler::aarch64::system::registers; - if key == DEVICE_SITE_KEY { - return Self::Device; - } - let word = if key >> 24 == 0xd5 { key | 0x1f } else { key }; - if let Some(access) = registers::decode(word) { - let encoding = access.encoding(); - return match (encoding.op0(), encoding.crn()) { - (3, 15) => Self::ImplementationDefined, - (3, 14) => Self::Timer, - (3, 1 | 2 | 10 | 13) => Self::TranslationControl, - _ => Self::Other, - }; - } - if let Some(access) = registers::decode_sys(word) { - return match access.encoding().crn() { - 7 | 8 => Self::Maintenance, - _ => Self::Other, - }; - } - let name = system_key_name(key); - match name.split(['.', ':']).next().unwrap_or_default() { - "Compression" => Self::Compression, - "Synchronization" => Self::Barrier, - "Wait" => Self::Wait, - "Exception" | "Guarded" => Self::Transition, - _ => Self::Other, - } - } -} - -/// One [`SystemExits`] key's exits, the ticks handling them, and how many -/// of them closed every mirror cell (`Machine::derived_changed`), after -/// which each MRS and MSR site exits again once. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct SystemExit { - pub key: u32, - pub count: u64, - pub ticks: u64, - pub closes: u64, -} - -impl SystemExit { - fn add(&mut self, count: u64, ticks: u64, closes: u64) { - self.count += count; - self.ticks += ticks; - self.closes += closes; - } -} - -/// System exits by [`system_key`] since they were last taken, under step -/// timing: an open-addressed table, with the keys past its size in `other`; -/// the device accesses the engine completed; and the floating-point exits -/// by what their completion found ([`FloatingReason`]), in all and by word -/// with their operands ([`FloatingWords`]). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct SystemExits { - pub entries: [SystemExit; SYSTEM_KEYS], - pub other: SystemExit, - pub devices: DeviceExits, - pub floating: [u64; FloatingReason::COUNT], - pub floating_words: FloatingWords, - pub barriers: BarrierWaits, - pub regimes: RegimeSyncs, - /// WKDMC, then WKDMD ([`Compression`]). - pub compression: [Compression; 2], - /// Where sampled System exits' round trips went ([`ExitPaths`]). - pub paths: ExitPaths, -} - -/// The points a traced System exit's round trip passes ([`ExitTrace`]), in -/// order: native code's return in the host, the engine's adoption of what -/// it did, the start and end of the profile's look at the exit's word, the -/// end of the service, of its links and charge, the start and end of the -/// next schedule, the end of the devices' and the fetch's phases, and the -/// host's next entry into native code. -pub const PATH_RETURNED: usize = 0; -pub const PATH_ADOPTED: usize = 1; -pub const PATH_WORD: usize = 2; -pub const PATH_SERVICE: usize = 3; -pub const PATH_SERVED: usize = 4; -pub const PATH_CLOSED: usize = 5; -pub const PATH_SCHEDULE: usize = 6; -pub const PATH_SCHEDULED: usize = 7; -pub const PATH_DEVICES: usize = 8; -pub const PATH_FETCHED: usize = 9; -pub const PATH_ENTERED: usize = 10; -const PATH_POINTS: usize = PATH_ENTERED + 1; - -/// The segments between the [`ExitTrace`] points, as `PES EXIT PATH` names -/// them. -pub const PATH_SEGMENTS: usize = PATH_POINTS - 1; -pub const PATH_NAMES: [&str; PATH_SEGMENTS] = [ - "back", "prelude", "word", "service", "close", "loop", "schedule", "devices", "fetch", "enter", -]; - -/// One System exit in this many is traced: a few hundred cycles of stamps -/// on one in 64 keep the trace's cost far below the step timing's own. -pub const PATH_EVERY: u32 = 64; - -/// Sampled System exits' round trips under step timing, from native code's -/// return to its next entry, by segment ([`PATH_NAMES`]): the exits traced -/// and those whose trace another path ended first (an interrupt taken, an -/// exception, the run loop left); within the traced services, the host's -/// regime syncs and prediction isolations; and every change of derived -/// state that closed every mirror cell, with the open cells it closed, each -/// of which costs an exit to open again where code reaches it; and the TCR -/// writes that kept them (`Machine::layout_written`), with the open cells -/// they kept; and the System exits after which the run loop fetched at once -/// (`Machine::continues_directly`), traced or not. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct ExitPaths { - pub traced: u64, - pub abandoned: u64, - pub ticks: [u64; PATH_SEGMENTS], - pub syncs: u64, - pub sync_ticks: u64, - pub isolations: u64, - pub isolation_ticks: u64, - pub closes: u64, - pub cells_closed: u64, - pub layouts: u64, - pub cells_kept: u64, - pub direct: u64, -} - -impl ExitPaths { - /// Add everything `other` counts. - pub fn merge(&mut self, other: &Self) { - self.traced += other.traced; - self.abandoned += other.abandoned; - for (ticks, more) in self.ticks.iter_mut().zip(other.ticks) { - *ticks += more; - } - self.syncs += other.syncs; - self.sync_ticks += other.sync_ticks; - self.isolations += other.isolations; - self.isolation_ticks += other.isolation_ticks; - self.closes += other.closes; - self.cells_closed += other.cells_closed; - self.layouts += other.layouts; - self.cells_kept += other.cells_kept; - self.direct += other.direct; - } -} - -/// The System exit being traced on a PE, if any: the profile ticks at each -/// point it passed ([`PATH_RETURNED`] and on), the next point it expects, -/// and the syncs its service made. A point out of order abandons it, as -/// does leaving the run loop; the next native entry folds it into -/// [`ExitPaths`]. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct ExitTrace { - countdown: u32, - next: usize, - stamps: [u64; PATH_POINTS], - syncs: [u64; 4], -} - -impl ExitTrace { - /// Whether the next System exit is one to trace. - #[inline] - pub fn due(&mut self) -> bool { - if self.countdown != 0 { - self.countdown -= 1; - return false; - } - true - } - - /// Trace the System exit native code returned for at `returned` (the - /// host's ticks, 0 where it keeps none), which the engine adopted by - /// `adopted`, its word looked at from `now`. - pub fn begin(&mut self, returned: u64, adopted: u64, now: u64) { - self.countdown = PATH_EVERY - 1; - let returned = if returned == 0 || returned > adopted { - adopted - } else { - returned - }; - self.stamps[PATH_RETURNED] = returned; - self.stamps[PATH_ADOPTED] = adopted; - self.stamps[PATH_WORD] = now; - self.syncs = [0; 4]; - self.next = PATH_SERVICE; - } - - /// Drop the exit begun, which is not one to trace (a wait, a device - /// site): the next System exit is traced instead. - pub fn cancel(&mut self) { - self.next = 0; - self.countdown = 0; - } - - #[inline] - pub fn open(&self) -> bool { - self.next != 0 - } - - /// Whether the traced exit's service runs. - #[inline] - pub fn in_service(&self) -> bool { - self.next == PATH_SERVED - } - - /// The trace reached `point` at `now`; out of order, it is abandoned. - pub fn stamp(&mut self, point: usize, now: u64, paths: &mut ExitPaths) { - if self.next == 0 { - return; - } - if self.next != point { - return self.abandon(paths); - } - self.stamps[point] = now; - self.next = point + 1; - } - - /// End the trace without a sample. - pub fn abandon(&mut self, paths: &mut ExitPaths) { - if self.next != 0 { - self.next = 0; - paths.abandoned += 1; - } - } - - /// The service synchronized the host's regime in `ticks`, and isolated - /// its predictions in `isolated`'s. - pub fn sync(&mut self, ticks: u64, isolated: Option) { - self.syncs[0] += 1; - self.syncs[1] += ticks; - if let Some(isolated) = isolated { - self.syncs[2] += 1; - self.syncs[3] += isolated; - } - } - - /// Native code was entered again at `entered` (the host's ticks, 0 - /// where it keeps none): the trace ends and its segments count. - pub fn finish(&mut self, entered: u64, paths: &mut ExitPaths) { - if self.next == 0 { - return; - } - if self.next != PATH_ENTERED { - return self.abandon(paths); - } - let fetched = self.stamps[PATH_FETCHED]; - self.stamps[PATH_ENTERED] = if entered < fetched { fetched } else { entered }; - for (segment, ticks) in paths.ticks.iter_mut().enumerate() { - *ticks += self.stamps[segment + 1].saturating_sub(self.stamps[segment]); - } - paths.traced += 1; - paths.syncs += self.syncs[0]; - paths.sync_ticks += self.syncs[1]; - paths.isolations += self.syncs[2]; - paths.isolation_ticks += self.syncs[3]; - self.next = 0; - } -} - -/// The host's regime changes ([`super::Host::set_regime`]) and prediction -/// isolations ([`super::Host::isolate_predictions`]) under step timing: how -/// many and their profile ticks. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct RegimeSyncs { - pub syncs: u64, - pub sync_ticks: u64, - pub isolations: u64, - pub isolation_ticks: u64, - /// The syncs that gave the host the regime it had and isolated nothing. - pub unchanged: u64, - /// The syncs by what asked for them ([`SyncSource`]). - pub sources: [u64; SyncSource::COUNT], -} - -/// What asked for a regime sync ([`RegimeSyncs::sources`]): a PAN change by -/// MSR in the engine, a PAN change native code made, a translation change -/// (an SPRR_PERM write and others), a TTBR0 write, an exception entry or -/// return or GXF transition the engine made, a change of derived state, and -/// anything else. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SyncSource { - Pan, - NativePan, - Translation, - TableBase, - Transition, - Derived, - Other, -} - -impl SyncSource { - pub const COUNT: usize = Self::Other as usize + 1; - pub const NAMES: [&str; Self::COUNT] = [ - "pan", - "native_pan", - "translation", - "table_base", - "transition", - "derived", - "other", - ]; -} - -impl RegimeSyncs { - /// Add every change `other` counts. - pub fn merge(&mut self, other: &Self) { - self.syncs += other.syncs; - self.sync_ticks += other.sync_ticks; - self.isolations += other.isolations; - self.isolation_ticks += other.isolation_ticks; - self.unchanged += other.unchanged; - for (count, more) in self.sources.iter_mut().zip(other.sources) { - *count += more; - } - } -} - -/// The [`BarrierWaits`] blocker of a PE in native code. -pub const BLOCKER_NATIVE: u64 = 1; -/// The [`BarrierWaits`] blocker of a PE that entered a fetched block and -/// prepares its native run, or takes the fetch's exception or checked -/// instruction. -pub const BLOCKER_ENTERING: u64 = 2; -/// The [`BarrierWaits`] blocker of a PE whose native run returned, before -/// it knows the exit. -pub const BLOCKER_RETURNED: u64 = 3; -/// Bit 63 of a blocker: a PE completing an exit of the slot in bits 32-62 -/// at the [`system_key`] in bits 0-31 (0 where the exit has no word). -pub const BLOCKER_EXIT: u64 = 1 << 63; -/// The blockers [`BarrierWaits`] holds apart. -pub const BARRIER_BLOCKERS: usize = 32; - -/// The blocker of PE in an exit of `slot` at `word`. -pub fn exit_blocker(slot: usize, word: Option) -> u64 { - BLOCKER_EXIT | (slot as u64) << 32 | u64::from(word.map_or(0, system_key)) -} - -/// The waits for one blocker: how many and their ticks. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct BarrierBlocker { - pub key: u64, - pub count: u64, - pub ticks: u64, -} - -/// DSBs that completed maintenance this PE posted, under step timing: how -/// many, those that found every PE had applied it at the first look -/// (`quick`), and the profile ticks they spent; and by the last PE they -/// waited for, what that PE was doing when last seen (its blocker: native -/// code, [`BLOCKER_NATIVE`], or an exit, [`exit_blocker`]), with the rest in -/// `other`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct BarrierWaits { - pub waits: u64, - pub quick: u64, - pub ticks: u64, - pub blockers: [BarrierBlocker; BARRIER_BLOCKERS], - pub other: BarrierBlocker, -} - -impl Default for BarrierWaits { - fn default() -> Self { - Self { - waits: 0, - quick: 0, - ticks: 0, - blockers: [BarrierBlocker::default(); BARRIER_BLOCKERS], - other: BarrierBlocker::default(), - } - } -} - -impl BarrierWaits { - /// Count a wait of `ticks`: one that waited for a PE last seen at - /// `blocker`, or `None` when none was waited for. - pub fn add(&mut self, blocker: Option, ticks: u64) { - self.waits += 1; - self.ticks += ticks; - match blocker { - None => self.quick += 1, - Some(key) => self.add_blocker(key, 1, ticks), - } - } - - fn add_blocker(&mut self, key: u64, count: u64, ticks: u64) { - let entry = match self - .blockers - .iter() - .position(|entry| entry.count == 0 || entry.key == key) - { - Some(index) => &mut self.blockers[index], - None => &mut self.other, - }; - if entry.count == 0 { - entry.key = key; - } - entry.count += count; - entry.ticks += ticks; - } - - /// Add every wait `other` counts. - pub fn merge(&mut self, other: &Self) { - self.waits += other.waits; - self.quick += other.quick; - self.ticks += other.ticks; - for entry in other.blockers.iter().filter(|entry| entry.count != 0) { - self.add_blocker(entry.key, entry.count, entry.ticks); - } - self.other.count += other.other.count; - self.other.ticks += other.other.ticks; - } -} - -/// WKDMC or WKDMD instructions the engine completed under step timing, and -/// the ticks of their handling split: the whole handler; reading the source -/// through translated guest memory; the codec; and writing the destination -/// (the host's publication of the bytes into guest RAM). The rest of the -/// handler is translation checks and the result; the rest of the exit, in -/// `SYSTEM WORDS`, is leaving and entering the guest. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Compression { - pub count: u64, - pub whole: u64, - pub read: u64, - pub codec: u64, - pub write: u64, -} - -impl Compression { - /// Count one of `whole` ticks: `parts` are its read, codec and write. - pub fn add(&mut self, whole: u64, parts: [u64; 3]) { - self.count += 1; - self.whole += whole; - self.read += parts[0]; - self.codec += parts[1]; - self.write += parts[2]; - } - - fn merge(&mut self, other: &Self) { - self.count += other.count; - self.whole += other.whole; - self.read += other.read; - self.codec += other.codec; - self.write += other.write; - } -} - -/// What the software completion of a floating-point exit found, which names -/// the guard that sent it there: an enabled trap (FPCR's enables, which every -/// recipe sends to the helper), the first fresh FPSR flag in Arm's order -/// (invalid: NaN or invalid operation; divide by zero; overflow; underflow: a -/// tiny result; input denormal flushed), inexact alone, no flag (exact: a -/// signed zero, an infinity, a quiet NaN, a subnormal input or result that -/// was exact, or a form without an inline recipe), and apart from those, how -/// many ran with FZ, FZ16, FIZ, AH or DN set (`Mode`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FloatingReason { - Trap, - Invalid, - Divide, - Overflow, - Underflow, - Denormal, - Inexact, - Exact, - Mode, -} - -impl FloatingReason { - pub const COUNT: usize = Self::Mode as usize + 1; - pub const NAMES: [&'static str; Self::COUNT] = [ - "trap", - "invalid", - "divide", - "overflow", - "underflow", - "denormal", - "inexact", - "exact", - "mode", - ]; - - /// The reason of a completion with fresh cumulative flags `fresh` - /// (FPSR's bit layout) that trapped (`trapped`) or not under `fpcr`. - pub fn of(fpcr: u32, fresh: u32, trapped: bool) -> Self { - use stela_compiler::aarch64::floating::FPCR_EXCEPTION_ENABLE_MASK; - const FLAGS: [(u32, FloatingReason); 6] = [ - (1 << 0, FloatingReason::Invalid), - (1 << 1, FloatingReason::Divide), - (1 << 2, FloatingReason::Overflow), - (1 << 3, FloatingReason::Underflow), - (1 << 7, FloatingReason::Denormal), - (1 << 4, FloatingReason::Inexact), - ]; - if trapped || fpcr & FPCR_EXCEPTION_ENABLE_MASK != 0 { - return Self::Trap; - } - FLAGS - .iter() - .find(|(flag, _)| fresh & flag != 0) - .map_or(Self::Exact, |&(_, reason)| reason) - } - - /// Whether `fpcr` selects a flushing or alternative mode. - pub fn moded(fpcr: u32) -> bool { - use stela_compiler::aarch64::floating::{FPCR_AH, FPCR_DN, FPCR_FIZ, FPCR_FZ, FPCR_FZ16}; - fpcr & (FPCR_FZ | FPCR_FZ16 | FPCR_FIZ | FPCR_AH | FPCR_DN) != 0 - } -} - -/// What the operands of a floating-point exit held, which names the recipe -/// guard that sent it to the engine where its flags do not (a subnormal -/// input raises no flag with FZ clear, a quiet NaN none at all): a NaN, a -/// subnormal, a zero or an infinity in an active source lane; a nonzero -/// result lane below twice the minimum normal (`Tiny`, which recipes leave -/// to the engine in case it was tiny before rounding); none of those -/// (`Ordinary`); and a form whose lanes [`census_lanes`] does not read -/// (`Unread`). An exit counts in every class its operands show. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Operands { - Nan, - Subnormal, - Zero, - Infinite, - Tiny, - Ordinary, - Unread, -} - -impl Operands { - pub const COUNT: usize = Self::Unread as usize + 1; - pub const NAMES: [&'static str; Self::COUNT] = [ - "nan", - "subnormal", - "zero", - "infinite", - "tiny", - "ordinary", - "unread", - ]; - - const fn bit(self) -> u8 { - 1 << self as u8 - } -} - -/// A register the census reads: its lanes, from one lane alone when -/// indexed. -#[derive(Debug, Clone, Copy)] -struct CensusRegister { - register: u8, - lane: Option, - lanes: u32, -} - -impl CensusRegister { - const fn whole(register: u8, lanes: u32) -> Self { - Self { - register, - lane: None, - lanes, - } - } -} - -/// The lanes of an operation the census reads: its format, up to three -/// sources and the result. -#[derive(Debug, Clone, Copy)] -struct CensusLanes { - format: stela_compiler::aarch64::floating::Format, - sources: [Option; 3], - result: CensusRegister, -} - -/// The lanes [`Operands`] classifies for the families with the most exits -/// (fused, binary arithmetic, min/max, estimates, roots and rounding); none -/// for the rest, which count as [`Operands::Unread`]. -fn census_lanes( - operation: &stela_compiler::aarch64::FloatingPointOperation, -) -> Option { - use stela_compiler::aarch64::{ - FloatingPointOperation as Operation, - simd::{arithmetic::Inputs, estimate::Kind, minmax}, - }; - let whole = CensusRegister::whole; - let lanes = - |format, shape: stela_compiler::aarch64::simd::arithmetic::Shape| shape.lane_count(format); - Some(match operation { - Operation::Fused(operand) => { - let count = lanes(operand.format, operand.shape); - CensusLanes { - format: operand.format, - sources: [ - Some(whole(operand.left, count)), - Some(CensusRegister { - register: operand.right, - lane: operand.right_lane, - lanes: count, - }), - Some(whole(operand.addend, count)), - ], - result: whole(operand.destination, count), - } - } - Operation::Binary(operand) => { - let count = lanes(operand.format, operand.shape); - let (left, right) = match operand.inputs { - Inputs::Elementwise { left, right } | Inputs::Pairwise { left, right } => { - (whole(left, count), Some(whole(right, count))) - } - Inputs::Indexed { - left, - right, - right_lane, - } => ( - whole(left, count), - Some(CensusRegister { - register: right, - lane: Some(right_lane), - lanes: count, - }), - ), - Inputs::PairwiseScalar { source } => (whole(source, 2), None), - }; - CensusLanes { - format: operand.format, - sources: [Some(left), right, None], - result: whole(operand.destination, count), - } - } - Operation::MinMax(operand) => match *operand { - minmax::Operand::Binary { - format, - shape, - destination, - left, - right, - .. - } => { - let count = lanes(format, shape); - CensusLanes { - format, - sources: [Some(whole(left, count)), Some(whole(right, count)), None], - result: whole(destination, count), - } - } - minmax::Operand::PairwiseScalar { - format, - destination, - source, - .. - } => CensusLanes { - format, - sources: [Some(whole(source, 2)), None, None], - result: whole(destination, 1), - }, - minmax::Operand::Reduction { - format, - shape, - destination, - source, - .. - } => CensusLanes { - format, - sources: [Some(whole(source, lanes(format, shape))), None, None], - result: whole(destination, 1), - }, - }, - Operation::Estimate(operand) - if !matches!( - operand.kind, - Kind::UnsignedReciprocal | Kind::UnsignedReciprocalSquareRoot - ) => - { - let count = lanes(operand.format, operand.shape); - CensusLanes { - format: operand.format, - sources: [Some(whole(operand.source, count)), None, None], - result: whole(operand.destination, count), - } - } - Operation::SquareRoot(operand) => { - let count = lanes(operand.format, operand.shape); - CensusLanes { - format: operand.format, - sources: [Some(whole(operand.source, count)), None, None], - result: whole(operand.destination, count), - } - } - Operation::Rounding(operand) => { - let count = lanes(operand.format, operand.shape); - CensusLanes { - format: operand.format, - sources: [Some(whole(operand.source, count)), None, None], - result: whole(operand.destination, count), - } - } - _ => return None, - }) -} - -/// The lane `lane` of `format` in vector `vector`. -fn census_lane( - vector: &[u64; 2], - format: stela_compiler::aarch64::floating::Format, - lane: u32, -) -> u64 { - let bits = format.bits(); - let offset = lane * bits; - let word = vector[(offset / u64::BITS) as usize] >> (offset % u64::BITS); - word & (u64::MAX >> (u64::BITS - bits)) -} - -/// The exponent field and the fraction of `format` value `bits`, and the -/// field's all-ones value. -fn census_fields(bits: u64, format: stela_compiler::aarch64::floating::Format) -> (u64, u64, u64) { - use stela_compiler::aarch64::floating::Format; - let (exponent_bits, fraction_bits) = match format { - Format::Half => (5, 10), - Format::Single => (8, 23), - Format::Double => (11, 52), - }; - let maximum = (1 << exponent_bits) - 1; - ( - (bits >> fraction_bits) & maximum, - bits & ((1 << fraction_bits) - 1), - maximum, - ) -} - -/// The operand census of one floating-point exit: what its sources held -/// before the completion ([`FloatingCensus::read`]), then what its result -/// held after it ([`FloatingCensus::finish`]). -#[derive(Debug, Clone, Copy)] -pub struct FloatingCensus { - lanes: Option, - classes: u8, -} - -impl FloatingCensus { - /// Classify the active source lanes of `operation` in `state`. - pub fn read( - state: &stela_compiler::GuestState, - operation: &stela_compiler::aarch64::FloatingPointOperation, - ) -> Self { - let lanes = census_lanes(operation); - let mut classes = 0; - let sources = lanes.iter().flat_map(|lanes| { - lanes - .sources - .iter() - .flatten() - .map(move |source| (lanes.format, source)) - }); - for (format, source) in sources { - let vector = &state.v[usize::from(source.register & 31)]; - for lane in 0..source.lanes { - let bits = census_lane(vector, format, source.lane.map_or(lane, u32::from)); - let (exponent, fraction, maximum) = census_fields(bits, format); - classes |= match (exponent, fraction == 0) { - (0, true) => Operands::Zero.bit(), - (0, false) => Operands::Subnormal.bit(), - (e, true) if e == maximum => Operands::Infinite.bit(), - (e, false) if e == maximum => Operands::Nan.bit(), - _ => 0, - }; - } - } - Self { lanes, classes } - } - - /// Add the classes of the result lanes in `state` (none when the - /// completion trapped and wrote no result), and return every class - /// seen as [`Operands`] bits. - pub fn finish(self, state: &stela_compiler::GuestState, completed: bool) -> u8 { - let Some(lanes) = self.lanes else { - return Operands::Unread.bit(); - }; - let mut classes = self.classes; - if completed { - let result = lanes.result; - let vector = &state.v[usize::from(result.register & 31)]; - for lane in 0..result.lanes { - let bits = census_lane(vector, lanes.format, lane); - let (exponent, fraction, maximum) = census_fields(bits, lanes.format); - if exponent < 2 && (exponent != 0 || fraction != 0) && exponent != maximum { - classes |= Operands::Tiny.bit(); - } - } - } - const DATA: u8 = Operands::Nan.bit() | Operands::Subnormal.bit() | Operands::Tiny.bit(); - if classes & DATA == 0 { - classes |= Operands::Ordinary.bit(); - } - classes - } -} - -/// One floating-point exit word's exits since they were last taken, by -/// [`FloatingReason`] (the `Mode` count apart from the others), by the -/// [`Operands`] classes they showed, and how many found FPSR.IXC clear, -/// where no sticky-inexact path runs. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct FloatingWord { - pub key: u32, - pub reasons: [u32; FloatingReason::COUNT], - pub operands: [u32; Operands::COUNT], - pub inexact_clear: u32, -} - -impl FloatingWord { - /// Its exits: every reason but `Mode`, which they also count in. - pub fn count(&self) -> u64 { - self.reasons[..FloatingReason::Mode as usize] - .iter() - .map(|&count| u64::from(count)) - .sum() - } - - /// Add every exit `other` counts. - pub fn merge(&mut self, other: &Self) { - for (count, more) in self.reasons.iter_mut().zip(other.reasons) { - *count = count.saturating_add(more); - } - for (count, more) in self.operands.iter_mut().zip(other.operands) { - *count = count.saturating_add(more); - } - self.inexact_clear = self.inexact_clear.saturating_add(other.inexact_clear); - } -} - -/// The words [`FloatingWords`] holds apart: a beat's floating-point exits -/// have reached about 240 words machine-wide. -pub const FLOATING_WORDS: usize = 256; - -/// Floating-point exits by word with their causes ([`FloatingWord`]), -/// under step timing: an open-addressed table, with the words past its -/// size in `other`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct FloatingWords { - pub entries: [FloatingWord; FLOATING_WORDS], - pub other: FloatingWord, -} - -impl Default for FloatingWords { - fn default() -> Self { - Self { - entries: [FloatingWord::default(); FLOATING_WORDS], - other: FloatingWord::default(), - } - } -} - -impl FloatingWords { - /// The entry of `key`, or `other` once the table is full. - fn entry(&mut self, key: u32) -> &mut FloatingWord { - let start = - (key.wrapping_mul(0x9e37_79b9) >> (u32::BITS - FLOATING_WORDS.ilog2())) as usize; - let found = (0..FLOATING_WORDS) - .map(|probe| (start + probe) % FLOATING_WORDS) - .find(|&index| { - let entry = &self.entries[index]; - entry.key == key || entry.count() == 0 - }); - match found { - Some(index) => { - let entry = &mut self.entries[index]; - entry.key = key; - entry - } - None => &mut self.other, - } - } - - /// Count one exit of `key` for `reason`, in `Mode` too if `moded`, - /// with [`Operands`] bits `operands`, that found FPSR.IXC clear if - /// `inexact_clear`. - pub fn add( - &mut self, - key: u32, - reason: FloatingReason, - moded: bool, - operands: u8, - inexact_clear: bool, - ) { - let entry = self.entry(key); - entry.reasons[reason as usize] = entry.reasons[reason as usize].saturating_add(1); - if moded { - let mode = &mut entry.reasons[FloatingReason::Mode as usize]; - *mode = mode.saturating_add(1); - } - for (class, count) in entry.operands.iter_mut().enumerate() { - if operands & (1 << class) != 0 { - *count = count.saturating_add(1); - } - } - entry.inexact_clear = entry.inexact_clear.saturating_add(u32::from(inexact_clear)); - } - - /// Add every exit `words` counts. - pub fn merge(&mut self, words: &Self) { - for word in words.counted() { - self.entry(word.key).merge(word); - } - self.other.merge(&words.other); - } - - /// The words with exits. - pub fn counted(&self) -> impl Iterator { - self.entries.iter().filter(|word| word.count() != 0) - } - - pub fn is_empty(&self) -> bool { - self.other.count() == 0 && self.counted().next().is_none() - } -} - -/// The keys [`SystemExits`] holds apart. The report merges every PE's into -/// one table each beat, and a process spawn alone exits on well over 128 -/// keys machine-wide: with 128 the costliest of them landed in `other` -/// (12-18 ms of exit time per spawn, unnamed). -pub const SYSTEM_KEYS: usize = 512; - -impl Default for SystemExits { - fn default() -> Self { - Self { - entries: [SystemExit::default(); SYSTEM_KEYS], - other: SystemExit::default(), - devices: DeviceExits::default(), - floating: [0; FloatingReason::COUNT], - floating_words: FloatingWords::default(), - barriers: BarrierWaits::default(), - regimes: RegimeSyncs::default(), - compression: [Compression::default(); 2], - paths: ExitPaths::default(), - } - } -} - -impl SystemExits { - /// Count `count` exits of `key` that took `ticks` and closed the cells - /// `closes` times. - pub fn add(&mut self, key: u32, count: u64, ticks: u64, closes: u64) { - let start = (key.wrapping_mul(0x9e37_79b9) >> (u32::BITS - SYSTEM_KEYS.ilog2())) as usize; - for probe in 0..SYSTEM_KEYS { - let entry = &mut self.entries[(start + probe) % SYSTEM_KEYS]; - if entry.count == 0 { - entry.key = key; - } - if entry.key == key { - return entry.add(count, ticks, closes); - } - } - self.other.add(count, ticks, closes); - } - - /// Add every exit `exits` counts. - pub fn merge(&mut self, exits: &Self) { - for entry in exits.entries.iter().filter(|entry| entry.count != 0) { - self.add(entry.key, entry.count, entry.ticks, entry.closes); - } - let other = exits.other; - self.other.add(other.count, other.ticks, other.closes); - self.devices.merge(&exits.devices); - for (count, more) in self.floating.iter_mut().zip(exits.floating) { - *count += more; - } - self.floating_words.merge(&exits.floating_words); - self.barriers.merge(&exits.barriers); - self.regimes.merge(&exits.regimes); - for (compression, other) in self.compression.iter_mut().zip(&exits.compression) { - compression.merge(other); - } - self.paths.merge(&exits.paths); - } - - /// The keys with exits. - pub fn counted(&self) -> impl Iterator { - self.entries.iter().filter(|entry| entry.count != 0) - } - - pub fn is_empty(&self) -> bool { - self.other.count == 0 - && self.counted().next().is_none() - && self.devices.is_empty() - && self.floating.iter().all(|&count| count == 0) - && self.floating_words.is_empty() - && self.barriers.waits == 0 - && self.regimes == RegimeSyncs::default() - && self.paths == ExitPaths::default() - && self - .compression - .iter() - .all(|compression| compression.count == 0) - } -} - -/// The 4 KiB page of a device register, as [`DeviceExits`] keys it. -pub fn device_page(physical: u64) -> u32 { - (physical >> 12) as u32 -} - -/// One device page's accesses, the ticks handling them, and the host -/// counter ticks of those spent waiting for the board's lock. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DeviceExit { - pub page: u32, - pub count: u64, - pub ticks: u64, - pub waited: u64, -} - -impl DeviceExit { - fn add(&mut self, count: u64, ticks: u64, waited: u64) { - self.count += count; - self.ticks += ticks; - self.waited += waited; - } -} - -/// The device pages [`DeviceExits`] holds apart. -pub const DEVICE_PAGES: usize = 64; - -/// One device register's reads or writes the engine completed, with -/// [`DeviceExit`]'s counts: `register` its physical address, with -/// [`DEVICE_REGISTER_WRITE`] set for writes, whose ticks also split as -/// [`DeviceWrites`]' do into the access and the settle after it, and the -/// settle's transfer and deferred copies; `longest` is the longest exit, -/// which tells a few long exits (a preempted host thread) from many. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DeviceRegisterExit { - pub register: u64, - pub count: u64, - pub ticks: u64, - pub waited: u64, - pub access: u64, - pub settle: u64, - pub transfer: u64, - pub copies: u64, - pub released: u64, - pub longest: u64, -} - -impl DeviceRegisterExit { - fn add(&mut self, other: &Self) { - self.count += other.count; - self.ticks += other.ticks; - self.waited += other.waited; - self.access += other.access; - self.settle += other.settle; - self.transfer += other.transfer; - self.copies += other.copies; - self.released += other.released; - self.longest = self.longest.max(other.longest); - } -} - -/// The parts a device write's exit is timed in: its access, its settle, -/// its gate call, and of the settle the transfer under the devices' lock, -/// the deferred DMA copies after the lock's release and the host work the -/// release did on the writing core, in the board counter's ticks as a lock -/// wait is ([`DeviceWrites::add`]). -pub const WRITE_PARTS: usize = 6; - -/// The bit of [`DeviceRegisterExit::register`] that says writes: physical -/// addresses never reach it. -pub const DEVICE_REGISTER_WRITE: u64 = 1 << 63; - -/// The registers and directions [`DeviceExits`] holds apart. -pub const DEVICE_REGISTERS: usize = 128; - -/// Device writes the engine completed, and the ticks of their exits split: -/// the whole exit; the access, up to the model's write done (the devices' -/// lock and the write); the settle after it (in the same locked call every -/// master's transfer, then the release: the PEs it woke, the publication, -/// the deferred copies and the host work after); and a gate call it made -/// ([`super::Devices::write_settled`]). The rest of the exit is the -/// engine's own: leaving and entering the guest, decode, routing and -/// watching. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DeviceWrites { - pub count: u64, - pub exit: u64, - pub access: u64, - pub settle: u64, - pub call: u64, - pub transfer: u64, - pub copies: u64, - pub released: u64, -} - -impl DeviceWrites { - pub fn add(&mut self, exit: u64, parts: [u64; WRITE_PARTS]) { - self.count += 1; - self.exit += exit; - self.access += parts[0]; - self.settle += parts[1]; - self.call += parts[2]; - self.transfer += parts[3]; - self.copies += parts[4]; - self.released += parts[5]; - } - - fn merge(&mut self, other: &Self) { - self.count += other.count; - self.exit += other.exit; - self.access += other.access; - self.settle += other.settle; - self.call += other.call; - self.transfer += other.transfer; - self.copies += other.copies; - self.released += other.released; - } -} - -/// Device accesses the engine completed, from native faults and device -/// sites, by [`device_page`], under step timing: an open-addressed table, -/// with the pages past its size in `other`; and the accesses forwarded to -/// the home machine, with the ticks their PEs waited for its answers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DeviceExits { - pub entries: [DeviceExit; DEVICE_PAGES], - pub other: DeviceExit, - pub forwarded: u64, - pub forwarded_ticks: u64, - pub writes: DeviceWrites, - /// The same accesses by register and direction, an open-addressed - /// table too, with the rest in `other_registers`. - pub registers: [DeviceRegisterExit; DEVICE_REGISTERS], - pub other_registers: DeviceRegisterExit, -} - -impl Default for DeviceExits { - fn default() -> Self { - Self { - entries: [DeviceExit::default(); DEVICE_PAGES], - other: DeviceExit::default(), - forwarded: 0, - forwarded_ticks: 0, - writes: DeviceWrites::default(), - registers: [DeviceRegisterExit::default(); DEVICE_REGISTERS], - other_registers: DeviceRegisterExit::default(), - } - } -} - -impl DeviceExits { - /// Count `count` accesses of `page` that took `ticks`, `waited` of them - /// in host counter ticks waiting for the board's lock. - pub fn add(&mut self, page: u32, count: u64, ticks: u64, waited: u64) { - let start = (page.wrapping_mul(0x9e37_79b9) >> (u32::BITS - DEVICE_PAGES.ilog2())) as usize; - for probe in 0..DEVICE_PAGES { - let entry = &mut self.entries[(start + probe) % DEVICE_PAGES]; - if entry.count == 0 { - entry.page = page; - } - if entry.page == page { - return entry.add(count, ticks, waited); - } - } - self.other.add(count, ticks, waited); - } - - /// Count the accesses `exit` holds of its register as [`Self::add`] - /// counts its page's. - pub fn add_register(&mut self, exit: DeviceRegisterExit) { - let register = exit.register; - let hash = (register ^ register >> 32).wrapping_mul(0x9e37_79b9_7f4a_7c15); - let start = (hash >> (u64::BITS - DEVICE_REGISTERS.ilog2())) as usize; - for probe in 0..DEVICE_REGISTERS { - let entry = &mut self.registers[(start + probe) % DEVICE_REGISTERS]; - if entry.count == 0 { - entry.register = register; - } - if entry.register == register { - return entry.add(&exit); - } - } - self.other_registers.add(&exit); - } - - /// The registers with accesses. - pub fn counted_registers(&self) -> impl Iterator { - self.registers.iter().filter(|entry| entry.count != 0) - } - - pub fn merge(&mut self, exits: &Self) { - for entry in exits.counted() { - self.add(entry.page, entry.count, entry.ticks, entry.waited); - } - for entry in exits.counted_registers() { - self.add_register(*entry); - } - self.other_registers.add(&exits.other_registers); - let other = exits.other; - self.other.add(other.count, other.ticks, other.waited); - self.forwarded += exits.forwarded; - self.forwarded_ticks += exits.forwarded_ticks; - self.writes.merge(&exits.writes); - } - - /// The pages with accesses. - pub fn counted(&self) -> impl Iterator { - self.entries.iter().filter(|entry| entry.count != 0) - } - - pub fn is_empty(&self) -> bool { - self.other.count == 0 && self.forwarded == 0 && self.counted().next().is_none() - } -} - -/// A native fault's slot in [`StepTiming::exits`], by cause: the guest's -/// translation, a device, a native check, a watched or tag-checked page, -/// or translation the engine does not implement. -pub fn fault_slot(cause: &super::FaultCause) -> usize { - use super::FaultCause; - FAULT_SLOTS - + match cause { - FaultCause::Guest(_) => 0, - FaultCause::Device { .. } => DEVICE_FAULT_SLOT - FAULT_SLOTS, - FaultCause::NonCanonical | FaultCause::InvalidOpcode => CHECK_FAULT_SLOT - FAULT_SLOTS, - FaultCause::Watched | FaultCause::TagChecked => 3, - FaultCause::Translation(_) => 4, - } -} - -/// One completed phase's largest observed profile-clock interval. -/// -/// The CPU fields are a materialized snapshot after the phase, not a precise -/// fault PC or an attribution to one guest instruction. Fetch includes finding, -/// compiling and installing code; every phase can include host descheduling. -/// These observations are diagnostics, never architectural latency bounds. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Maximum { - pub ticks: u64, - /// The same profile-clock sample used to close this interval. - pub finished_ticks: u64, - pub pc_after: u64, - pub el_after: u8, - pub daif_after: u8, -} - -impl Maximum { - #[inline] - pub(super) fn observe( - &mut self, - ticks: u64, - finished_ticks: u64, - pc_after: u64, - el_after: u8, - daif_after: u8, - ) { - if ticks > self.ticks { - *self = Self { - ticks, - finished_ticks, - pc_after, - el_after, - daif_after, - }; - } - } -} - -/// The guest states [`Levels::ticks`] splits busy time by. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(usize)] -pub enum Level { - /// EL0. - User, - /// EL1 or EL2 outside guarded mode. - Kernel, - /// Apple GXF guarded mode at any level. - Guarded, -} - -impl Level { - pub const COUNT: usize = Self::Guarded as usize + 1; - - pub fn of(el: u8, guarded: bool) -> Self { - match (guarded, el) { - (true, _) => Self::Guarded, - (false, 0) => Self::User, - (false, _) => Self::Kernel, - } - } -} - -/// Where native code was when a sampled run's transfer budget ran out, under -/// step timing (`Machine::execute`): one run in [`HOT_SAMPLE_EVERY`] gets a -/// budget drawn uniformly from 1..=[`HOT_SAMPLE_SPAN`], so a run of `n` -/// transfers is sampled with a chance in proportion to `n` and at a uniformly -/// chosen one of them: each transfer of native code is equally likely to be -/// the sample, which ranks blocks by the native work in them rather than by -/// where they exit. A sample is the entered block's guest PC and [`Level`]. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct HotBlocks { - /// Open-addressed `(pc, level, count)` entries, [`HOT_BLOCKS`] of them - /// once the first sample is added; samples past them are in `other`. - pub entries: alloc::vec::Vec, - /// Samples by [`Level`], and those that found the table full. - pub samples: [u64; Level::COUNT], - pub other: u64, - /// The samples that were a block's RET, BLR or BR form's transfer, at - /// most [`DYNAMIC_SAMPLES`]; those past them are in `dynamic_other`. - pub dynamic: alloc::vec::Vec, - pub dynamic_other: u64, - /// The same samples by guest address space ([`AsidSamples`]). - pub asids: AsidSamples, -} - -/// [`HotBlocks`]' samples by the ASID the PE's translations were tagged with -/// at each one (`Machine::current_space_asid`), at any level: a user thread's system calls and faults count with -/// its process, as the guest's own CPU time does, and kernel threads with -/// the kernel's address space. Each address space's samples by [`Level`], -/// and its EL0 blocks apart, so the PCs name the process (its frameworks) -/// for an ASID the host cannot map to a process name. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct AsidSamples { - /// Open-addressed address spaces, [`ASID_SLOTS`] once the first sample - /// is added; samples past them are in `other`. - pub spaces: alloc::vec::Vec, - /// Open-addressed EL0 blocks keyed by ASID and PC ([`AsidBlock`]), - /// [`ASID_BLOCKS`] of them; samples past them count only by space. - pub blocks: alloc::vec::Vec, - pub other: u64, -} - -/// One address space's samples ([`AsidSamples`]). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct AsidSpace { - pub asid: u16, - pub samples: [u64; Level::COUNT], -} - -impl AsidSpace { - pub fn total(&self) -> u64 { - self.samples.iter().sum() - } -} - -/// One EL0 block's samples in one address space ([`AsidSamples`]). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct AsidBlock { - pub asid: u16, - pub pc: u64, - pub count: u64, -} - -/// The address spaces [`AsidSamples`] holds apart. -pub const ASID_SLOTS: usize = 512; -/// The EL0 blocks by address space [`AsidSamples`] holds apart. -pub const ASID_BLOCKS: usize = 4096; - -/// A slot of an open-addressed table of `slots` (a power of two) for `key`: -/// where its probe starts. -fn probe_start(key: u64, slots: usize) -> usize { - (key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (u64::BITS - slots.ilog2())) as usize -} - -impl AsidSamples { - /// Count `count` samples at `level` in address space `asid`, and an EL0 - /// sample's block at `pc` apart. - pub fn add(&mut self, asid: u16, pc: u64, level: Level, count: u64) { - self.allocate(); - let start = probe_start(u64::from(asid), ASID_SLOTS); - let space = (0..ASID_SLOTS / 8) - .map(|probe| (start + probe) % ASID_SLOTS) - .find(|&slot| self.spaces[slot].total() == 0 || self.spaces[slot].asid == asid); - let Some(slot) = space else { - self.other += count; - return; - }; - self.spaces[slot].asid = asid; - self.spaces[slot].samples[level as usize] += count; - if level != Level::User { - return; - } - let start = probe_start(pc ^ u64::from(asid) << 48, ASID_BLOCKS); - for probe in 0..ASID_BLOCKS / 8 { - let block = &mut self.blocks[(start + probe) % ASID_BLOCKS]; - if block.count == 0 { - *block = AsidBlock { asid, pc, count: 0 }; - } - if block.asid == asid && block.pc == pc { - block.count += count; - return; - } - } - } - - /// Add every sample `other` holds. - pub fn merge(&mut self, other: &Self) { - // EL0 samples by block first, each address space's held ones - // counted, then the rest of every space's samples. - let mut held = alloc::collections::BTreeMap::::new(); - for block in other.blocks.iter().filter(|block| block.count != 0) { - self.add(block.asid, block.pc, Level::User, block.count); - *held.entry(block.asid).or_default() += block.count; - } - for space in other.spaces.iter().filter(|space| space.total() != 0) { - for level in [Level::Kernel, Level::Guarded] { - let count = space.samples[level as usize]; - if count != 0 { - self.add(space.asid, 0, level, count); - } - } - let user = space.samples[Level::User as usize]; - let rest = user.saturating_sub(held.get(&space.asid).copied().unwrap_or(0)); - if rest != 0 { - self.add_space_only(space.asid, rest); - } - } - self.other += other.other; - } - - /// The tables, once the first sample comes. - fn allocate(&mut self) { - if self.spaces.is_empty() { - self.spaces = alloc::vec![AsidSpace::default(); ASID_SLOTS]; - self.blocks = alloc::vec![AsidBlock::default(); ASID_BLOCKS]; - } - } - - /// EL0 samples of `asid` whose block no table held. - fn add_space_only(&mut self, asid: u16, count: u64) { - self.allocate(); - let start = probe_start(u64::from(asid), ASID_SLOTS); - match (0..ASID_SLOTS / 8) - .map(|probe| (start + probe) % ASID_SLOTS) - .find(|&slot| self.spaces[slot].total() == 0 || self.spaces[slot].asid == asid) - { - Some(slot) => { - self.spaces[slot].asid = asid; - self.spaces[slot].samples[Level::User as usize] += count; - } - None => self.other += count, - } - } - - /// The `shown` address spaces with the most samples, most first. - pub fn top(&self, shown: usize) -> alloc::vec::Vec { - let mut spaces: alloc::vec::Vec = self - .spaces - .iter() - .filter(|space| space.total() != 0) - .copied() - .collect(); - spaces.sort_unstable_by(|a, b| b.total().cmp(&a.total()).then(a.asid.cmp(&b.asid))); - spaces.truncate(shown); - spaces - } - - /// The `shown` EL0 blocks of `asid` with the most samples, most first. - pub fn top_blocks(&self, asid: u16, shown: usize) -> alloc::vec::Vec { - let mut blocks: alloc::vec::Vec = self - .blocks - .iter() - .filter(|block| block.count != 0 && block.asid == asid) - .copied() - .collect(); - blocks.sort_unstable_by(|a, b| b.count.cmp(&a.count).then(a.pc.cmp(&b.pc))); - blocks.truncate(shown); - blocks - } -} - -/// A sampled transfer of a block's RET, BLR or BR form ([`HotBlocks`]): -/// the form and the block's PC, which stands for its site, and the target. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct DynamicSample { - pub form: DynamicForm, - pub site: u64, - pub target: u64, -} - -/// A branch to a register's value: RET, BLR, BR, then their PAC forms -/// (RETA*, BLRA*, BRA*). -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -#[repr(u8)] -pub enum DynamicForm { - Ret, - Blr, - Br, - Reta, - Blra, - Bra, -} - -impl DynamicForm { - pub const ALL: [Self; 6] = [ - Self::Ret, - Self::Blr, - Self::Br, - Self::Reta, - Self::Blra, - Self::Bra, - ]; -} - -/// The [`DynamicSample`]s one [`HotBlocks`] holds. -pub const DYNAMIC_SAMPLES: usize = 1 << 16; - -/// The sites of sampled RET, BLR and BR transfers since the first sample -/// ([`HotBlocks::dynamic`]), each with the first target seen there and -/// whether another followed: whether a one-target inline cache would serve -/// the hot ones. At most [`DYNAMIC_SITES`] sites; samples of further ones -/// are in `untracked`. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct DynamicSites { - sites: alloc::collections::BTreeMap<(DynamicForm, u64), DynamicSite>, - pub untracked: u64, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct DynamicSite { - target: u64, - samples: u64, - targets_differ: bool, -} - -/// The sites [`DynamicSites`] tells apart. -pub const DYNAMIC_SITES: usize = 1 << 15; - -/// One form's sites with at least two samples ([`DynamicSites::seen`]): -/// how many, how many had one target in every sample, and the samples of -/// each group. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DynamicSeen { - pub sites: u64, - pub monomorphic: u64, - pub samples: u64, - pub monomorphic_samples: u64, -} - -impl DynamicSites { - pub fn add(&mut self, samples: &[DynamicSample]) { - for sample in samples { - let key = (sample.form, sample.site); - if let Some(site) = self.sites.get_mut(&key) { - site.samples += 1; - site.targets_differ |= site.target != sample.target; - } else if self.sites.len() < DYNAMIC_SITES { - self.sites.insert( - key, - DynamicSite { - target: sample.target, - samples: 1, - targets_differ: false, - }, - ); - } else { - self.untracked += 1; - } - } - } - - /// The sites of `form` sampled at least twice. - pub fn seen(&self, form: DynamicForm) -> DynamicSeen { - let mut seen = DynamicSeen::default(); - let sites = self.sites.range((form, 0)..=(form, u64::MAX)); - for site in sites.map(|(_, site)| site).filter(|site| site.samples >= 2) { - seen.sites += 1; - seen.samples += site.samples; - if !site.targets_differ { - seen.monomorphic += 1; - seen.monomorphic_samples += site.samples; - } - } - seen - } -} - -/// One block's samples. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct HotBlock { - /// An EL0 block's PC; a kernel or guarded block's PC less the - /// sampling PE's vector base (wrapping), which moves with the slide. - pub pc: u64, - pub level: u8, - pub count: u64, -} - -/// The blocks [`HotBlocks`] holds apart. -pub const HOT_BLOCKS: usize = 8192; -/// One run in this many is sampled. -pub const HOT_SAMPLE_EVERY: u32 = 16; -/// A sampled run's budget is at most this many transfers. -pub const HOT_SAMPLE_SPAN: u64 = 4096; - -impl HotBlocks { - /// Count `count` samples of the block at `pc` at `level`. - pub fn add(&mut self, pc: u64, level: Level, count: u64) { - if self.entries.is_empty() { - self.entries = alloc::vec![HotBlock::default(); HOT_BLOCKS]; - } - self.samples[level as usize] += count; - let key = pc ^ (level as u64) << 62; - let start = - (key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (u64::BITS - HOT_BLOCKS.ilog2())) as usize; - for probe in 0..HOT_BLOCKS / 8 { - let entry = &mut self.entries[(start + probe) % HOT_BLOCKS]; - if entry.count == 0 { - *entry = HotBlock { - pc, - level: level as u8, - count: 0, - }; - } - if entry.pc == pc && entry.level == level as u8 { - entry.count += count; - return; - } - } - self.other += count; - } - - /// Add every sample `hot` holds. - pub fn merge(&mut self, hot: &Self) { - for entry in hot.counted() { - let level = - [Level::User, Level::Kernel, Level::Guarded][usize::from(entry.level).min(2)]; - self.add(entry.pc, level, entry.count); - } - self.other += hot.other; - // `add` counted the table's samples by level; the others only here. - for (level, samples) in self.samples.iter_mut().enumerate() { - let counted: u64 = hot - .counted() - .filter(|e| usize::from(e.level) == level) - .map(|e| e.count) - .sum(); - *samples += hot.samples[level] - counted; - } - self.add_dynamic(&hot.dynamic); - self.dynamic_other += hot.dynamic_other; - self.asids.merge(&hot.asids); - } - - /// Keep `samples` of dynamic transfers, as many as fit. - pub fn add_dynamic(&mut self, samples: &[DynamicSample]) { - let room = DYNAMIC_SAMPLES.saturating_sub(self.dynamic.len()); - let kept = samples.len().min(room); - self.dynamic.extend_from_slice(&samples[..kept]); - self.dynamic_other += (samples.len() - kept) as u64; - } - - /// The blocks with samples. - pub fn counted(&self) -> impl Iterator { - self.entries.iter().filter(|entry| entry.count != 0) - } - - /// The `shown` blocks of `level` with the most samples, most first. - pub fn top(&self, level: Level, shown: usize) -> alloc::vec::Vec { - let mut blocks: alloc::vec::Vec = self - .counted() - .filter(|e| e.level == level as u8) - .copied() - .collect(); - blocks.sort_unstable_by(|a, b| b.count.cmp(&a.count).then(a.pc.cmp(&b.pc))); - blocks.truncate(shown); - blocks - } - - pub fn is_empty(&self) -> bool { - self.samples.iter().all(|&n| n == 0) - } -} - -/// Where a PE's busy time goes in guest terms, under step timing: every -/// phase but [`Phase::Schedule`] charged by the guest's state at the charge -/// (an exit after its handling: an exception entry counts as the level it -/// entered), and the PE's waits for interrupt and event. What the guest's -/// own CPU accounting cannot see apart: its idle path between WFIs and its -/// interrupt handlers run on busy host time too. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Levels { - /// Ticks by [`Level`]. - pub ticks: [u64; Level::COUNT], - /// IRQs and FIQs taken, and the ticks charged from taking one until the - /// next exception return: handlers, and the switch to another thread - /// when one returns through it. - pub interrupts: u64, - pub interrupt_ticks: u64, - /// WFIs, and those that completed at once with an interrupt pending. - pub wfi: u64, - pub wfi_at_once: u64, - /// WFEs that reached the engine, and those that completed at once with - /// the event register set (native code completes some itself). - pub wfe: u64, - pub wfe_at_once: u64, - /// WFEs native code completed after spinning for the event register, - /// spins that ended without it, WFEs that exited without a spin for an - /// exclusive monitor, and the system counts spins spent - /// (`x86_64::register_read::event_wait_thunk`). - pub wfe_spun: u64, - pub wfe_spin_missed: u64, - pub wfe_held: u64, - pub wfe_spin_counts: u64, - /// WFEs native code completed on an event stream edge since the last - /// sample (`x86_64::register_read::EventStream`). - pub wfe_streamed: u64, - /// MSR CNTV_TVAL_EL0s that reached the engine, by why native code left - /// them to it ([`TimerExit`]). - pub timer_value_exits: [u64; TimerExit::COUNT], - /// At each WFI, the kernel ticks charged since the PE last ran EL0 code - /// or reached a WFI: wake-ups that found nothing for user code, idle - /// paths and kernel threads. - pub kernel_before_wfi: u64, - /// Between an interrupt's entry and the next exception return. - pub in_interrupt: bool, - /// Kernel ticks charged since the PE last ran EL0 code or reached a WFI. - pub kernel_run: u64, -} - -impl Levels { - /// Charge `spent` busy ticks at `level`. - #[inline] - pub(super) fn charge(&mut self, level: Level, spent: u64) { - self.ticks[level as usize] += spent; - // No handler runs at EL0: back there, the one taken has returned, - // whether native code or the engine made its exception return. - if level == Level::User { - self.in_interrupt = false; - } - if self.in_interrupt { - self.interrupt_ticks += spent; - } - if level == Level::User { - self.kernel_run = 0; - } else { - self.kernel_run += spent; - } - } - - pub(super) fn interrupt_taken(&mut self) { - self.interrupts += 1; - self.in_interrupt = true; - } - - /// Native code made an exception return: the handler taken has ended, - /// and the run's ticks charged after are not its. What the run spent in - /// the handler before its return is charged outside it, so - /// `interrupt_ticks` is a lower bound. - pub(super) fn exception_returned(&mut self) { - self.in_interrupt = false; - } - - /// A WFI, which completed at once if `at_once`. - pub(super) fn wait_for_interrupt(&mut self, at_once: bool) { - self.wfi += 1; - self.wfi_at_once += u64::from(at_once); - self.kernel_before_wfi += core::mem::take(&mut self.kernel_run); - } - - /// A WFE, which completed at once if `at_once`. - pub(super) fn wait_for_event(&mut self, at_once: bool) { - self.wfe += 1; - self.wfe_at_once += u64::from(at_once); - } - - /// What native WFEs counted of their spins. - pub(super) fn event_spins(&mut self, spin: stela_compiler::x86_64::register_read::EventSpin) { - self.wfe_spun += spin.completed; - self.wfe_spin_missed += spin.missed; - self.wfe_held += spin.held; - self.wfe_spin_counts += spin.counts; - self.wfe_streamed += spin.streamed; - } - - /// The counts since `earlier`; the state is this one's. - pub fn since(&self, earlier: &Self) -> Self { - let mut ticks = self.ticks; - for (now, then) in ticks.iter_mut().zip(earlier.ticks) { - *now = now.wrapping_sub(then); - } - Self { - ticks, - interrupts: self.interrupts.wrapping_sub(earlier.interrupts), - interrupt_ticks: self.interrupt_ticks.wrapping_sub(earlier.interrupt_ticks), - wfi: self.wfi.wrapping_sub(earlier.wfi), - wfi_at_once: self.wfi_at_once.wrapping_sub(earlier.wfi_at_once), - wfe: self.wfe.wrapping_sub(earlier.wfe), - wfe_at_once: self.wfe_at_once.wrapping_sub(earlier.wfe_at_once), - wfe_spun: self.wfe_spun.wrapping_sub(earlier.wfe_spun), - wfe_spin_missed: self.wfe_spin_missed.wrapping_sub(earlier.wfe_spin_missed), - wfe_held: self.wfe_held.wrapping_sub(earlier.wfe_held), - wfe_spin_counts: self.wfe_spin_counts.wrapping_sub(earlier.wfe_spin_counts), - wfe_streamed: self.wfe_streamed.wrapping_sub(earlier.wfe_streamed), - timer_value_exits: core::array::from_fn(|reason| { - self.timer_value_exits[reason].wrapping_sub(earlier.timer_value_exits[reason]) - }), - kernel_before_wfi: self - .kernel_before_wfi - .wrapping_sub(earlier.kernel_before_wfi), - ..*self - } - } -} - -/// Why a timer write reached the engine, where the native timer write -/// (`x86_64::register_read::timer_thunk`) would have completed it otherwise, -/// in the order that thunk tests. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TimerExit { - /// Not at EL2 with HCR_EL2.E2H, at a guarded level, or a chip with two - /// timer banks: no native write serves the state. - State, - /// The timer cells are closed. - Closed, - /// The engine had not said when it looks at the lines again - /// (`Mirrors::lines_until`), as it kept no device lines for the PE... - LinesDevices, - /// ...as a performance monitor overflow was due or near... - LinesMonitor, - /// ...or as the PE's own fast IPI word was set. - LinesIpi, - /// The channel's output was high, and what lowering it leaves waiting - /// was not known. - High, - /// The write arms a compare the count has reached: the line rises. - Now, - /// Native code could have completed it (no thunk at the site). - Native, -} - -impl TimerExit { - pub const COUNT: usize = 8; -} - -/// Whether `word` is ERET, ERETAA or ERETAB. -pub fn exception_return(word: u32) -> bool { - matches!(word, 0xd69f_03e0 | 0xd69f_0bff | 0xd69f_0fff) -} - -/// Host ticks spent so far, by phase and by exit. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct StepTiming { - pub phases: [u64; Phase::COUNT], - /// Lifetime maxima since timing was enabled or reset. A zero interval - /// has no witness. These are held, not subtracted, by [`Self::since`]. - pub lifetime_maxima: [Maximum; Phase::COUNT], - /// Exits handled and the ticks handling them, by `ExitKind` value, then - /// native faults by cause ([`fault_slot`]). - pub exits: [(u64, u64); EXIT_SLOTS], - /// What the native check fault being handled found, which its exit is - /// charged to ([`Check`]). - pub check: Option, - /// Busy time in guest terms ([`Levels`]). - pub levels: Levels, -} - -impl StepTiming { - /// Cumulative phase/exit totals spent since `earlier`, keeping the - /// current lifetime maximum snapshots. An interval maximum cannot be - /// derived by subtracting maxima. - pub fn since(&self, earlier: &Self) -> Self { - let mut delta = *self; - for (now, then) in delta.phases.iter_mut().zip(earlier.phases) { - *now = now.wrapping_sub(then); - } - for (now, then) in delta.exits.iter_mut().zip(earlier.exits) { - *now = (now.0.wrapping_sub(then.0), now.1.wrapping_sub(then.1)); - } - delta.levels = self.levels.since(&earlier.levels); - delta - } -} - -#[cfg(test)] -mod tests { - use super::*; - - const FAULT_SLOT: usize = FAULT_SLOTS + 1; - - /// Each System exit key falls in the class of what it does. - #[test] - fn system_keys_fall_in_the_class_of_what_they_do() { - let cases = [ - (DEVICE_SITE_KEY, SystemClass::Device), - (0x0020_0c20, SystemClass::Compression), - (0xd503_3b80, SystemClass::Barrier), - (0xd508_83a0, SystemClass::Maintenance), - (0xd508_7500, SystemClass::Maintenance), - (0xd503_2040, SystemClass::Wait), - (0xd51b_e300, SystemClass::Timer), - (0xd53a_f000, SystemClass::ImplementationDefined), - (0xd51d_f000, SystemClass::ImplementationDefined), - (0xd518_2000, SystemClass::TranslationControl), - (0xd518_1000, SystemClass::TranslationControl), - (0xd69f_03e0, SystemClass::Transition), - (0xd400_1001, SystemClass::Transition), - (0xd503_47e0, SystemClass::Other), - ]; - for (key, class) in cases { - let name = system_key_name(key); - assert_eq!(SystemClass::of(key), class, "{key:#010x} {name}"); - assert_eq!(wait_key(key), class == SystemClass::Wait, "{key:#010x}"); - } - } - - /// `wait_key` finds the Wait class exactly, over the whole hint and - /// barrier space (CRn 1 to 3 of op0 0) and the timed waits. - #[test] - fn wait_keys_are_the_wait_class() { - let mut waits = 0; - for key in (0xd503_1000u32..0xd503_4000).step_by(0x20) { - let wait = SystemClass::of(key) == SystemClass::Wait; - assert_eq!(wait_key(key), wait, "{key:#010x} {}", system_key_name(key)); - waits += usize::from(wait); - } - // WFE, WFI, WFET and WFIT. - assert_eq!(waits, 4); - } - - #[test] - fn hot_blocks_rank_by_samples_per_level_and_merge() { - let mut hot = HotBlocks::default(); - assert!(hot.is_empty()); - hot.add(0x1000, Level::Kernel, 3); - hot.add(0x2000, Level::Kernel, 5); - // The same PC at another level is another block. - hot.add(0x1000, Level::User, 7); - let top = hot.top(Level::Kernel, 8); - assert_eq!( - top.iter() - .map(|b| (b.pc, b.count)) - .collect::>(), - [(0x2000, 5), (0x1000, 3)] - ); - assert_eq!(hot.top(Level::User, 8)[0].count, 7); - assert_eq!(hot.samples, [7, 8, 0]); - let mut merged = HotBlocks::default(); - merged.add(0x2000, Level::Kernel, 1); - merged.merge(&hot); - assert_eq!( - merged.top(Level::Kernel, 1)[0], - HotBlock { - pc: 0x2000, - level: Level::Kernel as u8, - count: 6 - } - ); - assert_eq!(merged.samples, [7, 9, 0]); - } - - /// One run in HOT_SAMPLE_EVERY gets a drawn budget; a sampled run whose - /// budget ran out names the block it ended in, and nothing is sampled - /// without step timing. - #[test] - fn a_sampled_run_whose_budget_ran_out_names_its_last_block() { - use super::super::{ - NativeExit, - chain::{Account, ChainControl}, - }; - use stela_compiler::block::ExitKind; - const ADD: u32 = 0x9100_0400; // add x0, x0, #1 - let mut machine = super::super::tests::machine(&[ADD, 0x1400_0002, 0, ADD, 0x17ff_fffc]); - let base = machine.cpu.pc; - let direct = |next_pc| NativeExit::Exit { - next_pc, - kind: ExitKind::Direct as u64, - }; - let run = |machine: &mut crate::machine::Machine< - super::super::tests::FakeHost, - crate::machine::NoDevices, - >, - runs: u32| { - for _ in 0..runs { - let next = if machine.cpu.pc == base { - base + 12 - } else { - base - }; - let current = machine.chain.snapshot(); - machine.host.chained = Some(( - machine.chain.address() as *mut ChainControl, - ChainControl { - block: 1, - ..current - }, - Account::spent(0), - )); - machine.host.exits = alloc::vec![direct(next)]; - machine.step().unwrap(); - } - }; - // Both blocks compiled, then runs that all spend their budget. - machine.slice_end = u64::MAX; - machine.block_limit = u64::MAX; - machine.host.exits = alloc::vec![direct(base + 12), direct(base)]; - machine.step().unwrap(); - machine.step().unwrap(); - run(&mut machine, 2 * HOT_SAMPLE_EVERY); - assert!(!machine.has_hot_samples(), "no samples without step timing"); - // Kernel PCs are kept as offsets from the vector base of their EL. - const VBAR: u64 = 0x800; - for register in [ - crate::machine::system::Register::VBAR_EL1, - crate::machine::system::Register::VBAR_EL2, - ] { - machine.cpu.registers.set(register, 0, VBAR); - } - let expected = - if Level::of(machine.cpu.pstate.el, machine.cpu.pstate.guarded) == Level::User { - base + 12 - } else { - (base + 12).wrapping_sub(VBAR) - }; - // Each regime's TTBR0 holds an ASID of its own (8 bits: TCR.AS is - // clear); the sample names the one its regime tags translations - // with, never a constant. - use crate::machine::system::Register; - machine - .cpu - .registers - .set(Register::TTBR0_EL1, 0, 0x11 << 48); - machine - .cpu - .registers - .set(Register::TTBR0_EL2, 0, 0x22 << 48); - let asid = machine.current_space_asid(); - let in_el20 = - machine.cpu.pstate.el == 2 || machine.cpu.pstate.el == 0 && machine.cpu.in_host(); - assert_eq!(asid, if in_el20 { 0x22 } else { 0x11 }); - machine.set_step_timing(true); - run(&mut machine, 2 * HOT_SAMPLE_EVERY); - let mut hot = HotBlocks::default(); - machine.take_hot_samples(&mut hot); - let total: u64 = hot.samples.iter().sum(); - assert_eq!(total, 2); - let pcs: alloc::vec::Vec = hot.counted().map(|block| block.pc).collect(); - assert_eq!(pcs, [expected]); - let spaces: alloc::vec::Vec<(u16, u64)> = hot - .asids - .top(8) - .iter() - .map(|space| (space.asid, space.total())) - .collect(); - assert_eq!(spaces, [(asid, 2)]); - assert!(!machine.has_hot_samples()); - // Draws stay within the span and below the run's own budget. - for _ in 0..1000 { - let (budget, sampled) = machine.sampled_budget(HOT_SAMPLE_SPAN + 1); - assert!((1..=HOT_SAMPLE_SPAN + 1).contains(&budget)); - assert_eq!(sampled, budget <= HOT_SAMPLE_SPAN); - } - } - - /// A sample's address space is the ASID its regime tags translations - /// with: under VHE with HCR_EL2.TGE (XNU on an M2, kernel at EL2) EL0 - /// and EL2 take TTBR0_EL2's, where the kernel's TTBR0_EL1 writes land, - /// and TTBR0_EL1 stays 0; in EL1&0 TTBR0_EL1's; TCR.A1 picks TTBR1. - #[test] - fn a_samples_address_space_is_its_regimes_asid() { - use crate::machine::system::Register; - const HCR_TGE: u64 = 1 << 27; - const HCR_E2H: u64 = 1 << 34; - const TCR_A1: u64 = 1 << 22; - const TCR_AS: u64 = 1 << 36; - let mut machine = super::super::tests::machine(&[0x9100_0400]); - machine.cpu.registers.set(Register::TTBR0_EL1, 0, 0); - machine - .cpu - .registers - .set(Register::TTBR0_EL2, 0, 0x1234 << 48); - machine - .cpu - .registers - .set(Register::TTBR1_EL2, 0, 0x5678 << 48); - machine.cpu.registers.set(Register::TCR_EL2, 0, TCR_AS); - machine - .cpu - .registers - .set(Register::HCR_EL2, 0, HCR_TGE | HCR_E2H); - for el in [0, 2] { - machine.cpu.pstate.el = el; - assert_eq!(machine.current_space_asid(), 0x1234, "EL{el} under TGE"); - } - machine - .cpu - .registers - .set(Register::TCR_EL2, 0, TCR_AS | TCR_A1); - assert_eq!(machine.current_space_asid(), 0x5678, "TCR.A1"); - // EL1&0: TTBR0_EL1's, 8 bits without TCR_EL1.AS. - machine.cpu.registers.set(Register::HCR_EL2, 0, 0); - machine - .cpu - .registers - .set(Register::TTBR0_EL1, 0, 0x1abc << 48); - machine.cpu.pstate.el = 1; - assert_eq!(machine.current_space_asid(), 0xbc); - machine.cpu.pstate.el = 0; - assert_eq!(machine.current_space_asid(), 0xbc); - } - - /// Sites sampled once are not judged; a site whose samples all named - /// one target is monomorphic; the forms are counted apart; a merge - /// keeps the samples of both, as many as fit. - #[test] - fn dynamic_sites_tell_one_target_sites_apart() { - let sample = |form, site, target| DynamicSample { form, site, target }; - let mut hot = HotBlocks::default(); - hot.add_dynamic(&[ - sample(DynamicForm::Ret, 0x100, 0x500), - sample(DynamicForm::Ret, 0x100, 0x500), - sample(DynamicForm::Ret, 0x100, 0x500), - sample(DynamicForm::Ret, 0x200, 0x600), - sample(DynamicForm::Ret, 0x200, 0x604), - sample(DynamicForm::Ret, 0x300, 0x700), - sample(DynamicForm::Blr, 0x100, 0x800), - sample(DynamicForm::Blr, 0x100, 0x800), - ]); - let mut merged = HotBlocks::default(); - merged.merge(&hot); - assert_eq!(merged.dynamic, hot.dynamic); - let mut sites = DynamicSites::default(); - sites.add(&merged.dynamic); - let seen = |sites: &DynamicSites, form| { - let seen = sites.seen(form); - [ - seen.sites, - seen.monomorphic, - seen.samples, - seen.monomorphic_samples, - ] - }; - assert_eq!(seen(&sites, DynamicForm::Ret), [2, 1, 5, 3]); - assert_eq!(seen(&sites, DynamicForm::Blr), [1, 1, 2, 2]); - assert_eq!(seen(&sites, DynamicForm::Br), [0; 4]); - let mut full = HotBlocks { - dynamic: alloc::vec![sample(DynamicForm::Br, 0, 0); DYNAMIC_SAMPLES - 1], - ..HotBlocks::default() - }; - full.add_dynamic(&hot.dynamic[..2]); - assert_eq!( - (full.dynamic.len(), full.dynamic_other), - (DYNAMIC_SAMPLES, 1) - ); - } - - /// Samples count by address space at every level, EL0 blocks apart per - /// address space, and a merge keeps both, those no block held included. - #[test] - fn asid_samples_rank_address_spaces_and_their_user_blocks_and_merge() { - let mut asids = AsidSamples::default(); - asids.add(7, 0x1000, Level::User, 5); - asids.add(7, 0x2000, Level::User, 2); - asids.add(7, 0x10, Level::Kernel, 4); - asids.add(0, 0x20, Level::Kernel, 9); - // The same PC in another address space is another block. - asids.add(9, 0x1000, Level::User, 1); - let top = asids.top(8); - assert_eq!( - top.iter() - .map(|s| (s.asid, s.samples)) - .collect::>(), - [(7, [7, 4, 0]), (0, [0, 9, 0]), (9, [1, 0, 0])] - ); - assert_eq!( - asids - .top_blocks(7, 8) - .iter() - .map(|b| (b.pc, b.count)) - .collect::>(), - [(0x1000, 5), (0x2000, 2)] - ); - // Kernel samples name no block. - assert!(asids.top_blocks(0, 8).is_empty()); - let mut merged = AsidSamples::default(); - merged.add(7, 0x1000, Level::User, 1); - merged.merge(&asids); - assert_eq!(merged.top(1)[0].samples, [8, 4, 0]); - assert_eq!(merged.top_blocks(7, 1)[0].count, 6); - // HotBlocks carries them through its own merge. - let hot = HotBlocks { - asids: asids.clone(), - ..HotBlocks::default() - }; - let mut total = HotBlocks::default(); - total.merge(&hot); - assert_eq!(total.asids.top(8), asids.top(8)); - // EL0 samples whose blocks did not fit still count by space. - let mut full = AsidSamples::default(); - for pc in 0..(ASID_BLOCKS as u64 + 50) { - full.add(3, pc * 4, Level::User, 1); - } - let mut again = AsidSamples::default(); - again.merge(&full); - assert_eq!( - again.top(1)[0].samples[Level::User as usize], - ASID_BLOCKS as u64 + 50 - ); - } - - #[test] - fn hot_blocks_count_what_the_table_cannot_hold_as_other() { - let mut hot = HotBlocks::default(); - for pc in 0..(HOT_BLOCKS as u64 + 100) { - hot.add(pc * 4, Level::Kernel, 1); - } - let held: u64 = hot.counted().map(|e| e.count).sum(); - assert_eq!(held + hot.other, HOT_BLOCKS as u64 + 100); - assert_eq!(hot.samples[Level::Kernel as usize], HOT_BLOCKS as u64 + 100); - let mut merged = HotBlocks::default(); - merged.merge(&hot); - assert_eq!(merged.samples, hot.samples); - } - - #[test] - fn system_keys_drop_registers_and_name_the_instruction() { - // MRS X1 and X30, TPIDR_EL1: one key, the accessor's name. - assert_eq!(system_key(0xd538_d081), system_key(0xd538_d09e)); - assert_eq!(system_key(0xd538_d081), 0xd538_d080); - assert_eq!(system_key_name(0xd538_d080), "MRS_TPIDR_EL1"); - assert_eq!(system_key_name(0xd518_c000), "MSR_VBAR_EL1"); - // TLBI VAE1IS, X0. - assert_eq!(system_key_name(system_key(0xd508_8320)), "TLBI_VAE1IS"); - // An Apple register without an accessor: its encoding. - assert_eq!(system_key_name(0xd53c_f200), "MRS_S3_4_C15_C2_0"); - assert_eq!( - system_key_name(0xd69f_03e0), - "Exception.ExceptionReturn:0xd69f03e0" - ); - assert_eq!(system_key_name(DEVICE_SITE_KEY), "device-site"); - // LDXR W1, [X2] and LDXR W3, [X4]: one key. - assert_eq!(system_key(0x885f_7c41), system_key(0x885f_7c83)); - } - - #[test] - fn system_exits_count_by_key_and_keep_the_rest_in_other() { - let mut exits = SystemExits::default(); - assert!(exits.is_empty()); - for key in 0..SYSTEM_KEYS as u32 + 2 { - exits.add(key, 1, 10, u64::from(key == 0)); - } - exits.add(0, 1, 5, 0); - let first = exits.counted().find(|exit| exit.key == 0).unwrap(); - assert_eq!((first.count, first.ticks, first.closes), (2, 15, 1)); - assert_eq!(exits.counted().count(), SYSTEM_KEYS); - assert_eq!((exits.other.count, exits.other.ticks), (2, 20)); - let mut merged = SystemExits::default(); - merged.merge(&exits); - merged.merge(&exits); - let first = merged.counted().find(|exit| exit.key == 0).unwrap(); - assert_eq!((first.count, first.closes), (4, 2)); - assert_eq!(merged.other.count, 4); - } - - /// Registers count apart by address and direction, the ones past the - /// table in `other_registers`, and merge. - #[test] - fn device_exits_count_by_register_and_direction() { - let mut exits = DeviceExits::default(); - const REGISTER: u64 = 0x2_3b0c_8000; - let exit = |register, ticks, waited, access, settle| DeviceRegisterExit { - register, - count: 1, - ticks, - waited, - access, - settle, - ..DeviceRegisterExit::default() - }; - exits.add_register(exit(REGISTER, 10, 2, 0, 0)); - exits.add_register(exit(REGISTER | DEVICE_REGISTER_WRITE, 20, 0, 6, 9)); - exits.add_register(exit(REGISTER, 5, 1, 0, 0)); - for index in 0..DEVICE_REGISTERS as u64 { - exits.add_register(exit(0x1000 + index * 4, 1, 0, 0, 0)); - } - let count = |exits: &DeviceExits, register| { - exits - .counted_registers() - .find(|exit| exit.register == register) - .map(|exit| { - ( - exit.count, - exit.ticks, - exit.waited, - exit.access, - exit.settle, - ) - }) - }; - assert_eq!(count(&exits, REGISTER), Some((2, 15, 3, 0, 0))); - assert_eq!( - count(&exits, REGISTER | DEVICE_REGISTER_WRITE), - Some((1, 20, 0, 6, 9)) - ); - assert_eq!(exits.other_registers.count, 2); - let mut merged = DeviceExits::default(); - merged.merge(&exits); - merged.merge(&exits); - assert_eq!(count(&merged, REGISTER), Some((4, 30, 6, 0, 0))); - let total: u64 = merged.counted_registers().map(|exit| exit.count).sum(); - assert_eq!( - total + merged.other_registers.count, - 2 * (3 + DEVICE_REGISTERS as u64) - ); - } - - #[test] - fn regime_syncs_merge() { - let regimes = RegimeSyncs { - syncs: 3, - sync_ticks: 30, - isolations: 1, - isolation_ticks: 7, - unchanged: 2, - sources: [1, 0, 0, 0, 2, 0, 0], - }; - let exits = SystemExits { - regimes, - ..SystemExits::default() - }; - assert!(!exits.is_empty()); - let mut merged = SystemExits::default(); - merged.merge(&exits); - merged.merge(&exits); - assert_eq!( - merged.regimes, - RegimeSyncs { - syncs: 6, - sync_ticks: 60, - isolations: 2, - isolation_ticks: 14, - unchanged: 4, - sources: [2, 0, 0, 0, 4, 0, 0], - } - ); - } - - #[test] - fn barrier_waits_count_quick_ones_apart_and_merge_by_blocker() { - let system = stela_compiler::block::ExitKind::System as usize; - let mut waits = BarrierWaits::default(); - waits.add(None, 3); - waits.add(Some(BLOCKER_NATIVE), 10); - let dsb = exit_blocker(system, Some(0xd503_3b9f)); - assert_eq!(dsb, exit_blocker(system, Some(0xd503_3b80))); - waits.add(Some(dsb), 20); - for key in 0..BARRIER_BLOCKERS as u64 { - waits.add(Some(BLOCKER_EXIT | key << 32), 1); - } - assert_eq!((waits.waits, waits.quick, waits.ticks), (35, 1, 65)); - assert_eq!(waits.other.count, 2); - let exits = SystemExits { - barriers: waits, - ..SystemExits::default() - }; - assert!(!exits.is_empty()); - let mut merged = SystemExits::default(); - merged.merge(&exits); - merged.merge(&exits); - let merged = merged.barriers; - assert_eq!((merged.waits, merged.quick, merged.ticks), (70, 2, 130)); - let native = merged - .blockers - .iter() - .find(|b| b.key == BLOCKER_NATIVE) - .unwrap(); - assert_eq!((native.count, native.ticks), (2, 20)); - let dsb = merged.blockers.iter().find(|b| b.key == dsb).unwrap(); - assert_eq!((dsb.count, dsb.ticks), (2, 40)); - assert_eq!(merged.other.count, 4); - } - - #[test] - fn device_exits_count_by_page_and_merge_with_forwards() { - let mut exits = DeviceExits::default(); - assert!(exits.is_empty()); - assert_eq!(device_page(0x2_3b0c_8000), device_page(0x2_3b0c_8ffc)); - assert_ne!(device_page(0x2_3b0c_8000), device_page(0x2_3b0c_6658)); - for page in 0..DEVICE_PAGES as u32 + 3 { - exits.add(page, 1, 10, 2); - } - exits.add(0, 1, 5, 1); - exits.forwarded = 1; - exits.forwarded_ticks = 7; - let first = *exits.counted().find(|exit| exit.page == 0).unwrap(); - assert_eq!((first.count, first.ticks, first.waited), (2, 15, 3)); - assert_eq!(exits.counted().count(), DEVICE_PAGES); - assert_eq!((exits.other.count, exits.other.waited), (3, 6)); - let system = SystemExits { - devices: exits, - ..SystemExits::default() - }; - assert!(!system.is_empty()); - let mut merged = SystemExits::default(); - merged.merge(&system); - merged.merge(&system); - let first = *merged - .devices - .counted() - .find(|exit| exit.page == 0) - .unwrap(); - assert_eq!((first.count, first.waited), (4, 6)); - assert_eq!( - (merged.devices.forwarded, merged.devices.forwarded_ticks), - (2, 14) - ); - } - - #[test] - fn a_system_exit_is_charged_to_its_key_with_the_cells_it_closed() { - use super::super::tests::BASE; - const MRS_X1_TPIDR_EL1: u32 = 0xd538_d081; - const MSR_VBAR_EL1_X2: u32 = 0xd518_c002; - let mut machine = super::super::tests::machine(&[MRS_X1_TPIDR_EL1, MSR_VBAR_EL1_X2]); - machine.set_step_timing(true); - machine.cpu.state.x[2] = BASE + 0x800; - for pc in [BASE, BASE + 4] { - machine.host.exits.push(super::super::NativeExit::Exit { - next_pc: pc, - kind: stela_compiler::block::ExitKind::System as u64, - }); - machine.step().unwrap(); - } - assert_eq!(machine.cpu.pc, BASE + 8); - let system = stela_compiler::block::ExitKind::System as usize; - assert_eq!(machine.step_timing().unwrap().exits[system].0, 2); - let exits = machine.take_system_exits(); - let key = |key| *exits.counted().find(|exit| exit.key == key).unwrap(); - // The read changed nothing; the VBAR_EL1 write closed every cell. - assert_eq!((key(0xd538_d080).count, key(0xd538_d080).closes), (1, 0)); - assert_eq!((key(0xd518_c000).count, key(0xd518_c000).closes), (1, 1)); - assert!(machine.take_system_exits().is_empty()); - } - - /// A floating-point exit is charged to its whole word, which the report - /// tells from System keys, and stays out of the System words. - #[test] - fn a_floating_point_exit_is_charged_to_its_word() { - use super::super::tests::BASE; - const FADD_S0_S1_S2: u32 = 0x1e22_2820; - const FCVTNU_8H: u32 = 0x6e79_aa67; - let mut machine = super::super::tests::machine(&[FADD_S0_S1_S2]); - machine.set_step_timing(true); - // FP/SIMD enabled at EL1 (CPACR_EL1.FPEN). - machine - .cpu - .registers - .set(crate::machine::system::Register::CPACR_EL1, 0, 0b11 << 20); - machine.host.exits.push(super::super::NativeExit::Exit { - next_pc: BASE, - kind: stela_compiler::block::ExitKind::FloatingPoint as u64, - }); - machine.step().unwrap(); - assert_eq!(machine.cpu.pc, BASE + 4); - let slot = stela_compiler::block::ExitKind::FloatingPoint as usize; - assert_eq!(machine.step_timing().unwrap().exits[slot].0, 1); - let exits = machine.take_system_exits(); - let exit = *exits - .counted() - .find(|exit| exit.key == FADD_S0_S1_S2) - .unwrap(); - assert_eq!(exit.count, 1); - assert!(numerical_key(FADD_S0_S1_S2) && numerical_key(FCVTNU_8H)); - assert!(!numerical_key(0xd538_d080) && !numerical_key(DEVICE_SITE_KEY)); - assert!(system_key_name(FCVTNU_8H).ends_with(":0x6e79aa67")); - assert!(!machine.system_words().contains_key(&FADD_S0_S1_S2)); - // Zeros add exactly: no fresh flag. - assert_eq!(exits.floating[FloatingReason::Exact as usize], 1); - assert_eq!(exits.floating.iter().sum::(), 1); - // Its word counts the reason, the zero operands and the clear IXC. - let word = *exits - .floating_words - .counted() - .find(|word| word.key == FADD_S0_S1_S2) - .unwrap(); - assert_eq!(word.count(), 1); - assert_eq!(word.reasons[FloatingReason::Exact as usize], 1); - assert_eq!(word.inexact_clear, 1); - assert_eq!(word.operands[Operands::Zero as usize], 1); - assert_eq!(word.operands[Operands::Ordinary as usize], 1); - assert_eq!(word.operands[Operands::Subnormal as usize], 0); - } - - /// A pointer authentication exit is charged to its word, which the - /// report tells from System and floating-point keys, and stays out of - /// the System words. - #[test] - fn a_pointer_authentication_exit_is_charged_to_its_word() { - use super::super::tests::BASE; - const RETAA: u32 = 0xd65f_0bff; - // PACIASP, a hint whose key clears Rt. - const PACIASP: u32 = 0xd503_233f; - let mut machine = super::super::tests::machine(&[RETAA]); - machine.set_step_timing(true); - machine.cpu.state.x[30] = BASE + 0x40; - machine.host.exits.push(super::super::NativeExit::Exit { - next_pc: BASE, - kind: stela_compiler::block::ExitKind::PointerAuthentication as u64, - }); - let _ = machine.step(); - let slot = stela_compiler::block::ExitKind::PointerAuthentication as usize; - assert_eq!(machine.step_timing().unwrap().exits[slot].0, 1); - let exits = machine.take_system_exits(); - let exit = *exits.counted().find(|exit| exit.key == RETAA).unwrap(); - assert_eq!(exit.count, 1); - assert!(!machine.system_words().contains_key(&RETAA)); - assert!(pointer_key(RETAA) && pointer_key(system_key(PACIASP))); - assert!(system_key_name(RETAA).starts_with("PAC.")); - assert!(system_key_name(system_key(PACIASP)).starts_with("PAC.")); - assert!(!pointer_key(0xd538_d080) && !pointer_key(DEVICE_SITE_KEY)); - assert!(!pointer_key(0x1e22_2820) && !numerical_key(RETAA)); - } - - /// The census names what the operands of an exit held: subnormal, NaN - /// and zero source lanes, an indexed source's one lane, a tiny result, - /// and forms it does not read. - #[test] - fn a_floating_point_census_classifies_operands() { - use stela_compiler::{GuestState, aarch64::FloatingPointOperation}; - // FMLA V29.4S, V26.4S, V21.S[1]. - const FMLA_INDEXED_4S: u32 = 0x4fb5_135d; - // SCVTF D0, X0. - const SCVTF_D0_X0: u32 = 0x9e62_0000; - const ONE: u64 = 0x3f80_0000; - const SUBNORMAL: u64 = 0x0000_0001; - const NAN: u64 = 0x7fc0_0000; - let decode = |word| match FloatingPointOperation::decode(word) { - Some(Ok(operation)) => operation, - other => panic!("{word:#x}: {other:?}"), - }; - let fmla = decode(FMLA_INDEXED_4S); - let ones = ONE | ONE << 32; - let bit = |class: Operands| 1u8 << class as u8; - let mut state = GuestState::default(); - state.v[26] = [ones, ones]; - state.v[29] = [ones, ones]; - // Only lane 1 of V21 is read: a NaN in lane 0 is not. - state.v[21] = [NAN | ONE << 32, NAN | NAN << 32]; - let census = FloatingCensus::read(&state, &fmla); - assert_eq!(census.finish(&state, true), bit(Operands::Ordinary)); - // A subnormal lane of V26 and a tiny result lane. - state.v[26][1] = ONE | SUBNORMAL << 32; - let census = FloatingCensus::read(&state, &fmla); - state.v[29][0] = SUBNORMAL; - assert_eq!( - census.finish(&state, true), - bit(Operands::Subnormal) | bit(Operands::Tiny) - ); - // A trapped completion's result is not read. - state.v[29] = [ones, ones]; - let census = FloatingCensus::read(&state, &fmla); - state.v[29][0] = SUBNORMAL; - assert_eq!(census.finish(&state, false), bit(Operands::Subnormal)); - // NaN and zero in the addend. - state.v[26] = [ones, ones]; - state.v[29] = [NAN, ones]; - let census = FloatingCensus::read(&state, &fmla); - state.v[29] = [ones, ones]; - assert_eq!( - census.finish(&state, true), - bit(Operands::Nan) | bit(Operands::Zero) - ); - let scvtf = decode(SCVTF_D0_X0); - let census = FloatingCensus::read(&state, &scvtf); - assert_eq!(census.finish(&state, true), bit(Operands::Unread)); - } - - #[test] - fn floating_words_count_by_word_and_keep_the_rest_in_other() { - let mut words = FloatingWords::default(); - assert!(words.is_empty()); - let subnormal = 1 << Operands::Subnormal as u8; - for key in 0..FLOATING_WORDS as u32 + 2 { - words.add(key, FloatingReason::Exact, false, subnormal, true); - } - words.add(0, FloatingReason::Inexact, true, subnormal, false); - let first = *words.counted().find(|word| word.key == 0).unwrap(); - assert_eq!(first.count(), 2); - assert_eq!(first.reasons[FloatingReason::Mode as usize], 1); - assert_eq!(first.operands[Operands::Subnormal as usize], 2); - assert_eq!(first.inexact_clear, 1); - assert_eq!(words.counted().count(), FLOATING_WORDS); - assert_eq!(words.other.count(), 2); - let exits = SystemExits { - floating_words: words, - ..SystemExits::default() - }; - assert!(!exits.is_empty()); - let mut merged = SystemExits::default(); - merged.merge(&exits); - merged.merge(&exits); - let first = *merged - .floating_words - .counted() - .find(|word| word.key == 0) - .unwrap(); - assert_eq!((first.count(), first.inexact_clear), (4, 2)); - assert_eq!(merged.floating_words.other.count(), 4); - } - - /// The reason counter keeps FPSR as the completion leaves it: earlier - /// flags stay, fresh ones are added, and the first fresh one names it. - #[test] - fn a_floating_point_exit_reason_keeps_fpsr() { - use super::super::tests::BASE; - const FDIV_S0_S1_S2: u32 = 0x1e22_1820; - const INEXACT: u32 = 1 << 4; - let mut machine = super::super::tests::machine(&[FDIV_S0_S1_S2]); - machine.set_step_timing(true); - machine - .cpu - .registers - .set(crate::machine::system::Register::CPACR_EL1, 0, 0b11 << 20); - machine.cpu.state.fpsr = INEXACT; - // 1 / 0: divide by zero. - machine.cpu.state.v[1] = [0x3f80_0000, 0]; - machine.host.exits.push(super::super::NativeExit::Exit { - next_pc: BASE, - kind: stela_compiler::block::ExitKind::FloatingPoint as u64, - }); - machine.step().unwrap(); - assert_eq!(machine.cpu.state.fpsr, INEXACT | 1 << 1); - assert_eq!(machine.cpu.state.v[0][0], 0x7f80_0000); - let exits = machine.take_system_exits(); - assert_eq!(exits.floating[FloatingReason::Divide as usize], 1); - assert_eq!(FloatingReason::of(0, 0x11, false), FloatingReason::Invalid); - assert_eq!(FloatingReason::of(1 << 8, 0, false), FloatingReason::Trap); - assert_eq!( - FloatingReason::of(0, 0x18, false), - FloatingReason::Underflow - ); - assert_eq!(FloatingReason::of(0, 0x10, false), FloatingReason::Inexact); - } - - /// Busy phases go to the guest level they were charged at, the kernel - /// run before a WFI is kept at it, and an interrupt's ticks end with - /// its exception return, whose own ticks count. - #[test] - fn busy_time_is_split_by_level_wait_and_interrupt() { - use super::super::tests::{machine_on, one_timer_bank}; - const WFI: u32 = 0xd503_207f; - let mut machine = machine_on(one_timer_bank(), &[]); - machine.set_step_timing(true); - machine.cpu.pstate.el = 0; - machine.host.now = 10; - machine.timing_charge(Phase::Native, 0); - machine.cpu.pstate.el = 1; - machine.host.now = 30; - machine.timing_charge(Phase::Fetch, 10); - machine.host.now = 100; - machine.timing_charge(Phase::Schedule, 30); - machine.cpu.pstate.guarded = true; - machine.host.now = 105; - machine.timing_charge(Phase::Native, 100); - machine.cpu.pstate.guarded = false; - let levels = machine.step_timing().unwrap().levels; - assert_eq!(levels.ticks, [10, 20, 5]); - assert_eq!(levels.kernel_run, 25); - // Nothing pending: the WFI waits, and takes the kernel run. - machine.lines(); - machine.system_instruction(WFI).unwrap(); - assert!(machine.waiting.is_some()); - machine.waiting = None; - let levels = machine.step_timing().unwrap().levels; - assert_eq!((levels.wfi, levels.wfi_at_once), (1, 0)); - assert_eq!((levels.kernel_before_wfi, levels.kernel_run), (25, 0)); - // An expired virtual timer's FIQ, taken, then its handler's return. - machine.cpu.state.x[0] = 1500; - machine.system_instruction(0xd51b_e300).unwrap(); // msr cntv_tval_el0, x0 - machine.cpu.state.x[0] = 1; - machine.system_instruction(0xd51b_e320).unwrap(); // msr cntv_ctl_el0, x0 - machine.host.now = 2000; - machine.lines(); - // Pending though masked: a WFI completes at once. - machine.cpu.pstate.daif = 0xf; - machine.system_instruction(WFI).unwrap(); - assert!(machine.waiting.is_none()); - machine.cpu.pstate.daif = 0; - assert!(machine.deliver_interrupts()); - machine.host.now = 2007; - machine.timing_charge(Phase::Native, 2000); - machine.timed_word = Some(0xd69f_03e0); - machine.host.now = 2010; - machine.timing_exit(stela_compiler::block::ExitKind::System as usize, 2007); - machine.host.now = 2050; - machine.timing_charge(Phase::Native, 2010); - let levels = machine.step_timing().unwrap().levels; - assert_eq!((levels.wfi, levels.wfi_at_once), (2, 1)); - assert_eq!((levels.interrupts, levels.interrupt_ticks), (1, 10)); - assert!(!levels.in_interrupt); - // A delta keeps the state and subtracts the counts. - let delta = levels.since(&Levels { - wfi: 1, - ticks: [10, 0, 0], - ..Levels::default() - }); - assert_eq!((delta.wfi, delta.ticks[0]), (1, 0)); - assert_eq!(delta.kernel_run, levels.kernel_run); - assert!(exception_return(0xd69f_0bff) && !exception_return(0xd65f_03c0)); - } - - #[test] - fn a_delta_subtracts_each_phase_and_exit() { - let mut earlier = StepTiming::default(); - earlier.phases[Phase::Exit as usize] = 5; - earlier.exits[FAULT_SLOT] = (1, 10); - earlier.lifetime_maxima[Phase::Exit as usize].observe(5, 50, 0x1000, 1, 2); - let mut now = earlier; - now.phases[Phase::Exit as usize] = 12; - now.exits[FAULT_SLOT] = (3, 40); - now.lifetime_maxima[Phase::Exit as usize].observe(9, 90, 0x2000, 2, 3); - let delta = now.since(&earlier); - assert_eq!(delta.phases[Phase::Exit as usize], 7); - assert_eq!(delta.exits[FAULT_SLOT], (2, 30)); - assert_eq!(delta.phases[Phase::Native as usize], 0); - assert_eq!(delta.lifetime_maxima, now.lifetime_maxima); - let later_delta = now.since(&now); - assert_eq!(later_delta.phases, [0; Phase::COUNT]); - assert_eq!(later_delta.lifetime_maxima, now.lifetime_maxima); - } - - /// Native code makes most exception returns (`PES TRANSITIONS eret`): - /// one ends the handler the engine saw taken, and so does reaching EL0, - /// where no handler runs. Before, only a return the engine handled did, - /// and `irq%` counted the user time after native returns. - #[test] - fn a_native_exception_return_or_el0_time_ends_the_interrupt() { - let mut levels = Levels::default(); - levels.interrupt_taken(); - levels.charge(Level::Kernel, 5); - levels.exception_returned(); - levels.charge(Level::Kernel, 7); - assert_eq!((levels.interrupts, levels.interrupt_ticks), (1, 5)); - levels.interrupt_taken(); - levels.charge(Level::Guarded, 2); - levels.charge(Level::User, 30); - levels.charge(Level::Kernel, 4); - assert_eq!((levels.interrupts, levels.interrupt_ticks), (2, 7)); - assert!(!levels.in_interrupt); - // In-interrupt time never exceeds kernel and guarded time. - let handlers = levels.ticks[Level::Kernel as usize] + levels.ticks[Level::Guarded as usize]; - assert!(levels.interrupt_ticks <= handlers); - } - - #[test] - fn completed_phase_maxima_keep_their_materialized_witness_and_clock_samples() { - let mut machine = super::super::tests::machine(&[]); - machine.set_step_timing(true); - let reads = machine.host.counter_reads; - machine.host.now = 100; - machine.cpu.pc = 0x4000; - machine.cpu.pstate.el = 1; - machine.cpu.pstate.daif = 2; - assert_eq!(machine.timing_charge(Phase::Fetch, 90), 100); - let first = Maximum { - ticks: 10, - finished_ticks: 100, - pc_after: 0x4000, - el_after: 1, - daif_after: 2, - }; - assert_eq!( - machine.step_timing().unwrap().lifetime_maxima[Phase::Fetch as usize], - first - ); - machine.host.now = 115; - machine.cpu.pc = 0x5000; - machine.timing_charge(Phase::Fetch, 110); - machine.host.now = 125; - machine.timing_charge(Phase::Fetch, 115); - // Smaller and tied intervals preserve the original witness. - assert_eq!( - machine.step_timing().unwrap().lifetime_maxima[Phase::Fetch as usize], - first - ); - machine.host.now = 200; - machine.cpu.pstate.el = 2; - machine.cpu.pstate.daif = 15; - machine.timing_charge(Phase::Fetch, 150); - let timing = machine.step_timing().unwrap(); - assert_eq!(timing.phases[Phase::Fetch as usize], 75); - assert_eq!( - timing.lifetime_maxima[Phase::Fetch as usize], - Maximum { - ticks: 50, - finished_ticks: 200, - pc_after: 0x5000, - el_after: 2, - daif_after: 15 - } - ); - // Exit/fault accounting uses its existing sample too, including wrap. - machine.host.now = 4; - machine.timing_exit(FAULT_SLOT, u64::MAX - 8); - let timing = machine.step_timing().unwrap(); - assert_eq!(timing.exits[FAULT_SLOT], (1, 13)); - assert_eq!(timing.phases[Phase::Exit as usize], 13); - assert_eq!( - timing.lifetime_maxima[Phase::Exit as usize], - Maximum { - ticks: 13, - finished_ticks: 4, - pc_after: 0x5000, - el_after: 2, - daif_after: 15 - } - ); - assert_eq!(machine.host.counter_reads - reads, 5); - } - - #[test] - fn a_device_faults_ticks_go_to_the_register_it_reached() { - const REGISTER: u64 = 0x2_3520_0018; - let mut machine = super::super::tests::machine(&[]); - machine.set_step_timing(true); - machine.count_device_access(REGISTER); - machine.host.now = 30; - machine.timing_exit(DEVICE_FAULT_SLOT, 10); - // Another exit's ticks are not the register's, even after an - // access it did not fault for. - machine.count_device_access(REGISTER); - machine.host.now = 100; - machine.timing_exit(FAULT_SLOTS, 40); - machine.host.now = 120; - machine.timing_exit(DEVICE_FAULT_SLOT, 110); - assert_eq!( - machine.device_registers()[®ISTER], - super::super::DeviceRegister { - accesses: 2, - ticks: 20 - } - ); - } - - /// A native check fault is charged to what the engine found at it, once; - /// another exit keeps its slot and leaves the finding alone. - #[test] - fn check_faults_are_charged_by_outcome() { - assert_eq!( - fault_slot(&super::super::FaultCause::NonCanonical), - CHECK_FAULT_SLOT - ); - let slots = [ - Check::Tagged, - Check::Alignment, - Check::Abort, - Check::Translated, - ] - .map(Check::slot); - assert_eq!(slots, [19, 20, 21, 22]); - assert_eq!(EXIT_SLOTS, 23); - let mut machine = super::super::tests::machine(&[]); - machine.set_step_timing(true); - machine.timed_check(Check::Tagged); - machine.timing_exit(CHECK_FAULT_SLOT, 0); - machine.timing_exit(CHECK_FAULT_SLOT, 0); - machine.timed_check(Check::Abort); - machine.timing_exit(FAULT_SLOTS, 0); - let exits = machine.step_timing().unwrap().exits; - assert_eq!(exits[Check::Tagged.slot()].0, 1); - assert_eq!(exits[CHECK_FAULT_SLOT].0, 1); - assert_eq!(exits[FAULT_SLOTS].0, 1); - assert_eq!(exits[Check::Abort.slot()].0, 0); - assert_eq!(machine.step_timing().unwrap().check, None); - } - - #[test] - fn resetting_timing_clears_maxima_and_disabled_timing_reads_no_clock() { - let mut machine = super::super::tests::machine(&[]); - let reads = machine.host.counter_reads; - assert_eq!(machine.timing_start(), 0); - assert_eq!(machine.timing_charge(Phase::Fetch, 0), 0); - machine.timing_exit(FAULT_SLOT, 0); - assert_eq!(machine.host.counter_reads, reads); - machine.set_step_timing(true); - machine.host.now = 20; - machine.timing_charge(Phase::Native, 10); - assert_eq!( - machine.step_timing().unwrap().lifetime_maxima[Phase::Native as usize].ticks, - 10 - ); - let reads = machine.host.counter_reads; - machine.set_step_timing(true); - assert_eq!(machine.step_timing(), Some(&StepTiming::default())); - machine.set_step_timing(false); - assert!(machine.step_timing().is_none()); - machine.timing_exit(FAULT_SLOT, 0); - assert_eq!(machine.host.counter_reads, reads); - } -} +//! `--profile`: where a run's host time goes between translated blocks, by +//! phase of the engine's step loop and by the exit kind the engine handles. +//! The host supplies the clock ([`super::Host::profile_ticks`]); while off, +//! each phase boundary costs one branch. + +pub mod pc_samples; +mod regions; +pub use pc_samples::{BlockSample, NO_BLOCK, PcBlock, PcHit, PcSamples}; +pub use regions::{CodeRegion, block_regions, pointer_service_calls}; + +/// Words of a PE's PAC census (`Statistics` `pac_census`): cipher runs by +/// key (IA, IB, DA, DB, GA) and operation (signing, authentication, +/// PACGA), then by cause (new, here, other), then those of native code, +/// then new key generations. +pub const PAC_CENSUS_WORDS: usize = super::pointer::census::WORDS; + +/// A phase of the step loop ([`super::Machine::run_blocks`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(usize)] +pub enum Phase { + /// Choosing the PE to run, ending slices and waiting. + Schedule, + /// Due device work and interrupt delivery before each step. + Devices, + /// Finding the next block, compiling and installing it when new. + Fetch, + /// Translated code, chained blocks included. + Native, + /// Handling the exit translated code returned with, by kind. + Exit, +} + +impl Phase { + pub const COUNT: usize = Self::Exit as usize + 1; + pub const ALL: [Self; Self::COUNT] = [ + Self::Schedule, + Self::Devices, + Self::Fetch, + Self::Native, + Self::Exit, + ]; + + pub fn name(self) -> &'static str { + match self { + Self::Schedule => "schedule", + Self::Devices => "devices", + Self::Fetch => "fetch", + Self::Native => "native", + Self::Exit => "exit", + } + } +} + +/// The exits [`StepTiming::exits`] counts: each `ExitKind`, then native +/// faults by cause ([`fault_slot`]), then [`DEVICE_SITE_SLOT`], then the +/// native check faults by what the engine found ([`Check`]). +pub const EXIT_SLOTS: usize = CHECK_SLOTS + Check::COUNT; +/// [`StepTiming::exits`]' first native-fault slot. +const FAULT_SLOTS: usize = 13; +/// The slot of native faults that reached a device ([`fault_slot`]). +pub const DEVICE_FAULT_SLOT: usize = FAULT_SLOTS + 1; +/// The slot of native check faults (`FaultCause::NonCanonical` and +/// `InvalidOpcode`) whose outcome no [`Check`] names. +pub const CHECK_FAULT_SLOT: usize = FAULT_SLOTS + 2; +/// The slot of System exits at a device site's stub: device accesses the +/// engine completes (`Machine::complete_device_site`), not System +/// instructions. +pub const DEVICE_SITE_SLOT: usize = FAULT_SLOTS + 5; +/// [`StepTiming::exits`]' first [`Check`] slot. +const CHECK_SLOTS: usize = DEVICE_SITE_SLOT + 1; + +/// What the engine found at a native check fault, which takes the fault's +/// slot from [`CHECK_FAULT_SLOT`] ([`Check::slot`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(usize)] +pub enum Check { + /// A tagged address that translates under TBI, run again untagged by a + /// single-instruction block (`Machine::retry_untagged`). + Tagged, + /// An Alignment fault: SP alignment, SCTLR_ELx.A, or an atomic or + /// ordered access crossing its granule. + Alignment, + /// An address outside the native ranges whose translation faults: a + /// Data Abort. + Abort, + /// An untagged address the host does not map natively: the page runs in + /// the translated variant. + Translated, +} + +impl Check { + pub const COUNT: usize = Self::Translated as usize + 1; + + /// Its slot in [`StepTiming::exits`]. + pub const fn slot(self) -> usize { + CHECK_SLOTS + self as usize + } +} + +/// The [`SystemExits`] key of an exit at a device site's stub. No System +/// instruction has this word. +pub const DEVICE_SITE_KEY: u32 = u32::MAX; + +/// The [`SystemExits`] key of the System exit at instruction `word`: the +/// word without the registers it names, so one register's MRS from every +/// Xt counts together. +pub fn system_key(word: u32) -> u32 { + match word >> 24 { + // MRS, MSR, SYS, SYSL, hints and barriers: Rt. + 0xd5 => word & !0x1f, + // Exclusives: Rs, Rt2, Rn and Rt. + 0x08 | 0x48 | 0x88 | 0xc8 => word & !0x001f_7fff, + // LDTR and STTR forms: imm9, Rn and Rt. + 0x38 | 0x78 | 0xb8 | 0xf8 => word & !0x001f_f3ff, + _ => word, + } +} + +/// Whether [`SystemExits`] key `key` is a floating-point exit's word, which +/// the engine charges by the whole word next to the System keys; no System +/// key decodes as numerical FP. +pub fn numerical_key(key: u32) -> bool { + key != DEVICE_SITE_KEY + && matches!( + stela_compiler::aarch64::FloatingPointOperation::decode(key), + Some(Ok(_)) + ) +} + +/// Whether [`SystemExits`] key `key` is a pointer authentication exit's +/// word (an authenticated branch, return or load, or a PAC form a closed +/// key cell sent to the engine), which the report shows apart from the +/// System keys; no System key decodes as one. +pub fn pointer_key(key: u32) -> bool { + key != DEVICE_SITE_KEY + && matches!( + stela_compiler::block::decode_pointer_authentication( + stela_compiler::GuestAddress(0), + register_word(key) + ), + Ok(Some(_)) + ) +} + +/// The word of [`system_key`] `key` with its MRS, MSR, SYS, SYSL or hint +/// Rt set to 31, which the key cleared. +fn register_word(key: u32) -> u32 { + if key >> 24 == 0xd5 { key | 0x1f } else { key } +} + +/// Whether [`system_key`] `key` is a WFE, WFI, WFET or WFIT: of class +/// [`SystemClass::Wait`], found by one decode, without the name +/// [`SystemClass::of`] builds for it. +pub fn wait_key(key: u32) -> bool { + use stela_compiler::aarch64::system::synchronization::{Operation, decode}; + matches!(decode(register_word(key)), Some(Operation::Wait { .. })) +} + +/// A short name of [`system_key`] `key` for reports: the accessor's for +/// MRS, MSR, SYS and SYSL (`MRS_TPIDR_EL1`, `TLBI_VAE1IS`), else the +/// operation's kind and the key (`Exception.ExceptionReturn:0xd69f03e0`). +pub fn system_key_name(key: u32) -> alloc::string::String { + use stela_compiler::aarch64::system::registers::{self, Direction}; + if key == DEVICE_SITE_KEY { + return "device-site".into(); + } + if let Some(Ok(operation)) = stela_compiler::aarch64::FloatingPointOperation::decode(key) { + let debug = alloc::format!("{operation:?}"); + let kind = debug.split(['(', ' ', '{']).next().unwrap_or("FP"); + return alloc::format!("{kind}:{key:#010x}"); + } + if let Ok(Some(instruction)) = stela_compiler::block::decode_pointer_authentication( + stela_compiler::GuestAddress(0), + register_word(key), + ) { + let debug = alloc::format!("{:?}", instruction.operation); + let kind = debug.split(['(', ' ', '{']).next().unwrap_or("PAC"); + return alloc::format!("PAC.{kind}:{key:#010x}"); + } + let word = register_word(key); + let access = registers::decode(word) + .map(|access| (access, true)) + .or_else(|| registers::decode_sys(word).map(|access| (access, false))); + if let Some((access, register)) = access { + let read = access.direction() == Direction::Read; + let encoding = access.encoding(); + if let Some((accessor, _)) = crate::machine::system::Lookup::new().find(encoding, read) { + return accessor + .name + .replace("MSRregister", "MSR") + .replace(' ', "_"); + } + let kind = match (register, read) { + (true, true) => "MRS", + (true, false) => "MSR", + (false, true) => "SYSL", + (false, false) => "SYS", + }; + return alloc::format!( + "{kind}_S{}_{}_C{}_C{}_{}", + encoding.op0(), + encoding.op1(), + encoding.crn(), + encoding.crm(), + encoding.op2() + ); + } + let operation = stela_compiler::block::decode_system_mode_instruction( + stela_compiler::GuestAddress(0), + word, + ) + .ok() + .flatten() + .map(|instruction| alloc::format!("{:?}", instruction.operation)); + let kind = operation + .as_deref() + .and_then(|debug| debug.split([' ', '{', ')']).next()) + .unwrap_or("word") + .trim_end_matches('(') + .replace('(', "."); + alloc::format!("{kind}:{key:#010x}") +} + +/// What a System exit key does, for the per-class totals of `PES SYSTEM`, +/// which leave no key out: device sites; Apple's compression instructions; +/// barriers; TLB and cache maintenance and address translation (TLBI, IC, +/// DC, AT: SYS with CRn 7 or 8); waits (WFE, WFI); the generic timer's +/// registers (CRn 14); implementation-defined registers (CRn 15: Apple's +/// counters, IPIs and controls); the translation controls (SCTLR, CPACR, +/// TTBRn, TCR, MAIR, CONTEXTIDR: CRn 1, 2, 10, 13); exception entries and +/// returns and guarded-level transitions; and everything else. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SystemClass { + Device, + Compression, + Barrier, + Maintenance, + Wait, + Timer, + ImplementationDefined, + TranslationControl, + Transition, + Other, +} + +impl SystemClass { + pub const COUNT: usize = Self::Other as usize + 1; + pub const NAMES: [&'static str; Self::COUNT] = [ + "device", + "compression", + "barrier", + "maintenance", + "wait", + "timer", + "impdef", + "translation", + "transition", + "other", + ]; + + /// The class of System exit key `key`. + pub fn of(key: u32) -> Self { + use stela_compiler::aarch64::system::registers; + if key == DEVICE_SITE_KEY { + return Self::Device; + } + let word = if key >> 24 == 0xd5 { key | 0x1f } else { key }; + if let Some(access) = registers::decode(word) { + let encoding = access.encoding(); + return match (encoding.op0(), encoding.crn()) { + (3, 15) => Self::ImplementationDefined, + (3, 14) => Self::Timer, + (3, 1 | 2 | 10 | 13) => Self::TranslationControl, + _ => Self::Other, + }; + } + if let Some(access) = registers::decode_sys(word) { + return match access.encoding().crn() { + 7 | 8 => Self::Maintenance, + _ => Self::Other, + }; + } + let name = system_key_name(key); + match name.split(['.', ':']).next().unwrap_or_default() { + "Compression" => Self::Compression, + "Synchronization" => Self::Barrier, + "Wait" => Self::Wait, + "Exception" | "Guarded" => Self::Transition, + _ => Self::Other, + } + } +} + +/// One [`SystemExits`] key's exits, the ticks handling them, and how many +/// of them closed every mirror cell (`Machine::derived_changed`), after +/// which each MRS and MSR site exits again once. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SystemExit { + pub key: u32, + pub count: u64, + pub ticks: u64, + pub closes: u64, +} + +impl SystemExit { + fn add(&mut self, count: u64, ticks: u64, closes: u64) { + self.count += count; + self.ticks += ticks; + self.closes += closes; + } +} + +/// System exits by [`system_key`] since they were last taken, under step +/// timing: an open-addressed table, with the keys past its size in `other`; +/// the device accesses the engine completed; and the floating-point exits +/// by what their completion found ([`FloatingReason`]), in all and by word +/// with their operands ([`FloatingWords`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SystemExits { + pub entries: [SystemExit; SYSTEM_KEYS], + pub other: SystemExit, + pub devices: DeviceExits, + pub floating: [u64; FloatingReason::COUNT], + pub floating_words: FloatingWords, + pub barriers: BarrierWaits, + pub regimes: RegimeSyncs, + /// WKDMC, then WKDMD ([`Compression`]). + pub compression: [Compression; 2], + /// Where sampled System exits' round trips went ([`ExitPaths`]). + pub paths: ExitPaths, +} + +/// The points a traced System exit's round trip passes ([`ExitTrace`]), in +/// order: native code's return in the host, the engine's adoption of what +/// it did, the start and end of the profile's look at the exit's word, the +/// end of the service, of its links and charge, the start and end of the +/// next schedule, the end of the devices' and the fetch's phases, and the +/// host's next entry into native code. +pub const PATH_RETURNED: usize = 0; +pub const PATH_ADOPTED: usize = 1; +pub const PATH_WORD: usize = 2; +pub const PATH_SERVICE: usize = 3; +pub const PATH_SERVED: usize = 4; +pub const PATH_CLOSED: usize = 5; +pub const PATH_SCHEDULE: usize = 6; +pub const PATH_SCHEDULED: usize = 7; +pub const PATH_DEVICES: usize = 8; +pub const PATH_FETCHED: usize = 9; +pub const PATH_ENTERED: usize = 10; +const PATH_POINTS: usize = PATH_ENTERED + 1; + +/// The segments between the [`ExitTrace`] points, as `PES EXIT PATH` names +/// them. +pub const PATH_SEGMENTS: usize = PATH_POINTS - 1; +pub const PATH_NAMES: [&str; PATH_SEGMENTS] = [ + "back", "prelude", "word", "service", "close", "loop", "schedule", "devices", "fetch", "enter", +]; + +/// One System exit in this many is traced: a few hundred cycles of stamps +/// on one in 64 keep the trace's cost far below the step timing's own. +pub const PATH_EVERY: u32 = 64; + +/// Sampled System exits' round trips under step timing, from native code's +/// return to its next entry, by segment ([`PATH_NAMES`]): the exits traced +/// and those whose trace another path ended first (an interrupt taken, an +/// exception, the run loop left); within the traced services, the host's +/// regime syncs and prediction isolations; and every change of derived +/// state that closed every mirror cell, with the open cells it closed, each +/// of which costs an exit to open again where code reaches it; and the TCR +/// writes that kept them (`Machine::layout_written`), with the open cells +/// they kept; and the System exits after which the run loop fetched at once +/// (`Machine::continues_directly`), traced or not. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct ExitPaths { + pub traced: u64, + pub abandoned: u64, + pub ticks: [u64; PATH_SEGMENTS], + pub syncs: u64, + pub sync_ticks: u64, + pub isolations: u64, + pub isolation_ticks: u64, + pub closes: u64, + pub cells_closed: u64, + pub layouts: u64, + pub cells_kept: u64, + pub direct: u64, +} + +impl ExitPaths { + /// Add everything `other` counts. + pub fn merge(&mut self, other: &Self) { + self.traced += other.traced; + self.abandoned += other.abandoned; + for (ticks, more) in self.ticks.iter_mut().zip(other.ticks) { + *ticks += more; + } + self.syncs += other.syncs; + self.sync_ticks += other.sync_ticks; + self.isolations += other.isolations; + self.isolation_ticks += other.isolation_ticks; + self.closes += other.closes; + self.cells_closed += other.cells_closed; + self.layouts += other.layouts; + self.cells_kept += other.cells_kept; + self.direct += other.direct; + } +} + +/// The System exit being traced on a PE, if any: the profile ticks at each +/// point it passed ([`PATH_RETURNED`] and on), the next point it expects, +/// and the syncs its service made. A point out of order abandons it, as +/// does leaving the run loop; the next native entry folds it into +/// [`ExitPaths`]. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct ExitTrace { + countdown: u32, + next: usize, + stamps: [u64; PATH_POINTS], + syncs: [u64; 4], +} + +impl ExitTrace { + /// Whether the next System exit is one to trace. + #[inline] + pub fn due(&mut self) -> bool { + if self.countdown != 0 { + self.countdown -= 1; + return false; + } + true + } + + /// Trace the System exit native code returned for at `returned` (the + /// host's ticks, 0 where it keeps none), which the engine adopted by + /// `adopted`, its word looked at from `now`. + pub fn begin(&mut self, returned: u64, adopted: u64, now: u64) { + self.countdown = PATH_EVERY - 1; + let returned = if returned == 0 || returned > adopted { + adopted + } else { + returned + }; + self.stamps[PATH_RETURNED] = returned; + self.stamps[PATH_ADOPTED] = adopted; + self.stamps[PATH_WORD] = now; + self.syncs = [0; 4]; + self.next = PATH_SERVICE; + } + + /// Drop the exit begun, which is not one to trace (a wait, a device + /// site): the next System exit is traced instead. + pub fn cancel(&mut self) { + self.next = 0; + self.countdown = 0; + } + + #[inline] + pub fn open(&self) -> bool { + self.next != 0 + } + + /// Whether the traced exit's service runs. + #[inline] + pub fn in_service(&self) -> bool { + self.next == PATH_SERVED + } + + /// The trace reached `point` at `now`; out of order, it is abandoned. + pub fn stamp(&mut self, point: usize, now: u64, paths: &mut ExitPaths) { + if self.next == 0 { + return; + } + if self.next != point { + return self.abandon(paths); + } + self.stamps[point] = now; + self.next = point + 1; + } + + /// End the trace without a sample. + pub fn abandon(&mut self, paths: &mut ExitPaths) { + if self.next != 0 { + self.next = 0; + paths.abandoned += 1; + } + } + + /// The service synchronized the host's regime in `ticks`, and isolated + /// its predictions in `isolated`'s. + pub fn sync(&mut self, ticks: u64, isolated: Option) { + self.syncs[0] += 1; + self.syncs[1] += ticks; + if let Some(isolated) = isolated { + self.syncs[2] += 1; + self.syncs[3] += isolated; + } + } + + /// Native code was entered again at `entered` (the host's ticks, 0 + /// where it keeps none): the trace ends and its segments count. + pub fn finish(&mut self, entered: u64, paths: &mut ExitPaths) { + if self.next == 0 { + return; + } + if self.next != PATH_ENTERED { + return self.abandon(paths); + } + let fetched = self.stamps[PATH_FETCHED]; + self.stamps[PATH_ENTERED] = if entered < fetched { fetched } else { entered }; + for (segment, ticks) in paths.ticks.iter_mut().enumerate() { + *ticks += self.stamps[segment + 1].saturating_sub(self.stamps[segment]); + } + paths.traced += 1; + paths.syncs += self.syncs[0]; + paths.sync_ticks += self.syncs[1]; + paths.isolations += self.syncs[2]; + paths.isolation_ticks += self.syncs[3]; + self.next = 0; + } +} + +/// The host's regime changes ([`super::Host::set_regime`]) and prediction +/// isolations ([`super::Host::isolate_predictions`]) under step timing: how +/// many and their profile ticks. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct RegimeSyncs { + pub syncs: u64, + pub sync_ticks: u64, + pub isolations: u64, + pub isolation_ticks: u64, + /// The syncs that gave the host the regime it had and isolated nothing. + pub unchanged: u64, + /// The syncs by what asked for them ([`SyncSource`]). + pub sources: [u64; SyncSource::COUNT], +} + +/// What asked for a regime sync ([`RegimeSyncs::sources`]): a PAN change by +/// MSR in the engine, a PAN change native code made, a translation change +/// (an SPRR_PERM write and others), a TTBR0 write, an exception entry or +/// return or GXF transition the engine made, a change of derived state, and +/// anything else. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SyncSource { + Pan, + NativePan, + Translation, + TableBase, + Transition, + Derived, + Other, +} + +impl SyncSource { + pub const COUNT: usize = Self::Other as usize + 1; + pub const NAMES: [&str; Self::COUNT] = [ + "pan", + "native_pan", + "translation", + "table_base", + "transition", + "derived", + "other", + ]; +} + +impl RegimeSyncs { + /// Add every change `other` counts. + pub fn merge(&mut self, other: &Self) { + self.syncs += other.syncs; + self.sync_ticks += other.sync_ticks; + self.isolations += other.isolations; + self.isolation_ticks += other.isolation_ticks; + self.unchanged += other.unchanged; + for (count, more) in self.sources.iter_mut().zip(other.sources) { + *count += more; + } + } +} + +/// The [`BarrierWaits`] blocker of a PE in native code. +pub const BLOCKER_NATIVE: u64 = 1; +/// The [`BarrierWaits`] blocker of a PE that entered a fetched block and +/// prepares its native run, or takes the fetch's exception or checked +/// instruction. +pub const BLOCKER_ENTERING: u64 = 2; +/// The [`BarrierWaits`] blocker of a PE whose native run returned, before +/// it knows the exit. +pub const BLOCKER_RETURNED: u64 = 3; +/// Bit 63 of a blocker: a PE completing an exit of the slot in bits 32-62 +/// at the [`system_key`] in bits 0-31 (0 where the exit has no word). +pub const BLOCKER_EXIT: u64 = 1 << 63; +/// The blockers [`BarrierWaits`] holds apart. +pub const BARRIER_BLOCKERS: usize = 32; + +/// The blocker of PE in an exit of `slot` at `word`. +pub fn exit_blocker(slot: usize, word: Option) -> u64 { + BLOCKER_EXIT | (slot as u64) << 32 | u64::from(word.map_or(0, system_key)) +} + +/// The waits for one blocker: how many and their ticks. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct BarrierBlocker { + pub key: u64, + pub count: u64, + pub ticks: u64, +} + +/// DSBs that completed maintenance this PE posted, under step timing: how +/// many, those that found every PE had applied it at the first look +/// (`quick`), and the profile ticks they spent; and by the last PE they +/// waited for, what that PE was doing when last seen (its blocker: native +/// code, [`BLOCKER_NATIVE`], or an exit, [`exit_blocker`]), with the rest in +/// `other`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BarrierWaits { + pub waits: u64, + pub quick: u64, + pub ticks: u64, + pub blockers: [BarrierBlocker; BARRIER_BLOCKERS], + pub other: BarrierBlocker, +} + +impl Default for BarrierWaits { + fn default() -> Self { + Self { + waits: 0, + quick: 0, + ticks: 0, + blockers: [BarrierBlocker::default(); BARRIER_BLOCKERS], + other: BarrierBlocker::default(), + } + } +} + +impl BarrierWaits { + /// Count a wait of `ticks`: one that waited for a PE last seen at + /// `blocker`, or `None` when none was waited for. + pub fn add(&mut self, blocker: Option, ticks: u64) { + self.waits += 1; + self.ticks += ticks; + match blocker { + None => self.quick += 1, + Some(key) => self.add_blocker(key, 1, ticks), + } + } + + fn add_blocker(&mut self, key: u64, count: u64, ticks: u64) { + let entry = match self + .blockers + .iter() + .position(|entry| entry.count == 0 || entry.key == key) + { + Some(index) => &mut self.blockers[index], + None => &mut self.other, + }; + if entry.count == 0 { + entry.key = key; + } + entry.count += count; + entry.ticks += ticks; + } + + /// Add every wait `other` counts. + pub fn merge(&mut self, other: &Self) { + self.waits += other.waits; + self.quick += other.quick; + self.ticks += other.ticks; + for entry in other.blockers.iter().filter(|entry| entry.count != 0) { + self.add_blocker(entry.key, entry.count, entry.ticks); + } + self.other.count += other.other.count; + self.other.ticks += other.other.ticks; + } +} + +/// WKDMC or WKDMD instructions the engine completed under step timing, and +/// the ticks of their handling split: the whole handler; reading the source +/// through translated guest memory; the codec; and writing the destination +/// (the host's publication of the bytes into guest RAM). The rest of the +/// handler is translation checks and the result; the rest of the exit, in +/// `SYSTEM WORDS`, is leaving and entering the guest. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Compression { + pub count: u64, + pub whole: u64, + pub read: u64, + pub codec: u64, + pub write: u64, +} + +impl Compression { + /// Count one of `whole` ticks: `parts` are its read, codec and write. + pub fn add(&mut self, whole: u64, parts: [u64; 3]) { + self.count += 1; + self.whole += whole; + self.read += parts[0]; + self.codec += parts[1]; + self.write += parts[2]; + } + + fn merge(&mut self, other: &Self) { + self.count += other.count; + self.whole += other.whole; + self.read += other.read; + self.codec += other.codec; + self.write += other.write; + } +} + +/// What the software completion of a floating-point exit found, which names +/// the guard that sent it there: an enabled trap (FPCR's enables, which every +/// recipe sends to the helper), the first fresh FPSR flag in Arm's order +/// (invalid: NaN or invalid operation; divide by zero; overflow; underflow: a +/// tiny result; input denormal flushed), inexact alone, no flag (exact: a +/// signed zero, an infinity, a quiet NaN, a subnormal input or result that +/// was exact, or a form without an inline recipe), and apart from those, how +/// many ran with FZ, FZ16, FIZ, AH or DN set (`Mode`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FloatingReason { + Trap, + Invalid, + Divide, + Overflow, + Underflow, + Denormal, + Inexact, + Exact, + Mode, +} + +impl FloatingReason { + pub const COUNT: usize = Self::Mode as usize + 1; + pub const NAMES: [&'static str; Self::COUNT] = [ + "trap", + "invalid", + "divide", + "overflow", + "underflow", + "denormal", + "inexact", + "exact", + "mode", + ]; + + /// The reason of a completion with fresh cumulative flags `fresh` + /// (FPSR's bit layout) that trapped (`trapped`) or not under `fpcr`. + pub fn of(fpcr: u32, fresh: u32, trapped: bool) -> Self { + use stela_compiler::aarch64::floating::FPCR_EXCEPTION_ENABLE_MASK; + const FLAGS: [(u32, FloatingReason); 6] = [ + (1 << 0, FloatingReason::Invalid), + (1 << 1, FloatingReason::Divide), + (1 << 2, FloatingReason::Overflow), + (1 << 3, FloatingReason::Underflow), + (1 << 7, FloatingReason::Denormal), + (1 << 4, FloatingReason::Inexact), + ]; + if trapped || fpcr & FPCR_EXCEPTION_ENABLE_MASK != 0 { + return Self::Trap; + } + FLAGS + .iter() + .find(|(flag, _)| fresh & flag != 0) + .map_or(Self::Exact, |&(_, reason)| reason) + } + + /// Whether `fpcr` selects a flushing or alternative mode. + pub fn moded(fpcr: u32) -> bool { + use stela_compiler::aarch64::floating::{FPCR_AH, FPCR_DN, FPCR_FIZ, FPCR_FZ, FPCR_FZ16}; + fpcr & (FPCR_FZ | FPCR_FZ16 | FPCR_FIZ | FPCR_AH | FPCR_DN) != 0 + } +} + +/// What the operands of a floating-point exit held, which names the recipe +/// guard that sent it to the engine where its flags do not (a subnormal +/// input raises no flag with FZ clear, a quiet NaN none at all): a NaN, a +/// subnormal, a zero or an infinity in an active source lane; a nonzero +/// result lane below twice the minimum normal (`Tiny`, which recipes leave +/// to the engine in case it was tiny before rounding); none of those +/// (`Ordinary`); and a form whose lanes [`census_lanes`] does not read +/// (`Unread`). An exit counts in every class its operands show. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Operands { + Nan, + Subnormal, + Zero, + Infinite, + Tiny, + Ordinary, + Unread, +} + +impl Operands { + pub const COUNT: usize = Self::Unread as usize + 1; + pub const NAMES: [&'static str; Self::COUNT] = [ + "nan", + "subnormal", + "zero", + "infinite", + "tiny", + "ordinary", + "unread", + ]; + + const fn bit(self) -> u8 { + 1 << self as u8 + } +} + +/// A register the census reads: its lanes, from one lane alone when +/// indexed. +#[derive(Debug, Clone, Copy)] +struct CensusRegister { + register: u8, + lane: Option, + lanes: u32, +} + +impl CensusRegister { + const fn whole(register: u8, lanes: u32) -> Self { + Self { + register, + lane: None, + lanes, + } + } +} + +/// The lanes of an operation the census reads: its format, up to three +/// sources and the result. +#[derive(Debug, Clone, Copy)] +struct CensusLanes { + format: stela_compiler::aarch64::floating::Format, + sources: [Option; 3], + result: CensusRegister, +} + +/// The lanes [`Operands`] classifies for the families with the most exits +/// (fused, binary arithmetic, min/max, estimates, roots and rounding); none +/// for the rest, which count as [`Operands::Unread`]. +fn census_lanes( + operation: &stela_compiler::aarch64::FloatingPointOperation, +) -> Option { + use stela_compiler::aarch64::{ + FloatingPointOperation as Operation, + simd::{arithmetic::Inputs, estimate::Kind, minmax}, + }; + let whole = CensusRegister::whole; + let lanes = + |format, shape: stela_compiler::aarch64::simd::arithmetic::Shape| shape.lane_count(format); + Some(match operation { + Operation::Fused(operand) => { + let count = lanes(operand.format, operand.shape); + CensusLanes { + format: operand.format, + sources: [ + Some(whole(operand.left, count)), + Some(CensusRegister { + register: operand.right, + lane: operand.right_lane, + lanes: count, + }), + Some(whole(operand.addend, count)), + ], + result: whole(operand.destination, count), + } + } + Operation::Binary(operand) => { + let count = lanes(operand.format, operand.shape); + let (left, right) = match operand.inputs { + Inputs::Elementwise { left, right } | Inputs::Pairwise { left, right } => { + (whole(left, count), Some(whole(right, count))) + } + Inputs::Indexed { + left, + right, + right_lane, + } => ( + whole(left, count), + Some(CensusRegister { + register: right, + lane: Some(right_lane), + lanes: count, + }), + ), + Inputs::PairwiseScalar { source } => (whole(source, 2), None), + }; + CensusLanes { + format: operand.format, + sources: [Some(left), right, None], + result: whole(operand.destination, count), + } + } + Operation::MinMax(operand) => match *operand { + minmax::Operand::Binary { + format, + shape, + destination, + left, + right, + .. + } => { + let count = lanes(format, shape); + CensusLanes { + format, + sources: [Some(whole(left, count)), Some(whole(right, count)), None], + result: whole(destination, count), + } + } + minmax::Operand::PairwiseScalar { + format, + destination, + source, + .. + } => CensusLanes { + format, + sources: [Some(whole(source, 2)), None, None], + result: whole(destination, 1), + }, + minmax::Operand::Reduction { + format, + shape, + destination, + source, + .. + } => CensusLanes { + format, + sources: [Some(whole(source, lanes(format, shape))), None, None], + result: whole(destination, 1), + }, + }, + Operation::Estimate(operand) + if !matches!( + operand.kind, + Kind::UnsignedReciprocal | Kind::UnsignedReciprocalSquareRoot + ) => + { + let count = lanes(operand.format, operand.shape); + CensusLanes { + format: operand.format, + sources: [Some(whole(operand.source, count)), None, None], + result: whole(operand.destination, count), + } + } + Operation::SquareRoot(operand) => { + let count = lanes(operand.format, operand.shape); + CensusLanes { + format: operand.format, + sources: [Some(whole(operand.source, count)), None, None], + result: whole(operand.destination, count), + } + } + Operation::Rounding(operand) => { + let count = lanes(operand.format, operand.shape); + CensusLanes { + format: operand.format, + sources: [Some(whole(operand.source, count)), None, None], + result: whole(operand.destination, count), + } + } + _ => return None, + }) +} + +/// The lane `lane` of `format` in vector `vector`. +fn census_lane( + vector: &[u64; 2], + format: stela_compiler::aarch64::floating::Format, + lane: u32, +) -> u64 { + let bits = format.bits(); + let offset = lane * bits; + let word = vector[(offset / u64::BITS) as usize] >> (offset % u64::BITS); + word & (u64::MAX >> (u64::BITS - bits)) +} + +/// The exponent field and the fraction of `format` value `bits`, and the +/// field's all-ones value. +fn census_fields(bits: u64, format: stela_compiler::aarch64::floating::Format) -> (u64, u64, u64) { + use stela_compiler::aarch64::floating::Format; + let (exponent_bits, fraction_bits) = match format { + Format::Half => (5, 10), + Format::Single => (8, 23), + Format::Double => (11, 52), + }; + let maximum = (1 << exponent_bits) - 1; + ( + (bits >> fraction_bits) & maximum, + bits & ((1 << fraction_bits) - 1), + maximum, + ) +} + +/// The operand census of one floating-point exit: what its sources held +/// before the completion ([`FloatingCensus::read`]), then what its result +/// held after it ([`FloatingCensus::finish`]). +#[derive(Debug, Clone, Copy)] +pub struct FloatingCensus { + lanes: Option, + classes: u8, +} + +impl FloatingCensus { + /// Classify the active source lanes of `operation` in `state`. + pub fn read( + state: &stela_compiler::GuestState, + operation: &stela_compiler::aarch64::FloatingPointOperation, + ) -> Self { + let lanes = census_lanes(operation); + let mut classes = 0; + let sources = lanes.iter().flat_map(|lanes| { + lanes + .sources + .iter() + .flatten() + .map(move |source| (lanes.format, source)) + }); + for (format, source) in sources { + let vector = &state.v[usize::from(source.register & 31)]; + for lane in 0..source.lanes { + let bits = census_lane(vector, format, source.lane.map_or(lane, u32::from)); + let (exponent, fraction, maximum) = census_fields(bits, format); + classes |= match (exponent, fraction == 0) { + (0, true) => Operands::Zero.bit(), + (0, false) => Operands::Subnormal.bit(), + (e, true) if e == maximum => Operands::Infinite.bit(), + (e, false) if e == maximum => Operands::Nan.bit(), + _ => 0, + }; + } + } + Self { lanes, classes } + } + + /// Add the classes of the result lanes in `state` (none when the + /// completion trapped and wrote no result), and return every class + /// seen as [`Operands`] bits. + pub fn finish(self, state: &stela_compiler::GuestState, completed: bool) -> u8 { + let Some(lanes) = self.lanes else { + return Operands::Unread.bit(); + }; + let mut classes = self.classes; + if completed { + let result = lanes.result; + let vector = &state.v[usize::from(result.register & 31)]; + for lane in 0..result.lanes { + let bits = census_lane(vector, lanes.format, lane); + let (exponent, fraction, maximum) = census_fields(bits, lanes.format); + if exponent < 2 && (exponent != 0 || fraction != 0) && exponent != maximum { + classes |= Operands::Tiny.bit(); + } + } + } + const DATA: u8 = Operands::Nan.bit() | Operands::Subnormal.bit() | Operands::Tiny.bit(); + if classes & DATA == 0 { + classes |= Operands::Ordinary.bit(); + } + classes + } +} + +/// One floating-point exit word's exits since they were last taken, by +/// [`FloatingReason`] (the `Mode` count apart from the others), by the +/// [`Operands`] classes they showed, and how many found FPSR.IXC clear, +/// where no sticky-inexact path runs. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FloatingWord { + pub key: u32, + pub reasons: [u32; FloatingReason::COUNT], + pub operands: [u32; Operands::COUNT], + pub inexact_clear: u32, +} + +impl FloatingWord { + /// Its exits: every reason but `Mode`, which they also count in. + pub fn count(&self) -> u64 { + self.reasons[..FloatingReason::Mode as usize] + .iter() + .map(|&count| u64::from(count)) + .sum() + } + + /// Add every exit `other` counts. + pub fn merge(&mut self, other: &Self) { + for (count, more) in self.reasons.iter_mut().zip(other.reasons) { + *count = count.saturating_add(more); + } + for (count, more) in self.operands.iter_mut().zip(other.operands) { + *count = count.saturating_add(more); + } + self.inexact_clear = self.inexact_clear.saturating_add(other.inexact_clear); + } +} + +/// The words [`FloatingWords`] holds apart: a beat's floating-point exits +/// have reached about 240 words machine-wide. +pub const FLOATING_WORDS: usize = 256; + +/// Floating-point exits by word with their causes ([`FloatingWord`]), +/// under step timing: an open-addressed table, with the words past its +/// size in `other`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FloatingWords { + pub entries: [FloatingWord; FLOATING_WORDS], + pub other: FloatingWord, +} + +impl Default for FloatingWords { + fn default() -> Self { + Self { + entries: [FloatingWord::default(); FLOATING_WORDS], + other: FloatingWord::default(), + } + } +} + +impl FloatingWords { + /// The entry of `key`, or `other` once the table is full. + fn entry(&mut self, key: u32) -> &mut FloatingWord { + let start = + (key.wrapping_mul(0x9e37_79b9) >> (u32::BITS - FLOATING_WORDS.ilog2())) as usize; + let found = (0..FLOATING_WORDS) + .map(|probe| (start + probe) % FLOATING_WORDS) + .find(|&index| { + let entry = &self.entries[index]; + entry.key == key || entry.count() == 0 + }); + match found { + Some(index) => { + let entry = &mut self.entries[index]; + entry.key = key; + entry + } + None => &mut self.other, + } + } + + /// Count one exit of `key` for `reason`, in `Mode` too if `moded`, + /// with [`Operands`] bits `operands`, that found FPSR.IXC clear if + /// `inexact_clear`. + pub fn add( + &mut self, + key: u32, + reason: FloatingReason, + moded: bool, + operands: u8, + inexact_clear: bool, + ) { + let entry = self.entry(key); + entry.reasons[reason as usize] = entry.reasons[reason as usize].saturating_add(1); + if moded { + let mode = &mut entry.reasons[FloatingReason::Mode as usize]; + *mode = mode.saturating_add(1); + } + for (class, count) in entry.operands.iter_mut().enumerate() { + if operands & (1 << class) != 0 { + *count = count.saturating_add(1); + } + } + entry.inexact_clear = entry.inexact_clear.saturating_add(u32::from(inexact_clear)); + } + + /// Add every exit `words` counts. + pub fn merge(&mut self, words: &Self) { + for word in words.counted() { + self.entry(word.key).merge(word); + } + self.other.merge(&words.other); + } + + /// The words with exits. + pub fn counted(&self) -> impl Iterator { + self.entries.iter().filter(|word| word.count() != 0) + } + + pub fn is_empty(&self) -> bool { + self.other.count() == 0 && self.counted().next().is_none() + } +} + +/// The keys [`SystemExits`] holds apart. The report merges every PE's into +/// one table each beat, and a process spawn alone exits on well over 128 +/// keys machine-wide: with 128 the costliest of them landed in `other` +/// (12-18 ms of exit time per spawn, unnamed). +pub const SYSTEM_KEYS: usize = 512; + +impl Default for SystemExits { + fn default() -> Self { + Self { + entries: [SystemExit::default(); SYSTEM_KEYS], + other: SystemExit::default(), + devices: DeviceExits::default(), + floating: [0; FloatingReason::COUNT], + floating_words: FloatingWords::default(), + barriers: BarrierWaits::default(), + regimes: RegimeSyncs::default(), + compression: [Compression::default(); 2], + paths: ExitPaths::default(), + } + } +} + +impl SystemExits { + /// Count `count` exits of `key` that took `ticks` and closed the cells + /// `closes` times. + pub fn add(&mut self, key: u32, count: u64, ticks: u64, closes: u64) { + let start = (key.wrapping_mul(0x9e37_79b9) >> (u32::BITS - SYSTEM_KEYS.ilog2())) as usize; + for probe in 0..SYSTEM_KEYS { + let entry = &mut self.entries[(start + probe) % SYSTEM_KEYS]; + if entry.count == 0 { + entry.key = key; + } + if entry.key == key { + return entry.add(count, ticks, closes); + } + } + self.other.add(count, ticks, closes); + } + + /// Add every exit `exits` counts. + pub fn merge(&mut self, exits: &Self) { + for entry in exits.entries.iter().filter(|entry| entry.count != 0) { + self.add(entry.key, entry.count, entry.ticks, entry.closes); + } + let other = exits.other; + self.other.add(other.count, other.ticks, other.closes); + self.devices.merge(&exits.devices); + for (count, more) in self.floating.iter_mut().zip(exits.floating) { + *count += more; + } + self.floating_words.merge(&exits.floating_words); + self.barriers.merge(&exits.barriers); + self.regimes.merge(&exits.regimes); + for (compression, other) in self.compression.iter_mut().zip(&exits.compression) { + compression.merge(other); + } + self.paths.merge(&exits.paths); + } + + /// The keys with exits. + pub fn counted(&self) -> impl Iterator { + self.entries.iter().filter(|entry| entry.count != 0) + } + + pub fn is_empty(&self) -> bool { + self.other.count == 0 + && self.counted().next().is_none() + && self.devices.is_empty() + && self.floating.iter().all(|&count| count == 0) + && self.floating_words.is_empty() + && self.barriers.waits == 0 + && self.regimes == RegimeSyncs::default() + && self.paths == ExitPaths::default() + && self + .compression + .iter() + .all(|compression| compression.count == 0) + } +} + +/// The 4 KiB page of a device register, as [`DeviceExits`] keys it. +pub fn device_page(physical: u64) -> u32 { + (physical >> 12) as u32 +} + +/// One device page's accesses, the ticks handling them, and the host +/// counter ticks of those spent waiting for the board's lock. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeviceExit { + pub page: u32, + pub count: u64, + pub ticks: u64, + pub waited: u64, +} + +impl DeviceExit { + fn add(&mut self, count: u64, ticks: u64, waited: u64) { + self.count += count; + self.ticks += ticks; + self.waited += waited; + } +} + +/// The device pages [`DeviceExits`] holds apart. +pub const DEVICE_PAGES: usize = 64; + +/// One device register's reads or writes the engine completed, with +/// [`DeviceExit`]'s counts: `register` its physical address, with +/// [`DEVICE_REGISTER_WRITE`] set for writes, whose ticks also split as +/// [`DeviceWrites`]' do into the access and the settle after it, and the +/// settle's transfer and deferred copies; `longest` is the longest exit, +/// which tells a few long exits (a preempted host thread) from many. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeviceRegisterExit { + pub register: u64, + pub count: u64, + pub ticks: u64, + pub waited: u64, + pub access: u64, + pub settle: u64, + pub transfer: u64, + pub copies: u64, + pub released: u64, + pub longest: u64, +} + +impl DeviceRegisterExit { + fn add(&mut self, other: &Self) { + self.count += other.count; + self.ticks += other.ticks; + self.waited += other.waited; + self.access += other.access; + self.settle += other.settle; + self.transfer += other.transfer; + self.copies += other.copies; + self.released += other.released; + self.longest = self.longest.max(other.longest); + } +} + +/// The parts a device write's exit is timed in: its access, its settle, +/// its gate call, and of the settle the transfer under the devices' lock, +/// the deferred DMA copies after the lock's release and the host work the +/// release did on the writing core, in the board counter's ticks as a lock +/// wait is ([`DeviceWrites::add`]). +pub const WRITE_PARTS: usize = 6; + +/// The bit of [`DeviceRegisterExit::register`] that says writes: physical +/// addresses never reach it. +pub const DEVICE_REGISTER_WRITE: u64 = 1 << 63; + +/// The registers and directions [`DeviceExits`] holds apart. +pub const DEVICE_REGISTERS: usize = 128; + +/// Device writes the engine completed, and the ticks of their exits split: +/// the whole exit; the access, up to the model's write done (the devices' +/// lock and the write); the settle after it (in the same locked call every +/// master's transfer, then the release: the PEs it woke, the publication, +/// the deferred copies and the host work after); and a gate call it made +/// ([`super::Devices::write_settled`]). The rest of the exit is the +/// engine's own: leaving and entering the guest, decode, routing and +/// watching. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeviceWrites { + pub count: u64, + pub exit: u64, + pub access: u64, + pub settle: u64, + pub call: u64, + pub transfer: u64, + pub copies: u64, + pub released: u64, +} + +impl DeviceWrites { + pub fn add(&mut self, exit: u64, parts: [u64; WRITE_PARTS]) { + self.count += 1; + self.exit += exit; + self.access += parts[0]; + self.settle += parts[1]; + self.call += parts[2]; + self.transfer += parts[3]; + self.copies += parts[4]; + self.released += parts[5]; + } + + fn merge(&mut self, other: &Self) { + self.count += other.count; + self.exit += other.exit; + self.access += other.access; + self.settle += other.settle; + self.call += other.call; + self.transfer += other.transfer; + self.copies += other.copies; + self.released += other.released; + } +} + +/// Device accesses the engine completed, from native faults and device +/// sites, by [`device_page`], under step timing: an open-addressed table, +/// with the pages past its size in `other`; and the accesses forwarded to +/// the home machine, with the ticks their PEs waited for its answers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DeviceExits { + pub entries: [DeviceExit; DEVICE_PAGES], + pub other: DeviceExit, + pub forwarded: u64, + pub forwarded_ticks: u64, + pub writes: DeviceWrites, + /// The same accesses by register and direction, an open-addressed + /// table too, with the rest in `other_registers`. + pub registers: [DeviceRegisterExit; DEVICE_REGISTERS], + pub other_registers: DeviceRegisterExit, +} + +impl Default for DeviceExits { + fn default() -> Self { + Self { + entries: [DeviceExit::default(); DEVICE_PAGES], + other: DeviceExit::default(), + forwarded: 0, + forwarded_ticks: 0, + writes: DeviceWrites::default(), + registers: [DeviceRegisterExit::default(); DEVICE_REGISTERS], + other_registers: DeviceRegisterExit::default(), + } + } +} + +impl DeviceExits { + /// Count `count` accesses of `page` that took `ticks`, `waited` of them + /// in host counter ticks waiting for the board's lock. + pub fn add(&mut self, page: u32, count: u64, ticks: u64, waited: u64) { + let start = (page.wrapping_mul(0x9e37_79b9) >> (u32::BITS - DEVICE_PAGES.ilog2())) as usize; + for probe in 0..DEVICE_PAGES { + let entry = &mut self.entries[(start + probe) % DEVICE_PAGES]; + if entry.count == 0 { + entry.page = page; + } + if entry.page == page { + return entry.add(count, ticks, waited); + } + } + self.other.add(count, ticks, waited); + } + + /// Count the accesses `exit` holds of its register as [`Self::add`] + /// counts its page's. + pub fn add_register(&mut self, exit: DeviceRegisterExit) { + let register = exit.register; + let hash = (register ^ register >> 32).wrapping_mul(0x9e37_79b9_7f4a_7c15); + let start = (hash >> (u64::BITS - DEVICE_REGISTERS.ilog2())) as usize; + for probe in 0..DEVICE_REGISTERS { + let entry = &mut self.registers[(start + probe) % DEVICE_REGISTERS]; + if entry.count == 0 { + entry.register = register; + } + if entry.register == register { + return entry.add(&exit); + } + } + self.other_registers.add(&exit); + } + + /// The registers with accesses. + pub fn counted_registers(&self) -> impl Iterator { + self.registers.iter().filter(|entry| entry.count != 0) + } + + pub fn merge(&mut self, exits: &Self) { + for entry in exits.counted() { + self.add(entry.page, entry.count, entry.ticks, entry.waited); + } + for entry in exits.counted_registers() { + self.add_register(*entry); + } + self.other_registers.add(&exits.other_registers); + let other = exits.other; + self.other.add(other.count, other.ticks, other.waited); + self.forwarded += exits.forwarded; + self.forwarded_ticks += exits.forwarded_ticks; + self.writes.merge(&exits.writes); + } + + /// The pages with accesses. + pub fn counted(&self) -> impl Iterator { + self.entries.iter().filter(|entry| entry.count != 0) + } + + pub fn is_empty(&self) -> bool { + self.other.count == 0 && self.forwarded == 0 && self.counted().next().is_none() + } +} + +/// A native fault's slot in [`StepTiming::exits`], by cause: the guest's +/// translation, a device, a native check, a watched or tag-checked page, +/// or translation the engine does not implement. +pub fn fault_slot(cause: &super::FaultCause) -> usize { + use super::FaultCause; + FAULT_SLOTS + + match cause { + FaultCause::Guest(_) => 0, + FaultCause::Device { .. } => DEVICE_FAULT_SLOT - FAULT_SLOTS, + FaultCause::NonCanonical | FaultCause::InvalidOpcode => CHECK_FAULT_SLOT - FAULT_SLOTS, + FaultCause::Watched | FaultCause::TagChecked => 3, + FaultCause::Translation(_) => 4, + } +} + +/// One completed phase's largest observed profile-clock interval. +/// +/// The CPU fields are a materialized snapshot after the phase, not a precise +/// fault PC or an attribution to one guest instruction. Fetch includes finding, +/// compiling and installing code; every phase can include host descheduling. +/// These observations are diagnostics, never architectural latency bounds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Maximum { + pub ticks: u64, + /// The same profile-clock sample used to close this interval. + pub finished_ticks: u64, + pub pc_after: u64, + pub el_after: u8, + pub daif_after: u8, +} + +impl Maximum { + #[inline] + pub(super) fn observe( + &mut self, + ticks: u64, + finished_ticks: u64, + pc_after: u64, + el_after: u8, + daif_after: u8, + ) { + if ticks > self.ticks { + *self = Self { + ticks, + finished_ticks, + pc_after, + el_after, + daif_after, + }; + } + } +} + +/// The guest states [`Levels::ticks`] splits busy time by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(usize)] +pub enum Level { + /// EL0. + User, + /// EL1 or EL2 outside guarded mode. + Kernel, + /// Apple GXF guarded mode at any level. + Guarded, +} + +impl Level { + pub const COUNT: usize = Self::Guarded as usize + 1; + + pub fn of(el: u8, guarded: bool) -> Self { + match (guarded, el) { + (true, _) => Self::Guarded, + (false, 0) => Self::User, + (false, _) => Self::Kernel, + } + } +} + +/// Where native code was when a sampled run's transfer budget ran out, under +/// step timing (`Machine::execute`): one run in [`HOT_SAMPLE_EVERY`] gets a +/// budget drawn uniformly from 1..=[`HOT_SAMPLE_SPAN`], so a run of `n` +/// transfers is sampled with a chance in proportion to `n` and at a uniformly +/// chosen one of them: each transfer of native code is equally likely to be +/// the sample, which ranks blocks by the native work in them rather than by +/// where they exit. A sample is the entered block's guest PC and [`Level`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HotBlocks { + /// Open-addressed `(pc, level, count)` entries, [`HOT_BLOCKS`] of them + /// once the first sample is added; samples past them are in `other`. + pub entries: alloc::vec::Vec, + /// Samples by [`Level`], and those that found the table full. + pub samples: [u64; Level::COUNT], + pub other: u64, + /// The samples that were a block's RET, BLR or BR form's transfer, at + /// most [`DYNAMIC_SAMPLES`]; those past them are in `dynamic_other`. + pub dynamic: alloc::vec::Vec, + pub dynamic_other: u64, + /// The same samples by guest address space ([`AsidSamples`]). + pub asids: AsidSamples, +} + +/// [`HotBlocks`]' samples by the ASID the PE's translations were tagged with +/// at each one (`Machine::current_space_asid`), at any level: a user thread's system calls and faults count with +/// its process, as the guest's own CPU time does, and kernel threads with +/// the kernel's address space. Each address space's samples by [`Level`], +/// and its EL0 blocks apart, so the PCs name the process (its frameworks) +/// for an ASID the host cannot map to a process name. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AsidSamples { + /// Open-addressed address spaces, [`ASID_SLOTS`] once the first sample + /// is added; samples past them are in `other`. + pub spaces: alloc::vec::Vec, + /// Open-addressed EL0 blocks keyed by ASID and PC ([`AsidBlock`]), + /// [`ASID_BLOCKS`] of them; samples past them count only by space. + pub blocks: alloc::vec::Vec, + pub other: u64, +} + +/// One address space's samples ([`AsidSamples`]). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AsidSpace { + pub asid: u16, + pub samples: [u64; Level::COUNT], +} + +impl AsidSpace { + pub fn total(&self) -> u64 { + self.samples.iter().sum() + } +} + +/// One EL0 block's samples in one address space ([`AsidSamples`]). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AsidBlock { + pub asid: u16, + pub pc: u64, + pub count: u64, +} + +/// The address spaces [`AsidSamples`] holds apart. +pub const ASID_SLOTS: usize = 512; +/// The EL0 blocks by address space [`AsidSamples`] holds apart. +pub const ASID_BLOCKS: usize = 4096; + +/// A slot of an open-addressed table of `slots` (a power of two) for `key`: +/// where its probe starts. +fn probe_start(key: u64, slots: usize) -> usize { + (key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (u64::BITS - slots.ilog2())) as usize +} + +impl AsidSamples { + /// Count `count` samples at `level` in address space `asid`, and an EL0 + /// sample's block at `pc` apart. + pub fn add(&mut self, asid: u16, pc: u64, level: Level, count: u64) { + self.allocate(); + let start = probe_start(u64::from(asid), ASID_SLOTS); + let space = (0..ASID_SLOTS / 8) + .map(|probe| (start + probe) % ASID_SLOTS) + .find(|&slot| self.spaces[slot].total() == 0 || self.spaces[slot].asid == asid); + let Some(slot) = space else { + self.other += count; + return; + }; + self.spaces[slot].asid = asid; + self.spaces[slot].samples[level as usize] += count; + if level != Level::User { + return; + } + let start = probe_start(pc ^ u64::from(asid) << 48, ASID_BLOCKS); + for probe in 0..ASID_BLOCKS / 8 { + let block = &mut self.blocks[(start + probe) % ASID_BLOCKS]; + if block.count == 0 { + *block = AsidBlock { asid, pc, count: 0 }; + } + if block.asid == asid && block.pc == pc { + block.count += count; + return; + } + } + } + + /// Add every sample `other` holds. + pub fn merge(&mut self, other: &Self) { + // EL0 samples by block first, each address space's held ones + // counted, then the rest of every space's samples. + let mut held = alloc::collections::BTreeMap::::new(); + for block in other.blocks.iter().filter(|block| block.count != 0) { + self.add(block.asid, block.pc, Level::User, block.count); + *held.entry(block.asid).or_default() += block.count; + } + for space in other.spaces.iter().filter(|space| space.total() != 0) { + for level in [Level::Kernel, Level::Guarded] { + let count = space.samples[level as usize]; + if count != 0 { + self.add(space.asid, 0, level, count); + } + } + let user = space.samples[Level::User as usize]; + let rest = user.saturating_sub(held.get(&space.asid).copied().unwrap_or(0)); + if rest != 0 { + self.add_space_only(space.asid, rest); + } + } + self.other += other.other; + } + + /// The tables, once the first sample comes. + fn allocate(&mut self) { + if self.spaces.is_empty() { + self.spaces = alloc::vec![AsidSpace::default(); ASID_SLOTS]; + self.blocks = alloc::vec![AsidBlock::default(); ASID_BLOCKS]; + } + } + + /// EL0 samples of `asid` whose block no table held. + fn add_space_only(&mut self, asid: u16, count: u64) { + self.allocate(); + let start = probe_start(u64::from(asid), ASID_SLOTS); + match (0..ASID_SLOTS / 8) + .map(|probe| (start + probe) % ASID_SLOTS) + .find(|&slot| self.spaces[slot].total() == 0 || self.spaces[slot].asid == asid) + { + Some(slot) => { + self.spaces[slot].asid = asid; + self.spaces[slot].samples[Level::User as usize] += count; + } + None => self.other += count, + } + } + + /// The `shown` address spaces with the most samples, most first. + pub fn top(&self, shown: usize) -> alloc::vec::Vec { + let mut spaces: alloc::vec::Vec = self + .spaces + .iter() + .filter(|space| space.total() != 0) + .copied() + .collect(); + spaces.sort_unstable_by(|a, b| b.total().cmp(&a.total()).then(a.asid.cmp(&b.asid))); + spaces.truncate(shown); + spaces + } + + /// The `shown` EL0 blocks of `asid` with the most samples, most first. + pub fn top_blocks(&self, asid: u16, shown: usize) -> alloc::vec::Vec { + let mut blocks: alloc::vec::Vec = self + .blocks + .iter() + .filter(|block| block.count != 0 && block.asid == asid) + .copied() + .collect(); + blocks.sort_unstable_by(|a, b| b.count.cmp(&a.count).then(a.pc.cmp(&b.pc))); + blocks.truncate(shown); + blocks + } +} + +/// A sampled transfer of a block's RET, BLR or BR form ([`HotBlocks`]): +/// the form and the block's PC, which stands for its site, and the target. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DynamicSample { + pub form: DynamicForm, + pub site: u64, + pub target: u64, +} + +/// A branch to a register's value: RET, BLR, BR, then their PAC forms +/// (RETA*, BLRA*, BRA*). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[repr(u8)] +pub enum DynamicForm { + Ret, + Blr, + Br, + Reta, + Blra, + Bra, +} + +impl DynamicForm { + pub const ALL: [Self; 6] = [ + Self::Ret, + Self::Blr, + Self::Br, + Self::Reta, + Self::Blra, + Self::Bra, + ]; +} + +/// The [`DynamicSample`]s one [`HotBlocks`] holds. +pub const DYNAMIC_SAMPLES: usize = 1 << 16; + +/// The sites of sampled RET, BLR and BR transfers since the first sample +/// ([`HotBlocks::dynamic`]), each with the first target seen there and +/// whether another followed: whether a one-target inline cache would serve +/// the hot ones. At most [`DYNAMIC_SITES`] sites; samples of further ones +/// are in `untracked`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DynamicSites { + sites: alloc::collections::BTreeMap<(DynamicForm, u64), DynamicSite>, + pub untracked: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct DynamicSite { + target: u64, + samples: u64, + targets_differ: bool, +} + +/// The sites [`DynamicSites`] tells apart. +pub const DYNAMIC_SITES: usize = 1 << 15; + +/// One form's sites with at least two samples ([`DynamicSites::seen`]): +/// how many, how many had one target in every sample, and the samples of +/// each group. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DynamicSeen { + pub sites: u64, + pub monomorphic: u64, + pub samples: u64, + pub monomorphic_samples: u64, +} + +impl DynamicSites { + pub fn add(&mut self, samples: &[DynamicSample]) { + for sample in samples { + let key = (sample.form, sample.site); + if let Some(site) = self.sites.get_mut(&key) { + site.samples += 1; + site.targets_differ |= site.target != sample.target; + } else if self.sites.len() < DYNAMIC_SITES { + self.sites.insert( + key, + DynamicSite { + target: sample.target, + samples: 1, + targets_differ: false, + }, + ); + } else { + self.untracked += 1; + } + } + } + + /// The sites of `form` sampled at least twice. + pub fn seen(&self, form: DynamicForm) -> DynamicSeen { + let mut seen = DynamicSeen::default(); + let sites = self.sites.range((form, 0)..=(form, u64::MAX)); + for site in sites.map(|(_, site)| site).filter(|site| site.samples >= 2) { + seen.sites += 1; + seen.samples += site.samples; + if !site.targets_differ { + seen.monomorphic += 1; + seen.monomorphic_samples += site.samples; + } + } + seen + } +} + +/// One block's samples. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct HotBlock { + /// An EL0 block's PC; a kernel or guarded block's PC less the + /// sampling PE's vector base (wrapping), which moves with the slide. + pub pc: u64, + pub level: u8, + pub count: u64, +} + +/// The blocks [`HotBlocks`] holds apart. +pub const HOT_BLOCKS: usize = 8192; +/// One run in this many is sampled. +pub const HOT_SAMPLE_EVERY: u32 = 16; +/// A sampled run's budget is at most this many transfers. +pub const HOT_SAMPLE_SPAN: u64 = 4096; + +impl HotBlocks { + /// Count `count` samples of the block at `pc` at `level`. + pub fn add(&mut self, pc: u64, level: Level, count: u64) { + if self.entries.is_empty() { + self.entries = alloc::vec![HotBlock::default(); HOT_BLOCKS]; + } + self.samples[level as usize] += count; + let key = pc ^ (level as u64) << 62; + let start = + (key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (u64::BITS - HOT_BLOCKS.ilog2())) as usize; + for probe in 0..HOT_BLOCKS / 8 { + let entry = &mut self.entries[(start + probe) % HOT_BLOCKS]; + if entry.count == 0 { + *entry = HotBlock { + pc, + level: level as u8, + count: 0, + }; + } + if entry.pc == pc && entry.level == level as u8 { + entry.count += count; + return; + } + } + self.other += count; + } + + /// Add every sample `hot` holds. + pub fn merge(&mut self, hot: &Self) { + for entry in hot.counted() { + let level = + [Level::User, Level::Kernel, Level::Guarded][usize::from(entry.level).min(2)]; + self.add(entry.pc, level, entry.count); + } + self.other += hot.other; + // `add` counted the table's samples by level; the others only here. + for (level, samples) in self.samples.iter_mut().enumerate() { + let counted: u64 = hot + .counted() + .filter(|e| usize::from(e.level) == level) + .map(|e| e.count) + .sum(); + *samples += hot.samples[level] - counted; + } + self.add_dynamic(&hot.dynamic); + self.dynamic_other += hot.dynamic_other; + self.asids.merge(&hot.asids); + } + + /// Keep `samples` of dynamic transfers, as many as fit. + pub fn add_dynamic(&mut self, samples: &[DynamicSample]) { + let room = DYNAMIC_SAMPLES.saturating_sub(self.dynamic.len()); + let kept = samples.len().min(room); + self.dynamic.extend_from_slice(&samples[..kept]); + self.dynamic_other += (samples.len() - kept) as u64; + } + + /// The blocks with samples. + pub fn counted(&self) -> impl Iterator { + self.entries.iter().filter(|entry| entry.count != 0) + } + + /// The `shown` blocks of `level` with the most samples, most first. + pub fn top(&self, level: Level, shown: usize) -> alloc::vec::Vec { + let mut blocks: alloc::vec::Vec = self + .counted() + .filter(|e| e.level == level as u8) + .copied() + .collect(); + blocks.sort_unstable_by(|a, b| b.count.cmp(&a.count).then(a.pc.cmp(&b.pc))); + blocks.truncate(shown); + blocks + } + + pub fn is_empty(&self) -> bool { + self.samples.iter().all(|&n| n == 0) + } +} + +/// Where a PE's busy time goes in guest terms, under step timing: every +/// phase but [`Phase::Schedule`] charged by the guest's state at the charge +/// (an exit after its handling: an exception entry counts as the level it +/// entered), and the PE's waits for interrupt and event. What the guest's +/// own CPU accounting cannot see apart: its idle path between WFIs and its +/// interrupt handlers run on busy host time too. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Levels { + /// Ticks by [`Level`]. + pub ticks: [u64; Level::COUNT], + /// IRQs and FIQs taken, and the ticks charged from taking one until the + /// next exception return: handlers, and the switch to another thread + /// when one returns through it. + pub interrupts: u64, + pub interrupt_ticks: u64, + /// WFIs, and those that completed at once with an interrupt pending. + pub wfi: u64, + pub wfi_at_once: u64, + /// WFEs that reached the engine, and those that completed at once with + /// the event register set (native code completes some itself). + pub wfe: u64, + pub wfe_at_once: u64, + /// WFEs native code completed after spinning for the event register, + /// spins that ended without it, WFEs that exited without a spin for an + /// exclusive monitor, and the system counts spins spent + /// (`x86_64::register_read::event_wait_thunk`). + pub wfe_spun: u64, + pub wfe_spin_missed: u64, + pub wfe_held: u64, + pub wfe_spin_counts: u64, + /// WFEs native code completed on an event stream edge since the last + /// sample (`x86_64::register_read::EventStream`). + pub wfe_streamed: u64, + /// MSR CNTV_TVAL_EL0s that reached the engine, by why native code left + /// them to it ([`TimerExit`]). + pub timer_value_exits: [u64; TimerExit::COUNT], + /// At each WFI, the kernel ticks charged since the PE last ran EL0 code + /// or reached a WFI: wake-ups that found nothing for user code, idle + /// paths and kernel threads. + pub kernel_before_wfi: u64, + /// Between an interrupt's entry and the next exception return. + pub in_interrupt: bool, + /// Kernel ticks charged since the PE last ran EL0 code or reached a WFI. + pub kernel_run: u64, +} + +impl Levels { + /// Charge `spent` busy ticks at `level`. + #[inline] + pub(super) fn charge(&mut self, level: Level, spent: u64) { + self.ticks[level as usize] += spent; + // No handler runs at EL0: back there, the one taken has returned, + // whether native code or the engine made its exception return. + if level == Level::User { + self.in_interrupt = false; + } + if self.in_interrupt { + self.interrupt_ticks += spent; + } + if level == Level::User { + self.kernel_run = 0; + } else { + self.kernel_run += spent; + } + } + + pub(super) fn interrupt_taken(&mut self) { + self.interrupts += 1; + self.in_interrupt = true; + } + + /// Native code made an exception return: the handler taken has ended, + /// and the run's ticks charged after are not its. What the run spent in + /// the handler before its return is charged outside it, so + /// `interrupt_ticks` is a lower bound. + pub(super) fn exception_returned(&mut self) { + self.in_interrupt = false; + } + + /// A WFI, which completed at once if `at_once`. + pub(super) fn wait_for_interrupt(&mut self, at_once: bool) { + self.wfi += 1; + self.wfi_at_once += u64::from(at_once); + self.kernel_before_wfi += core::mem::take(&mut self.kernel_run); + } + + /// A WFE, which completed at once if `at_once`. + pub(super) fn wait_for_event(&mut self, at_once: bool) { + self.wfe += 1; + self.wfe_at_once += u64::from(at_once); + } + + /// What native WFEs counted of their spins. + pub(super) fn event_spins(&mut self, spin: stela_compiler::x86_64::register_read::EventSpin) { + self.wfe_spun += spin.completed + spin.held_completed; + self.wfe_spin_missed += spin.missed; + self.wfe_held += spin.held; + self.wfe_spin_counts += spin.counts; + self.wfe_streamed += spin.streamed; + } + + /// The counts since `earlier`; the state is this one's. + pub fn since(&self, earlier: &Self) -> Self { + let mut ticks = self.ticks; + for (now, then) in ticks.iter_mut().zip(earlier.ticks) { + *now = now.wrapping_sub(then); + } + Self { + ticks, + interrupts: self.interrupts.wrapping_sub(earlier.interrupts), + interrupt_ticks: self.interrupt_ticks.wrapping_sub(earlier.interrupt_ticks), + wfi: self.wfi.wrapping_sub(earlier.wfi), + wfi_at_once: self.wfi_at_once.wrapping_sub(earlier.wfi_at_once), + wfe: self.wfe.wrapping_sub(earlier.wfe), + wfe_at_once: self.wfe_at_once.wrapping_sub(earlier.wfe_at_once), + wfe_spun: self.wfe_spun.wrapping_sub(earlier.wfe_spun), + wfe_spin_missed: self.wfe_spin_missed.wrapping_sub(earlier.wfe_spin_missed), + wfe_held: self.wfe_held.wrapping_sub(earlier.wfe_held), + wfe_spin_counts: self.wfe_spin_counts.wrapping_sub(earlier.wfe_spin_counts), + wfe_streamed: self.wfe_streamed.wrapping_sub(earlier.wfe_streamed), + timer_value_exits: core::array::from_fn(|reason| { + self.timer_value_exits[reason].wrapping_sub(earlier.timer_value_exits[reason]) + }), + kernel_before_wfi: self + .kernel_before_wfi + .wrapping_sub(earlier.kernel_before_wfi), + ..*self + } + } +} + +/// Why a timer write reached the engine, where the native timer write +/// (`x86_64::register_read::timer_thunk`) would have completed it otherwise, +/// in the order that thunk tests. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TimerExit { + /// Not at EL2 with HCR_EL2.E2H, at a guarded level, or a chip with two + /// timer banks: no native write serves the state. + State, + /// The timer cells are closed. + Closed, + /// The engine had not said when it looks at the lines again + /// (`Mirrors::lines_until`), as it kept no device lines for the PE... + LinesDevices, + /// ...as a performance monitor overflow was due or near... + LinesMonitor, + /// ...or as the PE's own fast IPI word was set. + LinesIpi, + /// The channel's output was high, and what lowering it leaves waiting + /// was not known. + High, + /// The write arms a compare the count has reached: the line rises. + Now, + /// Native code could have completed it (no thunk at the site). + Native, +} + +impl TimerExit { + pub const COUNT: usize = 8; +} + +/// Whether `word` is ERET, ERETAA or ERETAB. +pub fn exception_return(word: u32) -> bool { + matches!(word, 0xd69f_03e0 | 0xd69f_0bff | 0xd69f_0fff) +} + +/// Host ticks spent so far, by phase and by exit. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct StepTiming { + pub phases: [u64; Phase::COUNT], + /// Lifetime maxima since timing was enabled or reset. A zero interval + /// has no witness. These are held, not subtracted, by [`Self::since`]. + pub lifetime_maxima: [Maximum; Phase::COUNT], + /// Exits handled and the ticks handling them, by `ExitKind` value, then + /// native faults by cause ([`fault_slot`]). + pub exits: [(u64, u64); EXIT_SLOTS], + /// What the native check fault being handled found, which its exit is + /// charged to ([`Check`]). + pub check: Option, + /// Busy time in guest terms ([`Levels`]). + pub levels: Levels, +} + +impl StepTiming { + /// Cumulative phase/exit totals spent since `earlier`, keeping the + /// current lifetime maximum snapshots. An interval maximum cannot be + /// derived by subtracting maxima. + pub fn since(&self, earlier: &Self) -> Self { + let mut delta = *self; + for (now, then) in delta.phases.iter_mut().zip(earlier.phases) { + *now = now.wrapping_sub(then); + } + for (now, then) in delta.exits.iter_mut().zip(earlier.exits) { + *now = (now.0.wrapping_sub(then.0), now.1.wrapping_sub(then.1)); + } + delta.levels = self.levels.since(&earlier.levels); + delta + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FAULT_SLOT: usize = FAULT_SLOTS + 1; + + /// Each System exit key falls in the class of what it does. + #[test] + fn system_keys_fall_in_the_class_of_what_they_do() { + let cases = [ + (DEVICE_SITE_KEY, SystemClass::Device), + (0x0020_0c20, SystemClass::Compression), + (0xd503_3b80, SystemClass::Barrier), + (0xd508_83a0, SystemClass::Maintenance), + (0xd508_7500, SystemClass::Maintenance), + (0xd503_2040, SystemClass::Wait), + (0xd51b_e300, SystemClass::Timer), + (0xd53a_f000, SystemClass::ImplementationDefined), + (0xd51d_f000, SystemClass::ImplementationDefined), + (0xd518_2000, SystemClass::TranslationControl), + (0xd518_1000, SystemClass::TranslationControl), + (0xd69f_03e0, SystemClass::Transition), + (0xd400_1001, SystemClass::Transition), + (0xd503_47e0, SystemClass::Other), + ]; + for (key, class) in cases { + let name = system_key_name(key); + assert_eq!(SystemClass::of(key), class, "{key:#010x} {name}"); + assert_eq!(wait_key(key), class == SystemClass::Wait, "{key:#010x}"); + } + } + + /// `wait_key` finds the Wait class exactly, over the whole hint and + /// barrier space (CRn 1 to 3 of op0 0) and the timed waits. + #[test] + fn wait_keys_are_the_wait_class() { + let mut waits = 0; + for key in (0xd503_1000u32..0xd503_4000).step_by(0x20) { + let wait = SystemClass::of(key) == SystemClass::Wait; + assert_eq!(wait_key(key), wait, "{key:#010x} {}", system_key_name(key)); + waits += usize::from(wait); + } + // WFE, WFI, WFET and WFIT. + assert_eq!(waits, 4); + } + + #[test] + fn hot_blocks_rank_by_samples_per_level_and_merge() { + let mut hot = HotBlocks::default(); + assert!(hot.is_empty()); + hot.add(0x1000, Level::Kernel, 3); + hot.add(0x2000, Level::Kernel, 5); + // The same PC at another level is another block. + hot.add(0x1000, Level::User, 7); + let top = hot.top(Level::Kernel, 8); + assert_eq!( + top.iter() + .map(|b| (b.pc, b.count)) + .collect::>(), + [(0x2000, 5), (0x1000, 3)] + ); + assert_eq!(hot.top(Level::User, 8)[0].count, 7); + assert_eq!(hot.samples, [7, 8, 0]); + let mut merged = HotBlocks::default(); + merged.add(0x2000, Level::Kernel, 1); + merged.merge(&hot); + assert_eq!( + merged.top(Level::Kernel, 1)[0], + HotBlock { + pc: 0x2000, + level: Level::Kernel as u8, + count: 6 + } + ); + assert_eq!(merged.samples, [7, 9, 0]); + } + + /// One run in HOT_SAMPLE_EVERY gets a drawn budget; a sampled run whose + /// budget ran out names the block it ended in, and nothing is sampled + /// without step timing. + #[test] + fn a_sampled_run_whose_budget_ran_out_names_its_last_block() { + use super::super::{ + NativeExit, + chain::{Account, ChainControl}, + }; + use stela_compiler::block::ExitKind; + const ADD: u32 = 0x9100_0400; // add x0, x0, #1 + let mut machine = super::super::tests::machine(&[ADD, 0x1400_0002, 0, ADD, 0x17ff_fffc]); + let base = machine.cpu.pc; + let direct = |next_pc| NativeExit::Exit { + next_pc, + kind: ExitKind::Direct as u64, + }; + let run = |machine: &mut crate::machine::Machine< + super::super::tests::FakeHost, + crate::machine::NoDevices, + >, + runs: u32| { + for _ in 0..runs { + let next = if machine.cpu.pc == base { + base + 12 + } else { + base + }; + let current = machine.chain.snapshot(); + machine.host.chained = Some(( + machine.chain.address() as *mut ChainControl, + ChainControl { + block: 1, + ..current + }, + Account::spent(0), + )); + machine.host.exits = alloc::vec![direct(next)]; + machine.step().unwrap(); + } + }; + // Both blocks compiled, then runs that all spend their budget. + machine.slice_end = u64::MAX; + machine.block_limit = u64::MAX; + machine.host.exits = alloc::vec![direct(base + 12), direct(base)]; + machine.step().unwrap(); + machine.step().unwrap(); + run(&mut machine, 2 * HOT_SAMPLE_EVERY); + assert!(!machine.has_hot_samples(), "no samples without step timing"); + // Kernel PCs are kept as offsets from the vector base of their EL. + const VBAR: u64 = 0x800; + for register in [ + crate::machine::system::Register::VBAR_EL1, + crate::machine::system::Register::VBAR_EL2, + ] { + machine.cpu.registers.set(register, 0, VBAR); + } + let expected = + if Level::of(machine.cpu.pstate.el, machine.cpu.pstate.guarded) == Level::User { + base + 12 + } else { + (base + 12).wrapping_sub(VBAR) + }; + // Each regime's TTBR0 holds an ASID of its own (8 bits: TCR.AS is + // clear); the sample names the one its regime tags translations + // with, never a constant. + use crate::machine::system::Register; + machine + .cpu + .registers + .set(Register::TTBR0_EL1, 0, 0x11 << 48); + machine + .cpu + .registers + .set(Register::TTBR0_EL2, 0, 0x22 << 48); + let asid = machine.current_space_asid(); + let in_el20 = + machine.cpu.pstate.el == 2 || machine.cpu.pstate.el == 0 && machine.cpu.in_host(); + assert_eq!(asid, if in_el20 { 0x22 } else { 0x11 }); + machine.set_step_timing(true); + run(&mut machine, 2 * HOT_SAMPLE_EVERY); + let mut hot = HotBlocks::default(); + machine.take_hot_samples(&mut hot); + let total: u64 = hot.samples.iter().sum(); + assert_eq!(total, 2); + let pcs: alloc::vec::Vec = hot.counted().map(|block| block.pc).collect(); + assert_eq!(pcs, [expected]); + let spaces: alloc::vec::Vec<(u16, u64)> = hot + .asids + .top(8) + .iter() + .map(|space| (space.asid, space.total())) + .collect(); + assert_eq!(spaces, [(asid, 2)]); + assert!(!machine.has_hot_samples()); + // Draws stay within the span and below the run's own budget. + for _ in 0..1000 { + let (budget, sampled) = machine.sampled_budget(HOT_SAMPLE_SPAN + 1); + assert!((1..=HOT_SAMPLE_SPAN + 1).contains(&budget)); + assert_eq!(sampled, budget <= HOT_SAMPLE_SPAN); + } + } + + /// A sample's address space is the ASID its regime tags translations + /// with: under VHE with HCR_EL2.TGE (XNU on an M2, kernel at EL2) EL0 + /// and EL2 take TTBR0_EL2's, where the kernel's TTBR0_EL1 writes land, + /// and TTBR0_EL1 stays 0; in EL1&0 TTBR0_EL1's; TCR.A1 picks TTBR1. + #[test] + fn a_samples_address_space_is_its_regimes_asid() { + use crate::machine::system::Register; + const HCR_TGE: u64 = 1 << 27; + const HCR_E2H: u64 = 1 << 34; + const TCR_A1: u64 = 1 << 22; + const TCR_AS: u64 = 1 << 36; + let mut machine = super::super::tests::machine(&[0x9100_0400]); + machine.cpu.registers.set(Register::TTBR0_EL1, 0, 0); + machine + .cpu + .registers + .set(Register::TTBR0_EL2, 0, 0x1234 << 48); + machine + .cpu + .registers + .set(Register::TTBR1_EL2, 0, 0x5678 << 48); + machine.cpu.registers.set(Register::TCR_EL2, 0, TCR_AS); + machine + .cpu + .registers + .set(Register::HCR_EL2, 0, HCR_TGE | HCR_E2H); + for el in [0, 2] { + machine.cpu.pstate.el = el; + assert_eq!(machine.current_space_asid(), 0x1234, "EL{el} under TGE"); + } + machine + .cpu + .registers + .set(Register::TCR_EL2, 0, TCR_AS | TCR_A1); + assert_eq!(machine.current_space_asid(), 0x5678, "TCR.A1"); + // EL1&0: TTBR0_EL1's, 8 bits without TCR_EL1.AS. + machine.cpu.registers.set(Register::HCR_EL2, 0, 0); + machine + .cpu + .registers + .set(Register::TTBR0_EL1, 0, 0x1abc << 48); + machine.cpu.pstate.el = 1; + assert_eq!(machine.current_space_asid(), 0xbc); + machine.cpu.pstate.el = 0; + assert_eq!(machine.current_space_asid(), 0xbc); + } + + /// Sites sampled once are not judged; a site whose samples all named + /// one target is monomorphic; the forms are counted apart; a merge + /// keeps the samples of both, as many as fit. + #[test] + fn dynamic_sites_tell_one_target_sites_apart() { + let sample = |form, site, target| DynamicSample { form, site, target }; + let mut hot = HotBlocks::default(); + hot.add_dynamic(&[ + sample(DynamicForm::Ret, 0x100, 0x500), + sample(DynamicForm::Ret, 0x100, 0x500), + sample(DynamicForm::Ret, 0x100, 0x500), + sample(DynamicForm::Ret, 0x200, 0x600), + sample(DynamicForm::Ret, 0x200, 0x604), + sample(DynamicForm::Ret, 0x300, 0x700), + sample(DynamicForm::Blr, 0x100, 0x800), + sample(DynamicForm::Blr, 0x100, 0x800), + ]); + let mut merged = HotBlocks::default(); + merged.merge(&hot); + assert_eq!(merged.dynamic, hot.dynamic); + let mut sites = DynamicSites::default(); + sites.add(&merged.dynamic); + let seen = |sites: &DynamicSites, form| { + let seen = sites.seen(form); + [ + seen.sites, + seen.monomorphic, + seen.samples, + seen.monomorphic_samples, + ] + }; + assert_eq!(seen(&sites, DynamicForm::Ret), [2, 1, 5, 3]); + assert_eq!(seen(&sites, DynamicForm::Blr), [1, 1, 2, 2]); + assert_eq!(seen(&sites, DynamicForm::Br), [0; 4]); + let mut full = HotBlocks { + dynamic: alloc::vec![sample(DynamicForm::Br, 0, 0); DYNAMIC_SAMPLES - 1], + ..HotBlocks::default() + }; + full.add_dynamic(&hot.dynamic[..2]); + assert_eq!( + (full.dynamic.len(), full.dynamic_other), + (DYNAMIC_SAMPLES, 1) + ); + } + + /// Samples count by address space at every level, EL0 blocks apart per + /// address space, and a merge keeps both, those no block held included. + #[test] + fn asid_samples_rank_address_spaces_and_their_user_blocks_and_merge() { + let mut asids = AsidSamples::default(); + asids.add(7, 0x1000, Level::User, 5); + asids.add(7, 0x2000, Level::User, 2); + asids.add(7, 0x10, Level::Kernel, 4); + asids.add(0, 0x20, Level::Kernel, 9); + // The same PC in another address space is another block. + asids.add(9, 0x1000, Level::User, 1); + let top = asids.top(8); + assert_eq!( + top.iter() + .map(|s| (s.asid, s.samples)) + .collect::>(), + [(7, [7, 4, 0]), (0, [0, 9, 0]), (9, [1, 0, 0])] + ); + assert_eq!( + asids + .top_blocks(7, 8) + .iter() + .map(|b| (b.pc, b.count)) + .collect::>(), + [(0x1000, 5), (0x2000, 2)] + ); + // Kernel samples name no block. + assert!(asids.top_blocks(0, 8).is_empty()); + let mut merged = AsidSamples::default(); + merged.add(7, 0x1000, Level::User, 1); + merged.merge(&asids); + assert_eq!(merged.top(1)[0].samples, [8, 4, 0]); + assert_eq!(merged.top_blocks(7, 1)[0].count, 6); + // HotBlocks carries them through its own merge. + let hot = HotBlocks { + asids: asids.clone(), + ..HotBlocks::default() + }; + let mut total = HotBlocks::default(); + total.merge(&hot); + assert_eq!(total.asids.top(8), asids.top(8)); + // EL0 samples whose blocks did not fit still count by space. + let mut full = AsidSamples::default(); + for pc in 0..(ASID_BLOCKS as u64 + 50) { + full.add(3, pc * 4, Level::User, 1); + } + let mut again = AsidSamples::default(); + again.merge(&full); + assert_eq!( + again.top(1)[0].samples[Level::User as usize], + ASID_BLOCKS as u64 + 50 + ); + } + + #[test] + fn hot_blocks_count_what_the_table_cannot_hold_as_other() { + let mut hot = HotBlocks::default(); + for pc in 0..(HOT_BLOCKS as u64 + 100) { + hot.add(pc * 4, Level::Kernel, 1); + } + let held: u64 = hot.counted().map(|e| e.count).sum(); + assert_eq!(held + hot.other, HOT_BLOCKS as u64 + 100); + assert_eq!(hot.samples[Level::Kernel as usize], HOT_BLOCKS as u64 + 100); + let mut merged = HotBlocks::default(); + merged.merge(&hot); + assert_eq!(merged.samples, hot.samples); + } + + #[test] + fn system_keys_drop_registers_and_name_the_instruction() { + // MRS X1 and X30, TPIDR_EL1: one key, the accessor's name. + assert_eq!(system_key(0xd538_d081), system_key(0xd538_d09e)); + assert_eq!(system_key(0xd538_d081), 0xd538_d080); + assert_eq!(system_key_name(0xd538_d080), "MRS_TPIDR_EL1"); + assert_eq!(system_key_name(0xd518_c000), "MSR_VBAR_EL1"); + // TLBI VAE1IS, X0. + assert_eq!(system_key_name(system_key(0xd508_8320)), "TLBI_VAE1IS"); + // An Apple register without an accessor: its encoding. + assert_eq!(system_key_name(0xd53c_f200), "MRS_S3_4_C15_C2_0"); + assert_eq!( + system_key_name(0xd69f_03e0), + "Exception.ExceptionReturn:0xd69f03e0" + ); + assert_eq!(system_key_name(DEVICE_SITE_KEY), "device-site"); + // LDXR W1, [X2] and LDXR W3, [X4]: one key. + assert_eq!(system_key(0x885f_7c41), system_key(0x885f_7c83)); + } + + #[test] + fn system_exits_count_by_key_and_keep_the_rest_in_other() { + let mut exits = SystemExits::default(); + assert!(exits.is_empty()); + for key in 0..SYSTEM_KEYS as u32 + 2 { + exits.add(key, 1, 10, u64::from(key == 0)); + } + exits.add(0, 1, 5, 0); + let first = exits.counted().find(|exit| exit.key == 0).unwrap(); + assert_eq!((first.count, first.ticks, first.closes), (2, 15, 1)); + assert_eq!(exits.counted().count(), SYSTEM_KEYS); + assert_eq!((exits.other.count, exits.other.ticks), (2, 20)); + let mut merged = SystemExits::default(); + merged.merge(&exits); + merged.merge(&exits); + let first = merged.counted().find(|exit| exit.key == 0).unwrap(); + assert_eq!((first.count, first.closes), (4, 2)); + assert_eq!(merged.other.count, 4); + } + + /// Registers count apart by address and direction, the ones past the + /// table in `other_registers`, and merge. + #[test] + fn device_exits_count_by_register_and_direction() { + let mut exits = DeviceExits::default(); + const REGISTER: u64 = 0x2_3b0c_8000; + let exit = |register, ticks, waited, access, settle| DeviceRegisterExit { + register, + count: 1, + ticks, + waited, + access, + settle, + ..DeviceRegisterExit::default() + }; + exits.add_register(exit(REGISTER, 10, 2, 0, 0)); + exits.add_register(exit(REGISTER | DEVICE_REGISTER_WRITE, 20, 0, 6, 9)); + exits.add_register(exit(REGISTER, 5, 1, 0, 0)); + for index in 0..DEVICE_REGISTERS as u64 { + exits.add_register(exit(0x1000 + index * 4, 1, 0, 0, 0)); + } + let count = |exits: &DeviceExits, register| { + exits + .counted_registers() + .find(|exit| exit.register == register) + .map(|exit| { + ( + exit.count, + exit.ticks, + exit.waited, + exit.access, + exit.settle, + ) + }) + }; + assert_eq!(count(&exits, REGISTER), Some((2, 15, 3, 0, 0))); + assert_eq!( + count(&exits, REGISTER | DEVICE_REGISTER_WRITE), + Some((1, 20, 0, 6, 9)) + ); + assert_eq!(exits.other_registers.count, 2); + let mut merged = DeviceExits::default(); + merged.merge(&exits); + merged.merge(&exits); + assert_eq!(count(&merged, REGISTER), Some((4, 30, 6, 0, 0))); + let total: u64 = merged.counted_registers().map(|exit| exit.count).sum(); + assert_eq!( + total + merged.other_registers.count, + 2 * (3 + DEVICE_REGISTERS as u64) + ); + } + + #[test] + fn regime_syncs_merge() { + let regimes = RegimeSyncs { + syncs: 3, + sync_ticks: 30, + isolations: 1, + isolation_ticks: 7, + unchanged: 2, + sources: [1, 0, 0, 0, 2, 0, 0], + }; + let exits = SystemExits { + regimes, + ..SystemExits::default() + }; + assert!(!exits.is_empty()); + let mut merged = SystemExits::default(); + merged.merge(&exits); + merged.merge(&exits); + assert_eq!( + merged.regimes, + RegimeSyncs { + syncs: 6, + sync_ticks: 60, + isolations: 2, + isolation_ticks: 14, + unchanged: 4, + sources: [2, 0, 0, 0, 4, 0, 0], + } + ); + } + + #[test] + fn barrier_waits_count_quick_ones_apart_and_merge_by_blocker() { + let system = stela_compiler::block::ExitKind::System as usize; + let mut waits = BarrierWaits::default(); + waits.add(None, 3); + waits.add(Some(BLOCKER_NATIVE), 10); + let dsb = exit_blocker(system, Some(0xd503_3b9f)); + assert_eq!(dsb, exit_blocker(system, Some(0xd503_3b80))); + waits.add(Some(dsb), 20); + for key in 0..BARRIER_BLOCKERS as u64 { + waits.add(Some(BLOCKER_EXIT | key << 32), 1); + } + assert_eq!((waits.waits, waits.quick, waits.ticks), (35, 1, 65)); + assert_eq!(waits.other.count, 2); + let exits = SystemExits { + barriers: waits, + ..SystemExits::default() + }; + assert!(!exits.is_empty()); + let mut merged = SystemExits::default(); + merged.merge(&exits); + merged.merge(&exits); + let merged = merged.barriers; + assert_eq!((merged.waits, merged.quick, merged.ticks), (70, 2, 130)); + let native = merged + .blockers + .iter() + .find(|b| b.key == BLOCKER_NATIVE) + .unwrap(); + assert_eq!((native.count, native.ticks), (2, 20)); + let dsb = merged.blockers.iter().find(|b| b.key == dsb).unwrap(); + assert_eq!((dsb.count, dsb.ticks), (2, 40)); + assert_eq!(merged.other.count, 4); + } + + #[test] + fn device_exits_count_by_page_and_merge_with_forwards() { + let mut exits = DeviceExits::default(); + assert!(exits.is_empty()); + assert_eq!(device_page(0x2_3b0c_8000), device_page(0x2_3b0c_8ffc)); + assert_ne!(device_page(0x2_3b0c_8000), device_page(0x2_3b0c_6658)); + for page in 0..DEVICE_PAGES as u32 + 3 { + exits.add(page, 1, 10, 2); + } + exits.add(0, 1, 5, 1); + exits.forwarded = 1; + exits.forwarded_ticks = 7; + let first = *exits.counted().find(|exit| exit.page == 0).unwrap(); + assert_eq!((first.count, first.ticks, first.waited), (2, 15, 3)); + assert_eq!(exits.counted().count(), DEVICE_PAGES); + assert_eq!((exits.other.count, exits.other.waited), (3, 6)); + let system = SystemExits { + devices: exits, + ..SystemExits::default() + }; + assert!(!system.is_empty()); + let mut merged = SystemExits::default(); + merged.merge(&system); + merged.merge(&system); + let first = *merged + .devices + .counted() + .find(|exit| exit.page == 0) + .unwrap(); + assert_eq!((first.count, first.waited), (4, 6)); + assert_eq!( + (merged.devices.forwarded, merged.devices.forwarded_ticks), + (2, 14) + ); + } + + #[test] + fn a_system_exit_is_charged_to_its_key_with_the_cells_it_closed() { + use super::super::tests::BASE; + const MRS_X1_TPIDR_EL1: u32 = 0xd538_d081; + const MSR_VBAR_EL1_X2: u32 = 0xd518_c002; + let mut machine = super::super::tests::machine(&[MRS_X1_TPIDR_EL1, MSR_VBAR_EL1_X2]); + machine.set_step_timing(true); + machine.cpu.state.x[2] = BASE + 0x800; + for pc in [BASE, BASE + 4] { + machine.host.exits.push(super::super::NativeExit::Exit { + next_pc: pc, + kind: stela_compiler::block::ExitKind::System as u64, + }); + machine.step().unwrap(); + } + assert_eq!(machine.cpu.pc, BASE + 8); + let system = stela_compiler::block::ExitKind::System as usize; + assert_eq!(machine.step_timing().unwrap().exits[system].0, 2); + let exits = machine.take_system_exits(); + let key = |key| *exits.counted().find(|exit| exit.key == key).unwrap(); + // The read changed nothing; the VBAR_EL1 write closed every cell. + assert_eq!((key(0xd538_d080).count, key(0xd538_d080).closes), (1, 0)); + assert_eq!((key(0xd518_c000).count, key(0xd518_c000).closes), (1, 1)); + assert!(machine.take_system_exits().is_empty()); + } + + /// A floating-point exit is charged to its whole word, which the report + /// tells from System keys, and stays out of the System words. + #[test] + fn a_floating_point_exit_is_charged_to_its_word() { + use super::super::tests::BASE; + const FADD_S0_S1_S2: u32 = 0x1e22_2820; + const FCVTNU_8H: u32 = 0x6e79_aa67; + let mut machine = super::super::tests::machine(&[FADD_S0_S1_S2]); + machine.set_step_timing(true); + // FP/SIMD enabled at EL1 (CPACR_EL1.FPEN). + machine + .cpu + .registers + .set(crate::machine::system::Register::CPACR_EL1, 0, 0b11 << 20); + machine.host.exits.push(super::super::NativeExit::Exit { + next_pc: BASE, + kind: stela_compiler::block::ExitKind::FloatingPoint as u64, + }); + machine.step().unwrap(); + assert_eq!(machine.cpu.pc, BASE + 4); + let slot = stela_compiler::block::ExitKind::FloatingPoint as usize; + assert_eq!(machine.step_timing().unwrap().exits[slot].0, 1); + let exits = machine.take_system_exits(); + let exit = *exits + .counted() + .find(|exit| exit.key == FADD_S0_S1_S2) + .unwrap(); + assert_eq!(exit.count, 1); + assert!(numerical_key(FADD_S0_S1_S2) && numerical_key(FCVTNU_8H)); + assert!(!numerical_key(0xd538_d080) && !numerical_key(DEVICE_SITE_KEY)); + assert!(system_key_name(FCVTNU_8H).ends_with(":0x6e79aa67")); + assert!(!machine.system_words().contains_key(&FADD_S0_S1_S2)); + // Zeros add exactly: no fresh flag. + assert_eq!(exits.floating[FloatingReason::Exact as usize], 1); + assert_eq!(exits.floating.iter().sum::(), 1); + // Its word counts the reason, the zero operands and the clear IXC. + let word = *exits + .floating_words + .counted() + .find(|word| word.key == FADD_S0_S1_S2) + .unwrap(); + assert_eq!(word.count(), 1); + assert_eq!(word.reasons[FloatingReason::Exact as usize], 1); + assert_eq!(word.inexact_clear, 1); + assert_eq!(word.operands[Operands::Zero as usize], 1); + assert_eq!(word.operands[Operands::Ordinary as usize], 1); + assert_eq!(word.operands[Operands::Subnormal as usize], 0); + } + + /// A pointer authentication exit is charged to its word, which the + /// report tells from System and floating-point keys, and stays out of + /// the System words. + #[test] + fn a_pointer_authentication_exit_is_charged_to_its_word() { + use super::super::tests::BASE; + const RETAA: u32 = 0xd65f_0bff; + // PACIASP, a hint whose key clears Rt. + const PACIASP: u32 = 0xd503_233f; + let mut machine = super::super::tests::machine(&[RETAA]); + machine.set_step_timing(true); + machine.cpu.state.x[30] = BASE + 0x40; + machine.host.exits.push(super::super::NativeExit::Exit { + next_pc: BASE, + kind: stela_compiler::block::ExitKind::PointerAuthentication as u64, + }); + let _ = machine.step(); + let slot = stela_compiler::block::ExitKind::PointerAuthentication as usize; + assert_eq!(machine.step_timing().unwrap().exits[slot].0, 1); + let exits = machine.take_system_exits(); + let exit = *exits.counted().find(|exit| exit.key == RETAA).unwrap(); + assert_eq!(exit.count, 1); + assert!(!machine.system_words().contains_key(&RETAA)); + assert!(pointer_key(RETAA) && pointer_key(system_key(PACIASP))); + assert!(system_key_name(RETAA).starts_with("PAC.")); + assert!(system_key_name(system_key(PACIASP)).starts_with("PAC.")); + assert!(!pointer_key(0xd538_d080) && !pointer_key(DEVICE_SITE_KEY)); + assert!(!pointer_key(0x1e22_2820) && !numerical_key(RETAA)); + } + + /// The census names what the operands of an exit held: subnormal, NaN + /// and zero source lanes, an indexed source's one lane, a tiny result, + /// and forms it does not read. + #[test] + fn a_floating_point_census_classifies_operands() { + use stela_compiler::{GuestState, aarch64::FloatingPointOperation}; + // FMLA V29.4S, V26.4S, V21.S[1]. + const FMLA_INDEXED_4S: u32 = 0x4fb5_135d; + // SCVTF D0, X0. + const SCVTF_D0_X0: u32 = 0x9e62_0000; + const ONE: u64 = 0x3f80_0000; + const SUBNORMAL: u64 = 0x0000_0001; + const NAN: u64 = 0x7fc0_0000; + let decode = |word| match FloatingPointOperation::decode(word) { + Some(Ok(operation)) => operation, + other => panic!("{word:#x}: {other:?}"), + }; + let fmla = decode(FMLA_INDEXED_4S); + let ones = ONE | ONE << 32; + let bit = |class: Operands| 1u8 << class as u8; + let mut state = GuestState::default(); + state.v[26] = [ones, ones]; + state.v[29] = [ones, ones]; + // Only lane 1 of V21 is read: a NaN in lane 0 is not. + state.v[21] = [NAN | ONE << 32, NAN | NAN << 32]; + let census = FloatingCensus::read(&state, &fmla); + assert_eq!(census.finish(&state, true), bit(Operands::Ordinary)); + // A subnormal lane of V26 and a tiny result lane. + state.v[26][1] = ONE | SUBNORMAL << 32; + let census = FloatingCensus::read(&state, &fmla); + state.v[29][0] = SUBNORMAL; + assert_eq!( + census.finish(&state, true), + bit(Operands::Subnormal) | bit(Operands::Tiny) + ); + // A trapped completion's result is not read. + state.v[29] = [ones, ones]; + let census = FloatingCensus::read(&state, &fmla); + state.v[29][0] = SUBNORMAL; + assert_eq!(census.finish(&state, false), bit(Operands::Subnormal)); + // NaN and zero in the addend. + state.v[26] = [ones, ones]; + state.v[29] = [NAN, ones]; + let census = FloatingCensus::read(&state, &fmla); + state.v[29] = [ones, ones]; + assert_eq!( + census.finish(&state, true), + bit(Operands::Nan) | bit(Operands::Zero) + ); + let scvtf = decode(SCVTF_D0_X0); + let census = FloatingCensus::read(&state, &scvtf); + assert_eq!(census.finish(&state, true), bit(Operands::Unread)); + } + + #[test] + fn floating_words_count_by_word_and_keep_the_rest_in_other() { + let mut words = FloatingWords::default(); + assert!(words.is_empty()); + let subnormal = 1 << Operands::Subnormal as u8; + for key in 0..FLOATING_WORDS as u32 + 2 { + words.add(key, FloatingReason::Exact, false, subnormal, true); + } + words.add(0, FloatingReason::Inexact, true, subnormal, false); + let first = *words.counted().find(|word| word.key == 0).unwrap(); + assert_eq!(first.count(), 2); + assert_eq!(first.reasons[FloatingReason::Mode as usize], 1); + assert_eq!(first.operands[Operands::Subnormal as usize], 2); + assert_eq!(first.inexact_clear, 1); + assert_eq!(words.counted().count(), FLOATING_WORDS); + assert_eq!(words.other.count(), 2); + let exits = SystemExits { + floating_words: words, + ..SystemExits::default() + }; + assert!(!exits.is_empty()); + let mut merged = SystemExits::default(); + merged.merge(&exits); + merged.merge(&exits); + let first = *merged + .floating_words + .counted() + .find(|word| word.key == 0) + .unwrap(); + assert_eq!((first.count(), first.inexact_clear), (4, 2)); + assert_eq!(merged.floating_words.other.count(), 4); + } + + /// The reason counter keeps FPSR as the completion leaves it: earlier + /// flags stay, fresh ones are added, and the first fresh one names it. + #[test] + fn a_floating_point_exit_reason_keeps_fpsr() { + use super::super::tests::BASE; + const FDIV_S0_S1_S2: u32 = 0x1e22_1820; + const INEXACT: u32 = 1 << 4; + let mut machine = super::super::tests::machine(&[FDIV_S0_S1_S2]); + machine.set_step_timing(true); + machine + .cpu + .registers + .set(crate::machine::system::Register::CPACR_EL1, 0, 0b11 << 20); + machine.cpu.state.fpsr = INEXACT; + // 1 / 0: divide by zero. + machine.cpu.state.v[1] = [0x3f80_0000, 0]; + machine.host.exits.push(super::super::NativeExit::Exit { + next_pc: BASE, + kind: stela_compiler::block::ExitKind::FloatingPoint as u64, + }); + machine.step().unwrap(); + assert_eq!(machine.cpu.state.fpsr, INEXACT | 1 << 1); + assert_eq!(machine.cpu.state.v[0][0], 0x7f80_0000); + let exits = machine.take_system_exits(); + assert_eq!(exits.floating[FloatingReason::Divide as usize], 1); + assert_eq!(FloatingReason::of(0, 0x11, false), FloatingReason::Invalid); + assert_eq!(FloatingReason::of(1 << 8, 0, false), FloatingReason::Trap); + assert_eq!( + FloatingReason::of(0, 0x18, false), + FloatingReason::Underflow + ); + assert_eq!(FloatingReason::of(0, 0x10, false), FloatingReason::Inexact); + } + + /// Busy phases go to the guest level they were charged at, the kernel + /// run before a WFI is kept at it, and an interrupt's ticks end with + /// its exception return, whose own ticks count. + #[test] + fn busy_time_is_split_by_level_wait_and_interrupt() { + use super::super::tests::{machine_on, one_timer_bank}; + const WFI: u32 = 0xd503_207f; + let mut machine = machine_on(one_timer_bank(), &[]); + machine.set_step_timing(true); + machine.cpu.pstate.el = 0; + machine.host.now = 10; + machine.timing_charge(Phase::Native, 0); + machine.cpu.pstate.el = 1; + machine.host.now = 30; + machine.timing_charge(Phase::Fetch, 10); + machine.host.now = 100; + machine.timing_charge(Phase::Schedule, 30); + machine.cpu.pstate.guarded = true; + machine.host.now = 105; + machine.timing_charge(Phase::Native, 100); + machine.cpu.pstate.guarded = false; + let levels = machine.step_timing().unwrap().levels; + assert_eq!(levels.ticks, [10, 20, 5]); + assert_eq!(levels.kernel_run, 25); + // Nothing pending: the WFI waits, and takes the kernel run. + machine.lines(); + machine.system_instruction(WFI).unwrap(); + assert!(machine.waiting.is_some()); + machine.waiting = None; + let levels = machine.step_timing().unwrap().levels; + assert_eq!((levels.wfi, levels.wfi_at_once), (1, 0)); + assert_eq!((levels.kernel_before_wfi, levels.kernel_run), (25, 0)); + // An expired virtual timer's FIQ, taken, then its handler's return. + machine.cpu.state.x[0] = 1500; + machine.system_instruction(0xd51b_e300).unwrap(); // msr cntv_tval_el0, x0 + machine.cpu.state.x[0] = 1; + machine.system_instruction(0xd51b_e320).unwrap(); // msr cntv_ctl_el0, x0 + machine.host.now = 2000; + machine.lines(); + // Pending though masked: a WFI completes at once. + machine.cpu.pstate.daif = 0xf; + machine.system_instruction(WFI).unwrap(); + assert!(machine.waiting.is_none()); + machine.cpu.pstate.daif = 0; + assert!(machine.deliver_interrupts()); + machine.host.now = 2007; + machine.timing_charge(Phase::Native, 2000); + machine.timed_word = Some(0xd69f_03e0); + machine.host.now = 2010; + machine.timing_exit(stela_compiler::block::ExitKind::System as usize, 2007); + machine.host.now = 2050; + machine.timing_charge(Phase::Native, 2010); + let levels = machine.step_timing().unwrap().levels; + assert_eq!((levels.wfi, levels.wfi_at_once), (2, 1)); + assert_eq!((levels.interrupts, levels.interrupt_ticks), (1, 10)); + assert!(!levels.in_interrupt); + // A delta keeps the state and subtracts the counts. + let delta = levels.since(&Levels { + wfi: 1, + ticks: [10, 0, 0], + ..Levels::default() + }); + assert_eq!((delta.wfi, delta.ticks[0]), (1, 0)); + assert_eq!(delta.kernel_run, levels.kernel_run); + assert!(exception_return(0xd69f_0bff) && !exception_return(0xd65f_03c0)); + } + + #[test] + fn a_delta_subtracts_each_phase_and_exit() { + let mut earlier = StepTiming::default(); + earlier.phases[Phase::Exit as usize] = 5; + earlier.exits[FAULT_SLOT] = (1, 10); + earlier.lifetime_maxima[Phase::Exit as usize].observe(5, 50, 0x1000, 1, 2); + let mut now = earlier; + now.phases[Phase::Exit as usize] = 12; + now.exits[FAULT_SLOT] = (3, 40); + now.lifetime_maxima[Phase::Exit as usize].observe(9, 90, 0x2000, 2, 3); + let delta = now.since(&earlier); + assert_eq!(delta.phases[Phase::Exit as usize], 7); + assert_eq!(delta.exits[FAULT_SLOT], (2, 30)); + assert_eq!(delta.phases[Phase::Native as usize], 0); + assert_eq!(delta.lifetime_maxima, now.lifetime_maxima); + let later_delta = now.since(&now); + assert_eq!(later_delta.phases, [0; Phase::COUNT]); + assert_eq!(later_delta.lifetime_maxima, now.lifetime_maxima); + } + + /// Native code makes most exception returns (`PES TRANSITIONS eret`): + /// one ends the handler the engine saw taken, and so does reaching EL0, + /// where no handler runs. Before, only a return the engine handled did, + /// and `irq%` counted the user time after native returns. + #[test] + fn a_native_exception_return_or_el0_time_ends_the_interrupt() { + let mut levels = Levels::default(); + levels.interrupt_taken(); + levels.charge(Level::Kernel, 5); + levels.exception_returned(); + levels.charge(Level::Kernel, 7); + assert_eq!((levels.interrupts, levels.interrupt_ticks), (1, 5)); + levels.interrupt_taken(); + levels.charge(Level::Guarded, 2); + levels.charge(Level::User, 30); + levels.charge(Level::Kernel, 4); + assert_eq!((levels.interrupts, levels.interrupt_ticks), (2, 7)); + assert!(!levels.in_interrupt); + // In-interrupt time never exceeds kernel and guarded time. + let handlers = levels.ticks[Level::Kernel as usize] + levels.ticks[Level::Guarded as usize]; + assert!(levels.interrupt_ticks <= handlers); + } + + #[test] + fn completed_phase_maxima_keep_their_materialized_witness_and_clock_samples() { + let mut machine = super::super::tests::machine(&[]); + machine.set_step_timing(true); + let reads = machine.host.counter_reads; + machine.host.now = 100; + machine.cpu.pc = 0x4000; + machine.cpu.pstate.el = 1; + machine.cpu.pstate.daif = 2; + assert_eq!(machine.timing_charge(Phase::Fetch, 90), 100); + let first = Maximum { + ticks: 10, + finished_ticks: 100, + pc_after: 0x4000, + el_after: 1, + daif_after: 2, + }; + assert_eq!( + machine.step_timing().unwrap().lifetime_maxima[Phase::Fetch as usize], + first + ); + machine.host.now = 115; + machine.cpu.pc = 0x5000; + machine.timing_charge(Phase::Fetch, 110); + machine.host.now = 125; + machine.timing_charge(Phase::Fetch, 115); + // Smaller and tied intervals preserve the original witness. + assert_eq!( + machine.step_timing().unwrap().lifetime_maxima[Phase::Fetch as usize], + first + ); + machine.host.now = 200; + machine.cpu.pstate.el = 2; + machine.cpu.pstate.daif = 15; + machine.timing_charge(Phase::Fetch, 150); + let timing = machine.step_timing().unwrap(); + assert_eq!(timing.phases[Phase::Fetch as usize], 75); + assert_eq!( + timing.lifetime_maxima[Phase::Fetch as usize], + Maximum { + ticks: 50, + finished_ticks: 200, + pc_after: 0x5000, + el_after: 2, + daif_after: 15 + } + ); + // Exit/fault accounting uses its existing sample too, including wrap. + machine.host.now = 4; + machine.timing_exit(FAULT_SLOT, u64::MAX - 8); + let timing = machine.step_timing().unwrap(); + assert_eq!(timing.exits[FAULT_SLOT], (1, 13)); + assert_eq!(timing.phases[Phase::Exit as usize], 13); + assert_eq!( + timing.lifetime_maxima[Phase::Exit as usize], + Maximum { + ticks: 13, + finished_ticks: 4, + pc_after: 0x5000, + el_after: 2, + daif_after: 15 + } + ); + assert_eq!(machine.host.counter_reads - reads, 5); + } + + #[test] + fn a_device_faults_ticks_go_to_the_register_it_reached() { + const REGISTER: u64 = 0x2_3520_0018; + let mut machine = super::super::tests::machine(&[]); + machine.set_step_timing(true); + machine.count_device_access(REGISTER); + machine.host.now = 30; + machine.timing_exit(DEVICE_FAULT_SLOT, 10); + // Another exit's ticks are not the register's, even after an + // access it did not fault for. + machine.count_device_access(REGISTER); + machine.host.now = 100; + machine.timing_exit(FAULT_SLOTS, 40); + machine.host.now = 120; + machine.timing_exit(DEVICE_FAULT_SLOT, 110); + assert_eq!( + machine.device_registers()[®ISTER], + super::super::DeviceRegister { + accesses: 2, + ticks: 20 + } + ); + } + + /// A native check fault is charged to what the engine found at it, once; + /// another exit keeps its slot and leaves the finding alone. + #[test] + fn check_faults_are_charged_by_outcome() { + assert_eq!( + fault_slot(&super::super::FaultCause::NonCanonical), + CHECK_FAULT_SLOT + ); + let slots = [ + Check::Tagged, + Check::Alignment, + Check::Abort, + Check::Translated, + ] + .map(Check::slot); + assert_eq!(slots, [19, 20, 21, 22]); + assert_eq!(EXIT_SLOTS, 23); + let mut machine = super::super::tests::machine(&[]); + machine.set_step_timing(true); + machine.timed_check(Check::Tagged); + machine.timing_exit(CHECK_FAULT_SLOT, 0); + machine.timing_exit(CHECK_FAULT_SLOT, 0); + machine.timed_check(Check::Abort); + machine.timing_exit(FAULT_SLOTS, 0); + let exits = machine.step_timing().unwrap().exits; + assert_eq!(exits[Check::Tagged.slot()].0, 1); + assert_eq!(exits[CHECK_FAULT_SLOT].0, 1); + assert_eq!(exits[FAULT_SLOTS].0, 1); + assert_eq!(exits[Check::Abort.slot()].0, 0); + assert_eq!(machine.step_timing().unwrap().check, None); + } + + #[test] + fn resetting_timing_clears_maxima_and_disabled_timing_reads_no_clock() { + let mut machine = super::super::tests::machine(&[]); + let reads = machine.host.counter_reads; + assert_eq!(machine.timing_start(), 0); + assert_eq!(machine.timing_charge(Phase::Fetch, 0), 0); + machine.timing_exit(FAULT_SLOT, 0); + assert_eq!(machine.host.counter_reads, reads); + machine.set_step_timing(true); + machine.host.now = 20; + machine.timing_charge(Phase::Native, 10); + assert_eq!( + machine.step_timing().unwrap().lifetime_maxima[Phase::Native as usize].ticks, + 10 + ); + let reads = machine.host.counter_reads; + machine.set_step_timing(true); + assert_eq!(machine.step_timing(), Some(&StepTiming::default())); + machine.set_step_timing(false); + assert!(machine.step_timing().is_none()); + machine.timing_exit(FAULT_SLOT, 0); + assert_eq!(machine.host.counter_reads, reads); + } +} diff --git a/crates/stela-engine/src/pauth.rs b/crates/stela-engine/src/pauth.rs index 99edb43c4d..61519fa707 100644 --- a/crates/stela-engine/src/pauth.rs +++ b/crates/stela-engine/src/pauth.rs @@ -1,500 +1,519 @@ -//! Software pointer authentication (QARMA5) for arm64e. -//! -//! The default profile is PAuth1 with a 47-bit VA, instruction TBI off and data -//! TBI on in the lower range only (`PROCESS_TCR`). Signing a pointer with an invalid extension corrupts the PAC; a failed -//! authentication returns the classic poisoned pointer. Optional profiles add -//! PAuth2 XOR insertion and FPAC/FPACCOMBINE faults. The caller owns the keys and -//! binds the context to its address space. QARMA (`qarma`) never indexes memory -//! with secret data: its S-box is Boolean polynomials or, with SSSE3, PSHUFB -//! register lookups (Arm pseudocode `ComputePACQARMA`, `InsertPAC`, -//! `Authenticate`). -use core::fmt; -use serde::Serialize; - -pub mod generic; -pub mod memory; -pub mod policy; -pub use policy::Version; - -pub const PROFILE_ID: &str = "stela-classic-arm64e-qarma5-va47-itbi0-ib-v1"; -pub const FULL_PROFILE_ID: &str = "stela-classic-arm64e-qarma5-va47-itbi0-dtbi1-all-keys-v1"; -pub const GENERIC_PROFILE_ID: &str = - "stela-classic-arm64e-qarma5-va47-itbi0-dtbi1-explicit-keys-ga-v1"; -pub const ENHANCED_PROFILE_ID: &str = "stela-pauth2-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; -pub const FAULTING_PROFILE_ID: &str = "stela-fpac-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; -pub const COMBINED_PROFILE_ID: &str = "stela-fpaccombine-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; -const GENERIC_CODE_MASK: u64 = (u32::MAX as u64) << u32::BITS; -#[cfg(test)] -const ADDRESS_MASK: u64 = (1 << 47) - 1; -#[cfg(test)] -const REGION_BIT: u64 = 1 << 55; -#[cfg(test)] -const PAC_MASK: u64 = !(ADDRESS_MASK | REGION_BIT); -#[cfg(test)] -const POISON_MASK: u64 = 3 << 61; -#[cfg(test)] -const IB_POISON: u64 = 2 << 61; -#[cfg(test)] -const DATA_EXTENSION_MASK: u64 = 0x00ff_ffff_ffff_ffff & !ADDRESS_MASK; -#[cfg(test)] -const DATA_PAC_MASK: u64 = DATA_EXTENSION_MASK & !REGION_BIT; - -use stela_contracts::pauth::Key; - -const fn key_domain(key: Key) -> policy::Domain { - if key.is_data() { - policy::Domain::Data - } else { - policy::Domain::Instruction - } -} -#[cfg(test)] -const fn key_pac_mask(key: Key) -> u64 { - if key.is_data() { - DATA_PAC_MASK - } else { - PAC_MASK - } -} - -/// Process keys, never Debug or Serialize. Each pair follows the architectural -/// KeyLo/KeyHi registers. A missing key is not a zero key. -pub struct Keys { - words: [Option<[u64; 2]>; 4], - generic: Option<[u64; 2]>, -} -impl Keys { - pub fn from_ib_words(low: u64, high: u64) -> Self { - Self::from_optional_words([None, Some([low, high]), None, None]) - } - pub fn from_words(ia: [u64; 2], ib: [u64; 2], da: [u64; 2], db: [u64; 2]) -> Self { - Self::from_optional_words([Some(ia), Some(ib), Some(da), Some(db)]) - } - /// Build a key set where absent keys stay absent rather than zero. - pub(crate) fn from_optional_words(words: [Option<[u64; 2]>; 4]) -> Self { - Self { - words, - generic: None, - } - } - pub fn with_generic_words(mut self, words: [u64; 2]) -> Self { - self.generic = Some(words); - self - } - fn get(&self, key: Key) -> Result<&[u64; 2], AuthenticationError> { - self.words[key.index()] - .as_ref() - .ok_or(AuthenticationError::KeyUnavailable { key }) - } -} - -pub struct Context { - address_space: u64, - keys: Keys, - version: Version, - /// TCR_EL1 of the system-mode regime; `None` keeps the process profile. - regime: Option, - /// Whether PACs come from [`keyed`], not QARMA5. - keyed: bool, - /// The regime's layouts worked out ahead ([`Self::with_layouts`]). - layouts: Option, -} - -/// Every PAC layout of one translation regime, by domain, by signing or -/// authentication and by the pointer's bits 55 and 63, which select the -/// range ([`Context::with_layouts`]): a signing or authentication then looks -/// its layout up instead of working it out from TCR_EL1. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Layouts { - tcr: u64, - table: [policy::Layout; 16], -} - -impl Layouts { - /// The layouts of the regime TCR_EL1 `tcr` describes. - pub fn new(tcr: u64) -> Self { - let mut table = [policy::Domain::Data.layout(); 16]; - for (index, layout) in table.iter_mut().enumerate() { - let domain = if index & 8 != 0 { - policy::Domain::Data - } else { - policy::Domain::Instruction - }; - let pointer = (index as u64 & 2) << 54 | (index as u64 & 1) << 63; - *layout = regime_layout(tcr, domain, pointer, index & 4 != 0); - } - Self { tcr, table } - } - - /// The TCR_EL1 the layouts follow. - pub fn tcr(&self) -> u64 { - self.tcr - } - - /// What native code completes `domain`'s canonical pointers with - /// (`x86_64::pointer::cipher::Range`): the authentication layout's - /// extension mask with bit 55 clear and set. `Auth` selects TnSZ and TBI - /// by bit 55. So does `AddPAC` for a pointer whose extension is all - /// equal to bit 55: when it selects by bit 63 instead, neither range - /// ignores the top byte, so its extension holds bit 63, equal to bit 55. - pub(crate) fn native(&self, data: bool) -> [u64; 2] { - let domain = if data { - policy::Domain::Data - } else { - policy::Domain::Instruction - }; - [0, 1 << 55].map(|pointer| self.get(domain, pointer, false).extension_mask()) - } - - fn get(&self, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { - let index = usize::from(domain == policy::Domain::Data) << 3 - | usize::from(signing) << 2 - | ((pointer >> 54) & 2) as usize - | (pointer >> 63) as usize; - self.table[index] - } -} - -/// The PAC field of `pointer` for an `operation` in `domain` under TCR_EL1 -/// `tcr`. Arm `AddPAC` selects the range whose TnSZ bounds the field by bit -/// 55 when either range ignores the domain's top byte and by bit 63 -/// otherwise; `Auth` and `Strip` always select by bit 55 -/// (`CalculateBottomPACBit(ptr<55>)`), since a signed pointer's bit 63 is PAC -/// whenever the top byte is not ignored. Only bits 55 and 63 of `pointer` -/// matter ([`Layouts`]). -fn regime_layout(tcr: u64, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { - // EffectiveTBI selects TBI0/TBI1 by bit 55; TBIDn exempts instructions. - let ignores_top_byte = |upper: bool| { - let (tbi, tbid) = if upper { (38, 52) } else { (37, 51) }; - tcr & (1 << tbi) != 0 && !(domain == policy::Domain::Instruction && tcr & (1 << tbid) != 0) - }; - let tbi = ignores_top_byte(pointer & (1 << 55) != 0); - let select = if signing && !ignores_top_byte(false) && !ignores_top_byte(true) { - 63 - } else { - 55 - }; - let tnsz = if pointer & (1 << select) != 0 { - (tcr >> 16) & 63 - } else { - tcr & 63 - }; - // CalculateBottomPACBit: an out-of-range TnSZ is CONSTRAINED - // UNPREDICTABLE, FORCE or NONE; FORCE to 16..=39 (no FEAT_TTST or - // 52-bit VAs), the range the system engine's walker admits. - let tnsz = tnsz.clamp(MIN_TNSZ, MAX_TNSZ); - policy::Layout::new(64 - tnsz as u32, if tbi { 55 } else { 63 }, select) -} -impl fmt::Debug for Context { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Context") - .field("address_space", &self.address_space) - .field("profile", &self.profile_id()) - .finish_non_exhaustive() - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -pub struct AuthResult { - pub pointer: u64, - pub authenticated: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum AuthenticationError { - KeyUnavailable { key: Key }, - GenericKeyUnavailable, - Failure { code: u8 }, -} - -impl fmt::Display for AuthenticationError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::KeyUnavailable { key } => write!( - formatter, - "pointer authentication key {key:?} is unavailable" - ), - Self::GenericKeyUnavailable => { - formatter.write_str("generic pointer authentication key is unavailable") - } - Self::Failure { code } => write!( - formatter, - "architectural pointer authentication failure {code}" - ), - } - } -} - -impl core::error::Error for AuthenticationError {} - -impl Context { - pub fn new(address_space: u64, keys: Keys) -> Self { - Self::new_with_version(address_space, keys, Version::Classic) - } - pub fn new_with_version(address_space: u64, keys: Keys, version: Version) -> Self { - Self { - address_space, - keys, - version, - regime: None, - keyed: false, - layouts: None, - } - } - - /// Lay PAC fields out for the EL1&0 regime this TCR_EL1 describes, as - /// the system-mode engine requires, instead of the fixed process profile. - pub fn with_translation_regime(mut self, tcr: u64) -> Self { - self.regime = Some(tcr); - self.layouts = None; - self - } - - /// [`Self::with_translation_regime`] with that regime's layouts worked - /// out ahead, for a context that serves many results. - pub fn with_layouts(mut self, layouts: Layouts) -> Self { - self.regime = Some(layouts.tcr); - self.layouts = Some(layouts); - self - } - - /// Take [`keyed`]'s cipher in place of QARMA5. The ID registers still - /// report QARMA5, which only a guest recomputing a PAC from its own keys - /// could find untrue. - pub fn with_implementation_defined_cipher(mut self) -> Self { - self.keyed = true; - self - } - - /// The PAC of `data` and `modifier` under `key`. - #[inline] - fn cipher(&self, data: u64, modifier: u64, key: &[u64; 2]) -> u64 { - match self.keyed { - true => keyed::compute(data, modifier, key), - false => qarma5(data, modifier, key), - } - } - - /// The PAC field of `pointer` for an `operation` in `domain` - /// ([`regime_layout`]). - #[inline] - fn layout(&self, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { - match &self.layouts { - Some(layouts) => layouts.get(domain, pointer, signing), - None => regime_layout(self.regime.unwrap_or(PROCESS_TCR), domain, pointer, signing), - } - } - pub fn version(&self) -> Version { - self.version - } - pub fn address_space(&self) -> u64 { - self.address_space - } - pub fn profile_id(&self) -> &'static str { - match self.version { - Version::Enhanced => ENHANCED_PROFILE_ID, - Version::Faulting => FAULTING_PROFILE_ID, - Version::FaultingCombined => COMBINED_PROFILE_ID, - Version::Classic if self.keys.generic.is_some() => GENERIC_PROFILE_ID, - Version::Classic if self.keys.words.iter().all(Option::is_some) => FULL_PROFILE_ID, - Version::Classic => PROFILE_ID, - } - } - pub fn has_key(&self, key: Key) -> bool { - self.keys.words[key.index()].is_some() - } - - /// InsertPAC with the process's VA47 controls (`PROCESS_TCR`): instruction - /// TBI off, data TBI on in the lower range. - /// Data keeps its tag in both QARMA input and output; it is not ignored by - /// authentication. Null is signed. Classic invalid extension corrupts - /// PAC bit62 (instruction) or54 (data), following June2026 Arm ASL, rather - /// than the older Unicorn invalid-extension behavior. Enhanced profiles XOR the PAC field. - pub fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { - Ok(self.sign_with(key, self.keys.get(key)?, pointer, modifier)) - } - - /// [`Self::sign`] with `key`'s `words` in hand, for the hot path of a - /// service that has already looked them up ([`Self::words`]). - #[inline(always)] - pub(crate) fn sign_with(&self, key: Key, words: &[u64; 2], pointer: u64, modifier: u64) -> u64 { - let layout = self.layout(key_domain(key), pointer, true); - let input = policy::signing_input(layout, pointer); - policy::sign( - self.version, - layout, - pointer, - self.cipher(input, modifier, words), - ) - } - - /// The AES schedule native code computes PACs of the key at tag word - /// `index` with (`x86_64::pointer::cipher`): IA, IB, DA, DB, then the - /// generic key. `None` when the context lacks the key or its cipher is - /// not the AES rounds native code runs ([`keyed::native`]). - pub(crate) fn native_schedule(&self, index: usize) -> Option<[[u64; 2]; keyed::SCHEDULE]> { - if !self.keyed || !keyed::native() { - return None; - } - let words = match index { - 4 => self.keys.generic.as_ref(), - index => self.keys.words.get(index)?.as_ref(), - }?; - Some(keyed::schedule(words)) - } - - /// The words of `key`, when the context has it. - #[inline] - pub(crate) fn words(&self, key: Key) -> Option<&[u64; 2]> { - self.keys.words[key.index()].as_ref() - } - - /// Standalone AUT policy; combined loads/transfers use authenticate_operation. - pub fn authenticate( - &self, - key: Key, - pointer: u64, - modifier: u64, - ) -> Result { - self.authenticate_operation(key, pointer, modifier, false) - } - - pub fn authenticate_operation( - &self, - key: Key, - pointer: u64, - modifier: u64, - combined: bool, - ) -> Result { - let result = self - .authenticate_with(key, self.keys.get(key)?, pointer, modifier, combined) - .map_err(|failure| AuthenticationError::Failure { code: failure.code })?; - Ok(AuthResult { - pointer: result.pointer, - authenticated: result.authenticated, - }) - } - - /// [`Self::authenticate_operation`] with `key`'s `words` in hand - /// ([`Self::sign_with`]). - #[inline(always)] - pub(crate) fn authenticate_with( - &self, - key: Key, - words: &[u64; 2], - pointer: u64, - modifier: u64, - combined: bool, - ) -> Result { - let domain = key_domain(key); - let layout = self.layout(domain, pointer, false); - let input = policy::authentication_input(layout, pointer); - policy::authenticate( - self.version, - domain, - layout, - if key.is_b() { - policy::Side::B - } else { - policy::Side::A - }, - combined, - pointer, - self.cipher(input, modifier, words), - ) - } - - pub fn has_generic_key(&self) -> bool { - self.keys.generic.is_some() - } - - /// PACGA has no address-domain canonicalization; all64 data/modifier bits enter QARMA. - pub fn generic_code(&self, data: u64, modifier: u64) -> Result { - let words = self - .keys - .generic - .as_ref() - .ok_or(AuthenticationError::GenericKeyUnavailable)?; - Ok(self.cipher(data, modifier, words) & GENERIC_CODE_MASK) - } - - /// Architectural XPAC: keyless restoration, never an authentication check. - /// Ia/Ib select instruction layout, Da/Db tagged-data layout; this succeeds - /// even when that domain's cryptographic key was not provided. - #[inline] - pub fn strip(&self, key: Key, pointer: u64) -> u64 { - policy::authentication_input(self.layout(key_domain(key), pointer, false), pointer) - } - - /// The bits kept by XPAC in the lower and upper address ranges. - /// Strip selects both its TnSZ and effective TBI by pointer bit 55. - /// These masks contain no key material and do not depend on key enables. - pub(crate) fn stripping_masks(&self, data: bool) -> [u64; 2] { - let domain = if data { - policy::Domain::Data - } else { - policy::Domain::Instruction - }; - [0, 1 << 55].map(|pointer| !self.layout(domain, pointer, false).extension_mask()) - } - - /// Sign with the IB key (the original single-key profile). - pub fn sign_ib(&self, pointer: u64, modifier: u64) -> Result { - self.sign(Key::Ib, pointer, modifier) - } - pub fn authenticate_ib( - &self, - pointer: u64, - modifier: u64, - ) -> Result { - self.authenticate(Key::Ib, pointer, modifier) - } -} - -/// The EL0 regime of a macOS process: T0SZ = T1SZ = 17 (VA47), TBI0 with -/// TBID0, so lower-range data pointers keep their top byte and instruction -/// pointers do not, and TBI1 clear, so upper-range pointers keep no top -/// byte. An M1 Pro strips XPACD 0x00ff7fff12345678 to 0xffffffff12345678 -/// and 0x5a3c7fff12345678 to 0x5a007fff12345678 (`cargo xtask -/// cpu-reference`). -const PROCESS_TCR: u64 = 17 | 17 << 16 | 1 << 37 | 1 << 51; - -/// TnSZ limits of the PAC field without FEAT_TTST or 52-bit VAs. -const MIN_TNSZ: u64 = 16; -const MAX_TNSZ: u64 = 39; - -pub(crate) mod keyed; -mod qarma; -use qarma::compute as qarma5; - -pub(crate) mod features; -pub use features::UnsupportedInstructionProfile; - -pub(crate) mod lr_instruction; - -mod two_modifier; - -pub(crate) mod conditional; - -impl stela_contracts::pauth::TranslationSigner for Context { - fn with_translation_regime(self, tcr_el1: u64) -> Self { - Self::with_translation_regime(self, tcr_el1) - } -} - -impl stela_contracts::pauth::Signer for Context { - type Error = AuthenticationError; - fn address_space(&self) -> u64 { - self.address_space() - } - fn profile_id(&self) -> &'static str { - self.profile_id() - } - fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { - self.sign(key, pointer, modifier) - } -} - -#[cfg(test)] -mod tests; +//! Software pointer authentication (QARMA5) for arm64e. +//! +//! The default profile is PAuth1 with a 47-bit VA, instruction TBI off and data +//! TBI on in the lower range only (`PROCESS_TCR`). Signing a pointer with an invalid extension corrupts the PAC; a failed +//! authentication returns the classic poisoned pointer. Optional profiles add +//! PAuth2 XOR insertion and FPAC/FPACCOMBINE faults. The caller owns the keys and +//! binds the context to its address space. QARMA (`qarma`) never indexes memory +//! with secret data: its S-box is Boolean polynomials or, with SSSE3, PSHUFB +//! register lookups (Arm pseudocode `ComputePACQARMA`, `InsertPAC`, +//! `Authenticate`). +use core::fmt; +use serde::Serialize; + +pub mod generic; +pub mod memory; +pub mod policy; +pub use policy::Version; + +pub const PROFILE_ID: &str = "stela-classic-arm64e-qarma5-va47-itbi0-ib-v1"; +pub const FULL_PROFILE_ID: &str = "stela-classic-arm64e-qarma5-va47-itbi0-dtbi1-all-keys-v1"; +pub const GENERIC_PROFILE_ID: &str = + "stela-classic-arm64e-qarma5-va47-itbi0-dtbi1-explicit-keys-ga-v1"; +pub const ENHANCED_PROFILE_ID: &str = "stela-pauth2-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; +pub const FAULTING_PROFILE_ID: &str = "stela-fpac-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; +pub const COMBINED_PROFILE_ID: &str = "stela-fpaccombine-qarma5-va47-itbi0-dtbi1-explicit-keys-v1"; +const GENERIC_CODE_MASK: u64 = (u32::MAX as u64) << u32::BITS; +#[cfg(test)] +const ADDRESS_MASK: u64 = (1 << 47) - 1; +#[cfg(test)] +const REGION_BIT: u64 = 1 << 55; +#[cfg(test)] +const PAC_MASK: u64 = !(ADDRESS_MASK | REGION_BIT); +#[cfg(test)] +const POISON_MASK: u64 = 3 << 61; +#[cfg(test)] +const IB_POISON: u64 = 2 << 61; +#[cfg(test)] +const DATA_EXTENSION_MASK: u64 = 0x00ff_ffff_ffff_ffff & !ADDRESS_MASK; +#[cfg(test)] +const DATA_PAC_MASK: u64 = DATA_EXTENSION_MASK & !REGION_BIT; + +use stela_contracts::pauth::Key; + +const fn key_domain(key: Key) -> policy::Domain { + if key.is_data() { + policy::Domain::Data + } else { + policy::Domain::Instruction + } +} +#[cfg(test)] +const fn key_pac_mask(key: Key) -> u64 { + if key.is_data() { + DATA_PAC_MASK + } else { + PAC_MASK + } +} + +/// Process keys, never Debug or Serialize. Each pair follows the architectural +/// KeyLo/KeyHi registers. A missing key is not a zero key. +pub struct Keys { + words: [Option<[u64; 2]>; 4], + generic: Option<[u64; 2]>, +} +impl Keys { + pub fn from_ib_words(low: u64, high: u64) -> Self { + Self::from_optional_words([None, Some([low, high]), None, None]) + } + pub fn from_words(ia: [u64; 2], ib: [u64; 2], da: [u64; 2], db: [u64; 2]) -> Self { + Self::from_optional_words([Some(ia), Some(ib), Some(da), Some(db)]) + } + /// Build a key set where absent keys stay absent rather than zero. + pub(crate) fn from_optional_words(words: [Option<[u64; 2]>; 4]) -> Self { + Self { + words, + generic: None, + } + } + pub fn with_generic_words(mut self, words: [u64; 2]) -> Self { + self.generic = Some(words); + self + } + fn get(&self, key: Key) -> Result<&[u64; 2], AuthenticationError> { + self.words[key.index()] + .as_ref() + .ok_or(AuthenticationError::KeyUnavailable { key }) + } +} + +pub struct Context { + address_space: u64, + keys: Keys, + version: Version, + /// TCR_EL1 of the system-mode regime; `None` keeps the process profile. + regime: Option, + /// Whether PACs come from [`keyed`], not QARMA5. + keyed: bool, + /// The regime's layouts worked out ahead ([`Self::with_layouts`]). + layouts: Option, +} + +/// Every PAC layout of one translation regime, by domain, by signing or +/// authentication and by the pointer's bits 55 and 63, which select the +/// range ([`Context::with_layouts`]): a signing or authentication then looks +/// its layout up instead of working it out from TCR_EL1. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Layouts { + tcr: u64, + table: [policy::Layout; 16], +} + +impl Layouts { + /// The layouts of the regime TCR_EL1 `tcr` describes. + pub fn new(tcr: u64) -> Self { + let mut table = [policy::Domain::Data.layout(); 16]; + for (index, layout) in table.iter_mut().enumerate() { + let domain = if index & 8 != 0 { + policy::Domain::Data + } else { + policy::Domain::Instruction + }; + let pointer = (index as u64 & 2) << 54 | (index as u64 & 1) << 63; + *layout = regime_layout(tcr, domain, pointer, index & 4 != 0); + } + Self { tcr, table } + } + + /// The TCR_EL1 the layouts follow. + pub fn tcr(&self) -> u64 { + self.tcr + } + + /// What native code completes `domain`'s canonical pointers with + /// (`x86_64::pointer::cipher::Range`): the authentication layout's + /// extension mask with bit 55 clear and set. `Auth` selects TnSZ and TBI + /// by bit 55. So does `AddPAC` for a pointer whose extension is all + /// equal to bit 55: when it selects by bit 63 instead, neither range + /// ignores the top byte, so its extension holds bit 63, equal to bit 55. + pub(crate) fn native(&self, data: bool) -> [u64; 2] { + let domain = if data { + policy::Domain::Data + } else { + policy::Domain::Instruction + }; + [0, 1 << 55].map(|pointer| self.get(domain, pointer, false).extension_mask()) + } + + /// Whether `domain` signing selects TnSZ by bit 63 rather than bit 55 + /// (neither range ignores the top byte). + pub(crate) fn native_signing_select_bit63(&self, data: bool) -> bool { + let domain = if data { + policy::Domain::Data + } else { + policy::Domain::Instruction + }; + self.get(domain, 0, true).select_shift == 63 + } + + fn get(&self, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { + let index = usize::from(domain == policy::Domain::Data) << 3 + | usize::from(signing) << 2 + | ((pointer >> 54) & 2) as usize + | (pointer >> 63) as usize; + self.table[index] + } +} + +/// The PAC field of `pointer` for an `operation` in `domain` under TCR_EL1 +/// `tcr`. Arm `AddPAC` selects the range whose TnSZ bounds the field by bit +/// 55 when either range ignores the domain's top byte and by bit 63 +/// otherwise; `Auth` and `Strip` always select by bit 55 +/// (`CalculateBottomPACBit(ptr<55>)`), since a signed pointer's bit 63 is PAC +/// whenever the top byte is not ignored. Only bits 55 and 63 of `pointer` +/// matter ([`Layouts`]). +fn regime_layout(tcr: u64, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { + // EffectiveTBI selects TBI0/TBI1 by bit 55; TBIDn exempts instructions. + let ignores_top_byte = |upper: bool| { + let (tbi, tbid) = if upper { (38, 52) } else { (37, 51) }; + tcr & (1 << tbi) != 0 && !(domain == policy::Domain::Instruction && tcr & (1 << tbid) != 0) + }; + let tbi = ignores_top_byte(pointer & (1 << 55) != 0); + let select = if signing && !ignores_top_byte(false) && !ignores_top_byte(true) { + 63 + } else { + 55 + }; + let tnsz = if pointer & (1 << select) != 0 { + (tcr >> 16) & 63 + } else { + tcr & 63 + }; + // CalculateBottomPACBit: an out-of-range TnSZ is CONSTRAINED + // UNPREDICTABLE, FORCE or NONE; FORCE to 16..=39 (no FEAT_TTST or + // 52-bit VAs), the range the system engine's walker admits. + let tnsz = tnsz.clamp(MIN_TNSZ, MAX_TNSZ); + policy::Layout::new(64 - tnsz as u32, if tbi { 55 } else { 63 }, select) +} +impl fmt::Debug for Context { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Context") + .field("address_space", &self.address_space) + .field("profile", &self.profile_id()) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct AuthResult { + pub pointer: u64, + pub authenticated: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum AuthenticationError { + KeyUnavailable { key: Key }, + GenericKeyUnavailable, + Failure { code: u8 }, +} + +impl fmt::Display for AuthenticationError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::KeyUnavailable { key } => write!( + formatter, + "pointer authentication key {key:?} is unavailable" + ), + Self::GenericKeyUnavailable => { + formatter.write_str("generic pointer authentication key is unavailable") + } + Self::Failure { code } => write!( + formatter, + "architectural pointer authentication failure {code}" + ), + } + } +} + +impl core::error::Error for AuthenticationError {} + +impl Context { + pub fn new(address_space: u64, keys: Keys) -> Self { + Self::new_with_version(address_space, keys, Version::Classic) + } + pub fn new_with_version(address_space: u64, keys: Keys, version: Version) -> Self { + Self { + address_space, + keys, + version, + regime: None, + keyed: false, + layouts: None, + } + } + + /// Lay PAC fields out for the EL1&0 regime this TCR_EL1 describes, as + /// the system-mode engine requires, instead of the fixed process profile. + pub fn with_translation_regime(mut self, tcr: u64) -> Self { + self.regime = Some(tcr); + self.layouts = None; + self + } + + /// [`Self::with_translation_regime`] with that regime's layouts worked + /// out ahead, for a context that serves many results. + pub fn with_layouts(mut self, layouts: Layouts) -> Self { + self.regime = Some(layouts.tcr); + self.layouts = Some(layouts); + self + } + + /// Take [`keyed`]'s cipher in place of QARMA5. The ID registers still + /// report QARMA5, which only a guest recomputing a PAC from its own keys + /// could find untrue. + pub fn with_implementation_defined_cipher(mut self) -> Self { + self.keyed = true; + self + } + + /// The PAC of `data` and `modifier` under `key`. + #[inline] + fn cipher(&self, data: u64, modifier: u64, key: &[u64; 2]) -> u64 { + match self.keyed { + true => keyed::compute(data, modifier, key), + false => qarma5(data, modifier, key), + } + } + + /// The PAC field of `pointer` for an `operation` in `domain` + /// ([`regime_layout`]). + #[inline] + fn layout(&self, domain: policy::Domain, pointer: u64, signing: bool) -> policy::Layout { + match &self.layouts { + Some(layouts) => layouts.get(domain, pointer, signing), + None => regime_layout(self.regime.unwrap_or(PROCESS_TCR), domain, pointer, signing), + } + } + pub fn version(&self) -> Version { + self.version + } + pub fn address_space(&self) -> u64 { + self.address_space + } + pub fn profile_id(&self) -> &'static str { + match self.version { + Version::Enhanced => ENHANCED_PROFILE_ID, + Version::Faulting => FAULTING_PROFILE_ID, + Version::FaultingCombined => COMBINED_PROFILE_ID, + Version::Classic if self.keys.generic.is_some() => GENERIC_PROFILE_ID, + Version::Classic if self.keys.words.iter().all(Option::is_some) => FULL_PROFILE_ID, + Version::Classic => PROFILE_ID, + } + } + pub fn has_key(&self, key: Key) -> bool { + self.keys.words[key.index()].is_some() + } + + pub(crate) fn set_key_words(&mut self, index: usize, words: Option<[u64; 2]>) { + if index < 4 { + self.keys.words[index] = words; + } else if index == 4 { + self.keys.generic = words; + } + } + + /// InsertPAC with the process's VA47 controls (`PROCESS_TCR`): instruction + /// TBI off, data TBI on in the lower range. + /// Data keeps its tag in both QARMA input and output; it is not ignored by + /// authentication. Null is signed. Classic invalid extension corrupts + /// PAC bit62 (instruction) or54 (data), following June2026 Arm ASL, rather + /// than the older Unicorn invalid-extension behavior. Enhanced profiles XOR the PAC field. + pub fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { + Ok(self.sign_with(key, self.keys.get(key)?, pointer, modifier)) + } + + /// [`Self::sign`] with `key`'s `words` in hand, for the hot path of a + /// service that has already looked them up ([`Self::words`]). + #[inline(always)] + pub(crate) fn sign_with(&self, key: Key, words: &[u64; 2], pointer: u64, modifier: u64) -> u64 { + let layout = self.layout(key_domain(key), pointer, true); + let input = policy::signing_input(layout, pointer); + policy::sign( + self.version, + layout, + pointer, + self.cipher(input, modifier, words), + ) + } + + /// The AES schedule native code computes PACs of the key at tag word + /// `index` with (`x86_64::pointer::cipher`): IA, IB, DA, DB, then the + /// generic key. `None` when the context lacks the key or its cipher is + /// not the AES rounds native code runs ([`keyed::native`]). + pub(crate) fn native_schedule(&self, index: usize) -> Option<[[u64; 2]; keyed::SCHEDULE]> { + if !self.keyed || !keyed::native() { + return None; + } + let words = match index { + 4 => self.keys.generic.as_ref(), + index => self.keys.words.get(index)?.as_ref(), + }?; + Some(keyed::schedule(words)) + } + + /// The words of `key`, when the context has it. + #[inline] + pub(crate) fn words(&self, key: Key) -> Option<&[u64; 2]> { + self.keys.words[key.index()].as_ref() + } + + /// Standalone AUT policy; combined loads/transfers use authenticate_operation. + pub fn authenticate( + &self, + key: Key, + pointer: u64, + modifier: u64, + ) -> Result { + self.authenticate_operation(key, pointer, modifier, false) + } + + pub fn authenticate_operation( + &self, + key: Key, + pointer: u64, + modifier: u64, + combined: bool, + ) -> Result { + let result = self + .authenticate_with(key, self.keys.get(key)?, pointer, modifier, combined) + .map_err(|failure| AuthenticationError::Failure { code: failure.code })?; + Ok(AuthResult { + pointer: result.pointer, + authenticated: result.authenticated, + }) + } + + /// [`Self::authenticate_operation`] with `key`'s `words` in hand + /// ([`Self::sign_with`]). + #[inline(always)] + pub(crate) fn authenticate_with( + &self, + key: Key, + words: &[u64; 2], + pointer: u64, + modifier: u64, + combined: bool, + ) -> Result { + let domain = key_domain(key); + let layout = self.layout(domain, pointer, false); + let input = policy::authentication_input(layout, pointer); + policy::authenticate( + self.version, + domain, + layout, + if key.is_b() { + policy::Side::B + } else { + policy::Side::A + }, + combined, + pointer, + self.cipher(input, modifier, words), + ) + } + + pub fn has_generic_key(&self) -> bool { + self.keys.generic.is_some() + } + + /// PACGA has no address-domain canonicalization; all64 data/modifier bits enter QARMA. + pub fn generic_code(&self, data: u64, modifier: u64) -> Result { + let words = self + .keys + .generic + .as_ref() + .ok_or(AuthenticationError::GenericKeyUnavailable)?; + Ok(self.cipher(data, modifier, words) & GENERIC_CODE_MASK) + } + + /// Architectural XPAC: keyless restoration, never an authentication check. + /// Ia/Ib select instruction layout, Da/Db tagged-data layout; this succeeds + /// even when that domain's cryptographic key was not provided. + #[inline] + pub fn strip(&self, key: Key, pointer: u64) -> u64 { + policy::authentication_input(self.layout(key_domain(key), pointer, false), pointer) + } + + /// The bits kept by XPAC in the lower and upper address ranges. + /// Strip selects both its TnSZ and effective TBI by pointer bit 55. + /// These masks contain no key material and do not depend on key enables. + pub(crate) fn stripping_masks(&self, data: bool) -> [u64; 2] { + let domain = if data { + policy::Domain::Data + } else { + policy::Domain::Instruction + }; + [0, 1 << 55].map(|pointer| !self.layout(domain, pointer, false).extension_mask()) + } + + /// Sign with the IB key (the original single-key profile). + pub fn sign_ib(&self, pointer: u64, modifier: u64) -> Result { + self.sign(Key::Ib, pointer, modifier) + } + pub fn authenticate_ib( + &self, + pointer: u64, + modifier: u64, + ) -> Result { + self.authenticate(Key::Ib, pointer, modifier) + } +} + +/// The EL0 regime of a macOS process: T0SZ = T1SZ = 17 (VA47), TBI0 with +/// TBID0, so lower-range data pointers keep their top byte and instruction +/// pointers do not, and TBI1 clear, so upper-range pointers keep no top +/// byte. An M1 Pro strips XPACD 0x00ff7fff12345678 to 0xffffffff12345678 +/// and 0x5a3c7fff12345678 to 0x5a007fff12345678 (`cargo xtask +/// cpu-reference`). +const PROCESS_TCR: u64 = 17 | 17 << 16 | 1 << 37 | 1 << 51; + +/// TnSZ limits of the PAC field without FEAT_TTST or 52-bit VAs. +const MIN_TNSZ: u64 = 16; +const MAX_TNSZ: u64 = 39; + +pub(crate) mod keyed; +mod qarma; +use qarma::compute as qarma5; + +pub(crate) mod features; +pub use features::UnsupportedInstructionProfile; + +pub(crate) mod lr_instruction; + +mod two_modifier; + +pub(crate) mod conditional; + +impl stela_contracts::pauth::TranslationSigner for Context { + fn with_translation_regime(self, tcr_el1: u64) -> Self { + Self::with_translation_regime(self, tcr_el1) + } +} + +impl stela_contracts::pauth::Signer for Context { + type Error = AuthenticationError; + fn address_space(&self) -> u64 { + self.address_space() + } + fn profile_id(&self) -> &'static str { + self.profile_id() + } + fn sign(&self, key: Key, pointer: u64, modifier: u64) -> Result { + self.sign(key, pointer, modifier) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-engine/src/translations/writer.rs b/crates/stela-engine/src/translations/writer.rs index 03eab828f1..550e599edf 100644 --- a/crates/stela-engine/src/translations/writer.rs +++ b/crates/stela-engine/src/translations/writer.rs @@ -728,6 +728,9 @@ impl<'a> Writer<'a> { /// every segment was read, after its first segment came due and while /// translation does not press, enough segments or lists. fn full_merge_due(&self) -> bool { + if self.partial { + return false; + } let segments = self.count(SEGMENT_BLOB); self.refill_due() || segments >= MERGE_FULL diff --git a/crates/stela-engine/tests/opt2_jit_suite.rs b/crates/stela-engine/tests/opt2_jit_suite.rs new file mode 100644 index 0000000000..2ea3a5be3b --- /dev/null +++ b/crates/stela-engine/tests/opt2_jit_suite.rs @@ -0,0 +1,550 @@ +//! Windows-compatible (and POSIX-compatible) JIT execution verification +//! for Opt 2 (bounded native WFE monitor-spin), Opt 3 (per-key PAC invalidation), +//! Opt 4 (inline non-canonical FEAT_PAuth2 signing across 10,000 differential samples), +//! and Opt 5 (32-entry table_switch runtime loop). +#![cfg(target_arch = "x86_64")] + +use core::ffi::c_void; +use core::mem::offset_of; +use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; +use stela_compiler::{ + Anchor, GuestAddress, GuestState, Place, + block::{ExitKind, PointerAuthenticationKey, PointerAuthenticationOperation as Operation}, + x86_64::{ + block_entry, + chain::ChainControl, + pinned, + pointer::{self, Completion, Form, GENERIC_KEY, TAG_WORDS, cipher::Cipher, cipher::Range}, + register_read::{ + Cell, Count, CountState, EventSpin, EventStream, EventWaitPlaces, Written, + event_wait_thunk, key_write_thunk, + }, + table_switch::{self, ENTRIES, Entry, Places as SwitchPlaces, Sets, Table, switch_thunk}, + }, +}; +use stela_contracts::pauth::Key; +use stela_engine::pauth::{Context, Keys, Version}; + +#[repr(C)] +#[derive(Debug, PartialEq, Eq)] +struct Exit { + pc: u64, + kind: u64, +} + +struct ExecPage { + ptr: *mut c_void, + #[cfg_attr(target_os = "windows", allow(dead_code))] + bytes: usize, +} + +impl ExecPage { + fn new(thunk_code: &[u8]) -> Self { + let code = pinned::entered(thunk_code); + let bytes = code.len().next_multiple_of(4096); + #[cfg(target_os = "windows")] + unsafe { + unsafe extern "system" { + fn VirtualAlloc(a: *const c_void, b: usize, t: u32, p: u32) -> *mut c_void; + fn VirtualProtect(a: *const c_void, b: usize, p: u32, o: *mut u32) -> i32; + } + let ptr = VirtualAlloc(core::ptr::null(), bytes, 0x1000 | 0x2000, 0x04); + assert!(!ptr.is_null()); + core::ptr::copy_nonoverlapping(code.as_ptr(), ptr.cast(), code.len()); + let mut old = 0u32; + assert_ne!(VirtualProtect(ptr, bytes, 0x20, &mut old), 0); + Self { ptr, bytes } + } + #[cfg(any(target_os = "linux", target_os = "macos"))] + unsafe { + unsafe extern "C" { + fn mmap(a: *mut c_void, b: usize, p: i32, f: i32, fd: i32, o: i64) -> *mut c_void; + fn mprotect(a: *mut c_void, b: usize, p: i32) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANON: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANON: i32 = 0x20; + let ptr = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANON, -1, 0); + assert_ne!(ptr as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), ptr.cast(), code.len()); + assert_eq!(mprotect(ptr, bytes, 5), 0); + Self { ptr, bytes } + } + } + + fn run(&self, state: &mut GuestState) -> Exit { + let ret = unsafe { block_entry::enter(self.ptr.cast(), state, 0, 0) }; + Exit { + pc: ret as u64, + kind: (ret >> 64) as u64, + } + } +} + +impl Drop for ExecPage { + fn drop(&mut self) { + #[cfg(target_os = "windows")] + unsafe { + unsafe extern "system" { + fn VirtualFree(a: *mut c_void, b: usize, t: u32) -> i32; + } + assert_ne!(VirtualFree(self.ptr, 0, 0x8000), 0); + } + #[cfg(any(target_os = "linux", target_os = "macos"))] + unsafe { + unsafe extern "C" { + fn munmap(a: *mut c_void, b: usize) -> i32; + } + let _ = self.bytes; + assert_eq!(munmap(self.ptr, self.bytes), 0); + } + } +} + +#[test] +fn opt2_bounded_wfe_monitor_spin_executes_natively_and_caps_at_16() { + #[repr(C)] + #[derive(Default)] + struct Waits { + events: Cell, + waits: Cell, + monitor: u64, + lines_until: u64, + spin: EventSpin, + stream: EventStream, + } + const PC: GuestAddress = GuestAddress(0x4000); + let place = |offset: usize| Place::new(Anchor::Mirrors, offset); + let places = EventWaitPlaces { + events: place(offset_of!(Waits, events)), + waits: place(offset_of!(Waits, waits)), + monitor: place(offset_of!(Waits, monitor)), + control: Place::new(Anchor::Control, 0), + lines_until: place(offset_of!(Waits, lines_until)), + count: Place::new(Anchor::Count, 0), + spin: place(offset_of!(Waits, spin)), + stream: place(offset_of!(Waits, stream)), + }; + let exec = ExecPage::new(&event_wait_thunk(PC, places).code); + let event = Box::new(AtomicU8::new(0)); + let mut waits = Box::new(Waits::default()); + waits.events = Cell { + readable: 1, + value: &*event as *const AtomicU8 as u64, + }; + waits.waits.readable = 1; + waits.lines_until = 101; + let mut control = Box::new(ChainControl::default()); + let published = Box::new(CountState::default()); + published.offset.store(100, Relaxed); + published.ceiling.store(u64::MAX, Relaxed); + let mut count = Box::new(Count { + state: &*published as *const CountState as u64, + ..Count::default() + }); + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &mut *waits as *mut Waits as u64; + state.anchors[Anchor::Control] = &mut *control as *mut ChainControl as u64; + state.anchors[Anchor::Count] = &mut *count as *mut Count as u64; + + let next = Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + }; + let miss = Exit { + pc: PC.0, + kind: ExitKind::System as u64, + }; + + // Engine-held monitor always exits immediately even if exclusive_bytes != 0. + waits.monitor = 1; + state.exclusive_bytes = 8; + assert_eq!(exec.run(&mut state), miss); + assert_eq!(waits.spin.held, 1); + assert_eq!(waits.spin.held_completed, 0); + + // Clear engine monitor; native monitor-spin completes up to 16 times, then exits. + waits.monitor = 0; + for step in 0..16 { + assert_eq!(exec.run(&mut state), next, "step {step}"); + assert_eq!(state.exclusive_bytes, 8); + } + assert_eq!(waits.spin.held_streak, 16); + assert_eq!(waits.spin.held_completed, 16); + assert_eq!(waits.spin.held, 1); + assert_eq!(exec.run(&mut state), miss); + assert_eq!(waits.spin.held, 2); + + // If a deadline is due (count >= lines_until), exits before spinning. + waits.spin = EventSpin::default(); + waits.lines_until = 100; + assert_eq!(exec.run(&mut state), miss); + assert_eq!(waits.spin, EventSpin::default()); +} + +#[test] +fn opt3_key_write_thunk_only_clears_target_key_and_marks_dirty() { + #[repr(C)] + struct PtrArea { + tags: [u64; TAG_WORDS], + dirty: u64, + } + const PC: GuestAddress = GuestAddress(0x5000); + let mut storage = Box::new(0x1111_2222_3333_4444_u64); + let cell = Box::new(Cell { + readable: 1, + value: &mut *storage as *mut u64 as u64, + }); + let mut ptr = Box::new(PtrArea { + tags: [0x11, 0x22, 0x33, 0x44, 0x55], + dirty: 0, + }); + let tag = Place::new(Anchor::Pointer, offset_of!(PtrArea, tags) + 8); + let dirty = Place::new(Anchor::Pointer, offset_of!(PtrArea, dirty)); + let exec = ExecPage::new( + &key_write_thunk(PC, 3, Place::new(Anchor::Mirrors, 0), tag, dirty, 1).code, + ); + + let mut state = GuestState::default(); + state.anchors[Anchor::Mirrors] = &*cell as *const Cell as u64; + state.anchors[Anchor::Pointer] = &mut *ptr as *mut PtrArea as u64; + + // Unchanged value keeps all tags and dirty == 0. + state.x[3] = 0x1111_2222_3333_4444; + assert_eq!( + exec.run(&mut state), + Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + } + ); + assert_eq!(ptr.tags, [0x11, 0x22, 0x33, 0x44, 0x55]); + assert_eq!(ptr.dirty, 0); + + // Changed value zeroes ONLY tags[1] and sets bit 1 in dirty. + state.x[3] = 0xaaaa_bbbb_cccc_dddd; + assert_eq!( + exec.run(&mut state), + Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + } + ); + assert_eq!(*storage, 0xaaaa_bbbb_cccc_dddd); + assert_eq!(ptr.tags, [0x11, 0, 0x33, 0x44, 0x55]); + assert_eq!(ptr.dirty, 1 << 1); +} + +#[test] +fn opt4_differential_10000_canonical_and_noncanonical_pointers() { + if !std::arch::is_x86_feature_detected!("aes") { + return; + } + + const PI_CONSTANTS: [u64; 12] = [ + 0x1319_8a2e_0370_7344, + 0xa409_3822_299f_31d0, + 0x082e_fa98_ec4e_6c89, + 0x4528_21e6_38d0_1377, + 0xbe54_66cf_34e9_0c6c, + 0xc0ac_29b7_c97c_50dd, + 0x3f84_d5b5_b547_0917, + 0x9216_d5d9_8979_fb1b, + 0xd131_0ba6_98df_b5ac, + 0x2ffd_72db_d01a_dfb7, + 0xb8e1_afed_6a26_7e96, + 0xba7c_9045_f12c_7f99, + ]; + fn aes_schedule(key: [u64; 2]) -> [[u64; 2]; 7] { + let mut s = [key; 7]; + for (r, w) in s[1..].iter_mut().enumerate() { + w[0] ^= PI_CONSTANTS[2 * r]; + w[1] ^= PI_CONSTANTS[2 * r + 1]; + } + s + } + fn tcr_range(tcr: u64, data: bool, upper: bool, classic: bool) -> Range { + let ignores = |u: bool| { + let (tbi, tbid) = if u { (38, 52) } else { (37, 51) }; + tcr & (1 << tbi) != 0 && !(!data && tcr & (1 << tbid) != 0) + }; + let tbi = ignores(upper); + let tnsz = ((if upper { tcr >> 16 } else { tcr }) & 63).clamp(16, 39); + let addr_bits = 64 - tnsz as u32; + let top_shift = if tbi { 55 } else { 63 }; + let below_top = if top_shift == 63 { + u64::MAX + } else { + (1u64 << (top_shift + 1)) - 1 + }; + let ext = below_top & !((1u64 << addr_bits) - 1); + let select_bit63 = !ignores(false) && !ignores(true); + Range::new(ext, upper, classic, select_bit63) + } + + #[repr(C)] + struct PointerBlock { + tags: [u64; TAG_WORDS], + cipher: Cipher, + ctx_ptr: u64, + version_idx: u64, + tcr: u64, + } + + struct CtxEntry { + ctx: Context, + } + + extern "sysv64" fn fallback_service( + pointer_anchor: u64, + request: u32, + pointer: u64, + modifier: u64, + ) -> Completion { + let block = unsafe { &*(pointer_anchor as *const PointerBlock) }; + let contexts = unsafe { &*(block.ctx_ptr as *const [CtxEntry; 24]) }; + let ctx = &contexts[block.version_idx as usize].ctx; + let (k, auth, combined) = pointer::requested(request); + let pauth_key = match k { + PointerAuthenticationKey::Ia => Key::Ia, + PointerAuthenticationKey::Ib => Key::Ib, + PointerAuthenticationKey::Da => Key::Da, + PointerAuthenticationKey::Db => Key::Db, + }; + if !auth { + let value = ctx.sign(pauth_key, pointer, modifier).unwrap(); + Completion { + completed: 1, + value, + } + } else { + match ctx.authenticate_operation(pauth_key, pointer, modifier, combined) { + Ok(r) if r.authenticated => Completion { + completed: 1, + value: r.pointer, + }, + _ => Completion::default(), + } + } + } + + const PC: GuestAddress = GuestAddress(0x6000); + const KEY_WORDS: [[u64; 2]; 5] = [ + [0x1122_3344_5566_7788, 0x99aa_bbcc_ddee_ff00], + [0x2233_4455_6677_8899, 0xaabb_ccdd_eeff_0011], + [0x3344_5566_7788_99aa, 0xbbcc_ddee_ff00_1122], + [0x4455_6677_8899_aabb, 0xccdd_eeff_0011_2233], + [0x5566_7788_99aa_bbcc, 0xddee_ff00_1122_3344], + ]; + const VERSIONS: [Version; 4] = [ + Version::Classic, + Version::Enhanced, + Version::Faulting, + Version::FaultingCombined, + ]; + const TCRS: [u64; 6] = [ + 25 | 25 << 16 | 1 << 37, + 17 | 25 << 16 | 1 << 37 | 1 << 51, + 17 | 17 << 16 | 1 << 37 | 1 << 38, + 25 | 25 << 16, + 16 | 39 << 16 | 1 << 38 | 1 << 52, + 39 | 16 << 16 | 1 << 38, + ]; + let keys = [ + PointerAuthenticationKey::Ia, + PointerAuthenticationKey::Ib, + PointerAuthenticationKey::Da, + PointerAuthenticationKey::Db, + ]; + let key_map = [Key::Ia, Key::Ib, Key::Da, Key::Db]; + + let contexts: Vec = VERSIONS + .iter() + .flat_map(|&v| { + TCRS.iter().map(move |&tcr| CtxEntry { + ctx: Context::new_with_version( + 0, + Keys::from_words(KEY_WORDS[0], KEY_WORDS[1], KEY_WORDS[2], KEY_WORDS[3]) + .with_generic_words(KEY_WORDS[4]), + v, + ) + .with_translation_regime(tcr) + .with_implementation_defined_cipher(), + }) + }) + .collect(); + + let tags_place = Place::new(Anchor::Pointer, offset_of!(PointerBlock, tags)); + let cipher_place = Place::new(Anchor::Pointer, offset_of!(PointerBlock, cipher)); + let execs: Vec = keys + .iter() + .map(|&key| { + let op = Operation::Sign { + key, + destination: 3, + modifier: stela_compiler::block::PointerAuthenticationModifier::Register(5), + }; + let form = Form::of(op).unwrap(); + ExecPage::new( + &pointer::thunk( + form, + PC, + tags_place, + fallback_service as *const () as usize as u64, + Some(cipher_place), + ) + .code, + ) + }) + .collect(); + + let mut block = Box::new(PointerBlock { + tags: [ + pointer::tag(1, 0, 0), + pointer::tag(1, 1, 0), + pointer::tag(1, 2, 0), + pointer::tag(1, 3, 0), + pointer::tag(1, GENERIC_KEY, 0), + ], + cipher: Cipher { + schedules: core::array::from_fn(|i| aes_schedule(KEY_WORDS[i])), + ranges: [[Range::default(); 2]; 2], + }, + ctx_ptr: contexts.as_ptr() as u64, + version_idx: 0, + tcr: 0, + }); + + let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; + let mut next_u64 = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + + const SAMPLES: usize = 10_000; + for sample in 0..SAMPLES { + let combo = sample % contexts.len(); + let v_idx = combo / TCRS.len(); + let t_idx = combo % TCRS.len(); + let version = VERSIONS[v_idx]; + let tcr = TCRS[t_idx]; + let classic = version == Version::Classic; + block.version_idx = combo as u64; + block.tcr = tcr; + block.cipher.ranges = [false, true].map(|data| { + [false, true].map(|upper| tcr_range(tcr, data, upper, classic)) + }); + + let k_idx = (sample / contexts.len()) % keys.len(); + let raw = next_u64(); + let pointer = match sample % 4 { + 0 => raw & 0x0000_7fff_ffff_ffff, + 1 => raw | 0xffff_ff80_0000_0000, + 2 => (raw & !(1u64 << 55)) | ((sample as u64 & 4) << 53), + _ => raw, + }; + let modifier = next_u64(); + + let mut state = GuestState::default(); + state.anchors[Anchor::Pointer] = &mut *block as *mut PointerBlock as u64; + state.x[3] = pointer; + state.x[5] = modifier; + assert_eq!( + execs[k_idx].run(&mut state), + Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + } + ); + let expected = contexts[combo].ctx.sign(key_map[k_idx], pointer, modifier).unwrap(); + assert_eq!( + state.x[3], expected, + "sample={sample} version={version:?} tcr={tcr:#x} key={:?} ptr={pointer:#x}", + keys[k_idx] + ); + } +} + +#[test] +fn opt5_table_switch_finds_all_32_entry_slots() { + assert_eq!(ENTRIES, 32); + #[repr(C)] + struct World { + cell: Cell, + register: u64, + table: Table, + contexts: [u64; 2], + salts: [u32; 2], + contexts_generation: u64, + translating: u32, + pending: u8, + } + const PC: GuestAddress = GuestAddress(0x7000); + const RT: u8 = 3; + const UPPER: u64 = 0x77; + let at = |offset: usize| Place::new(Anchor::Mirrors, offset); + let places = SwitchPlaces { + table: at(offset_of!(World, table)), + contexts: at(offset_of!(World, contexts)), + salts: at(offset_of!(World, salts)), + contexts_generation: at(offset_of!(World, contexts_generation)), + closes: vec![], + cr3: None, + isolate: false, + }; + let all = Written { + keep: u64::MAX, + set: 0, + }; + let exec = ExecPage::new(&switch_thunk(PC, RT, at(offset_of!(World, cell)), all, &places).code); + + for slot in 0..ENTRIES as u64 { + let mut world = Box::new(World { + cell: Cell::default(), + register: 0x1000, + table: Table::default(), + contexts: [0x11, UPPER], + salts: [0x21, 0x22], + contexts_generation: 9, + translating: 0x100, + pending: 0, + }); + world.cell = Cell { + readable: 1, + value: &world.register as *const u64 as u64, + }; + world.table.translating = &world.translating as *const u32 as u64; + world.table.pending = &world.pending as *const u8 as u64; + for other in 0..slot { + world.table.keep(Entry { + value: 0x9000 + other, + upper: UPPER, + ..Entry::default() + }); + } + world.table.keep(Entry { + value: 0xa000, + upper: UPPER, + lower: 0x99 + slot, + salt: 0x55, + translating: 0x200, + ..Entry::default() + }); + let mut state = GuestState::default(); + state.x[RT as usize] = 0xa000; + state.anchors[Anchor::Mirrors] = &mut *world as *mut World as u64; + assert_eq!( + exec.run(&mut state), + Exit { + pc: PC.0 + 4, + kind: ExitKind::Fallthrough as u64, + }, + "slot {slot}" + ); + assert_eq!(world.contexts[0], 0x99 + slot, "slot {slot}"); + } + let _ = (Sets::default(), table_switch::ENTRIES); +} diff --git a/crates/stela-runtime/src/translation_bulk.rs b/crates/stela-runtime/src/translation_bulk.rs index 4ef74c3eee..2ec91adb17 100644 --- a/crates/stela-runtime/src/translation_bulk.rs +++ b/crates/stela-runtime/src/translation_bulk.rs @@ -403,13 +403,21 @@ impl FileRead { reads: Vec::new(), failed: false, }; + // Keep each NVMe read <= 64 KiB (within NVMe BOUNCE_BYTES = 128 KiB) so + // 512 KiB merge reads never fail with bounce-buffer overflow. + let max_chunk = (64 * 1024u64 / block).max(1) * block; for (lba, length, from) in ranges { - let command = Command::Read { - lba, - bytes: length as usize, - }; - let tag = device.start_more(command).ok()?; - read.reads.push((tag, from)); + let mut off = 0u64; + while off < length { + let chunk = (length - off).min(max_chunk); + let command = Command::Read { + lba: lba + off / block, + bytes: chunk as usize, + }; + let tag = device.start_more(command).ok()?; + read.reads.push((tag, from + off as usize)); + off += chunk; + } } Some(read) } diff --git a/xtask/src/hle_signatures.rs b/xtask/src/hle_signatures.rs index a7f3be5590..757f5fc734 100644 --- a/xtask/src/hle_signatures.rs +++ b/xtask/src/hle_signatures.rs @@ -1,449 +1,455 @@ -//! `cargo xtask hle-signatures`: the signatures of the guest functions HLE -//! replaces, from a macOS build's dyld shared cache (phase 0's reader, -//! `symbolize::code`). For each routine it looks up the symbols that may -//! name it, takes each function from its address to the next function -//! start (less the padding after its last word), its first `ret` as its -//! exit, and runs the engine's own `Signature::of`, so a function the -//! engine would refuse is refused here with the same reason. -//! -//! It prints one report row per symbol found, `symbol image address length -//! exit verdict`. With `--out` it writes a `signatures.rs` table of the -//! eligible ones: routine, length, exit and hashes only, never bytes, one -//! `Signature::generated` line each under a comment naming the symbol, -//! image and build. With `--extract` it writes each function's bytes -//! (`.bin`) and description (`.json`), for the opt-in -//! real-bytes oracle (`tests/hle_real.rs`): Apple's bytes, which never go -//! in the repository, so `--extract` refuses a directory inside it. -use anyhow::{Context, Result, bail, ensure}; -use clap::Args; -use std::fmt::Write as _; -use std::path::{Path, PathBuf}; -use stela_engine::hle::{Id, Ineligible, Signature}; - -use crate::symbolize::code::{self, Function}; - -/// The longest function a signature covers: one fetch page. -const LIMIT: usize = 4096; -/// `ret`. -const RET: u32 = 0xd65f_03c0; -/// The words that pad a function to the next one's alignment, which it -/// never runs: UDF #0 and NOP. -const PADDING: [u32; 2] = [0, 0xd503_201f]; - -/// The symbols that may name each routine, to be confirmed by the report -/// on each macOS build. -/// -/// Mach-O prepends a leading underscore to C symbols, so Libplatform's -/// `_platform_*` symbols appear in the shared cache as `__platform_*`. -pub const CANDIDATES: [(Id, &[&str]); 5] = [ - ( - Id::Memmove, - &[ - "__platform_memmove", - "__platform_memcpy", - "_platform_memmove", - "_memmove", - "_memcpy", - "_platform_memcpy", - ], - ), - ( - Id::Bzero, - &["__platform_bzero", "_platform_bzero", "_bzero", "___bzero"], - ), - ( - Id::Memset, - &["__platform_memset", "_platform_memset", "_memset"], - ), - ( - Id::Memcmp, - &[ - "__platform_memcmp", - "__platform_bcmp", - "_platform_memcmp", - "_platform_bcmp", - "_memcmp", - "_bcmp", - ], - ), - ( - Id::Strlen, - &["__platform_strlen", "_platform_strlen", "_strlen"], - ), -]; - -#[derive(Args)] -pub struct HleSignatures { - /// The guest's dyld shared cache: its main file - /// (`dyld_shared_cache_arm64e`, its subcaches beside it) or the - /// directory holding it. - #[arg(long)] - cache: PathBuf, - /// Write the eligible functions' signatures here as a `signatures.rs` - /// table (`crates/stela-engine/src/hle/signatures.rs` once the oracle - /// passes; a private path before). - #[arg(long)] - out: Option, - /// Write each function's bytes and description into this directory, - /// outside the repository. - #[arg(long)] - extract: Option, - /// The macOS build the cache is from, such as `26B123`, for the table's - /// comments. - #[arg(long, default_value = "unknown-build")] - build: String, -} - -impl HleSignatures { - pub fn run(&self) -> Result<()> { - if let Some(extract) = &self.extract { - refuse_inside_repository(extract)?; - } - let names: Vec<&str> = CANDIDATES - .iter() - .flat_map(|(_, names)| names.iter().copied()) - .collect(); - let functions = code::cache_functions(&self.cache, &names, LIMIT)?; - ensure!( - !functions.is_empty(), - "{} names none of {names:?}", - self.cache.display() - ); - let mut rows = Vec::new(); - for function in &functions { - let Some(id) = routine(&function.symbol) else { - continue; - }; - rows.push(Row::of(id, function)); - } - println!("symbol image address length exit verdict"); - for row in &rows { - println!("{}", row.report()); - } - let eligible: Vec<&Row> = rows.iter().filter(|row| row.signature.is_some()).collect(); - println!( - "{} of {} functions eligible; routines: {}", - eligible.len(), - rows.len(), - CANDIDATES - .iter() - .map(|(id, _)| format!( - "{}={}", - id.name(), - eligible.iter().filter(|row| row.id == *id).count() - )) - .collect::>() - .join(" ") - ); - if let Some(out) = &self.out { - std::fs::write(out, table(&eligible, &self.build)) - .with_context(|| format!("write {}", out.display()))?; - println!("wrote {} signatures to {}", eligible.len(), out.display()); - } - if let Some(extract) = &self.extract { - std::fs::create_dir_all(extract)?; - for (row, function) in rows - .iter() - .zip(functions.iter().filter(|f| routine(&f.symbol).is_some())) - { - let stem = format!("{}-{:x}", row.symbol.trim_start_matches('_'), row.address); - std::fs::write( - extract.join(format!("{stem}.bin")), - &function.bytes[..row.length], - )?; - let description = serde_json::json!({ - "id": row.id.name(), - "symbol": row.symbol, - "image": row.image, - "address": row.address, - "length": row.length, - "exit": row.exit, - "verdict": row.verdict, - }); - std::fs::write( - extract.join(format!("{stem}.json")), - serde_json::to_string_pretty(&description)?, - )?; - } - println!( - "extracted {} functions to {}", - rows.len(), - extract.display() - ); - } - Ok(()) - } -} - -/// The routine a symbol may name. -fn routine(symbol: &str) -> Option { - CANDIDATES - .iter() - .find(|(_, names)| names.contains(&symbol)) - .map(|(id, _)| *id) -} - -/// Refuse to write Apple's bytes into the repository. -fn refuse_inside_repository(path: &Path) -> Result<()> { - let root = crate::tools::root(); - let absolute = std::path::absolute(path)?; - if absolute.starts_with(root) { - bail!( - "--extract {} is inside the repository ({}): Apple's bytes stay outside it", - path.display(), - root.display() - ); - } - Ok(()) -} - -/// One function's report row and, if eligible, its signature. -#[derive(Debug, Clone, PartialEq, Eq)] -struct Row { - id: Id, - symbol: String, - image: String, - address: u64, - /// Its bytes, its trailing padding left out. - length: usize, - exit: Option, - verdict: String, - signature: Option, -} - -impl Row { - fn of(id: Id, function: &Function) -> Self { - let bytes = trimmed(&function.bytes); - let exit = first_ret(bytes); - let page_offset = (function.address & 0xfff) as usize; - let (signature, verdict) = if page_offset + bytes.len() > LIMIT { - (None, String::from("crosses-page")) - } else { - match exit.map(|exit| Signature::of(id, bytes, exit)) { - None => (None, String::from("exit: no ret")), - Some(Ok(signature)) => (Some(signature), String::from("eligible")), - Some(Err(why)) => (None, refusal(why)), - } - }; - Self { - id, - symbol: function.symbol.clone(), - image: function.image.clone(), - address: function.address, - length: bytes.len(), - exit, - verdict, - signature, - } - } - - fn report(&self) -> String { - let exit = self.exit.map_or(String::from("-"), |exit| exit.to_string()); - format!( - "{} {} {:#x} {} {exit} {}", - self.symbol, self.image, self.address, self.length, self.verdict - ) - } -} - -/// A refusal's name and the word's offset. -fn refusal(why: Ineligible) -> String { - let named = |name: &str, offset: u32| format!("{name} at {offset:#x}"); - match why { - Ineligible::Length => String::from("length"), - Ineligible::Exit => String::from("exit"), - Ineligible::FallsThrough => String::from("falls-through"), - Ineligible::Masked { offset } => named("masked", offset), - Ineligible::Call { offset } => named("call", offset), - Ineligible::RegisterBranch { offset } => named("register-branch", offset), - Ineligible::System { offset } => named("system", offset), - Ineligible::Exception { offset } => named("exception", offset), - Ineligible::Reserved { offset } => named("reserved", offset), - Ineligible::Exclusive { offset } => named("exclusive", offset), - Ineligible::Pointer { offset } => named("pointer", offset), - } -} - -/// `bytes` without the padding words after its last word that runs. -fn trimmed(bytes: &[u8]) -> &[u8] { - let mut end = bytes.len() / 4 * 4; - while end >= 4 { - let word = u32::from_le_bytes(bytes[end - 4..end].try_into().expect("a word")); - if !PADDING.contains(&word) { - break; - } - end -= 4; - } - &bytes[..end] -} - -/// The byte offset of the first `ret`. -fn first_ret(bytes: &[u8]) -> Option { - let (words, _) = bytes.as_chunks::<4>(); - words - .iter() - .position(|word| u32::from_le_bytes(*word) == RET) - .map(|index| (index * 4) as u16) -} - -/// The `Signature::generated` line of `row`'s signature, under a comment -/// naming it. -fn line(row: &Row, build: &str) -> String { - let signature = row.signature.expect("an eligible row"); - let digest = signature - .digest() - .iter() - .map(|byte| format!("{byte:#04x}")) - .collect::>() - .join(", "); - let variant = match row.id { - Id::Memmove => "Memmove", - Id::Bzero => "Bzero", - Id::Memset => "Memset", - Id::Memcmp => "Memcmp", - Id::Strlen => "Strlen", - #[allow( - unreachable_patterns, - reason = "the test routines exist only under test-support" - )] - _ => unreachable!("no production table holds a test routine"), - }; - format!( - " // {} {} {build} at {:#x}\n Signature::generated(\n Id::{variant},\n {},\n {},\n {:#018x},\n [{digest}],\n ),\n", - row.symbol, - row.image, - row.address, - signature.length(), - signature.exit(), - signature.prefix(), - ) -} - -/// The `signatures.rs` of `rows`. -fn table(rows: &[&Row], build: &str) -> String { - let mut out = String::from( - "//! The signatures of the guest functions HLE replaces, generated offline\n\ - //! from a macOS build's dyld shared cache (`cargo xtask hle-signatures`),\n\ - //! one line per function naming its symbol, image and build. A line holds\n\ - //! the function's routine, length, exit offset and hashes\n\ - //! ([`Signature::generated`]), never its bytes: Stela contains no Apple\n\ - //! software. A function joins the table only once its routine has agreed\n\ - //! with it on the real bytes (`tests/hle_real.rs`).\n\ - use super::{Id, Signature};\n\npub static SIGNATURES: &[Signature] = &[\n", - ); - let mut seen = Vec::new(); - for row in rows { - let Some(signature) = row.signature else { - continue; - }; - if seen.contains(&signature) { - continue; - } - seen.push(signature); - let _ = write!(out, "{}", line(row, build)); - } - out.push_str("];\n"); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - const NOP: u32 = 0xd503_201f; - - /// A 16-word leaf: adds, an inside `b.ne`, a `ret` at word 12, padding. - fn leaf() -> Vec { - let mut words = vec![0x9100_0400u32; 10]; - words[5] = 0x5400_0001 | 2 << 5; // b.ne .+8 - words.extend([0x9100_0400, NOP, RET, 0, 0, NOP]); - words.iter().flat_map(|word| word.to_le_bytes()).collect() - } - - fn function(bytes: Vec, address: u64) -> Function { - Function { - symbol: String::from("_platform_memmove"), - image: String::from("/usr/lib/system/libsystem_platform.dylib"), - address, - bytes, - } - } - - /// The numbers of a generated line, in order. - fn numbers(line: &str) -> Vec { - let code: String = line - .lines() - .filter(|line| !line.trim_start().starts_with("//")) - .collect(); - code.split(|c: char| !(c.is_ascii_hexdigit() || c == 'x')) - .filter(|token| { - !token.is_empty() && token.chars().next().is_some_and(|c| c.is_ascii_digit()) - }) - .map(|token| match token.strip_prefix("0x") { - Some(hex) => u64::from_str_radix(hex, 16).unwrap(), - None => token.parse().unwrap(), - }) - .collect() - } - - #[test] - fn a_generated_line_reproduces_the_signature() { - let row = Row::of(Id::Memmove, &function(leaf(), 0x1_8000_0100)); - assert_eq!(row.verdict, "eligible"); - // The trailing UDF and NOP words are padding, not function. - assert_eq!((row.length, row.exit), (52, Some(48))); - let line = line(&row, "26B123"); - assert!( - line.contains("// _platform_memmove /usr/lib/system/libsystem_platform.dylib 26B123") - ); - let numbers = numbers(&line); - let digest: Vec = numbers[3..].iter().map(|&byte| byte as u8).collect(); - let generated = Signature::generated( - Id::Memmove, - numbers[0] as u16, - numbers[1] as u16, - numbers[2], - digest.try_into().unwrap(), - ); - let of = Signature::of(Id::Memmove, &leaf()[..52], 48).unwrap(); - assert_eq!(generated, of); - assert!(generated.matches(&leaf())); - assert!(table(&[&row], "26B123").contains("pub static SIGNATURES: &[Signature] = &[")); - } - - #[test] - fn the_report_names_each_refusal() { - // Past its page's end. - let row = Row::of(Id::Memmove, &function(leaf(), 0x1_8000_0fe0)); - assert_eq!(row.verdict, "crosses-page"); - // A word that branches out, a call, and no ret. - let with = |index: usize, word: u32| { - let mut bytes = leaf(); - bytes[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes()); - Row::of(Id::Memmove, &function(bytes, 0x1_8000_0000)).verdict - }; - assert_eq!(with(3, 0x1400_0100), "masked at 0xc"); - assert_eq!(with(3, 0x9400_0001), "call at 0xc"); - assert_eq!(with(12, 0x9100_0400), "exit: no ret"); - assert!(row.report().starts_with( - "_platform_memmove /usr/lib/system/libsystem_platform.dylib 0x180000fe0 52 48 " - )); - } - - #[test] - fn extracts_stay_out_of_the_repository() { - assert!(refuse_inside_repository(&crate::tools::root().join("target/hle")).is_err()); - assert!(refuse_inside_repository(Path::new("/tmp/hle-private")).is_ok()); - } - - #[test] - fn every_production_routine_has_candidates() { - for id in Id::PRODUCTION { - assert!( - CANDIDATES - .iter() - .any(|(candidate, names)| *candidate == id && !names.is_empty()) - ); - } - } -} +//! `cargo xtask hle-signatures`: the signatures of the guest functions HLE +//! replaces, from a macOS build's dyld shared cache (phase 0's reader, +//! `symbolize::code`). For each routine it looks up the symbols that may +//! name it, takes each function from its address to the next function +//! start (less the padding after its last word), its first `ret` as its +//! exit, and runs the engine's own `Signature::of`, so a function the +//! engine would refuse is refused here with the same reason. +//! +//! It prints one report row per symbol found, `symbol image address length +//! exit verdict`. With `--out` it writes a `signatures.rs` table of the +//! eligible ones: routine, length, exit and hashes only, never bytes, one +//! `Signature::generated` line each under a comment naming the symbol, +//! image and build. With `--extract` it writes each function's bytes +//! (`.bin`) and description (`.json`), for the opt-in +//! real-bytes oracle (`tests/hle_real.rs`): Apple's bytes, which never go +//! in the repository, so `--extract` refuses a directory inside it. +use anyhow::{Context, Result, bail, ensure}; +use clap::Args; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use stela_engine::hle::{Id, Ineligible, Signature}; + +use crate::symbolize::code::{self, Function}; + +/// The longest function a signature covers: one fetch page. +const LIMIT: usize = 4096; +/// `ret`. +const RET: u32 = 0xd65f_03c0; +/// The words that pad a function to the next one's alignment, which it +/// never runs: UDF #0 and NOP. +const PADDING: [u32; 2] = [0, 0xd503_201f]; + +/// The symbols that may name each routine, to be confirmed by the report +/// on each macOS build. +/// +/// Mach-O prepends a leading underscore to C symbols, so Libplatform's +/// `_platform_*` symbols appear in the shared cache as `__platform_*`. +pub const CANDIDATES: [(Id, &[&str]); 5] = [ + ( + Id::Memmove, + &[ + "__platform_memmove", + &[ + "__platform_bzero", + "__platform_bzero$VARIANT$Base", + "_platform_bzero", + "_bzero", + "___bzero", + ], + ), + ( + Id::Memset, + &[ + "__platform_memset", + "__platform_memset$VARIANT$Base", + "_platform_memset", + "_memset", + ], + ), + ( + Id::Memcmp, + &[ + "__platform_memcmp", + "__platform_bcmp", + "_platform_memcmp", + "_platform_bcmp", + "_memcmp", + "_bcmp", + ], + ), + ( + Id::Strlen, + &[ + "__platform_strlen", + "_platform_strlen", + "_strlen", + ], + ), +]; + +#[derive(Args)] +pub struct HleSignatures { + /// The guest's dyld shared cache: its main file + /// (`dyld_shared_cache_arm64e`, its subcaches beside it) or the + /// directory holding it. + #[arg(long)] + cache: PathBuf, + /// Write the eligible functions' signatures here as a `signatures.rs` + /// table (`crates/stela-engine/src/hle/signatures.rs` once the oracle + /// passes; a private path before). + #[arg(long)] + out: Option, + /// Write each function's bytes and description into this directory, + /// outside the repository. + #[arg(long)] + extract: Option, + /// The macOS build the cache is from, such as `26B123`, for the table's + /// comments. + #[arg(long, default_value = "unknown-build")] + build: String, +} + +impl HleSignatures { + pub fn run(&self) -> Result<()> { + if let Some(extract) = &self.extract { + refuse_inside_repository(extract)?; + } + let names: Vec<&str> = CANDIDATES + .iter() + .flat_map(|(_, names)| names.iter().copied()) + .collect(); + let functions = code::cache_functions(&self.cache, &names, LIMIT)?; + ensure!( + !functions.is_empty(), + "{} names none of {names:?}", + self.cache.display() + ); + let mut rows = Vec::new(); + for function in &functions { + let Some(id) = routine(&function.symbol) else { + continue; + }; + rows.push(Row::of(id, function)); + } + println!("symbol image address length exit verdict"); + for row in &rows { + println!("{}", row.report()); + } + let eligible: Vec<&Row> = rows.iter().filter(|row| row.signature.is_some()).collect(); + println!( + "{} of {} functions eligible; routines: {}", + eligible.len(), + rows.len(), + CANDIDATES + .iter() + .map(|(id, _)| format!( + "{}={}", + id.name(), + eligible.iter().filter(|row| row.id == *id).count() + )) + .collect::>() + .join(" ") + ); + if let Some(out) = &self.out { + std::fs::write(out, table(&eligible, &self.build)) + .with_context(|| format!("write {}", out.display()))?; + println!("wrote {} signatures to {}", eligible.len(), out.display()); + } + if let Some(extract) = &self.extract { + std::fs::create_dir_all(extract)?; + for (row, function) in rows + .iter() + .zip(functions.iter().filter(|f| routine(&f.symbol).is_some())) + { + let stem = format!("{}-{:x}", row.symbol.trim_start_matches('_'), row.address); + std::fs::write( + extract.join(format!("{stem}.bin")), + &function.bytes[..row.length], + )?; + let description = serde_json::json!({ + "id": row.id.name(), + "symbol": row.symbol, + "image": row.image, + "address": row.address, + "length": row.length, + "exit": row.exit, + "verdict": row.verdict, + }); + std::fs::write( + extract.join(format!("{stem}.json")), + serde_json::to_string_pretty(&description)?, + )?; + } + println!( + "extracted {} functions to {}", + rows.len(), + extract.display() + ); + } + Ok(()) + } +} + +/// The routine a symbol may name. +fn routine(symbol: &str) -> Option { + CANDIDATES + .iter() + .find(|(_, names)| names.contains(&symbol)) + .map(|(id, _)| *id) +} + +/// Refuse to write Apple's bytes into the repository. +fn refuse_inside_repository(path: &Path) -> Result<()> { + let root = crate::tools::root(); + let absolute = std::path::absolute(path)?; + if absolute.starts_with(root) { + bail!( + "--extract {} is inside the repository ({}): Apple's bytes stay outside it", + path.display(), + root.display() + ); + } + Ok(()) +} + +/// One function's report row and, if eligible, its signature. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Row { + id: Id, + symbol: String, + image: String, + address: u64, + /// Its bytes, its trailing padding left out. + length: usize, + exit: Option, + verdict: String, + signature: Option, +} + +impl Row { + fn of(id: Id, function: &Function) -> Self { + let bytes = trimmed(&function.bytes); + let exit = first_ret(bytes); + let page_offset = (function.address & 0xfff) as usize; + let (signature, verdict) = if page_offset + bytes.len() > LIMIT { + (None, String::from("crosses-page")) + } else { + match exit.map(|exit| Signature::of(id, bytes, exit)) { + None => (None, String::from("exit: no ret")), + Some(Ok(signature)) => (Some(signature), String::from("eligible")), + Some(Err(why)) => (None, refusal(why)), + } + }; + Self { + id, + symbol: function.symbol.clone(), + image: function.image.clone(), + address: function.address, + length: bytes.len(), + exit, + verdict, + signature, + } + } + + fn report(&self) -> String { + let exit = self.exit.map_or(String::from("-"), |exit| exit.to_string()); + format!( + "{} {} {:#x} {} {exit} {}", + self.symbol, self.image, self.address, self.length, self.verdict + ) + } +} + +/// A refusal's name and the word's offset. +fn refusal(why: Ineligible) -> String { + let named = |name: &str, offset: u32| format!("{name} at {offset:#x}"); + match why { + Ineligible::Length => String::from("length"), + Ineligible::Exit => String::from("exit"), + Ineligible::FallsThrough => String::from("falls-through"), + Ineligible::Masked { offset } => named("masked", offset), + Ineligible::Call { offset } => named("call", offset), + Ineligible::RegisterBranch { offset } => named("register-branch", offset), + Ineligible::System { offset } => named("system", offset), + Ineligible::Exception { offset } => named("exception", offset), + Ineligible::Reserved { offset } => named("reserved", offset), + Ineligible::Exclusive { offset } => named("exclusive", offset), + Ineligible::Pointer { offset } => named("pointer", offset), + } +} + +/// `bytes` without the padding words after its last word that runs. +fn trimmed(bytes: &[u8]) -> &[u8] { + let mut end = bytes.len() / 4 * 4; + while end >= 4 { + let word = u32::from_le_bytes(bytes[end - 4..end].try_into().expect("a word")); + if !PADDING.contains(&word) { + break; + } + end -= 4; + } + &bytes[..end] +} + +/// The byte offset of the first `ret`. +fn first_ret(bytes: &[u8]) -> Option { + let (words, _) = bytes.as_chunks::<4>(); + words + .iter() + .position(|word| u32::from_le_bytes(*word) == RET) + .map(|index| (index * 4) as u16) +} + +/// The `Signature::generated` line of `row`'s signature, under a comment +/// naming it. +fn line(row: &Row, build: &str) -> String { + let signature = row.signature.expect("an eligible row"); + let digest = signature + .digest() + .iter() + .map(|byte| format!("{byte:#04x}")) + .collect::>() + .join(", "); + let variant = match row.id { + Id::Memmove => "Memmove", + Id::Bzero => "Bzero", + Id::Memset => "Memset", + Id::Memcmp => "Memcmp", + Id::Strlen => "Strlen", + #[allow( + unreachable_patterns, + reason = "the test routines exist only under test-support" + )] + _ => unreachable!("no production table holds a test routine"), + }; + format!( + " // {} {} {build} at {:#x}\n Signature::generated(\n Id::{variant},\n {},\n {},\n {:#018x},\n [{digest}],\n ),\n", + row.symbol, + row.image, + row.address, + signature.length(), + signature.exit(), + signature.prefix(), + ) +} + +/// The `signatures.rs` of `rows`. +fn table(rows: &[&Row], build: &str) -> String { + let mut out = String::from( + "//! The signatures of the guest functions HLE replaces, generated offline\n\ + //! from a macOS build's dyld shared cache (`cargo xtask hle-signatures`),\n\ + //! one line per function naming its symbol, image and build. A line holds\n\ + //! the function's routine, length, exit offset and hashes\n\ + //! ([`Signature::generated`]), never its bytes: Stela contains no Apple\n\ + //! software. A function joins the table only once its routine has agreed\n\ + //! with it on the real bytes (`tests/hle_real.rs`).\n\ + use super::{Id, Signature};\n\npub static SIGNATURES: &[Signature] = &[\n", + ); + let mut seen = Vec::new(); + for row in rows { + let Some(signature) = row.signature else { + continue; + }; + if seen.contains(&signature) { + continue; + } + seen.push(signature); + let _ = write!(out, "{}", line(row, build)); + } + out.push_str("];\n"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOP: u32 = 0xd503_201f; + + /// A 16-word leaf: adds, an inside `b.ne`, a `ret` at word 12, padding. + fn leaf() -> Vec { + let mut words = vec![0x9100_0400u32; 10]; + words[5] = 0x5400_0001 | 2 << 5; // b.ne .+8 + words.extend([0x9100_0400, NOP, RET, 0, 0, NOP]); + words.iter().flat_map(|word| word.to_le_bytes()).collect() + } + + fn function(bytes: Vec, address: u64) -> Function { + Function { + symbol: String::from("_platform_memmove"), + image: String::from("/usr/lib/system/libsystem_platform.dylib"), + address, + bytes, + } + } + + /// The numbers of a generated line, in order. + fn numbers(line: &str) -> Vec { + let code: String = line + .lines() + .filter(|line| !line.trim_start().starts_with("//")) + .collect(); + code.split(|c: char| !(c.is_ascii_hexdigit() || c == 'x')) + .filter(|token| { + !token.is_empty() && token.chars().next().is_some_and(|c| c.is_ascii_digit()) + }) + .map(|token| match token.strip_prefix("0x") { + Some(hex) => u64::from_str_radix(hex, 16).unwrap(), + None => token.parse().unwrap(), + }) + .collect() + } + + #[test] + fn a_generated_line_reproduces_the_signature() { + let row = Row::of(Id::Memmove, &function(leaf(), 0x1_8000_0100)); + assert_eq!(row.verdict, "eligible"); + // The trailing UDF and NOP words are padding, not function. + assert_eq!((row.length, row.exit), (52, Some(48))); + let line = line(&row, "26B123"); + assert!( + line.contains("// _platform_memmove /usr/lib/system/libsystem_platform.dylib 26B123") + ); + let numbers = numbers(&line); + let digest: Vec = numbers[3..].iter().map(|&byte| byte as u8).collect(); + let generated = Signature::generated( + Id::Memmove, + numbers[0] as u16, + numbers[1] as u16, + numbers[2], + digest.try_into().unwrap(), + ); + let of = Signature::of(Id::Memmove, &leaf()[..52], 48).unwrap(); + assert_eq!(generated, of); + assert!(generated.matches(&leaf())); + assert!(table(&[&row], "26B123").contains("pub static SIGNATURES: &[Signature] = &[")); + } + + #[test] + fn the_report_names_each_refusal() { + // Past its page's end. + let row = Row::of(Id::Memmove, &function(leaf(), 0x1_8000_0fe0)); + assert_eq!(row.verdict, "crosses-page"); + // A word that branches out, a call, and no ret. + let with = |index: usize, word: u32| { + let mut bytes = leaf(); + bytes[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes()); + Row::of(Id::Memmove, &function(bytes, 0x1_8000_0000)).verdict + }; + assert_eq!(with(3, 0x1400_0100), "masked at 0xc"); + assert_eq!(with(3, 0x9400_0001), "call at 0xc"); + assert_eq!(with(12, 0x9100_0400), "exit: no ret"); + assert!(row.report().starts_with( + "_platform_memmove /usr/lib/system/libsystem_platform.dylib 0x180000fe0 52 48 " + )); + } + + #[test] + fn extracts_stay_out_of_the_repository() { + assert!(refuse_inside_repository(&crate::tools::root().join("target/hle")).is_err()); + assert!(refuse_inside_repository(Path::new("/tmp/hle-private")).is_ok()); + } + + #[test] + fn every_production_routine_has_candidates() { + for id in Id::PRODUCTION { + assert!( + CANDIDATES + .iter() + .any(|(candidate, names)| *candidate == id && !names.is_empty()) + ); + } + } +}