merge: fork/tlbi-keep into fork/build1

# Conflicts:
#	crates/stela-boot-core/src/options.rs
#	crates/stela-boot-core/src/options/parse.rs
#	crates/stela-loader/src/mount_interface.rs
This commit is contained in:
Garvit Surana committed 2026-11-23 11:02:52 +00:00
commit cfec986c86
20 files changed
+1658 -43

No files matched your search

+34
View File
@@ -338,6 +338,18 @@ pub const ACPI_HARDWARE: &str = "--acpi-hardware";
/// hand-written opt-in for debugging that setup never writes, so the
/// options revision stays 13.
pub const KEEP_RUNNING_ON_PANIC: &str = "--keep-running-on-panic";
/// Keep the ITLB's lookup contexts across a TLBI of everything and verify
/// each entry against the tables before any lookup uses it again, instead
/// of forgetting them all (`--tlbi-keep on|off`, off unless given). A
/// hand-written opt-in setup never writes, so the options revision stays
/// 13; it stays off by default until a boot has proven it.
pub const TLBI_KEEP: &str = "--tlbi-keep";
/// With `--tlbi-keep on`, also walk every entry verification keeps in full
/// and drop it, counted as a mismatch, where the walk differs
/// (`--tlbi-verify-check`): a debug safety mode, hand-written like
/// `--acpi-hardware`, so the options revision stays 13.
pub const TLBI_VERIFY_CHECK: &str = "--tlbi-verify-check";
/// Cables an emulated Magic Trackpad 2 fed by the host's precision
/// touchpads (`--trackpad mt2|builtin`): a hand-written opt-in, in a
@@ -671,6 +683,12 @@ pub struct System {
pub acpi_hardware: bool,
/// Run on after a guest kernel panic ([`KEEP_RUNNING_ON_PANIC`]).
pub keep_running_on_panic: bool,
/// [`TLBI_KEEP`]'s value, unset where the line has none
/// ([`Self::tlbi_keep`]).
pub tlbi_keep: Option<bool>,
/// Walk every entry a kept context's verification keeps in full as
/// well ([`TLBI_VERIFY_CHECK`]).
pub tlbi_verify_check: bool,
/// Whether a laptop takes its laptop features unasked ([`LAPTOP`]);
/// [`Laptop::Auto`] unless given ([`Self::laptop`]).
pub laptop: Option<Laptop>,
@@ -806,6 +824,8 @@ impl Default for System {
brightness_keys: false,
acpi_hardware: false,
keep_running_on_panic: false,
tlbi_keep: None,
tlbi_verify_check: false,
laptop: None,
asus_mode: None,
amx_native: None,
@@ -982,6 +1002,15 @@ impl System {
self.asus_mode.unwrap_or_default()
}
/// Whether the ITLB keeps its contexts across a TLBI of everything and
/// verifies them ([`TLBI_KEEP`]), and whether every entry it keeps is
/// walked in full as well ([`TLBI_VERIFY_CHECK`], only with the first):
/// off unless `--tlbi-keep on`.
pub fn tlbi_keep(&self) -> (bool, bool) {
let keep = self.tlbi_keep.unwrap_or(false);
(keep, keep && self.tlbi_verify_check)
}
/// The trackpad this boot cables: `--trackpad`, on the hub `--input`
/// cables, so none without host input. The hub's disk-port count and
/// the cabling both read this, so they agree.
@@ -1346,6 +1375,11 @@ impl fmt::Display for System {
line.flag("--brightness-keys", self.brightness_keys)?;
line.flag(ACPI_HARDWARE, self.acpi_hardware)?;
line.flag(KEEP_RUNNING_ON_PANIC, self.keep_running_on_panic)?;
line.value(
TLBI_KEEP,
self.tlbi_keep.map(|keep| if keep { "on" } else { "off" }),
)?;
line.flag(TLBI_VERIFY_CHECK, self.tlbi_verify_check)?;
line.value(LAPTOP, self.laptop.map(Laptop::name))?;
line.value(ASUS_MODE, self.asus_mode.map(AsusMode::name))?;
line.value(AMX_NATIVE, self.amx_native)?;
@@ -84,6 +84,9 @@ pub enum Error {
DuplicateLaptop,
AsusMode,
DuplicateAsusMode,
TlbiKeep,
DuplicateTlbiKeep,
DuplicateTlbiVerifyCheck,
DuplicateAudioHpet,
DuplicateNativePciIoapic,
MissingAudioMode,
@@ -233,6 +236,9 @@ impl Error {
Self::DuplicateLaptop => "duplicate --laptop",
Self::AsusMode => "--asus-mode takes performance, turbo, silent or off",
Self::DuplicateAsusMode => "duplicate --asus-mode",
Self::TlbiKeep => "--tlbi-keep takes on or off",
Self::DuplicateTlbiKeep => "duplicate --tlbi-keep",
Self::DuplicateTlbiVerifyCheck => "duplicate --tlbi-verify-check",
Self::DuplicateAudioHpet => "duplicate audio HPET handoff",
Self::DuplicateNativePciIoapic => "duplicate native PCI IOAPIC handoff",
Self::MissingAudioMode => "missing audio check mode",
@@ -40,6 +40,20 @@ impl ParseState<'_> {
"--brightness-keys" => options.brightness_keys = true,
ACPI_HARDWARE => options.acpi_hardware = true,
KEEP_RUNNING_ON_PANIC => options.keep_running_on_panic = true,
TLBI_KEEP => {
let keep = match value() {
Some("on") => true,
Some("off") => false,
_ => return Err(Error::TlbiKeep),
};
if options.tlbi_keep.replace(keep).is_some() {
return Err(Error::DuplicateTlbiKeep);
}
}
TLBI_VERIFY_CHECK => flag(
&mut options.tlbi_verify_check,
Error::DuplicateTlbiVerifyCheck,
)?,
"--lid" => {
if options.lid.is_some() {
return Err(Error::DuplicateLid);
@@ -93,6 +93,41 @@ fn an_asus_laptop_runs_in_performance_unless_asus_mode_says_otherwise() {
}
}
#[test]
fn the_tlbi_keep_is_off_unless_asked_for_and_its_check_needs_it() {
let plain = System::parse("--system").unwrap();
assert_eq!(plain.tlbi_keep(), (false, false));
assert_eq!(plain.to_string(), "--system");
for (text, keep) in [
("--system --tlbi-keep on", (true, false)),
("--system --tlbi-keep off", (false, false)),
("--system --tlbi-keep on --tlbi-verify-check", (true, true)),
(
"--system --tlbi-keep off --tlbi-verify-check",
(false, false),
),
("--system --tlbi-verify-check", (false, false)),
] {
let options = System::parse(text).unwrap();
assert_eq!(options.tlbi_keep(), keep, "{text}");
assert_eq!(options.to_string(), text);
}
for (text, error) in [
("--system --tlbi-keep", Error::TlbiKeep),
("--system --tlbi-keep yes", Error::TlbiKeep),
(
"--system --tlbi-keep on --tlbi-keep off",
Error::DuplicateTlbiKeep,
),
(
"--system --tlbi-verify-check --tlbi-verify-check",
Error::DuplicateTlbiVerifyCheck,
),
] {
assert_eq!(System::parse(text).err(), Some(error), "{text}");
}
}
#[test]
fn audio_hpet_handoff_requires_an_audio_diagnostic() {
assert_eq!(
+17
View File
@@ -1304,6 +1304,23 @@ fn run_machine<H: Host>(
}
}
machine.set_step_timing(options.profile);
let (tlbi_keep, tlbi_verify_check) = options.tlbi_keep();
machine.set_tlbi_keep(tlbi_keep, tlbi_verify_check);
if tlbi_keep {
output::arguments(format_args!(
"TLBI KEEP on (--tlbi-keep on): a TLBI of everything keeps the ITLB's contexts, \
each verified against the tables at its next fetch; verify check {}\n",
if tlbi_verify_check {
"on (--tlbi-verify-check): every kept entry is walked in full too"
} else {
"off"
}
));
} else if options.tlbi_verify_check {
output::arguments(format_args!(
"TLBI KEEP off: --tlbi-verify-check does nothing without --tlbi-keep on\n"
));
}
let amx_model = options.amx_model();
machine.set_amx_model(amx_model.0);
if amx_model == stela_boot_core::options::AmxModel::ALL {
+7
View File
@@ -101,6 +101,9 @@ pub(crate) struct Settings {
/// `--amx-native`: the AMX register operations the reference model
/// completes alone, by number, as on the home machine.
pub amx_model: u32,
/// `--tlbi-keep` and `--tlbi-verify-check` ([`stela_boot_core::options::System::tlbi_keep`]),
/// as on the home machine.
pub tlbi_keep: (bool, bool),
}
/// Give each AP the PE its worker binding names, to run on a machine of its
@@ -133,6 +136,7 @@ pub(crate) fn spawn<H: Host>(
watches: settings.watches.clone(),
step_timing: settings.step_timing,
amx_model: settings.amx_model,
tlbi_keep: settings.tlbi_keep,
};
processor.spawn(Box::new(move |owner| pe.run(owner)), sender, tsc_hz)?;
}
@@ -156,6 +160,7 @@ struct Pe {
watches: Vec<(u64, u64)>,
step_timing: bool,
amx_model: u32,
tlbi_keep: (bool, bool),
}
impl Pe {
@@ -169,6 +174,7 @@ impl Pe {
watches,
step_timing,
amx_model,
tlbi_keep,
} = self;
// This core's driver calls keep the engine's TLB entries.
let _tagged = super::storage::TaggedRoots::enable();
@@ -192,6 +198,7 @@ impl Pe {
.unwrap_or_else(|error| output::fatal(error));
machine.set_step_timing(step_timing);
machine.set_amx_model(amx_model);
machine.set_tlbi_keep(tlbi_keep.0, tlbi_keep.1);
if step_timing {
host::pmu::start(pe);
}
+37
View File
@@ -2809,6 +2809,43 @@ impl Heartbeat {
}
}
output::arguments(format_args!("{line}\n{sampled}"));
// `--tlbi-keep on`: what keeping the contexts across those TLBIs
// did, every PE's together and then each PE's kept/dropped, and
// every mismatch `--tlbi-verify-check` found.
if per_pe.iter().any(|counts| counts.tlbi_keep.tlbis != 0) {
let mut keep = stela_engine::machine::engine::TlbiKeepCounts::default();
let mut each = String::new();
for (pe, counts) in per_pe.iter().enumerate() {
let counts = &counts.tlbi_keep;
keep.add(counts);
each.push_str(&format!(" {pe}:{}/{}", counts.kept, counts.dropped));
}
let ns_each = (u128::from(keep.ticks) * 1_000_000_000
/ u128::from(host::COUNTER_HZ * keep.tlbis.max(1)))
as u64;
output::arguments(format_args!(
"PES TLBI KEEP tlbis={} contexts={} verified={} forgotten={} kept={} \
dropped={} checked={} mismatches(check)={} verify_ns_per_tlbi={ns_each} \
kept/dropped{each}\n",
keep.tlbis,
keep.contexts,
keep.verified,
keep.forgotten,
keep.kept,
keep.dropped,
keep.checked,
keep.mismatches,
));
for [page, context, key, frame] in keep.samples {
if context != 0 {
output::arguments(format_args!(
"PES TLBI KEEP MISMATCH page={page:#x} context={context:#x} \
kept_key={key:#x} walked_frame={frame:#x}: a kept entry's full \
walk differed, so it was dropped\n"
));
}
}
}
output::arguments(format_args!("{transitions}\n"));
let [svc, eret, genter, gexit] = [0, 1, 2, 3].map(|kind| {
transition_misses[kind * 9..kind * 9 + 9]
+1
View File
@@ -1440,6 +1440,7 @@ fn start_machine(boot: Boot<'_>, parts: MachineParts) -> ! {
watches: options.watches.clone(),
step_timing: options.profile,
amx_model: options.amx_model().0,
tlbi_keep: options.tlbi_keep(),
};
// The loader handle's last RAM copy preceded canonical registration; its
// borrow has ended. It never executes a guest instruction.
+11 -4
View File
@@ -17,8 +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, WHOLE_TLBI_SAMPLE_EVERY, WHOLE_TLBI_SAMPLES,
WatchHit, WholeTlbiSites, WholeTlbiTrigger,
Suspension, TLBI_KEEP_SAMPLES, TRACE_HITS, TlbiKeepCounts, TraceHit, WATCH_HITS,
WHOLE_TLBI_SAMPLE_EVERY, WHOLE_TLBI_SAMPLES, WatchHit, WholeTlbiSites, WholeTlbiTrigger,
};
mod amx;
pub use amx::{AmxCell, AmxCounts, AmxForms, FORMS};
@@ -62,6 +62,7 @@ mod scheduler;
mod system_access;
mod table_switches;
mod timing;
mod tlbi_keep;
mod transitions;
pub use board::{CodeReport, LockCounts, LockSite, SiteCounts};
pub use churn::ChurnCounts;
@@ -603,7 +604,7 @@ impl Successor {
}
}
#[derive(Clone, Copy)]
#[derive(Clone, Copy, PartialEq, Eq)]
struct FetchEntry {
page: u64,
physical: u64,
@@ -619,13 +620,15 @@ struct FetchEntry {
/// A walk no instruction asked for ([`Machine::quiet_fetch_physical`]):
/// the page's frame, its leaf's guarded and global bits, and the bytes the
/// leaf maps over both stages.
/// leaf maps over both stages; with `--tlbi-keep on`, what the walk read
/// ([`tlbi_keep::WalkRecord`]).
#[derive(Clone, Copy)]
struct QuietFetch {
physical: u64,
guarded: bool,
global: bool,
size: u64,
record: Option<tlbi_keep::WalkRecord>,
}
/// One batch of walks no instruction asked for ([`Machine::refill_pages`]):
@@ -988,6 +991,9 @@ pub struct Machine<H: Host, D: Devices> {
/// issued ([`WholeTlbiTrigger`]).
whole_tlbi_ttbr0: u64,
whole_tlbis: u64,
/// Keeping the lookup contexts across a TLBI of everything, and
/// verifying them before use (`--tlbi-keep on`, [`tlbi_keep`]).
tlbi_keep: tlbi_keep::TlbiKeep,
/// 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`]).
@@ -1492,6 +1498,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
fill_next: 0,
whole_tlbi_ttbr0: 0,
whole_tlbis: 0,
tlbi_keep: tlbi_keep::TlbiKeep::default(),
pending_refills: BTreeMap::new(),
refills: Vec::new(),
dropped_refills: BTreeMap::new(),
@@ -283,33 +283,26 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
/// [`Self::forget_spaces`] for a caller that advances the generation.
fn forget_contexts(&mut self, halves: core::ops::RangeInclusive<usize>, cause: usize) {
pub(super) fn forget_contexts(
&mut self,
halves: core::ops::RangeInclusive<usize>,
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;
// Bits are inserted with a fetched size and only cleared here.
if !keep_filter && 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());
}
}
if !keep_filter {
self.clear_fetched_leaves(half);
}
self.private_fetches[half] = false;
if half == 0 {
@@ -318,6 +311,28 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
}
/// 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
@@ -584,7 +599,12 @@ impl<H: Host, D: Devices> Machine<H, D> {
let started = self.whole_tlbi_clock();
let live =
!self.fill_log.is_empty() || self.spaces.iter().any(|spaces| spaces.len() != 0);
self.forget_spaces(0..=1, 1);
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));
}
@@ -308,7 +308,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
let walk = self.cached_fetch(pc);
let global = walk.is_none_or(|walk| walk.global);
let shared = walk.is_some_and(|walk| walk.global);
self.take_page(pc, key, Taken::Fetch, global, shared);
let record = self.fetch_record(pc);
self.take_page(pc, key, Taken::Fetch, global, shared, record);
}
/// [`Self::translate_page`] for the fetch at `pc` of the frame
@@ -318,7 +319,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
pub(super) fn translate_leaf(&mut self, pc: u64, key: u64, physical: u64, current: Variant) {
self.translate_page(pc, key);
if let Some(walk) = self.cached_fetch(pc) {
self.take_leaf_pages(pc, physical, walk.size, current, walk.global);
let record = self.fetch_record(pc);
self.take_leaf_pages(pc, physical, walk.size, current, walk.global, record);
}
}
@@ -332,7 +334,8 @@ impl<H: Host, D: Devices> Machine<H, D> {
/// the ITLB holds already are left to their own fetch. A TLBI by VA of
/// any of them reaches all: the fetch recorded the whole leaf
/// (`fetched_through`). `current` is the fetch's variant before each
/// page's own (`page_variant`).
/// page's own (`page_variant`). `record` is the walk's, which each
/// page's entry is kept with (`tlbi_keep.rs`).
fn take_leaf_pages(
&mut self,
pc: u64,
@@ -340,6 +343,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
size: u64,
current: Variant,
global: bool,
record: Option<tlbi_keep::WalkRecord>,
) {
let span = size.min(LEAF_FILL);
if span <= FETCH_PAGE {
@@ -361,7 +365,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
continue;
};
let key = self.block_key(other_frame, id);
self.take_page(other, key, Taken::Leaf, global, global);
self.take_page(other, key, Taken::Leaf, global, global, record);
}
}
@@ -369,11 +373,26 @@ impl<H: Host, D: Devices> Machine<H, D> {
/// was `taken` ([`Taken`]). `global` marks a page whose walk ended in
/// a global leaf ([`chain::LookupEntry::global_page`]), or may have;
/// `shared` puts a lower-half page whose walk did in the context every
/// address space shares ([`Self::itlb_context`]).
fn take_page(&mut self, pc: u64, key: u64, taken: Taken, global: bool, shared: bool) {
/// address space shares ([`Self::itlb_context`]). With `--tlbi-keep on`
/// the entry is kept with `record`, the walk it came from, or its
/// context marked unverifiable without one (`tlbi_keep.rs`).
fn take_page(
&mut self,
pc: u64,
key: u64,
taken: Taken,
global: bool,
shared: bool,
record: Option<tlbi_keep::WalkRecord>,
) {
debug_assert!(global || !shared, "only a global page is shared");
let half = chain::half(pc);
let context = self.itlb_context(pc, shared);
// No context until a fetch takes its own (`keep_spaces`): an entry
// there would be found by every later run in it.
if context == contexts::VOID {
return;
}
let page = pc & !(FETCH_PAGE - 1);
let slot = self.itlb.page_slot(pc, context);
let entry = match global {
@@ -382,6 +401,9 @@ impl<H: Host, D: Devices> Machine<H, D> {
};
let held = self.itlb.find(slot, page, context);
if held == entry {
if self.tlbi_keep.on && record.is_some() {
self.note_kept_fill(page, context, record);
}
return;
}
let held_page = held.pc == page && held.key == context;
@@ -441,6 +463,9 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
self.itlb.insert_over(slot, entry, &dead);
}
if self.tlbi_keep.on {
self.note_kept_fill(page, context, record);
}
}
/// Why the ITLB lacked the page `page` in `context`, whose
@@ -727,9 +752,23 @@ impl<H: Host, D: Devices> Machine<H, D> {
let variant = self.page_variant(current, walk.physical);
if let Some(id) = self.known_variant(variant) {
let key = self.block_key(walk.physical, id);
self.take_page(pc, key, Taken::Refill, walk.global, walk.global);
self.take_page(
pc,
key,
Taken::Refill,
walk.global,
walk.global,
walk.record,
);
}
self.take_leaf_pages(pc, walk.physical, walk.size, current, walk.global);
self.take_leaf_pages(
pc,
walk.physical,
walk.size,
current,
walk.global,
walk.record,
);
}
}
@@ -22,6 +22,18 @@ pub(super) const UPPER_CONTEXTS: usize = 256;
const SLOT_BITS: u32 = 12;
const SLOT_MASK: u64 = (1 << SLOT_BITS) - 1;
const _: () = assert!(LOWER_CONTEXTS <= 1 << SLOT_BITS && UPPER_CONTEXTS <= 1 << SLOT_BITS);
/// The context native code runs in between a TLBI of everything that keeps
/// the contexts and the next fetch, which verifies the one it runs in
/// ([`super::tlbi_keep`]): made 0th (the first context made is the 1st, so
/// no context has this number), in a slot past every half's capacity (so
/// none is live), it names no ITLB entry, stamp or jump cache entry, and the
/// engine puts none in it.
pub(super) const VOID: u64 = SLOT_MASK << chain::LOOKUP_SALT_BITS;
const _: () = assert!(max(LOWER_CONTEXTS, UPPER_CONTEXTS) < SLOT_MASK as usize);
/// The larger of `a` and `b`, in a constant.
const fn max(a: usize, b: usize) -> usize {
if a > b { a } else { b }
}
/// No slot, in the recency list.
const NONE: u32 = u32::MAX;
@@ -51,6 +63,12 @@ pub(super) struct Space {
/// The ASID of its non-global translations ([`mmu::current_asid`]).
pub(super) asid: u16,
pub(super) regime: mmu::Regime,
/// Kept across a TLBI of everything (`--tlbi-keep on`) and not verified
/// since ([`super::tlbi_keep`]): its number names ITLB entries no lookup
/// may use until each is checked against the tables again, so
/// [`Contexts::find`] does not give it, nor do the native paths, which
/// take their numbers from `find` alone.
pub(super) kept: bool,
}
/// A half's contexts.
@@ -100,13 +118,53 @@ impl Contexts {
}
/// The number of the context of `key`, which becomes the most recently
/// used.
/// used; none for a context kept across a TLBI of everything and not
/// verified since ([`Space::kept`], [`Self::kept`]).
pub(super) fn find(&mut self, key: &Key) -> Option<u64> {
let slot = *self.keys.get(key)?;
if self.spaces[slot as usize].kept {
return None;
}
self.touch(slot);
Some(self.spaces[slot as usize].number)
}
/// The number of the context of `key` while it is kept and unverified
/// ([`Space::kept`]).
pub(super) fn kept(&self, key: &Key) -> Option<u64> {
let slot = *self.keys.get(key)?;
let space = &self.spaces[slot as usize];
space.kept.then_some(space.number)
}
/// Mark every context kept and unverified, at a TLBI of everything that
/// keeps them: how many there are.
pub(super) fn keep_all(&mut self) -> usize {
for &slot in self.keys.values() {
self.spaces[slot as usize].kept = true;
}
self.keys.len()
}
/// The kept context `number` was verified: [`Self::find`] gives it
/// again, and it becomes the most recently used.
pub(super) fn confirm(&mut self, number: u64) {
let slot = number_slot(number);
if self.live(number).is_some() {
self.spaces[slot].kept = false;
self.touch(slot as u32);
}
}
/// Remove the context `number`: whether it was live.
pub(super) fn remove_number(&mut self, number: u64) -> bool {
let live = self.live(number).is_some();
if live {
self.remove(number_slot(number) as u32);
}
live
}
/// Make a context of `key`, numbered by `number` from its slot: the
/// most recently used. Past the capacity the least recently used goes
/// first, which this returns.
@@ -132,6 +190,7 @@ impl Contexts {
number: 0,
asid,
regime,
kept: false,
});
self.older.push(NONE);
self.newer.push(NONE);
@@ -145,6 +204,7 @@ impl Contexts {
number,
asid,
regime,
kept: false,
};
self.keys.insert(key, slot);
self.link_newest(slot);
@@ -179,6 +239,7 @@ impl Contexts {
let space = &mut self.spaces[slot as usize];
self.keys.remove(&space.key);
space.number = 0;
space.kept = false;
self.unlink(slot);
self.free.push(slot);
}
@@ -271,4 +332,28 @@ mod tests {
assert!(contexts.live(fourth).is_none());
assert!(contexts.live(0).is_none());
}
/// A kept context stays live, but `find` does not give it until it is
/// confirmed; a removed one is gone, and its key is made again anew.
#[test]
fn a_kept_context_is_found_only_once_confirmed() {
let mut contexts = Contexts::new(4);
let mut made = 0;
let (one, _) = insert(&mut contexts, 1, &mut made);
let (two, _) = insert(&mut contexts, 2, &mut made);
assert_eq!(contexts.keep_all(), 2);
assert_eq!(contexts.find(&key(1)), None);
assert_eq!(contexts.kept(&key(1)), Some(one));
assert!(contexts.live(one).is_some_and(|space| space.kept));
contexts.confirm(one);
assert_eq!(contexts.find(&key(1)), Some(one));
assert_eq!(contexts.kept(&key(1)), None);
assert!(contexts.remove_number(two));
assert!(!contexts.remove_number(two));
assert_eq!(contexts.kept(&key(2)), None);
assert_eq!(contexts.find(&key(2)), None);
let (again, _) = insert(&mut contexts, 2, &mut made);
assert_ne!(again, two);
assert_eq!(contexts.find(&key(2)), Some(again));
}
}
+56 -13
View File
@@ -171,9 +171,15 @@ impl<H: Host, D: Devices> Machine<H, D> {
let (controls, hcr) = self.half_inputs(half, el);
let frame = self.context_frame(controls, hcr);
let key = context_key(&controls, frame, el, variant);
// A context kept across a TLBI of everything is verified before its
// number is given to anything (`tlbi_keep.rs`); one that cannot be
// goes, and the key's context is made anew.
let number = match self.spaces[half].find(&key) {
Some(number) => number,
None => self.make_context(half, key, &controls),
None => match self.spaces[half].kept(&key) {
Some(kept) if self.verify_kept(half, el, variant, kept) => kept,
_ => self.make_context(half, key, &controls),
},
};
self.salt_clock += 1;
self.salt_uses[(number % chain::LOOKUP_SALTS as u64) as usize] = self.salt_clock;
@@ -386,8 +392,24 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
let requester = self.cpu.requester();
let controls = self.cpu.controls(self.cpu.regime());
let mut tables = RamTables(&mut self.host);
match mmu::translate(&controls, pc, Access::Execute, requester, &mut tables) {
// With `--tlbi-keep on` the walk's reads are kept with its cache
// entry, for the ITLB entries it fills (`tlbi_keep.rs`).
let mut reads = None;
let outcome = if self.tlbi_keep.on {
let mut tables = tlbi_keep::RecordingTables::new(&mut self.host);
let outcome = mmu::translate(&controls, pc, Access::Execute, requester, &mut tables);
reads = Some(tables.reads);
outcome
} else {
mmu::translate(
&controls,
pc,
Access::Execute,
requester,
&mut RamTables(&mut self.host),
)
};
match outcome {
Translated::Mapped(_) if !self.host.fetch_permitted(pc) => {
let fault =
mmu::Fault::stage1(mmu::FaultKind::Permission, HOST_REFUSED_FETCH_LEVEL);
@@ -407,7 +429,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
}
self.fetched_through(half, pc, translation.size, translation.global);
let physical = translation.physical & !(FETCH_PAGE - 1);
self.fetch[slot] = Some(FetchEntry {
let entry = FetchEntry {
page,
physical,
guarded: translation.guarded,
@@ -415,7 +437,11 @@ impl<H: Host, D: Devices> Machine<H, D> {
size: translation.size,
el,
epoch: self.fetch_epoch(half),
});
};
self.fetch[slot] = Some(entry);
if let Some(reads) = reads {
self.note_fetch_walk(slot, entry, &reads, &translation, controls.ttbr0);
}
Ok(translation.physical)
}
Translated::Fault(fault)
@@ -472,14 +498,30 @@ impl<H: Host, D: Devices> Machine<H, D> {
pc: u64,
walk: &mut QuietWalk,
) -> Option<QuietFetch> {
let mut tables = RamTables(&mut self.host);
let Translated::Mapped(translation) = walk.memo.translate(
&walk.controls,
pc,
Access::Execute,
walk.requester,
&mut tables,
) else {
// With `--tlbi-keep on` an entry needs the walk's every read, which a
// walk from the memo's table leaves out: it walks in full.
let mut reads = None;
let outcome = if self.tlbi_keep.on {
let mut tables = tlbi_keep::RecordingTables::new(&mut self.host);
let outcome = mmu::translate(
&walk.controls,
pc,
Access::Execute,
walk.requester,
&mut tables,
);
reads = Some(tables.reads);
outcome
} else {
walk.memo.translate(
&walk.controls,
pc,
Access::Execute,
walk.requester,
&mut RamTables(&mut self.host),
)
};
let Translated::Mapped(translation) = outcome else {
return None;
};
if !self.host.fetch_permitted(pc) {
@@ -495,6 +537,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
guarded: translation.guarded,
global: translation.global,
size: translation.size,
record: reads.and_then(|reads| reads.record(pc, &translation, walk.controls.ttbr0)),
})
}
@@ -725,6 +725,8 @@ pub struct Counts {
pub whole_tlbi_times: [u64; 3],
/// ([`super::Statistics::whole_tlbi_trigger`]).
pub whole_tlbi_trigger: super::WholeTlbiTrigger,
/// ([`super::Statistics::tlbi_keep`]).
pub tlbi_keep: super::TlbiKeepCounts,
/// 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
@@ -2878,6 +2880,7 @@ impl<H: Host, D: Devices> Machine<H, D> {
whole_tlbi_sites: statistics.whole_tlbi_sites,
whole_tlbi_times: statistics.whole_tlbi_times,
whole_tlbi_trigger: statistics.whole_tlbi_trigger,
tlbi_keep: statistics.tlbi_keep,
transitions: [
statistics.native_transitions[stela_compiler::x86_64::transition::GUARDED_ENTER],
statistics.engine_transitions[stela_compiler::x86_64::transition::GUARDED_ENTER],
@@ -628,6 +628,9 @@ pub struct Statistics {
pub whole_tlbi_times: [u64; 3],
/// What came before those TLBIs ([`WholeTlbiTrigger`]).
pub whole_tlbi_trigger: WholeTlbiTrigger,
/// What keeping the contexts across those TLBIs did (`--tlbi-keep on`,
/// [`TlbiKeepCounts`]).
pub tlbi_keep: TlbiKeepCounts,
pub compiled: u64,
/// Of `compiled`, the blocks that run their iterations inside
/// themselves (`CompiledBlock::self_loop`).
@@ -881,6 +884,70 @@ impl WholeTlbiTrigger {
}
}
/// The mismatches a [`TlbiKeepCounts`] keeps.
pub const TLBI_KEEP_SAMPLES: usize = 4;
/// What one PE's keeping of its lookup contexts across TLBIs of everything
/// did (`--tlbi-keep on`, `tlbi_keep.rs`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(
all(feature = "std", feature = "native-profile"),
derive(serde::Serialize)
)]
pub struct TlbiKeepCounts {
/// TLBIs of everything that kept the contexts, and the contexts they
/// marked unverified.
pub tlbis: u64,
pub contexts: u64,
/// Kept contexts verified at their next fetch, and those forgotten
/// instead: an ITLB entry of theirs had no walk record, or the fetch
/// ran in another state than their key's.
pub verified: u64,
pub forgotten: u64,
/// ITLB entries verification kept, and those it dropped (a descriptor,
/// the TTBR0 of a lower-half page, the host's fetch permission or the
/// entry's block key no longer what the walk recorded).
pub kept: u64,
pub dropped: u64,
/// Under `--tlbi-verify-check`: the kept entries walked again in full,
/// and those whose walk gave something else, which were dropped.
pub checked: u64,
pub mismatches: u64,
/// Counter ticks spent verifying.
pub ticks: u64,
/// The first mismatches: the page, the context, the ITLB entry's block
/// key and the frame the walk gave (`u64::MAX` for none); `[0; 4]` none.
pub samples: [[u64; 4]; TLBI_KEEP_SAMPLES],
}
impl TlbiKeepCounts {
/// Count a mismatch, keeping the first few.
pub fn mismatch(&mut self, sample: [u64; 4]) {
if let Some(free) = self.samples.iter_mut().find(|held| **held == [0; 4]) {
*free = sample;
}
self.mismatches += 1;
}
/// Add `other`'s counts, and its samples where room is left.
pub fn add(&mut self, other: &Self) {
self.tlbis += other.tlbis;
self.contexts += other.contexts;
self.verified += other.verified;
self.forgotten += other.forgotten;
self.kept += other.kept;
self.dropped += other.dropped;
self.checked += other.checked;
self.mismatches += other.mismatches;
self.ticks += other.ticks;
for &sample in other.samples.iter().filter(|sample| **sample != [0; 4]) {
if let Some(free) = self.samples.iter_mut().find(|held| **held == [0; 4]) {
*free = sample;
}
}
}
}
/// [`MailWait`]'s parts.
pub const MAIL_WAITS: usize = MailWait::LongestNative as usize + 1;
@@ -916,6 +983,7 @@ impl core::ops::AddAssign for Statistics {
whole_tlbi_sites,
whole_tlbi_times,
whole_tlbi_trigger,
tlbi_keep,
compiled,
self_loops,
regions,
@@ -1075,6 +1143,7 @@ impl core::ops::AddAssign for Statistics {
*total += count;
}
self.whole_tlbi_trigger.add(&whole_tlbi_trigger);
self.tlbi_keep.add(&tlbi_keep);
for (total, count) in self.record_misses.iter_mut().zip(record_misses) {
*total += count;
}
@@ -10540,6 +10540,7 @@ mod table_base;
mod tagged;
mod thread_switch;
mod timer_native;
mod tlbi_keep;
#[test]
fn host_work_holds_the_shared_count_only_for_a_pe_stopped_in_the_kernel() {
@@ -806,8 +806,20 @@ fn a_whole_tlbi_refill_walks_from_the_leaf_table_and_takes_what_full_walks_give(
/// 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).
/// With `--tlbi-keep on` (`tlbi_keep.rs`) they run in `tests/tlbi_keep.rs`,
/// with the check and under the mutation that keeps without verifying.
#[test]
fn after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives() {
let (failed, _) = whole_tlbi_acceptance(&|_| {});
assert!(failed.is_empty(), "{failed:#?}");
}
/// The scenarios of [`after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives`],
/// each on a machine `configure` sets up before its first fetch: what failed,
/// and what keeping the contexts did on all of them.
pub(super) fn whole_tlbi_acceptance(
configure: &dyn Fn(&mut Machine<FakeHost, NoDevices>),
) -> (Vec<String>, TlbiKeepCounts) {
use mmu::tlbi::{Everywhere, Reach};
const RET: u32 = 0xd65f_03c0;
const NG: u64 = 1 << 11;
@@ -842,6 +854,7 @@ fn after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives() {
words[frame * 0x400] = RET;
}
let mut machine = machine(&words);
configure(&mut machine);
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
for page in 0..FRAMES {
map(&mut machine, l3, page, frame(page));
@@ -920,6 +933,7 @@ fn after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives() {
}),
];
let mut failed = Vec::new();
let mut kept = TlbiKeepCounts::default();
for (name, scenario) in scenarios {
let (mut machine, keys) = start();
for (what, ran, expected) in scenario(&mut machine, &keys) {
@@ -929,8 +943,9 @@ fn after_a_whole_tlbi_every_fetch_runs_what_its_walk_now_gives() {
));
}
}
kept.add(&machine.statistics.tlbi_keep);
}
assert!(failed.is_empty(), "{failed:#?}");
(failed, kept)
}
/// A machine running `words` at BASE through 4 KiB pages of address
@@ -0,0 +1,623 @@
//! `--tlbi-keep on` (`tlbi_keep.rs`): a TLBI of everything keeps the lookup
//! contexts, and a fetch runs only what its walk now gives. Each machine
//! here runs with `--tlbi-verify-check` too, whose count of mismatches must
//! stay zero: a mismatch is an entry verification kept that a full walk
//! contradicts. Expectations are a full walk of the machine's own tables at
//! the fetch ([`walk`]), never what the test thinks it changed.
use super::process_switching::whole_tlbi_acceptance;
use super::*;
use mmu::tlbi::{Everywhere, Reach};
type M = Machine<FakeHost, NoDevices>;
const RET: u32 = 0xd65f_03c0;
const NG: u64 = 1 << 11;
const MSR_TTBR0_EL1_X0: u32 = 0xd518_2000;
/// Frames 0 to 3, each a page with a RET.
const FRAMES: u64 = 4;
fn frame(n: u64) -> u64 {
BASE + n * 0x1000
}
fn pc(page: u64) -> u64 {
BASE + page * 0x1000
}
/// Space `space` selected by TTBR0_EL1 with `asid`.
fn 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();
}
/// Space `space`'s level 3 entry of page `page`: `frame`, private (nG) unless
/// `global`.
fn map(machine: &mut M, space: usize, page: u64, frame: u64, global: bool) {
let [_, _, l3] = SPACES_TABLES[space];
let ng = if global { 0 } else { NG };
write_entry(machine, l3 + page * 8, page_descriptor(frame, false) | ng);
}
fn all(machine: &mut M) {
machine.tlb_maintained(Reach::All, Everywhere::All, None);
}
/// A TLBI by VA of the page at `va`, of every ASID.
fn page_tlbi(machine: &mut M, va: u64) {
let reach = Reach::Containing(va);
machine.tlb_maintained(reach, Everywhere::Addresses(reach), None);
}
/// What a fetch of `pc` runs: its page's block key, or None for a fault.
fn 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"),
}
}
/// What a full walk of `pc` in the machine's state gives now, as the key of
/// the frame it translates to (`keys`, by frame), or None for a fault.
fn walk(machine: &mut M, keys: &[u64], pc: u64) -> Option<u64> {
let controls = machine.cpu.controls(machine.cpu.regime());
let requester = machine.cpu.requester();
let walked = mmu::translate(
&controls,
pc,
Access::Execute,
requester,
&mut RamTables(&mut machine.host),
);
match walked {
Translated::Mapped(translation) if machine.host.fetch_permitted(pc) => {
let frame = (translation.physical - BASE) / 0x1000;
Some(*keys.get(frame as usize).expect("a frame with a key"))
}
_ => None,
}
}
/// `run` and `walk` agree at `pc`: what it ran.
#[track_caller]
fn runs_its_walk(machine: &mut M, keys: &[u64], pc: u64) -> Option<u64> {
let ran = run(machine, pc);
assert_eq!(ran, walk(machine, keys, pc), "{pc:#x}");
ran
}
/// A machine keeping its contexts with the check on, space 0 mapping page
/// `n` at frame `n` (private to ASID 1, or `global`), each page run once,
/// and each frame's key.
fn kept(global: bool) -> (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);
machine.set_tlbi_keep(true, true);
assert_eq!(machine.tlbi_keep(), (true, true));
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
for page in 0..FRAMES {
map(&mut machine, 0, page, frame(page), global);
}
select(&mut machine, 0, 1);
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
(machine, keys)
}
/// No kept entry was contradicted by its full walk.
#[track_caller]
fn no_mismatches(machine: &M) {
let counts = machine.statistics.tlbi_keep;
assert_eq!(counts.mismatches, 0, "{counts:#?}");
assert_eq!(counts.checked, counts.kept, "{counts:#?}");
}
/// The acceptance set passes with the contexts kept, with and without the
/// check; the check finds nothing to drop; the keep did keep and drop.
#[test]
fn the_acceptance_set_passes_with_the_contexts_kept() {
for check in [false, true] {
let (failed, counts) = whole_tlbi_acceptance(&|machine| machine.set_tlbi_keep(true, check));
assert!(failed.is_empty(), "check {check}: {failed:#?}");
assert!(counts.tlbis >= 5, "{counts:#?}");
assert!(counts.verified > 0 && counts.kept > 0, "{counts:#?}");
assert!(
counts.dropped >= 5,
"every scenario drops a page: {counts:#?}"
);
assert_eq!(counts.mismatches, 0, "{counts:#?}");
assert_eq!(counts.checked, if check { counts.kept } else { 0 });
}
}
/// The mutation "keep without verifying": every scenario of the acceptance
/// set fails.
#[test]
fn the_acceptance_set_fails_where_kept_contexts_go_unverified() {
let (failed, _) = whole_tlbi_acceptance(&|machine| {
machine.set_tlbi_keep(true, false);
machine.tlbi_keep.unverified = true;
});
for name in [
"remapped page",
"unmapped page",
"execute-never page",
"reused TTBR0 and ASID",
"one VA in two spaces",
] {
assert!(
failed.iter().any(|failure| failure.starts_with(name)),
"{name} passed unverified: {failed:#?}"
);
}
}
/// Without `--tlbi-keep on` nothing is kept: the contexts are made anew.
#[test]
fn the_keep_is_off_by_default() {
let mut machine = machine(&[RET]);
assert_eq!(machine.tlbi_keep(), (false, false));
paged_space(&mut machine, 0, &[BASE]);
run(&mut machine, BASE);
let before = machine.chain.contexts();
all(&mut machine);
run(&mut machine, BASE);
assert_ne!(machine.chain.contexts()[0], before[0]);
assert_eq!(machine.statistics.tlbi_keep, TlbiKeepCounts::default());
}
/// ITLB drop epoch of `half` ([`chain::ITLB_DROPS`]).
fn drop_epoch(machine: &M, half: usize) -> u64 {
let at =
(machine.itlb.address() as i64 + i64::from(chain::ITLB_DROPS)) as u64 + 8 * half as u64;
// SAFETY: the ITLB's header words precede its first slot, live while
// the machine does, and only this thread writes them.
unsafe { (at as *const u64).read() }
}
/// Between the TLBI and the verifying fetch nothing native can reach a kept
/// context: the chain runs in the void context, every stamp and jump cache
/// entry is void with its drop epoch, and neither the transition records
/// nor the TTBR0 switch table can take its number (`live_contexts`). The
/// fetch then verifies it and runs in it again, under its old number.
#[test]
fn native_code_reaches_no_kept_context_before_its_verification() {
let (mut machine, keys) = kept(false);
let before = machine.chain.contexts();
let epochs = [0, 1].map(|half| drop_epoch(&machine, half));
let switches = machine.mirrors.table_switch.generation;
let el = machine.cpu.pstate.el;
let variant = machine.current_variant(false, false);
assert_eq!(machine.live_contexts(el, variant), Some(before));
all(&mut machine);
assert_eq!(machine.chain.contexts(), [contexts::VOID; 2]);
for (half, &epoch) in epochs.iter().enumerate() {
assert!(drop_epoch(&machine, half) > epoch, "half {half}");
}
assert_ne!(machine.mirrors.table_switch.generation, switches);
assert_eq!(machine.live_contexts(el, variant), None);
for page in 0..FRAMES {
assert_eq!(machine.current_key(pc(page)), None);
}
assert_eq!(runs_its_walk(&mut machine, &keys, pc(1)), Some(keys[1]));
assert_eq!(machine.chain.contexts(), before);
assert_eq!(machine.live_contexts(el, variant), Some(before));
// Every other page was kept without a walk.
for page in [0, 2, 3] {
assert_eq!(machine.current_key(pc(page)), Some(keys[page as usize]));
}
assert_eq!(machine.statistics.tlbi_keep.dropped, 0);
assert_eq!(machine.statistics.tlbi_keep.kept, FRAMES);
no_mismatches(&machine);
}
/// A descriptor changed and changed back before the TLBI holds its old
/// value: the entry is the walk's and stays. Changed, flushed and run, then
/// changed back and flushed, each fetch runs the walk of its time.
#[test]
fn a_descriptor_changed_and_back_runs_its_walk() {
let (mut machine, keys) = kept(false);
map(&mut machine, 0, 1, frame(2), false);
map(&mut machine, 0, 1, frame(1), false);
all(&mut machine);
assert_eq!(runs_its_walk(&mut machine, &keys, pc(1)), Some(keys[1]));
assert_eq!(machine.statistics.tlbi_keep.dropped, 0);
map(&mut machine, 0, 1, frame(2), false);
all(&mut machine);
assert_eq!(runs_its_walk(&mut machine, &keys, pc(1)), Some(keys[2]));
map(&mut machine, 0, 1, frame(1), false);
all(&mut machine);
assert_eq!(runs_its_walk(&mut machine, &keys, pc(1)), Some(keys[1]));
for page in 0..FRAMES {
runs_its_walk(&mut machine, &keys, pc(page));
}
assert_eq!(machine.statistics.tlbi_keep.dropped, 2);
no_mismatches(&machine);
}
/// A level 3 table freed and its page reused for another table: the level 2
/// entry names a new table (other mappings), and the old page holds another
/// space's entries; or the level 2 entry stays and its page's contents are
/// another table's.
#[test]
fn a_table_page_freed_and_reused_runs_its_walk() {
const NEW_TABLE: u64 = 0x9000;
let [_, l2, l3] = SPACES_TABLES[0];
for keep_level2 in [false, true] {
let (mut machine, keys) = kept(false);
let (table, other) = if keep_level2 {
(l3, l3)
} else {
write_entry(&mut machine, l2, (BASE + NEW_TABLE) | 0b11);
(NEW_TABLE, l3)
};
for page in 0..FRAMES {
write_entry(
&mut machine,
table + page * 8,
page_descriptor(frame(FRAMES - 1 - page), false) | NG,
);
if other != table {
// The old page, another space's table now.
write_entry(
&mut machine,
other + page * 8,
page_descriptor(frame((page + 1) % FRAMES), false) | NG,
);
}
}
all(&mut machine);
for page in 0..FRAMES {
let ran = runs_its_walk(&mut machine, &keys, pc(page));
assert_eq!(ran, Some(keys[(FRAMES - 1 - page) as usize]));
}
no_mismatches(&machine);
}
}
/// A 2 MiB block split into a level 3 table that maps one page elsewhere:
/// every page runs the new walk, and the block's entries, a leaf fill's
/// among them, go.
#[test]
fn a_block_split_into_a_table_runs_its_walk() {
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);
machine.set_tlbi_keep(true, true);
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
let [_, l2, l3] = SPACES_TABLES[0];
for page in 0..FRAMES {
map(&mut machine, 0, page, frame(page), false);
}
select(&mut machine, 0, 1);
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
// The block, of the same frames.
write_entry(&mut machine, l2, BASE | 1 << 10 | 3 << 8 | NG | 0b01);
all(&mut machine);
for page in 0..FRAMES {
assert_eq!(
runs_its_walk(&mut machine, &keys, pc(page)),
Some(keys[page as usize])
);
}
// Split: page 0 moves to frame 2.
write_entry(&mut machine, l2, (BASE + l3) | 0b11);
map(&mut machine, 0, 0, frame(2), false);
all(&mut machine);
assert_eq!(runs_its_walk(&mut machine, &keys, pc(0)), Some(keys[2]));
for page in 1..FRAMES {
assert_eq!(
runs_its_walk(&mut machine, &keys, pc(page)),
Some(keys[page as usize])
);
}
assert!(machine.statistics.tlbi_keep.dropped >= FRAMES);
no_mismatches(&machine);
}
/// Only permissions change: UXN (no effect on an EL1 fetch), AP read-only
/// (none either), AP writable at EL0 (privileged execute-never) and PXN.
/// Each page runs what its walk gives, faults included.
#[test]
fn a_permission_change_runs_its_walk() {
const AP_EL0: u64 = 1 << 6;
const AP_READ_ONLY: u64 = 1 << 7;
const UXN: u64 = 1 << 54;
const PXN: u64 = 1 << 53;
let (mut machine, keys) = kept(false);
let [_, _, l3] = SPACES_TABLES[0];
for (page, bits) in [(0, UXN), (1, AP_READ_ONLY), (2, AP_EL0), (3, PXN)] {
write_entry(
&mut machine,
l3 + page * 8,
page_descriptor(frame(page), false) | NG | bits,
);
}
all(&mut machine);
let ran: Vec<Option<u64>> = (0..FRAMES)
.map(|page| runs_its_walk(&mut machine, &keys, pc(page)))
.collect();
assert_eq!(ran[0], Some(keys[0]));
assert_eq!(ran[3], None, "PXN faults");
assert_eq!(machine.statistics.tlbi_keep.dropped, FRAMES);
no_mismatches(&machine);
}
/// The host's answer to `fetch_permitted` is in no descriptor: a page it
/// refuses after the TLBI faults, though its tables are unchanged.
#[test]
fn a_page_the_host_refuses_after_the_tlbi_faults() {
let (mut machine, keys) = kept(false);
machine.host.refused.push(pc(2));
all(&mut machine);
for page in 0..FRAMES {
let ran = runs_its_walk(&mut machine, &keys, pc(page));
assert_eq!(ran.is_none(), page == 2, "page {page}");
}
assert_eq!(machine.statistics.tlbi_keep.dropped, 1);
no_mismatches(&machine);
}
/// A frame whose blocks take another variant (it needs the translated one)
/// under unchanged tables: the kept entry's block key is the old variant's,
/// which a fill would not make now, so it goes, and the fetch runs the new
/// variant's block.
#[test]
fn a_frame_whose_variant_changed_runs_its_new_variant() {
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);
machine.host.placement = mmu::placement::Placement::four_level(2).unwrap();
machine.host.translation_helper = Some(0x1000);
machine.derived_changed();
machine.set_tlbi_keep(true, true);
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
for page in 0..FRAMES {
map(&mut machine, 0, page, frame(page), false);
}
select(&mut machine, 0, 1);
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
// Only the variant input changes: no IC maintenance tells the ITLB.
machine.translated_pages.insert(frame(1));
all(&mut machine);
let ran = run(&mut machine, pc(1)).expect("mapped");
assert_ne!(ran, keys[1], "the old variant's key was kept");
let Ok(Fetched::Block(block)) = machine.fetch_block(pc(1), false) else {
panic!("a block");
};
assert!(machine.variants[machine.code.blocks[block].variant.0 as usize].translated);
for page in [0, 2, 3] {
assert_eq!(run(&mut machine, pc(page)), Some(keys[page as usize]));
}
assert_eq!(machine.statistics.tlbi_keep.dropped, 1);
no_mismatches(&machine);
}
/// An ASID a new process takes again, with the same VA layout but tables of
/// its own (another TTBR0 base): its pages run its frames, whether they are
/// private (its own context) or global (the upper half's context holds the
/// lower half's global pages, which the TTBR0 check keeps apart).
#[test]
fn an_asid_reused_with_the_same_layout_runs_its_walk() {
for global in [false, true] {
let (mut machine, keys) = kept(global);
paged_space(
&mut machine,
1,
&(0..FRAMES)
.map(|n| frame((n + 2) % FRAMES))
.collect::<Vec<_>>(),
);
for page in 0..FRAMES {
map(&mut machine, 1, page, frame((page + 2) % FRAMES), global);
}
select(&mut machine, 0, 1);
// The first process exits; its ASID goes to the next, after a flush.
all(&mut machine);
select(&mut machine, 1, 1);
for page in 0..FRAMES {
assert_eq!(
runs_its_walk(&mut machine, &keys, pc(page)),
Some(keys[((page + 2) % FRAMES) as usize]),
"global {global}, page {page}"
);
}
no_mismatches(&machine);
}
}
/// A stage-2 change under an unchanged stage 1: the EL1&0 regime with
/// HCR_EL2.VM maps the IPA space through a 1 GiB stage-2 block, then the
/// block is made execute-never, and a fetch faults.
#[test]
fn a_stage2_change_runs_its_walk() {
// 4 KiB, 40-bit IPA from level 1 with two concatenated tables, 48-bit PS.
const VTCR_4K: u64 = 24 | 1 << 6 | 5 << 16 | 1 << 31;
const LEVEL1: u64 = 0x6000;
const HCR_VM: u64 = 1;
const XN: u64 = 1 << 54;
let block = |xn: u64| BASE | 1 << 10 | 3 << 8 | 3 << 6 | 0xf << 2 | xn | 0b01;
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);
machine.set_tlbi_keep(true, true);
paged_space(&mut machine, 0, &(0..FRAMES).map(frame).collect::<Vec<_>>());
for page in 0..FRAMES {
map(&mut machine, 0, page, frame(page), false);
}
let entry = LEVEL1 + ((BASE >> 30) & 0x3ff) * 8;
write_entry(&mut machine, entry, block(0));
let registers = &mut machine.cpu.registers;
let hcr = registers.get(SystemRegister::HCR_EL2, 0);
registers.set(SystemRegister::VTCR_EL2, 0, VTCR_4K);
registers.set(SystemRegister::VTTBR_EL2, 0, BASE + LEVEL1);
registers.set(SystemRegister::HCR_EL2, 0, hcr | HCR_VM);
machine.translations_changed();
select(&mut machine, 0, 1);
assert!(machine.cpu.stage2(machine.cpu.regime()), "stage 2 applies");
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
// Stage 1 is unchanged: every entry stays.
all(&mut machine);
for page in 0..FRAMES {
assert_eq!(
runs_its_walk(&mut machine, &keys, pc(page)),
Some(keys[page as usize])
);
}
assert_eq!(machine.statistics.tlbi_keep.dropped, 0);
assert!(machine.statistics.tlbi_keep.kept >= FRAMES);
write_entry(&mut machine, entry, block(XN));
all(&mut machine);
for page in 0..FRAMES {
assert_eq!(runs_its_walk(&mut machine, &keys, pc(page)), None);
}
no_mismatches(&machine);
}
/// A seeded xorshift.
struct Draws(u64);
impl Draws {
fn next(&mut self, below: u64) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0 % below
}
}
/// Two machines, one forgetting at a TLBI of everything and one keeping
/// with the check, take one random sequence: descriptor rewrites in either
/// space (another frame, private or global, unmapped, PXN), each followed by
/// a TLBI by VA or of everything; TLBIs of everything alone; address-space
/// switches with ASID reuse, flushed as XNU flushes (the global mappings of
/// the two spaces differ, or the ASID last served another space); and
/// fetches. Every fetch of both runs what its walk gives, and the two agree.
#[test]
fn kept_and_forgotten_contexts_run_alike_across_random_table_changes() {
const STEPS: usize = 2500;
let mut words = vec![0u32; (FRAMES * 0x1000 / 4) as usize];
for frame in 0..FRAMES as usize {
words[frame * 0x400] = RET;
}
let make = |keep: bool| {
let mut machine = machine(&words);
machine.set_tlbi_keep(keep, keep);
for space in [1, 0] {
paged_space(
&mut machine,
space,
&(0..FRAMES).map(frame).collect::<Vec<_>>(),
);
for page in 0..FRAMES {
map(&mut machine, space, page, frame(page), false);
}
}
select(&mut machine, 0, 1);
let keys: Vec<u64> = (0..FRAMES)
.map(|page| run(&mut machine, pc(page)).expect("mapped"))
.collect();
(machine, keys)
};
let mut totals = TlbiKeepCounts::default();
for seed in [0x9e37_79b9_7f4a_7c15u64, 7, 0x1234_5678, 0xdead_beef_cafe] {
let (mut forgetting, forgetting_keys) = make(false);
let (mut keeping, keeping_keys) = make(true);
let mut draws = Draws(seed);
// The model's descriptors, by space and page, to flush as XNU does.
let mut descriptors = [core::array::from_fn::<u64, { FRAMES as usize }, _>(|page| {
page_descriptor(frame(page as u64), false) | NG
}); 2];
let globals = |descriptors: &[[u64; FRAMES as usize]; 2], space: usize| {
descriptors[space].map(|descriptor| {
(descriptor & 1 != 0 && descriptor & NG == 0).then_some(descriptor)
})
};
let mut space = 0usize;
let mut owners = [0usize; 4];
let mut fetches = 0;
for step in 0..STEPS {
let draw = draws.next(100);
let mut apply = |action: &dyn Fn(&mut M)| {
action(&mut forgetting);
action(&mut keeping);
};
if draw < 30 {
let (at, page) = (draws.next(2) as usize, draws.next(FRAMES));
let target = frame(draws.next(FRAMES));
let [_, _, l3] = SPACES_TABLES[at];
let descriptor = match draws.next(5) {
0 => 0,
1 => page_descriptor(target, true) | NG,
2 => page_descriptor(target, false),
_ => page_descriptor(target, false) | NG,
};
descriptors[at][page as usize] = descriptor;
apply(&|machine| write_entry(machine, l3 + page * 8, descriptor));
if draws.next(2) == 0 {
apply(&|machine| page_tlbi(machine, pc(page)));
} else {
apply(&|machine| all(machine));
}
} else if draw < 38 {
apply(&|machine| all(machine));
} else if draw < 55 {
let (to, to_asid) = (draws.next(2) as usize, 1 + draws.next(3));
if globals(&descriptors, to) != globals(&descriptors, space)
|| owners[to_asid as usize] != to
{
apply(&|machine| all(machine));
}
owners[to_asid as usize] = to;
space = to;
apply(&|machine| select(machine, to, to_asid));
} else {
let at = pc(draws.next(FRAMES));
let forgot = run(&mut forgetting, at);
let kept = run(&mut keeping, at);
let walked = walk(&mut forgetting, &forgetting_keys, at);
assert_eq!(
forgot, walked,
"seed {seed:#x} step {step}: forgetting at {at:#x}"
);
assert_eq!(
kept,
walk(&mut keeping, &keeping_keys, at),
"seed {seed:#x} step {step}: keeping at {at:#x}"
);
// Both machines number frames' blocks alike.
assert_eq!(
forgot.map(|key| forgetting_keys.iter().position(|&held| held == key)),
kept.map(|key| keeping_keys.iter().position(|&held| held == key)),
"seed {seed:#x} step {step}: at {at:#x}"
);
fetches += 1;
}
}
assert!(fetches > STEPS / 3);
no_mismatches(&keeping);
assert_eq!(forgetting.statistics.tlbi_keep, TlbiKeepCounts::default());
totals.add(&keeping.statistics.tlbi_keep);
}
assert!(totals.tlbis > 400, "{totals:#?}");
assert!(totals.kept > 100 && totals.dropped > 100, "{totals:#?}");
assert!(totals.verified > 100, "{totals:#?}");
}
@@ -0,0 +1,556 @@
//! "Verify instead of forget" (`--tlbi-keep on`): a TLBI of everything
//! keeps the lookup contexts and their ITLB entries, marked unverified, and
//! the next fetch in each checks every entry of its context against the
//! tables before any lookup uses one again. Off by default.
//!
//! A TLB may hold any translation a walk would give now. A walk's result is
//! a function of the controls, which a context's key holds (all but TTBR0 and
//! the SPRR permissions in its frame, those two in the key itself), and of
//! the descriptors it reads: each read's address follows from the controls
//! and the values read before it. So a walk that reads the same addresses
//! and finds the same values gives the same result. Every ITLB fill records
//! its walk ([`WalkRecord`]): each descriptor address and value it read, over
//! both stages, in order (the leaf and every table on its path), the TTBR0
//! it walked from and what it gave. Verification ([`Machine::verify_kept`])
//! keeps an entry only where:
//!
//! - every recorded descriptor still holds its value;
//! - for a lower-half page, TTBR0 is the one the walk started from: the
//! upper half's context, which holds the lower half's global pages
//! (`itlb_context`), has no TTBR0 in its key, and XNU flushes everything
//! precisely when the next process's shared region (global pages) differs;
//! - the host still permits the fetch (`Host::fetch_permitted`), which is
//! host state and in no descriptor;
//! - the entry is what a fill would make of the walk now: the block key of
//! the frame in the page's variant as it is now (`page_variant`, which
//! reads host and board state about the frame) and the global mark.
//!
//! Anything else drops the entry (and grows its half's drop epoch, as every
//! drop does), and its page is walked again at the fetch. A context with an
//! entry no walk record covers, or met in another state than its key's, is
//! forgotten as a TLBI of everything forgets them all without the keep.
//!
//! Nothing reaches a kept context's entries before its verification:
//! - [`contexts::Contexts::find`] does not give a kept context's number, and
//! every number native code holds comes from it: the fetch's contexts
//! ([`Machine::contexts`]), the native TTBR0 switch table's entries
//! (`keep_table_switches` takes `switch_contexts`) and the transition
//! records' (`refresh_transition_contexts` takes `live_contexts`);
//! - the TLBI forgets the switch table and moves the transition records'
//! generation ([`Machine::advance_translation_generation`]), as before;
//! - the chain's contexts become [`contexts::VOID`], which no entry has;
//! - both halves' ITLB drop epochs grow, so no stamp or jump cache entry made
//! before the TLBI holds after it (a stamp may name a page whose ITLB
//! entry an eviction took, which no verification sees);
//! - the filters TLBIs by VA reach entries through are cleared, as before,
//! and verification records each entry it keeps in them again, as a walk
//! does. A TLBI by VA between the TLBI of everything and a verification
//! needs to reach no kept entry: verification reads the tables after it.
//!
//! Verification runs inside one fetch on this PE: no mail is read during it.
//! Another PE's table write and its TLBI by VA race it as they race a walk,
//! and as for a walk the entry is in the filters before it is used.
//!
//! `--tlbi-verify-check` walks every entry verification keeps in full as
//! well, and drops it, counted as a mismatch with a sample, where the walk
//! gives anything else: a check of the argument above on a real boot.
use super::*;
/// The descriptor reads a [`WalkRecord`] holds: four levels of stage 1 (five
/// with 52-bit addresses) and room to spare. A walk that reads more (stage 2
/// under stage 1) has no record, which makes its context unverifiable.
pub(super) const WALK_READS: usize = 8;
/// Entries of a verification's cache of descriptors read already: the
/// tables a context's pages share are read once.
const CONFIRMED: usize = 64;
/// The walk an ITLB entry was filled from: what it read, what it started
/// from and what it gave.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct WalkRecord {
/// The page walked, and its frame: another page of the same leaf
/// (`take_leaf_pages`) is at the same offset in the leaf's output.
pub(super) page: u64,
pub(super) physical: u64,
/// The bytes the leaf maps, and its guarded and global bits.
pub(super) size: u64,
pub(super) guarded: bool,
pub(super) global: bool,
/// The TTBR0 value of the controls it walked under.
pub(super) ttbr0: u64,
reads: [(u64, u64); WALK_READS],
len: u8,
}
impl WalkRecord {
fn reads(&self) -> &[(u64, u64)] {
&self.reads[..usize::from(self.len)]
}
/// Whether the page `page` is in this walk's leaf.
fn covers(&self, page: u64) -> bool {
self.size >= FETCH_PAGE
&& self.size.is_power_of_two()
&& (page ^ self.page) & !(self.size - 1) == 0
}
}
/// The descriptor reads of one walk, in order ([`RecordingTables`]).
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct WalkReads {
reads: [(u64, u64); WALK_READS],
len: u8,
/// More reads than fit, or a descriptor update: no record.
spoilt: bool,
}
impl WalkReads {
/// The record of this walk of `pc` under `ttbr0`, which gave
/// `translation`.
pub(super) fn record(
&self,
pc: u64,
translation: &mmu::Translation,
ttbr0: u64,
) -> Option<WalkRecord> {
(!self.spoilt && self.len != 0).then_some(WalkRecord {
page: pc & !(FETCH_PAGE - 1),
physical: translation.physical & !(FETCH_PAGE - 1),
size: translation.size,
guarded: translation.guarded,
global: translation.global,
ttbr0,
reads: self.reads,
len: self.len,
})
}
}
/// [`RamTables`] noting every descriptor a walk reads ([`WalkReads`]).
pub(super) struct RecordingTables<'a, H: Host> {
host: &'a mut H,
pub(super) reads: WalkReads,
}
impl<'a, H: Host> RecordingTables<'a, H> {
pub(super) fn new(host: &'a mut H) -> Self {
Self {
host,
reads: WalkReads::default(),
}
}
}
impl<H: Host> mmu::TableMemory for RecordingTables<'_, H> {
fn read_descriptor(&mut self, physical: u64) -> Option<u64> {
let value = self.host.read_ram_descriptor(physical);
let reads = &mut self.reads;
match value {
Some(value) if usize::from(reads.len) < WALK_READS => {
reads.reads[usize::from(reads.len)] = (physical, value);
reads.len += 1;
}
// A read that fails ends the walk in a fault, which no entry
// records; one past the room spoils the record.
Some(_) | None => reads.spoilt = true,
}
value
}
fn update_descriptor(&mut self, physical: u64, old: u64, new: u64) -> Option<bool> {
// The walker makes none (no FEAT_HAFDBS); one would change what the
// record read.
self.reads.spoilt = true;
RamTables(&mut *self.host).update_descriptor(physical, old, new)
}
}
/// A verification's cache of descriptors it read, by address.
struct Confirmed([(u64, Option<u64>); CONFIRMED]);
impl Confirmed {
fn new() -> Self {
Self([(u64::MAX, None); CONFIRMED])
}
fn slot(address: u64) -> usize {
((address >> 3).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 58) as usize % CONFIRMED
}
}
/// One PE's state for `--tlbi-keep on`.
#[derive(Default)]
pub(super) struct TlbiKeep {
/// `--tlbi-keep on`: a TLBI of everything keeps the contexts.
pub(super) on: bool,
/// `--tlbi-verify-check`: every entry verification keeps is walked in
/// full as well.
pub(super) check: bool,
/// The walk each ITLB entry was filled from, by context and page. An
/// entry the ITLB evicted leaves its record until a verification or a
/// prune finds it gone.
records: BTreeMap<(u64, u64), WalkRecord>,
/// Contexts with an ITLB entry no record covers, which no verification
/// can keep.
incomplete: BTreeSet<u64>,
/// The walk of each fetch cache entry, with the entry it made
/// ([`Machine::fetch_record`]).
fetch_walks: Vec<Option<(FetchEntry, WalkRecord)>>,
/// Test only: kept contexts are confirmed without a check, the mutation
/// the acceptance tests must catch.
#[cfg(test)]
pub(super) unverified: bool,
}
impl<H: Host, D: Devices> Machine<H, D> {
/// Keep the lookup contexts across a TLBI of everything and verify them
/// before use (`keep`, `--tlbi-keep on`), walking every entry kept in
/// full as well (`check`, `--tlbi-verify-check`). Contexts made before
/// have entries without walk records: they go.
pub fn set_tlbi_keep(&mut self, keep: bool, check: bool) {
if keep && !self.tlbi_keep.on && self.spaces.iter().any(|spaces| spaces.len() != 0) {
self.forget_spaces(0..=1, 3);
}
self.tlbi_keep = TlbiKeep {
on: keep,
check: keep && check,
fetch_walks: if keep {
vec![None; FETCH_CACHE]
} else {
Vec::new()
},
..TlbiKeep::default()
};
}
/// Whether this machine keeps its contexts across a TLBI of everything,
/// and checks what it keeps.
pub fn tlbi_keep(&self) -> (bool, bool) {
(self.tlbi_keep.on, self.tlbi_keep.check)
}
/// The fetch cache's entry in `slot` came from a walk that read `reads`
/// under `ttbr0` and gave `translation`.
pub(super) fn note_fetch_walk(
&mut self,
slot: usize,
entry: FetchEntry,
reads: &WalkReads,
translation: &mmu::Translation,
ttbr0: u64,
) {
let record = reads.record(entry.page, translation, ttbr0);
if let Some(held) = self.tlbi_keep.fetch_walks.get_mut(slot) {
*held = record.map(|record| (entry, record));
}
}
/// The walk the fetch cache's current entry of the page of `pc` came
/// from, when it was recorded.
pub(super) fn fetch_record(&self, pc: u64) -> Option<WalkRecord> {
if !self.tlbi_keep.on {
return None;
}
let entry = self.cached_fetch(pc)?;
let slot = (entry.page / FETCH_PAGE) as usize % FETCH_CACHE;
match self.tlbi_keep.fetch_walks.get(slot)? {
Some((held, record)) if *held == entry => Some(*record),
_ => None,
}
}
/// The ITLB holds the page `page` in `context`, from the walk `record`
/// (none: unknown, so the context can no longer be verified).
pub(super) fn note_kept_fill(&mut self, page: u64, context: u64, record: Option<WalkRecord>) {
let limit = 2 * self.itlb.entries();
if self.tlbi_keep.records.len() >= limit {
self.prune_kept_records();
}
let keep = &mut self.tlbi_keep;
match record.filter(|record| record.covers(page)) {
Some(record) if keep.records.len() < limit => {
keep.records.insert((context, page), record);
}
_ => {
keep.records.remove(&(context, page));
keep.incomplete.insert(context);
}
}
}
/// Drop the records of entries the ITLB no longer holds, and of
/// contexts that went.
fn prune_kept_records(&mut self) {
let (itlb, spaces) = (&self.itlb, &self.spaces);
let live = |number: u64| spaces.iter().any(|spaces| spaces.live(number).is_some());
self.tlbi_keep.records.retain(|&(context, page), _| {
let held = itlb.find(itlb.page_slot(page, context), page, context);
held.pc == page && held.key == context && live(context)
});
self.tlbi_keep.incomplete.retain(|&number| live(number));
}
/// The contexts of `half` go: their records with them.
pub(super) fn forget_kept_records(&mut self, half: usize) {
if !self.tlbi_keep.on {
return;
}
let numbers: Vec<u64> = self.spaces[half].iter().map(|space| space.number).collect();
for number in numbers {
self.take_kept_records(number);
self.tlbi_keep.incomplete.remove(&number);
}
}
/// Take the records of `context`'s entries out.
fn take_kept_records(&mut self, context: u64) -> Vec<(u64, WalkRecord)> {
let records = &mut self.tlbi_keep.records;
let taken: Vec<(u64, WalkRecord)> = records
.range((context, 0)..=(context, u64::MAX))
.map(|(&(_, page), &record)| (page, record))
.collect();
for (page, _) in &taken {
records.remove(&(context, *page));
}
taken
}
/// A TLBI of everything with `--tlbi-keep on`: every context stays,
/// unverified, unreachable until its next fetch verifies it (the module
/// documentation says why nothing reaches it before).
///
/// The upper half is kept only while its keys leave out the ASID (no
/// upper-half fetch was non-global since its contexts were last
/// forgotten), as a forget would reset that: else it is forgotten as
/// without the keep, so that native TTBR0 switches, which need it, come
/// back.
pub(super) fn keep_spaces(&mut self) {
if self.private_fetches[1] {
self.forget_contexts(1..=1, 1);
}
let kept = self.spaces[0].keep_all() + self.spaces[1].keep_all();
self.statistics.tlbi_keep.tlbis += 1;
self.statistics.tlbi_keep.contexts += kept as u64;
for half in 0..2 {
self.recent[half] = [None; RECENT];
self.clear_fetched_leaves(half);
}
// A span of one granule in each half, which holds no entry: both
// halves' drop epochs grow (`LookupTable::forget_range_where`), so
// every stamp and jump cache entry this PE made goes.
const UPPER_GRANULE: u64 = !0 << 14;
self.itlb.forget_range_where(0..=0, |_| false);
self.itlb
.forget_range_where(UPPER_GRANULE..=UPPER_GRANULE, |_| false);
self.chain.set_contexts([contexts::VOID; 2]);
self.advance_translation_generation();
}
/// Verify the kept context `number` of `half` before a fetch at `el` in
/// `variant` runs in it: whether it stays, every entry of it kept one a
/// walk now gives ([`Self::kept_walk_holds`]) and in the filters, every
/// other dropped and its page walked again at the fetch. One that cannot
/// be verified is forgotten, its pages walked again.
pub(super) fn verify_kept(
&mut self,
half: usize,
el: u8,
variant: Variant,
number: u64,
) -> bool {
let started = self.host.counter();
let records = self.take_kept_records(number);
let current = self.cpu.pstate.el | u8::from(self.cpu.pstate.guarded) << 4;
let incomplete = self.tlbi_keep.incomplete.remove(&number);
let verified = if el != current || incomplete {
self.refills.extend(records.iter().map(|&(page, _)| page));
self.spaces[half].remove_number(number);
self.statistics.tlbi_keep.forgotten += 1;
false
} else {
self.verify_records(number, variant, records);
self.spaces[half].confirm(number);
self.statistics.tlbi_keep.verified += 1;
true
};
self.statistics.tlbi_keep.ticks += self.host.counter().wrapping_sub(started);
verified
}
/// [`Self::verify_kept`]'s check of each of `records`, the context
/// `number`'s.
fn verify_records(&mut self, number: u64, variant: Variant, records: Vec<(u64, WalkRecord)>) {
let controls = self.cpu.controls(self.cpu.regime());
let requester = self.cpu.requester();
let mut confirmed = Confirmed::new();
for (page, record) in records {
let held = self
.itlb
.find(self.itlb.page_slot(page, number), page, number);
// An entry the ITLB evicted: nothing to keep.
if held.pc != page || held.key != number {
continue;
}
#[cfg(test)]
if self.tlbi_keep.unverified {
self.tlbi_keep.records.insert((number, page), record);
continue;
}
let mut kept =
self.kept_walk_holds(page, held, &record, &controls, variant, &mut confirmed);
if kept && self.tlbi_keep.check {
kept = self.check_kept(page, held, &record, &controls, requester, variant);
}
if kept {
self.tlbi_keep.records.insert((number, page), record);
self.statistics.tlbi_keep.kept += 1;
} else {
self.itlb
.forget_range_where(page..=page, |entry| entry.key == number);
self.statistics.tlbi_keep.dropped += 1;
self.refills.push(page);
}
}
}
/// Whether the entry `held` of the page `page`, filled from `record`, is
/// what a walk under `controls` gives now (the module documentation's
/// conditions); one that is goes in the filters, as a walk's fetch does
/// (`fetched_through`). `confirmed` caches this verification's reads.
fn kept_walk_holds(
&mut self,
page: u64,
held: chain::LookupEntry,
record: &WalkRecord,
controls: &mmu::Controls,
variant: Variant,
confirmed: &mut Confirmed,
) -> bool {
let half = chain::half(page);
if !record.covers(page)
|| half == 0 && record.ttbr0 != controls.ttbr0
|| !self.reads_hold(record, Some(confirmed))
|| !self.host.fetch_permitted(page)
{
return false;
}
let physical = record.physical.wrapping_add(page).wrapping_sub(record.page);
if self.kept_entry(
page,
held.key,
physical,
record.guarded,
record.global,
variant,
) != Some(held)
{
return false;
}
// A wider span may have let a broadcast pass the PE by while it read:
// as a fetch walks again (`fetch_physical`), it reads again.
if half == 0
&& record.global
&& self.widen_lower_globals(page, record.size)
&& !self.reads_hold(record, None)
{
return false;
}
// The upper half's first non-global fetch forgets its contexts;
// a kept one has none past the forget (`keep_spaces`).
if half == 1 && !record.global && !self.private_fetches[1] {
return false;
}
self.fetched_through(half, page, record.size, record.global);
true
}
/// Whether every descriptor `record` read holds its value still, reading
/// through `confirmed` where given.
fn reads_hold(&mut self, record: &WalkRecord, mut confirmed: Option<&mut Confirmed>) -> bool {
record.reads().iter().all(|&(address, value)| {
let now = match confirmed.as_deref_mut() {
Some(cache) => {
let slot = &mut cache.0[Confirmed::slot(address)];
if slot.0 != address {
*slot = (address, self.host.read_ram_descriptor(address));
}
slot.1
}
None => self.host.read_ram_descriptor(address),
};
now == Some(value)
})
}
/// The ITLB entry a fill in `context` would make of the page `page`
/// translating to the frame of `physical`, `guarded` and `global`, for a
/// fetch in `variant`: what [`Self::take_page`] holds of such a walk.
fn kept_entry(
&self,
page: u64,
context: u64,
physical: u64,
guarded: bool,
global: bool,
variant: Variant,
) -> Option<chain::LookupEntry> {
let current = Variant {
guarded_page: guarded,
..variant
};
let frame = physical & !(FETCH_PAGE - 1);
let id = self.known_variant(self.page_variant(current, frame))?;
let key = self.block_key(frame, id);
Some(match global {
true => chain::LookupEntry::global_page(page, context, key),
false => chain::LookupEntry::page(page, context, key),
})
}
/// `--tlbi-verify-check`: whether a full walk of `page` under
/// `controls` gives what verification kept of it (`held`, from
/// `record`); a mismatch is counted, sampled and dropped.
fn check_kept(
&mut self,
page: u64,
held: chain::LookupEntry,
record: &WalkRecord,
controls: &mmu::Controls,
requester: mmu::Requester,
variant: Variant,
) -> bool {
self.statistics.tlbi_keep.checked += 1;
let walked = match mmu::translate(
controls,
page,
Access::Execute,
requester,
&mut RamTables(&mut self.host),
) {
Translated::Mapped(walked) if self.host.fetch_permitted(page) => Some(walked),
_ => None,
};
let matches = walked.is_some_and(|walked| {
walked.size == record.size
&& walked.global == record.global
&& walked.guarded == record.guarded
&& self.kept_entry(
page,
held.key,
walked.physical,
walked.guarded,
walked.global,
variant,
) == Some(held)
});
if !matches {
let frame = walked.map_or(u64::MAX, |walked| walked.physical & !(FETCH_PAGE - 1));
self.statistics
.tlbi_keep
.mismatch([page, held.key, held.entry, frame]);
}
matches
}
}
@@ -57,6 +57,9 @@ pub const MARKER_BYTES: usize = MAGIC.len() + 4 * FIELDS;
/// performance unasked, and no line setup writes holds the option. So
/// does the fork's `--keep-running-on-panic`, a hand-written debugging
/// opt-in that lets a guest whose kernel panicked run on.
/// So do the fork's `--tlbi-keep on|off` and `--tlbi-verify-check`,
/// hand-written opt-ins that keep the ITLB's contexts across a TLBI of
/// everything and check what they keep: no line setup writes holds them.
pub const OPTIONS_REVISION: u32 = 13;
/// The startup choices, beside `stela.cfg` on the ESP.