perf(engine): complete PMC0 reads natively after a native transition, computing the cycle count from the monitor's state at the native count

This commit is contained in:
Tyler Smith committed 2026-11-11 15:15:09 -05:00
1 parent 21f3293b88
commit 3baa1dafae
9 files changed
+494 -1

No files matched your search

@@ -59,6 +59,9 @@
//! names, and an [`event_wait_thunk`] consumes a set one; 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 [`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};
@@ -674,6 +677,128 @@ pub fn energy_thunk(pc: GuestAddress, rt: u8, cell: Place, count: Place) -> Thun
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.
#[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,
}
impl CycleCounter {
/// The counter at system count `now`, `None` where the thunk exits
/// (closed, or a quotient that does not fit in 64 bits).
pub fn at(&self, now: u64) -> Option<u64> {
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()?;
Some(self.counter.wrapping_add(increment) & self.mask)
}
}
/// The thunk completing `MRS Xt, <cycle counter>` 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.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], 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`],
@@ -1534,6 +1659,111 @@ mod tests {
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::<Cell>());
const CYCLES: Place = Place::new(Anchor::Mirrors, 2 * size_of::<Cell>());
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,
},
});
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));
// 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));
}
/// 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.
@@ -1382,6 +1382,13 @@ impl<H: Host, D: Devices> Machine<H, D> {
self.clock.native(self.host.tsc_counter()?);
let count = Place::new(Anchor::Count, 0);
register_read::count_thunk(GuestAddress(pc), rt, cell, count)
} else if index == COUNTER_MIRRORS[0]
&& let Some(tsc) = self.host.tsc_counter()
{
self.clock.native(tsc);
let count = Place::new(Anchor::Count, 0);
let plain = cell_place(CYCLES_PLAIN);
register_read::cycle_counter_thunk(GuestAddress(pc), rt, cell, plain, CYCLES, count)
} else if index == DAIF_MIRROR && self.native_system().exclusive {
register_read::mask_read_thunk(GuestAddress(pc), rt, cell)
} else {
@@ -107,6 +107,10 @@ pub(super) struct Mirrors {
/// canonical memory, set as native code is entered: native ERET then
/// leaves clearing and signalling them to the engine.
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,
}
/// Where native code finds the cell at `index` of the PE's state.
@@ -212,8 +216,19 @@ pub(super) enum TimerWord {
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 of the first of the [`STORED_WRITES`].
const STORED_WRITE_CELLS: usize = TIMER_CONTROL + 1;
const STORED_WRITE_CELLS: usize = CYCLES_PLAIN + 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
@@ -315,6 +330,7 @@ impl Default for Mirrors {
lines_until: 0,
switches: register_read::SwitchLog::default(),
monitor: 0,
cycles: register_read::CycleCounter::default(),
}
}
}
@@ -279,6 +279,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
self.mirrors.enter(self.cpu.pstate);
self.cpu.state.pan = u64::from(self.cpu.pstate.pan);
self.enter_amx_cell();
self.enter_cycles();
self.cpu.state.anchors = self.anchors();
self.cpu.state.lower_limit = self.lower_limit();
let entered = self.timing_start();
@@ -430,10 +430,31 @@ impl<H: Host, D: Devices> Machine<H, D> {
};
if let (Ok(()), true, Some(value)) = (&step, after == before, value) {
self.mirrors[index] = register_read::Cell { readable: 1, value };
if index == COUNTER_MIRRORS[0] {
self.mirrors[CYCLES_PLAIN] = register_read::Cell {
readable: 1,
value: 0,
};
}
}
step
}
/// Fill [`Mirrors::cycles`] as native code is entered: the monitor's
/// PMC0, which no native code changes, unless a read of it answers a
/// degraded value instead of the count.
pub(super) fn enter_cycles(&mut self) {
let degraded = !self.cpu.degraded.is_empty()
&& self
.cpu
.degraded
.contains_key(&MIRRORED[COUNTER_MIRRORS[0]].selector());
self.mirrors.cycles = match &self.cpu.pmu {
Some(pmu) if !degraded => pmu.native_cycles(),
_ => register_read::CycleCounter::default(),
};
}
/// MRS or MSR of a [`GUARDED_MIRRORS`] register: in a guarded level, one
/// that completes plainly opens its cell on the bank's storage.
fn guarded_access(&mut self, word: u32, access: RegisterAccess, index: usize) -> Step {
@@ -9270,6 +9270,7 @@ fn upper_occupancy_lists_the_mapped_level_one_ranges_and_outermost_blocks() {
mod arena;
mod context_id;
mod cycles_native;
mod exits;
mod floating_point_traps;
mod native_exceptions;
@@ -0,0 +1,198 @@
//! Native PMC0 reads (`x86_64::register_read::cycle_counter_thunk`) run on
//! the machine's own frame and cells against the engine path: where a
//! native transition closed the counter's cell but the read stays plain,
//! the thunk computes the count the engine's read would answer at the same
//! system count and opens the cell on it.
use super::super::transitions::tests::run_native;
use super::*;
use crate::machine::pmu::{self, Context, Filter, Pmu};
use core::sync::atomic::Ordering::Relaxed;
use stela_compiler::x86_64::register_read::{Count, CountState};
const MRS_X10_PMC0: u32 = 0xd53a_f00a;
const ADD: u32 = 0x9100_0400; // add x0, x0, #1
/// A PE at EL1 whose PMC0 counts cycles of a 36 000 007 Hz core on a
/// 24 MHz system counter at EL1 (or not at all with `counting` false), and
/// whose native count reader reads `clock`.
fn counting_machine(clock: &CountState, counting: bool) -> Machine<FakeHost, NoDevices> {
let mut machine = machine(&[]);
machine.cpu.pstate = Pstate::reset(1);
let context = Context {
el: 1,
filter: Filter::Guest,
waiting: false,
};
let mut monitor = Pmu::new(36_000_007, 24_000_000);
monitor.write(pmu::PMCR1, 1 << 16, 0, 0, context).unwrap();
monitor
.write(pmu::PMCR1_EL12, 1 << 16, 0, 0, context)
.unwrap();
monitor
.write(pmu::PMCR0, u64::from(counting), 0, 0, context)
.unwrap();
monitor.write(pmu::PMC[0], 1_000, 0, 0, context).unwrap();
machine.cpu.pmu = Some(monitor);
machine.derived_changed();
let reader = machine.clock.reader() as *mut Count;
// SAFETY: the machine's own reader, which no native code runs over
// meanwhile; `clock` outlives every run of the test.
unsafe {
(*reader).per_tsc = 0;
(*reader).last = 0;
(*reader).state = clock as *const CountState as u64;
}
machine
}
fn count_state() -> alloc::boxed::Box<CountState> {
let clock = alloc::boxed::Box::new(CountState::default());
clock.ceiling.store(u64::MAX, Relaxed);
clock
}
/// The engine's count and the native one at `now`.
fn at(machine: &mut Machine<FakeHost, NoDevices>, clock: &CountState, now: u64) {
machine.host.now = now;
clock.offset.store(now, Relaxed);
}
/// PMC0 as the engine reads it.
fn engine(machine: &mut Machine<FakeHost, NoDevices>) -> u64 {
machine.cpu.pc = BASE;
machine.system_instruction(MRS_X10_PMC0).unwrap();
assert_eq!(machine.cpu.pc, BASE + 4, "completed plainly");
machine.cpu.state.x[10]
}
/// PMC0 as the thunk reads it, if it completed.
fn native(machine: &mut Machine<FakeHost, NoDevices>) -> Option<u64> {
let thunk = register_read::cycle_counter_thunk(
GuestAddress(BASE),
10,
cell_place(COUNTER_MIRRORS[0]),
cell_place(CYCLES_PLAIN),
CYCLES,
Place::new(Anchor::Count, 0),
);
machine.cpu.state.x[10] = 0xdead;
match run_native(machine, &thunk.code) {
(pc, kind) if pc == BASE + 4 && kind == ExitKind::Fallthrough as u64 => {
Some(machine.cpu.state.x[10])
}
(pc, kind) => {
assert_eq!((pc, kind), (BASE, ExitKind::System as u64));
assert_eq!(machine.cpu.state.x[10], 0xdead);
None
}
}
}
/// What a native transition does to the counter's cell.
fn transition_natively(machine: &mut Machine<FakeHost, NoDevices>) {
machine.mirrors[COUNTER_MIRRORS[0]].readable = 0;
}
/// After each native transition the thunk reads what a twin that takes
/// every read in the engine reads at the same count, with native and
/// engine reads interleaved, the remainder carried, and never backwards;
/// it opens the cell on that count as the engine does.
#[test]
fn native_cycle_reads_equal_the_engine_path_at_the_same_count() {
let clock = count_state();
let mut machine = counting_machine(&clock, true);
let twin_clock = count_state();
let mut twin = counting_machine(&twin_clock, true);
at(&mut machine, &clock, 100);
at(&mut twin, &twin_clock, 100);
assert_eq!(engine(&mut machine), engine(&mut twin));
assert_eq!(machine.mirrors[CYCLES_PLAIN].readable, 1);
let mut last = 0;
for (step, now) in [101, 103, 104, 1_000, 1_001, 77_777, 77_778, 1 << 33]
.into_iter()
.enumerate()
{
at(&mut machine, &clock, now);
at(&mut twin, &twin_clock, now);
transition_natively(&mut machine);
transition_natively(&mut twin);
let expected = engine(&mut twin);
let read = if step % 3 == 2 {
engine(&mut machine)
} else {
native(&mut machine).expect("plain, stale")
};
assert_eq!(read, expected, "at {now}");
assert!(read >= last, "monotonic at {now}");
last = read;
assert_eq!(
machine.mirrors[COUNTER_MIRRORS[0]],
register_read::Cell {
readable: 1,
value: read
}
);
// The open cell keeps the count until the next transition, as for
// the existing cell thunk; an engine read is always live.
at(&mut machine, &clock, now + 50);
assert_eq!(native(&mut machine), Some(read));
}
// A PMC0 that does not count reads its count as it stands.
let mut idle = counting_machine(&clock, false);
at(&mut idle, &clock, 100);
assert_eq!(engine(&mut idle), 1_000);
at(&mut idle, &clock, 5_000);
transition_natively(&mut idle);
assert_eq!(native(&mut idle), Some(1_000));
}
/// The thunk exits where the read may not be plain: before the engine
/// completed one in the state, after derived state changed, without a
/// monitor or with a degraded answer; and the block's exit gets the thunk
/// only where the host counts its TSC.
#[test]
fn native_cycle_reads_exit_unless_the_read_is_plain() {
let clock = count_state();
let mut machine = counting_machine(&clock, true);
at(&mut machine, &clock, 100);
assert_eq!(native(&mut machine), None, "no plain read yet");
let read = engine(&mut machine);
transition_natively(&mut machine);
at(&mut machine, &clock, 200);
assert!(native(&mut machine).is_some_and(|value| value > read));
machine.derived_changed();
assert_eq!(machine.mirrors[CYCLES_PLAIN].readable, 0);
assert_eq!(native(&mut machine), None, "derived state changed");
engine(&mut machine);
transition_natively(&mut machine);
let selector = MIRRORED[COUNTER_MIRRORS[0]].selector();
machine.cpu.degraded.insert(selector, 7);
assert_eq!(native(&mut machine), None, "degraded");
machine.cpu.degraded.remove(&selector);
machine.cpu.pmu = None;
assert_eq!(native(&mut machine), None, "no monitor");
for tsc in [None, Some((5, 7))] {
let mut machine = super::machine(&[ADD, MRS_X10_PMC0, ADD]);
machine.host.tsc_counter = tsc;
let base = machine.cpu.pc;
machine.host.exits = vec![NativeExit::Exit {
next_pc: base + 8,
kind: ExitKind::Fallthrough as u64,
}];
machine.step().unwrap();
let thunk = register_read::cycle_counter_thunk(
GuestAddress(base + 4),
10,
cell_place(COUNTER_MIRRORS[0]),
cell_place(CYCLES_PLAIN),
CYCLES,
Place::new(Anchor::Count, 0),
);
assert_eq!(
machine.host.installed.last() == Some(&thunk.code),
tsc.is_some()
);
}
}
@@ -637,6 +637,7 @@ pub(super) mod tests {
machine.mirrors.transition(state);
machine.mirrors.enter(machine.cpu.pstate);
machine.cpu.state.pan = u64::from(machine.cpu.pstate.pan);
machine.enter_cycles();
machine.cpu.state.anchors = machine.anchors();
machine.cpu.state.lower_limit = machine.lower_limit();
let code = stela_compiler::x86_64::pinned::entered(code);
+18
View File
@@ -388,6 +388,24 @@ impl Pmu {
(self.pmcr0 & counter_bit(0, 32, n) == 0).then(|| &self.counters[n] as *const u64 as u64)
}
/// PMC0 as a read at a later system count finds it: [`Self::read`]
/// counts from `synced_count` in the context of the last
/// synchronization, which no read changes, so the count at `now` is
/// `counters[0]` plus the floor of the ticks since, scaled with the
/// carried remainder, and nothing while PMC0 does not count there.
pub fn native_cycles(&self) -> stela_compiler::x86_64::register_read::CycleCounter {
let counting = self.counts(CYCLES, self.context);
stela_compiler::x86_64::register_read::CycleCounter {
open: 1,
counter: self.counters[CYCLES],
synced: self.synced_count,
remainder: self.remainder[CYCLES],
clock: if counting { self.clock } else { 0 },
frequency: self.frequency,
mask: self.layout.width.mask(),
}
}
/// Whether an enabled event depends on the core clock.
pub fn timed(&self) -> bool {
(0..COUNTERS).any(|n| {