feat(runtime): run AMX instructions with per-thread state in the thread block profiles

This commit is contained in:
Tyler Smith committed 2026-10-16 19:26:42 +00:00
1 parent 9d665389ec
commit 55cedd6c63
19 files changed
+836 -7

No files matched your search

+18 -2
View File
@@ -177,6 +177,17 @@ impl BlockProfile {
)
}
/// AMX state is per guest thread, so only the direct-RAM thread profiles
/// carry AMX exits.
pub const fn supports_amx(self) -> bool {
matches!(
self,
Self::DarwinArm64ThreadV1
| Self::AppleArm64eSoftwarePauthThreadV1
| Self::AppleArm64eSoftwarePauthClockThreadV1
)
}
pub const fn supports_thread_registers(self) -> bool {
matches!(
self,
@@ -205,6 +216,9 @@ pub enum ExitKind {
FloatingPoint = 9,
ScalableNumerical = 10,
System = 11,
/// An Apple AMX coprocessor instruction, still unexecuted; the runtime
/// completes it against the thread's AMX state.
Amx = 12,
}
impl TryFrom<u64> for ExitKind {
@@ -224,6 +238,7 @@ impl TryFrom<u64> for ExitKind {
9 => Ok(Self::FloatingPoint),
10 => Ok(Self::ScalableNumerical),
11 => Ok(Self::System),
12 => Ok(Self::Amx),
_ => Err(()),
}
}
@@ -349,6 +364,7 @@ pub(crate) enum Terminator {
ThreadRegister(ThreadRegisterInstruction),
/// Scalar mapping that unconditionally returns to numerical completion.
FloatingPoint(crate::aarch64::FloatingPointOperation),
Amx(crate::amx::AmxInstruction),
}
fn decode_terminator(pc: GuestAddress, word: u32) -> Result<Option<Terminator>, CompileError> {
@@ -989,10 +1005,10 @@ mod tests {
assert_eq!(core::mem::size_of::<BlockExit>(), 16);
assert_eq!(core::mem::offset_of!(BlockExit, next_pc), 0);
assert_eq!(core::mem::offset_of!(BlockExit, kind), 8);
for kind in 0..=ExitKind::System as u64 {
for kind in 0..=ExitKind::Amx as u64 {
assert_eq!(ExitKind::try_from(kind).unwrap() as u64, kind);
}
assert_eq!(ExitKind::try_from(ExitKind::System as u64 + 1), Err(()));
assert_eq!(ExitKind::try_from(ExitKind::Amx as u64 + 1), Err(()));
assert_eq!(ExitKind::try_from(u64::MAX), Err(()));
}
@@ -71,6 +71,7 @@ pub struct BlockAnalysis {
pub pointer_authentication: Option<PointerAuthentication>,
pub clock_instruction: Option<ClockInstruction>,
pub thread_register_instruction: Option<ThreadRegisterInstruction>,
pub amx_instruction: Option<crate::amx::AmxInstruction>,
}
/// Find block boundaries and edges with the parser shared by AOT and JIT. Call
/// continuations are candidates, since the callee may not return; dynamic
@@ -92,6 +93,7 @@ pub fn analyze_with_profile(
let mut pointer_authentication = None;
let mut clock_instruction = None;
let mut thread_register_instruction = None;
let mut amx_instruction = None;
let mut add = |kind, target| successors.push(StaticSuccessor { kind, target });
match parsed.terminal.as_ref().map(|(_, terminal)| terminal) {
None => add(SuccessorKind::Fallthrough, parsed.next_pc),
@@ -181,6 +183,10 @@ pub fn analyze_with_profile(
Some(Terminator::FloatingPoint(_)) => {
add(SuccessorKind::Fallthrough, parsed.next_pc);
}
Some(Terminator::Amx(value)) => {
amx_instruction = Some(*value);
add(SuccessorKind::Fallthrough, value.next_pc);
}
Some(Terminator::Branch(_)) => {
unreachable!("private parser only stores branch operations as terminators")
}
@@ -195,6 +201,7 @@ pub fn analyze_with_profile(
pointer_authentication,
clock_instruction,
thread_register_instruction,
amx_instruction,
})
}
@@ -333,6 +340,16 @@ pub(super) fn parse(
terminal = Some((pc, Terminator::ThreadRegister(decoded)));
break;
}
if profile.supports_amx()
&& let Some(decoded) =
crate::amx::decode(pc, word).map_err(|error| BlockAnalysisError {
pc,
detail: error.0,
})?
{
terminal = Some((pc, Terminator::Amx(decoded)));
break;
}
if let Some(decoded) = decode_terminator(pc, word).map_err(|error| BlockAnalysisError {
pc,
detail: error.0,
+2 -1
View File
@@ -194,7 +194,8 @@ impl CheckedPlan {
| super::Terminator::PointerAuthentication(_)
| super::Terminator::Clock(_)
| super::Terminator::ThreadRegister(_)
| super::Terminator::System(_) => {
| super::Terminator::System(_)
| super::Terminator::Amx(_) => {
return Err(CompileError(
"terminal service is not admitted by checked GPR memory profile".into(),
));
@@ -71,6 +71,7 @@ fn reject_unavailable_service(pc: GuestAddress, word: u32) -> Result<(), Compile
|| block::decode_pointer_authentication(pc, word)?.is_some()
|| block::decode_clock_instruction(pc, word)?.is_some()
|| block::decode_thread_register_instruction(pc, word)?.is_some()
|| crate::amx::decode(pc, word)?.is_some()
{
return Err(CompileError(format!(
"context block service is not integrated at {:#x}",
@@ -198,6 +198,10 @@ fn emit_terminal(
Terminator::ThreadRegister(request) => {
direct_exit(code, request.instruction_pc, ExitKind::ThreadRegister);
}
Terminator::Amx(request) => {
// The runtime runs the operation on the thread's AMX state.
direct_exit(code, request.instruction_pc, ExitKind::Amx);
}
Terminator::PointerAuthentication(request) => {
// Return to the checked runtime helper with unchanged guest
// state at this instruction. Never embed keys/helper pointers.
+360
View File
@@ -0,0 +1,360 @@
//! Apple AMX state for a hosted guest thread and completion of AMX block exits.
//!
//! In hosted execution Stela is the guest's operating system, so each guest
//! thread owns its AMX registers beside its TSD: `set` allocates a zeroed
//! register file, `clr` discards it, and every other operation runs against it.
//! A context switch needs no AMX work because the state never leaves its
//! thread's [`crate::thread::Context`]. The system-mode ABI, where the guest
//! kernel saves and restores the registers itself under `AMX_CTL_EL1`, is
//! documented in `docs/design/runtime.md#apple-amx`.
//!
//! `fma32`/`fms32`/`fma64`/`fms64` with every lane enabled run as native
//! kernels when the target admits a kernel tier; every other operation, and
//! every target without one, runs the reference model. Memory is direct RAM,
//! bounded by the profile's user range.
use crate::{execution::platform::Mapping, memory::DIRECT_RAM_USER_END};
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
use anyhow::{Context as _, Result};
use serde::Serialize;
use stela_compiler::{
GuestState, TargetCpu,
amx::{
AmxInstruction, AmxOperand, AmxOperation, AmxRegisters,
model::{self, AmxError, AmxMemory, MemoryFault},
},
x86_64::amx::{Library, Tier, select},
};
/// Why an AMX instruction did not complete. Nothing was written: guest
/// registers, AMX state and memory are unchanged, and the PC stays on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Failure {
/// An operation other than `set` while AMX is disabled. Hardware delivers
/// an exception whose syndrome has not been researched.
Disabled,
/// `set` while enabled or `clr` while disabled: behavior not researched.
Enablement { enabled: bool },
/// The operand lies outside the hardware-compared domain of the model.
Unsupported { detail: &'static str },
/// The transfer touches memory outside the direct-RAM user range.
Memory { address: u64, write: bool },
}
/// How an AMX instruction completed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Completion {
Enabled,
Disabled,
Native(Tier),
Model,
}
/// One guest thread's AMX state. Disabled threads hold no register file.
#[derive(Debug, Default)]
pub struct Thread {
registers: Option<Box<AmxRegisters>>,
}
impl Thread {
pub const fn new() -> Self {
Self { registers: None }
}
pub fn enabled(&self) -> bool {
self.registers.is_some()
}
pub fn registers(&self) -> Option<&AmxRegisters> {
self.registers.as_deref()
}
/// Complete `instruction` with the guest's general-purpose operand.
///
/// # Safety
/// The caller holds the direct-RAM contract for the guest address space:
/// every in-range guest address is host memory of this process.
pub unsafe fn complete(
&mut self,
instruction: &AmxInstruction,
state: &GuestState,
kernels: Option<&Kernels>,
) -> core::result::Result<Completion, Failure> {
match (instruction.operation, &mut self.registers) {
(AmxOperation::Set, None) => {
self.registers = Some(Box::new(AmxRegisters::zeroed()));
return Ok(Completion::Enabled);
}
(AmxOperation::Clear, Some(_)) => {
self.registers = None;
return Ok(Completion::Disabled);
}
(AmxOperation::Set | AmxOperation::Clear, registers) => {
return Err(Failure::Enablement {
enabled: registers.is_some(),
});
}
(_, None) => return Err(Failure::Disabled),
(_, Some(_)) => {}
}
let registers = self.registers.as_deref_mut().expect("enabled above");
let operand = match instruction.operand {
AmxOperand::Register(index) if index < 31 => state.x[usize::from(index)],
AmxOperand::Register(_) | AmxOperand::None => 0,
};
if let Some(kernels) = kernels
&& let Some(kernel) = select(instruction.operation, operand)
{
let x = registers.x_operand((operand >> 10) & 0x1ff);
let y = registers.y_operand(operand & 0x1ff);
// SAFETY: `select` chose this kernel for the operation, and the
// pointers meet its ABI: the 4 KiB Z grid and 64-byte X and Y.
unsafe {
kernels.call(
kernels.library.offset(kernel),
registers.z.as_mut_ptr().cast(),
&x,
&y,
(operand >> 20) & 63,
)
};
return Ok(Completion::Native(kernels.library.tier));
}
model::execute(registers, instruction.operation, operand, &mut DirectRam)
.map(|()| Completion::Model)
.map_err(|error| match error {
AmxError::Memory(MemoryFault { address, write }) => {
Failure::Memory { address, write }
}
AmxError::Unsupported { detail } => Failure::Unsupported { detail },
AmxError::Enablement => unreachable!("set and clr are handled above"),
})
}
}
/// The native kernel library of the best tier the target admits, mapped RX.
#[derive(Debug)]
pub struct Kernels {
library: Library,
mapping: Mapping,
}
impl Kernels {
/// `None` when no tier is both requested by `target` and admitted by the
/// host; such threads use the model for every operation.
pub fn new(target: TargetCpu) -> Result<Option<Self>> {
let Some(tier) = [Tier::Avx512, Tier::Fma].into_iter().find(|tier| {
target.supports(tier.requires()) && crate::platform::cpu::admitted(tier.requires())
}) else {
return Ok(None);
};
let library = Library::new(tier);
let mapping = Mapping::new(&library.code).context("map AMX kernels")?;
Ok(Some(Self { library, mapping }))
}
pub fn tier(&self) -> Tier {
self.library.tier
}
/// # Safety
/// `offset` starts a kernel in this library and `z` is a 4 KiB Z grid.
unsafe fn call(&self, offset: usize, z: *mut u8, x: &[u8; 64], y: &[u8; 64], row: u64) {
// SAFETY: as above; the library's kernels are leaf functions that
// touch only their arguments and restore MXCSR.
unsafe {
self.mapping
.call_amx_kernel(offset, z, x.as_ptr(), y.as_ptr(), row)
.expect("hosted AMX kernel storage cannot fail")
};
}
}
/// Guest memory in the direct-RAM profile: guest addresses are host addresses
/// below [`DIRECT_RAM_USER_END`].
struct DirectRam;
impl DirectRam {
fn check(address: u64, bytes: usize, write: bool) -> core::result::Result<(), MemoryFault> {
let end = address.checked_add(bytes as u64);
if address == 0 || end.is_none_or(|end| end > DIRECT_RAM_USER_END) {
return Err(MemoryFault { address, write });
}
Ok(())
}
}
impl AmxMemory for DirectRam {
fn read(
&mut self,
address: u64,
destination: &mut [u8],
) -> core::result::Result<(), MemoryFault> {
Self::check(address, destination.len(), false)?;
// SAFETY: the caller of `Thread::complete` holds the direct-RAM
// contract for this in-range address.
unsafe {
core::ptr::copy_nonoverlapping(
address as *const u8,
destination.as_mut_ptr(),
destination.len(),
)
};
Ok(())
}
fn write(&mut self, address: u64, source: &[u8]) -> core::result::Result<(), MemoryFault> {
Self::check(address, source.len(), true)?;
// SAFETY: as for `read`.
unsafe {
core::ptr::copy_nonoverlapping(source.as_ptr(), address as *mut u8, source.len())
};
Ok(())
}
}
#[cfg(all(
test,
target_arch = "x86_64",
any(target_os = "macos", target_os = "linux")
))]
mod tests {
use super::*;
use stela_compiler::{
GuestAddress,
amx::{AmxOperation::*, decode},
x86_64::amx::Kernel,
};
fn instruction(operation: AmxOperation, register: u8) -> AmxInstruction {
decode(GuestAddress(0x1000), operation.word(register))
.unwrap()
.unwrap()
}
fn state(x0: u64) -> GuestState {
let mut state = GuestState::default();
state.x[0] = x0;
state
}
#[test]
fn enablement_transitions_are_explicit() {
let mut thread = Thread::new();
let none = GuestState::default();
unsafe {
assert_eq!(
thread.complete(&instruction(Fma32, 0), &none, None),
Err(Failure::Disabled)
);
assert_eq!(
thread.complete(&instruction(Clear, 0), &none, None),
Err(Failure::Enablement { enabled: false })
);
assert_eq!(
thread.complete(&instruction(Set, 0), &none, None),
Ok(Completion::Enabled)
);
assert_eq!(thread.registers(), Some(&AmxRegisters::zeroed()));
assert_eq!(
thread.complete(&instruction(Set, 0), &none, None),
Err(Failure::Enablement { enabled: true })
);
assert_eq!(
thread.complete(&instruction(Clear, 0), &none, None),
Ok(Completion::Disabled)
);
}
assert!(!thread.enabled());
}
#[test]
fn transfers_use_direct_ram_and_refuse_addresses_outside_it() {
let mut thread = Thread::new();
let source: [u8; 64] = core::array::from_fn(|index| index as u8);
let mut destination = [0u8; 64];
unsafe {
thread
.complete(&instruction(Set, 0), &GuestState::default(), None)
.unwrap();
// ldx row 3, then stx row 3 into another buffer.
let row = 3u64 << 56;
let load = state(source.as_ptr() as u64 | row);
assert_eq!(
thread.complete(&instruction(LoadX, 0), &load, None),
Ok(Completion::Model)
);
let store = state(destination.as_mut_ptr() as u64 | row);
thread
.complete(&instruction(StoreX, 0), &store, None)
.unwrap();
assert_eq!(destination, source);
for address in [0, DIRECT_RAM_USER_END - 32, (1 << 55) | 0x1000] {
assert!(matches!(
thread.complete(&instruction(LoadZ, 0), &state(address), None),
Err(Failure::Memory { .. })
));
}
// X31 reads zero: a load from address zero faults.
assert_eq!(
thread.complete(&instruction(LoadY, 31), &GuestState::default(), None),
Err(Failure::Memory {
address: 0,
write: false
})
);
}
}
#[test]
fn native_kernels_and_the_model_produce_the_same_state() {
let Some(kernels) = Kernels::new(TargetCpu::detect()).unwrap() else {
return;
};
let mut seed = 0x5851_f42d_4c95_7f2d_u64;
let mut next = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
for kernel in Kernel::ALL {
let mut native = Thread::new();
let mut model = Thread::new();
unsafe {
native
.complete(&instruction(Set, 0), &GuestState::default(), None)
.unwrap();
model
.complete(&instruction(Set, 0), &GuestState::default(), None)
.unwrap();
}
let mut fill = AmxRegisters::zeroed();
for byte in fill.as_bytes_mut() {
*byte = next() as u8;
}
*native.registers.as_deref_mut().unwrap() = fill.clone();
*model.registers.as_deref_mut().unwrap() = fill;
for _ in 0..32 {
let random = next();
let operand = (random & 0x000f_ffff)
| ((random >> 20) & 63) << 20
| u64::from(kernel.product_only) << 27
| u64::from(kernel.shape == stela_compiler::x86_64::amx::Shape::Vector) << 63;
let operation = instruction(kernel.operation(), 0);
unsafe {
assert_eq!(
native.complete(&operation, &state(operand), Some(&kernels)),
Ok(Completion::Native(kernels.tier()))
);
assert_eq!(
model.complete(&operation, &state(operand), None),
Ok(Completion::Model)
);
}
}
assert_eq!(native.registers(), model.registers(), "{kernel:?}");
}
}
}
+55 -3
View File
@@ -42,7 +42,7 @@ pub(in crate::blocks) use translation::{
InstalledEl1Owner, InstalledEl1Sources, InstalledM0Owner, InstalledM0Sources,
};
use crate::{clock, execution::platform, floating, memory, pauth, system, thread};
use crate::{amx, clock, execution::platform, floating, memory, pauth, system, thread};
#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, string::String, string::ToString, vec::Vec};
use alloc::{collections::BTreeMap, rc::Rc};
@@ -63,8 +63,8 @@ use stela_compiler::{
},
};
use validate::{
validate_clock_exit, validate_interior_word, validate_numerical_exit, validate_pauth_exit,
validate_source_map, validate_system_exit, validate_terminal_word,
validate_amx_exit, validate_clock_exit, validate_interior_word, validate_numerical_exit,
validate_pauth_exit, validate_source_map, validate_system_exit, validate_terminal_word,
validate_thread_register_exit, validate_trap_exit,
};
@@ -107,6 +107,8 @@ pub struct BlockRuntime {
next_generation: u64,
regions: BTreeMap<u64, CodeRegion>,
loaded: BTreeMap<u64, LoadedBlock>,
/// Mapped on the first AMX exit; `Some(None)` when no tier is admitted.
amx_kernels: Option<Option<amx::Kernels>>,
_serialized: PhantomData<Rc<()>>,
}
@@ -557,6 +559,8 @@ impl BlockRuntime {
pointer_authentication_events: Vec::new(),
clock_events: Vec::new(),
thread_register_events: Vec::new(),
amx_operations: 0,
amx_native_operations: 0,
};
loop {
let pc = state.pc;
@@ -735,6 +739,21 @@ impl BlockRuntime {
} else {
None
};
let amx_instruction = if exit_kind == ExitKind::Amx {
ensure!(
self.profile.supports_amx(),
"block produced an unrequested AMX exit"
);
Some(validate_amx_exit(
pc,
GuestAddress(next_pc),
block.source_bytes,
block.region_base,
&current.source,
)?)
} else {
None
};
let system_boundary = if exit_kind == ExitKind::System {
ensure!(
self.profile.supports_system(),
@@ -817,6 +836,39 @@ impl BlockRuntime {
value,
});
}
if let Some(instruction) = amx_instruction {
let Some(thread) = thread_context else {
outcome.reason = StopReason::AmxRequired { instruction };
break;
};
if self.amx_kernels.is_none() {
self.amx_kernels = Some(amx::Kernels::new(self.target)?);
}
let kernels = self.amx_kernels.as_ref().and_then(Option::as_ref);
// SAFETY: this runtime executes the direct-RAM thread profile,
// whose guest addresses are host addresses of this process.
let completed = unsafe {
thread
.amx()
.complete(&instruction, &state.registers, kernels)
};
match completed {
Ok(completion) => {
state.pc = instruction.next_pc;
outcome.amx_operations += 1;
if matches!(completion, amx::Completion::Native(_)) {
outcome.amx_native_operations += 1;
}
}
Err(failure) => {
outcome.reason = StopReason::AmxFailure {
instruction,
failure,
};
break;
}
}
}
if let Some(instruction) = clock_instruction {
let Some(clock) = clock_context.as_deref_mut() else {
outcome.reason = StopReason::ClockRequired { instruction };
+3
View File
@@ -77,6 +77,7 @@ impl BlockRuntime {
next_generation: 0,
regions: BTreeMap::new(),
loaded: BTreeMap::new(),
amx_kernels: None,
_serialized: PhantomData,
}
}
@@ -249,6 +250,8 @@ mod tests {
memory_cache_hits: 0,
last_exit: None,
floating_point_helpers: 0,
amx_operations: 0,
amx_native_operations: 0,
pointer_authentication_events: Vec::new(),
clock_events: Vec::new(),
thread_register_events: Vec::new(),
+20 -1
View File
@@ -1,8 +1,9 @@
//! Run outcomes: why execution stopped and the service events it produced.
use crate::{memory, system};
use crate::{amx, memory, system};
#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
use serde::Serialize;
use stela_compiler::amx::AmxInstruction;
use stela_compiler::{
GuestAddress, GuestState,
block::{
@@ -90,6 +91,15 @@ pub enum StopReason {
ThreadRegisterRequired {
instruction: ThreadRegisterInstruction,
},
/// An AMX exit without a thread context to own the AMX state.
AmxRequired {
instruction: AmxInstruction,
},
/// The AMX instruction did not execute; see [`amx::Failure`].
AmxFailure {
instruction: AmxInstruction,
failure: amx::Failure,
},
SystemContextRequired {
instruction_pc: GuestAddress,
},
@@ -145,6 +155,11 @@ pub struct RunOutcome {
pub last_exit: Option<(u64, u64)>,
/// Successful numerical slowpath completions; no per-instruction event allocation.
pub floating_point_helpers: usize,
/// Completed AMX instructions, and how many of them ran native kernels.
#[serde(skip_serializing_if = "is_zero")]
pub amx_operations: usize,
#[serde(skip_serializing_if = "is_zero")]
pub amx_native_operations: usize,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub pointer_authentication_events: Vec<PointerAuthenticationEvent>,
#[serde(skip_serializing_if = "Vec::is_empty")]
@@ -152,3 +167,7 @@ pub struct RunOutcome {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub thread_register_events: Vec<ThreadRegisterEvent>,
}
fn is_zero(value: &usize) -> bool {
*value == 0
}
@@ -967,6 +967,8 @@ fn empty_accounting() -> RunOutcome {
memory_cache_hits: 0,
last_exit: None,
floating_point_helpers: 0,
amx_operations: 0,
amx_native_operations: 0,
pointer_authentication_events: Vec::new(),
clock_events: Vec::new(),
thread_register_events: Vec::new(),
@@ -168,6 +168,18 @@ pub(super) fn validate_thread_register_exit(
.context("thread-register exit does not identify a reviewed instruction")
}
pub(super) fn validate_amx_exit(
entry: GuestAddress,
exit: GuestAddress,
source_bytes: usize,
region_base: u64,
source: &[u8],
) -> Result<stela_compiler::amx::AmxInstruction> {
let word = validate_terminal_word(entry, exit, source_bytes, region_base, source)?;
stela_compiler::amx::decode(exit, word)?
.context("AMX exit does not identify an AMX instruction")
}
pub(super) fn validate_trap_exit(
entry: GuestAddress,
exit: GuestAddress,
@@ -121,6 +121,32 @@ impl<'rx, S: ExecutableStorage + ?Sized> NativeImage<'rx, S> {
})
}
/// Call an AMX kernel at `offset` in a `stela_compiler::x86_64::amx`
/// library image.
///
/// # Safety
/// `offset` starts a kernel of that image, `z` is a writable 4 KiB Z grid,
/// and `x` and `y` are 64 readable bytes each. The host admits the
/// library's tier.
#[cfg(feature = "std")]
pub(super) unsafe fn call_amx_kernel(
&self,
offset: usize,
z: *mut u8,
x: *const u8,
y: *const u8,
row: u64,
) -> Result<ReachedCall<(), S::Error>, S::Error> {
self.revalidate()?;
let function: unsafe extern "sysv64" fn(*mut u8, *const u8, *const u8, u64) =
unsafe { core::mem::transmute(self.storage.entry().as_ptr().add(offset)) };
unsafe { function(z, x, y, row) };
Ok(ReachedCall {
returned: (),
storage_after: self.revalidate(),
})
}
/// # Safety
/// The direct-RAM block ABI and every memory, fault and target requirement
/// apply, as does the PE session contract above.
@@ -76,4 +76,16 @@ impl Mapping {
pub unsafe fn call_block(&self, _state: &mut GuestState) -> Result<BlockExit> {
anyhow::bail!("freestanding native entry requires the original observed canonical session")
}
/// The boot platform admits only the baseline target, so no AMX kernel
/// tier is ever mapped here.
pub(crate) unsafe fn call_amx_kernel(
&self,
_offset: usize,
_z: *mut u8,
_x: *const u8,
_y: *const u8,
_row: u64,
) -> Result<()> {
anyhow::bail!("freestanding AMX kernels are not admitted")
}
}
@@ -181,6 +181,33 @@ impl Mapping {
Ok(reached.into_infallible())
}
/// Call the AMX kernel at `offset` in this library image.
///
/// # Safety
/// As for `NativeImage::call_amx_kernel`.
pub(crate) unsafe fn call_amx_kernel(
&self,
offset: usize,
z: *mut u8,
x: *const u8,
y: *const u8,
row: u64,
) -> Result<()> {
ensure!(
offset < self.length,
"AMX kernel offset outside its library"
);
// SAFETY: the mapping stays borrowed and the caller upholds the
// kernel ABI.
let reached =
match unsafe { NativeImage::borrow(self).call_amx_kernel(offset, z, x, y, row) } {
Ok(reached) => reached,
Err(never) => match never {},
};
reached.into_infallible();
Ok(())
}
#[cfg(test)]
pub fn address(&self) -> usize {
self.pointer.as_ptr() as usize
@@ -56,4 +56,15 @@ impl Mapping {
ensure_supported()?;
unreachable!()
}
pub(crate) unsafe fn call_amx_kernel(
&self,
_offset: usize,
_z: *mut u8,
_x: *const u8,
_y: *const u8,
_row: u64,
) -> Result<()> {
ensure_supported()
}
}
+1
View File
@@ -9,6 +9,7 @@ extern crate alloc;
compile_error!(
"freestanding runtime requires aborting panic; platform must terminate the machine on panic"
);
pub mod amx;
pub mod blocks;
pub mod boot_bundle;
pub mod clock;
+9
View File
@@ -1,6 +1,7 @@
//! A guest thread on the current host thread: identity, Mach rights and TSD
//! (XNU `thread_info.h`, `machine_thread_set_tsd_base`).
use crate::{
amx,
blocks::ThreadState,
darwin::{
self, BsdCompletion, BsdPrototype, BsdRequest, BsdReturnType, PendingBsdCall,
@@ -14,6 +15,7 @@ use alloc::rc::Rc;
#[cfg(not(feature = "std"))]
use alloc::{string::String, string::ToString};
use anyhow::{Result, ensure};
use core::cell::{RefCell, RefMut};
use serde::Serialize;
use stela_compiler::block::SynchronousTrap;
@@ -47,6 +49,8 @@ pub struct Context {
thread_specific_data: u64,
vm_maximum: VmMaximum,
process: Option<Rc<process::Context>>,
/// AMX registers live with the thread, like its TSD.
amx: RefCell<amx::Thread>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Snapshot {
@@ -68,6 +72,7 @@ impl Context {
thread_specific_data: 0,
vm_maximum,
process: None,
amx: RefCell::new(amx::Thread::new()),
})
}
/// Bind this thread to a declared process, acquiring the native thread
@@ -86,6 +91,10 @@ impl Context {
pub fn thread_specific_data(&self) -> u64 {
self.thread_specific_data
}
/// The thread's AMX state. Completion borrows it for one instruction.
pub fn amx(&self) -> RefMut<'_, amx::Thread> {
self.amx.borrow_mut()
}
pub fn snapshot(&self) -> Snapshot {
Snapshot {
profile_id: PROFILE_ID,
@@ -1509,3 +1509,5 @@ mod native_shared_region;
mod native_mach_vm_map;
mod native_process;
mod native_amx;
@@ -0,0 +1,254 @@
//! AMX instructions in translated guest blocks: the per-thread state, native
//! kernels and the model, and explicit stops.
#![cfg(target_os = "macos")]
use super::*;
use stela_compiler::{
TargetCpu,
amx::{AmxOperation, AmxRegisters, model},
block::BlockProfile,
};
use stela_runtime::{
amx::Failure,
memory::DIRECT_RAM_USER_END,
thread::{Context, VmMaximum},
};
const RET_X30: u32 = 0xd65f03c0;
const ADDRESS_SPACE_ID: u64 = 0x414d58;
/// Each AMX word ends a block.
const BUDGET: usize = 64;
fn word(operation: AmxOperation, register: u8) -> u32 {
operation.word(register)
}
fn amx_runtime(cache: &std::path::Path, words: &[u32], target: TargetCpu) -> Result<BlockRuntime> {
let mut runtime = BlockRuntime::new_for_target(
ADDRESS_SPACE_ID,
cache.into(),
BlockProfile::DarwinArm64ThreadV1,
target,
);
runtime.register_code(
GuestAddress(BASE),
words.iter().flat_map(|word| word.to_le_bytes()).collect(),
)?;
Ok(runtime)
}
/// A copy of guest memory that originally lived at `base`.
struct Host<'a> {
base: u64,
bytes: &'a mut [u8],
}
impl model::AmxMemory for Host<'_> {
fn read(&mut self, address: u64, destination: &mut [u8]) -> Result<(), model::MemoryFault> {
let start = (address - self.base) as usize;
destination.copy_from_slice(&self.bytes[start..start + destination.len()]);
Ok(())
}
fn write(&mut self, address: u64, source: &[u8]) -> Result<(), model::MemoryFault> {
let start = (address - self.base) as usize;
self.bytes[start..start + source.len()].copy_from_slice(source);
Ok(())
}
}
/// set; ldx; ldy; fma32 (matrix, native when admitted); fma32 (lane-masked,
/// model); four stz; clr; ret. The stored Z rows and the final state match the
/// model run over the same operands.
#[test]
fn guest_blocks_run_amx_with_thread_state_on_every_target() -> Result<()> {
let program = [
word(AmxOperation::Set, 0),
word(AmxOperation::LoadX, 0),
word(AmxOperation::LoadY, 1),
word(AmxOperation::Fma32, 2),
word(AmxOperation::Fma32, 3),
word(AmxOperation::StoreZ, 4),
word(AmxOperation::StoreZ, 5),
word(AmxOperation::StoreZ, 6),
word(AmxOperation::StoreZ, 7),
word(AmxOperation::Clear, 0),
RET_X30,
];
for target in [TargetCpu::Baseline, TargetCpu::detect()] {
let cache = tempfile::tempdir()?;
let mut runtime = amx_runtime(cache.path(), &program, target)?;
let context = Context::native(ADDRESS_SPACE_ID, VmMaximum::new(DIRECT_RAM_USER_END)?)?;
// X: 1.0 + i/16; Y: 2.0 - j/32, in two pairs of 64-byte rows.
let mut memory = vec![0u8; 512];
for lane in 0..16 {
let x = 1.0f32 + lane as f32 / 16.0;
let y = 2.0f32 - lane as f32 / 32.0;
memory[lane * 4..lane * 4 + 4].copy_from_slice(&x.to_le_bytes());
memory[64 + lane * 4..64 + lane * 4 + 4].copy_from_slice(&y.to_le_bytes());
}
let base = memory.as_ptr() as u64;
let mut state = thread(0, 0);
state.registers.x[0] = base;
state.registers.x[1] = base + 64;
// Z row group 1 with every lane; then group 2 with only X lane 3
// (mask mode 1), which the kernels leave to the model.
state.registers.x[2] = 1 << 20;
state.registers.x[3] = (2 << 20) | (1 << 46) | (3 << 41);
let store = |row: u64| base + 128 + 64 * (row - 1);
for (register, row) in [(4, 1), (5, 2), (6, 5), (7, 6)] {
state.registers.x[register] = store(row) | (row << 56);
}
// The model over a copy of the same memory.
let mut expected_memory = memory.clone();
let mut expected = AmxRegisters::zeroed();
let mut host = Host {
base,
bytes: &mut expected_memory,
};
for (operation, register) in [
(AmxOperation::LoadX, 0),
(AmxOperation::LoadY, 1),
(AmxOperation::Fma32, 2),
(AmxOperation::Fma32, 3),
(AmxOperation::StoreZ, 4),
(AmxOperation::StoreZ, 5),
(AmxOperation::StoreZ, 6),
(AmxOperation::StoreZ, 7),
] {
model::execute(
&mut expected,
operation,
state.registers.x[register],
&mut host,
)
.unwrap();
}
let before = state.registers.clone();
// SAFETY: AMX transfers touch only `memory`; RET leaves for STOP.
let outcome = unsafe {
runtime.run_with_thread(
&mut state,
Some(GuestAddress(STOP)),
BUDGET,
&context,
None,
None,
)?
};
assert_eq!(outcome.reason, StopReason::StopAddress);
assert_eq!(outcome.amx_operations, 10);
let native = usize::from(target.supports(TargetCpu::Fma));
assert_eq!(outcome.amx_native_operations, native);
assert_eq!(memory, expected_memory);
// Stored rows hold real products: z[j*4+1][i] = x[i] * y[j].
let z = f32::from_le_bytes(memory[128 + 4..128 + 8].try_into()?);
assert_eq!(z, (1.0 + 1.0 / 16.0) * 2.0);
// AMX writes no guest register; clr released the thread's state.
assert_eq!(state.registers, before);
assert!(!context.amx().enabled());
}
Ok(())
}
#[test]
fn amx_stops_are_explicit_and_keep_the_instruction_pending() -> Result<()> {
let cache = tempfile::tempdir()?;
let fma = word(AmxOperation::Fma64, 0);
let mut runtime = amx_runtime(cache.path(), &[fma, RET_X30], TargetCpu::detect())?;
let mut state = thread(0, 0);
let before = state.clone();
// Without a thread context the instruction stays pending.
// SAFETY: no instruction reaches memory.
let missing = unsafe { runtime.run(&mut state, Some(GuestAddress(STOP)), BUDGET)? };
let StopReason::AmxRequired { instruction } = missing.reason else {
bail!(
"AMX exit did not request its thread context: {:?}",
missing.reason
);
};
assert_eq!(instruction.word, fma);
assert_eq!(state.pc, GuestAddress(BASE));
// With a context but without `set`, the instruction is refused.
let context = Context::native(ADDRESS_SPACE_ID, VmMaximum::new(DIRECT_RAM_USER_END)?)?;
let disabled = unsafe {
runtime.run_with_thread(
&mut state,
Some(GuestAddress(STOP)),
BUDGET,
&context,
None,
None,
)?
};
assert_eq!(
disabled.reason,
StopReason::AmxFailure {
instruction,
failure: Failure::Disabled
}
);
assert_state(&state, &before);
// An address outside direct RAM is refused before any effect.
let load = word(AmxOperation::LoadZ, 0);
let mut runtime = amx_runtime(
cache.path(),
&[word(AmxOperation::Set, 0), load, RET_X30],
TargetCpu::detect(),
)?;
state.registers.x[0] = DIRECT_RAM_USER_END;
let fault = unsafe {
runtime.run_with_thread(
&mut state,
Some(GuestAddress(STOP)),
BUDGET,
&context,
None,
None,
)?
};
let StopReason::AmxFailure {
instruction,
failure,
} = fault.reason
else {
bail!("out-of-range AMX load completed");
};
assert_eq!(instruction.word, load);
assert_eq!(
failure,
Failure::Memory {
address: DIRECT_RAM_USER_END,
write: false
}
);
assert_eq!(state.pc, GuestAddress(BASE + 4));
assert_eq!(context.amx().registers(), Some(&AmxRegisters::zeroed()));
Ok(())
}
/// Profiles without a thread owner keep AMX words unsupported.
#[test]
fn profiles_without_thread_state_refuse_amx() -> Result<()> {
let cache = tempfile::tempdir()?;
let mut runtime = BlockRuntime::new_with_profile(
ADDRESS_SPACE_ID,
cache.path().into(),
BlockProfile::Ordinary,
);
runtime.register_code(
GuestAddress(BASE),
[word(AmxOperation::Set, 0), RET_X30]
.iter()
.flat_map(|word| word.to_le_bytes())
.collect(),
)?;
let mut state = thread(0, 0);
// SAFETY: the unsupported word is refused before execution.
let outcome = unsafe { runtime.run(&mut state, Some(GuestAddress(STOP)), BUDGET)? };
ensure!(
matches!(outcome.reason, StopReason::Unsupported { .. }),
"ordinary profile admitted AMX: {:?}",
outcome.reason
);
Ok(())
}