From 8db69bcd6496a4e57871246c0aa30febb1295ff9 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 4 Dec 2026 14:37:57 +0000 Subject: [PATCH] kwemu: grow the data TLBs to 16384 entries, with a fill log and a reverse map from host page to write-TLB entries markCode scanned the whole write TLB each time a page got its first decoded chunk, about 40K times per npm --version run (again after every nursery reset), so a larger TLB made npm 18% slower. The reverse map finds a page's write entries through one short chain, so markCode and resetNursery no longer depend on the TLB size; a log of the last 256 fills lets flushAll clear only those. The 544.5 KiB this takes per CPU comes out of the nursery (35K of 320K ops): KW_CPU_SIZE and the ABI stay. Unit tests check the map and the code_flag invariant after every fill, flush and mark change (rmapCheck), and two new tests cover write entries cached before a page gains code, on one CPU and on two. --- .agents/a64/tier.md | 11 ++- .agents/kwemu.md | 15 ++-- src/a64/tier_tests.zig | 173 +++++++++++++++++++++++++++++++++++++ src/emu/kwemu.zig | 190 ++++++++++++++++++++++++++++++++++++----- 4 files changed, 359 insertions(+), 30 deletions(-) diff --git a/.agents/a64/tier.md b/.agents/a64/tier.md index 7946618..d87a632 100644 --- a/.agents/a64/tier.md +++ b/.agents/a64/tier.md @@ -196,10 +196,13 @@ countdowns and compiled code across resets: ring). **Marking decoded code.** Every decode marks its 64-byte chunks in the -page's mark (`markCode`; kwemu.md, Coherence). The write TLB (1024 -entries) is scanned only when a page gets its first marked chunk (or gets -bits again after stores cleared them all); later fills look the page up. -Scanning on every mark was 12% of npm's busy host time. Marks are exact +page's mark (`markCode`; kwemu.md, Coherence). The page's write-TLB +entries are flagged only when it gets its first marked chunk (or gets +bits again after stores cleared them all), found through a reverse map +from host page to write-TLB entries; later fills look the page up. +Scanning the write TLB on every mark was 12% of npm's busy host time, +and a scan per first chunk grew with the TLB (16384 entries: npm 18% +slower, 2026-12-04). Marks are exact per page, 4096 in sets of 8 ways; a page that finds its set full evicts another page's mark and retires that page's generations (its blocks revalidate and mark again before they run). The filter it replaced diff --git a/.agents/kwemu.md b/.agents/kwemu.md index f9a4f0d..545cccc 100644 --- a/.agents/kwemu.md +++ b/.agents/kwemu.md @@ -52,7 +52,8 @@ block is shaped is the ISA's (a64/tier.md). vpn` and `add = host - va`, and the tag is compared against the vpn of the access's last byte, so page-straddling accesses take the slow path for free (still about 15 wasm instructions per access). Read and write - TLBs are direct-mapped, 1024 entries each (32 KiB). Against 256 (riscv64 + TLBs are direct-mapped, 16384 entries each (512 KiB); a log of the last + 256 fills lets a full flush clear only those. Against 256 (riscv64 guest, 2026-11-15): apk, sort, gzip and an ash loop 1.5-3% faster; 4096 gained nothing (Rejected designs). - **Ops.** The op arena is an array of 16-byte slots (`kwemu.Slot`) the @@ -81,8 +82,9 @@ block is shaped is the ISA's (a64/tier.md). stores are tracked exactly: pages holding code have a mark (host page and a 64-byte-chunk bitmap; 4096 marks in sets of 8 ways), and their write-TLB entries carry `code_flag`, which sends stores to the slow - path; the write TLB is scanned only when a page gets its first marked - chunk. A page that finds its set full takes the way of another page, + path; when a page gets its first marked chunk, a reverse map from host + page to write-TLB entries (`WRmap`) finds its entries without a scan of + the write TLB. A page that finds its set full takes the way of another page, whose generations are retired, so its blocks revalidate (and mark again) before they run. A store into a marked chunk retires the page's generations and ends the block, so self-modifying code takes effect at @@ -105,9 +107,10 @@ block is shaped is the ISA's (a64/tier.md). An interpreted self-loop that an interrupt ends still counts its passes towards the compile threshold (`loopDone`): under a stream of IPIs a hot loop otherwise never got compiled. -- **Cache.** 32K block slots, 448K op slots (7 MiB of the 9 MiB - `KW_CPU_SIZE`). The op arena has a nursery (320K slots) where blocks - are decoded and a tenured ring (128K, `ten_default`) where a block's ops +- **Cache.** 32K block slots, 413K op slots (6.45 MiB of the 9 MiB + `KW_CPU_SIZE`; the data TLBs past 1024 entries each, their fill log + and the reverse map take 35K). The op arena has a nursery (285K slots) + where blocks are decoded and a tenured ring (128K, `ten_default`) where a block's ops are copied when it is compiled. When the nursery fills, only its ops are discarded: blocks keep their table entry with pc, host and compile countdown (`op_gone`), a re-decode of the same pc and host goes on diff --git a/src/a64/tier_tests.zig b/src/a64/tier_tests.zig index ba12685..d40d15d 100644 --- a/src/a64/tier_tests.zig +++ b/src/a64/tier_tests.zig @@ -193,6 +193,179 @@ test "a64 tier: stores into code of pages that share a mark set" { for (0..n) |k| try t.expectEqual(@as(u64, 40 + k), try go(&m, 0x100000 + k * 0x10000)); } +test "a64 tier: write-TLB entries cached before a page gains code, aliases and colliding host pages" { + // Every write entry of a page must carry code_flag once the page holds + // decoded code, also entries filled before (through two writable aliases + // and the executable mapping's own VA), so that stores, including those + // of compiled code's inline fast path, take the slow path. Pages whose + // host frames are dtlb_n frames apart share a bucket of the write-TLB + // reverse map (kwemu.zig, `WRmap`): entries of other pages in the chain + // stay unflagged, and flushRange and a refill of the same slot by + // another VA take entries out of the middle of a chain. + const nb: u64 = kwemu.dtlb_n; + var m = try Machine.initSize(t.allocator, (3 * nb + 64) * 4096); + defer m.deinit(); + const fc = m.frame(); // the code page, with two writable aliases + const fs = m.frame(); // a page written and run at one VA + m.next = (fc - mach.pa_base) + nb * 4096; + const col1 = m.frame(); // same bucket as fc + m.next = (fc - mach.pa_base) + 2 * nb * 4096; + const col2 = m.frame(); // same bucket as fc + const fz = m.frame(); + const xva = 0x100000; + const w1 = 0x200000; + const w2 = 0x300000; + const sva = 0x500000; + const zva = w1 + nb * 4096; // the write-TLB slot of w1 + // Everything is mapped first: a map flushes this CPU's TLB. + m.map(xva, fc, R | X); + m.map(w1, fc, R | W); + m.map(w2, fc, R | W); + m.map(sva, fs, R | W | X); + m.map(0x401000, col1, R | W); + m.map(0x402000, col2, R | W); + m.map(zva, fz, R | W); + m.code(0x50000, &.{ A.strw(3, 2, 0), A.svc }); + const store = struct { + fn f(mm: *Machine, va: u64, v: u64) !void { + mm.regs.x[2] = va; + mm.regs.x[3] = v; + mm.regs.pc = 0x50000; + try expectEv(mm, mach.EV_SYSCALL, mm.run(100)); + mm.cpu.rmapCheck(); + } + }.f; + const go = struct { + fn f(mm: *Machine, pc: u64) !u64 { + mm.regs.x[0] = 0; + mm.regs.pc = pc; + try expectEv(mm, mach.EV_SYSCALL, mm.run(100)); + mm.cpu.rmapCheck(); + return mm.regs.x[0]; + } + }.f; + const add = struct { + fn f(imm: u32) u64 { + return A.addi(0, 0, imm); + } + }.f; + const put = struct { + fn f(mm: *Machine, va: u64, imm: u32) void { + const w = [_]u32{ A.addi(0, 0, imm), A.svc }; + @memcpy(mm.at(va)[0..8], std.mem.sliceAsBytes(&w)); + } + }.f; + // Fill the write entries before any code: the code page's aliases, the + // colliding pages, the run-in-place page (twice: the store block is + // compiled by then where the host compiles eagerly). + for (0..2) |_| { + for ([_]u64{ w1, w2, 0x401000, 0x402000, sva }) |va| try store(&m, va + 0x800, 0); + } + put(&m, xva, 1); + put(&m, sva, 1); + try t.expectEqual(@as(u64, 1), try go(&m, xva)); + try t.expectEqual(@as(u64, 1), try go(&m, sva)); + // Stores through every cached entry are seen at once. + try store(&m, w1, add(5)); + try t.expectEqual(@as(u64, 5), try go(&m, xva)); + try store(&m, w2, add(7)); + try t.expectEqual(@as(u64, 7), try go(&m, xva)); + try store(&m, sva, add(9)); + try t.expectEqual(@as(u64, 9), try go(&m, sva)); + // Stores to the other pages of the chain leave the code alone. + try store(&m, 0x401000, add(60)); + try store(&m, 0x402000, add(61)); + try t.expectEqual(@as(u64, 7), try go(&m, xva)); + // flushRange takes w2's entry out of the chain; the refill finds the + // page marked. + m.cpu.flushRange(w2, w2 + 4096); + m.cpu.rmapCheck(); + try store(&m, 0x401000 + 0x800, 0); + try store(&m, w2, add(11)); + try t.expectEqual(@as(u64, 11), try go(&m, xva)); + // Another VA takes w1's slot (its entry leaves the chain), then w1 + // takes it back. + try store(&m, zva, 0); + try store(&m, w1, add(13)); + try t.expectEqual(@as(u64, 13), try go(&m, xva)); + try store(&m, zva + 4, 0); + try t.expectEqual(@as(u64, 13), try go(&m, xva)); + // A store into a chunk with no code leaves the page's code marked. + try store(&m, w1 + 0x800, 0); + try store(&m, w2, add(15)); + try t.expectEqual(@as(u64, 15), try go(&m, xva)); +} + +test "a64 tier: another CPU's write entry, cached before the page gains code there" { + // Code tracking is per kw_cpu: each CPU flags its own write entries when + // it decodes code of the page. CPU B fills its write entries of page P + // (through an alias and through P's own VA) before any code, A and then + // B decode P, and each one's stores through its cached entries are seen + // by its own next run. B sees A's store after B's own IC IVAU. + var m = try Machine.init(t.allocator); + defer m.deinit(); + const pa = m.frame(); + m.map(0x100000, pa, R | W | X); + m.map(0x200000, pa, R | W); + m.code(0x50000, &.{ A.strw(3, 2, 0), A.svc }); + m.code(0x60000, &.{ A.movz(9, 0x10, 1), A.icivau(9), A.isb, A.svc }); + const other = try m.newCpu(); + defer m.freeCpu(other); + other.flushAll(); + var r2: c.Regs = .{}; + const Run = struct { + fn store(mm: *Machine, cpu: *Cpu, r: *c.Regs, va: u64, v: u64) !void { + r.x[2] = va; + r.x[3] = v; + r.pc = 0x50000; + cpu.budget = 100; + if (cpu == mm.cpu) { + mm.regs = r.*; + try expectEv(mm, mach.EV_SYSCALL, mm.run(100)); + r.* = mm.regs; + } else try expectEv(mm, mach.EV_SYSCALL, tier.run(cpu, r)); + cpu.rmapCheck(); + } + fn go(mm: *Machine, cpu: *Cpu, r: *c.Regs, pc: u64) !u64 { + r.x[0] = 0; + r.pc = pc; + cpu.budget = 100; + if (cpu == mm.cpu) { + mm.regs = r.*; + try expectEv(mm, mach.EV_SYSCALL, mm.run(100)); + r.* = mm.regs; + } else try expectEv(mm, mach.EV_SYSCALL, tier.run(cpu, r)); + cpu.rmapCheck(); + return r.x[0]; + } + }; + var r1: c.Regs = .{}; + const w = [_]u32{ A.addi(0, 0, 1), A.svc }; + // Both CPUs fill write entries of P before it holds decoded code. + for ([_]u64{ 0x200800, 0x100800 }) |va| { + try Run.store(&m, other, &r2, va, 0); + try Run.store(&m, m.cpu, &r1, va, 0); + } + @memcpy(m.at(0x100000)[0..8], std.mem.sliceAsBytes(&w)); + try t.expectEqual(@as(u64, 1), try Run.go(&m, m.cpu, &r1, 0x100000)); + try t.expectEqual(@as(u64, 1), try Run.go(&m, other, &r2, 0x100000)); + // B's stores through its alias entry and its same-VA entry. + try Run.store(&m, other, &r2, 0x200000, A.addi(0, 0, 3)); + try t.expectEqual(@as(u64, 3), try Run.go(&m, other, &r2, 0x100000)); + try Run.store(&m, other, &r2, 0x100000, A.addi(0, 0, 4)); + try t.expectEqual(@as(u64, 4), try Run.go(&m, other, &r2, 0x100000)); + // A's own stores through its cached entries. + try Run.store(&m, m.cpu, &r1, 0x200000, A.addi(0, 0, 5)); + try t.expectEqual(@as(u64, 5), try Run.go(&m, m.cpu, &r1, 0x100000)); + try Run.store(&m, m.cpu, &r1, 0x100000, A.addi(0, 0, 6)); + try t.expectEqual(@as(u64, 6), try Run.go(&m, m.cpu, &r1, 0x100000)); + // B sees A's store once B has run IC IVAU of the line. + r2.pc = 0x60000; + other.budget = 100; + try expectEv(&m, mach.EV_SYSCALL, tier.run(other, &r2)); + try t.expectEqual(@as(u64, 6), try Run.go(&m, other, &r2, 0x100000)); +} + test "a64 tier: kernel rewrite + flush, COW copy, set_pgd, and a rewrite made visible only by IC IVAU" { var m = try Machine.init(t.allocator); defer m.deinit(); diff --git a/src/emu/kwemu.zig b/src/emu/kwemu.zig index 9292c53..c3436df 100644 --- a/src/emu/kwemu.zig +++ b/src/emu/kwemu.zig @@ -40,8 +40,31 @@ const tlb_bits = 8; const tlb_n = 1 << tlb_bits; /// Data TLB entries (read and write each). The JIT derives its index mask /// from the array length. -const dtlb_bits = 10; -const dtlb_n = 1 << dtlb_bits; +const dtlb_bits = 14; +pub const dtlb_n = 1 << dtlb_bits; +/// The data-TLB fills since the last `flushAll` are logged (`DLog`), up to +/// this many. While the log has not overflowed, every valid data-TLB entry +/// is one of the logged ones, so `flushAll` (every context switch) visits +/// only those instead of 2 * dtlb_n entries. +const dlog_len = 256; +/// The fill log: entry = TLB index | 0x8000 for the write TLB; `n` counts +/// fills up to dlog_len + 1 (overflowed: the whole TLBs must be cleared). +const DLog = extern struct { n: u64, e: [dlog_len]u16 }; +/// A reverse map from host page to the valid write-TLB entries that map it, +/// so that `markCode` (a page gets its first marked chunk: about 40K times +/// per run of npm --version, most of them again after nursery resets) and +/// `resetNursery` flag that page's entries without scanning the write TLB. +/// Chains of write-TLB slots by host page: `head[b]` is 1 + the first slot +/// of bucket b (b = host page number modulo dtlb_n), `next[i]` 1 + the slot +/// after slot i in its chain; 0 ends a chain. Invariant: the chain of bucket +/// b holds exactly the valid write-TLB entries whose host page is in b, each +/// once (`translate` links a fill and unlinks the entry it replaces, +/// `flushRange` unlinks, `flushAll` empties every chain). Zeroed memory is +/// the empty map. +const WRmap = extern struct { head: [dtlb_n]u16, next: [dtlb_n]u16 }; +/// Unit tests check the reverse map and the write-TLB invariant after every +/// change of marks (`rmapCheck`). +const rmap_check = @import("builtin").is_test; const invalid_tag = std.math.maxInt(u64); /// Write-TLB tag flag: the page holds decoded code, so stores must take the /// slow path (which invalidates the affected blocks). Never matches a vpn. @@ -106,7 +129,7 @@ const ppn_mask: u64 = (1 << 44) - 1; /// collide must not evict each other forever). const nsets = 16384; const nblocks = 2 * nsets; -/// Op arena (16 bytes per op, 7 MiB). With 128K ops, node's startup +/// Op arena (16 bytes per op, 6.45 MiB). With 128K ops, node's startup /// filled it every ~2M instructions (about 270 resets per `npx --version`, /// each freeing every compiled block); 384K ops cut npx by ~7%. /// Two parts: the nursery [0, Priv.nursery), where blocks are decoded, and @@ -114,8 +137,15 @@ const nblocks = 2 * nsets; /// compiled (`tenure`). A full nursery is reset without touching compiled /// code (`resetNursery`); the tenured part is a ring whose oldest blocks /// make room (their code is dropped). -const nops = 448 * 1024; -/// The tenured ring's size in ops (the nursery has the rest, 320K): it holds +const nops = 448 * 1024 - dtlb_extra_ops; +/// Ops given up for the data TLBs beyond 1024 entries each, the fill log and +/// the write-TLB reverse map (544.5 KiB), in steps of 1024 ops: 35K, so that +/// KW_CPU_SIZE stays. The nursery shrinks by as much. +const dtlb_extra_ops = blk: { + const extra: usize = 2 * (dtlb_n - 1024) * @sizeOf(Tlb) + @sizeOf(DLog) + @sizeOf(WRmap); + break :blk (extra + 16 * 1024 - 1) / (16 * 1024) * 1024; +}; +/// The tenured ring's size in ops (the nursery has the rest, 285K): it holds /// the compiled set of one run of a Bun-based program, and a smaller /// nursery made npm slower (a64/performance.md, Tenured ring). pub const ten_default = 128 * 1024; @@ -303,6 +333,8 @@ const Priv = extern struct { stats: Stats, tlb_r: [dtlb_n]Tlb, tlb_w: [dtlb_n]Tlb, + dlog: DLog, + wrmap: WRmap, tlb_x: [2 * tlb_n]XTlb, marks: [nmarks]Mark, blocks: [nblocks]Block, @@ -351,16 +383,35 @@ pub const Cpu = extern struct { // ---- TLB ------------------------------------------------------------------ pub fn flushAll(self: *Cpu) void { - // Volatile stores: keep LLVM from turning this into a memset call. - inline for (.{ &self.priv.tlb_r, &self.priv.tlb_w }) |tlb| { - const p: [*]volatile Tlb = tlb; - for (0..dtlb_n) |i| p[i].tag = invalid_tag; + const d = &self.priv.dlog; + if (d.n <= dlog_len) { + // Every valid data-TLB entry was logged at its fill, so clearing + // the logged ones clears them all, and emptying the reverse-map + // bucket of each logged write entry that is still valid empties + // every chain. + for (d.e[0..@intCast(d.n)]) |x| { + const i: usize = x & 0x7fff; + if (x >> 15 != 0) { + self.rmapEmpty(i); + self.priv.tlb_w[i].tag = invalid_tag; + } else self.priv.tlb_r[i].tag = invalid_tag; + } + } else { + // Volatile stores: keep LLVM from turning this into a memset call. + inline for (.{ &self.priv.tlb_r, &self.priv.tlb_w }) |tlb| { + const p: [*]volatile Tlb = tlb; + for (0..dtlb_n) |i| p[i].tag = invalid_tag; + } + const h: [*]volatile u16 = &self.priv.wrmap.head; + for (0..dtlb_n) |i| h[i] = 0; } + d.n = 0; const x: [*]volatile XTlb = &self.priv.tlb_x; for (0..2 * tlb_n) |i| { x[i].tag = invalid_tag; x[i].gen = 0; } + if (rmap_check) self.rmapCheck(); } pub fn flushRange(self: *Cpu, start: u64, end: u64) void { @@ -373,7 +424,10 @@ pub const Cpu = extern struct { const i: usize = @intCast(vpn & (tlb_n - 1)); const d: usize = @intCast(vpn & (dtlb_n - 1)); if (self.priv.tlb_r[d].tag == vpn) self.priv.tlb_r[d].tag = invalid_tag; - if (self.priv.tlb_w[d].tag & ~code_flag == vpn) self.priv.tlb_w[d].tag = invalid_tag; + if (self.priv.tlb_w[d].tag & ~code_flag == vpn) { + self.rmapUnlink(d); + self.priv.tlb_w[d].tag = invalid_tag; + } for (self.priv.tlb_x[2 * i ..][0..2]) |*x| { if (x.tag == vpn) { x.tag = invalid_tag; @@ -382,6 +436,7 @@ pub const Cpu = extern struct { } if (vpn == last) break; } + if (rmap_check) self.rmapCheck(); } /// Retire every exec-TLB generation: each block is revalidated (same @@ -512,8 +567,19 @@ pub const Cpu = extern struct { const i: usize = @intCast(vpn & (tlb_n - 1)); const add = host -% (vpn << page_shift); switch (access) { - .read => self.priv.tlb_r[@intCast(vpn & (dtlb_n - 1))] = .{ .tag = vpn, .add = add }, - .write => self.priv.tlb_w[@intCast(vpn & (dtlb_n - 1))] = .{ .tag = if (self.isMarked(host)) vpn | code_flag else vpn, .add = add }, + .read => { + const d: u16 = @intCast(vpn & (dtlb_n - 1)); + self.priv.tlb_r[d] = .{ .tag = vpn, .add = add }; + self.logFill(d); + }, + .write => { + const d: u16 = @intCast(vpn & (dtlb_n - 1)); + if (self.priv.tlb_w[d].tag != invalid_tag) self.rmapUnlink(d); + self.priv.tlb_w[d] = .{ .tag = if (self.isMarked(host)) vpn | code_flag else vpn, .add = add }; + self.rmapLink(d, host); + if (rmap_check) self.rmapCheck(); + self.logFill(d | 0x8000); + }, .exec => { const x = self.priv.tlb_x[2 * i ..][0..2]; if (x[0].tag != invalid_tag) x[1] = x[0]; @@ -523,6 +589,13 @@ pub const Cpu = extern struct { return host; } + /// Note a data-TLB fill (`DLog`). + inline fn logFill(self: *Cpu, x: u16) void { + const d = &self.priv.dlog; + if (d.n < dlog_len) d.e[@intCast(d.n)] = x; + if (d.n <= dlog_len) d.n += 1; + } + /// Host address of `va` for a read (no straddle handling). inline fn readHost(self: *Cpu, va: u64) core.Error!u64 { const vpn = va >> page_shift; @@ -565,6 +638,80 @@ pub const Cpu = extern struct { return host; } + // ---- write-TLB reverse map (`WRmap`) -------------------------------------- + + inline fn rmapBucket(host_page: u64) usize { + return @intCast((host_page >> page_shift) & (dtlb_n - 1)); + } + + /// Host page of write-TLB entry `e` (valid; the shift drops code_flag). + inline fn wHostPage(e: Tlb) u64 { + return (e.tag << page_shift) +% e.add; + } + + /// Slot `i` was just filled with a mapping of host `page`'s page. + inline fn rmapLink(self: *Cpu, i: usize, page: u64) void { + const r = &self.priv.wrmap; + const b = rmapBucket(page); + r.next[i] = r.head[b]; + r.head[b] = @intCast(i + 1); + } + + /// Take valid slot `i` out of its chain (before it is replaced or + /// invalidated). Chains average under one entry per bucket. + fn rmapUnlink(self: *Cpu, i: usize) void { + const r = &self.priv.wrmap; + var p: *u16 = &r.head[rmapBucket(wHostPage(self.priv.tlb_w[i]))]; + while (p.* != 0) : (p = &r.next[p.* - 1]) { + if (p.* - 1 == i) { + p.* = r.next[i]; + return; + } + } + unreachable; // a valid entry is in the chain of its bucket + } + + /// flushAll with the fill log: empty the chain that holds slot `i` if it + /// is valid. + inline fn rmapEmpty(self: *Cpu, i: usize) void { + const e = self.priv.tlb_w[i]; + if (e.tag != invalid_tag) self.priv.wrmap.head[rmapBucket(wHostPage(e))] = 0; + } + + /// Set code_flag on every write-TLB entry that maps host `page`. + inline fn rmapFlag(self: *Cpu, page: u64) void { + const r = &self.priv.wrmap; + var p = r.head[rmapBucket(page)]; + while (p != 0) : (p = r.next[p - 1]) { + const e = &self.priv.tlb_w[p - 1]; + if (e.tag & code_flag == 0 and wHostPage(e.*) == page) e.tag |= code_flag; + } + } + + /// Tests: the reverse map holds exactly the valid write entries, each in + /// the chain of its bucket once, and no valid entry of a marked page + /// lacks code_flag (the invariant of `markCode`). + pub fn rmapCheck(self: *Cpu) void { + const r = &self.priv.wrmap; + var seen = [_]bool{false} ** dtlb_n; + for (0..dtlb_n) |b| { + var p = r.head[b]; + while (p != 0) : (p = r.next[p - 1]) { + const i = p - 1; + if (seen[i]) @panic("rmap: slot in two chains or a cycle"); + seen[i] = true; + const e = self.priv.tlb_w[i]; + if (e.tag == invalid_tag) @panic("rmap: invalid entry in a chain"); + if (rmapBucket(wHostPage(e)) != b) @panic("rmap: entry in the wrong chain"); + } + } + for (self.priv.tlb_w, 0..) |e, i| { + if (e.tag == invalid_tag) continue; + if (!seen[i]) @panic("rmap: valid entry in no chain"); + if (e.tag & code_flag == 0 and self.isMarked(wHostPage(e))) @panic("rmap: marked page with an unflagged write entry"); + } + } + // ---- decoded-code tracking ------------------------------------------------ /// The ways of the mark set of `host_page`. @@ -585,13 +732,12 @@ pub const Cpu = extern struct { } /// Record that `mask` chunks of `page` hold decoded code; stores to a - /// page that gets its first marked chunk take the slow path from now on. + /// page that gets its first marked chunk take the slow path from now on + /// (its write-TLB entries are found through the reverse map, `WRmap`). fn markCode(self: *Cpu, page: u64, mask: u64) void { if (!self.markChunks(page, mask)) return; - for (&self.priv.tlb_w) |*e| { - if (e.tag != invalid_tag and e.tag & code_flag == 0 and (e.tag << page_shift) +% e.add == page) - e.tag |= code_flag; - } + self.rmapFlag(page); + if (rmap_check) self.rmapCheck(); } /// The mark part of `markCode`; true if `page` had no marked chunk @@ -711,10 +857,10 @@ pub const Cpu = extern struct { } // Stores into the marked pages take the slow path (markCode does // this per page). - for (&self.priv.tlb_w) |*e| { - if (e.tag != invalid_tag and e.tag & code_flag == 0 and self.isMarked((e.tag << page_shift) +% e.add)) - e.tag |= code_flag; + for (&self.priv.marks) |*m| { + if (m.mask != 0) self.rmapFlag(m.key & ~@as(u64, 1)); } + if (rmap_check) self.rmapCheck(); self.priv.ops_used = 0; } @@ -973,6 +1119,9 @@ comptime { // Layout must match include/kw_emu.h exactly. std.debug.assert(@sizeOf(usize) == 8); // pointer field in kw_cpu std.debug.assert(@sizeOf(Cpu) <= cpu_size); + // DLog: 15-bit indices; WRmap: 1 + slot in a u16. + std.debug.assert(dtlb_bits >= 10 and dtlb_bits <= 14); + std.debug.assert(dlog_len < 1 << 16); // harness.zig reads this layout std.debug.assert(@sizeOf(Stats) == (11 + 192 + (if (stats_on) 2 + 192 + 40 + 64 + 3 * gen_words_n else 0)) * 8); if (stats_on) std.debug.assert(jc.Jx.end <= 64); @@ -1004,6 +1153,7 @@ pub fn cpuInit(cpu: *Cpu) void { cpu.priv.gen = 1; cpu.priv.nursery = nops - ten_default; cpu.priv.ten_mask = ten_default - 1; + cpu.priv.dlog.n = dlog_len + 1; // every entry may hold anything cpu.flushAll(); cpu.resetCache(); if (jc.enabled) jc.init(cpu);