Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ Cargo.lock
tests/kernel/mtstress
tests/kernel/lzmat
__pycache__/
tests/kernel/tbi
16 changes: 16 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1285,6 +1285,18 @@ the code and its commit history are authoritative.
sleeping in `futex()` pins all of them). The epoch is published after the table
reset, so a thread that sees it can't pick up a stale table entry.
- **io_uring is disabled for guests** (§11.2).
- **Top-byte-ignore (TBI).** arm64 Linux ignores bits 63:56 of user data
addresses. The interpreter applies this to every data access. Translated code
doesn't mask addresses, so untagged programs pay nothing. A tagged pointer is
non-canonical on x86, so a tagged access raises #GP. A #GP hook in
`exc_general_protection` recovers the guest state and runs the instruction in
the interpreter, then continues, or delivers `SEGV_MAPERR`/`SEGV_ACCERR` with
the untagged address, as arm64 reports it. After 8 such faults a block is
retranslated with address masking (`Cfg::tbi`: the base is copied and untagged
with `shl 8; sar 8`; atomics and exclusives use the interpreter helper), and
such translations bypass the shared cache. The tagged-address syscall ABI
(`PR_SET_TAGGED_ADDR_CTRL`) isn't supported, so syscalls given tagged pointers
fail with `EFAULT` (the arm64 default).
- **Oversized superblocks.** When exit slots or recovery points run out, the
translation is retried with half the instruction limit instead of failing.

Expand All @@ -1301,6 +1313,10 @@ the code and its commit history are authoritative.
translation time, flushes and targeted invalidations.
- `kemu.stress=<n>` bumps the epoch and kicks every other thread once per n
translations. This forces state recovery at arbitrary points in translated code.
(State recovery once mistook a block's exit trampolines, which run after the
remap epilogue, for remapped code. A thread interrupted there got one guest
register's value in another, which crashed HotSpot's C2 compiler about once in
60 runs. Trampolines now start with an explicit canonical `REMAP 0` point.)
- kemu-user:
- `KEMU_JIT_STATS` prints a helper-instruction histogram;
- `KEMU_XLAT_BENCH=<span>` measures translator throughput;
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ Performance, measured against native x86_64 builds of the same C source
| qsort | ~84% |
| matmul (NEON) | ~65% |

Tagged pointers work as on arm64 Linux: the top byte of data addresses is
ignored (TBI). Untagged code runs at full speed; code that uses tags is
retranslated with address masking after a few faults.

io_uring isn't offered to arm64 programs (the syscalls return `ENOSYS` and
libraries fall back to plain syscalls), because ring operations use native
struct layouts behind kemu's back.
Expand Down
3 changes: 3 additions & 0 deletions overlay/include/linux/kemu.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,14 @@ void kemu_unmapped(struct mm_struct *mm, unsigned long start, unsigned long end)
bool kemu_vma_hidden(struct vm_area_struct *vma);
int kemu_show_cpuinfo(struct seq_file *m, unsigned int cpu);
bool kemu_user_fault(struct pt_regs *regs, unsigned long address);
bool kemu_user_gp(struct pt_regs *regs);

#else /* !CONFIG_KEMU */

#define task_is_kemu(t) false

static inline bool kemu_user_gp(struct pt_regs *regs) { return false; }

static inline void kemu_exit_to_user(struct pt_regs *regs) { }
static inline void kemu_do_signal(struct pt_regs *regs) { }
static inline int kemu_dup_mm(struct mm_struct *oldmm, struct mm_struct *mm) { return 0; }
Expand Down
5 changes: 3 additions & 2 deletions overlay/kernel/kemu/core.c
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ static struct kemu_mm *kemu_mm_alloc(void)
xa_init(&km->binfo);
xa_init(&km->pages);
xa_init(&km->sites);
xa_init(&km->tbi_pcs);
spin_lock_init(&km->pend_lock);
ida_init(&km->slot_ida);
spin_lock_init(&km->threads_lock);
Expand All @@ -160,10 +161,10 @@ static void kemu_mm_free(struct kemu_mm *km)
unsigned long xe, xb;

kemu_xc_stats(&xe, &xb);
pr_info("kemu: %s[%d] mm stats: %lu translations (%lu from xcache), %lu lookups (%llu us), %lu chains, %lu helpers, %lu flushes, %lu invalidations (%lu blocks), %lu interp insns; xcache %lu entries %lu KiB, %ld hits %ld misses %ld stale\n",
pr_info("kemu: %s[%d] mm stats: %lu translations (%lu from xcache), %lu lookups (%llu us), %lu chains, %lu helpers, %lu flushes, %lu invalidations (%lu blocks), %lu tagged accesses emulated, %lu interp insns; xcache %lu entries %lu KiB, %ld hits %ld misses %ld stale\n",
current->comm, task_pid_nr(current), km->translations, km->xc_hits,
km->lookups, km->translate_ns / 1000, km->chains, km->helpers,
km->flushes, km->invals, km->killed, km->interp_insns, xe, xb >> 10,
km->flushes, km->invals, km->killed, km->tbi_emul, km->interp_insns, xe, xb >> 10,
atomic_long_read(&kemu_xc_hits), atomic_long_read(&kemu_xc_misses),
atomic_long_read(&kemu_xc_stale));
}
Expand Down
62 changes: 59 additions & 3 deletions overlay/kernel/kemu/jit.c
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ void kemu_jit_free(struct kemu_mm *km)
kemu_chunk_free(km, c);
xa_destroy(&km->blocks);
kemu_inval_free(km);
xa_destroy(&km->tbi_pcs);
kvfree(km->scratch);
km->scratch = NULL;
}
Expand Down Expand Up @@ -532,7 +533,7 @@ static int kemu_translate(struct kemu_mm *km, u64 pc, unsigned long *main,
struct kemu_xc_key key;
unsigned long off, uaddr;
u64 pages[KEMU_MAX_PAGES];
bool cacheable;
bool cacheable, tbi;
int c, err, tries = 0, npages = -1;
u64 gpc;
u32 moff;
Expand All @@ -554,7 +555,9 @@ static int kemu_translate(struct kemu_mm *km, u64 pc, unsigned long *main,
return 0;
}

cacheable = kemu_xc_key(pc, &key);
/* Blocks that keep faulting on tagged pointers mask addresses (TBI). */
tbi = xa_load(&km->tbi_pcs, pc >> 2) != NULL;
cacheable = !tbi && kemu_xc_key(pc, &key);
for (;;) {
if (km->cur_chunk < 0) {
err = kemu_chunk_new(km);
Expand All @@ -574,7 +577,7 @@ static int kemu_translate(struct kemu_mm *km, u64 pc, unsigned long *main,
}
err = kemu_rs_translate(km->scratch, pc, out,
KEMU_CHUNK_SIZE - km->chunk_used[c], uaddr,
km->code_base, &km->stubs, res, cacheable);
km->code_base, &km->stubs, res, cacheable, tbi);
if (err == -ENOSPC && km->chunk_used[c] > 0 && tries++ < 4) {
km->cur_chunk = -1;
continue;
Expand Down Expand Up @@ -782,6 +785,59 @@ void kemu_jit_exit_to_user(struct kemu_thread *kt, struct pt_regs *regs)
}
}

/*
* #GP in translated code: a non-canonical data address. On arm64 that is a
* tagged pointer (TBI ignores the top byte) or an address beyond the VA
* range (a translation fault). Untagged code runs without masking, so run
* the instruction in the interpreter, which applies TBI, and either carry
* on or deliver the fault as arm64 would. Blocks that do this often are
* retranslated with address masking.
*/
#define KEMU_TBI_RETRANSLATE 8

bool kemu_user_gp(struct pt_regs *regs)
{
struct kemu_thread *kt = current->kemu;
struct kemu_mm *km = current->mm->kemu;
unsigned long ip = kemu_reg(regs, ip), off, boff;
struct kemu_blkinfo *bi;
struct kemu_rs_exit ex;
size_t len;
u8 *blk;

if (!kt || !km || ip < km->code_base + KEMU_CHUNK_SIZE ||
ip >= km->code_base + KEMU_CODE_SIZE)
return false;
off = ip - km->code_base;
kemu_materialize(regs);

mutex_lock(&km->lock);
blk = kemu_find_block(km, off, &len);
if (blk) {
boff = (off & ~(KEMU_CHUNK_SIZE - 1)) +
(blk - (u8 *)km->chunks[off >> KEMU_CHUNK_SHIFT]);
bi = xa_load(&km->binfo, boff / KEMU_BLOCK_ALIGN);
if (bi && ++bi->tbi_faults >= KEMU_TBI_RETRANSLATE &&
!xa_err(xa_store(&km->tbi_pcs, bi->pc >> 2, xa_mk_value(1), GFP_KERNEL)))
kemu_blk_kill(km, boff);
}
mutex_unlock(&km->lock);

kt->shadow = *kt->cpu;
kemu_rs_interp(&kt->shadow, 1, &ex);
switch (ex.kind) {
case KEMU_EXIT_BUDGET:
*kt->cpu = kt->shadow;
km->tbi_emul++;
return true;
case KEMU_EXIT_FAULT:
kemu_force_fault(ex.addr, ex.access, ex.aux);
return true;
default:
return false;
}
}

/* ---- kemu ops from stubs ---- */

static unsigned long kemu_op_translate(struct kemu_thread *kt, struct kemu_mm *km,
Expand Down
5 changes: 4 additions & 1 deletion overlay/kernel/kemu/kemu_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ struct kemu_mm {
struct xarray pages; /* guest page >> PAGE_SHIFT -> kemu_pgvec */
struct kemu_pgvec *wide; /* blocks reading too many pages to index */
struct xarray sites; /* chained rel32 offset -> xa_mk_value(unchained value) */
struct xarray tbi_pcs; /* guest pc >> 2 of blocks translated with TBI */
u64 epoch; /* bumped on every flush or invalidation */
atomic_t flush_pending; /* executable mapping went away */
spinlock_t pend_lock;
Expand All @@ -130,6 +131,7 @@ struct kemu_mm {
unsigned long flushes;
unsigned long invals; /* targeted invalidations */
unsigned long killed; /* blocks they removed */
unsigned long tbi_emul; /* tagged accesses run by the interpreter */
unsigned long lookups; /* TRANSLATE/CHAIN ops */
unsigned long xc_hits; /* translations taken from the xcache */
u64 translate_ns; /* time spent in those ops */
Expand All @@ -146,6 +148,7 @@ struct kemu_blkinfo {
u32 off; /* code offset of the block */
u32 size;
u32 nin, cap;
u32 tbi_faults; /* tagged-pointer #GPs in this block */
struct kemu_chain_site *in;
};

Expand Down Expand Up @@ -299,7 +302,7 @@ int kemu_rs_gen_stubs(u8 *out, size_t len, u64 table_base, u32 mask8,
size_t kemu_rs_scratch_size(void);
int kemu_rs_translate(void *scratch, u64 pc, u8 *out, size_t len, u64 code_uaddr,
u64 stubs_base, const struct kemu_stubs *info,
struct kemu_trans *res, bool reloc);
struct kemu_trans *res, bool reloc, bool tbi);
long kemu_rs_xc_blob_size(void *scratch);
long kemu_rs_xc_blob(void *scratch, u64 pc, u64 blk_off, u8 *out, size_t len);
bool kemu_rs_xc_validate(const u8 *blob, size_t len, u64 pc);
Expand Down
3 changes: 2 additions & 1 deletion overlay/kernel/kemu/kemu_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ pub unsafe extern "C" fn kemu_rs_translate(
info: *const KemuStubs,
res: *mut KemuTrans,
reloc: bool,
tbi: bool,
) -> c_int {
// SAFETY: `Scratch` is repr(C) and made only of integers, so any
// initialized bytes are a valid value; the rest is guaranteed by the
Expand All @@ -364,7 +365,7 @@ pub unsafe extern "C" fn kemu_rs_translate(
&mut *res,
)
};
let cfg = t1::Cfg { stubs: info.addrs(stubs_base), code_uaddr, reloc };
let cfg = t1::Cfg { stubs: info.addrs(stubs_base), code_uaddr, reloc, tbi };
match t1::translate(&mut KEnv, pc, out, &cfg, s) {
Ok(r) => {
res.size = r.size as u64;
Expand Down
53 changes: 53 additions & 0 deletions overlay/rust/kemu_core/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,56 @@ pub trait Env {
/// Hardware random number for RNDR/RNDRRS; `None` on failure.
fn random(&mut self) -> Option<u64>;
}

/// Top-byte-ignore for EL0 data addresses, as Linux configures arm64
/// (TCR_EL1.TBI0): bits 63:56 are replaced by bit 55. Linux also reports
/// fault addresses without the tag (unless SA_EXPOSE_TAGBITS).
#[inline]
pub const fn untag(addr: u64) -> u64 {
((addr << 8) as i64 >> 8) as u64
}

/// `Env` adapter applying [`untag`] to every data access (not to fetch).
pub struct Tbi<'a, E: Env>(pub &'a mut E);

impl<E: Env> Env for Tbi<'_, E> {
fn fetch(&mut self, pc: u64) -> Result<u32, Fault> {
self.0.fetch(pc)
}
fn read_u8(&mut self, addr: u64) -> Result<u8, Fault> {
self.0.read_u8(untag(addr))
}
fn read_u16(&mut self, addr: u64) -> Result<u16, Fault> {
self.0.read_u16(untag(addr))
}
fn read_u32(&mut self, addr: u64) -> Result<u32, Fault> {
self.0.read_u32(untag(addr))
}
fn read_u64(&mut self, addr: u64) -> Result<u64, Fault> {
self.0.read_u64(untag(addr))
}
fn write_u8(&mut self, addr: u64, val: u8) -> Result<(), Fault> {
self.0.write_u8(untag(addr), val)
}
fn write_u16(&mut self, addr: u64, val: u16) -> Result<(), Fault> {
self.0.write_u16(untag(addr), val)
}
fn write_u32(&mut self, addr: u64, val: u32) -> Result<(), Fault> {
self.0.write_u32(untag(addr), val)
}
fn write_u64(&mut self, addr: u64, val: u64) -> Result<(), Fault> {
self.0.write_u64(untag(addr), val)
}
fn cmpxchg(&mut self, addr: u64, size: u32, expected: [u64; 2], new: [u64; 2]) -> Result<[u64; 2], Fault> {
self.0.cmpxchg(untag(addr), size, expected, new)
}
fn cntvct(&mut self) -> u64 {
self.0.cntvct()
}
fn cntfrq(&mut self) -> u64 {
self.0.cntfrq()
}
fn random(&mut self) -> Option<u64> {
self.0.random()
}
}
3 changes: 2 additions & 1 deletion overlay/rust/kemu_core/src/interp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn run<E: Env>(cpu: &mut CpuState, env: &mut E, max_insns: u32) -> (Exit, u3
Err(f) => return (Exit::Fault(f), n),
};
let insn = decode(word);
match step(cpu, env, insn, word) {
match step(cpu, &mut crate::env::Tbi(&mut *env), insn, word) {
Step::Next => {
cpu.pc = cpu.pc.wrapping_add(4);
n += 1;
Expand All @@ -52,6 +52,7 @@ pub fn run<E: Env>(cpu: &mut CpuState, env: &mut E, max_insns: u32) -> (Exit, u3
cpu.pc = t;
n += 1;
}
Step::Exit(Exit::IcInvalidate(va)) => return (Exit::IcInvalidate(crate::env::untag(va)), n),
Step::Exit(e) => return (e, n),
}
}
Expand Down
78 changes: 77 additions & 1 deletion overlay/rust/kemu_core/src/interp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,22 @@ fn memory_roundtrip() {
assert_eq!(cpu.x[2], 0xabcd);
}

#[test]
fn tagged_pointer_tbi() {
// movz x1,#0x2000; movk x1,#0x5a00,lsl #48 (tag 0x5a); movz x0,#0xabcd;
// str x0,[x1]; movz x5,#0x2000; ldr x2,[x5]; svc
let (cpu, e) = run_code(&[0xd2840001, 0xf2eb4001, 0xd29579a0, 0xf9000020, 0xd2840005, 0xf94000a2, 0xd4000001]);
assert_eq!(e, Exit::Svc);
assert_eq!(cpu.x[2], 0xabcd);
// A fault through a tagged pointer reports the untagged address.
// movz x1,#0xfff0,lsl #16 (0xfff00000); movk x1,#0x3300,lsl #48; ldr x0,[x1]
let (_, e) = run_code(&[0xd2bffe01, 0xf2e66001, 0xf9400020]);
match e {
Exit::Fault(f) => assert_eq!(f.addr, 0xfff0_0000),
e => panic!("expected fault, got {e:?}"),
}
}

#[test]
fn ccmp_and_cond() {
// cmp x0,#0 (x0=0) => eq; cset x0,eq -> 1
Expand Down Expand Up @@ -246,7 +262,7 @@ fn xcache_validate_and_relocate() {
};
let mut page = std::vec![0u8; 4096];
let so = stubs::gen_stubs(&mut page, stubs::ExitMode::Syscall, 0x7000_1000_0000, 0xfff8).expect("stubs");
let cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0000_0000 + (1 << 20), reloc: true };
let cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0000_0000 + (1 << 20), reloc: true, tbi: false };
let mut s = std::boxed::Box::new(t1::Scratch::new());
let mut out = std::vec![0u8; 8192];
let mut env = mk(0x40_0000, None);
Expand All @@ -272,3 +288,63 @@ fn xcache_validate_and_relocate() {
assert!(!xcache::validate(&mut mk(base2, Some((5, 0x8b020021))), blob, base2));
assert!(!xcache::validate(&mut mk(base2 + 4, None), blob, base2 + 4));
}

/// A thread interrupted in an exit trampoline of a remapped block must be
/// recovered with the canonical register map: every path into the
/// trampolines has run the remap epilogue, even if the block's main code
/// ends in the remapped state (here: a self-loop back-edge).
#[test]
fn recover_in_exit_trampoline_of_remapped_block() {
use crate::jit::{meta, regmap, stubs, t1};
let code: [u32; 6] = [
0x91000718, // add x24, x24, #1
0x91000718, // add x24, x24, #1
0x91000718, // add x24, x24, #1
0xeb09031f, // cmp x24, x9
0x54000800, // b.eq +0x100 (exit through a trampoline)
0x17fffffb, // b pc0 (back-edge: the main code ends remapped)
];
let mut mem = std::vec![0u8; 0x2000];
for (i, w) in code.iter().enumerate() {
mem[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes());
}
let mut env = TestEnv { mem, base: 0x40_0000 };
let mut page = std::vec![0u8; 4096];
let so = stubs::gen_stubs(&mut page, stubs::ExitMode::Syscall, 0x7000_1000_0000, 0xfff8).expect("stubs");
let cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0000_0000 + (1 << 20), reloc: false, tbi: false };
let mut s = std::boxed::Box::new(t1::Scratch::new());
let mut out = std::vec![0u8; 8192];
let r = t1::translate(&mut env, 0x40_0000, &mut out, &cfg, &mut s).expect("translate");
let blk = &out[..r.size];

// Trampolines: "lea rdx, [rip + site]" right before the jump to the chain stub.
let mut tramps = std::vec::Vec::new();
for o in 0..blk.len().saturating_sub(3) {
if blk[o..o + 3] == [0x48, 0x8d, 0x15] {
tramps.push(o as u32);
}
}
assert!(!tramps.is_empty(), "no exit trampolines found");

let mut h = meta::HostRegs { gpr: [0; 16], rflags: 0x202 };
for (i, g) in h.gpr.iter_mut().enumerate() {
*g = 0x1000 + i as u64;
}
for off in tramps {
let mut st = CpuState::new();
for n in 0..31 {
st.set_xr(n, 0x9000 + n as u64);
}
st.sp = 0x9999;
assert!(meta::recover(blk, off, &h, &mut st), "recover at {off:#x}");
// Canonical: pinned registers from their host registers, the rest
// from the state page.
for (g, hr) in regmap::PINNED.iter() {
let want = h.gpr[(*hr & 15) as usize];
let got = if *g == regmap::GUEST_SP { st.sp } else { st.xr(*g) };
assert_eq!(got, want, "pinned guest reg {g} at trampoline offset {off:#x}");
}
assert_eq!(st.xr(24), 0x9000 + 24, "x24 at trampoline offset {off:#x}");
assert_eq!(st.xr(9), 0x9000 + 9, "x9 at trampoline offset {off:#x}");
}
}
Loading
Loading