feat(log): count each PE's own TLBIs of everything by whether TTBR0_EL1 changed since its previous one, and under --profile sample one in 4096 with its PC, X16, X30 and both TTBR0 values, with the acceptance tests any whole-TLBI keep must pass, where nothing said what made SPTM flush everything at context-switch rate

PES WHOLE TLBI TRIGGER same_ttbr0/new_ttbr0 gives each PE's split, read at
the TLBI from the register, so native TTBR0 switches count too; mail's
TLBIs of everything are another PE's and count in neither. Under step
timing, PES WHOLE TLBI SAMPLE lines name the caller: if nearly every one
follows an address-space switch, the trigger is the shared-region rule in
pmap_switch, which only keeping translations across the flush answers; if
not, the CPU model makes SPTM flush. Reads registers only.

after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives runs five
scenarios on machines of their own: a page remapped, unmapped, made PXN, a
TTBR0 and ASID reused by a new process, one VA in two address spaces with
one changed. All pass, and all five fail when the TLBI of everything keeps
the contexts without checking them (a mutation of tlb_maintained), the
bar a "verify instead of forget" must clear. That change itself is not made
here. Engine translation inputs untouched: the translator id is unchanged.
This commit is contained in:
Garvit Surana committed 2026-11-23 08:23:30 +00:00
1 parent de600d5d1e
commit 72a0c83c07
7 files changed
+315 -1

No files matched your search

+19
View File
@@ -2782,6 +2782,25 @@ impl Heartbeat {
line.push_str(&format!(" {pc:#x}={count}"));
}
output::arguments(format_args!("{line}\n"));
// What came before them: an address-space switch since the PE's
// previous one or none, and under --profile a sample of where
// they were called from.
let mut line = String::from("PES WHOLE TLBI TRIGGER same_ttbr0/new_ttbr0");
let mut sampled = String::new();
for (pe, counts) in per_pe.iter().enumerate() {
let trigger = &counts.whole_tlbi_trigger;
let [same, new] = trigger.switched;
line.push_str(&format!(" {pe}:{same}/{new}"));
for [pc, x16, x30, from, to] in trigger.samples {
if pc != 0 {
sampled.push_str(&format!(
"PES WHOLE TLBI SAMPLE pe={pe} pc={pc:#x} x16={x16:#x} x30={x30:#x} \
ttbr0={from:#x}->{to:#x}\n"
));
}
}
}
output::arguments(format_args!("{line}\n{sampled}"));
output::arguments(format_args!("{transitions}\n"));
let [svc, eret, genter, gexit] = [0, 1, 2, 3].map(|kind| {
transition_misses[kind * 9..kind * 9 + 9]
+8 -1
View File
@@ -17,7 +17,8 @@ use reports::*;
pub use reports::{
DeviceRegister, Discard, Event, ExitWordsWalk, Footprint, FootprintWalk, MAIL_WAITS, MailWait,
Occupancy, PeState, Requirement, RequirementKind, Reset, Statistics, Stop, Surveyed,
Suspension, TRACE_HITS, TraceHit, WATCH_HITS, WatchHit, WholeTlbiSites,
Suspension, TRACE_HITS, TraceHit, WATCH_HITS, WHOLE_TLBI_SAMPLE_EVERY, WHOLE_TLBI_SAMPLES,
WatchHit, WholeTlbiSites, WholeTlbiTrigger,
};
mod amx;
pub use amx::{AmxCell, AmxCounts, AmxForms, FORMS};
@@ -983,6 +984,10 @@ pub struct Machine<H: Host, D: Devices> {
/// in a ring ([`Self::refill_after`]), and the next place.
fill_log: Vec<(u64, u64)>,
fill_next: usize,
/// TTBR0_EL1 at this PE's last TLBI of everything, and how many it
/// issued ([`WholeTlbiTrigger`]).
whole_tlbi_ttbr0: u64,
whole_tlbis: u64,
/// The pages forgotten contexts had taken last, by half and key: a
/// context made anew for the key walks them again at once
/// ([`Self::refill_pages`]).
@@ -1485,6 +1490,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
itlb_seen_bits: 0,
fill_log: Vec::new(),
fill_next: 0,
whole_tlbi_ttbr0: 0,
whole_tlbis: 0,
pending_refills: BTreeMap::new(),
refills: Vec::new(),
dropped_refills: BTreeMap::new(),
@@ -605,6 +605,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
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);
@@ -612,6 +613,29 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
}
/// 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
@@ -723,6 +723,8 @@ pub struct Counts {
pub whole_tlbi_sites: super::WholeTlbiSites,
/// ([`super::Statistics::whole_tlbi_times`]).
pub whole_tlbi_times: [u64; 3],
/// ([`super::Statistics::whole_tlbi_trigger`]).
pub whole_tlbi_trigger: super::WholeTlbiTrigger,
/// Its stamped transfers ([`chain::StampCount`]'s order), the exits it
/// gave a stamped tail, how many exits had one when it last looked, then
/// the PAC branch exits it gave a predicted tail and its probe
@@ -2875,6 +2877,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
itlb_sources: statistics.itlb_sources,
whole_tlbi_sites: statistics.whole_tlbi_sites,
whole_tlbi_times: statistics.whole_tlbi_times,
whole_tlbi_trigger: statistics.whole_tlbi_trigger,
transitions: [
statistics.native_transitions[stela_compiler::x86_64::transition::GUARDED_ENTER],
statistics.engine_transitions[stela_compiler::x86_64::transition::GUARDED_ENTER],
@@ -626,6 +626,8 @@ pub struct Statistics {
/// the counter ticks of all of them in the engine's forgetting and in
/// the host's shadow, those two under step timing only.
pub whole_tlbi_times: [u64; 3],
/// What came before those TLBIs ([`WholeTlbiTrigger`]).
pub whole_tlbi_trigger: WholeTlbiTrigger,
pub compiled: u64,
/// Of `compiled`, the blocks that run their iterations inside
/// themselves (`CompiledBlock::self_loop`).
@@ -827,6 +829,58 @@ impl WholeTlbiSites {
}
}
/// The samples a [`WholeTlbiTrigger`] keeps.
pub const WHOLE_TLBI_SAMPLES: usize = 4;
/// One TLBI of everything in this many is sampled, under step timing.
pub const WHOLE_TLBI_SAMPLE_EVERY: u64 = 4096;
/// What came before a PE's own TLBIs of everything, to find what makes a
/// guest flush everything at context-switch rate: whether TTBR0_EL1
/// changed since the PE's previous one (an address-space switch between
/// the two, natively or not), and, under step timing (`--profile`), a
/// rate-limited sample of where it was called from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(
all(feature = "std", feature = "native-profile"),
derive(serde::Serialize)
)]
pub struct WholeTlbiTrigger {
/// Those that found TTBR0_EL1 as the PE's previous one left it, and
/// those that found it changed.
pub switched: [u64; 2],
/// One in [`WHOLE_TLBI_SAMPLE_EVERY`] under step timing: its PC, X16,
/// X30, and TTBR0_EL1 at the PE's previous one and now; the latest
/// first, `[0; 5]` none.
pub samples: [[u64; 5]; WHOLE_TLBI_SAMPLES],
}
impl WholeTlbiTrigger {
/// Count one with TTBR0_EL1 `switched` or not, and keep `sample`.
pub fn note(&mut self, switched: bool, sample: Option<[u64; 5]>) {
self.switched[usize::from(switched)] += 1;
if let Some(sample) = sample {
self.samples.copy_within(..WHOLE_TLBI_SAMPLES - 1, 1);
self.samples[0] = sample;
}
}
/// Add `other`'s counts; its samples go first.
pub fn add(&mut self, other: &Self) {
self.switched[0] += other.switched[0];
self.switched[1] += other.switched[1];
let mut samples = [[0; 5]; WHOLE_TLBI_SAMPLES];
let kept = other
.samples
.iter()
.chain(&self.samples)
.filter(|sample| **sample != [0; 5]);
for (into, sample) in samples.iter_mut().zip(kept) {
*into = *sample;
}
self.samples = samples;
}
}
/// [`MailWait`]'s parts.
pub const MAIL_WAITS: usize = MailWait::LongestNative as usize + 1;
@@ -861,6 +915,7 @@ impl core::ops::AddAssign for Statistics {
itlb_sources,
whole_tlbi_sites,
whole_tlbi_times,
whole_tlbi_trigger,
compiled,
self_loops,
regions,
@@ -1019,6 +1074,7 @@ impl core::ops::AddAssign for Statistics {
for (total, count) in self.whole_tlbi_times.iter_mut().zip(whole_tlbi_times) {
*total += count;
}
self.whole_tlbi_trigger.add(&whole_tlbi_trigger);
for (total, count) in self.record_misses.iter_mut().zip(record_misses) {
*total += count;
}
@@ -10604,6 +10604,66 @@ fn whole_tlbi_benchmark() {
/// The census of TLBIs of everything keeps the most frequent PCs, merges a
/// PC it holds and orders them most first; a new PC takes the least
/// frequent's place and count.
/// A PE's own TLBIs of everything count by whether TTBR0_EL1 changed since
/// its previous one, natively written or not, and only under step timing
/// is one in [`WHOLE_TLBI_SAMPLE_EVERY`] sampled with its PC, X16, X30 and
/// both TTBR0 values; mail's TLBIs of everything count in neither.
#[test]
fn whole_tlbis_count_the_address_space_switches_before_them() {
use mmu::tlbi::{Everywhere, Reach};
const RET: u32 = 0xd65f_03c0;
let mut machine = machine(&[RET]);
let all = |machine: &mut Machine<FakeHost, NoDevices>| {
machine.tlb_maintained(Reach::All, Everywhere::All, None)
};
let trigger = |machine: &Machine<FakeHost, NoDevices>| machine.statistics.whole_tlbi_trigger;
all(&mut machine);
all(&mut machine);
assert_eq!(trigger(&machine).switched, [2, 0]);
// TTBR0 as a native switch leaves it, the engine not told.
machine
.cpu
.registers
.set(SystemRegister::TTBR0_EL1, 0, 0x1234_0000);
all(&mut machine);
all(&mut machine);
assert_eq!(trigger(&machine).switched, [3, 1]);
assert_eq!(trigger(&machine).samples, [[0; 5]; WHOLE_TLBI_SAMPLES]);
// Mail's TLBI of everything is another PE's.
machine.applying_mail = true;
machine
.cpu
.registers
.set(SystemRegister::TTBR0_EL1, 0, 0x5678_0000);
all(&mut machine);
machine.applying_mail = false;
assert_eq!(trigger(&machine).switched, [3, 1]);
// Under step timing: the next one taken is the 5th, not sampled, until
// WHOLE_TLBI_SAMPLE_EVERY of them.
machine.set_step_timing(true);
machine.cpu.state.x[16] = 0x16;
machine.cpu.state.x[30] = 0x30;
let pc = machine.cpu.pc;
for _ in 4..WHOLE_TLBI_SAMPLE_EVERY + 1 {
all(&mut machine);
}
let seen = trigger(&machine);
assert_eq!(
seen.switched[0] + seen.switched[1],
WHOLE_TLBI_SAMPLE_EVERY + 1
);
assert_eq!(seen.samples[0], [pc, 0x16, 0x30, 0x5678_0000, 0x5678_0000]);
assert_eq!(seen.samples[1], [0; 5]);
// Merged over PEs: counts add, samples of both are kept.
let mut merged = seen;
merged.add(&seen);
assert_eq!(
merged.switched,
[seen.switched[0] * 2, seen.switched[1] * 2]
);
assert_eq!(merged.samples[..2], [seen.samples[0]; 2]);
}
#[test]
fn whole_tlbi_sites_keep_the_most_frequent_pcs() {
let mut sites = WholeTlbiSites::default();
@@ -788,6 +788,151 @@ fn a_whole_tlbi_refill_walks_from_the_leaf_table_and_takes_what_full_walks_give(
assert!(reads >= PAGES as usize - 1, "{reads} descriptor reads");
}
/// The acceptance set for any change to what a TLBI of everything keeps
/// (the deep dive's "verify instead of forget", #1(c)): after the guest
/// rewrites its tables and issues one, every fetch runs what its walk now
/// gives, whatever the ITLB, the block table and the contexts held before.
/// Each scenario runs on a machine of its own, whose space 0 maps pages 0
/// to 3 at frames 0 to 3, private (nG) to ASID 1, each page fetched once:
///
/// - a page remapped to another frame runs that frame;
/// - a page unmapped faults;
/// - a page made privileged-execute-never faults;
/// - an address space whose TTBR0 value (table base and ASID) a new
/// process reuses, with other mappings, runs the new process's frame;
/// - of one VA in two address spaces, the one whose mapping changed runs
/// its new frame and the other keeps its own;
///
/// and in each the pages it did not change still run their frames. Every
/// scenario fails where the TLBI keeps a context's entries without checking
/// them, as removing its forgetting from `tlb_maintained` shows (all five).
#[test]
fn after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives() {
use mmu::tlbi::{Everywhere, Reach};
const RET: u32 = 0xd65f_03c0;
const NG: u64 = 1 << 11;
const MSR_TTBR0_EL1_X0: u32 = 0xd518_2000;
const FRAMES: u64 = 4;
type M = Machine<FakeHost, NoDevices>;
let frame = |n: u64| BASE + n * 0x1000;
let pc = |page: u64| BASE + page * 0x1000;
let [_, _, l3] = SPACES_TABLES[0];
let [_, _, l3_other] = SPACES_TABLES[1];
let map = |machine: &mut M, l3: u64, page: u64, frame: u64| {
write_entry(machine, l3 + page * 8, page_descriptor(frame, false) | NG);
};
let select = |machine: &mut M, space: usize, asid: u64| {
let [l1, _, _] = SPACES_TABLES[space];
machine.cpu.state.x[0] = (BASE + l1) | asid << 48;
machine.system_instruction(MSR_TTBR0_EL1_X0).unwrap();
};
// What a fetch of `pc` runs: its page's key, or None for a fault.
let run = |machine: &mut M, pc: u64| -> Option<u64> {
match machine.fetch_block(pc, false) {
Ok(Fetched::Block(_)) => Some(machine.current_key(pc).expect("taken")),
Ok(Fetched::Exception(_)) => None,
_ => panic!("{pc:#x}: neither a block nor an exception"),
}
};
let all = |machine: &mut M| machine.tlb_maintained(Reach::All, Everywhere::All, None);
// A machine with space 0 set up and run, and each frame's key.
let start = || -> (M, Vec<u64>) {
let mut words = vec![0u32; (FRAMES * 0x1000 / 4) as usize];
for frame in 0..FRAMES as usize {
words[frame * 0x400] = RET;
}
let mut machine = machine(&words);
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
for page in 0..FRAMES {
map(&mut machine, l3, page, frame(page));
}
select(&mut machine, 0, 1);
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
assert_eq!(
keys.iter()
.collect::<alloc::collections::BTreeSet<_>>()
.len(),
FRAMES as usize,
"one key a frame"
);
(machine, keys)
};
// Each scenario: what each fetch it makes after the TLBI ran, and what
// the walk then gives.
type Check = (&'static str, Option<u64>, Option<u64>);
type Scenario<'a> = &'a dyn Fn(&mut M, &[u64]) -> Vec<Check>;
let scenarios: [(&str, Scenario); 5] = [
("remapped page", &|machine, keys| {
map(machine, l3, 0, frame(1));
all(machine);
vec![
("page 0", run(machine, pc(0)), Some(keys[1])),
("page 3", run(machine, pc(3)), Some(keys[3])),
]
}),
("unmapped page", &|machine, keys| {
write_entry(machine, l3 + 8, 0);
all(machine);
vec![
("page 1", run(machine, pc(1)), None),
("page 3", run(machine, pc(3)), Some(keys[3])),
]
}),
("execute-never page", &|machine, keys| {
write_entry(machine, l3 + 2 * 8, page_descriptor(frame(2), true) | NG);
all(machine);
vec![
("page 2", run(machine, pc(2)), None),
("page 3", run(machine, pc(3)), Some(keys[3])),
]
}),
("reused TTBR0 and ASID", &|machine, keys| {
// The process goes; another runs (ASID 2); a new process takes
// the first one's table base and ASID with page 3 at frame 0,
// and the kernel flushes before it runs.
select(machine, 0, 2);
map(machine, l3, 3, frame(0));
all(machine);
select(machine, 0, 1);
vec![
("page 3", run(machine, pc(3)), Some(keys[0])),
("page 1", run(machine, pc(1)), Some(keys[1])),
]
}),
("one VA in two spaces", &|machine, keys| {
// Space 1 (ASID 3) maps page 0 at frame 2, and runs it.
paged_space(machine, 1, &[frame(2)]);
map(machine, l3_other, 0, frame(2));
select(machine, 1, 3);
let before = run(machine, pc(0));
// Then maps it at frame 3, and flushes.
map(machine, l3_other, 0, frame(3));
all(machine);
let changed = run(machine, pc(0));
select(machine, 0, 1);
vec![
("space 1 before", before, Some(keys[2])),
("space 1 after", changed, Some(keys[3])),
("space 0", run(machine, pc(0)), Some(keys[0])),
]
}),
];
let mut failed = Vec::new();
for (name, scenario) in scenarios {
let (mut machine, keys) = start();
for (what, ran, expected) in scenario(&mut machine, &keys) {
if ran != expected {
failed.push(alloc::format!(
"{name}, {what}: ran {ran:x?}, its walk gives {expected:x?}"
));
}
}
}
assert!(failed.is_empty(), "{failed:#?}");
}
/// A machine running `words` at BASE through 4 KiB pages of address
/// space 0, page `n` at frame `BASE + n * 4 KiB`.
fn machine_with_pages(words: &[u32]) -> Machine<FakeHost, NoDevices> {