kh_runtime/cpu.rs
1//! Thin AArch64 register helpers (TPIDR_EL0, SP).
2//!
3//! **Safety wall:** this is the only module that may `mrs`/`msr` `TPIDR_EL0`.
4//! All guest↔host TLS switches go through [`crate::thread`] wrappers that keep
5//! a per-thread host snapshot in `HostMeta`.
6#![allow(unsafe_code)]
7
8/// Reads `TPIDR_EL0` (user thread pointer; host glibc TLS / guest TSD).
9///
10/// # Safety
11///
12/// Pure register read; always safe on AArch64. Callers must treat the value as
13/// either host libc TLS or guest TSD depending on the current execution realm.
14#[cfg(target_arch = "aarch64")]
15#[inline]
16#[must_use]
17pub fn read_tpidr_el0() -> u64 {
18 let val: u64;
19 // SAFETY: `mrs` of TPIDR_EL0 is a pure register read.
20 unsafe {
21 core::arch::asm!(
22 "mrs {}, tpidr_el0",
23 out(reg) val,
24 options(nomem, nostack, preserves_flags),
25 );
26 }
27 val
28}
29
30/// Writes `TPIDR_EL0`.
31///
32/// # Safety
33///
34/// Caller must ensure `val` is a valid pointer for the next execution realm
35/// (host glibc TLS or guest TSD base). Wrong value breaks host TLS or guest
36/// `___error` / TSD until restored.
37#[cfg(target_arch = "aarch64")]
38#[inline]
39pub unsafe fn write_tpidr_el0(val: u64) {
40 // SAFETY: caller guarantees `val` is the correct realm pointer.
41 unsafe {
42 core::arch::asm!(
43 "msr tpidr_el0, {}",
44 in(reg) val,
45 options(nomem, nostack, preserves_flags),
46 );
47 }
48}
49
50/// Reads the current stack pointer.
51///
52/// # Safety
53///
54/// Pure register read.
55#[cfg(target_arch = "aarch64")]
56#[inline]
57#[must_use]
58pub fn read_sp() -> u64 {
59 let sp: u64;
60 // SAFETY: pure SP move.
61 unsafe {
62 core::arch::asm!(
63 "mov {}, sp",
64 out(reg) sp,
65 options(nomem, nostack, preserves_flags),
66 );
67 }
68 sp
69}
70
71#[cfg(not(target_arch = "aarch64"))]
72#[inline]
73#[must_use]
74pub fn read_tpidr_el0() -> u64 {
75 0
76}
77
78#[cfg(not(target_arch = "aarch64"))]
79#[inline]
80/// # Safety
81///
82/// No-op on non-AArch64.
83pub unsafe fn write_tpidr_el0(_val: u64) {}
84
85#[cfg(not(target_arch = "aarch64"))]
86#[inline]
87#[must_use]
88pub fn read_sp() -> u64 {
89 0
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn tpidr_roundtrip_restores() {
98 #[cfg(target_arch = "aarch64")]
99 {
100 let original = read_tpidr_el0();
101 // SAFETY: host libc TLS uses TPIDR_EL0 — never assert/format while it
102 // points at a non-host value (glibc would SEGV on thread-locals).
103 let seen = unsafe {
104 write_tpidr_el0(0xDEAD_BEEF_CAFE_u64);
105 let v = read_tpidr_el0();
106 write_tpidr_el0(original);
107 v
108 };
109 assert_eq!(seen, 0xDEAD_BEEF_CAFE_u64);
110 assert_eq!(read_tpidr_el0(), original);
111 }
112 #[cfg(not(target_arch = "aarch64"))]
113 {
114 assert_eq!(read_tpidr_el0(), 0);
115 }
116 }
117}