diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f1b3a64..f4da21f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore index c53250e..1c174d4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ tests/kernel/mtstress tests/kernel/lzmat __pycache__/ tests/kernel/tbi +tests/kernel/vector-state diff --git a/DESIGN.md b/DESIGN.md index 62202eb..55b8f81 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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) @@ -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 @@ -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=` bumps the epoch and kicks every other thread once per n diff --git a/README.md b/README.md index 1820554..c9a84ad 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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 @@ -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. @@ -158,7 +168,7 @@ x86 applets over the rootfs's binaries. | Parameter | Effect | |---|---| | `kemu.jit=0` | interpreter only | -| `kemu.jitoff=` | 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=` | 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=` | shared cache size limit (default 128) | | `kemu.debug=1` | per-process translation statistics on exit | diff --git a/overlay/arch/x86/include/asm/kemu.h b/overlay/arch/x86/include/asm/kemu.h index 59f6f32..1d9647d 100644 --- a/overlay/arch/x86/include/asm/kemu.h +++ b/overlay/arch/x86/include/asm/kemu.h @@ -9,6 +9,10 @@ #include #include +/* 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) diff --git a/overlay/arch/x86/kemu/env.c b/overlay/arch/x86/kemu/env.c index 57417e4..2d89d70 100644 --- a/overlay/arch/x86/kemu/env.c +++ b/overlay/arch/x86/kemu/env.c @@ -7,6 +7,36 @@ #include #include #include +#include +#include +#include + +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) { diff --git a/overlay/kernel/kemu/jit.c b/overlay/kernel/kemu/jit.c index 96a7de8..61a8b1f 100644 --- a/overlay/kernel/kemu/jit.c +++ b/overlay/kernel/kemu/jit.c @@ -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; @@ -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) @@ -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); diff --git a/overlay/kernel/kemu/kemu_internal.h b/overlay/kernel/kemu/kemu_internal.h index d5b678d..3d1c0bc 100644 --- a/overlay/kernel/kemu/kemu_internal.h +++ b/overlay/kernel/kemu/kemu_internal.h @@ -16,6 +16,10 @@ #include +#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 { @@ -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 */ @@ -295,6 +297,7 @@ 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, @@ -302,7 +305,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, 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); @@ -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); diff --git a/overlay/kernel/kemu/kemu_rs.rs b/overlay/kernel/kemu/kemu_rs.rs index 54b62b2..b734358 100644 --- a/overlay/kernel/kemu/kemu_rs.rs +++ b/overlay/kernel/kemu/kemu_rs.rs @@ -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 @@ -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; @@ -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. @@ -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). diff --git a/overlay/rust/kemu_core/src/interp/tests.rs b/overlay/rust/kemu_core/src/interp/tests.rs index 094a098..ed13c10 100644 --- a/overlay/rust/kemu_core/src/interp/tests.rs +++ b/overlay/rust/kemu_core/src/interp/tests.rs @@ -242,7 +242,9 @@ fn id_space_mrs_is_raz() { #[test] fn xcache_validate_and_relocate() { use crate::jit::{stubs, t1, xcache}; - let code: [u32; 8] = [ + let code: [u32; 10] = [ + 0x4ee08400, // add v0.2d, v0.2d, v0.2d (cached vector) + 0x4ee08400, 0x90000000, // adrp x0, 0 0xf9400001, // ldr x1, [x0] 0xeb02003f, // cmp x1, x2 @@ -262,7 +264,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, tbi: false, crypto: t1::HostCrypto::default() }; + let cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0000_0000 + (1 << 20), reloc: true, tbi: false, vector_cache: true, crypto: t1::HostCrypto::default() }; let mut s = std::boxed::Box::new(t1::Scratch::new()); let mut out = std::vec![0u8; 8192]; let mut env = mk(0x40_0000, None); @@ -284,8 +286,8 @@ fn xcache_validate_and_relocate() { // Changed instruction inside the block, or at an exit target the // flags look-ahead read: rejected. Unaligned delta: rejected. - assert!(!xcache::validate(&mut mk(base2, Some((1, 0xf9400401))), blob, base2)); - assert!(!xcache::validate(&mut mk(base2, Some((5, 0x8b020021))), blob, base2)); + assert!(!xcache::validate(&mut mk(base2, Some((3, 0xf9400401))), blob, base2)); + assert!(!xcache::validate(&mut mk(base2, Some((7, 0x8b020021))), blob, base2)); assert!(!xcache::validate(&mut mk(base2 + 4, None), blob, base2 + 4)); } @@ -311,7 +313,7 @@ fn recover_in_exit_trampoline_of_remapped_block() { 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, crypto: t1::HostCrypto::default() }; + let cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0000_0000 + (1 << 20), reloc: false, tbi: false, vector_cache: true, crypto: t1::HostCrypto::default() }; 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"); @@ -326,7 +328,7 @@ fn recover_in_exit_trampoline_of_remapped_block() { } assert!(!tramps.is_empty(), "no exit trampolines found"); - let mut h = meta::HostRegs { gpr: [0; 16], rflags: 0x202 }; + let mut h = meta::HostRegs { gpr: [0; 16], rflags: 0x202, ..Default::default() }; for (i, g) in h.gpr.iter_mut().enumerate() { *g = 0x1000 + i as u64; } @@ -348,3 +350,71 @@ fn recover_in_exit_trampoline_of_remapped_block() { assert_eq!(st.xr(9), 0x9000 + 9, "x9 at trampoline offset {off:#x}"); } } + +/// Cache fills, spills, helper returns and side exits must agree about +/// which copy of V0 is authoritative, including coincident metadata points. +#[test] +fn recover_cached_vectors() { + use crate::jit::{meta, stubs, t1}; + let code: [u32; 7] = [ + 0x4ee08400, // add v0.2d, v0.2d, v0.2d + 0x4ee08400, + 0x4ee08400, + 0x54000800, // b.eq +0x100: conditional side exit + 0x4ee00c00, // sqadd v0.2d, v0.2d, v0.2d: interpreter helper + 0x4ee08400, + 0x17fffffa, // b pc0: retain the cache on the back-edge + ]; + 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 stubs = std::vec![0u8; 4096]; + let so = stubs::gen_stubs(&mut stubs, stubs::ExitMode::Syscall, 0x7000_1000_0000, 0xfff8).unwrap(); + let mut cfg = t1::Cfg { stubs: so.addrs(0x7000_0000_0000), code_uaddr: 0x7000_0010_0000, + reloc: false, tbi: false, vector_cache: true, crypto: t1::HostCrypto::default() }; + let mut scratch = std::boxed::Box::new(t1::Scratch::new()); + let mut out = std::vec![0; 16384]; + for enabled in [true, false] { + cfg.vector_cache = enabled; + let r = t1::translate(&mut env, 0x40_0000, &mut out, &cfg, &mut scratch).unwrap(); + let blk = &out[..r.size]; + let hdr = meta::Header::read(blk).unwrap(); + let m = &blk[hdr.meta_off as usize..][..hdr.meta_len as usize]; + assert_eq!(&m[8..16], if enabled { &[0, 255, 255, 255, 255, 255, 255, 255] } else { &[255; 8] }); + let mut host = meta::HostRegs::default(); + host.xmm = [[0xabc, 0xdef]; 8]; + let check = |off, live| { + let mut st = CpuState::new(); + st.v = [[0x123, 0x456]; 32]; + assert!(meta::recover(blk, off, &host, &mut st)); + assert_eq!(st.v[0], if live { host.xmm[0] } else { [0x123, 0x456] }, "at {off:#x}"); + assert!(st.v[1..].iter().all(|v| *v == [0x123, 0x456])); + }; + check(hdr.main_off, false); // fill has not run yet + let (np, _) = meta::meta_counts(m).unwrap(); + let mut bodies = 0; + let mut helpers = 0; + let mut exits = 0; + for i in 0..np { + let p = meta::read_point(m, i).unwrap(); + match p.kind { + meta::kind::INSN if p.idx == 1 || p.idx == 5 => { + check(p.off, enabled); // after a result commit / helper refill + bodies += 1; + } + meta::kind::DONE if p.idx == 4 => { + check(p.off, false); // helper has returned; refill hasn't run + helpers += 1; + } + meta::kind::EXIT => { + check(p.off, false); // trampoline after a live self-loop + exits += 1; + } + _ => {} + } + } + assert!(bodies >= 2 && (!enabled || helpers > 0) && exits > 0, "enabled={enabled} bodies={bodies} helpers={helpers} exits={exits}"); + } +} diff --git a/overlay/rust/kemu_core/src/jit/meta.rs b/overlay/rust/kemu_core/src/jit/meta.rs index 29fe490..2e7b805 100644 --- a/overlay/rust/kemu_core/src/jit/meta.rs +++ b/overlay/rust/kemu_core/src/jit/meta.rs @@ -25,7 +25,10 @@ pub const IC_OFF: usize = 32; pub const CHECK_OFF: usize = 64; pub const POINT_SIZE: usize = 12; pub const EXIT_SIZE: usize = 16; -pub const META_HDR_SIZE: usize = 8; +pub const META_HDR_SIZE: usize = 16; +/// XMM0..7 cache guest vectors; XMM8..15 are lowering temporaries. +pub const VECTOR_REGS: usize = 8; +pub const NO_VECTOR: u8 = 0xff; pub const NO_SITE: u32 = u32::MAX; /// Kinds of recovery points. @@ -56,6 +59,9 @@ pub mod kind { /// STXR performed its compare-exchange: finish by writing the status /// (ZF ? 0 : 1) to guest register `a`; continue at the next insn. pub const ROLL_STATUS: u8 = 8; + /// Vector cache location: 0 = state page, 1 = XMM0..7. The metadata + /// header maps each host register to a guest vector (or NO_VECTOR). + pub const VSTATE: u8 = 9; } /// Flag locations for `kind::INSN` points. @@ -175,13 +181,14 @@ impl Header { } /// Serialize metadata into `b`; returns bytes written. -pub fn write_meta(b: &mut [u8], points: &[Point], exits: &[Exit], remap: &[(u8, u8)]) -> Option { +pub fn write_meta(b: &mut [u8], points: &[Point], exits: &[Exit], remap: &[(u8, u8)], vectors: &[u8; VECTOR_REGS]) -> Option { let np = u16::try_from(points.len()).ok()?; let ne = u16::try_from(exits.len()).ok()?; let nr = u32::try_from(remap.len()).ok()?; if !(put16(b, 0, np) && put16(b, 2, ne) && put32(b, 4, nr)) { return None; } + b.get_mut(8..META_HDR_SIZE)?.copy_from_slice(vectors); let mut off = META_HDR_SIZE; for p in points { if !(put32(b, off, p.off) && put16(b, off + 4, p.idx)) { @@ -264,11 +271,13 @@ pub fn find_exit_site(m: &[u8], site: u32) -> Option { None } -/// Host general-purpose registers and flags at the interruption point. +/// Host registers at the interruption point. XMM8..15 hold only scratch +/// values and need not be captured by the caller. #[derive(Clone, Copy, Default, Debug)] pub struct HostRegs { pub gpr: [u64; 16], pub rflags: u64, + pub xmm: [[u64; 2]; VECTOR_REGS], } /// Copy pinned guest registers from host registers into `st`. @@ -313,6 +322,7 @@ pub fn recover(blk: &[u8], host_off: u32, h: &HostRegs, st: &mut CpuState) -> bo let mut best: Option = None; let mut flags_loc = FLAGS_MEM; let mut remap_mode = 0u8; + let mut vectors_live = false; for i in 0..np { let p = match read_point(m, i) { Some(p) => p, @@ -328,6 +338,10 @@ pub fn recover(blk: &[u8], host_off: u32, h: &HostRegs, st: &mut CpuState) -> bo remap_mode = p.a; continue; } + kind::VSTATE => { + vectors_live = p.a != 0; + continue; + } _ => {} } best = Some(p); @@ -359,6 +373,17 @@ pub fn recover(blk: &[u8], host_off: u32, h: &HostRegs, st: &mut CpuState) -> bo } } } + if vectors_live { + for (x, v) in h.xmm.iter().enumerate() { + let g = match m.get(8 + x) { + Some(&g) => g, + None => return false, + }; + if g < 32 { + st.v[g as usize] = *v; + } + } + } let pc_of = |idx: u16| hdr.guest_pc.wrapping_add((idx as u64) * 4); let flags_from = |st: &mut CpuState, loc: u8| match loc { FLAGS_HOST => st.nzcv = regmap::nzcv_from_rflags(h.rflags, false), diff --git a/overlay/rust/kemu_core/src/jit/stubs.rs b/overlay/rust/kemu_core/src/jit/stubs.rs index 9472451..09e799f 100644 --- a/overlay/rust/kemu_core/src/jit/stubs.rs +++ b/overlay/rust/kemu_core/src/jit/stubs.rs @@ -5,8 +5,10 @@ //! block chaining, single-instruction helpers and guest syscalls. Stubs //! transfer to the kernel with `syscall` (`%eax` = kemu operation). +use super::meta::{self, HostRegs}; use super::regmap::*; use super::x86::*; +use crate::state::CpuState; /// kemu operations (include/linux/kemu_abi.h). pub const OP_SVC: u32 = 0x6b65_6d00; @@ -49,6 +51,25 @@ pub struct StubOffsets { pub const STUB_PAGE_STATE: u8 = 0; // guest state fully in the state page pub const STUB_PINNED_LIVE: u8 = 1; // pinned regs in host regs, pc in page pub const STUB_PINNED_LIVE_PC_RAX: u8 = 2; // pinned in host regs, pc in %rax +pub const STUB_PINNED_LIVE_SVC: u8 = 3; // pinned live, pending SVC at page pc - 4 +pub const STUB_PAGE_STATE_SVC: u8 = 4; // page authoritative, pending SVC at pc - 4 + +/// Recover an interrupted stub using its range attribute. SVC callers +/// advance the page PC before entering the stub. Before the host +/// syscall/call executes, recovery must restart that guest SVC. At its +/// return address the page may contain a new PC and registers restored +/// by rt_sigreturn, which must remain authoritative. +pub fn recover(info: u8, h: &HostRegs, st: &mut CpuState) { + match info { + STUB_PINNED_LIVE_PC_RAX => st.pc = h.gpr[RAX as usize], + STUB_PINNED_LIVE_SVC | STUB_PAGE_STATE_SVC => st.pc = st.pc.wrapping_sub(4), + _ => {} + } + if matches!(info, STUB_PINNED_LIVE | STUB_PINNED_LIVE_PC_RAX | STUB_PINNED_LIVE_SVC) { + meta::pinned_from_host(st, h); + } + st.nzcv = nzcv_from_image(st.flags_x86); +} /// Absolute user addresses of the stubs, as needed by the translator. #[derive(Clone, Copy, Debug, Default)] @@ -186,14 +207,16 @@ pub fn gen_stubs(out: &mut [u8], mode: ExitMode, table_base: u64, table_mask8: u let s = a.pos; spill_all(&mut a); exit(&mut a, mode, OP_SVC, slot); - o.push(s, a.pos, STUB_PINNED_LIVE); + o.push(s, a.pos, STUB_PINNED_LIVE_SVC); reload_all(&mut a); a.ret(); // interp_svc: interpreter mode; state is in the page. a.align(16); o.interp_svc = a.pos as u32; + let s = a.pos; exit(&mut a, mode, OP_SVC, slot); + o.push(s, a.pos, STUB_PAGE_STATE_SVC); let d = o.dispatch as usize; a.jmp(Some(d)); @@ -211,3 +234,54 @@ pub fn gen_stubs(out: &mut [u8], mode: ExitMode, table_base: u64, table_mask8: u None } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recover_svc_entry_and_return_boundaries() { + let mut page = [0u8; 4096]; + let o = gen_stubs(&mut page, ExitMode::Syscall, 0x7000_1000_0000, 0xfff8).unwrap(); + let mut host = HostRegs::default(); + host.gpr.fill(0xdead_beef); + let state = |pc| { + let mut st = CpuState::new(); + st.pc = pc; + st.x[0] = 0x1234; + st.v[0] = [0x5678, 0x9abc]; + st.flags_x86 = image_from_nzcv(0xa000_0000); + st + }; + for (start, end, pending, pinned) in [ + (o.svc, o.interp_svc, STUB_PINNED_LIVE_SVC, true), + (o.interp_svc, o.step, STUB_PAGE_STATE_SVC, false), + ] { + let bytes = &page[start as usize..end as usize]; + let syscall = start + bytes.windows(2).position(|b| b == [0x0f, 0x05]).unwrap() as u32; + // Include the syscall instruction itself: an interrupt at + // its IP is still before the guest syscall takes effect. + for off in start..syscall + 2 { + assert_eq!(o.info(off), pending, "at {off:#x}"); + let mut st = state(0x6404_0008); + recover(o.info(off), &host, &mut st); + assert_eq!(st.pc, 0x6404_0004, "pending SVC at {off:#x}"); + assert_eq!(st.x[0], if pinned { 0xdead_beef } else { 0x1234 }); + assert_eq!(st.v[0], [0x5678, 0x9abc]); + assert_eq!(st.nzcv, 0xa000_0000); + } + // Ordinary syscall completion and rt_sigreturn both leave + // the page authoritative, including throughout GPR reloads. + for off in syscall + 2..end { + assert_eq!(o.info(off), STUB_PAGE_STATE, "at {off:#x}"); + for pc in [0x6404_0008, 0x400970] { + let mut st = state(pc); + recover(o.info(off), &host, &mut st); + assert_eq!(st.pc, pc, "completed SVC at {off:#x}"); + assert_eq!(st.x[0], 0x1234); + assert_eq!(st.v[0], [0x5678, 0x9abc]); + } + } + } + } +} diff --git a/overlay/rust/kemu_core/src/jit/t1.rs b/overlay/rust/kemu_core/src/jit/t1.rs index 3f431c3..65a3d70 100644 --- a/overlay/rust/kemu_core/src/jit/t1.rs +++ b/overlay/rust/kemu_core/src/jit/t1.rs @@ -26,12 +26,14 @@ use crate::env::{Env, Fault}; mod crypto; pub use crypto::HostCrypto; mod fp; +mod vector; pub const MAX_INSNS: usize = 64; /// Debug knob (kemu.jitoff=): disable JIT features to bisect bugs. /// 1 = helper for all non-control-flow insns, 2 = helper for SIMD/FP, -/// 4 = single-instruction blocks, 32 = no register remapping. +/// 4 = single-instruction blocks, 32 = no register remapping, +/// 64 = no vector register cache. /// (8 = no chaining is handled by the kernel.) pub static JIT_OFF: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); @@ -198,6 +200,8 @@ pub struct Cfg { /// back to the interpreter when a tagged access faults, and /// retranslates blocks that do that often with this set. pub tbi: bool, + /// The caller can capture XMM0..7 for asynchronous state recovery. + pub vector_cache: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -257,6 +261,8 @@ struct Gen<'s, 'b> { live_in0: bool, /// Loop-body entry (after the remap prologue); self-loops jump here. body_off: usize, + vectors: [u8; meta::VECTOR_REGS], + vlive: bool, } pub const MAX_REMAP: usize = 4; @@ -277,10 +283,11 @@ impl<'s, 'b> Gen<'s, 'b> { fn point(&mut self, kind: u8, a: u8, b: u8) { let p = Point { off: self.a.pos as u32, idx: self.idx as u16, kind, a, b }; // Collapse points at the same offset (the later one wins). - // REMAP points are state changes, not resume points: keep them. - if self.np > 0 && kind != kind::REMAP { + // Location changes and resume points at the same offset are both + // needed (e.g. the first instruction after the cache fill). + if self.np > 0 && !matches!(kind, kind::REMAP | kind::VSTATE) { if let Some(prev) = self.s.points.get_mut(self.np - 1) { - if prev.off == p.off && prev.kind != kind::REMAP { + if prev.off == p.off && !matches!(prev.kind, kind::REMAP | kind::VSTATE) { *prev = p; return; } @@ -429,8 +436,9 @@ impl<'s, 'b> Gen<'s, 'b> { } } - /// Establish the block's register remapping (canonical -> remapped). + /// Fill the vector cache and establish the block's GPR remapping. fn remap_prologue(&mut self) { + self.vector_prologue(); if self.nremap == 0 || self.remapped { return; } @@ -449,8 +457,9 @@ impl<'s, 'b> Gen<'s, 'b> { self.point(kind::REMAP, 2, 0); } - /// Return to the canonical register map (remapped -> canonical). + /// Spill the vector cache and return GPRs to the canonical map. fn remap_epilogue(&mut self) { + self.vector_epilogue(); if !self.remapped { return; } @@ -593,7 +602,7 @@ impl<'s, 'b> Gen<'s, 'b> { /// Unconditional exit to guest `target`. Flags must be in memory. fn exit_to(&mut self, target: u64, main_off: usize) { if target == self.pc0 { - let t = if self.remapped { self.body_off } else { main_off }; + let t = if self.remapped || self.vlive { self.body_off } else { main_off }; self.a.jmp(Some(t)); return; } @@ -606,11 +615,13 @@ impl<'s, 'b> Gen<'s, 'b> { /// Conditional exit to guest `target` if `cc`. fn exit_if(&mut self, cc: Cc, target: u64, main_off: usize) { if target == self.pc0 { - let t = if self.remapped { self.body_off } else { main_off }; + let t = if self.remapped || self.vlive { self.body_off } else { main_off }; self.a.jcc(cc, Some(t)); return; } - if self.remapped { + if self.remapped || self.vlive { + let was_remapped = self.remapped; + let was_vectors = self.vlive; // Out-of-line exit with the epilogue; fall through stays remapped. let skip = self.a.jcc(cc.invert(), None); self.remap_epilogue(); @@ -618,8 +629,10 @@ impl<'s, 'b> Gen<'s, 'b> { let at = self.a.jmp(None); self.add_exit(at as u32, target); self.a.bind32(skip); - self.remapped = true; - self.point(kind::REMAP, 2, 0); + self.remapped = was_remapped; + if was_remapped { self.point(kind::REMAP, 2, 0); } + self.vlive = was_vectors; + if was_vectors { self.point(kind::VSTATE, 1, 0); } return; } self.pad_for_rel32(2); @@ -649,6 +662,7 @@ impl<'s, 'b> Gen<'s, 'b> { } let saved = self.fl; let was_remapped = self.remapped; + let was_vectors = self.vlive; let skip = self.a.jcc(cc.invert(), None); self.flags_to_mem(); self.remap_epilogue(); @@ -661,6 +675,8 @@ impl<'s, 'b> Gen<'s, 'b> { if was_remapped { self.point(kind::REMAP, 2, 0); } + self.vlive = was_vectors; + if was_vectors { self.point(kind::VSTATE, 1, 0); } // Fall-through: the instruction can restart with flags in EFLAGS. self.insn_point(); true @@ -729,7 +745,6 @@ impl<'s, 'b> Gen<'s, 'b> { fn helper(&mut self) { self.flags_to_mem(); self.fl.host = false; - let was = self.remapped; self.remap_epilogue(); let pc = self.pc(); self.gpc_imm(RAX, pc); @@ -737,9 +752,7 @@ impl<'s, 'b> Gen<'s, 'b> { self.call_abs(self.cfg.stubs.helper); self.fl = Flags { host: false, inv: false, mem: true }; self.point(kind::DONE, FLAGS_MEM, 0); - if was { - self.remap_prologue(); - } + self.remap_prologue(); } // ---- shifted / extended operands ---- @@ -1535,49 +1548,47 @@ impl<'s, 'b> Gen<'s, 'b> { } fn load_fp(&mut self, size: u8, rt: u32, m: Mem) { - let v = OFF_V + (rt as i32 & 31) * 16; match size { 4 => { self.a.vmovdqu_load(15, m); - self.a.vmovdqu_store(Mem::gs(v), 15); + self.store_vec(rt, 15); } 3 => { self.a.vmovq_load(15, m); - self.a.vmovdqu_store(Mem::gs(v), 15); + self.store_vec(rt, 15); } 2 => { self.a.vmovd_load(15, m); - self.a.vmovdqu_store(Mem::gs(v), 15); + self.store_vec(rt, 15); } _ => { self.a.movzx(if size == 0 { Sz::B } else { Sz::W }, RAX, Rm::M(m)); self.a.vmov_from_gpr(Sz::D, 15, RAX); - self.a.vmovdqu_store(Mem::gs(v), 15); + self.store_vec(rt, 15); } } } fn store_fp(&mut self, size: u8, rt: u32, m: Mem) { - let v = OFF_V + (rt as i32 & 31) * 16; match size { 4 => { - self.a.vmovdqu_load(15, Mem::gs(v)); + self.ld_vec(15, rt); self.a.vmovdqu_store(m, 15); } 3 => { - self.a.load(Sz::Q, RAX, Mem::gs(v)); + self.vector_extract(Sz::Q, RAX, rt, 0); self.a.store(Sz::Q, m, RAX); } 2 => { - self.a.load(Sz::D, RAX, Mem::gs(v)); + self.vector_extract(Sz::D, RAX, rt, 0); self.a.store(Sz::D, m, RAX); } 1 => { - self.a.load(Sz::D, RAX, Mem::gs(v)); + self.vector_extract(Sz::D, RAX, rt, 0); self.a.store(Sz::W, m, RAX); } _ => { - self.a.load(Sz::D, RAX, Mem::gs(v)); + self.vector_extract(Sz::D, RAX, rt, 0); self.a.store(Sz::B, m, RAX); } } @@ -2343,6 +2354,10 @@ fn translate_n(env: &mut E, pc: u64, out: &mut [u8], cfg: &Cfg, s: &mut nremap: 0, remapped: false, body_off: 0, + vectors: if cfg.vector_cache && jit_off() & 64 == 0 { + vector::choose(&insns[..n.min(MAX_INSNS)]) + } else { [meta::NO_VECTOR; meta::VECTOR_REGS] }, + vlive: false, live_in0, }; if jit_off() & 32 == 0 { @@ -2727,6 +2742,10 @@ fn translate_n(env: &mut E, pc: u64, out: &mut [u8], cfg: &Cfg, s: &mut g.remapped = false; g.point(kind::REMAP, 0, 0); } + if g.vectors[0] != meta::NO_VECTOR && ne > 0 { + g.vlive = false; + g.point(kind::VSTATE, 0, 0); + } for k in 0..ne { let e = g.s.exits.get(k).copied().unwrap_or_default(); let t = g.a.pos; @@ -2750,6 +2769,7 @@ fn translate_n(env: &mut E, pc: u64, out: &mut [u8], cfg: &Cfg, s: &mut let overflow = g.overflow; let g_nremap = g.nremap; let g_remap = g.remap; + let vectors = g.vectors; let mut a = g.a; let s = g.s; if overflow || !a.ok() { @@ -2773,7 +2793,7 @@ fn translate_n(env: &mut E, pc: u64, out: &mut [u8], cfg: &Cfg, s: &mut for (d, s) in pairs.iter_mut().zip(remap.iter().take(nremap)) { *d = (s.0 as u8, s.1 as u8); } - let mlen = meta::write_meta(meta_buf, points, exits, &pairs[..nremap]).ok_or(TErr::NoSpace)?; + let mlen = meta::write_meta(meta_buf, points, exits, &pairs[..nremap], &vectors).ok_or(TErr::NoSpace)?; let hdr = Header { main_off: main_off as u32, code_end: code_end as u32, diff --git a/overlay/rust/kemu_core/src/jit/t1/crypto.rs b/overlay/rust/kemu_core/src/jit/t1/crypto.rs index 5966c6f..03f7403 100644 --- a/overlay/rust/kemu_core/src/jit/t1/crypto.rs +++ b/overlay/rust/kemu_core/src/jit/t1/crypto.rs @@ -5,7 +5,6 @@ //! vector operations leave NZCV, FPCR and FPSR untouched. use super::*; -use super::fp::voff; /// Optional host crypto features. AVX state support is already required /// by the JIT; the 128-bit VEX forms need AES/PCLMUL, not VAES/VPCLMUL. @@ -15,7 +14,7 @@ pub struct HostCrypto { pub pclmul: bool, } -// Guest vectors live in the state page; these host registers are scratch. +// XMM0..7 cache guest vectors; these host registers are scratch. const X: u8 = 8; const Y: u8 = 9; const W: u8 = 10; @@ -80,15 +79,15 @@ impl<'s, 'b> Gen<'s, 'b> { if !self.cfg.crypto.aes { return false; } + self.ld_vec(X, rd); + self.ld_vec(Y, rn); let a = &mut self.a; - a.vmovdqu_load(X, Mem::gs(voff(rd))); - a.vmovdqu_load(Y, Mem::gs(voff(rn))); // Arm adds the round key before SubBytes/ShiftRows; x86 adds it // afterwards. XOR first, then use a last round with a zero key. bin(a, XOR, X, X, Y); bin(a, XOR, Y, Y, Y); a.vex(2, 1, false, false, if decrypt { 0xdf } else { 0xdd }, X, X, Rm::R(Y)); - a.vmovdqu_store(Mem::gs(voff(rd)), X); + self.store_vec(rd, X); true } @@ -96,8 +95,8 @@ impl<'s, 'b> Gen<'s, 'b> { if !self.cfg.crypto.aes { return false; } + self.ld_vec(X, rn); let a = &mut self.a; - a.vmovdqu_load(X, Mem::gs(voff(rn))); if inverse { a.vex(2, 1, false, false, 0xdb, X, 0, Rm::R(X)); // vaesimc } else { @@ -107,7 +106,7 @@ impl<'s, 'b> Gen<'s, 'b> { a.vex(2, 1, false, false, 0xdf, X, X, Rm::R(Y)); a.vex(2, 1, false, false, 0xdc, X, X, Rm::R(Y)); } - a.vmovdqu_store(Mem::gs(voff(rd)), X); + self.store_vec(rd, X); true } @@ -115,17 +114,19 @@ impl<'s, 'b> Gen<'s, 'b> { if size != 0 && (size != 3 || !self.cfg.crypto.pclmul) { return false; } + if size == 3 { + self.ld_vec(X, rn); + self.ld_vec(Y, rm); + } else { + self.widen(X, rn, 0, false, high); + self.widen(Y, rm, 0, false, high); + } let a = &mut self.a; if size == 3 { - a.vmovdqu_load(X, Mem::gs(voff(rn))); - a.vmovdqu_load(Y, Mem::gs(voff(rm))); a.vex_ib(3, 1, false, false, 0x44, W, X, Rm::R(Y), if high { 0x11 } else { 0 }); } else { // Eight independent 8x8 -> 16-bit polynomial products. // Widen first so shifts cannot spill into adjacent lanes. - let offset = if high { 8 } else { 0 }; - a.vex(2, 1, false, false, 0x30, X, 0, Rm::M(Mem::gs(voff(rn) + offset))); - a.vex(2, 1, false, false, 0x30, Y, 0, Rm::M(Mem::gs(voff(rm) + offset))); bin(a, XOR, W, W, W); for i in 0..8 { // Broadcast bit i of each multiplier to a 16-bit mask. @@ -138,7 +139,7 @@ impl<'s, 'b> Gen<'s, 'b> { } } } - a.vmovdqu_store(Mem::gs(voff(rd)), W); + self.store_vec(rd, W); true } @@ -146,13 +147,13 @@ impl<'s, 'b> Gen<'s, 'b> { if op > 5 { return false; } + self.ld_vec(X, rd); + self.ld_vec(Y, rn); + if op <= 3 { self.ld_vec(W, rm); } let a = &mut self.a; - a.vmovdqu_load(X, Mem::gs(voff(rd))); - a.vmovdqu_load(Y, Mem::gs(voff(rn))); match op { 0..=2 => { // X = [a,b,c,d], Y.low = e, W = four message words + K. - a.vmovdqu_load(W, Mem::gs(voff(rm))); for _ in 0..4 { shuffle(a, T, X, 0x55); // b shuffle(a, U, X, 0xaa); // c @@ -187,7 +188,6 @@ impl<'s, 'b> Gen<'s, 'b> { } } 3 => { - a.vmovdqu_load(W, Mem::gs(voff(rm))); align(a, T, Y, X, 8); // [d2,d3,n0,n1] bin(a, XOR, X, X, T); bin(a, XOR, X, X, W); @@ -207,7 +207,7 @@ impl<'s, 'b> Gen<'s, 'b> { bin(a, XOR, X, Y, U); // high lane also XORs ROL(t0,2) } } - a.vmovdqu_store(Mem::gs(voff(rd)), X); + self.store_vec(rd, X); true } @@ -215,15 +215,15 @@ impl<'s, 'b> Gen<'s, 'b> { if !matches!(op, 4 | 5 | 6 | 0x10) { return false; } - let a = &mut self.a; // Read every operand before committing, including when they alias. - a.vmovdqu_load(X, Mem::gs(voff(if op == 5 { rn } else { rd }))); - a.vmovdqu_load(Y, Mem::gs(voff(if op == 5 { rd } else { rn }))); + self.ld_vec(X, if op == 5 { rn } else { rd }); + self.ld_vec(Y, if op == 5 { rd } else { rn }); + if op != 0x10 { self.ld_vec(W, rm); } + let a = &mut self.a; let result = match op { 4 | 5 => { // Four rounds: X = [a,b,c,d], Y = [e,f,g,h], W = Wt+Kt. // Only the low lane of each round's temporaries is used. - a.vmovdqu_load(W, Mem::gs(voff(rm))); for _ in 0..4 { sigma(a, T, Y, [6, 11, 25], false, U, V); shuffle(a, U, Y, 0x55); // f @@ -266,7 +266,6 @@ impl<'s, 'b> Gen<'s, 'b> { _ => { // SHA256SU1: the upper two lanes depend on the newly // computed lower lanes, not on the old destination. - a.vmovdqu_load(W, Mem::gs(voff(rm))); align(a, T, W, Y, 4); // [n1,n2,n3,m0] bin(a, ADD, X, X, T); shift_bytes(a, Y, W, false, 8); // [m2,m3,0,0] @@ -279,7 +278,7 @@ impl<'s, 'b> Gen<'s, 'b> { X } }; - a.vmovdqu_store(Mem::gs(voff(rd)), result); + self.store_vec(rd, result); true } } diff --git a/overlay/rust/kemu_core/src/jit/t1/fp.rs b/overlay/rust/kemu_core/src/jit/t1/fp.rs index ac34b3c..d13f750 100644 --- a/overlay/rust/kemu_core/src/jit/t1/fp.rs +++ b/overlay/rust/kemu_core/src/jit/t1/fp.rs @@ -2,8 +2,8 @@ //! Tier-1 lowering of scalar floating point and common Advanced SIMD //! instructions to SSE/AVX2 (VEX-encoded). //! -//! V registers live in the state page. Results are computed in scratch -//! xmm registers (13..15) and committed with a single 128-bit store, so +//! V registers live in the cache or state page. Results use scratch +//! XMM registers (12..15) and commit in a single host instruction, so //! every instruction stays restartable. Bit-exactness: whenever a result //! could differ from AArch64 semantics (NaN results, out-of-range //! conversions), the fast path branches to the helper, which re-executes @@ -44,7 +44,11 @@ impl<'s, 'b> Gen<'s, 'b> { /// Load a scalar (32/64-bit) from V[n] into xmm `x` (upper zeroed). fn ld_scalar(&mut self, double: bool, x: u8, n: u32) { if double { - self.a.vmovq_load(x, Mem::gs(voff(n))); + self.a.vex(1, PP_F3, false, false, 0x7e, x, 0, self.v_rm(n)); + } else if let Some(src) = self.vector_host(n) { + // Keep only the low word without borrowing a GPR or flags. + self.a.vex_ib(1, PP_66, false, false, 0x73, 7, x, Rm::R(src), 12); + self.a.vex_ib(1, PP_66, false, false, 0x73, 3, x, Rm::R(x), 12); } else { self.a.vmovd_load(x, Mem::gs(voff(n))); } @@ -59,7 +63,7 @@ impl<'s, 'b> Gen<'s, 'b> { self.a.vmov_to_gpr(Sz::D, RAX, x); self.a.vmov_from_gpr(Sz::D, x, RAX); } - self.a.vmovdqu_store(Mem::gs(voff(d)), x); + self.store_vec(d, x); } /// Commit a vector result: zero the upper half for 64-bit forms. @@ -67,7 +71,7 @@ impl<'s, 'b> Gen<'s, 'b> { if !q { self.a.vex(1, PP_F3, false, false, 0x7e, x, 0, Rm::R(x)); } - self.a.vmovdqu_store(Mem::gs(voff(d)), x); + self.store_vec(d, x); } /// Branch to the slow path if `x` holds a NaN (scalar). Returns the @@ -120,7 +124,7 @@ impl<'s, 'b> Gen<'s, 'b> { let v = fp_imm(double, imm8); self.mov_imm(RAX, v); self.a.vmov_from_gpr(Sz::Q, X14, RAX); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); true } @@ -140,9 +144,7 @@ impl<'s, 'b> Gen<'s, 'b> { self.fp_prologue(); let pp = if double { PP_F2 } else { PP_F3 }; self.ld_scalar(double, X14, rn); - let m = if double { Mem::gs(voff(rm)) } else { Mem::gs(voff(rm)) }; - // Scalar VEX ops with a memory operand read only 32/64 bits. - self.a.vex(1, pp, false, false, opc, X14, X14, Rm::M(m)); + self.a.vex(1, pp, false, false, opc, X14, X14, self.v_rm(rm)); let s = self.nan_guard_scalar(double, X14); if op == Fp2Op::Nmul { self.a.vmov_to_gpr(Sz::Q, RAX, X14); @@ -173,7 +175,7 @@ impl<'s, 'b> Gen<'s, 'b> { self.fp_prologue(); self.ld_scalar(double, X14, ra); self.ld_scalar(double, X15, rn); - self.a.vex(2, PP_66, double, false, opc, X14, X15, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(2, PP_66, double, false, opc, X14, X15, self.v_rm(rm)); let s = self.nan_guard_scalar(double, X14); self.st_scalar(double, X14, rd); self.slow_paths(&[s]); @@ -190,7 +192,7 @@ impl<'s, 'b> Gen<'s, 'b> { Fp1Op::Mov | Fp1Op::Abs | Fp1Op::Neg => { // Pure bit operations, never trap. self.clobber(); - self.a.load(Sz::Q, RAX, Mem::gs(voff(rn))); + self.vector_extract(Sz::Q, RAX, rn, 0); if !double { self.a.mov_rr(Sz::D, RAX, RAX); } @@ -202,7 +204,7 @@ impl<'s, 'b> Gen<'s, 'b> { _ => {} } self.a.vmov_from_gpr(Sz::Q, X14, RAX); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); true } Fp1Op::Sqrt => { @@ -289,16 +291,22 @@ impl<'s, 'b> Gen<'s, 'b> { } self.flags_to_host(); let cc = self.cond_cc(cond); - self.a.load(Sz::Q, RAX, Mem::gs(voff(rm))); + self.vector_extract(Sz::Q, RAX, rm, 0); match cc { - Some(cc) => self.a.cmov(cc, Sz::Q, RAX, Rm::M(Mem::gs(voff(rn)))), - None => self.a.load(Sz::Q, RAX, Mem::gs(voff(rn))), + Some(cc) if self.vector_host(rn).is_none() => { + self.a.cmov(cc, Sz::Q, RAX, Rm::M(Mem::gs(voff(rn)))); + } + Some(cc) => { + self.vector_extract(Sz::Q, RDX, rn, 0); + self.a.cmov(cc, Sz::Q, RAX, Rm::R(RDX)); + } + None => self.vector_extract(Sz::Q, RAX, rn, 0), } if ftype == 0 { self.a.mov_rr(Sz::D, RAX, RAX); } self.a.vmov_from_gpr(Sz::Q, X14, RAX); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); true } @@ -319,16 +327,16 @@ impl<'s, 'b> Gen<'s, 'b> { if to_fp { let r = self.get(rn, false, RAX); if top { - self.a.store(Sz::Q, Mem::gs(voff(rd) + 8), r); + self.vector_insert(Sz::Q, rd, 1, r); } else { self.a.vmov_from_gpr(sz, X14, r); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); } } else { match self.gp(rd, false) { - Gp::R(r) => self.a.load(sz, r, Mem::gs(voff(rn) + off)), + Gp::R(r) => self.vector_extract(sz, r, rn, (off / 8) as u8), Gp::M(o) => { - self.a.load(sz, RAX, Mem::gs(voff(rn) + off)); + self.vector_extract(sz, RAX, rn, (off / 8) as u8); self.a.store(Sz::Q, Mem::gs(o), RAX); } Gp::Zero => {} @@ -419,10 +427,6 @@ impl<'s, 'b> Gen<'s, 'b> { // ---- Advanced SIMD ---- - fn ld_vec(&mut self, x: u8, n: u32) { - self.a.vmovdqu_load(x, Mem::gs(voff(n))); - } - /// Splat a 32-bit constant into xmm `x`. fn splat32(&mut self, x: u8, v: u32) { self.a.mov_ri32(RAX, v); @@ -449,10 +453,10 @@ impl<'s, 'b> Gen<'s, 'b> { // 64-bit compares: pcmpeqq / pcmpgtq (0F38 29 / 37) let o = if op == SimdOp::CmEq { 0x29 } else { 0x37 }; self.ld_vec(X14, rn); - self.a.vex(2, PP_66, false, false, o, X14, X14, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(2, PP_66, false, false, o, X14, X14, self.v_rm(rm)); } else { self.ld_vec(X14, rn); - self.a.vex(1, PP_66, false, false, opc, X14, X14, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(1, PP_66, false, false, opc, X14, X14, self.v_rm(rm)); } self.st_vec(q, X14, rd); return true; @@ -462,9 +466,9 @@ impl<'s, 'b> Gen<'s, 'b> { SimdOp::And | SimdOp::Orr | SimdOp::Eor | SimdOp::Bic => { self.ld_vec(X14, rn); match op { - SimdOp::And => self.a.vex(1, PP_66, false, false, 0xdb, X14, X14, Rm::M(Mem::gs(voff(rm)))), - SimdOp::Orr => self.a.vex(1, PP_66, false, false, 0xeb, X14, X14, Rm::M(Mem::gs(voff(rm)))), - SimdOp::Eor => self.a.vex(1, PP_66, false, false, 0xef, X14, X14, Rm::M(Mem::gs(voff(rm)))), + SimdOp::And => self.a.vex(1, PP_66, false, false, 0xdb, X14, X14, self.v_rm(rm)), + SimdOp::Orr => self.a.vex(1, PP_66, false, false, 0xeb, X14, X14, self.v_rm(rm)), + SimdOp::Eor => self.a.vex(1, PP_66, false, false, 0xef, X14, X14, self.v_rm(rm)), _ => { // vpandn x14, x15(rm), x14(rn) : ~rm & rn self.ld_vec(X15, rm); @@ -519,7 +523,7 @@ impl<'s, 'b> Gen<'s, 'b> { (_, _) => (2, 0x39), }; self.ld_vec(X14, rn); - self.a.vex(map, PP_66, false, false, opc, X14, X14, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(map, PP_66, false, false, opc, X14, X14, self.v_rm(rm)); self.st_vec(q, X14, rd); true } @@ -549,9 +553,9 @@ impl<'s, 'b> Gen<'s, 'b> { SimdOp::Mul | SimdOp::Mla | SimdOp::Mls if size == 1 || size == 2 => { self.ld_vec(X14, rn); if size == 1 { - self.a.vex(1, PP_66, false, false, 0xd5, X14, X14, Rm::M(Mem::gs(voff(rm)))); // vpmullw + self.a.vex(1, PP_66, false, false, 0xd5, X14, X14, self.v_rm(rm)); // vpmullw } else { - self.a.vex(2, PP_66, false, false, 0x40, X14, X14, Rm::M(Mem::gs(voff(rm)))); // vpmulld + self.a.vex(2, PP_66, false, false, 0x40, X14, X14, self.v_rm(rm)); // vpmulld } if op != SimdOp::Mul { self.ld_vec(X15, rd); @@ -642,12 +646,12 @@ impl<'s, 'b> Gen<'s, 'b> { }; self.fp_prologue(); self.ld_vec(X14, rn); - self.a.vex(1, if double { PP_66 } else { PP_NONE }, false, false, opc, X14, X14, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(1, if double { PP_66 } else { PP_NONE }, false, false, opc, X14, X14, self.v_rm(rm)); if !q { self.a.vex(1, PP_F3, false, false, 0x7e, X14, 0, Rm::R(X14)); } let s = self.nan_guard_vec(double, X14); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); self.slow_paths(&[s]); true } @@ -660,12 +664,12 @@ impl<'s, 'b> Gen<'s, 'b> { self.ld_vec(X14, rd); self.ld_vec(X15, rn); let opc = if op == SimdOp::FMla { 0xb8 } else { 0xbc }; // vfmadd231ps / vfnmadd231ps - self.a.vex(2, PP_66, double, false, opc, X14, X15, Rm::M(Mem::gs(voff(rm)))); + self.a.vex(2, PP_66, double, false, opc, X14, X15, self.v_rm(rm)); if !q { self.a.vex(1, PP_F3, false, false, 0x7e, X14, 0, Rm::R(X14)); } let s = self.nan_guard_vec(double, X14); - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); self.slow_paths(&[s]); true } @@ -674,11 +678,11 @@ impl<'s, 'b> Gen<'s, 'b> { } /// x = sign/zero-extended lower (or upper) half of V[n] to double width. - fn widen(&mut self, x: u8, n: u32, size: u8, signed: bool, hi: bool) { - let m = Mem::gs(voff(n) + if hi { 8 } else { 0 }); + pub(super) fn widen(&mut self, x: u8, n: u32, size: u8, signed: bool, hi: bool) { + let src = self.vector_slice(n, if hi { 8 } else { 0 }, x); // vpmovsx{bw,wd,dq} 0F38 20/23/25 ; vpmovzx 30/33/35 (64-bit memory operand) let o = [0x20u8, 0x23, 0x25][(size & 3).min(2) as usize] + if signed { 0 } else { 0x10 }; - self.a.vex(2, PP_66, false, false, o, x, 0, Rm::M(m)); + self.a.vex(2, PP_66, false, false, o, x, 0, src); } pub(super) fn simd_permute(&mut self, q: bool, size: u8, opcode: u8, rd: u32, rn: u32, rm: u32) -> bool { @@ -754,14 +758,14 @@ impl<'s, 'b> Gen<'s, 'b> { } Simd2Op::Abs if size < 3 => { let opc = [0x1cu8, 0x1d, 0x1e][size as usize]; - self.a.vex(2, PP_66, false, false, opc, X14, 0, Rm::M(Mem::gs(voff(rn)))); + self.a.vex(2, PP_66, false, false, opc, X14, 0, self.v_rm(rn)); self.st_vec(q, X14, rd); return true; } Simd2Op::Neg => { let opc = [0xf8u8, 0xf9, 0xfa, 0xfb][(size & 3) as usize]; self.a.vex(1, PP_66, false, false, 0xef, X14, X14, Rm::R(X14)); - self.a.vex(1, PP_66, false, false, opc, X14, X14, Rm::M(Mem::gs(voff(rn)))); + self.a.vex(1, PP_66, false, false, opc, X14, X14, self.v_rm(rn)); self.st_vec(q, X14, rd); return true; } @@ -788,8 +792,8 @@ impl<'s, 'b> Gen<'s, 'b> { self.a.vex(2, PP_66, false, false, opc, X14, 0, Rm::R(X14)); } else { let idx = imm5 >> (size + 1); - let off = voff(rn) + (idx << size) as i32; - self.a.vex(2, PP_66, false, false, opc, X14, 0, Rm::M(Mem::gs(off))); + let src = self.vector_slice(rn, (idx << size) as u8, X14); + self.a.vex(2, PP_66, false, false, opc, X14, 0, src); } self.st_vec(q, X14, rd); true @@ -801,18 +805,15 @@ impl<'s, 'b> Gen<'s, 'b> { return false; } let idx = imm5 >> (size + 1); - let m = Mem::gs(voff(rn) + (idx << size) as i32); - // Scalar DUP/MOV copies one element and zeros the rest of Vd. - // MOVZX/VMOV preserve live NZCV and read before any aliased write. - match size { - 0 | 1 => { - self.a.movzx(if size == 0 { Sz::B } else { Sz::W }, RAX, Rm::M(m)); - self.a.vmov_from_gpr(Sz::D, X14, RAX); - } - 2 => self.a.vmovd_load(X14, m), - _ => self.a.vmovq_load(X14, m), + let sz = [Sz::B, Sz::W, Sz::D, Sz::Q][size as usize]; + if self.vector_host(rn).is_none() && size >= 2 { + let m = Mem::gs(voff(rn) + (idx << size) as i32); + if size == 3 { self.a.vmovq_load(X14, m); } else { self.a.vmovd_load(X14, m); } + } else { + self.vector_extract(sz, RAX, rn, idx as u8); + self.a.vmov_from_gpr(if size == 3 { Sz::Q } else { Sz::D }, X14, RAX); } - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); true } @@ -831,7 +832,7 @@ impl<'s, 'b> Gen<'s, 'b> { if q { self.a.vex(2, PP_66, false, false, 0x59, X14, 0, Rm::R(X14)); // vpbroadcastq } - self.a.vmovdqu_store(Mem::gs(voff(rd)), X14); + self.store_vec(rd, X14); true } @@ -911,7 +912,7 @@ impl<'s, 'b> Gen<'s, 'b> { // SHRN2: insert into upper half of Vd self.ld_vec(X15, rd); self.a.vex(1, PP_66, false, false, 0x6c, X15, X15, Rm::R(X14)); // punpcklqdq - self.a.vmovdqu_store(Mem::gs(voff(rd)), X15); + self.store_vec(rd, X15); } else { self.st_vec(false, X14, rd); } @@ -927,7 +928,7 @@ impl<'s, 'b> Gen<'s, 'b> { } // EXT: bytes imm4.. of Vm:Vn == vpalignr x14, vm, vn, imm4 self.ld_vec(X15, rm); - self.a.vex_ib(3, PP_66, false, false, 0x0f, X14, X15, Rm::M(Mem::gs(voff(rn))), imm4 as u8); + self.a.vex_ib(3, PP_66, false, false, 0x0f, X14, X15, self.v_rm(rn), imm4 as u8); self.st_vec(true, X14, rd); true } @@ -938,18 +939,12 @@ impl<'s, 'b> Gen<'s, 'b> { return false; } let idx = imm5 >> (size + 1); - let m = Mem::gs(voff(rn) + (idx << size) as i32); let dst = match self.gp(rd, false) { Gp::R(r) => r, Gp::Zero => return true, Gp::M(_) => RAX, }; - match size { - 0 => self.a.movzx(Sz::B, dst, Rm::M(m)), - 1 => self.a.movzx(Sz::W, dst, Rm::M(m)), - 2 => self.a.load(Sz::D, dst, m), - _ => self.a.load(Sz::Q, dst, m), - } + self.vector_extract([Sz::B, Sz::W, Sz::D, Sz::Q][size as usize], dst, rn, idx as u8); if dst == RAX { self.put(rd, false, RAX); } @@ -962,15 +957,9 @@ impl<'s, 'b> Gen<'s, 'b> { return false; } let idx = imm5 >> (size + 1); - let m = Mem::gs(voff(rd) + (idx << size) as i32); let sz = [Sz::B, Sz::W, Sz::D, Sz::Q][size as usize]; - match self.gp(rn, false) { - Gp::Zero => self.a.store_imm(sz, m, 0), - _ => { - let r = self.get(rn, false, RAX); - self.a.store(sz, m, r); - } - } + let r = self.get(rn, false, RAX); + self.vector_insert(sz, rd, idx as u8, r); true } @@ -982,13 +971,8 @@ impl<'s, 'b> Gen<'s, 'b> { let di = imm5 >> (size + 1); let si = imm4 >> size; let sz = [Sz::B, Sz::W, Sz::D, Sz::Q][size as usize]; - let src = Mem::gs(voff(rn) + (si << size) as i32); - match size { - 0 => self.a.movzx(Sz::B, RAX, Rm::M(src)), - 1 => self.a.movzx(Sz::W, RAX, Rm::M(src)), - _ => self.a.load(sz, RAX, src), - } - self.a.store(sz, Mem::gs(voff(rd) + (di << size) as i32), RAX); + self.vector_extract(sz, RAX, rn, si as u8); + self.vector_insert(sz, rd, di as u8, RAX); true } @@ -1057,12 +1041,12 @@ impl<'s, 'b> Gen<'s, 'b> { } else { self.a.vmovq_load(X14, m); } - self.a.vmovdqu_store(Mem::gs(voff(r)), X14); + self.store_vec(r, X14); } else if q { - self.a.vmovdqu_load(X14, Mem::gs(voff(r))); + self.ld_vec(X14, r); self.a.vmovdqu_store(m, X14); } else { - self.a.load(Sz::Q, RAX, Mem::gs(voff(r))); + self.vector_extract(Sz::Q, RAX, r, 0); self.a.store(Sz::Q, m, RAX); } } diff --git a/overlay/rust/kemu_core/src/jit/t1/vector.rs b/overlay/rust/kemu_core/src/jit/t1/vector.rs new file mode 100644 index 0000000..f2de070 --- /dev/null +++ b/overlay/rust/kemu_core/src/jit/t1/vector.rs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Block-local vector register cache. A fixed allocation keeps recovery +//! simple: the page is authoritative while filling, XMM0..7 while live +//! (including while spilling). Scratch results commit in one instruction. + +use super::*; +use super::fp::voff; +use crate::decode::FcvtOp; + +pub(super) fn choose(insns: &[Insn]) -> [u8; meta::VECTOR_REGS] { + let mut uses = [0u16; 32]; + let has_loop = insns.iter().enumerate().any(|(idx, i)| match i { + Insn::B { imm } | Insn::BCond { imm, .. } | Insn::Cbz { imm, .. } + | Insn::Tbz { imm, .. } => *imm == -(idx as i64 * 4), + _ => false, + }); + for &i in insns { + let mut add = |r: u32| uses[(r & 31) as usize] += 1; + match i { + Insn::FpImm { rd, .. } | Insn::SimdModImm { rd, .. } + | Insn::SimdInsGpr { rd, .. } | Insn::SimdDup { from_gpr: true, rd, .. } => add(rd), + Insn::FpCmp { rn, rm, zero, .. } => { add(rn); if !zero { add(rm); } } + Insn::FpCCmp { rn, rm, .. } => { add(rn); add(rm); } + Insn::SimdUmov { rn, .. } | Insn::SimdSmov { rn, .. } => add(rn), + Insn::FpCvt { op, rd, rn, .. } => match op { + FcvtOp::Fmov { to_fp: true, .. } | FcvtOp::ItoF { .. } | FcvtOp::FixedToF { .. } => add(rd), + _ => add(rn), + }, + Insn::Fp1 { rd, rn, .. } | Insn::SimdMisc { rd, rn, .. } + | Insn::SimdAcross { rd, rn, .. } | Insn::SimdDup { rd, rn, .. } + | Insn::SimdInsElt { rd, rn, .. } | Insn::SimdShift { rd, rn, .. } + | Insn::SimdScalarCopy { rd, rn, .. } | Insn::Aese { rd, rn } + | Insn::Aesd { rd, rn } | Insn::Aesmc { rd, rn } | Insn::Aesimc { rd, rn } => { + add(rd); add(rn); + } + Insn::FpCSel { rd, rn, rm, .. } | Insn::Fp2 { rd, rn, rm, .. } + | Insn::SimdThree { rd, rn, rm, .. } | Insn::SimdExt { rd, rn, rm, .. } + | Insn::SimdPermute { rd, rn, rm, .. } | Insn::SimdIndexed { rd, rn, rm, .. } + | Insn::Sha1 { rd, rn, rm, .. } | Insn::Sha256 { rd, rn, rm, .. } => { + add(rd); add(rn); add(rm); + } + Insn::Fp3 { rd, rn, rm, ra, .. } => { add(rd); add(rn); add(rm); add(ra); } + Insn::LdSt { fp: true, rt, .. } | Insn::LdStLiteral { fp: true, rt, .. } + | Insn::LdStReg { fp: true, rt, .. } => add(rt), + Insn::LdStPair { fp: true, rt, rt2, .. } => { add(rt); add(rt2); } + Insn::SimdLdSt { rt, opcode, single: false, .. } => { + let n = match opcode { 7 => 1, 10 => 2, 6 => 3, 2 => 4, _ => 0 }; + for j in 0..n { add(rt + j); } + } + Insn::SimdLdSt { rt, replicate: true, .. } => add(rt), + _ => {} + } + } + let mut map = [meta::NO_VECTOR; meta::VECTOR_REGS]; + for slot in &mut map { + let mut best = 0; + for r in 1..32 { + if uses[r] > uses[best] { best = r; } + } + // A fill and a spill cost two memory accesses. In a self-loop + // they are amortized across iterations, so even an operand used + // only once per iteration is worth caching. Ties favor low Vn. + if uses[best] <= if has_loop { 0 } else { 2 } { break; } + *slot = best as u8; + uses[best] = 0; + } + map +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn promote_single_use_loop_input() { + let mut insns = [decode::decode(0x4ee18400), decode::decode(0xb5ffffe0)]; + // add v0.2d,v0.2d,v1.2d; cbnz x0,pc0. V1 is read just once. + assert_eq!(choose(&insns)[..3], [0, 1, meta::NO_VECTOR]); + insns[1] = Insn::Ret { rn: 30 }; + assert_eq!(choose(&insns), [meta::NO_VECTOR; meta::VECTOR_REGS]); + } +} + +impl<'s, 'b> Gen<'s, 'b> { + pub(super) fn vector_prologue(&mut self) { + if self.vlive || self.vectors[0] == meta::NO_VECTOR { return; } + for (x, &g) in self.vectors.iter().enumerate() { + if g < 32 { self.a.vmovdqu_load(x as u8, Mem::gs(voff(g as u32))); } + } + self.vlive = true; + self.point(kind::VSTATE, 1, 0); + } + + pub(super) fn vector_epilogue(&mut self) { + if !self.vlive { return; } + for (x, &g) in self.vectors.iter().enumerate() { + if g < 32 { self.a.vmovdqu_store(Mem::gs(voff(g as u32)), x as u8); } + } + self.vlive = false; + self.point(kind::VSTATE, 0, 0); + } + + pub(super) fn vector_host(&self, n: u32) -> Option { + if !self.vlive { return None; } + self.vectors.iter().position(|&g| g as u32 == n).map(|x| x as u8) + } + + pub(super) fn v_rm(&self, n: u32) -> Rm { + self.vector_host(n).map(Rm::R).unwrap_or(Rm::M(Mem::gs(voff(n)))) + } + + pub(super) fn ld_vec(&mut self, x: u8, n: u32) { + self.a.vex(1, 2, false, false, 0x6f, x, 0, self.v_rm(n)); + } + + pub(super) fn store_vec(&mut self, n: u32, x: u8) { + match self.vector_host(n) { + Some(d) => self.a.vex(1, 2, false, false, 0x6f, d, 0, Rm::R(x)), + None => self.a.vmovdqu_store(Mem::gs(voff(n)), x), + } + } + + /// Return a vector operand starting at a byte offset, using `tmp` + /// when a cached value needs shifting. Does not change guest flags. + pub(super) fn vector_slice(&mut self, n: u32, off: u8, tmp: u8) -> Rm { + match self.vector_host(n) { + Some(x) if off != 0 => { + self.a.vex_ib(1, 1, false, false, 0x73, 3, tmp, Rm::R(x), off); + Rm::R(tmp) + } + Some(x) => Rm::R(x), + None => Rm::M(Mem::gs(voff(n) + off as i32)), + } + } + + /// Zero-extend one lane into a host GPR, without modifying flags. + pub(super) fn vector_extract(&mut self, sz: Sz, dst: Reg, n: u32, lane: u8) { + if let Some(x) = self.vector_host(n) { + if lane == 0 && matches!(sz, Sz::D | Sz::Q) { + self.a.vmov_to_gpr(sz, dst, x); + } else { + let opc = match sz { Sz::B => 0x14, Sz::W => 0x15, _ => 0x16 }; + self.a.vex_ib(3, 1, sz == Sz::Q, false, opc, x, 0, Rm::R(dst), lane); + } + } else { + let bytes = match sz { Sz::B => 1, Sz::W => 2, Sz::D => 4, Sz::Q => 8 }; + let m = Mem::gs(voff(n) + lane as i32 * bytes); + match sz { + Sz::B | Sz::W => self.a.movzx(sz, dst, Rm::M(m)), + _ => self.a.load(sz, dst, m), + } + } + } + + /// Insert one lane in a single commit; all other lanes are preserved. + pub(super) fn vector_insert(&mut self, sz: Sz, n: u32, lane: u8, src: Reg) { + if let Some(x) = self.vector_host(n) { + let (map, opc) = match sz { Sz::B => (3, 0x20), Sz::W => (1, 0xc4), _ => (3, 0x22) }; + self.a.vex_ib(map, 1, sz == Sz::Q, false, opc, x, x, Rm::R(src), lane); + } else { + let bytes = match sz { Sz::B => 1, Sz::W => 2, Sz::D => 4, Sz::Q => 8 }; + self.a.store(sz, Mem::gs(voff(n) + lane as i32 * bytes), src); + } + } +} diff --git a/scripts/vm-smoke.sh b/scripts/vm-smoke.sh index 1dd800e..ae20e8c 100755 --- a/scripts/vm-smoke.sh +++ b/scripts/vm-smoke.sh @@ -14,9 +14,10 @@ grep -q "ALL PASSED" /tmp/abi.log && echo "SMOKE ok abi" echo "== mtstress"; ./mtstress | tail -3 | tee /tmp/mt.log; grep -q "mtstress: ok" /tmp/mt.log && echo "SMOKE ok mtstress" echo "== tbi"; ./tbi > /tmp/tbi.log 2>&1; grep FAIL /tmp/tbi.log; tail -1 /tmp/tbi.log grep -q "TBI ALL PASSED" /tmp/tbi.log && echo "SMOKE ok tbi" +echo "== vector-state"; ./vector-state && echo "SMOKE ok vector-state" echo "== intbench"; ../bench/intbench.arm64 && echo "SMOKE ok intbench" ' 2>&1 | grep -vE '^\[ |iPXE|SeaBIOS|Press|Booting|^.\[\?7l' | tee "$log" -want="hello abi tbi mtstress intbench" +want="hello abi tbi vector-state mtstress intbench" rc=0 for t in $want; do grep -q "SMOKE ok $t" "$log" || { echo "FAILED: $t"; rc=1; } diff --git a/tests/kernel/Makefile b/tests/kernel/Makefile index a4195a6..768be0b 100644 --- a/tests/kernel/Makefile +++ b/tests/kernel/Makefile @@ -3,14 +3,14 @@ CC := aarch64-linux-gnu-gcc CFLAGS := -O2 -Wall -Wno-unused-result -STATIC := abi auxv cat crash hello-static tbi +STATIC := abi auxv cat crash hello-static tbi vector-state DYN := hello-dyn mtstress all: $(STATIC) $(DYN) ../bench/intbench.arm64 abi: abi.c $(CC) $(CFLAGS) -static -pthread -o $@ $< -auxv cat crash tbi: %: %.c +auxv cat crash tbi vector-state: %: %.c $(CC) $(CFLAGS) -static -o $@ $< hello-static: hello.c $(CC) $(CFLAGS) -static -o $@ $< diff --git a/tests/kernel/vector-state.c b/tests/kernel/vector-state.c new file mode 100644 index 0000000..8d7ee63 --- /dev/null +++ b/tests/kernel/vector-state.c @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Live vector cache recovery through a fault, timer signals and sigreturn. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t alarms, faults, bad_frame; +static void *fault_page; + +static void handler(int sig, siginfo_t *si, void *ptr) +{ + if (sig == SIGSEGV) { + ucontext_t *uc = ptr; + struct fpsimd_context *fp = (void *)uc->uc_mcontext.__reserved; + + /* The first loop iteration has committed two adds to V0. */ + if (si->si_addr != fault_page || fp->head.magic != FPSIMD_MAGIC || + (uint64_t)fp->vregs[0] != 3 || (uint64_t)(fp->vregs[0] >> 64) != 4) + bad_frame = 1; + faults++; + if (mprotect(fault_page, 4096, PROT_READ)) + _Exit(2); + } else { + alarms++; + } + /* Leave different values in every guest vector before sigreturn. */ + __asm__ volatile( + ".irp r,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n" + "movi v\\r\\().16b, #0x5a\n.endr\n" + ::: "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", + "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", + "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", + "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); +} + +extern void vector_loop(uint64_t v[32][2], void *fault, unsigned count); +__asm__( + ".text\n.globl vector_loop\n.type vector_loop,%function\nvector_loop:\n" + "stp q8,q9,[sp,#-128]!\nstp q10,q11,[sp,#32]\n" + "stp q12,q13,[sp,#64]\nstp q14,q15,[sp,#96]\n" + ".irp r,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n" + "ldr q\\r,[x0,#(16*\\r)]\n.endr\n" + "1:\n" + ".irp r,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29\n" + "add v\\r\\().2d,v\\r\\().2d,v31.2d\n.endr\n" + "ldr q30,[x1]\nsubs w2,w2,#1\nb.ne 1b\n" + ".irp r,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31\n" + "str q\\r,[x0,#(16*\\r)]\n.endr\n" + "ldp q10,q11,[sp,#32]\nldp q12,q13,[sp,#64]\nldp q14,q15,[sp,#96]\n" + "ldp q8,q9,[sp],#128\nret\n.size vector_loop,.-vector_loop\n"); + +int main(void) +{ + const unsigned n = 200000; + uint64_t v[32][2]; + struct sigaction sa = { .sa_sigaction = handler, .sa_flags = SA_SIGINFO }; + struct itimerval timer = { .it_interval.tv_usec = 100, .it_value.tv_usec = 100 }; + + fault_page = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + assert(fault_page != MAP_FAILED); + ((uint64_t *)fault_page)[0] = 0xfeed; + ((uint64_t *)fault_page)[1] = 0xbeef; + assert(!mprotect(fault_page, 4096, PROT_NONE)); + sigfillset(&sa.sa_mask); + assert(!sigaction(SIGSEGV, &sa, NULL)); + assert(!sigaction(SIGALRM, &sa, NULL)); + for (int r = 0; r < 32; r++) { + v[r][0] = 2 * r + 1; + v[r][1] = 2 * r + 2; + } + v[31][0] = v[31][1] = 1; + assert(!setitimer(ITIMER_REAL, &timer, NULL)); + vector_loop(v, fault_page, n); + timer.it_value.tv_usec = 0; + assert(!setitimer(ITIMER_REAL, &timer, NULL)); + assert(faults == 1 && alarms > 0 && !bad_frame); + for (int r = 0; r < 30; r++) { + uint64_t delta = n * (r < 8 ? 2 : 1); + assert(v[r][0] == 2 * r + 1 + delta && v[r][1] == 2 * r + 2 + delta); + } + assert(v[30][0] == 0xfeed && v[30][1] == 0xbeef); + assert(v[31][0] == 1 && v[31][1] == 1); + printf("PASS vector-state (%d signals, %d fault)\n", alarms, faults); + return 0; +} diff --git a/tools/jit-test/src/main.rs b/tools/jit-test/src/main.rs index c83c8de..4bbe1bb 100644 --- a/tools/jit-test/src/main.rs +++ b/tools/jit-test/src/main.rs @@ -208,7 +208,7 @@ fn lookup_or_translate(pc: u64) -> Result { } let base = REGION + hh.code_used as u64; let out = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, CODE_SIZE - hh.code_used) }; - let cfg = Cfg { stubs: hh.stubs.addrs(REGION), code_uaddr: base, reloc: std::env::var("RELOC").is_ok(), tbi: std::env::var("TBI").is_ok(), crypto: host_crypto() }; + let cfg = Cfg { stubs: hh.stubs.addrs(REGION), code_uaddr: base, reloc: std::env::var("RELOC").is_ok(), tbi: std::env::var("TBI").is_ok(), vector_cache: std::env::var("NO_VCACHE").is_err(), crypto: host_crypto() }; match t1::translate(&mut UEnv, pc, out, &cfg, &mut hh.scratch) { Ok(r) => { hh.blocks.push((base, r.size)); @@ -253,7 +253,7 @@ extern "C" fn on_alarm(_sig: i32, _info: *mut libc::siginfo_t, ucv: *mut libc::c let uc = unsafe { &mut *(ucv as *mut libc::ucontext_t) }; let g = &mut uc.uc_mcontext.gregs; let rip = g[libc::REG_RIP as usize] as u64; - let hregs = meta::HostRegs { + let mut hregs = meta::HostRegs { gpr: [ g[libc::REG_RAX as usize] as u64, g[libc::REG_RCX as usize] as u64, g[libc::REG_RDX as usize] as u64, g[libc::REG_RBX as usize] as u64, @@ -265,18 +265,18 @@ extern "C" fn on_alarm(_sig: i32, _info: *mut libc::siginfo_t, ucv: *mut libc::c g[libc::REG_R14 as usize] as u64, g[libc::REG_R15 as usize] as u64, ], rflags: g[libc::REG_EFL as usize] as u64, + xmm: [[0; 2]; meta::VECTOR_REGS], }; + let fp = unsafe { &*uc.uc_mcontext.fpregs }; + for (d, s) in hregs.xmm.iter_mut().zip(fp._xmm.iter()) { + d[0] = s.element[0] as u64 | ((s.element[1] as u64) << 32); + d[1] = s.element[2] as u64 | ((s.element[3] as u64) << 32); + } let st = state(); let hh = h(); if rip >= REGION && rip < REGION + 4096 { let info = hh.stubs.info((rip - REGION) as u32); - if info != stubs::STUB_PAGE_STATE { - if info == stubs::STUB_PINNED_LIVE_PC_RAX { - st.pc = hregs.gpr[0]; - } - meta::pinned_from_host(st, &hregs); - } - st.nzcv = nzcv_from_image(st.flags_x86); + stubs::recover(info, &hregs, st); } else if let Some(&(b, sz)) = hh.blocks.iter().find(|(b, sz)| rip >= *b && rip < *b + *sz as u64) { let blk = unsafe { std::slice::from_raw_parts(b as *const u8, sz) }; if !meta::recover(blk, (rip - b) as u32, &hregs, st) { @@ -636,6 +636,9 @@ fn gen_loop(r: &mut Rng) -> Vec { } fn gen_case(r: &mut Rng, mode: u32) -> Vec { + if mode == 8 { + return gen_vectors(r); + } if mode == 4 { return gen_calls(r); } @@ -691,6 +694,50 @@ fn gen_case(r: &mut Rng, mode: u32) -> Vec { v } +/// Cache pressure, partial vector writes, helper coherence, memory, calls +/// and conditional self-loops. X16 is the counter; X20 is the data base. +fn gen_vectors(r: &mut Rng) -> Vec { + const OPS: &[u32] = &[ + 0x4ee18400, 0x6e211c00, 0x4ee10c00, // ADD, EOR, SQADD (helper) + 0x4e1f1ce0, 0x4e1e1ce0, 0x4e1c1ce0, 0x4e181ce0, // INS from GPR + 0x6e1b5c20, 0x6e1a5420, 0x6e1c4420, 0x6e180420, // INS element + 0x9eaf00e0, 0x1e2700e0, 0x9e6700e0, // FMOV top/S/D + 0x4e1f0420, 0x4e1e0420, 0x4e1c0420, 0x4e180420, // DUP B/H/S/D + 0x3dc00680, 0x3d800a80, // LDR/STR Q + 0x3d400280, 0x7d400280, 0xbd400280, 0xfd400280, // LDR B/H/S/D + 0x3d000280, 0x7d000280, 0xbd000280, 0xfd000280, // STR B/H/S/D + 0xad400680, 0xad000680, // LDP/STP Q + 0x4c402280, 0x4c002280, 0x4d40ce80, // LD1/ST1/LD1R + 0x4e020020, // TBL: helper reads and writes cached vectors + ]; + let mut v = vec![0xd2800090, 0x14000001]; // mov x16,#4; b loop + let loop_start = v.len(); + for _ in 0..24 { + let w = OPS[r.below(OPS.len() as u64) as usize]; + // Reuse V0..9, with occasional V31/wrapping structure accesses. + let mut rd = if r.below(8) == 0 { 31 } else { r.below(10) as u32 }; + if w == 0xad400680 && rd == 1 { rd = 0; } // LDP destinations must differ + v.push(w | rd); + } + // Read cached lanes into a GPR and use the result for a side exit. + let reads = [0x0e1f3c09, 0x0e1e3c09, 0x0e1c3c09, 0x4e183c09, 0x9eae0009]; + v.push(reads[r.below(5) as usize] | ((r.below(10) as u32) << 5)); + v.push(0xb4000049); // cbz x9,+8 + v.push(0x4ee18400); // add v0.2d,v0.2d,v1.2d + // Exercise the cache across a call on half the cases; otherwise keep + // the entire loop in one block so the back-edge retains XMM state. + let call = if r.below(2) == 0 { let i = v.len(); v.push(0); Some(i) } else { None }; + v.push(0xf1000610); // subs x16,x16,#1 + let back = (loop_start as i32 - v.len() as i32) as u32; + v.push(0x54000001 | ((back & 0x7ffff) << 5)); // b.ne loop + v.push(0xd4200000); + if let Some(i) = call { + v[i] = 0x94000000 | ((v.len() - i) as u32); + v.extend([0x4ee08400, 0x4ee08400, 0x4ee08400, 0xd65f03c0]); + } + v +} + fn is_fp(i: &Insn) -> bool { matches!( i, diff --git a/tools/kemu-user/src/jit.rs b/tools/kemu-user/src/jit.rs index 2e88a26..24c15ea 100644 --- a/tools/kemu-user/src/jit.rs +++ b/tools/kemu-user/src/jit.rs @@ -116,7 +116,7 @@ fn translate(pc: u64) -> Option<(u64, u64)> { } let base = REGION + j.used as u64; let out = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, CODE_SIZE - j.used) }; - let cfg = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: base, reloc: false, tbi: false, crypto: host_crypto() }; + let cfg = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: base, reloc: false, tbi: false, vector_cache: std::env::var("NO_VCACHE").is_err(), crypto: host_crypto() }; let t0 = std::time::Instant::now(); let res = t1::translate(&mut j.env, pc, out, &cfg, &mut j.scratch); j.translate_ns += t0.elapsed().as_nanos() as u64; @@ -252,7 +252,7 @@ fn xlat_bench(start: u64, span: u64) { let j = jit(); let mut buf = vec![0u8; 256 << 10]; let reloc = std::env::var("KEMU_RELOC").is_ok(); - let cfg = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + (1 << 20), reloc, tbi: false, crypto: host_crypto() }; + let cfg = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + (1 << 20), reloc, tbi: false, vector_cache: std::env::var("NO_VCACHE").is_err(), crypto: host_crypto() }; let (mut n, mut bytes, mut insns) = (0u64, 0u64, 0u64); let t0 = std::time::Instant::now(); for _ in 0..5 { @@ -317,7 +317,7 @@ fn reloc_check(start: u64, span: u64) { let (mut n, mut bad, mut uncacheable) = (0u64, 0u64, 0u64); let mut pc = start; while pc < start + span { - let ca = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + off_a, reloc: true, tbi: false, crypto: host_crypto() }; + let ca = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + off_a, reloc: true, tbi: false, vector_cache: std::env::var("NO_VCACHE").is_err(), crypto: host_crypto() }; let ra = match t1::translate(&mut j.env, pc, &mut a, &ca, &mut j.scratch) { Ok(r) => r, Err(_) => { @@ -333,7 +333,7 @@ fn reloc_check(start: u64, span: u64) { continue; } }; - let cb = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + off_b, reloc: true, tbi: false, crypto: host_crypto() }; + let cb = Cfg { stubs: j.stubs.addrs(REGION), code_uaddr: REGION + off_b, reloc: true, tbi: false, vector_cache: std::env::var("NO_VCACHE").is_err(), crypto: host_crypto() }; let rb = { let mut sh = Shifted { env: &mut j.env, d }; t1::translate(&mut sh, pc + d, &mut b, &cb, &mut j.scratch)