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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ jobs:
$j 20000 7 7
INTR=50 RELOC=1 $j 20000 8 7
NO_AES=1 NO_PCLMUL=1 INTR=50 RELOC=1 $j 20000 9 7
INTR=20 RELOC=1 $j 10000 10 8
NO_VCACHE=1 INTR=20 RELOC=1 $j 10000 10 8
INTR=20 RELOC=1 $j 10000 32 3
- name: kemu-user smoke test
run: |
u=tools/kemu-user/target/release/kemu-user
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ tests/kernel/mtstress
tests/kernel/lzmat
__pycache__/
tests/kernel/tbi
tests/kernel/vector-state
30 changes: 20 additions & 10 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,11 +546,12 @@ in the translator:
- **Spill hoisting.** Fills and spills of guest registers that aren't live-through
a loop are moved to the loop's preheader and exits.

**Vector registers.** V0–V13 are pinned to `xmm0–xmm13`, with `xmm14`/`xmm15` as
scratch. V14–V31 live in `gs:[…]`. That's a good fit for AAPCS code, where V16–V31
are short-lived temporaries T2 can allocate inside regions. Upper YMM halves are kept
clean (VEX encoding everywhere, no legacy SSE), so there are no transition penalties
and no `vzeroupper`.
**Vector registers.** T1 assigns up to eight frequently used guest vectors to
`xmm0–xmm7` within each block, reserving `xmm8–xmm15` for lowering temporaries.
Unallocated vectors live in `gs:[…]`. Self-loop back-edges retain the allocation;
other block boundaries use the state page. T2 can extend allocation across blocks.
Upper YMM halves stay clean (VEX encoding everywhere, no legacy SSE), so there
are no transition penalties and no `vzeroupper`.

### 8.2 Flags (NZCV)

Expand Down Expand Up @@ -1259,10 +1260,18 @@ the code and its commit history are authoritative.
- cross-block flag liveness: direct exit targets are scanned and the flags image
is skipped when the target writes NZCV first;
- out-of-line flag saves on taken B.cond exits.
- **Guest V registers live in the state page.** Each NEON/FP operation loads and
stores through `%gs`. Block-level xmm allocation needs xmm-aware state recovery
in the kernel (reading guest values out of saved FPU state). It's the main
remaining performance item (matmul).
- **Block-local vector allocation.** Up to eight frequently used guest vectors
live in XMM0..7; XMM8..15 remain lowering temporaries. The allocation is fixed
per block and retained across self-loop back-edges. Other exits and interpreter
helpers spill the cache; helper returns refill it. Full, scalar and lane
accesses share cache-aware accessors, and results commit in one host instruction.
The metadata header records the mapping; `VSTATE` points distinguish the page
from saved XMM state without replacing instruction/flags recovery points.
During fills the page stays authoritative, and during spills XMM stays
authoritative until the last store. The kernel captures the interrupted task's
XMM state via an architecture hook (see README). Ports without the hook keep
the memory-only representation. Cross-block allocation and dynamic eviction
remain future work.
- **Shared-cache keying.** The cache is keyed by (sb, ino, i_generation, file
offset) and validated by content. Every guest instruction word a translation
read, including flag look-ahead into exit targets, is re-read at the new
Expand Down Expand Up @@ -1308,7 +1317,8 @@ the code and its commit history are authoritative.
- 2: helper for SIMD/FP;
- 4: one-instruction blocks;
- 8: no chaining;
- 32: no register remapping.
- 32: no register remapping;
- 64: no vector cache (`NO_VCACHE=1` in userspace tools).
- `kemu.debug=1` prints per-mm statistics: translations, shared-cache hits,
translation time, flushes and targeted invalidations.
- `kemu.stress=<n>` bumps the epoch and kicks every other thread once per n
Expand Down
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Working:
- Threads, futexes, LL/SC and seq_cst atomics, signals, ptrace and
single-step, core dumps, seccomp/audit as `AUDIT_ARCH_AARCH64`.
- T1 JIT with superblocks, block chaining, register remapping and lazy flags.
- Block-local caching of up to eight guest vectors in XMM registers, retained
across self-loops, with saved-XMM recovery for signals and faults.
- SHA-256 rounds, message schedules and vector byte reversal translated to
AVX2, without kernel entries per instruction or a requirement for host
SHA extensions.
Expand Down Expand Up @@ -61,7 +63,7 @@ libraries fall back to plain syscalls), because ring operations use native
struct layouts behind kemu's back.

Not done yet: a real vDSO, rseq, perf callchains through translated code, the
optimizing tier (T2), host-register allocation for NEON, the LSM hook and the
optimizing tier (T2), cross-block vector allocation, the LSM hook and the
code-cache verifier.

## Layout
Expand Down Expand Up @@ -113,6 +115,14 @@ register access, syscall entry, TLS, fault information and ELF personality.
The native implementation lives in `overlay/arch/x86/`; other x86_64 kernel
ports supply their own architecture code and select `HAVE_KEMU`.

To enable the vector register cache, a port defines `KEMU_ARCH_VECTOR_CACHE`
as 1 and provides `kemu_arch_read_xmm(u64 xmm[8][2])` in `asm/kemu.h`. It must
capture the interrupted task's user XMM0..7, synchronizing live FPU state
first, and work in task context with IRQs either enabled or disabled. Without
this opt-in, vectors remain in the state page. The native implementation
handles lazy FPU state and XSAVE's init-state optimization. Userspace callers
opt in with `Cfg::vector_cache` and supply `HostRegs::xmm` during recovery.

Host atomic access, the virtual counter and random-number generation use
the `kemu_arch_*` services declared in `include/linux/kemu.h`. The common
layer validates atomic sizes and alignment before calling the backend.
Expand Down Expand Up @@ -158,7 +168,7 @@ x86 applets over the rootfs's binaries.
| Parameter | Effect |
|---|---|
| `kemu.jit=0` | interpreter only |
| `kemu.jitoff=<mask>` | turn off JIT features one at a time, for bisecting (1 helper for all non-branches, 2 helper for SIMD/FP, 4 one-insn blocks, 8 no chaining, 32 no register remapping) |
| `kemu.jitoff=<mask>` | turn off JIT features one at a time, for bisecting (1 helper for all non-branches, 2 helper for SIMD/FP, 4 one-insn blocks, 8 no chaining, 32 no register remapping, 64 no vector cache) |
| `kemu.xcache=0` | disable the shared translation cache |
| `kemu.xcache_mb=<n>` | shared cache size limit (default 128) |
| `kemu.debug=1` | per-process translation statistics on exit |
Expand Down
4 changes: 4 additions & 0 deletions overlay/arch/x86/include/asm/kemu.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
#include <asm/prctl.h>
#include <asm/proto.h>

/* Opt in only when asynchronous recovery can capture user XMM0..7. */
#define KEMU_ARCH_VECTOR_CACHE 1
void kemu_arch_read_xmm(u64 xmm[8][2]);

#define kemu_reg(regs, name) ((regs)->name)

static inline long kemu_syscall_enter(struct pt_regs *regs)
Expand Down
30 changes: 30 additions & 0 deletions overlay/arch/x86/kemu/env.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,36 @@
#include <linux/highmem.h>
#include <asm/tsc.h>
#include <asm/archrandom.h>
#include <asm/fpu/api.h>
#include <asm/fpu/sched.h>
#include <asm/kemu.h>

void kemu_arch_read_xmm(u64 xmm[8][2])
{
struct fpu *fpu = x86_task_fpu(current);
const void *src;

/*
* The image may be stale until the live FPU is saved. Epoch recovery
* runs with IRQs off, which already excludes preemption/softirqs;
* fpu_sync_fpstate() uses BH locking and requires IRQs enabled.
*/
if (irqs_disabled()) {
if (!test_thread_flag(TIF_NEED_FPU_LOAD))
save_fpregs_to_fpstate(fpu);
} else {
fpu_sync_fpstate(fpu);
}
if (boot_cpu_has(X86_FEATURE_XSAVE))
src = get_xsave_addr(&fpu->fpstate->regs.xsave, XFEATURE_SSE);
else
src = fpu->fpstate->regs.fxsave.xmm_space;
/* XSAVE's init optimization can leave stale bytes in the image. */
if (src)
memcpy(xmm, src, 8 * 16);
else
memset(xmm, 0, 8 * 16);
}

static int kemu_cmpxchg128(u64 addr, const u64 *exp, const u64 *new, u64 *old)
{
Expand Down
21 changes: 9 additions & 12 deletions overlay/kernel/kemu/jit.c
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,8 @@ 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, tbi);
km->code_base, &km->stubs, res, cacheable, tbi,
KEMU_ARCH_VECTOR_CACHE);
if (err == -ENOSPC && km->chunk_used[c] > 0 && tries++ < 4) {
km->cur_chunk = -1;
continue;
Expand Down Expand Up @@ -693,6 +694,11 @@ static void kemu_host_regs(struct pt_regs *regs, struct kemu_host_regs *h)
h->gpr[14] = kemu_reg(regs, r14);
h->gpr[15] = kemu_reg(regs, r15);
h->rflags = kemu_reg(regs, flags);
#if KEMU_ARCH_VECTOR_CACHE
kemu_arch_read_xmm(h->xmm);
#else
memset(h->xmm, 0, sizeof(h->xmm));
#endif
}

static u32 kemu_stub_info(struct kemu_mm *km, u32 off)
Expand Down Expand Up @@ -724,17 +730,8 @@ void kemu_materialize(struct pt_regs *regs)
kemu_host_regs(regs, &h);
kt->shadow = *cpu;
if (ip >= km->code_base && ip < km->code_base + KEMU_STUBS_SIZE) {
switch (kemu_stub_info(km, ip - km->code_base)) {
case KEMU_STUB_PINNED_LIVE_PC_RAX:
kt->shadow.pc = kemu_reg(regs, ax);
fallthrough;
case KEMU_STUB_PINNED_LIVE:
kemu_rs_pinned_from_host(&h, &kt->shadow);
break;
default:
break;
}
kt->shadow.nzcv = kemu_rs_nzcv_from_image(kt->shadow.flags_x86);
kemu_rs_recover_stub(kemu_stub_info(km, ip - km->code_base),
&h, &kt->shadow);
} else if (ip >= km->code_base && ip < km->code_base + KEMU_CODE_SIZE) {
off = ip - km->code_base;
blk = kemu_find_block(km, off, &len);
Expand Down
11 changes: 7 additions & 4 deletions overlay/kernel/kemu/kemu_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@

#include <asm/kemu.h>

#ifndef KEMU_ARCH_VECTOR_CACHE
#define KEMU_ARCH_VECTOR_CACHE 0
#endif

/* ---- Guest CPU state (mirror of rust/kemu_core/src/state.rs) ---- */

struct kemu_cpu {
Expand Down Expand Up @@ -89,8 +93,6 @@ struct kemu_stubs {
};

#define KEMU_STUB_PAGE_STATE 0
#define KEMU_STUB_PINNED_LIVE 1
#define KEMU_STUB_PINNED_LIVE_PC_RAX 2

struct kemu_mm {
struct mutex lock; /* translation, chunks, block map */
Expand Down Expand Up @@ -295,14 +297,15 @@ struct kemu_trans {
struct kemu_host_regs {
u64 gpr[16];
u64 rflags;
u64 xmm[8][2];
};

int kemu_rs_gen_stubs(u8 *out, size_t len, u64 table_base, u32 mask8,
struct kemu_stubs *info);
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, bool tbi);
struct kemu_trans *res, bool reloc, bool tbi, bool vector_cache);
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 Expand Up @@ -331,7 +334,7 @@ int kemu_xc_init(void);
extern atomic_long_t kemu_xc_hits, kemu_xc_misses, kemu_xc_stale;
bool kemu_rs_recover(const u8 *blk, size_t len, u32 host_off,
const struct kemu_host_regs *h, struct kemu_cpu *cpu);
void kemu_rs_pinned_from_host(const struct kemu_host_regs *h, struct kemu_cpu *cpu);
void kemu_rs_recover_stub(u32 info, const struct kemu_host_regs *h, struct kemu_cpu *cpu);
size_t kemu_rs_block_info(const u8 *blk, size_t len, u64 *guest_pc, u32 *main_off);
bool kemu_rs_find_exit(const u8 *blk, size_t len, u32 site_off, u64 *target,
u32 *kind);
Expand Down
12 changes: 7 additions & 5 deletions overlay/kernel/kemu/kemu_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ pub unsafe extern "C" fn kemu_rs_translate(
res: *mut KemuTrans,
reloc: bool,
tbi: bool,
vector_cache: 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 @@ -381,7 +382,7 @@ pub unsafe extern "C" fn kemu_rs_translate(
&mut *res,
)
};
let cfg = t1::Cfg { stubs: info.addrs(stubs_base), code_uaddr, reloc, tbi, crypto: host_crypto() };
let cfg = t1::Cfg { stubs: info.addrs(stubs_base), code_uaddr, reloc, tbi, vector_cache, crypto: host_crypto() };
match t1::translate(&mut KEnv, pc, out, &cfg, s) {
Ok(r) => {
res.size = r.size as u64;
Expand Down Expand Up @@ -463,10 +464,11 @@ pub unsafe extern "C" fn kemu_rs_xc_apply(
pub struct KemuHostRegs {
pub gpr: [u64; 16],
pub rflags: u64,
pub xmm: [[u64; 2]; meta::VECTOR_REGS],
}

fn host_regs(h: &KemuHostRegs) -> meta::HostRegs {
meta::HostRegs { gpr: h.gpr, rflags: h.rflags }
meta::HostRegs { gpr: h.gpr, rflags: h.rflags, xmm: h.xmm }
}

/// Rebuild the guest state for a host PC inside a translated block.
Expand All @@ -486,15 +488,15 @@ pub unsafe extern "C" fn kemu_rs_recover(
meta::recover(blk, host_off, &host_regs(h), cpu)
}

/// Copy pinned guest registers from host registers.
/// Recover guest state using a stub range's attribute.
///
/// # Safety
/// `h` and `cpu` must be valid.
#[no_mangle]
pub unsafe extern "C" fn kemu_rs_pinned_from_host(h: *const KemuHostRegs, cpu: *mut CpuState) {
pub unsafe extern "C" fn kemu_rs_recover_stub(info: u32, h: *const KemuHostRegs, cpu: *mut CpuState) {
// SAFETY: guaranteed by the caller.
let (h, cpu) = unsafe { (&*h, &mut *cpu) };
meta::pinned_from_host(cpu, &host_regs(h));
stubs::recover(info as u8, &host_regs(h), cpu);
}

/// Validate a block header; returns its size (0 if invalid).
Expand Down
Loading
Loading