From f3bd8ca5d4e3a4e7ea47cba7977054fca579c07e Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:10:13 +0000 Subject: [PATCH] perf(runtime): complete MRS TPIDR_EL1 natively from an engine-held cell --- crates/stela-compiler/src/x86_64.rs | 1 + .../src/x86_64/register_read.rs | 159 ++++++++++++++++++ crates/stela-runtime/src/machine/engine.rs | 128 +++++++++++++- .../src/machine/engine/system.rs | 55 ++++++ crates/stela-runtime/src/machine/registers.rs | 1 + 5 files changed, 343 insertions(+), 1 deletion(-) create mode 100644 crates/stela-compiler/src/x86_64/register_read.rs diff --git a/crates/stela-compiler/src/x86_64.rs b/crates/stela-compiler/src/x86_64.rs index dc82bbfe3a..e38224c657 100644 --- a/crates/stela-compiler/src/x86_64.rs +++ b/crates/stela-compiler/src/x86_64.rs @@ -91,6 +91,7 @@ mod pointer_checks; mod prefetch; mod region; mod register_offset; +pub mod register_read; mod scalable; mod scalable_matrix; mod simd; diff --git a/crates/stela-compiler/src/x86_64/register_read.rs b/crates/stela-compiler/src/x86_64/register_read.rs new file mode 100644 index 0000000000..1c567e731e --- /dev/null +++ b/crates/stela-compiler/src/x86_64/register_read.rs @@ -0,0 +1,159 @@ +//! Native completion of MRS reads of a System register whose value the +//! system-mode engine keeps in a [`Cell`] at a fixed host address. +//! +//! The MRS ends its block with a System exit. A [`thunk`] the engine +//! installs over that exit completes it natively while the cell's +//! `readable` word is nonzero: it writes `value` to Xt (nothing for XZR) and +//! leaves through a direct exit to the next instruction, which the engine +//! may chain like a block's. Otherwise it takes the original exit. +//! +//! The engine sets `readable` only while the read at the current EL is the +//! plain register read of its AARCHMRS accessor, neither UNDEFINED nor +//! trapped nor redirected, with `value` the register's contents, and clears +//! it whenever a System register write, an exception, an exception return +//! or a PE switch may change either. Thunks clobber only RAX and flags. +use super::pointer::Thunk; +use crate::{GuestAddress, block::ExitKind}; +use alloc::vec::Vec; + +/// What a thunk reads. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Cell { + /// Nonzero while native code may complete the read with `value`. + pub readable: u64, + pub value: u64, +} + +const VALUE: u8 = core::mem::offset_of!(Cell, value) as u8; +const _: () = assert!(core::mem::offset_of!(Cell, readable) == 0); + +/// The thunk completing `MRS Xt, ` at `pc` from the cell at +/// `cell`, else exiting at `pc` for the engine. +pub fn thunk(pc: GuestAddress, rt: u8, cell: u64) -> Thunk { + let mut code = Vec::with_capacity(64); + code.extend([0x48, 0xb8]); // movabs rax,cell + code.extend(cell.to_le_bytes()); + code.extend([0x48, 0x83, 0x38, 0x00]); // cmp qword [rax],0 + code.extend([0x0f, 0x84]); // je miss + let fixup = code.len(); + code.extend([0; 4]); + if rt != 31 { + code.extend([0x48, 0x8b, 0x40, VALUE]); // mov rax,[rax+value] + code.extend([0x48, 0x89, 0x87]); // mov [rdi+x(rt)],rax + code.extend((u32::from(rt) * 8).to_le_bytes()); + } + let next = code.len(); + code.extend(super::chain::direct_exit( + GuestAddress(pc.0.wrapping_add(4)), + ExitKind::Fallthrough, + )); + let relative = (code.len() - fixup - 4) as i32; + code[fixup..fixup + 4].copy_from_slice(&relative.to_le_bytes()); + code.extend(super::chain::direct_exit(pc, ExitKind::System)); + Thunk { + code, + next: Some(next), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::x86_64::chain::{DIRECT_EXIT_BYTES, direct_exit}; + + #[test] + fn thunks_end_in_the_fallthrough_then_the_original_exit() { + let pc = GuestAddress(0x4000); + let thunk = thunk(pc, 8, 0x1000); + let end = thunk.code.len(); + assert_eq!( + thunk.code[end - DIRECT_EXIT_BYTES..], + direct_exit(pc, ExitKind::System) + ); + let next = thunk.next.unwrap(); + assert_eq!(next + DIRECT_EXIT_BYTES, end - DIRECT_EXIT_BYTES); + assert_eq!( + thunk.code[next..next + DIRECT_EXIT_BYTES], + direct_exit(GuestAddress(0x4004), ExitKind::Fallthrough) + ); + } + + /// Thunks run on the host: a readable cell completes the read into Xt, + /// or into nothing for XZR; a cleared one exits with no write. + #[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))] + #[test] + fn thunks_read_the_cell_only_while_it_is_readable() { + use crate::GuestState; + use core::ffi::c_void; + unsafe extern "C" { + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut c_void, bytes: usize) -> i32; + } + #[cfg(target_os = "macos")] + const MAP_ANONYMOUS: i32 = 0x1000; + #[cfg(target_os = "linux")] + const MAP_ANONYMOUS: i32 = 0x20; + const PAGE: usize = 4096; + #[repr(C)] + #[derive(Debug, PartialEq, Eq)] + struct Exit { + pc: u64, + kind: u64, + } + fn run(code: &[u8], state: &mut GuestState) -> Exit { + // SAFETY: private anonymous memory, RX after the copy, unmapped + // after the call; the thunk touches only `state` and the cell, + // which outlive it. + unsafe { + let page = mmap(core::ptr::null_mut(), PAGE, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + assert_eq!(mprotect(page, PAGE, 5), 0); + let entry: unsafe extern "sysv64" fn(*mut GuestState) -> Exit = + core::mem::transmute(page); + let exit = entry(state); + assert_eq!(munmap(page, PAGE), 0); + exit + } + } + let pc = GuestAddress(0x4000); + let mut cell = alloc::boxed::Box::new(Cell::default()); + let address = &mut *cell as *mut Cell; + let set = |value: Cell| unsafe { address.write(value) }; + let mut state = GuestState::default(); + state.x[19] = 7; + let read = thunk(pc, 19, address as u64); + let miss = Exit { + pc: pc.0, + kind: ExitKind::System as u64, + }; + let next = Exit { + pc: pc.0 + 4, + kind: ExitKind::Fallthrough as u64, + }; + set(Cell { + readable: 0, + value: 0xffff_fe00_1234_5000, + }); + assert_eq!(run(&read.code, &mut state), miss); + assert_eq!(state.x[19], 7); + set(Cell { + readable: 1, + value: 0xffff_fe00_1234_5000, + }); + assert_eq!(run(&read.code, &mut state), next); + assert_eq!(state.x[19], 0xffff_fe00_1234_5000); + let before = state.x; + assert_eq!(run(&thunk(pc, 31, address as u64).code, &mut state), next); + assert_eq!(state.x, before); + } +} diff --git a/crates/stela-runtime/src/machine/engine.rs b/crates/stela-runtime/src/machine/engine.rs index 7717bff8a3..4ab102a4db 100644 --- a/crates/stela-runtime/src/machine/engine.rs +++ b/crates/stela-runtime/src/machine/engine.rs @@ -48,7 +48,7 @@ use stela_compiler::{ x86_64::{ MemoryChecks, chain::{self, ChainControl}, - pointer, zero_block, + pointer, register_read, zero_block, }, }; @@ -677,6 +677,20 @@ struct Variant { zero_block: Option, } +/// Xt of `word` at `pc` if it is MRS Xt, TPIDR_EL1. +fn thread_pointer_read(pc: u64, word: u32) -> Option { + let instruction = block::decode_system_mode_instruction(GuestAddress(pc), word).ok()??; + match instruction.operation { + SystemOperation::Register(access) + if access.direction() == Direction::Read + && access.encoding() == registers::encodings::TPIDR_EL1 => + { + Some(access.rt()) + } + _ => None, + } +} + /// Whether `word` at `pc` is DC ZVA. fn zeroes_block(pc: u64, word: u32) -> bool { block::decode_system_mode_instruction(GuestAddress(pc), word) @@ -763,6 +777,10 @@ pub struct Machine { /// key enabled and untrapped under the current memo, and again whenever /// derived state may have changed. pointer_tags: alloc::boxed::Box<[u64; 4]>, + /// TPIDR_EL1 for native MRS reads (`x86_64::register_read`): readable + /// once an MRS exit finds the read plain at the current EL + /// (`system::thread_pointer_readable`), until derived state may change. + thread_pointer: alloc::boxed::Box, /// The chip's `Chip::admit`, indexed. admit_table: AdmitTable, /// The watched pages the host keeps unmapped. @@ -861,6 +879,7 @@ impl Machine { pointer_inputs_seen: Vec::new(), pointer_generations: 0, pointer_tags: alloc::boxed::Box::new([0; 4]), + thread_pointer: alloc::boxed::Box::default(), admit_table, watch: Watch::default(), current: 0, @@ -909,6 +928,7 @@ impl Machine { self.debug = None; self.pointer = None; *self.pointer_tags = [0; 4]; + self.thread_pointer.readable = 0; self.device_lines = None; } @@ -2025,6 +2045,12 @@ impl Machine { terminal_pc, terminal, )); + successors.extend(self.complete_thread_pointer_natively( + code, + &compiled.native.x86_64_code, + terminal_pc, + terminal, + )); } self.blocks.push(Block { pc, @@ -2085,6 +2111,37 @@ impl Machine { }) } + /// Redirect the System exit ending a block's `native` code, installed at + /// `code`, through a thunk that completes `word` at `pc`, if it is MRS + /// TPIDR_EL1, from [`Self::thread_pointer`] while it is readable + /// (`x86_64::register_read`); the thunk's direct exit to the next + /// instruction. + fn complete_thread_pointer_natively( + &mut self, + code: NativeCode, + native: &[u8], + pc: u64, + word: u32, + ) -> Option { + let exit = chain::direct_exit(GuestAddress(pc), ExitKind::System); + let site = native.len().checked_sub(chain::DIRECT_EXIT_BYTES)?; + if native[site..] != exit { + return None; + } + let rt = thread_pointer_read(pc, word)?; + let cell = &*self.thread_pointer as *const register_read::Cell as u64; + let thunk = register_read::thunk(GuestAddress(pc), rt, cell); + let installed = self.host.install(&thunk.code).ok()?; + let site = code.0 as u64 + site as u64; + let jump = chain::jump(site, installed.0 as u64)?; + self.host.patch(NativeCode(site as usize), &jump); + thunk.next.map(|next| Successor { + site: installed.0 as u64 + next as u64, + target: GuestAddress(pc + INSTRUCTION), + kind: ExitKind::Fallthrough, + }) + } + /// Compile the longest prefix the host target can emit. fn compile_prefix( &self, @@ -3760,7 +3817,18 @@ impl Machine { if let Some(outcome) = vgic { return self.register_outcome(word, Some(access), outcome); } + // Whether the access is a plain TPIDR_EL1 read, judged before it + // runs: one that is UNDEFINED or traps changes the EL. + let thread_pointer = encoding == registers::encodings::TPIDR_EL1 + && access.direction() == Direction::Read + && system::thread_pointer_readable(&self.cpu); if let Some(step) = self.system_access(word, access) { + if thread_pointer && step.is_ok() { + *self.thread_pointer = register_read::Cell { + readable: 1, + value: self.cpu.read(SystemRegister::TPIDR_EL1), + }; + } return step; } if let Some(outcome) = self.board_register(access) { @@ -5943,6 +6011,64 @@ mod tests { assert_eq!(*machine.pointer_tags, [0; 4]); } + /// MRS TPIDR_EL1 ends its block in a System exit that a thunk reading + /// the engine's cell takes over, chaining on to the next instruction; + /// the cell opens on a plain read and closes on any derived change. + #[test] + fn tpidr_el1_reads_complete_natively_from_the_open_cell() { + const ADD: u32 = 0x9100_0400; // add x0, x0, #1 + const MRS: u32 = 0xd538_d088; // mrs x8, tpidr_el1 + let mut machine = machine(&[ADD, MRS, ADD]); + let base = machine.cpu.pc; + machine.host.exits = vec![NativeExit::Exit { + next_pc: base + 8, + kind: ExitKind::Fallthrough as u64, + }]; + machine.step().unwrap(); + let block = &machine.blocks[0]; + let code = &machine.host.installed[block.code.0 - 1]; + let cell = &*machine.thread_pointer as *const register_read::Cell as u64; + let thunk = register_read::thunk(GuestAddress(base + 4), 8, cell); + let installed = machine.host.installed.len(); + assert_eq!(machine.host.installed[installed - 1], thunk.code); + let site = block.code.0 + code.len() - chain::DIRECT_EXIT_BYTES; + let jump = chain::jump(site as u64, installed as u64).unwrap().to_vec(); + assert_eq!(machine.host.patches, [(site, jump)]); + assert_eq!( + block.successors, + [Successor { + site: (installed + thunk.next.unwrap()) as u64, + target: GuestAddress(base + 8), + kind: ExitKind::Fallthrough, + }] + ); + // Other System reads keep their exit. + let mut other = super::tests::machine(&[ADD, 0xd538_1008]); // mrs x8, sctlr_el1 + other.host.exits = machine.host.exits.clone(); + other.host.exits.push(NativeExit::Exit { + next_pc: base + 8, + kind: ExitKind::Fallthrough as u64, + }); + other.step().unwrap(); + assert!(other.host.patches.is_empty() && other.blocks[0].successors.is_empty()); + machine + .cpu + .registers + .set(SystemRegister::TPIDR_EL1, 0, 0x5000); + machine.cpu.pc = base + 4; + machine.system_instruction(MRS).unwrap(); + assert_eq!(machine.cpu.state.x[8], 0x5000); + assert_eq!( + *machine.thread_pointer, + register_read::Cell { + readable: 1, + value: 0x5000 + } + ); + machine.derived_changed(); + assert_eq!(machine.thread_pointer.readable, 0); + } + /// Where DC ZVA cannot trap, a block ending in it zeroes natively and /// falls through; elsewhere the same PC compiles a block that exits. A /// fault in the native zeroing completes DC ZVA in the engine. diff --git a/crates/stela-runtime/src/machine/engine/system.rs b/crates/stela-runtime/src/machine/engine/system.rs index 955082c526..486f8d970f 100644 --- a/crates/stela-runtime/src/machine/engine/system.rs +++ b/crates/stela-runtime/src/machine/engine/system.rs @@ -198,6 +198,26 @@ const DCZID_BS: u64 = 0xf; /// HFGITR_EL2.DCZVA (FEAT_FGT). const HFGITR_DCZVA: u32 = 11; +/// HFGRTR_EL2.TPIDR_EL1 (FEAT_FGT). +const HFGRTR_TPIDR_EL1: u32 = 33; + +/// Whether MRS TPIDR_EL1 at the current EL only reads the register: the +/// generated `MRS TPIDR_EL1` accessor is UNDEFINED at EL0, traps at EL1 +/// under HFGRTR_EL2.TPIDR_EL1 with FEAT_FGT, and reads TPIDR_EL1 itself +/// otherwise, at EL2 too (HCR_EL2.E2H redirects no TPIDR_EL1 access). +/// Native code completes the read only then (`x86_64::register_read`). +pub(super) fn thread_pointer_readable(cpu: &Cpu) -> bool { + match cpu.pstate.el { + 1 => match cpu.registers.chip().implemented(Feature::FEAT_FGT) { + Ok(true) => cpu.field(Register::HFGRTR_EL2, HFGRTR_TPIDR_EL1, 1) == 0, + Ok(false) => true, + Err(_) => false, + }, + 2 => true, + _ => false, + } +} + /// The DC ZVA block, in bytes, while DC ZVA at the current EL completes by /// zeroing it: the generated `DC ZVA` accessor neither traps (SCTLR_EL1.DZE /// and HCR_EL2.TDZ, and HFGITR_EL2.DCZVA with FEAT_FGT, outside the host at @@ -1834,6 +1854,41 @@ mod tests { assert!(zeroes > 0 && zeroes < 5 * 32, "{zeroes}"); } + /// MRS TPIDR_EL1 completes natively in exactly the contexts where the + /// generated accessor reads the register with no trap or UNDEFINED, and + /// only such a read opens the cell native code reads. + #[test] + fn native_tpidr_el1_reads_are_exactly_the_plain_reads() { + const TPIDR_EL1: Encoding = Encoding::new(3, 0, 13, 0, 4); + const THREAD: u64 = 0xffff_fe00_1234_5000; + let mut reads = 0; + native_completion_contexts(|machine, pstate, case| { + machine.cpu.registers.set(Register::TPIDR_EL1, 0, THREAD); + machine.cpu.state.x[1] = 0; + let readable = super::thread_pointer_readable(&machine.cpu); + machine + .system_instruction(access(true, TPIDR_EL1, 1)) + .unwrap(); + let read = (machine.cpu.pstate.el, machine.cpu.pc) == (pstate.el, BASE + 4) + && machine.cpu.state.x[1] == THREAD; + assert_eq!(readable, read, "{case}"); + assert_eq!( + *machine.thread_pointer, + stela_compiler::x86_64::register_read::Cell { + readable: u64::from(read), + value: if read { THREAD } else { 0 }, + }, + "{case}" + ); + reads += usize::from(read); + *machine.thread_pointer = Default::default(); + }); + // UNDEFINED at EL0; at EL1 HFGRTR_EL2.TPIDR_EL1 traps with FEAT_FGT. + let machine = machine(&[]); + let fine_grained = Feature::FEAT_FGT.on(machine.cpu.registers.chip()); + assert_eq!(reads, if fine_grained { 16 + 64 } else { 32 + 64 }); + } + #[test] fn rmr_el2_resets_into_aarch64_and_refuses_a_warm_reset_request() { const RMR_EL2: Encoding = Encoding::new(3, 4, 12, 0, 2); diff --git a/crates/stela-runtime/src/machine/registers.rs b/crates/stela-runtime/src/machine/registers.rs index 2d5a326698..191e3f17ea 100644 --- a/crates/stela-runtime/src/machine/registers.rs +++ b/crates/stela-runtime/src/machine/registers.rs @@ -99,6 +99,7 @@ pub mod encodings { DCZID_EL0 = 3, 3, 0, 0, 7; FPCR = 3, 3, 4, 4, 0; FPSR = 3, 3, 4, 4, 1; + TPIDR_EL1 = 3, 0, 13, 0, 4; // Apple SPRR and GXF (m1n1 `cpu_regs.h`; Asahi "SPRR and GXF"). SPRR_CONFIG_EL1 = 3, 6, 15, 1, 0; GXF_CONFIG_EL1 = 3, 6, 15, 1, 2;