diff --git a/build.zig b/build.zig index 716cede8..25141efa 100644 --- a/build.zig +++ b/build.zig @@ -142,6 +142,7 @@ pub fn build(b: *std.Build) void { }); for (a64_guests) |name| addA64Guest(b, a64_target, name, b.fmt("test/guest/a64/{s}.c", .{name})); for (a64_ports) |p| addA64Guest(b, a64_target, p[0], p[1]); + addA64Guest(b, a64_target, "paravirt_bench", "test/guest/a64/paravirt_bench.c"); // A64 coverage classifier (test/a64-coverage.mjs): which raw words the // interpreter rejects as ILLEGAL, and the group each one is routed to. @@ -251,6 +252,7 @@ fn kwemuModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu fn addA64Guest(b: *std.Build, target: std.Build.ResolvedTarget, name: []const u8, src: []const u8) void { const mod = b.createModule(.{ .target = target, .optimize = .ReleaseFast, .link_libc = true }); + mod.addIncludePath(b.path("include")); mod.addCSourceFile(.{ .file = b.path(src), .flags = &.{ "-std=gnu11", "-Wall", "-fno-vectorize", "-fno-slp-vectorize" } }); mod.linkSystemLibrary("m", .{}); const exe = b.addExecutable(.{ .name = b.fmt("a64-{s}", .{name}), .root_module = mod, .linkage = .static }); diff --git a/include/kw_paravirt.h b/include/kw_paravirt.h new file mode 100644 index 00000000..11fa2561 --- /dev/null +++ b/include/kw_paravirt.h @@ -0,0 +1,102 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2026 Pooya Parsa + * + * Paravirt bulk-op helpers for AArch64 guests running under kwemu. + * + * Reserved permanently-undefined AArch64 UDF opcodes 0x0000_ff00..0x0000_ff0f: + * 0x0000_ff00 KW_MEMCPY x0=dst, x1=src, x2=len -> x0=dst (overlap-safe) + * 0x0000_ff01 KW_MEMSET x0=dst, x1=byte(u8), x2=len -> x0=dst + * 0x0000_ff02 KW_MEMCMP x0=a, x1=b, x2=len -> x0=signed diff + * 0x0000_ff03 KW_DAXPY x0=y, x1=x, x2=n, d0=a -> y[i] += a * x[i] + * 0x0000_ff04 KW_DDOT x0=a, x1=b, x2=n -> d0=sum(a[i] * b[i]) + * + * Example LD_PRELOAD / IFUNC usage: + * void *memcpy(void *dst, const void *src, size_t n) { + * return kw_memcpy(dst, src, n); + * } + * void *memset(void *dst, int c, size_t n) { + * return kw_memset(dst, c, n); + * } + * int memcmp(const void *a, const void *b, size_t n) { + * return kw_memcmp(a, b, n); + * } + */ +#ifndef KW_PARAVIRT_H +#define KW_PARAVIRT_H + +#include +#include + +#define KW_PV_MEMCPY 0x0000ff00u +#define KW_PV_MEMSET 0x0000ff01u +#define KW_PV_MEMCMP 0x0000ff02u +#define KW_PV_DAXPY 0x0000ff03u +#define KW_PV_DDOT 0x0000ff04u + +#if defined(__aarch64__) + +static inline void *kw_memcpy(void *dst, const void *src, size_t len) +{ + register void *x0 __asm__("x0") = dst; + register const void *x1 __asm__("x1") = src; + register size_t x2 __asm__("x2") = len; + __asm__ volatile(".inst 0x0000ff00" + : "+r"(x0) + : "r"(x1), "r"(x2) + : "memory"); + return x0; +} + +static inline void *kw_memset(void *dst, int byte, size_t len) +{ + register void *x0 __asm__("x0") = dst; + register uint64_t x1 __asm__("x1") = (uint8_t)byte; + register size_t x2 __asm__("x2") = len; + __asm__ volatile(".inst 0x0000ff01" + : "+r"(x0) + : "r"(x1), "r"(x2) + : "memory"); + return x0; +} + +static inline int kw_memcmp(const void *a, const void *b, size_t len) +{ + register intptr_t x0 __asm__("x0") = (intptr_t)a; + register const void *x1 __asm__("x1") = b; + register size_t x2 __asm__("x2") = len; + __asm__ volatile(".inst 0x0000ff02" + : "+r"(x0) + : "r"(x1), "r"(x2) + : "memory"); + return (int)x0; +} + +static inline void kw_daxpy(double *y, const double *x, size_t n, double a) +{ + register double *x0 __asm__("x0") = y; + register const double *x1 __asm__("x1") = x; + register size_t x2 __asm__("x2") = n; + register double d0 __asm__("d0") = a; + __asm__ volatile(".inst 0x0000ff03" + : + : "r"(x0), "r"(x1), "r"(x2), "w"(d0) + : "memory"); +} + +static inline double kw_ddot(const double *a, const double *b, size_t n) +{ + register const double *x0 __asm__("x0") = a; + register const double *x1 __asm__("x1") = b; + register size_t x2 __asm__("x2") = n; + register double d0 __asm__("d0"); + __asm__ volatile(".inst 0x0000ff04" + : "=w"(d0) + : "r"(x0), "r"(x1), "r"(x2) + : "memory"); + return d0; +} + +#endif /* __aarch64__ */ + +#endif /* KW_PARAVIRT_H */ diff --git a/src/a64/decode.zig b/src/a64/decode.zig index 39a62001..509082cd 100644 --- a/src/a64/decode.zig +++ b/src/a64/decode.zig @@ -18,11 +18,13 @@ const fp = @import("fp.zig"); const simd_move = @import("simd_move.zig"); const simd_arith = @import("simd_arith.zig"); const crypto = @import("crypto.zig"); +const paravirt = @import("paravirt.zig"); /// The file an encoding belongs to. `unallocated`: reserved, SME, SVE and /// unallocated top-level space (always ILLEGAL here). pub const Group = enum { unallocated, + paravirt, dp_imm, branch, ldst, @@ -37,8 +39,10 @@ pub const Group = enum { pub fn route(inst: u32) Group { const op0 = c.bits(inst, 28, 25); return switch (op0) { - // 0000 reserved (UDF) / SME, 0001 unallocated, 0010 SVE, 0011 unallocated - 0b0000, 0b0001, 0b0010, 0b0011 => .unallocated, + // 0000 reserved (UDF) / SME (0x0000_ff00..0x0000_ff0f: paravirt), + // 0001 unallocated, 0010 SVE, 0011 unallocated + 0b0000 => if (paravirt.isParavirt(inst)) .paravirt else .unallocated, + 0b0001, 0b0010, 0b0011 => .unallocated, 0b1000, 0b1001 => .dp_imm, 0b1010, 0b1011 => .branch, 0b0100, 0b0110, 0b1100, 0b1110 => routeLdSt(inst), @@ -89,6 +93,7 @@ fn routeSimdFp(inst: u32) Group { pub fn exec(s: c.St, inst: u32) c.Error!c.Exit { const e = switch (route(inst)) { .unallocated => return c.ill(s, inst), + .paravirt => try paravirt.exec(s, inst), .dp_imm => try dp_imm.exec(s, inst), .branch => try branch.exec(s, inst), .ldst => try ldst.exec(s, inst), diff --git a/src/a64/ops.zig b/src/a64/ops.zig index 51f47d7b..2d7572a3 100644 --- a/src/a64/ops.zig +++ b/src/a64/ops.zig @@ -26,6 +26,7 @@ const std = @import("std"); const c = @import("common.zig"); +const paravirt = @import("paravirt.zig"); /// Register-file slots, as u64 indexes from ®s.x (struct kw_regs). pub const sp: u8 = 31; @@ -348,7 +349,8 @@ fn extendXform(option: u32, shift: u32) Xform { /// ISB). pub fn decode(inst: u32, pc: u64) Decoded { return switch (bits(inst, 28, 25)) { - 0b0000, 0b0001, 0b0010, 0b0011 => generic(inst, pc, true), // UDF, SME, SVE, unallocated + 0b0000 => generic(inst, pc, !paravirt.isDefined(inst)), // UDF (paravirt stays in block), SME + 0b0001, 0b0010, 0b0011 => generic(inst, pc, true), // SVE, unallocated 0b1000, 0b1001 => dpImm(inst, pc), 0b1010, 0b1011 => branch(inst, pc), 0b0100, 0b0110, 0b1100, 0b1110 => ldst(inst, pc), diff --git a/src/a64/paravirt.zig b/src/a64/paravirt.zig new file mode 100644 index 00000000..217c89e2 --- /dev/null +++ b/src/a64/paravirt.zig @@ -0,0 +1,898 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +//! Paravirt bulk-op instructions in the permanently-undefined AArch64 UDF +//! range `0x0000_ff00 .. 0x0000_ff0f`: +//! 0x0000_ff00 KW_MEMCPY x0=dst, x1=src, x2=len -> x0=dst +//! 0x0000_ff01 KW_MEMSET x0=dst, x1=byte(u8), x2=len -> x0=dst +//! 0x0000_ff02 KW_MEMCMP x0=a, x1=b, x2=len -> x0=signed diff +//! 0x0000_ff03 KW_DAXPY x0=y, x1=x, x2=n, d0=a -> y[i] += a*x[i] +//! 0x0000_ff04 KW_DDOT x0=a, x1=b, x2=n -> d0=sum(a[i]*b[i]) +//! 0x0000_ff05 .. 0x0000_ff0f reserved (ILLEGAL) +//! +//! Each op translates guest pages once per 4 KiB chunk through Cpu.readHost / +//! Cpu.writeHost, probes all pages before mutating memory for precise faults +//! (so demand paging and JIT hand-backs never double-apply or leave partial +//! writes), and notifies SMC code-page tracking via Cpu.writeHost. + +const std = @import("std"); +const c = @import("common.zig"); +const core = @import("../cpu/core.zig"); +const Cpu = c.Cpu; + +pub const base: u32 = 0x0000_ff00; +pub const mask: u32 = 0xffff_fff0; + +pub const KW_MEMCPY: u32 = 0x0000_ff00; +pub const KW_MEMSET: u32 = 0x0000_ff01; +pub const KW_MEMCMP: u32 = 0x0000_ff02; +pub const KW_DAXPY: u32 = 0x0000_ff03; +pub const KW_DDOT: u32 = 0x0000_ff04; + +const page_size: u64 = 4096; +const page_mask: u64 = page_size - 1; + +pub inline fn isParavirt(inst: u32) bool { + return inst & mask == base; +} + +pub inline fn isDefined(inst: u32) bool { + return inst >= KW_MEMCPY and inst <= KW_DDOT; +} + +pub fn exec(s: c.St, inst: u32) c.Error!c.Exit { + return switch (inst) { + KW_MEMCPY => execMemcpy(s), + KW_MEMSET => execMemset(s), + KW_MEMCMP => execMemcmp(s), + KW_DAXPY => execDaxpy(s), + KW_DDOT => execDdot(s), + else => c.ill(s, inst), + }; +} + +fn probeRange(cpu: *Cpu, va: u64, len: u64, access: core.Access) c.Error!void { + return cpu.probeRange(va, len, access); +} + +inline fn hostMemmove(dst: u64, src: u64, n: usize) void { + const d: [*]allowzero u8 = @ptrFromInt(@as(usize, @intCast(dst))); + const s: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(src))); + @memmove(d[0..n], s[0..n]); +} + +inline fn hostMemset(dst: u64, val: u8, n: usize) void { + const d: [*]allowzero u8 = @ptrFromInt(@as(usize, @intCast(dst))); + @memset(d[0..n], val); +} + +fn compareChunk(a_addr: u64, b_addr: u64, n: usize) ?i64 { + const pa: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(a_addr))); + const pb: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(b_addr))); + var i: usize = 0; + while (i + 8 <= n) : (i += 8) { + const va = @as(*allowzero align(1) const u64, @ptrCast(pa + i)).*; + const vb = @as(*allowzero align(1) const u64, @ptrCast(pb + i)).*; + if (va != vb) { + // Little-endian: lowest differing bit lies in the first differing byte. + const diff_byte: usize = @ctz(va ^ vb) >> 3; + return @as(i64, pa[i + diff_byte]) - @as(i64, pb[i + diff_byte]); + } + } + while (i < n) : (i += 1) { + if (pa[i] != pb[i]) return @as(i64, pa[i]) - @as(i64, pb[i]); + } + return null; +} + +/// KW_MEMCPY: x0 = dst, x1 = src, x2 = len -> x0 = dst. +/// Handles arbitrary overlap safely (memmove semantics). +fn execMemcpy(s: c.St) c.Error!c.Exit { + const dst = s.r.x[0]; + const src = s.r.x[1]; + const len = s.r.x[2]; + if (len == 0) return .next; + const cpu = s.m; + + // Single-page fast path for both src and dst: one TLB check each, no pre-probe. + if (len <= page_size and (src & page_mask) + len <= page_size and (dst & page_mask) + len <= page_size) { + const shost = try cpu.readHost(src); + const dhost = try cpu.writeHost(dst, len); + if (dhost != shost) hostMemmove(dhost, shost, @intCast(len)); + return .next; + } + + // Multi-page: probe all pages before modifying memory for precise faults. + try probeRange(cpu, src, len, .read); + try probeRange(cpu, dst, len, .write); + if (dst == src) return .next; + + if (dst > src and dst - src < len) { + // Overlapping with dst > src: copy backward page-chunk by page-chunk. + var d_end = dst + len; + var s_end = src + len; + var rem = len; + while (rem > 0) { + const d_off = ((d_end - 1) & page_mask) + 1; + const s_off = ((s_end - 1) & page_mask) + 1; + const chunk = @min(rem, @min(d_off, s_off)); + d_end -= chunk; + s_end -= chunk; + const shost = try cpu.readHost(s_end); + const dhost = try cpu.writeHost(d_end, chunk); + if (dhost != shost) hostMemmove(dhost, shost, @intCast(chunk)); + rem -= chunk; + } + } else { + // Non-overlapping or dst < src: copy forward page-chunk by page-chunk. + var d_cur = dst; + var s_cur = src; + var rem = len; + while (rem > 0) { + const d_avail = page_size - (d_cur & page_mask); + const s_avail = page_size - (s_cur & page_mask); + const chunk = @min(rem, @min(d_avail, s_avail)); + const shost = try cpu.readHost(s_cur); + const dhost = try cpu.writeHost(d_cur, chunk); + if (dhost != shost) hostMemmove(dhost, shost, @intCast(chunk)); + d_cur += chunk; + s_cur += chunk; + rem -= chunk; + } + } + return .next; +} + +/// KW_MEMSET: x0 = dst, x1 = byte (low 8 bits), x2 = len -> x0 = dst. +fn execMemset(s: c.St) c.Error!c.Exit { + const dst = s.r.x[0]; + const byte: u8 = @truncate(s.r.x[1]); + const len = s.r.x[2]; + if (len == 0) return .next; + const cpu = s.m; + + if (len <= page_size and (dst & page_mask) + len <= page_size) { + const dhost = try cpu.writeHost(dst, len); + hostMemset(dhost, byte, @intCast(len)); + return .next; + } + + try probeRange(cpu, dst, len, .write); + var cur = dst; + var rem = len; + while (rem > 0) { + const chunk = @min(rem, page_size - (cur & page_mask)); + const dhost = try cpu.writeHost(cur, chunk); + hostMemset(dhost, byte, @intCast(chunk)); + cur += chunk; + rem -= chunk; + } + return .next; +} + +/// KW_MEMCMP: x0 = a, x1 = b, x2 = len -> x0 = signed diff (0 if equal). +fn execMemcmp(s: c.St) c.Error!c.Exit { + const a = s.r.x[0]; + const b = s.r.x[1]; + const len = s.r.x[2]; + if (len == 0) { + s.r.x[0] = 0; + return .next; + } + const cpu = s.m; + if (a == b) { + try probeRange(cpu, a, len, .read); + s.r.x[0] = 0; + return .next; + } + var a_cur = a; + var b_cur = b; + var rem = len; + while (rem > 0) { + const a_avail = page_size - (a_cur & page_mask); + const b_avail = page_size - (b_cur & page_mask); + const chunk = @min(rem, @min(a_avail, b_avail)); + const ahost = try cpu.readHost(a_cur); + const bhost = try cpu.readHost(b_cur); + if (compareChunk(ahost, bhost, @intCast(chunk))) |diff| { + s.r.x[0] = @bitCast(diff); + return .next; + } + a_cur +%= chunk; + b_cur +%= chunk; + rem -= chunk; + } + s.r.x[0] = 0; + return .next; +} + +inline fn daxpyChunk(yhost: u64, xhost: u64, count: usize, a: f64) void { + const py: [*]allowzero u8 = @ptrFromInt(@as(usize, @intCast(yhost))); + const px: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(xhost))); + var j: usize = 0; + while (j < count) : (j += 1) { + const off = j * 8; + const xv = @as(*allowzero align(1) const f64, @ptrCast(px + off)).*; + const yp = @as(*allowzero align(1) f64, @ptrCast(py + off)); + yp.* = yp.* + a * xv; + } +} + +/// KW_DAXPY: x0 = y (double*), x1 = x (const double*), x2 = n, d0 = a -> y[i] += a * x[i]. +fn execDaxpy(s: c.St) c.Error!c.Exit { + const y = s.r.x[0]; + const x = s.r.x[1]; + const n = s.r.x[2]; + if (n == 0) return .next; + const a: f64 = @bitCast(c.vd(s, 0)); + const cpu = s.m; + const bytes = if (n >= (@as(u64, 1) << 45)) std.math.maxInt(u64) else n << 3; + + if (bytes <= page_size and (x & page_mask) + bytes <= page_size and (y & page_mask) + bytes <= page_size) { + const xhost = try cpu.readHost(x); + const yhost = try cpu.writeHost(y, bytes); + daxpyChunk(yhost, xhost, @intCast(n), a); + return .next; + } + + // Multi-page: probe all pages before modifying y (daxpy is not idempotent). + try probeRange(cpu, x, bytes, .read); + try probeRange(cpu, y, bytes, .write); + + var y_cur = y; + var x_cur = x; + var rem = n; + while (rem > 0) { + const y_avail = page_size - (y_cur & page_mask); + const x_avail = page_size - (x_cur & page_mask); + const avail = @min(y_avail, x_avail); + if (avail >= 8) { + const count: usize = @intCast(@min(rem, avail >> 3)); + const chunk_bytes: u64 = @as(u64, count) * 8; + const xhost = try cpu.readHost(x_cur); + const yhost = try cpu.writeHost(y_cur, chunk_bytes); + daxpyChunk(yhost, xhost, count, a); + y_cur += chunk_bytes; + x_cur += chunk_bytes; + rem -= count; + } else { + // Unaligned element straddling a page boundary. + const xv: f64 = @bitCast(try cpu.load(u64, x_cur)); + const yv: f64 = @bitCast(try cpu.load(u64, y_cur)); + try cpu.store(u64, y_cur, @bitCast(yv + a * xv)); + y_cur += 8; + x_cur += 8; + rem -= 1; + } + } + return .next; +} + +inline fn ddotChunk(ahost: u64, bhost: u64, count: usize, sum0: f64) f64 { + const pa: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(ahost))); + const pb: [*]allowzero const u8 = @ptrFromInt(@as(usize, @intCast(bhost))); + var sum = sum0; + var j: usize = 0; + while (j < count) : (j += 1) { + const off = j * 8; + const av = @as(*allowzero align(1) const f64, @ptrCast(pa + off)).*; + const bv = @as(*allowzero align(1) const f64, @ptrCast(pb + off)).*; + sum += av * bv; + } + return sum; +} + +/// KW_DDOT: x0 = a (const double*), x1 = b (const double*), x2 = n -> d0 = sum(a[i] * b[i]). +fn execDdot(s: c.St) c.Error!c.Exit { + const a = s.r.x[0]; + const b = s.r.x[1]; + const n = s.r.x[2]; + if (n == 0) { + c.setVd(s, 0, 0); + return .next; + } + const cpu = s.m; + var sum: f64 = 0.0; + var a_cur = a; + var b_cur = b; + var rem = n; + while (rem > 0) { + const a_avail = page_size - (a_cur & page_mask); + const b_avail = page_size - (b_cur & page_mask); + const avail = @min(a_avail, b_avail); + if (avail >= 8) { + const count: usize = @intCast(@min(rem, avail >> 3)); + const chunk_bytes: u64 = @as(u64, count) * 8; + const ahost = try cpu.readHost(a_cur); + const bhost = try cpu.readHost(b_cur); + sum = ddotChunk(ahost, bhost, count, sum); + a_cur +%= chunk_bytes; + b_cur +%= chunk_bytes; + rem -= count; + } else { + const av: f64 = @bitCast(try cpu.load(u64, a_cur)); + const bv: f64 = @bitCast(try cpu.load(u64, b_cur)); + sum += av * bv; + a_cur +%= 8; + b_cur +%= 8; + rem -= 1; + } + } + c.setVd(s, 0, @bitCast(sum)); + return .next; +} + +// ---- unit tests (run natively and on wasm64+JIT via "a64 jit:" filter) -------- + +const t = std.testing; +const decode = @import("decode.zig"); +const mach = @import("machine.zig"); +const Machine = mach.Machine; + +const R: u64 = 2; +const W: u64 = 4; +const X: u64 = 8; + +fn writeGuestBytes(m: *Machine, va: u64, data: []const u8) void { + var cur = va; + var off: usize = 0; + while (off < data.len) { + const dst = m.at(cur); + const n = @min(data.len - off, dst.len); + @memcpy(dst[0..n], data[off..][0..n]); + cur += n; + off += n; + } +} + +fn readGuestBytes(m: *Machine, va: u64, out: []u8) void { + var cur = va; + var off: usize = 0; + while (off < out.len) { + const src = m.at(cur); + const n = @min(out.len - off, src.len); + @memcpy(out[off..][0..n], src[0..n]); + cur += n; + off += n; + } +} + +fn runLockstep(code: []const u32, setup: anytype, check: anytype) !void { + var m_tier = try Machine.init(t.allocator); + defer m_tier.deinit(); + var m_ref = try Machine.init(t.allocator); + defer m_ref.deinit(); + setup(&m_tier, code); + setup(&m_ref, code); + const ev_tier = m_tier.run(100_000); + const ev_ref = m_ref.runRef(100_000); + try t.expectEqual(ev_ref, ev_tier); + try t.expectEqual(m_ref.cpu.icount, m_tier.cpu.icount); + try t.expectEqual(m_ref.cpu.ev, m_tier.cpu.ev); + try t.expectEqual(m_ref.regs, m_tier.regs); + try check(&m_tier, &m_ref); +} + +test "a64 jit: paravirt decode routing and reserved UDF opcodes" { + try t.expectEqual(decode.Group.unallocated, decode.route(0x0000_0000)); + try t.expectEqual(decode.Group.unallocated, decode.route(0x0000_feff)); + try t.expectEqual(decode.Group.unallocated, decode.route(0x0000_ff10)); + try t.expectEqual(decode.Group.unallocated, decode.route(0x0000_dead)); + for (0..16) |i| { + try t.expectEqual(decode.Group.paravirt, decode.route(base + @as(u32, @intCast(i)))); + } + // Reserved slots 0x0000_ff05..0x0000_ff0f and outside UDFs must raise EV_ILLEGAL. + for ([_]u32{ 0x0000_0000, 0x0000_feff, 0x0000_ff05, 0x0000_ff0f, 0x0000_ff10 }) |w| { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.code(0x10000, &.{ w, mach.svc0 }); + try t.expectEqual(@as(u32, mach.EV_ILLEGAL), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + try t.expectEqual(@as(u64, w), m.cpu.ev.insn); + try t.expectEqual(@as(u64, 0), m.cpu.icount); + } +} + +test "a64 jit: paravirt KW_MEMCPY multi-page, unaligned, overlap, zero-len, lockstep" { + const src_va: u64 = 0x20000; + const dst_va: u64 = 0x40000; + // Unaligned copy crossing 3 page boundaries with different page offsets. + const len: usize = 9000; + var pattern: [len]u8 = undefined; + for (&pattern, 0..) |*b, i| b.* = @truncate((i * 73 + 19) ^ (i >> 5)); + + const S = struct { + pat: []const u8, + fn setup(self: @This(), m: *Machine, code: []const u32) void { + m.mapData(src_va, 4); + m.mapData(dst_va, 4); + writeGuestBytes(m, src_va + 17, self.pat); + m.code(0x10000, code); + m.regs.x[0] = dst_va + 333; + m.regs.x[1] = src_va + 17; + m.regs.x[2] = self.pat.len; + } + fn check(self: @This(), m_tier: *Machine, m_ref: *Machine) !void { + try t.expectEqual(@as(u64, dst_va + 333), m_tier.regs.x[0]); + var got_t: [len]u8 = undefined; + var got_r: [len]u8 = undefined; + readGuestBytes(m_tier, dst_va + 333, &got_t); + readGuestBytes(m_ref, dst_va + 333, &got_r); + try t.expectEqualSlices(u8, self.pat, &got_t); + try t.expectEqualSlices(u8, self.pat, &got_r); + } + }; + { + const ctx: S = .{ .pat = &pattern }; + const code = [_]u32{ KW_MEMCPY, mach.svc0 }; + var m_tier = try Machine.init(t.allocator); + defer m_tier.deinit(); + var m_ref = try Machine.init(t.allocator); + defer m_ref.deinit(); + ctx.setup(&m_tier, &code); + ctx.setup(&m_ref, &code); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_tier.run(100)); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_ref.runRef(100)); + try t.expectEqual(m_ref.cpu.icount, m_tier.cpu.icount); + try t.expectEqual(m_ref.regs, m_tier.regs); + try ctx.check(&m_tier, &m_ref); + } + + // Overlapping forward (dst > src) across multiple pages. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 5); + writeGuestBytes(&m, src_va + 50, &pattern); + m.code(0x10000, &.{ KW_MEMCPY, mach.svc0 }); + m.regs.x[0] = src_va + 50 + 500; + m.regs.x[1] = src_va + 50; + m.regs.x[2] = len; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, src_va + 550), m.regs.x[0]); + var got: [len]u8 = undefined; + readGuestBytes(&m, src_va + 550, &got); + try t.expectEqualSlices(u8, &pattern, &got); + } + + // Overlapping backward (dst < src) across multiple pages. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 5); + writeGuestBytes(&m, src_va + 700, &pattern); + m.code(0x10000, &.{ KW_MEMCPY, mach.svc0 }); + m.regs.x[0] = src_va + 123; + m.regs.x[1] = src_va + 700; + m.regs.x[2] = len; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + var got: [len]u8 = undefined; + readGuestBytes(&m, src_va + 123, &got); + try t.expectEqualSlices(u8, &pattern, &got); + } + + // Zero length with NULL pointers must not fault. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.code(0x10000, &.{ KW_MEMCPY, mach.svc0 }); + m.regs.x[0] = 0; + m.regs.x[1] = 0; + m.regs.x[2] = 0; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, 0), m.regs.x[0]); + } +} + +test "a64 jit: paravirt KW_MEMSET multi-page, unaligned, zero-len, lockstep" { + const dst_va: u64 = 0x30000; + const len: usize = 8500; + const code = [_]u32{ KW_MEMSET, mach.svc0 }; + + const setup = struct { + fn f(m: *Machine, w: []const u32) void { + m.mapData(dst_va, 4); + m.code(0x10000, w); + m.regs.x[0] = dst_va + 77; + m.regs.x[1] = 0xdead_beef_cafe_00a5; // only low byte 0xa5 used + m.regs.x[2] = len; + } + }.f; + const check = struct { + fn f(m_tier: *Machine, m_ref: *Machine) !void { + try t.expectEqual(@as(u64, dst_va + 77), m_tier.regs.x[0]); + var got_t: [len + 2]u8 = undefined; + var got_r: [len + 2]u8 = undefined; + readGuestBytes(m_tier, dst_va + 76, &got_t); + readGuestBytes(m_ref, dst_va + 76, &got_r); + try t.expectEqual(@as(u8, 0), got_t[0]); + try t.expectEqual(@as(u8, 0), got_t[len + 1]); + for (got_t[1 .. len + 1]) |b| try t.expectEqual(@as(u8, 0xa5), b); + try t.expectEqualSlices(u8, &got_r, &got_t); + } + }.f; + try runLockstep(&code, setup, check); + + // Zero length with unmapped pointer does not fault. + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.code(0x10000, &.{ KW_MEMSET, mach.svc0 }); + m.regs.x[0] = 0xdead_0000; + m.regs.x[1] = 0x55; + m.regs.x[2] = 0; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, 0xdead_0000), m.regs.x[0]); +} + +test "a64 jit: paravirt KW_MEMCMP equal, signed diff, unaligned, early stop, lockstep" { + const a_va: u64 = 0x20000; + const b_va: u64 = 0x40000; + const len: usize = 8500; + var buf: [len]u8 = undefined; + for (&buf, 0..) |*x, i| x.* = @truncate(i * 31 + 7); + + // Equal multi-page unaligned buffers -> 0. + { + var m_t = try Machine.init(t.allocator); + defer m_t.deinit(); + var m_r = try Machine.init(t.allocator); + defer m_r.deinit(); + for ([_]*Machine{ &m_t, &m_r }) |m| { + m.mapData(a_va, 4); + m.mapData(b_va, 4); + writeGuestBytes(m, a_va + 3, &buf); + writeGuestBytes(m, b_va + 4091, &buf); + m.code(0x10000, &.{ KW_MEMCMP, mach.svc0 }); + m.regs.x[0] = a_va + 3; + m.regs.x[1] = b_va + 4091; + m.regs.x[2] = len; + } + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_t.run(100)); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_r.runRef(100)); + try t.expectEqual(@as(u64, 0), m_t.regs.x[0]); + try t.expectEqual(m_r.regs, m_t.regs); + } + + // Differing bytes at various positions (unsigned byte diff sign-extended to i64). + const diff_cases = [_]struct { pos: usize, av: u8, bv: u8, want: i64 }{ + .{ .pos = 0, .av = 0xff, .bv = 0x00, .want = 255 }, + .{ .pos = 5, .av = 0x00, .bv = 0xff, .want = -255 }, + .{ .pos = 4095, .av = 0x10, .bv = 0x25, .want = -21 }, + .{ .pos = 4096, .av = 0x80, .bv = 0x7f, .want = 1 }, + .{ .pos = len - 1, .av = 0x01, .bv = 0x02, .want = -1 }, + }; + for (diff_cases) |dc| { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(a_va, 4); + m.mapData(b_va, 4); + writeGuestBytes(&m, a_va + 13, &buf); + writeGuestBytes(&m, b_va + 29, &buf); + writeGuestBytes(&m, a_va + 13 + dc.pos, &.{dc.av}); + writeGuestBytes(&m, b_va + 29 + dc.pos, &.{dc.bv}); + m.code(0x10000, &.{ KW_MEMCMP, mach.svc0 }); + m.regs.x[0] = a_va + 13; + m.regs.x[1] = b_va + 29; + m.regs.x[2] = len; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(dc.want, @as(i64, @bitCast(m.regs.x[0]))); + } + + // Early stop: differing on page 0 must NOT fault on unmapped page 1. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(a_va, 1); + m.mapData(b_va, 1); + writeGuestBytes(&m, a_va, &.{ 1, 2, 10 }); + writeGuestBytes(&m, b_va, &.{ 1, 2, 20 }); + m.code(0x10000, &.{ KW_MEMCMP, mach.svc0 }); + m.regs.x[0] = a_va; + m.regs.x[1] = b_va; + m.regs.x[2] = 8192; // page 1 unmapped + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(i64, -10), @as(i64, @bitCast(m.regs.x[0]))); + } + + // Zero length with NULL pointers -> 0. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.code(0x10000, &.{ KW_MEMCMP, mach.svc0 }); + m.regs.x[0] = 0; + m.regs.x[1] = 0; + m.regs.x[2] = 0; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, 0), m.regs.x[0]); + } +} + +test "a64 jit: paravirt KW_DAXPY and KW_DDOT multi-page, unaligned straddle, zero-len, lockstep" { + const y_va: u64 = 0x20000; + const x_va: u64 = 0x40000; + const n: usize = 1100; // > 2 pages (512 doubles/page) + var y_init: [n]f64 = undefined; + var x_init: [n]f64 = undefined; + var y_want: [n]f64 = undefined; + const alpha: f64 = -2.375; + var dot_want: f64 = 0.0; + for (0..n) |i| { + const fi: f64 = @floatFromInt(i); + y_init[i] = fi * 0.25 - 10.0; + x_init[i] = (fi * 0.125) + 1.5; + y_want[i] = y_init[i] + alpha * x_init[i]; + dot_want += y_want[i] * x_init[i]; + } + + // Test both 8-byte aligned and 4-byte unaligned (page-straddling doubles!). + for ([_]struct { yoff: u64, xoff: u64 }{ + .{ .yoff = 0, .xoff = 0 }, + .{ .yoff = 4, .xoff = 12 }, // forces doubles to straddle 4096-byte page boundaries! + .{ .yoff = 4092, .xoff = 4090 }, // immediate page straddle on element 0! + }) |offs| { + var m_t = try Machine.init(t.allocator); + defer m_t.deinit(); + var m_r = try Machine.init(t.allocator); + defer m_r.deinit(); + // Run KW_DAXPY then KW_DDOT in one block! + const code = [_]u32{ KW_DAXPY, KW_DDOT, mach.svc0 }; + for ([_]*Machine{ &m_t, &m_r }) |m| { + m.mapData(y_va, 4); + m.mapData(x_va, 4); + writeGuestBytes(m, y_va + offs.yoff, std.mem.sliceAsBytes(&y_init)); + writeGuestBytes(m, x_va + offs.xoff, std.mem.sliceAsBytes(&x_init)); + m.code(0x10000, &code); + m.regs.x[0] = y_va + offs.yoff; + m.regs.x[1] = x_va + offs.xoff; + m.regs.x[2] = n; + m.regs.v[0] = @as(u64, @bitCast(alpha)) | (@as(u128, 0xdeadbeef) << 64); + } + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_t.run(100)); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_r.runRef(100)); + try t.expectEqual(m_r.cpu.icount, m_t.cpu.icount); + try t.expectEqual(m_r.regs, m_t.regs); + // Verify y[] bit-for-bit and d0 bit-for-bit (and upper 64 bits of v0 cleared by KW_DDOT). + var y_got: [n]f64 = undefined; + readGuestBytes(&m_t, y_va + offs.yoff, std.mem.sliceAsBytes(&y_got)); + for (0..n) |i| { + try t.expectEqual(@as(u64, @bitCast(y_want[i])), @as(u64, @bitCast(y_got[i]))); + } + try t.expectEqual(@as(u128, @as(u64, @bitCast(dot_want))), m_t.regs.v[0]); + } + + // Zero length for KW_DAXPY and KW_DDOT. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.code(0x10000, &.{ KW_DAXPY, KW_DDOT, mach.svc0 }); + m.regs.x[0] = 0; + m.regs.x[1] = 0; + m.regs.x[2] = 0; + m.regs.v[0] = 0xffff_ffff_ffff_ffff_1234_5678_9abc_def0; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u128, 0), m.regs.v[0]); + } +} + +test "a64 jit: paravirt precise faults leave memory and registers untouched" { + const src_va: u64 = 0x20000; + const dst_va: u64 = 0x40000; + + // 1. KW_MEMCPY: page 0 of dst mapped RW, page 1 of dst unmapped -> page 0 must stay zero! + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 2); + m.mapData(dst_va, 1); // page 1 unmapped + @memset(m.at(src_va), 0x77); + @memset(m.at(src_va + 4096), 0x88); + m.code(0x10000, &.{ KW_MEMCPY, mach.svc0 }); + m.regs.x[0] = dst_va; + m.regs.x[1] = src_va; + m.regs.x[2] = 6000; + try t.expectEqual(@as(u32, mach.EV_FAULT), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + try t.expectEqual(@as(u32, @intFromEnum(core.Access.write)), m.cpu.ev.access); + try t.expectEqual(dst_va + 4096, m.cpu.ev.addr); + for (m.at(dst_va)) |b| try t.expectEqual(@as(u8, 0), b); + } + + // 2. KW_MEMSET: page 0 mapped RW, page 1 mapped read-only -> page 0 must stay untouched! + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(dst_va, 1); + m.map(dst_va + 4096, m.frame(), R); // read-only + m.code(0x10000, &.{ KW_MEMSET, mach.svc0 }); + m.regs.x[0] = dst_va; + m.regs.x[1] = 0x99; + m.regs.x[2] = 5000; + try t.expectEqual(@as(u32, mach.EV_FAULT), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + try t.expectEqual(@as(u32, @intFromEnum(core.Access.write)), m.cpu.ev.access); + try t.expectEqual(dst_va + 4096, m.cpu.ev.addr); + for (m.at(dst_va)) |b| try t.expectEqual(@as(u8, 0), b); + } + + // 3. KW_DAXPY: page 0 mapped RW, page 1 unmapped -> page 0 must stay untouched! + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 2); + m.mapData(dst_va, 1); + const one: f64 = 1.0; + const two: f64 = 2.0; + writeGuestBytes(&m, src_va, std.mem.asBytes(&one)); + writeGuestBytes(&m, dst_va, std.mem.asBytes(&two)); + m.code(0x10000, &.{ KW_DAXPY, mach.svc0 }); + m.regs.x[0] = dst_va; + m.regs.x[1] = src_va; + m.regs.x[2] = 600; // > 512 doubles + m.regs.v[0] = @as(u64, @bitCast(@as(f64, 3.0))); + try t.expectEqual(@as(u32, mach.EV_FAULT), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + var got: f64 = 0; + readGuestBytes(&m, dst_va, std.mem.asBytes(&got)); + try t.expectEqual(two, got); + } + + // 4. KW_DDOT: page 1 unmapped -> v0 must stay untouched! + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 1); + m.mapData(dst_va, 2); + m.code(0x10000, &.{ KW_DDOT, mach.svc0 }); + m.regs.x[0] = dst_va; + m.regs.x[1] = src_va; + m.regs.x[2] = 600; + const sentinel: u128 = 0x1122334455667788_99aabbccddeeff00; + m.regs.v[0] = sentinel; + try t.expectEqual(@as(u32, mach.EV_FAULT), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + try t.expectEqual(sentinel, m.regs.v[0]); + } + + // 5. KW_DAXPY / KW_DDOT with huge n (n * 8 overflows u64) faults immediately. + for ([_]u32{ KW_DAXPY, KW_DDOT }) |op| { + var m = try Machine.init(t.allocator); + defer m.deinit(); + m.mapData(src_va, 1); + m.mapData(dst_va, 1); + m.code(0x10000, &.{ op, mach.svc0 }); + m.regs.x[0] = dst_va; + m.regs.x[1] = src_va; + m.regs.x[2] = @as(u64, 1) << 62; + try t.expectEqual(@as(u32, mach.EV_FAULT), m.run(100)); + try t.expectEqual(@as(u64, 0x10000), m.regs.pc); + } +} + +test "a64 jit: paravirt SMC invalidation when KW_MEMCPY or KW_MEMSET overwrites code" { + const addi_x0_1: u32 = 0x9100_0400; // add x0, x0, #1 + const addi_x0_9: u32 = 0x9100_2400; // add x0, x0, #9 + const movz_x0_0: u32 = 0xd280_0000; + + // 1. KW_MEMCPY overwrites an instruction later in the SAME decoded/JIT block! + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + const code_va: u64 = 0x10000; + const data_va: u64 = 0x20000; + m.map(code_va, m.frame(), R | W | X); + m.mapData(data_va, 1); + writeGuestBytes(&m, data_va, std.mem.asBytes(&addi_x0_9)); + const words = [_]u32{ + KW_MEMCPY, // overwrites word 1 (code_va + 4) with add x0, x0, #9 + addi_x0_1, // originally add x0, x0, #1 + mach.svc0, + }; + writeGuestBytes(&m, code_va, std.mem.sliceAsBytes(&words)); + m.regs.pc = code_va; + m.regs.x[0] = code_va + 4; + m.regs.x[1] = data_va; + m.regs.x[2] = 4; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, code_va + 4 + 9), m.regs.x[0]); + } + + // 2. KW_MEMCPY overwrites a previously executed/compiled code page via a writable alias. + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + const target_pa = m.frame(); + m.map(0x10000, target_pa, R | X); + m.map(0x30000, target_pa, R | W); // writable alias + m.mapData(0x40000, 1); + const orig = [_]u32{ movz_x0_0, addi_x0_1, mach.svc0 }; + const patched = [_]u32{ movz_x0_0, addi_x0_9, mach.svc0 }; + writeGuestBytes(&m, 0x30000, std.mem.sliceAsBytes(&orig)); + writeGuestBytes(&m, 0x40000, std.mem.sliceAsBytes(&patched)); + m.code(0x50000, &.{ KW_MEMCPY, mach.svc0 }); + + // First run caches/compiles 0x10000 -> x0 = 1. + m.regs.pc = 0x10000; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, 1), m.regs.x[0]); + + // Overwrite via KW_MEMCPY through alias 0x30000. + m.regs.pc = 0x50000; + m.regs.x[0] = 0x30000; + m.regs.x[1] = 0x40000; + m.regs.x[2] = 12; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + + // Second run of 0x10000 must see the new code -> x0 = 9. + m.regs.pc = 0x10000; + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m.run(100)); + try t.expectEqual(@as(u64, 9), m.regs.x[0]); + } + + // 3. KW_MEMSET zeroes the next instruction in the same block -> EV_ILLEGAL (udf #0). + { + var m = try Machine.init(t.allocator); + defer m.deinit(); + const code_va: u64 = 0x10000; + m.map(code_va, m.frame(), R | W | X); + const words = [_]u32{ KW_MEMSET, addi_x0_1, mach.svc0 }; + writeGuestBytes(&m, code_va, std.mem.sliceAsBytes(&words)); + m.regs.pc = code_va; + m.regs.x[0] = code_va + 4; + m.regs.x[1] = 0; + m.regs.x[2] = 4; + try t.expectEqual(@as(u32, mach.EV_ILLEGAL), m.run(100)); + try t.expectEqual(@as(u64, code_va + 4), m.regs.pc); + try t.expectEqual(@as(u64, 0), m.cpu.ev.insn); + } +} + +test "a64 jit: paravirt loop with KW_DDOT stays lockstep with reference" { + // Tight loop calling KW_DDOT 8 times in a row (self-loop containing a paravirt op). + // loop: KW_DDOT; add x3, x3, #1; subs x4, x4, #1; b.ne loop; svc #0 + const y_va: u64 = 0x20000; + const x_va: u64 = 0x40000; + const n: usize = 64; + var a: [n]f64 = undefined; + var b: [n]f64 = undefined; + var want: f64 = 0.0; + for (0..n) |i| { + a[i] = @floatFromInt(i + 1); + b[i] = 0.5; + want += a[i] * b[i]; + } + const code = [_]u32{ + KW_DDOT, // x0=a, x1=b, x2=n -> d0 + 0x9100_0463, // add x3, x3, #1 + 0xf100_0484, // subs x4, x4, #1 + 0x54ff_ffa1, // b.ne -12 (back to KW_DDOT) + mach.svc0, + }; + const setup = struct { + aa: []const f64, + bb: []const f64, + fn f(self: @This(), m: *Machine) void { + m.mapData(y_va, 1); + m.mapData(x_va, 1); + writeGuestBytes(m, y_va, std.mem.sliceAsBytes(self.aa)); + writeGuestBytes(m, x_va, std.mem.sliceAsBytes(self.bb)); + m.code(0x10000, &code); + m.regs.x[0] = y_va; + m.regs.x[1] = x_va; + m.regs.x[2] = n; + m.regs.x[3] = 0; + m.regs.x[4] = 8; + } + }{ .aa = &a, .bb = &b }; + + var m_t = try Machine.init(t.allocator); + defer m_t.deinit(); + var m_r = try Machine.init(t.allocator); + defer m_r.deinit(); + setup.f(&m_t); + setup.f(&m_r); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_t.run(1000)); + try t.expectEqual(@as(u32, mach.EV_SYSCALL), m_r.runRef(1000)); + try t.expectEqual(m_r.cpu.icount, m_t.cpu.icount); + try t.expectEqual(@as(u64, 8), m_t.regs.x[3]); + try t.expectEqual(@as(u128, @as(u64, @bitCast(want))), m_t.regs.v[0]); + try t.expectEqual(m_r.regs, m_t.regs); +} diff --git a/src/emu/kwemu.zig b/src/emu/kwemu.zig index 5b361d55..8fa2b7e5 100644 --- a/src/emu/kwemu.zig +++ b/src/emu/kwemu.zig @@ -478,7 +478,7 @@ pub const Cpu = extern struct { } /// Host address of `va` for a read (no straddle handling). - inline fn readHost(self: *Cpu, va: u64) core.Error!u64 { + pub inline fn readHost(self: *Cpu, va: u64) core.Error!u64 { const vpn = va >> page_shift; const e = &self.priv.tlb_r[@intCast(vpn & (dtlb_n - 1))]; if (e.tag == vpn) return va +% e.add; @@ -508,7 +508,7 @@ pub const Cpu = extern struct { /// Host address of `va` for a write of `len` bytes that stays in the /// page; handles stores into pages with decoded code. - fn writeHost(self: *Cpu, va: u64, len: u64) core.Error!u64 { + pub fn writeHost(self: *Cpu, va: u64, len: u64) core.Error!u64 { const vpn = va >> page_shift; const i: usize = @intCast(vpn & (dtlb_n - 1)); const e = &self.priv.tlb_w[i]; @@ -837,6 +837,54 @@ pub const Cpu = extern struct { } } + /// Fault now unless every 4 KiB page intersecting `[va, va + len)` may be + /// accessed as `access`. Walks the upper Sv48 levels once per 2 MiB L0 + /// table and scans L0 PTEs directly (without thrashing the 1024-entry TLB), + /// matching `translate` on every permission, A/D, reserved and VA-range + /// check. + pub fn probeRange(self: *Cpu, va: u64, len: u64, access: core.Access) core.Error!void { + if (len == 0) return; + const need: u64 = switch (access) { + .read => pte_v | pte_r | pte_u | pte_a, + .write => pte_v | pte_w | pte_u | pte_a | pte_d, + .exec => pte_v | pte_x | pte_u | pte_a, + }; + var cur = va; + var rem = len; + if (len <= 16 * page_size) { + while (rem > 0) { + try self.probe(cur, access); + const step = @min(rem, page_size - (cur & page_mask)); + cur +%= step; + rem -= step; + } + return; + } + while (rem > 0) { + if (cur >> 48 != 0) return self.fault(cur, access); + var table = self.pgd; + inline for (.{ @as(u6, 3), @as(u6, 2), @as(u6, 1) }) |level| { + const idx = (cur >> (page_shift + 9 * level)) & 511; + const e = hostLoad(u64, self.phys_base +% table +% idx * 8); + if (e & pte_v == 0 or e & (pte_r | pte_w | pte_x) != 0) { + return self.fault(cur, access); + } + table = ((e >> 10) & ppn_mask) << page_shift; + } + const l0_base = self.phys_base +% table; + var idx0: u64 = (cur >> page_shift) & 511; + while (idx0 < 512 and rem > 0) : (idx0 += 1) { + const e = hostLoad(u64, l0_base +% idx0 * 8); + if (e & need != need or (e & (pte_w | pte_r) == pte_w)) { + return self.fault(cur, access); + } + const step = @min(rem, page_size - (cur & page_mask)); + cur +%= step; + rem -= step; + } + } + } + // ---- block lookup / decode -------------------------------------------------- // // The cache machinery (block table, generations, revalidation, code-page diff --git a/src/tests_a64.zig b/src/tests_a64.zig index ea069a11..14fb531f 100644 --- a/src/tests_a64.zig +++ b/src/tests_a64.zig @@ -11,4 +11,5 @@ test { _ = @import("a64/tier_tests.zig"); _ = @import("a64/jit/emit.zig"); _ = @import("a64/jit/tests.zig"); + _ = @import("a64/paravirt.zig"); } diff --git a/src/tests_a64_wasm.zig b/src/tests_a64_wasm.zig index 80cd6bd1..39761f7b 100644 --- a/src/tests_a64_wasm.zig +++ b/src/tests_a64_wasm.zig @@ -15,5 +15,6 @@ test { _ = @import("a64/tier_tests.zig"); _ = @import("a64/jit/emit.zig"); _ = jit_tests; + _ = @import("a64/paravirt.zig"); _ = @import("emu/kwemu.zig"); // kw_debug_cpu_of_jit_buf } diff --git a/test/guest/a64/paravirt_bench.c b/test/guest/a64/paravirt_bench.c new file mode 100644 index 00000000..271e491c --- /dev/null +++ b/test/guest/a64/paravirt_bench.c @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +/* + * Paravirt bulk-op benchmark: compares baseline C/libc vs kwemu paravirt + * bulk instructions (KW_MEMCPY, KW_MEMSET, KW_MEMCMP, KW_DAXPY, KW_DDOT). + * + * Portable across AArch64 Linux guest (kwemu), Native ARM64, and Direct Wasm + * (with -DPARAVIRT_WASM_EXPORT for freestanding wasm32/wasm64). + * + * Usage (CLI): + * paravirt_bench [reps] + * bench: mem_seq | mem_copy | mem_set | mem_cmp | fp_daxpy_2d | fp_matmul + * mode: base | pv + */ +#include +#include +#pragma STDC FP_CONTRACT OFF + +#if defined(__aarch64__) && !defined(PARAVIRT_NO_PV) +#include "kw_paravirt.h" +#define HAVE_KW_PV 1 +#else +#define HAVE_KW_PV 0 +#endif + +#ifndef PARAVIRT_WASM_EXPORT +#include +#include +#include +#include + +static uint64_t now_ns(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec; +} +#endif + +#define MEM_BYTES (8u << 20) +static uint8_t g_buf_a[MEM_BYTES] __attribute__((aligned(4096))); +static uint8_t g_buf_b[MEM_BYTES] __attribute__((aligned(4096))); + +#ifdef PARAVIRT_WASM_EXPORT +static void *base_memcpy(void *dst, const void *src, size_t n) +{ + return __builtin_memcpy(dst, src, n); +} +static void *base_memset(void *dst, int c, size_t n) +{ + return __builtin_memset(dst, c, n); +} +static int base_memcmp(const void *a, const void *b, size_t n) +{ + const uint8_t *pa = (const uint8_t *)a; + const uint8_t *pb = (const uint8_t *)b; + for (size_t i = 0; i < n; i++) { + if (pa[i] != pb[i]) + return (int)pa[i] - (int)pb[i]; + } + return 0; +} +#else +static void *base_memcpy(void *dst, const void *src, size_t n) +{ + return memcpy(dst, src, n); +} +static void *base_memset(void *dst, int c, size_t n) +{ + return memset(dst, c, n); +} +static int base_memcmp(const void *a, const void *b, size_t n) +{ + return memcmp(a, b, n); +} +#endif + +__attribute__((noinline)) +static void base_daxpy(double *y, const double *x, size_t n, double a) +{ + for (size_t i = 0; i < n; i++) + y[i] += a * x[i]; +} + +__attribute__((noinline)) +static double base_ddot(const double *a, const double *b, size_t n) +{ + double s = 0.0; + for (size_t i = 0; i < n; i++) + s += a[i] * b[i]; + return s; +} + +static uint64_t f64_bits(double v) +{ + uint64_t u; + __builtin_memcpy(&u, &v, sizeof(u)); + return u; +} + +/* Touch every page of g_buf_a and g_buf_b so timing measures warm steady-state. */ +static void init_mem(void) +{ + for (size_t i = 0; i < MEM_BYTES; i += 4096) { + uint8_t v = (uint8_t)((i >> 12) * 7 + 3); + g_buf_a[i] = v; + g_buf_b[i] = v; + } +} + +/* 1. mem_seq: 8 MiB memset + memcpy + memcmp (reps default 8). */ +static uint64_t bench_mem_seq(int use_pv, int reps) +{ + uint64_t acc = 0; + for (int r = 0; r < reps; r++) { + uint8_t val = (uint8_t)((r + 1) * 37 + 11); +#if HAVE_KW_PV + if (use_pv) { + kw_memset(g_buf_a, val, MEM_BYTES); + g_buf_a[r * 997] = (uint8_t)(val ^ 0x5a); + kw_memcpy(g_buf_b, g_buf_a, MEM_BYTES); + int eq = kw_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + g_buf_b[MEM_BYTES - 1] ^= 1; + int neq = kw_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + acc = acc * 131 + (uint64_t)(uint32_t)eq + (uint64_t)(uint32_t)(neq != 0) + g_buf_b[r * 997]; + continue; + } +#endif + (void)use_pv; + base_memset(g_buf_a, val, MEM_BYTES); + g_buf_a[r * 997] = (uint8_t)(val ^ 0x5a); + base_memcpy(g_buf_b, g_buf_a, MEM_BYTES); + int eq = base_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + g_buf_b[MEM_BYTES - 1] ^= 1; + int neq = base_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + acc = acc * 131 + (uint64_t)(uint32_t)eq + (uint64_t)(uint32_t)(neq != 0) + g_buf_b[r * 997]; + } + return acc; +} + +/* Pure 8 MiB memcpy (reps default 16 = 128 MiB copied). */ +static uint64_t bench_mem_copy(int use_pv, int reps) +{ + uint64_t acc = 0; + for (int r = 0; r < reps; r++) { + g_buf_a[(size_t)r * 4096 % MEM_BYTES] = (uint8_t)(r + 7); +#if HAVE_KW_PV + if (use_pv) { + kw_memcpy(g_buf_b, g_buf_a, MEM_BYTES); + } else +#endif + { + (void)use_pv; + base_memcpy(g_buf_b, g_buf_a, MEM_BYTES); + } + acc = acc * 31 + g_buf_b[(size_t)r * 4096 % MEM_BYTES]; + } + return acc; +} + +/* Pure 8 MiB memset (reps default 16 = 128 MiB filled). */ +static uint64_t bench_mem_set(int use_pv, int reps) +{ + uint64_t acc = 0; + for (int r = 0; r < reps; r++) { + int v = (r * 29 + 5) & 0xff; +#if HAVE_KW_PV + if (use_pv) { + kw_memset(g_buf_a, v, MEM_BYTES); + } else +#endif + { + (void)use_pv; + base_memset(g_buf_a, v, MEM_BYTES); + } + acc = acc * 31 + g_buf_a[MEM_BYTES - 1 - (size_t)r]; + } + return acc; +} + +/* Pure 8 MiB memcmp (reps default 16 = 128 MiB compared). */ +static uint64_t bench_mem_cmp(int use_pv, int reps) +{ + uint64_t acc = 0; + for (int r = 0; r < reps; r++) { + int d; +#if HAVE_KW_PV + if (use_pv) { + d = kw_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + } else +#endif + { + (void)use_pv; + d = base_memcmp(g_buf_a, g_buf_b, MEM_BYTES); + } + acc = acc * 31 + (uint64_t)(uint32_t)(d + r + 1); + } + return acc; +} + +/* 2. fp_daxpy_2d: 256 x 256 grid (65,536 doubles = 512 KiB per matrix). */ +enum { DAXPY_ROWS = 256, DAXPY_COLS = 256, DAXPY_N = DAXPY_ROWS * DAXPY_COLS }; +static double g_y[DAXPY_N] __attribute__((aligned(4096))); +static double g_x[DAXPY_N] __attribute__((aligned(4096))); + +static void init_daxpy(void) +{ + for (size_t i = 0; i < DAXPY_N; i++) { + g_y[i] = (double)((i * 7 + 3) % 251) * 0.125 - 10.0; + g_x[i] = (double)((i * 11 + 5) % 199) * 0.0625 + 0.5; + } +} + +static uint64_t bench_fp_daxpy_2d(int use_pv, int reps) +{ + for (int r = 0; r < reps; r++) { + double alpha = (r & 1) ? -0.375 : 0.625; + for (size_t row = 0; row < DAXPY_ROWS; row++) { + double *yr = g_y + row * DAXPY_COLS; + const double *xr = g_x + row * DAXPY_COLS; +#if HAVE_KW_PV + if (use_pv) { + kw_daxpy(yr, xr, DAXPY_COLS, alpha); + continue; + } +#endif + (void)use_pv; + base_daxpy(yr, xr, DAXPY_COLS, alpha); + } + } + double sum = 0.0; + for (size_t i = 0; i < DAXPY_N; i += 17) + sum += g_y[i]; + return f64_bits(sum); +} + +/* 3. fp_matmul: 96 x 96 double matmul using contiguous dot product (KW_DDOT). */ +enum { MM_N = 96 }; +static double g_A[MM_N][MM_N] __attribute__((aligned(4096))); +static double g_B[MM_N][MM_N] __attribute__((aligned(4096))); +static double g_Bt[MM_N][MM_N] __attribute__((aligned(4096))); +static double g_C[MM_N][MM_N] __attribute__((aligned(4096))); + +static void init_matmul(void) +{ + for (int i = 0; i < MM_N; i++) + for (int j = 0; j < MM_N; j++) { + g_A[i][j] = ((i * 7 + j * 3) % 17) * 0.25; + g_B[i][j] = ((i + 2 * j) % 13) * 0.5 - 1.0; + } + for (int i = 0; i < MM_N; i++) + for (int j = 0; j < MM_N; j++) + g_Bt[j][i] = g_B[i][j]; +} + +static uint64_t bench_fp_matmul(int use_pv, int reps) +{ + double acc = 0.0; + for (int r = 0; r < reps; r++) { + for (int i = 0; i < MM_N; i++) { + for (int j = 0; j < MM_N; j++) { +#if HAVE_KW_PV + if (use_pv) { + g_C[i][j] = kw_ddot(g_A[i], g_Bt[j], MM_N); + continue; + } +#endif + (void)use_pv; + g_C[i][j] = base_ddot(g_A[i], g_Bt[j], MM_N); + } + } + acc += g_C[r % MM_N][(r * 5) % MM_N]; + } + return f64_bits(acc); +} + +#ifdef PARAVIRT_WASM_EXPORT +__attribute__((export_name("init_bench"))) +void init_bench(int bench_id) +{ + switch (bench_id) { + case 0: case 1: case 2: case 3: init_mem(); break; + case 4: init_daxpy(); break; + case 5: init_matmul(); break; + default: break; + } +} + +__attribute__((export_name("run_bench"))) +uint64_t run_bench(int bench_id, int reps) +{ + switch (bench_id) { + case 0: return bench_mem_seq(0, reps ? reps : 8); + case 1: return bench_mem_copy(0, reps ? reps : 16); + case 2: return bench_mem_set(0, reps ? reps : 16); + case 3: return bench_mem_cmp(0, reps ? reps : 16); + case 4: return bench_fp_daxpy_2d(0, reps ? reps : 64); + case 5: return bench_fp_matmul(0, reps ? reps : 20); + default: return 0; + } +} +#else +int main(int argc, char **argv) +{ + const char *what = argc > 1 ? argv[1] : "mem_seq"; + const char *mode = argc > 2 ? argv[2] : "base"; + int reps = argc > 3 ? atoi(argv[3]) : 0; + int use_pv = !strcmp(mode, "pv"); + uint64_t r = 0, t0, t1; + + if (!strcmp(what, "mem_seq")) { + init_mem(); + t0 = now_ns(); + r = bench_mem_seq(use_pv, reps ? reps : 8); + t1 = now_ns(); + } else if (!strcmp(what, "mem_copy")) { + init_mem(); + t0 = now_ns(); + r = bench_mem_copy(use_pv, reps ? reps : 16); + t1 = now_ns(); + } else if (!strcmp(what, "mem_set")) { + init_mem(); + t0 = now_ns(); + r = bench_mem_set(use_pv, reps ? reps : 16); + t1 = now_ns(); + } else if (!strcmp(what, "mem_cmp")) { + init_mem(); + t0 = now_ns(); + r = bench_mem_cmp(use_pv, reps ? reps : 16); + t1 = now_ns(); + } else if (!strcmp(what, "fp_daxpy_2d")) { + init_daxpy(); + t0 = now_ns(); + r = bench_fp_daxpy_2d(use_pv, reps ? reps : 64); + t1 = now_ns(); + } else if (!strcmp(what, "fp_matmul")) { + init_matmul(); + t0 = now_ns(); + r = bench_fp_matmul(use_pv, reps ? reps : 20); + t1 = now_ns(); + } else { + fprintf(stderr, "unknown bench: %s\n", what); + return 2; + } + printf("%s/%s: %016llx ms=%.3f\n", what, mode, (unsigned long long)r, (double)(t1 - t0) / 1e6); + return 0; +} +#endif diff --git a/test/paravirt-bench.mjs b/test/paravirt-bench.mjs new file mode 100644 index 00000000..8c36eb3c --- /dev/null +++ b/test/paravirt-bench.mjs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// Benchmark comparing baseline AArch64 vs kwemu paravirt bulk ops +// (KW_MEMCPY, KW_MEMSET, KW_MEMCMP, KW_DAXPY, KW_DDOT) against +// Direct Wasm and Native ARM64 (warm steady-state timing). +// +// Usage: node test/paravirt-bench.mjs [zig-out prefix] [--reps N] +import { readFile, mkdtemp, rm } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; +import { join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { createJitHost } from "./kwemu-jit-host.mjs"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const argv = process.argv.slice(2); +const prefix = resolve(argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--reps") ?? join(root, "zig-out")); +const repsArg = argv.indexOf("--reps"); +const runs = repsArg >= 0 ? Number(argv[repsArg + 1]) : 5; + +const elf = join(prefix, "guest", "a64", "paravirt_bench.elf"); +const srcC = join(root, "test", "guest", "a64", "paravirt_bench.c"); +const jitPath = join(prefix, "bin", "kwemu-harness-jit.wasm"); +const dec = new TextDecoder(); + +const benchmarks = [ + { id: 0, name: "mem_seq", reps: 8, desc: "8 MiB memset+memcpy+memcmp x8" }, + { id: 1, name: "mem_copy", reps: 16, desc: "8 MiB memcpy x16 (128 MiB)" }, + { id: 2, name: "mem_set", reps: 16, desc: "8 MiB memset x16 (128 MiB)" }, + { id: 3, name: "mem_cmp", reps: 16, desc: "8 MiB memcmp x16 (128 MiB)" }, + { id: 4, name: "fp_daxpy_2d", reps: 64, desc: "256x256 daxpy x64 (4.19M ops)" }, + { id: 5, name: "fp_matmul", reps: 20, desc: "96x96 matmul (ddot) x20" }, +]; + +const jitModule = await WebAssembly.compile(await readFile(jitPath)); + +const tmp = await mkdtemp(join(tmpdir(), "kw-pv-bench-")); +const directWasmPath = join(tmp, "paravirt_bench_direct.wasm"); +const nativeBinPath = join(tmp, "paravirt_bench_native"); + +try { + // Compile Direct Wasm using zig cc (wasm32-freestanding + bulk-memory) + const wBuild = spawnSync("mise", [ + "exec", "zig@0.16.0", "--", "zig", "cc", + "-target", "wasm32-freestanding", "-O3", + "-mbulk-memory", "-fno-vectorize", "-fno-slp-vectorize", + "-DPARAVIRT_WASM_EXPORT", + "-Wl,--no-entry", "-Wl,--export=init_bench", "-Wl,--export=run_bench", "-Wl,--initial-memory=33554432", + srcC, "-o", directWasmPath, + ], { encoding: "utf8" }); + if (wBuild.status !== 0) { + throw new Error(`Direct Wasm build failed:\n${wBuild.stderr}`); + } + const directWasmMod = await WebAssembly.compile(await readFile(directWasmPath)); + + // Compile Native binary + const nBuild = spawnSync("clang", [ + "-O3", "-fno-vectorize", "-fno-slp-vectorize", + "-DPARAVIRT_NO_PV", srcC, "-o", nativeBinPath, + ], { encoding: "utf8" }); + if (nBuild.status !== 0) { + throw new Error(`Native build failed:\n${nBuild.stderr}`); + } + + function median(arr) { + const s = [...arr].sort((a, b) => a - b); + return s[(s.length - 1) >> 1]; + } + + function parseOut(stdout) { + const m = /([0-9a-f]{16}) ms=([\d.]+)/.exec(stdout); + if (!m) throw new Error(`unexpected benchmark output: ${JSON.stringify(stdout)}`); + return { sum: m[1], ms: Number(m[2]) }; + } + + async function runKwemuJit(benchName, mode, reps) { + let out = "", err = "", mem; + const jit = createJitHost(); // default threshold + const imports = { + env: { + host_write: (fd, ptr, len) => { + const s = dec.decode(new Uint8Array(mem.buffer, Number(ptr), Number(len))); + if (fd === 2) err += s; else out += s; + }, + host_now_ns: () => Number(process.hrtime.bigint()), + }, + unkernel: jit.imports, + }; + const inst = await WebAssembly.instantiate(jitModule, imports); + const ex = inst.exports; + mem = ex.memory; + jit.attach(ex); + const image = await readFile(elf); + const args = ["paravirt_bench", benchName, mode, String(reps)]; + const argBytes = new TextEncoder().encode(args.join("\0") + "\0"); + const total = image.length + argBytes.length; + const ptr = Number(ex.kwh_buf(BigInt(total))); + new Uint8Array(mem.buffer, ptr, total).set(image); + new Uint8Array(mem.buffer, ptr + image.length, argBytes.length).set(argBytes); + const status = ex.kwh_run(BigInt(image.length), BigInt(argBytes.length), 1); + if (status !== 0) throw new Error(`kwemu ${benchName}/${mode} failed (${status}): ${err}`); + const { sum, ms } = parseOut(out); + const insn = /instret=(\d+)/.exec(err)?.[1] ?? "0"; + return { ms, sum, insns: Number(insn) }; + } + + async function runDirectWasm(benchId, reps) { + const inst = await WebAssembly.instantiate(directWasmMod, {}); + const { init_bench, run_bench } = inst.exports; + // Warm up once for V8 TurboFan + init_bench(benchId); + run_bench(benchId, 1); + const times = []; + let sum = ""; + for (let i = 0; i < runs; i++) { + init_bench(benchId); + const t0 = process.hrtime.bigint(); + const r = run_bench(benchId, reps); + const dtMs = Number(process.hrtime.bigint() - t0) / 1e6; + times.push(dtMs); + sum = BigInt.asUintN(64, r).toString(16).padStart(16, "0"); + } + return { ms: median(times), sum }; + } + + function runNative(benchName, reps) { + const times = []; + let sum = ""; + for (let i = 0; i < runs; i++) { + const p = spawnSync(nativeBinPath, [benchName, "base", String(reps)], { encoding: "utf8" }); + if (p.status !== 0) throw new Error(`native ${benchName} failed: ${p.stderr}`); + const r = parseOut(p.stdout); + times.push(r.ms); + sum = r.sum; + } + return { ms: median(times), sum }; + } + + console.log(`Paravirt bulk-op benchmark (median of ${runs} runs, steady-state loop time, wasm64+jit default threshold)`); + console.log(""); + console.log("| benchmark | workload | kwemu base (ms) | kwemu pv (ms) | speedup | Direct Wasm (ms) | Native ARM64 (ms) | pv / Wasm | base Minsns | pv Minsns | checksum |"); + console.log("| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"); + + for (const b of benchmarks) { + const baseTimes = [], pvTimes = []; + let baseSum = "", pvSum = "", baseInsns = 0, pvInsns = 0; + for (let i = 0; i < runs; i++) { + const rb = await runKwemuJit(b.name, "base", b.reps); + baseTimes.push(rb.ms); + baseSum = rb.sum; + baseInsns = rb.insns; + const rp = await runKwemuJit(b.name, "pv", b.reps); + pvTimes.push(rp.ms); + pvSum = rp.sum; + pvInsns = rp.insns; + } + const dw = await runDirectWasm(b.id, b.reps); + const nat = runNative(b.name, b.reps); + + if (baseSum !== pvSum || baseSum !== dw.sum || baseSum !== nat.sum) { + throw new Error(`Checksum mismatch on ${b.name}: base=${baseSum} pv=${pvSum} wasm=${dw.sum} native=${nat.sum}`); + } + const bMs = median(baseTimes); + const pMs = median(pvTimes); + const speedup = bMs / pMs; + const vsWasm = pMs / dw.ms; + console.log( + `| ${b.name} | ${b.desc} | ${bMs.toFixed(2)} | ${pMs.toFixed(2)} | ${speedup.toFixed(2)}x | ${dw.ms.toFixed(2)} | ${nat.ms.toFixed(2)} | ${vsWasm.toFixed(2)}x | ${(baseInsns / 1e6).toFixed(2)} | ${(pvInsns / 1e6).toFixed(3)} | ${baseSum} |` + ); + } +} finally { + await rm(tmp, { recursive: true, force: true }); +}