fix(log): each beat states for every PE the kinds of exit that cost it the most time outside guest code, with their runs and milliseconds (PES EXIT TIME), where only --profile timed exits and only the home PE's exits were counted by kind

This commit is contained in:
Tyler Smith committed 2026-11-17 19:44:53 -05:00
1 parent 44d88aad23
commit ae335e1b52
9 files changed
+401 -30

No files matched your search

+278
View File
@@ -0,0 +1,278 @@
//! Where a PE's time outside compiled guest code goes, by the kind of exit
//! that ended each run of guest code, in any boot. A run of guest code ends
//! in an exit to the engine; the time from that return to the next entry is
//! the exit's handling, the lookup or translation of the next block and the
//! waits on other PEs it met. The host reads the TSC at every entry and
//! return already (its share of time in guest code), so this keeps two sums
//! per kind from those same readings and times nothing new per exit. What
//! is no exit's cost is left out: the core's halts and the host's work
//! between slices pause the pending exit's time.
use alloc::{format, string::String, vec::Vec};
use stela_compiler::block::ExitKind;
/// The kinds counted: the compiler's block exit kinds in their order, then
/// a fault taken in guest code.
pub const KINDS: usize = ExitKind::Amx as usize + 2;
/// A fault in guest code, after the block exit kinds.
pub const FAULT: usize = KINDS - 1;
/// System instructions and device register accesses, whose exits also
/// begin a PE's waits.
pub const SYSTEM: usize = ExitKind::System as usize;
/// The kinds' names in the heartbeat line.
pub const NAMES: [&str; KINDS] = [
"fallthrough",
"direct",
"indirect",
"call",
"return",
"trap",
"pointer-auth",
"clock",
"thread-register",
"floating-point",
"scalable",
"system",
"amx",
"fault",
];
/// The kinds a PE's part of the line shows, the costliest first.
const SHOWN: usize = 4;
/// One core's sums: for each kind the runs that ended in it and the ticks
/// from their returns to the next entries.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ExitTimes {
/// `[runs, ticks]` by kind.
sums: [[u64; 2]; KINDS],
/// The kind of the exit whose time is running.
kind: usize,
/// An exit's time is running since its return.
pending: bool,
/// Whether the time counts now, and since when: not while paused.
since: Option<u64>,
/// What the pending exit took before the last pause.
spent: u64,
}
impl ExitTimes {
pub const fn new() -> Self {
Self {
sums: [[0; 2]; KINDS],
kind: 0,
pending: false,
since: None,
spent: 0,
}
}
/// A run of guest code entered at `entered` returned at `returned`
/// with an exit of `kind` (one past the last is a fault's): the exit
/// before it took until `entered`, and this one's time starts.
pub fn run(&mut self, entered: u64, returned: u64, kind: usize) {
if self.pending {
let open = self.since.map_or(0, |since| entered.wrapping_sub(since));
let sum = &mut self.sums[self.kind];
sum[0] += 1;
sum[1] += self.spent + open;
}
self.kind = kind.min(FAULT);
self.pending = true;
self.since = Some(returned);
self.spent = 0;
}
/// From `now` the core does what is no exit's cost (it halts, or does
/// the host's work between slices) until [`Self::resume`].
pub fn pause(&mut self, now: u64) {
if let Some(since) = self.since.take() {
self.spent += now.wrapping_sub(since);
}
}
/// The pending exit's time counts again from `now`.
pub fn resume(&mut self, now: u64) {
if self.pending && self.since.is_none() {
self.since = Some(now);
}
}
/// `[runs, ticks]` by kind so far.
pub fn sums(&self) -> [[u64; 2]; KINDS] {
self.sums
}
}
/// One PE's interval: `[runs, ticks]` by kind, and the ticks it polled for
/// a wake without halting, which its waits' exits (System ones) include.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PeExits {
pub kinds: [[u64; 2]; KINDS],
pub polled: u64,
}
impl PeExits {
/// Its kinds with runs as `(ticks, runs, kind)`, the costliest first.
fn ranked(&self) -> Vec<(u64, u64, usize)> {
let mut ranked: Vec<_> = self
.kinds
.iter()
.enumerate()
.filter(|(_, sum)| sum[0] != 0)
.map(|(kind, sum)| {
let ticks = if kind == SYSTEM {
sum[1].saturating_sub(self.polled)
} else {
sum[1]
};
(ticks, sum[0], kind)
})
.collect();
ranked.sort_unstable_by(|a, b| b.cmp(a));
ranked
}
}
/// `PES EXIT TIME kind=runs/ms 0:system=154821/1210,return=128665/420,…
/// all:system=…`: for each PE the kinds of exit that cost it the most time
/// outside guest code since the last beat, each with the runs of guest code
/// that ended in it and the milliseconds from those returns to the next
/// entries (handling, the next block's lookup or translation, waits on
/// other PEs; not its halts, idle polling or host service), then every kind
/// over all PEs. `ticks_per_ms` is the ticks' rate.
pub fn pes_exit_time(ticks_per_ms: u64, pes: &[PeExits]) -> String {
let item = |&(ticks, runs, kind): &(u64, u64, usize)| {
format!("{}={runs}/{}", NAMES[kind], ticks / ticks_per_ms.max(1))
};
let mut line = String::from("PES EXIT TIME kind=runs/ms");
let mut all = PeExits::default();
for (pe, exits) in pes.iter().enumerate() {
let shown: Vec<_> = exits.ranked().iter().take(SHOWN).map(item).collect();
line.push_str(&format!(" {pe}:{}", shown.join(",")));
for (sum, kind) in all.kinds.iter_mut().zip(&exits.kinds) {
sum[0] += kind[0];
sum[1] += kind[1];
}
// Each PE's polling comes off its own System time.
let polled = exits.polled.min(exits.kinds[SYSTEM][1]);
all.kinds[SYSTEM][1] -= polled;
}
let shown: Vec<_> = all.ranked().iter().map(item).collect();
line.push_str(&format!(" all:{}", shown.join(",")));
line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_names_follow_the_compilers_exit_kinds() {
for (kind, name) in [
(ExitKind::Fallthrough, "fallthrough"),
(ExitKind::Direct, "direct"),
(ExitKind::Indirect, "indirect"),
(ExitKind::Call, "call"),
(ExitKind::Return, "return"),
(ExitKind::Trap, "trap"),
(ExitKind::PointerAuthentication, "pointer-auth"),
(ExitKind::Clock, "clock"),
(ExitKind::ThreadRegister, "thread-register"),
(ExitKind::FloatingPoint, "floating-point"),
(ExitKind::ScalableNumerical, "scalable"),
(ExitKind::System, "system"),
(ExitKind::Amx, "amx"),
] {
assert_eq!(NAMES[kind as usize], name);
}
assert_eq!(NAMES[FAULT], "fault");
}
#[test]
fn an_exit_takes_from_its_return_to_the_next_entry() {
let mut times = ExitTimes::new();
// The first run has no exit before it.
times.run(100, 1_000, 4);
assert_eq!(times.sums(), [[0; 2]; KINDS]);
// Its return exit took until the next entry; a System exit follows.
times.run(1_300, 5_000, SYSTEM);
let mut expected = [[0; 2]; KINDS];
expected[4] = [1, 300];
assert_eq!(times.sums(), expected);
times.run(5_050, 6_000, 4);
expected[SYSTEM] = [1, 50];
assert_eq!(times.sums(), expected);
// A fault, and a kind past the table's, count as faults.
times.run(6_010, 7_000, FAULT);
times.run(7_500, 8_000, 99);
times.run(8_100, 9_000, 0);
expected[4] = [2, 310];
expected[FAULT] = [2, 600];
assert_eq!(times.sums(), expected);
}
#[test]
fn halts_and_host_work_are_no_exits_time() {
let mut times = ExitTimes::new();
times.run(0, 1_000, SYSTEM);
// The PE waits: 40 ticks of handling, a halt, 10 more on the wake.
times.pause(1_040);
times.resume(900_000);
// The slice ends for host work, then the guest runs again.
times.pause(900_010);
times.resume(950_000);
times.run(950_025, 960_000, 1);
let mut expected = [[0; 2]; KINDS];
expected[SYSTEM] = [1, 75];
assert_eq!(times.sums(), expected);
// A pause with nothing pending, twice, and a resume without one,
// change nothing.
let mut idle = ExitTimes::new();
idle.resume(5);
idle.pause(10);
idle.pause(20);
idle.run(100, 200, 0);
idle.pause(210);
idle.pause(260);
idle.resume(300);
idle.resume(400);
idle.run(305, 500, 0);
let mut expected = [[0; 2]; KINDS];
expected[0] = [1, 15];
assert_eq!(idle.sums(), expected);
}
#[test]
fn the_line_names_each_pes_costliest_kinds_and_all_of_them_together() {
let mut busy = PeExits::default();
busy.kinds[SYSTEM] = [154_821, 1_210_000];
busy.kinds[4] = [128_665, 420_000];
busy.kinds[3] = [67_596, 380_000];
busy.kinds[1] = [44_687, 200_000];
busy.kinds[2] = [19_369, 90_000];
busy.kinds[FAULT] = [900, 4_000];
// Mostly waiting: its System exits' time is mostly idle polling.
let mut waiting = PeExits {
polled: 700_000,
..PeExits::default()
};
waiting.kinds[SYSTEM] = [9_000, 760_000];
waiting.kinds[4] = [2_000, 9_000];
assert_eq!(
pes_exit_time(1_000, &[busy, waiting, PeExits::default()]),
"PES EXIT TIME kind=runs/ms \
0:system=154821/1210,return=128665/420,call=67596/380,direct=44687/200 \
1:system=9000/60,return=2000/9 2: \
all:system=163821/1270,return=130665/429,call=67596/380,direct=44687/200,\
indirect=19369/90,fault=900/4"
);
// Polling past the System time leaves none, not a wrapped number.
waiting.polled = 9_000_000;
assert_eq!(
pes_exit_time(1_000, &[waiting]),
"PES EXIT TIME kind=runs/ms 0:return=2000/9,system=9000/0 \
all:return=2000/9,system=9000/0"
);
assert_eq!(pes_exit_time(0, &[]), "PES EXIT TIME kind=runs/ms all:");
}
}
+1
View File
@@ -35,6 +35,7 @@ pub mod drivers_turn;
pub mod early_fault;
pub mod entropy;
pub mod exit_port;
pub mod exit_times;
#[cfg(target_arch = "x86_64")]
pub mod fiber;
pub mod firmware_connect;
+31 -1
View File
@@ -600,6 +600,9 @@ pub struct State {
pub stray: u64,
/// TSC ticks spent in compiled guest code, its exits and faults.
pub native_ticks: u64,
/// The runs of compiled code and the time from their returns to the
/// next entries, by the kind of exit that ended them (`PES EXIT TIME`).
outside: stela_boot_core::exit_times::ExitTimes,
#[cfg(feature = "native-profile")]
native_profile: profile::Profile,
/// Where the guest's address space lies beside the window.
@@ -777,6 +780,7 @@ pub unsafe fn install(config: Config) -> Result<HostOwner> {
ring,
fills: 0,
native_ticks: 0,
outside: stela_boot_core::exit_times::ExitTimes::new(),
#[cfg(feature = "native-profile")]
native_profile: profile::Profile::default(),
resets: 0,
@@ -936,6 +940,23 @@ pub fn native_ticks() -> u64 {
state().native_ticks
}
/// From `now` (a TSC reading) this core does the host's work between two
/// slices of guest execution, which is no exit's time (`PES EXIT TIME`),
/// until [`outside_resume`]. Nothing on a core that runs no guest code.
pub(super) fn outside_pause(now: u64) {
if let Some(state) = local::installed() {
state.outside.pause(now);
}
}
/// This core runs its guest again from `now`: the time of the exit that
/// ended its last run of compiled code counts again.
pub(super) fn outside_resume(now: u64) {
if let Some(state) = local::installed() {
state.outside.resume(now);
}
}
/// Serialize both sides of the reference-counter observation. Compiler fences
/// also prevent moving memory work across these opt-in profiling boundaries.
#[cfg(feature = "native-profile")]
@@ -1389,7 +1410,16 @@ fn native_return(code: NativeCode, exit: BlockExit, entered: u64) -> NativeExit
crate::native_mmio::shootdown::service();
let state = state();
state.native = false;
state.native_ticks += rdtsc() - entered;
let returned = rdtsc();
state.native_ticks += returned - entered;
// The exit before this run took until `entered`; this one's time runs
// from here to the next entry.
let kind = if exit.kind == FAULT_KIND {
stela_boot_core::exit_times::FAULT
} else {
stela_compiler::x86_64::chain::ExitWord::split(exit.kind).0 as usize
};
state.outside.run(entered, returned, kind);
#[cfg(feature = "native-profile")]
state.native_profile.exit(exit.kind);
if exit.kind == FAULT_KIND
+42 -27
View File
@@ -358,6 +358,10 @@ impl Host for BareHost<'_> {
state().native_ticks
}
fn outside(&self) -> [[u64; 2]; stela_engine::machine::engine::OUTSIDE_KINDS] {
state().outside.sums()
}
unsafe fn execute(&mut self, code: NativeCode, guest: &mut GuestState) -> NativeExit {
assert!(!state().native, "nested native block entry");
state().native = true;
@@ -741,33 +745,10 @@ impl Host for BareHost<'_> {
}
fn wait_for_interrupt(&mut self) {
crate::native_mmio::shootdown::service();
local::clear_interrupt();
// The wait sends queued serial output until an interrupt comes,
// opening a window for one after each burst.
while crate::output::send_queued() {
// SAFETY: STI holds interrupts off for one more instruction, so
// only the NOP's boundary takes a pending one.
unsafe { asm!("sti", "nop", "cli", options(nomem, nostack)) };
if local::interrupted() {
return;
}
}
// The wait may last until the armed one-shot count runs out.
const MASKED: u32 = 1 << 16;
let budget = {
let state = state();
let remaining = state.apic.read(apic::CURRENT);
(state.apic_hz != 0 && state.apic.read(apic::LVT_TIMER) & MASKED == 0 && remaining != 0)
.then(|| u64::from(remaining) * 1_000_000 / state.apic_hz)
};
let ring = state().ring;
// Halted, it uses no window translation: shootdowns count it as
// acknowledged until it wakes, and it flushes first then.
let _idle = crate::native_mmio::shootdown::idle();
// SAFETY: interrupts are disabled and the host IDT takes the wake;
// the ring is this processor's.
unsafe { crate::native_idle::wait_with(|| budget, ring) };
// The wait is no exit's time (`PES EXIT TIME`).
state().outside.pause(rdtsc());
self.halt_for_interrupt();
state().outside.resume(rdtsc());
}
fn relax(&mut self) {
@@ -817,3 +798,37 @@ impl Host for BareHost<'_> {
.map(|store| store as &mut dyn stela_engine::machine::Translations)
}
}
impl BareHost<'_> {
/// Wait for an interrupt with this core halted, sending queued serial
/// output meanwhile.
fn halt_for_interrupt(&mut self) {
crate::native_mmio::shootdown::service();
local::clear_interrupt();
// The wait sends queued serial output until an interrupt comes,
// opening a window for one after each burst.
while crate::output::send_queued() {
// SAFETY: STI holds interrupts off for one more instruction, so
// only the NOP's boundary takes a pending one.
unsafe { asm!("sti", "nop", "cli", options(nomem, nostack)) };
if local::interrupted() {
return;
}
}
// The wait may last until the armed one-shot count runs out.
const MASKED: u32 = 1 << 16;
let budget = {
let state = state();
let remaining = state.apic.read(apic::CURRENT);
(state.apic_hz != 0 && state.apic.read(apic::LVT_TIMER) & MASKED == 0 && remaining != 0)
.then(|| u64::from(remaining) * 1_000_000 / state.apic_hz)
};
let ring = state().ring;
// Halted, it uses no window translation: shootdowns count it as
// acknowledged until it wakes, and it flushes first then.
let _idle = crate::native_mmio::shootdown::idle();
// SAFETY: interrupts are disabled and the host IDT takes the wake;
// the ring is this processor's.
unsafe { crate::native_idle::wait_with(|| budget, ring) };
}
}
+4
View File
@@ -230,10 +230,14 @@ impl Pe {
if step_timing {
host::sampling::host_service();
}
// The host's work between slices is no exit's time
// (`PES EXIT TIME`).
host::outside_resume(host::rdtsc());
let stop = machine.run_with_budget(RunBudget {
blocks: limit,
host_ticks: Some(host::COUNTER_HZ / WAIT_POLLS_PER_SECOND),
});
host::outside_pause(host::rdtsc());
#[cfg(feature = "native-profile")]
if step_timing {
let counter = host::fresh_counter();
+26
View File
@@ -905,10 +905,13 @@ pub(super) fn run<H: Host>(
};
let slice_started = host::rdtsc();
service.slice_start(slice_started);
// The host's work between slices is no exit's time (`PES EXIT TIME`).
host::outside_resume(slice_started);
machine.observe_parallel_source(parallel::SourcePhase::SliceEnter);
let stop = execute(machine, limit);
machine.observe_parallel_source(parallel::SourcePhase::SliceExit);
let service_now = host::rdtsc();
host::outside_pause(service_now);
let waited = matches!(stop, Stop::Waiting) || machine.yielded_for_interrupt(&stop);
service.slice_end(service_now, if waited { "wait" } else { "guest" });
heartbeat.sliced_ticks += service_now.wrapping_sub(slice_started);
@@ -2116,6 +2119,12 @@ impl Heartbeat {
// engine, and its runs of guest code
// (`stela_boot_core::load_lines`).
let mut pe_times = Vec::with_capacity(per_pe.len());
// Per PE in any boot: its runs of guest code and the time from
// their returns to the next entries by the kind of exit that
// ended them, in TSC ticks, and the ticks it polled for a wake
// without halting, which its waits' exits include
// (`stela_boot_core::exit_times`).
let mut pe_exits = Vec::with_capacity(per_pe.len());
let counter_ticks = |tsc: u64| {
(u128::from(tsc) * u128::from(host::COUNTER_HZ) / u128::from(tsc_hz.max(1))) as u64
};
@@ -2140,6 +2149,19 @@ impl Heartbeat {
.sum::<u64>()
.saturating_sub(before.fetches.iter().sum()),
});
let idle = |counts: &parallel::Counts| {
(counts.sleep_ticks + counts.spin_ticks).saturating_sub(counts.halt_ticks)
};
pe_exits.push(stela_boot_core::exit_times::PeExits {
kinds: core::array::from_fn(|kind| {
[0, 1].map(|part| {
now.outside[kind][part].saturating_sub(before.outside[kind][part])
})
}),
polled: (u128::from(idle(now).saturating_sub(idle(before)))
* u128::from(tsc_hz)
/ u128::from(host::COUNTER_HZ)) as u64,
});
let rate = u128::from(now.retired.saturating_sub(before.retired))
.saturating_mul(u128::from(tsc_hz))
/ u128::from(elapsed.max(1))
@@ -2413,6 +2435,10 @@ impl Heartbeat {
"{}\n",
stela_boot_core::load_lines::pes_share(interval_ticks as u64, &pe_times)
));
output::arguments(format_args!(
"{}\n",
stela_boot_core::exit_times::pes_exit_time(tsc_hz / 1000, &pe_exits)
));
output::arguments(format_args!("{fetches}\n"));
let mut cache = None;
if let Some(board) = machine.devices.hub().code_report() {
+2 -2
View File
@@ -7,8 +7,8 @@ mod reports;
use boundary::*;
pub use boundary::{
CodePartitions, CodeWindow, ConsumedPair, DeviceError, Devices, Host, LocalRegisters,
LockedMemory, NativeView, NoDevices, OwnLockAccess, OwnLockRegisters, PassiveRegisters,
PlainRead, ScalarRead, Settled, Start, UnlockedDma, WriteSettled,
LockedMemory, NativeView, NoDevices, OUTSIDE_KINDS, OwnLockAccess, OwnLockRegisters,
PassiveRegisters, PlainRead, ScalarRead, Settled, Start, UnlockedDma, WriteSettled,
};
use compilation::{PENDING_EXITS, PendingExits};
use mirrors::*;
@@ -6,6 +6,10 @@ use stela_contracts::{
refuse,
};
/// The kinds [`Host::outside`] counts: every [`ExitKind`], then a fault
/// taken in compiled code.
pub const OUTSIDE_KINDS: usize = ExitKind::Amx as usize + 2;
/// One PE's System registers that take none of the board's locks, as
/// [`Devices::system_register`] serves them.
pub trait LocalRegisters: Send + Sync {
@@ -422,6 +426,15 @@ pub trait Host {
fn native_ticks(&self) -> u64 {
0
}
/// For each kind of exit from compiled code (the compiler's
/// [`ExitKind`]s in their order, then a fault), the runs that ended in
/// it and the TSC ticks from their returns to the next entries, so far
/// and less the core's halts and the host's own work: the heartbeat's
/// split of each PE's time outside guest code. A host that does not
/// count them answers zeros.
fn outside(&self) -> [[u64; 2]; OUTSIDE_KINDS] {
[[0; 2]; OUTSIDE_KINDS]
}
/// A cycle count for `--profile`'s phase timing ([`step_timing`]); a
/// host without one answers 0.
fn profile_ticks(&mut self) -> u64 {
@@ -553,6 +553,9 @@ pub struct Counts {
pub line_ticks: u64,
/// TSC ticks its host core spent in compiled code ([`Host::native_ticks`]).
pub native_ticks: u64,
/// Its runs of compiled code and the TSC ticks from their returns to the
/// next entries, by the kind of exit that ended them ([`Host::outside`]).
pub outside: [[u64; 2]; super::OUTSIDE_KINDS],
/// Counter ticks its host core halted or spun on a monitored granule
/// ([`super::Statistics::sleep_ticks`], `spin_ticks`) and spent waiting
/// on other PEs ([`super::Statistics::sync_ticks`]), and its waits.
@@ -2661,6 +2664,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
line_queries: statistics.line_queries,
line_ticks: statistics.line_ticks,
native_ticks: self.host.native_ticks(),
outside: self.host.outside(),
sleep_ticks: statistics.sleep_ticks,
spin_ticks: statistics.spin_ticks,
halt_ticks: statistics.halt_ticks,