From 4c6b0c030e0fd43cee53d41ddb2a7ae2dbb2a9b7 Mon Sep 17 00:00:00 2001 From: Samueltgg12 Date: Mon, 30 Nov 2026 11:38:02 -0300 Subject: [PATCH 1/3] jitv2: per-CPU page generation counters remove the per-store shared RMW A jitv2 build paid ~10% on every guest store from a shared gen[phys >> 12].fetch_add(1, Release), which also ping-ponged the cache line between guest CPUs and compile workers. Each 4KB page now has 16 counters: slot 0 for bus/DMA/monitor writes, slots 1..8 for the guest CPUs. A CPU store bumps only its own slot with a plain Release store (no atomic RMW, single writer); PhysicalCodePage::current_gen() takes the max of all slots with Acquire, so any CPU's or a device's write is observed before code is published. CodePage::gen_slots bounds the read (16 for RAM, 1 for ROM/MMIO); NEVER_COMPILABLE_GEN is an array. ppMem GEN_RATIO 512 -> 32 (16 counters per page), GEN_WINDOW_SIZE 128MB; all window map/scrub/mark sites and the JIT inline store's gen index scaled by GEN_SLOTS; MipsCore::cpu_id selects the slot. bump_gen_all bumps every slot; install_jit_mem_ptrs stamps each cache's CPU id. SMP-safe: single-writer slots + Release/Acquire + max over all CPUs. cargo check (jitv2, +rex-jit/gr4-jit/gr2-jit/wgpu/gputrace) clean; ppmem 51 passed; jitv2 523 passed. Not yet guest-measured. --- CHANGELOG.md | 7 ++ clanker/INDEX.md | 1 + clanker/jitv2/per-cpu-page-generation.md | 73 +++++++++++++++ src/cpu/jitv2/codegen.rs | 40 ++++---- src/cpu/jitv2/jitv2.rs | 35 +++++-- src/cpu/mips_cache_shadow.rs | 22 ++++- src/cpu/mips_cache_v2.rs | 27 +++++- src/cpu/mips_exec.rs | 3 + src/dev/mem.rs | 31 ++++--- src/ppmem/mod.rs | 2 + src/ppmem/ppmem.rs | 112 +++++++++++++++-------- src/traits.rs | 12 ++- 12 files changed, 284 insertions(+), 81 deletions(-) create mode 100644 clanker/jitv2/per-cpu-page-generation.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b6265829d..aec0494d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -351,6 +351,13 @@ hashes are given where a change is easiest to understand by reading the commit. interrupt mask no longer empties the CPU's translation cache, which halves translation misses on a busy 4-CPU Tezro. All machines. +### jitv2 memory + +- jitv2 no longer bumps a shared per-page counter on every guest store. Each + CPU bumps its own counter slot and a compile reads the maximum of all slots, + so this also removes the cross-CPU cache-line contention. All machines; + especially SMP guests on small hosts. + ### jitv2 compile order - Under jitv2, code that turns hot while the compile workers are behind is diff --git a/clanker/INDEX.md b/clanker/INDEX.md index 52f828630..46deed039 100644 --- a/clanker/INDEX.md +++ b/clanker/INDEX.md @@ -85,6 +85,7 @@ The MIPS JIT (`src/cpu/jitv2/`): design, Cranelift codegen, delay slots, invalid | [dirty-cache-page-probe.md](jitv2/dirty-cache-page-probe.md) | history | jitv2: the dirty-cache blind spot, and the probe that closes it | | [dispatch-gate-shared-writes.md](jitv2/dispatch-gate-shared-writes.md) | rule | The dispatch gate must not write shared per-page state on every arrival: five atomic RMWs per arrival ping-ponged with the compile worker; test-then-set, count per CPU, reuse the gate's translation | | [emit_absolute_pc_exit-in_delay_slot-followup.md](jitv2/emit_absolute_pc_exit-in_delay_slot-followup.md) | open | Follow-up: `emit_absolute_pc_exit` should own its own `in_delay_slot=false` clear | +| [per-cpu-page-generation.md](jitv2/per-cpu-page-generation.md) | design | Per-CPU page generation slots (16/page): a store bumps only its CPU's slot (no shared RMW); a compile reads the max of all slots; SMP-safe | | [entry-word-bail-must-not-touch-pc-or-bd.md](jitv2/entry-word-bail-must-not-touch-pc-or-bd.md) | rule | An entry-word bail must not touch `pc` or `in_delay_slot` | | [flush-preserved-entry-point-inflation.md](jitv2/flush-preserved-entry-point-inflation.md) | rule | Flush-preserved pages inherited the previous program's entry points | | [fpu-flags-are-computed-not-read.md](jitv2/fpu-flags-are-computed-not-read.md) | rule | FPU exception flags are computed from bit patterns, never read from the host | diff --git a/clanker/jitv2/per-cpu-page-generation.md b/clanker/jitv2/per-cpu-page-generation.md new file mode 100644 index 000000000..60251a463 --- /dev/null +++ b/clanker/jitv2/per-cpu-page-generation.md @@ -0,0 +1,73 @@ +# per-CPU page generation counters remove the per-store shared RMW + +**Status:** implemented, awaiting guest measurement. 2026-11-30. + +## Symptom + +A jitv2 build with no code compiling was ~10% slower than a `tcache` build +without jitv2. The tax was `PpMemory::bump_gen` / `Memory::bump_gen` / +`tc_bump_gen` / `mips_cache_shadow::bump_gen` / the JIT inline store bump: +`gen[phys >> 12].fetch_add(1, Release)` on a **shared** `AtomicU64` for every +guest store, on all four vCPUs plus the compile workers touching the same +cache lines. + +## Rule / design + +- Each 4KB page gets **`GEN_SLOTS = 16` counters**: slot 0 is the **external** + counter (bus writes with no guest CPU: DMA, devices, monitor), slots 1..=8 + are **per guest CPU** (`MAX_CPUS = 8`). +- **A store from a CPU thread bumps only its own slot**, with a plain + `load(Relaxed) + store(Release)` — one writer, so **no atomic RMW** and no + shared-line ping-pong. Device/DMA writes keep `fetch_add(Release)` on slot 0. +- `PhysicalCodePage::current_gen()` reads **all** `gen_slots` counters with + `Acquire` and returns their **max**. Any CPU's write, or a device's, is + therefore observed before a snapshot publishes — SMP-correct. The Acquire + pairs with the store's Release so the compile sees the preceding bytes. +- `CodePage::gen_slots` says how many counters follow `gen`: 16 from + `CodeBank::page` (RAM), 1 from `CodeKey::flat_page` / a device with no bank + (ROM/MMIO). `PhysicalCodePage::gen_slots` bounds the read so a single + device counter is never read out of bounds. `NEVER_COMPILABLE_GEN` is an + array of 16 counters. +- `bump_gen_all()` (snapshot restore / power-on) bumps **every** slot of every + page, so all CPUs see the invalidation. +- ppMem layout: `GEN_RATIO = 4096 / 16 / 8 = 32` bytes of gen window per 32 + bytes of guest RAM, so `GEN_WINDOW_SIZE = 128 MB`. The counter *index* for + physical `p` is `(p >> 12) * GEN_SLOTS` (pointer `.add()` multiplies by 8). + All window mapping/scrub/mark sites are scaled accordingly. +- The JIT inline store now loads `MipsCore::cpu_id`, computes + `(phys >> 12) << GEN_SHIFT | (cpu + 1)`, and does a plain store; `atomic_gen` + is no longer used for the generation bump (`emit_sync` still uses it). + +## Why it is safe on SMP + +The per-CPU slots are single-writer (one guest CPU thread per `cpu_id`), so +there is no data race; the cross-thread visibility the JIT needs is supplied +by Release-store / Acquire-load. `current_gen()`'s max means a write by CPU 3 +is seen by a compile triggered on CPU 0. Device writes on external slot 0 are +also included. No per-page generation counter is reset by a CPU store. + +## Caveats / gotchas + +- `current_gen()` now issues up to **16 relaxed/Acquire loads** on any dispatch + that asks `is_runnable()` (each compiled-page arrival). This is a new cost + that must be measured against the removed atomic RMW on stores. Store-heavy + guests should win; dispatch-heavy ones may lose. If needed, reduce slots to + `MAX_CPUS + 1 = 9` (keeping a power-of-two window by padding to 16 but + reading only 9). +- `GEN_RATIO` changed from 512 to 32: **do not** revert it without reverting + all window mapping/scrub/mark scalings and the ppMem tests + (`gen_window_sizing`). +- `gen_ptr()` returns slot 0 (external). A device's `code_page()` with one + never-bumped counter sets `gen_slots = 1`; `current_gen()` then reads only + that counter. +- `PpMemory::bump_gen_cpu` is currently unused: CPU stores reach the slots + through the gen window pointer (`tc_gen`) already published into the cache + and into `MipsCore::jit_tc_gen`. Do not add a duplicate bump. + +## Verification + +- `cargo check -p iris --features jitv2` clean; also with + `rex-jit,gr4-jit,gr2-jit,wgpu,gputrace`. +- `cargo test -p iris --lib --features jitv2 ppmem::` — 51 passed. +- `cargo test -p iris --lib --features jitv2 jitv2::` — 523 passed. +- Not measured on a guest yet (the user's Tezro / impact profile). diff --git a/src/cpu/jitv2/codegen.rs b/src/cpu/jitv2/codegen.rs index 5434c9990..50b2726bf 100644 --- a/src/cpu/jitv2/codegen.rs +++ b/src/cpu/jitv2/codegen.rs @@ -5103,27 +5103,29 @@ fn emit_mem_write_fast(ctx: &mut EmitCtx, value: Value, size: MemSize, path: &In let gen_base = ctx.builder.ins().load(ptr_ty, mem, ctx.core_ptr, ir::immediates::Offset32::new(core_offset_of_jit_tc_gen())); let page = ctx.builder.ins().ushr_imm_s(path.fast_phys, 12); - let off = ctx.builder.ins().imul_imm_s(page, 8); + // Per-CPU slots: `GEN_SLOTS` counters per page, cpu `n` at slot `n`. + // Only this CPU's thread writes its slot, so the store is a plain + // load+add+store — no shared atomic RMW on every guest store, which + // was the jitv2 tax and ping-ponged between CPUs and compile workers. + let cpu = ctx.builder.ins().load(ir::types::I8, mem, ctx.core_ptr, + ir::immediates::Offset32::new(std::mem::offset_of!(MipsCore, cpu_id) as i32)); + let cpu = ctx.builder.ins().uextend(ir::types::I64, cpu); + let group = ctx.builder.ins().ishl_imm_s(page, crate::ppmem::GEN_SHIFT as i64); + let cpu_slot = ctx.builder.ins().iadd_imm_s(cpu, 1); + let slot = ctx.builder.ins().iadd(group, cpu_slot); + let off = ctx.builder.ins().imul_imm_s(slot, 8); let gp = ctx.builder.ins().iadd(gen_base, off); - if ctx.dc_geometry.atomic_gen { - let one = ctx.builder.ins().iconst(ir::types::I64, 1); - ctx.builder.ins().atomic_rmw(ir::types::I64, mem, ir::AtomicRmwOp::Add, gp, one); + let cur = ctx.builder.ins().load(ir::types::I64, mem, gp, + ir::immediates::Offset32::new(0)); + let inc = ctx.builder.ins().iadd_imm_s(cur, 1); + // Release, after the bytes: a compile snapshot reading the slot with + // Acquire sees them too. On x86_64 a plain store is already Release; + // on a weakly ordered host it is `stlr`. No `atomic_rmw`: the slot is + // single-writer, and an RMW would put the shared-line ping-pong back. + if cfg!(target_arch = "x86_64") { + ctx.builder.ins().store(mem, inc, gp, ir::immediates::Offset32::new(0)); } else { - let cur = ctx.builder.ins().load(ir::types::I64, mem, gp, - ir::immediates::Offset32::new(0)); - let inc = ctx.builder.ins().iadd_imm_s(cur, 1); - // Release, after the bytes: a compile snapshot that sees the new - // generation sees them too, as the Rust side's release bump - // (`tc_bump_gen`) gives. On x86_64 a plain store is that already - // (stores are not reordered with earlier stores), and Cranelift's - // `atomic_store` would add an `mfence` to every guest store; on - // a weakly ordered host it is `stlr`. The atomic add above is - // sequentially consistent already. - if cfg!(target_arch = "x86_64") { - ctx.builder.ins().store(mem, inc, gp, ir::immediates::Offset32::new(0)); - } else { - ctx.builder.ins().atomic_store(mem, inc, gp); - } + ctx.builder.ins().atomic_store(mem, inc, gp); } // tc_invalidate_l2_code: writing the line makes L2's decoded diff --git a/src/cpu/jitv2/jitv2.rs b/src/cpu/jitv2/jitv2.rs index 48bd05c21..f0e436534 100644 --- a/src/cpu/jitv2/jitv2.rs +++ b/src/cpu/jitv2/jitv2.rs @@ -973,7 +973,8 @@ impl JitStats { /// somehow executes out of true MMIO, this makes the JIT treat it like an /// immutable ROM page instead — the JIT is not in the business of making /// that scenario correct or fast, just of not crashing on it. -static NEVER_COMPILABLE_GEN: AtomicU64 = AtomicU64::new(0); +static NEVER_COMPILABLE_GEN: [AtomicU64; crate::ppmem::GEN_SLOTS] = + [const { AtomicU64::new(0) }; crate::ppmem::GEN_SLOTS]; /// Per-physical-page code cache metadata (§13.1 — one compiled function per /// page, internal dispatch by entry offset, superseding the old one-function- @@ -1007,6 +1008,10 @@ pub struct PhysicalCodePage { /// returns null) gets pointed at the shared [`NEVER_COMPILABLE_GEN`] /// fallback instead, by `claim()`. gen: *const AtomicU64, + /// How many counters follow `gen` (RAM: `GEN_SLOTS`, ROM/MMIO: 1). + /// Bounds `current_gen()`'s max over the per-CPU slots. + #[cfg(feature = "jitv2")] + gen_slots: u8, /// Offsets some dispatch has asked for an entry point at (§13.2) — a /// superset of `compiled` in general (a bit can be requested long before /// any compile picks it up, and stays requested across however many @@ -1571,7 +1576,8 @@ impl PhysicalCodePage { addr: std::array::from_fn(|cpu| AtomicU32::new(if claimed && cpu == 0 { pfn << 1 } else { NO_ADDR })), words: std::ptr::null(), next: NO_SLOT, - gen: if gen.is_null() { &NEVER_COMPILABLE_GEN } else { gen }, + gen: if gen.is_null() { NEVER_COMPILABLE_GEN.as_ptr() } else { gen }, + gen_slots: 1, requested: new_bitmap(), denied: new_bitmap_all_set(), compiled: new_bitmap(), @@ -1709,17 +1715,19 @@ impl PhysicalCodePage { /// [`Self::claim`] for the page a bus answered with. pub fn claim_code(&mut self, code: crate::traits::CodePage, fr1: bool) { self.claim(code.key, code.gen, fr1); + self.gen_slots = code.gen_slots; self.words = code.words; } pub fn claim(&mut self, key: CodeKey, gen: *const AtomicU64, fr1: bool) { - debug_assert!(std::ptr::eq(self.gen, &NEVER_COMPILABLE_GEN) && !self.is_claimed(), + debug_assert!(std::ptr::eq(self.gen, NEVER_COMPILABLE_GEN.as_ptr()) && !self.is_claimed(), "claim() called on a slot that wasn't clean (key={:?}) — every path that reuses a slot must reset it first (see reset_to_unclaimed)", self.key); debug_assert!(!self.has_code(), "claim() called on a slot with a still-published function — mega_flush must reset_to_unclaimed before this slot can be reused"); self.key = key; - self.gen = if gen.is_null() { &NEVER_COMPILABLE_GEN } else { gen }; + self.gen = if gen.is_null() { NEVER_COMPILABLE_GEN.as_ptr() } else { gen }; + self.gen_slots = 1; self.fr1.store(fr1, Ordering::Relaxed); // A freshly-claimed slot has no bail outstanding: `fr1` was just set // from the live mode, so there is nothing to correct. @@ -1802,7 +1810,7 @@ impl PhysicalCodePage { for a in &self.addr { a.store(NO_ADDR, Ordering::Relaxed); } - self.gen = &NEVER_COMPILABLE_GEN; + self.gen = NEVER_COMPILABLE_GEN.as_ptr(); } /// Reset `requested`/`denied`/`compiled` bitmaps, the compiled `func` @@ -1825,9 +1833,19 @@ impl PhysicalCodePage { /// branch needed on the caller's part. #[inline] pub fn current_gen(&self) -> u64 { - // Relaxed: publish-time (§13.3) and mutation-time (§7) orderings are - // established by the fetch_or/re-read pair at those call sites, not here. - unsafe { (*self.gen).load(Ordering::Relaxed) } + // Per-CPU slots: a CPU store bumps only its own slot with a plain + // Release store; device/DMA writes bump the external slot. The page's + // generation is the maximum of all of them, so a write by any CPU is + // observed before code is published. `Acquire` pairs with that + // Release, making the preceding data bytes visible to the compile + // snapshot (§7/§13.3). `NEVER_COMPILABLE_GEN` is one shared counter, + // so reading it repeatedly just returns the same value. + let mut gen = 0u64; + for slot in 0..self.gen_slots as usize { + let g = unsafe { (*self.gen.add(slot)).load(Ordering::Acquire) }; + gen = gen.max(g); + } + gen } /// Relaxed read of `entry_gen` — the generation `func`/`compiled` were @@ -3245,6 +3263,7 @@ impl Jitv2 { key: CodeKey::at_address(at.space, at.pfn, uncached), gen: bus.gen_ptr(addr), words: std::ptr::null(), + gen_slots: 1, // no bank answered: a single device counter }); let slot = match self.by_key.get(&code.key) { Some(&slot) => slot, diff --git a/src/cpu/mips_cache_shadow.rs b/src/cpu/mips_cache_shadow.rs index a51aa1708..8e2e0ef8f 100644 --- a/src/cpu/mips_cache_shadow.rs +++ b/src/cpu/mips_cache_shadow.rs @@ -242,6 +242,9 @@ pub struct ShadowCache< tc_key: AtomicU64, #[cfg(feature = "jitv2")] tc_gen: UnsafeCell<*mut std::sync::atomic::AtomicU64>, + /// Which guest CPU owns this cache; its own gen slot is bumped on stores. + #[cfg(feature = "jitv2")] + jit_cpu_id: UnsafeCell, /// Decoded instructions, by physical page. Never touches the shadow /// arrays above — see `decode_cache`. decode: UnsafeCell, @@ -319,6 +322,8 @@ impl< tc_key: AtomicU64::new(0), #[cfg(feature = "jitv2")] tc_gen: UnsafeCell::new(std::ptr::null_mut()), + #[cfg(feature = "jitv2")] + jit_cpu_id: UnsafeCell::new(0), decode: UnsafeCell::new(crate::cpu::decode_cache::DecodeCache::new()), view_space: UnsafeCell::new(std::ptr::null()), view: UnsafeCell::new(0), @@ -361,8 +366,16 @@ impl< { let g = unsafe { *self.tc_gen.get() }; if !g.is_null() { - // Release, after the bytes (`PpMemory::bump_gen`). - unsafe { (*g.add((_phys >> 12) as usize)).fetch_add(1, std::sync::atomic::Ordering::Release) }; + let slot = ((_phys >> 12) as usize) << crate::ppmem::GEN_SHIFT + | (*unsafe { &*self.jit_cpu_id.get() }) as usize + 1; + // Single-writer slot: a plain Release store, not a shared + // atomic RMW on every guest store. `current_gen()` reads the + // max across all CPUs' slots. + unsafe { + let c = g.add(slot); + (*c).store((*c).load(std::sync::atomic::Ordering::Relaxed).wrapping_add(1), + std::sync::atomic::Ordering::Release); + } } } } @@ -943,6 +956,11 @@ impl< unsafe { *self.tc_gen.get() = gen_base }; } + #[cfg(feature = "jitv2")] + fn set_jit_cpu_id(&self, cpu: u8) { + unsafe { *self.jit_cpu_id.get() = cpu }; + } + /// Under tcache, a tagless geometry: the inline path is the window alone. /// Declined until both windows are published, as `CpuCache` does, so the /// emitted code can assume them. Without tcache there is no inline path: diff --git a/src/cpu/mips_cache_v2.rs b/src/cpu/mips_cache_v2.rs index df92899a4..5a4381e73 100644 --- a/src/cpu/mips_cache_v2.rs +++ b/src/cpu/mips_cache_v2.rs @@ -816,6 +816,11 @@ pub trait MipsCache: Send + Sync { #[cfg(feature = "jitv2")] unsafe fn set_tcache_gen_window(&self, _gen_base: *mut AtomicU64) {} + /// JIT v2: which guest CPU owns this cache, for the per-CPU generation + /// slot a store bumps. Default no-op for caches without an inline store. + #[cfg(feature = "jitv2")] + fn set_jit_cpu_id(&self, _cpu: u8) {} + /// L1/L2 geometry, so CP0 Config reports this model rather than a build-time constant. const IC_SIZE: usize; const IC_LINE: usize; @@ -1494,6 +1499,9 @@ pub struct CpuCache< /// the guest just modified. #[cfg(feature = "jitv2")] tc_gen: UnsafeCell<*mut AtomicU64>, + /// Which guest CPU owns this cache; its own gen slot is bumped on stores. + #[cfg(feature = "jitv2")] + jit_cpu_id: UnsafeCell, } unsafe impl> 12) as usize; - // Release, after the bytes (`PpMemory::bump_gen`). - unsafe { (*g.add(page)).fetch_add(1, Ordering::Release) }; + let slot = ((_phys_addr >> 12) as usize) << crate::ppmem::GEN_SHIFT + | (*unsafe { &*self.jit_cpu_id.get() }) as usize + 1; + // Only this CPU's thread stores its slot: a plain Release + // store, not the shared `fetch_add` tax. `current_gen()` + // takes the max over all CPUs' slots. + unsafe { + let c = g.add(slot); + (*c).store((*c).load(Ordering::Relaxed).wrapping_add(1), Ordering::Release); + } } } } @@ -3605,6 +3621,11 @@ impl MipsExecutor { /// so any path already re-running that is covered. #[cfg(feature = "jitv2")] pub fn install_jit_mem_ptrs(&mut self) { + // The cache's inline/interpreter store path bumps this CPU's own gen + // slot (single-writer, no shared atomic RMW). + self.cache.set_jit_cpu_id(self.core.cpu_id); let mut geom = self.cache.jit_dc_geometry(); geom.atomic_gen = self.core.smp || std::env::var_os("IRIS_JIT_ATOMIC_GEN").is_some(); // Publish for the async compile workers, which own their Codegens by diff --git a/src/dev/mem.rs b/src/dev/mem.rs index 0a65da80c..723511939 100644 --- a/src/dev/mem.rs +++ b/src/dev/mem.rs @@ -5,6 +5,8 @@ use std::sync::Arc; use std::sync::atomic::Ordering; #[cfg(all(test, feature = "jitv2"))] use std::sync::atomic::AtomicU64; +#[cfg(all(test, feature = "jitv2"))] +use crate::ppmem::GEN_SLOTS; use crate::traits::{BusRead8, BusRead16, BusRead32, BusRead64, BusDevice, BUS_OK, BUS_ERR}; #[cfg(test)] use crate::traits::Resettable; @@ -65,34 +67,41 @@ impl Memory { size_words, addr_mask: (size_bytes - 1) as u64, #[cfg(feature = "jitv2")] - gen: (0..size_bytes.div_ceil(JITV2_PAGE_SIZE)).map(|_| AtomicU64::new(0)).collect(), + gen: (0..size_bytes.div_ceil(JITV2_PAGE_SIZE) * GEN_SLOTS).map(|_| AtomicU64::new(0)).collect(), #[cfg(feature = "jitv2")] code_bank: crate::traits::CodeBank::new(), } } - /// JIT v2: bump the generation counter for the page containing `addr` (post-mask). - /// Must be called on every mutating access so a compiled artifact can detect - /// staleness (clanker/jitv2/jit-v2-design.md §7 — "gen bumps ride on the RAM write"). + /// JIT v2: bump the external-slot generation counter for the page + /// containing `addr` (post-mask). Used by writes that have no guest CPU. #[cfg(feature = "jitv2")] #[inline(always)] fn bump_gen(&self, addr: u64) { let page = ((addr & self.addr_mask) as usize) / JITV2_PAGE_SIZE; // Release, after the bytes: a compile snapshot that sees this generation sees // them too (`comp::snapshot_page`). The publish-side re-check (§6.5) cannot - // stand in for it: a snapshot that already paired this generation with older - // bytes finds the same generation there and publishes them. - self.gen[page].fetch_add(1, Ordering::Release); + // stand in for it. + self.gen[page * GEN_SLOTS + crate::ppmem::GEN_EXTERNAL_SLOT].fetch_add(1, Ordering::Release); + } + + /// JIT v2: bump `cpu`'s own slot for the page containing `addr`. Only that + /// CPU's thread writes the slot, so a plain load+store replaces the + /// per-store shared atomic RMW; `Release` publishes the data store. + #[cfg(feature = "jitv2")] + #[inline(always)] + fn bump_gen_cpu(&self, addr: u64, cpu: usize) { + let page = ((addr & self.addr_mask) as usize) / JITV2_PAGE_SIZE; + let g = &self.gen[page * GEN_SLOTS + (cpu % GEN_SLOTS)]; + g.store(g.load(Ordering::Relaxed).wrapping_add(1), Ordering::Release); } - /// JIT v2: raw pointer to the generation counter for the page containing `addr`. - /// Used to populate `PhysicalCodePage::gen` (see src/cpu/jitv2/jitv2.rs). The pointer - /// is valid for the lifetime of `&self` (the `gen` vec is never resized after `new`). + /// JIT v2: pointer to the first of `GEN_SLOTS` counters for `addr`'s page. #[cfg(feature = "jitv2")] #[inline] pub fn gen_ptr(&self, addr: u64) -> *const AtomicU64 { let page = ((addr & self.addr_mask) as usize) / JITV2_PAGE_SIZE; - &self.gen[page] as *const AtomicU64 + &self.gen[page * GEN_SLOTS] as *const AtomicU64 } /// Set a new address mask. The provided mask is AND-ed with `mem_size_bytes-1` diff --git a/src/ppmem/mod.rs b/src/ppmem/mod.rs index 1ca4b4443..fc0e1998b 100644 --- a/src/ppmem/mod.rs +++ b/src/ppmem/mod.rs @@ -18,3 +18,5 @@ pub mod ppmem; pub use map::{align_up, granularity, is_aligned, AddrSpace, Prot, SharedMem}; pub use devmap::SparseDeviceMap; pub use ppmem::{bitmap_maps, bitmap_maps_at, map_granule, window_shift, MappedMemory, FINE_SHIFT, PpMemSpace, PpMemory, BITMAP_SHIFT, LARGE_WINDOW_SIZE, WINDOW_SIZE}; +#[cfg(feature = "jitv2")] +pub use ppmem::{GEN_EXTERNAL_SLOT, GEN_RATIO, GEN_SHIFT, GEN_SLOTS, GEN_WINDOW_SIZE}; diff --git a/src/ppmem/ppmem.rs b/src/ppmem/ppmem.rs index bb97f5a21..fb3a68718 100644 --- a/src/ppmem/ppmem.rs +++ b/src/ppmem/ppmem.rs @@ -79,13 +79,33 @@ pub fn bitmap_maps_at(bitmap: u64, shift: u32, phys: u64) -> bool { region < 64 && bitmap & (1u64 << region) != 0 } -/// Bytes of RAM per generation counter: one `AtomicU64` per 4KB page. +/// Generation counters per 4KB page: one per guest CPU plus one for writes +/// that do not come from a CPU (DMA, devices, the monitor). /// -/// `4096 / 8 == 512`, so a region's gen block is always its data size >> 9 and -/// sits at its data offset >> 9 — which is what keeps `gen_ptr` a pure shift -/// off the physical address. +/// A store from a CPU thread bumps **only its own slot**, with a plain +/// (non-RMW) store — the shared `fetch_add(1, Release)` on every guest store +/// was a measurable jitv2 tax and ping-ponged the cache line between CPUs and +/// compile workers. A compile reads the **maximum** of all slots, so a write +/// by any CPU (or a device) is always observed before code is published. +/// `MAX_CPUS` is 8, so 16 slots keeps `GEN_RATIO` a power of two and the gen +/// window a pure shift off `phys`. #[cfg(feature = "jitv2")] -pub const GEN_RATIO: u64 = (JITV2_PAGE_SIZE as u64) / 8; +pub const GEN_SLOTS: usize = 16; +#[cfg(feature = "jitv2")] +pub const GEN_SHIFT: u32 = 4; +/// Slot used by writes with no guest CPU (DMA, device, monitor). CPU `n` +/// uses slot `n` (`0..MAX_CPUS`). +#[cfg(feature = "jitv2")] +pub const GEN_EXTERNAL_SLOT: usize = 0; + +/// Bytes of RAM per generation-counter *group* (one group = `GEN_SLOTS` +/// counters for a 4KB page). +/// +/// `4096 / 16 == 256`, so a region's gen block is its data size >> 8 and sits +/// at its data offset >> 8 — which keeps both `gen_ptr` and the window's +/// `gen_window_base + (phys >> 12)` a pure shift off `phys`. +#[cfg(feature = "jitv2")] +pub const GEN_RATIO: u64 = (JITV2_PAGE_SIZE as u64) / (GEN_SLOTS as u64) / 8; /// Size of the generation window: one `AtomicU64` per 4KB page of the 4GB /// physical space = 8MB. A larger window scales with it. @@ -138,7 +158,7 @@ pub trait MappedMemory { fn window_base(&self) -> *mut u8; /// Base of the generation window. The counter for guest physical `p` is at - /// `gen_window_base() + (p >> 12)` — a pure shift off the physical + /// `gen_window_base() + (p >> 12) * GEN_SLOTS` — a pure shift off the physical /// address, no bank lookup, no masking, because banks' gen objects are /// mapped here in lockstep with their data. /// @@ -325,35 +345,55 @@ impl PpMemory { &self.gen_mem } - /// Number of generation counters this bank has (one per 4KB page). + /// Number of 4KB pages this bank has. #[cfg(feature = "jitv2")] #[inline(always)] - fn gen_count(&self) -> usize { + fn gen_pages(&self) -> usize { self.size_bytes / JITV2_PAGE_SIZE } - /// JIT v2: bump the generation counter for the page containing `addr`. + /// Number of generation counters this bank has (`GEN_SLOTS` per page). + #[cfg(feature = "jitv2")] + #[inline(always)] + fn gen_count(&self) -> usize { + self.gen_pages() * GEN_SLOTS + } + + /// JIT v2: bump the generation counter for the page containing `addr` + /// for a write with **no guest CPU** (DMA, device, monitor). Uses the + /// shared external slot; CPU stores use [`Self::bump_gen_cpu`] instead. #[cfg(feature = "jitv2")] #[inline(always)] fn bump_gen(&self, addr: u64) { let page = self.off(addr) / JITV2_PAGE_SIZE; // Release, after the bytes, for the same reason `Memory::bump_gen` is: a // compile snapshot that sees the new generation must see them too. - unsafe { (*self.gen_base.add(page)).fetch_add(1, Ordering::Release) }; + unsafe { (*self.gen_base.add(page * GEN_SLOTS + GEN_EXTERNAL_SLOT)).fetch_add(1, Ordering::Release) }; } - /// JIT v2: raw pointer to the generation counter for `addr`'s page. - /// - /// Valid for the lifetime of `&self`. Note the window offers the same - /// counter at `gen_window_base + (phys >> 12) * 8` — the two resolve to the - /// same physical memory whenever this bank is mapped, because - /// [`PpMemSpace::map_bank`] maps data and gen from these same two objects - /// in lockstep. + /// JIT v2: bump `cpu`'s own generation counter for the page containing + /// `addr`. Only the CPU's own thread ever writes this slot, so a plain + /// load+store replaces the per-store atomic RMW. `Release` publishes the + /// preceding data store to a compile that reads the slot with `Acquire`. + #[cfg(feature = "jitv2")] + #[inline(always)] + fn bump_gen_cpu(&self, addr: u64, cpu: usize) { + let page = self.off(addr) / JITV2_PAGE_SIZE; + unsafe { + let g = self.gen_base.add(page * GEN_SLOTS + 1 + (cpu % (GEN_SLOTS - 1))); + (*g).store((*g).load(Ordering::Relaxed).wrapping_add(1), Ordering::Release); + } + } + + /// JIT v2: pointer to the **first** of `GEN_SLOTS` counters for `addr`'s + /// page (slot 0). A `PhysicalCodePage` reads all slots from here via + /// [`crate::cpu::jitv2::jitv2::PhysicalCodePage::current_gen`]. The window + /// the window offers the group at `gen_window_base + (phys >> 12) * GEN_SLOTS`. #[cfg(feature = "jitv2")] #[inline] pub fn gen_ptr(&self, addr: u64) -> *const AtomicU64 { let page = self.off(addr) / JITV2_PAGE_SIZE; - unsafe { self.gen_base.add(page) as *const AtomicU64 } + unsafe { self.gen_base.add(page * GEN_SLOTS) as *const AtomicU64 } } #[cfg(feature = "jitv2")] @@ -518,7 +558,7 @@ impl BusDevice for PpMemory { let end = self.off(last) / JITV2_PAGE_SIZE; // Release, after the bytes (`bump_gen`). let bump = |page: usize| unsafe { - (*self.gen_base.add(page)).fetch_add(1, Ordering::Release); + (*self.gen_base.add(page * GEN_SLOTS + GEN_EXTERNAL_SLOT)).fetch_add(1, Ordering::Release); }; if end >= start { for page in start..=end { @@ -526,7 +566,7 @@ impl BusDevice for PpMemory { } } else { // Wrapped around the mask: bump the two remaining spans. - for page in start..self.gen_count() { + for page in start..self.gen_pages() { bump(page); } for page in 0..=end { @@ -699,7 +739,7 @@ pub struct PpMemSpace { /// /// Mapped in lockstep with `space` — see [`PpMemSpace::map_bank`] — so a /// mirrored data page and its counter are the same physical memory. That - /// makes `gen_ptr(phys) == gen_window_base + (phys >> 12) * 8` a pure + /// makes `gen_ptr(phys) == gen_window_base + (phys >> 12) * GEN_SLOTS` a pure /// function of the physical address, with no bank lookup and no masking. #[cfg(feature = "jitv2")] gen_space: AddrSpace, @@ -1313,7 +1353,7 @@ impl PpMemSpace { let d = if on { GEN_HELD } else { 1u64.wrapping_sub(GEN_HELD) }; let gens = self.gen_space.base() as *const AtomicU64; for a in (page..end).step_by(PAGE_SIZE as usize) { - unsafe { (*gens.add((a / PAGE_SIZE as u64) as usize)).fetch_add(d, Ordering::Release) }; + unsafe { (*gens.add((a / PAGE_SIZE as u64) as usize * GEN_SLOTS)).fetch_add(d, Ordering::Release) }; } } } @@ -1550,7 +1590,7 @@ impl MappedMemory for PpMemSpace { // the same counters". That holds for DATA — one object, two views of // the same mmap — but **not** for the generation window, which is a // separate parallel mapping addressed by a pure shift - // (`gen_window_base() + (p >> 12)`, no bank lookup, no masking). Two + // (`gen_window_base() + (p >> 12) * GEN_SLOTS`, no bank lookup, no masking). Two // addresses aliasing one page therefore index two *different* counters // unless the alias's gen range is explicitly mapped onto the same gen // object. @@ -1816,7 +1856,7 @@ mod tests { let base = 0x0800_0000u64; space.map_bank(0, base, 8 * MB as u64, 8 * MB as u64).unwrap(); let data = unsafe { space.window_base().add(base as usize + 0x100) as *const u32 }; - let gen = unsafe { space.gen_window_base().add((base as usize + 0x100) >> 12) }; + let gen = unsafe { space.gen_window_base().add(((base as usize + 0x100) >> 12) * GEN_SLOTS) }; unsafe { *(data as *mut u32) = 0xFEED_FACE; (*gen).fetch_add(7, std::sync::atomic::Ordering::Relaxed); @@ -2013,12 +2053,12 @@ mod tests { /// The low-512KB alias and LOMEM must resolve to the SAME generation /// counter — they are the same physical pages. /// - /// `gen_window_base() + (p >> 12)` is documented as "a pure shift off the + /// `gen_window_base() + (p >> 12) * GEN_SLOTS` is documented as "a pure shift off the /// physical address, no bank lookup, no masking", which means two addresses /// aliasing one page index *different* counters unless the alias's gen /// range is explicitly mapped onto the same object. `map_alias` only does /// that when the gen range meets host granularity, and the low-512KB alias - /// needs just 1KB of counters (512KB / GEN_RATIO = 1024 B < 4096), so the + /// needs 16KB of counters (512KB / GEN_RATIO = 16KB, now a whole granule), so the /// mapping is skipped — the code says so itself, calling it "harmless, /// since an alias is by definition the same physical pages ... hence the /// same counters". That reasoning holds for DATA (one mmap, two views) but @@ -2054,7 +2094,7 @@ mod tests { // addresses legitimately differ while their contents must not. let genbase = space.gen_window_base(); let alias_ctr = unsafe { &*genbase.add(0) }; - let lomem_ctr = unsafe { &*genbase.add(0x0800_0000 >> 12) }; + let lomem_ctr = unsafe { &*genbase.add((0x0800_0000 >> 12) as usize * GEN_SLOTS) }; let a0 = alias_ctr.load(Ordering::Relaxed); let l0 = lomem_ctr.load(Ordering::Relaxed); @@ -2139,7 +2179,7 @@ mod tests { space.map_bank(0, base, 128 * MB as u64, 32 * MB as u64).unwrap(); let gw = space.gen_window_base(); - let counter = |phys: u64| unsafe { &*gw.add((phys >> 12) as usize) }; + let counter = |phys: u64| unsafe { &*gw.add(((phys >> 12) as usize) * GEN_SLOTS) }; // Bump the counter for the first page through mirror 0, and observe it // through every other mirror. @@ -2211,9 +2251,9 @@ mod tests { space.map_bank(0, 0x0800_0000, 8 * MB as u64, 8 * MB as u64).unwrap(); let gw = space.gen_window_base(); for phys in [0x0800_0000u64, 0x0800_1000, 0x0840_0000, 0x087F_F000] { - let expect = unsafe { gw.add((phys >> 12) as usize) }; - let got = unsafe { (gw as *mut u8).add((phys >> 12) as usize * 8) } as *mut AtomicU64; - assert_eq!(expect, got, "gen offset is not (phys >> 12) * 8 at {phys:#x}"); + let expect = unsafe { gw.add(((phys >> 12) as usize) * GEN_SLOTS) }; + let got = unsafe { (gw as *mut u8).add(((phys >> 12) as usize) * GEN_SLOTS * 8) } as *mut AtomicU64; + assert_eq!(expect, got, "gen offset is not (phys >> 12) * GEN_SLOTS * 8 at {phys:#x}"); } } @@ -2221,13 +2261,13 @@ mod tests { #[cfg(feature = "jitv2")] #[test] fn gen_window_sizing() { - assert_eq!(GEN_RATIO, 512, "4096 bytes per page / 8 bytes per counter"); - assert_eq!(GEN_WINDOW_SIZE, 8 * 1024 * 1024, "4GB / 512 = 8MB"); + assert_eq!(GEN_RATIO, 32, "4096 bytes per page / 16 counters / 8 bytes"); + assert_eq!(GEN_WINDOW_SIZE, 128 * 1024 * 1024, "4GB / 32 = 128MB"); // The smallest supported bank must still produce a whole number of // host-granularity-sized gen blocks. let min_bank = 8 * MB; let gen_bytes = min_bank / GEN_RATIO as usize; - assert_eq!(gen_bytes, 16 * 1024, "8MB bank => 16KB of counters"); + assert_eq!(gen_bytes, 256 * 1024, "8MB bank => 256KB of counters (16 per page)"); } // ---- cached views ---- @@ -2361,7 +2401,7 @@ mod tests { space.map_bank(0, 0, 64 * MB as u64, 64 * MB as u64).unwrap(); let ((a, _fa), (b, _fb)) = (view_of(&space), view_of(&space)); let gen = |g: *const AtomicU64| unsafe { (*g).load(Ordering::Relaxed) }; - let at = || unsafe { space.gen_window_base().add(0x2000 >> 12) as *const AtomicU64 }; + let at = || unsafe { space.gen_window_base().add((0x2000 >> 12) as usize * GEN_SLOTS) as *const AtomicU64 }; space.hold_line_page(a, 0x2000); space.hold_line_page(b, 0x2040); assert_eq!(gen(at()) / GEN_HELD, 2, "a mark for each CPU"); @@ -2402,7 +2442,7 @@ mod tests { let (space, _banks) = PpMemSpace::with_bank_sizes(&[64]).unwrap(); space.allow_unbacked_lines(0, 64 * MB as u64); let ((a, _fa), (b, _fb)) = (view_of(&space), view_of(&space)); - let gen = || unsafe { (*(space.gen_window_base().add(0x10_0000 >> 12) as *const AtomicU64)).load(Ordering::Relaxed) }; + let gen = || unsafe { (*(space.gen_window_base().add((0x10_0000 >> 12) as usize * GEN_SLOTS) as *const AtomicU64)).load(Ordering::Relaxed) }; assert_eq!(space.hold_line_page(a, 0x10_0000), Some(true)); assert_eq!(space.hold_line_page(b, 0x10_0040), Some(true)); assert_eq!(gen() / GEN_HELD, 0, "no memory, no mark"); diff --git a/src/traits.rs b/src/traits.rs index b0432c589..5bcada6cd 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -98,7 +98,7 @@ impl CodeKey { /// [`Self::flat`] as a bus answers it, counted by `gen`. pub const fn flat_page(addr: u64, gen: *const std::sync::atomic::AtomicU64) -> CodePage { - CodePage { key: Self::flat(addr), gen, words: std::ptr::null() } + CodePage { key: Self::flat(addr), gen, words: std::ptr::null(), gen_slots: 1 } } } @@ -111,6 +111,13 @@ impl CodeKey { pub struct CodePage { pub key: CodeKey, pub gen: *const std::sync::atomic::AtomicU64, + /// How many generation counters follow `gen` for this page. RAM banks + /// publish [`crate::ppmem::GEN_SLOTS`] (one per CPU plus external); ROM / + /// MMIO devices have a single never-bumped counter (1). A compile reads + /// all of them and takes the max, so a device with one counter is not + /// read out of bounds. + #[cfg(feature = "jitv2")] + pub gen_slots: u8, /// The page's 1024 words in the bank's own storage, for a bank that can /// hand them out: the JIT's compile workers read the page there, with no /// bus and no address. Like `gen` it belongs to the bank, stays put when @@ -147,7 +154,8 @@ impl CodeBank { /// The page holding byte `offset` of this bank, counted by `gen`. #[inline] pub fn page(&self, offset: u64, gen: *const std::sync::atomic::AtomicU64) -> CodePage { - CodePage { key: self.key(offset), gen, words: std::ptr::null() } + CodePage { key: self.key(offset), gen, words: std::ptr::null(), + gen_slots: crate::ppmem::GEN_SLOTS as u8 } } } From d6425e48133a947efbc87c769ce39974f06c8c52 Mon Sep 17 00:00:00 2001 From: Samueltgg12 Date: Mon, 30 Nov 2026 12:14:15 -0300 Subject: [PATCH 2/3] cpu: make the data-side nutlb two-way set-associative MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/nutlb-design.md §8/§9 measured 95-100% of nutlb misses as same-set conflicts and §10 listed 2-way as the obvious next move. Each set now holds two entries: MipsCore::nutlb/nutlb_valid gain a [way] dimension and nutlb_lru records the next victim bit, flipped only on a fill so the hot hit path pays no LRU store. nutlb_translate probes both ways with a branchless AND of tag compare and valid bit, ORs the hits, and selects the matching phys; on a miss it fills the victim way. The JIT inline probe in codegen.rs mirrors this exactly: way 1 is one array past way 0, both valid words are read, hits OR-ed and e_phys selected. No victim-bit write in compiled code (fills are Rust-only). tlbstats conflict checking looks at either way. Flushing at all the existing barriers still clears both ways; nutlb is per-CPU, so SMP is unaffected. Arrays grow 8 KiB -> 16 KiB. docs/nutlb-design.md updated (§10 no longer open, §11.1 shape). cargo check (+jitv2_lockstep) clean; jitv2 523, mips_exec_test 218, nutlb 2, lockstep 15 tests passed. Not yet guest-measured. --- CHANGELOG.md | 4 ++ clanker/INDEX.md | 1 + clanker/cpu/nutlb-two-way.md | 54 +++++++++++++++++++++++++ docs/nutlb-design.md | 26 +++++++----- src/cpu/jitv2/codegen.rs | 76 ++++++++++++++++++++---------------- src/cpu/mips_core.rs | 50 ++++++++++++++++++------ src/cpu/mips_exec.rs | 50 ++++++++++-------------- src/cpu/mips_exec_test.rs | 4 +- 8 files changed, 180 insertions(+), 85 deletions(-) create mode 100644 clanker/cpu/nutlb-two-way.md diff --git a/CHANGELOG.md b/CHANGELOG.md index aec0494d0..71d81389e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -350,6 +350,10 @@ hashes are given where a change is easiest to understand by reading the commit. - IRIX spends less host time on address translation: raising or lowering the interrupt mask no longer empties the CPU's translation cache, which halves translation misses on a busy 4-CPU Tezro. All machines. +- Address translation keeps twice as many recent pages per set on every + machine, so workloads that alternate between pages no longer evict each + other on every access. SMP guests keep a separate translation cache per + CPU. ### jitv2 memory diff --git a/clanker/INDEX.md b/clanker/INDEX.md index 46deed039..fe85e6ef2 100644 --- a/clanker/INDEX.md +++ b/clanker/INDEX.md @@ -47,6 +47,7 @@ CPU architecture: CP0, TLB and its fast paths, caches, FPU, LL/SC, CPU models. B | [nanotlb-asid-mutation-flush.md](cpu/nanotlb-asid-mutation-flush.md) | rule | nanotlb must be flushed on ASID mutation, not just on privilege transition | | [translation-status-flush-filter.md](cpu/translation-status-flush-filter.md) | rule | skip the nutlb/nanotlb flush on a CP0 Status write that changes no translation-relevant bit (and on a no-op write) | | [nutlb-erl-guard-defeats-permission-test.md](cpu/nutlb-erl-guard-defeats-permission-test.md) | history | nutlb: the ERL guard bit defeats the permission test entirely | +| [nutlb-two-way.md](cpu/nutlb-two-way.md) | design | two ways per nutlb set, branchless both-way probe in Rust and the JIT mirror; victim bit flipped on fill only | | [r5000-taglo-is-the-r4400-pstate.md](cpu/r5000-taglo-is-the-r4400-pstate.md) | rule | R5000 L1 TagLo uses the R4400 PState encoding | | [r5k-l1i-cache-bugs.md](cpu/r5k-l1i-cache-bugs.md) | open | R5000 secondary cache: no working configuration currently exists | | [sc-succeeds-on-llbit-alone.md](cpu/sc-succeeds-on-llbit-alone.md) | rule | `SC` succeeds on the LLbit alone — `LLAddr` is not a gate | diff --git a/clanker/cpu/nutlb-two-way.md b/clanker/cpu/nutlb-two-way.md new file mode 100644 index 000000000..0dc317987 --- /dev/null +++ b/clanker/cpu/nutlb-two-way.md @@ -0,0 +1,54 @@ +# nutlb: two ways per set, branchless both-way probe + +**Status:** implemented 2026-11-30, awaiting guest measurement. + +## Symptom / motivation + +`docs/nutlb-design.md` §8/§9 measured 95–100% of nutlb misses as same-set +conflicts and §10 listed 2-way associativity as "still the obvious next move". +The one-way structure's cheap probe had already beaten a 4-way/AVX2 nanotlb +once, so the added tag compare had to be kept minimal. + +## Design + +- `MipsCore::nutlb` and `nutlb_valid` gain a **way** dimension: + `[Read|Write][way][set]`, `NUM_NUTLB_WAYS = 2`. `nutlb_lru[arr][word]` holds + one next-victim bit per set. Total arrays 16 KiB (was 8 KiB). +- `nutlb_translate` loads **both** ways' `virttag`, ANDs each with its valid + bit, ORs the two results (bitwise, branchless). On a hit it selects the + matching way's `phys`; on a miss it fills the set's victim way and flips + that bit. **No LRU store on a hit**, so the hot path is one extra tag load + and one extra valid-bit probe, plus a select. +- `nutlb_fill` takes the way chosen by the caller; `nutlb_clear` clears both + ways' valid bits and the LRU words; `nutlb_is_valid`/`nutlb_set_valid` take + a `way`. +- **JIT mirror** (`jitv2/codegen.rs::emit_inline_mem_guard`) computes way 1 + as `way0 + NUM_NUTLB_ENTRIES * 16`, reads both valid words + (`nutlb_valid[arr][way][idx >> 6]`), ORs the two hits and `select`s `e_phys`. + It does **not** update the victim bit (fills are Rust-only), so the emitted + probe stays two loads + two bit tests + one select. +- `tlbstats` conflict counting now checks either way for a valid foreign tag. + +## Why correct on SMP + +nutlb is per CPU; both ways are probed before any result is used, and the +valid bit still gates every tag. Flushing at all the existing barriers still +clears both ways. The JIT probe selects the same physical address the Rust +path would. The only new shared state is `nutlb_lru`, per-CPU and written +only on a fill, never on the hot hit path. + +## Verification + +`cargo check -p iris --features jitv2` clean; also `jitv2_lockstep`. +`cargo test -p iris --lib --features jitv2`: `jitv2::` 523 passed, +`mips_exec_test::` 218 passed, `nutlb` 2 passed, +`--features jitv2,jitv2_lockstep lockstep` 15 passed. + +## Caveats + +- 16 KiB host D-cache footprint (was 8 KiB). §0's warning stands: on this hot + path a cheaper probe has beaten a smarter structure twice before; this + needs live-IRIX + `iris-bench` measurement before believing it. +- `IRIS_*` no new config; no feature flag; `docs/nutlb-design.md` updated. +- If it regresses, revert the whole commit (the struct layout, the Rust + probe and the JIT mirror must stay in lockstep). diff --git a/docs/nutlb-design.md b/docs/nutlb-design.md index db6cdd6e1..570216e8f 100644 --- a/docs/nutlb-design.md +++ b/docs/nutlb-design.md @@ -1,8 +1,10 @@ -# nutlb — direct-mapped data-side micro-TLB +# nutlb — two-way set-associative data-side micro-TLB Status: **shipped, unconditional (no feature flag).** Replaces the Read/Write slots of the old 3-entry `nanotlb`; the Fetch slot survives as a separate, -specialised one-entry structure. +specialised one-entry structure. Two ways per set were added in November +2026 (§10); the measurements in this document are from the earlier one-way +design unless a section says otherwise. Companion reading: `HACKING.md` (data path), `clanker/testing/` (TLB findings), and an earlier nanotlb-associativity note (never checked in) — a previous 4-way/AVX2 @@ -641,9 +643,11 @@ with `&`. Ranked by expected value. Revised for Generation 2 — two entries that referred to Generation 1 machinery are now moot and marked so. -- **2-way associativity.** Still the obvious next move, and cheaper to try - now: with a 16 B entry a 2-way set is 32 B, one cache line, and the probe it - competes against is only two operations. But note that Generation 2 is the +- **2-way associativity — implemented November 2026.** Both ways of a set are + probed branchlessly; a fill toggles the set's victim bit, so the hot path + pays no LRU store (the JIT's inline probe mirrors this). The arrays grew to + 16 KiB. The measurement that follows is the original argument for trying it. + But note that Generation 2 is the *second* time a cheaper hit test beat a smarter one here (§0), so weight the extra tag comparison accordingly. Original reasoning: 95–100% of misses are same-set conflicts, and more sets demonstrably don't fix that (§8). Caveat @@ -694,7 +698,8 @@ to Generation 1 machinery are now moot and marked so. ### 11.1 Shape ```rust -pub const NUTLB_BITS: usize = 8; // 256 entries/array +pub const NUTLB_BITS: usize = 8; // 256 entries/way +pub const NUM_NUTLB_WAYS: usize = 2; pub const NUM_NUTLB_WORDS: usize = NUM_NUTLB_ENTRIES / 64; // 4 #[derive(Clone, Copy, Default)] @@ -704,12 +709,13 @@ pub struct NuTlbEntry { pub phys: u64, // PA[63:12] in [63:12]; C-field in [2:0] } -pub nutlb: [[NuTlbEntry; NUM_NUTLB_ENTRIES]; 2], // [0]=Read [1]=Write -pub nutlb_valid: [[u64; NUM_NUTLB_WORDS]; 2], // one bit per set +pub nutlb: [[[NuTlbEntry; NUM_NUTLB_ENTRIES]; NUM_NUTLB_WAYS]; 2], // [Read|Write][way][set] +pub nutlb_valid: [[[u64; NUM_NUTLB_WORDS]; NUM_NUTLB_WAYS]; 2], // one bit per set/way +pub nutlb_lru: [[u64; NUM_NUTLB_WORDS]; 2], // next victim way, flipped on fill ``` -16 B/entry, so both arrays together are **8 KiB** rather than Generation 1's -16 KiB. The Read/Write split (§2) and the `phys` encoding are unchanged. +16 B/entry, two ways, so all arrays together are **16 KiB** — the same as +Generation 1's one-way 32 B entries, but with twice the residency. The Read/Write split (§2) and the `phys` encoding are unchanged. **A zero tag is no longer self-evidently invalid.** VA 0 is a legal page number, so validity comes *only* from the bitmask. Never test `virttag` without diff --git a/src/cpu/jitv2/codegen.rs b/src/cpu/jitv2/codegen.rs index 50b2726bf..70e5c3d5f 100644 --- a/src/cpu/jitv2/codegen.rs +++ b/src/cpu/jitv2/codegen.rs @@ -4207,7 +4207,7 @@ fn emit_inline_mem_guard( let arr = if STORE { mc::NUTLB_WRITE } else { mc::NUTLB_READ }; let set_bytes = std::mem::size_of::() as i64; let arr_base = std::mem::offset_of!(MipsCore, nutlb) as i64 - + (arr as i64) * (mc::NUM_NUTLB_ENTRIES as i64) * set_bytes; + + (arr as i64) * (mc::NUM_NUTLB_WAYS as i64) * (mc::NUM_NUTLB_ENTRIES as i64) * set_bytes; let idx = ctx.builder.ins().ushr_imm_s(vaddr, 12); let idx = ctx.builder.ins().band_imm_s(idx, mc::NUTLB_INDEX_MASK as i64); @@ -4216,48 +4216,58 @@ fn emit_inline_mem_guard( // No uextend: already i64, and ptr_ty is i64 here — Cranelift's verifier // rejects a widening that isn't one, which silently declined every region // containing a load (see docs/jit-inline-memory.md §9). - let entry = ctx.builder.ins().iadd(ctx.core_ptr, entry_off); + let entry0 = ctx.builder.ins().iadd(ctx.core_ptr, entry_off); + // Way 1 lives after all 256 way-0 entries of this array. + let way1_base = ctx.builder.ins().iadd_imm_s( + entry0, (mc::NUM_NUTLB_ENTRIES as i64) * set_bytes); - let e_virttag = ctx.builder.ins().load(i64t, mem, entry, + let e0_virttag = ctx.builder.ins().load(i64t, mem, entry0, ir::immediates::Offset32::new(std::mem::offset_of!(mc::NuTlbEntry, virttag) as i32)); - let e_phys = ctx.builder.ins().load(i64t, mem, entry, + let e0_phys = ctx.builder.ins().load(i64t, mem, entry0, ir::immediates::Offset32::new(std::mem::offset_of!(mc::NuTlbEntry, phys) as i32)); + let e1_virttag = ctx.builder.ins().load(i64t, mem, way1_base, + ir::immediates::Offset32::new(std::mem::offset_of!(mc::NuTlbEntry, virttag) as i32)); + let e1_phys = ctx.builder.ins().load(i64t, mem, way1_base, + ir::immediates::Offset32::new(std::mem::offset_of!(mc::NuTlbEntry, phys) as i32)); + + // Tag compare + bitmask bit for both ways, mirroring + // `MipsExecutor::nutlb_translate`. Any divergence is a correctness bug. + let (hit0, hit1) = { + let va_page = ctx.builder.ins().band_imm_s(vaddr, !0xFFFi64); + let mut hit = |entry_tag: ir::Value, way: usize| { + let tag_eq = ctx.builder.ins().icmp(IntCC::Equal, entry_tag, va_page); + // valid[arr][way][idx >> 6] >> (idx & 63) & 1 + let words_base = std::mem::offset_of!(MipsCore, nutlb_valid) as i64 + + (arr as i64) * (mc::NUM_NUTLB_WAYS as i64) * (mc::NUM_NUTLB_WORDS as i64) * 8 + + (way as i64) * (mc::NUM_NUTLB_WORDS as i64) * 8; + let word_idx = ctx.builder.ins().ushr_imm_s(idx, 6); + let word_off = ctx.builder.ins().imul_imm_s(word_idx, 8); + let word_off = ctx.builder.ins().iadd_imm_s(word_off, words_base); + let word_ptr = ctx.builder.ins().iadd(ctx.core_ptr, word_off); + let word = ctx.builder.ins().load(i64t, mem, word_ptr, ir::immediates::Offset32::new(0)); + // Shift count is masked to 6 bits by the ISA (x86 `shr` masks to + // 63), and Cranelift's `ushr` is defined the same way, so the + // explicit `& 63` in the Rust version is redundant here. + let bit = ctx.builder.ins().ushr(word, idx); + let valid = ctx.builder.ins().band_imm_s(bit, 1); + let valid = ctx.builder.ins().icmp_imm_s(IntCC::NotEqual, valid, 0); + ctx.builder.ins().band(tag_eq, valid) + }; + (hit(e0_virttag, 0), hit(e1_virttag, 1)) + }; + // The Rust path takes way 0 when both somehow match; both cannot be + // valid for the same page unless a fill raced, but choose way 0 anyway. + let e_phys = ctx.builder.ins().select(hit0, e0_phys, e1_phys); // Cacheability. The Rust path branches on `TranslateResult::is_cached()` // and sends uncached accesses to the bus, never the D-cache — so the // inline path must decline them, or an uncached access could be served - // from a stale L1-D line. That is reachable, not theoretical: MIPS maps - // the same physical page both cached (kseg0) and uncached (kseg1), so a - // line filled through kseg0 carries a physical tag that a later kseg1 - // access would match. C-field lives in phys[2:0] (TR_UNCACHED == 2). + // from a stale L1-D line. C-field lives in phys[2:0] (TR_UNCACHED == 2). let c_field = ctx.builder.ins().band_imm_s(e_phys, 0x7); let cacheable = ctx.builder.ins().icmp_imm_s( IntCC::NotEqual, c_field, crate::cpu::mips_exec::TR_UNCACHED as i64); - - // Tag compare + bitmask bit, mirroring `MipsExecutor::nutlb_translate`. - // Any divergence here is a correctness bug, not a performance one. - let ok = { - let va_page = ctx.builder.ins().band_imm_s(vaddr, !0xFFFi64); - let tag_eq = ctx.builder.ins().icmp(IntCC::Equal, e_virttag, va_page); - - // valid[arr][idx >> 6] >> (idx & 63) & 1 - let words_base = std::mem::offset_of!(MipsCore, nutlb_valid) as i64 - + (arr as i64) * (mc::NUM_NUTLB_WORDS as i64) * 8; - let word_idx = ctx.builder.ins().ushr_imm_s(idx, 6); - let word_off = ctx.builder.ins().imul_imm_s(word_idx, 8); - let word_off = ctx.builder.ins().iadd_imm_s(word_off, words_base); - let word_ptr = ctx.builder.ins().iadd(ctx.core_ptr, word_off); - let word = ctx.builder.ins().load(i64t, mem, word_ptr, ir::immediates::Offset32::new(0)); - // Shift count is masked to 6 bits by the ISA (x86 `shr` masks to 63), - // and Cranelift's `ushr` is defined the same way, so the explicit - // `& 63` in the Rust version is redundant here rather than omitted. - let bit = ctx.builder.ins().ushr(word, idx); - let valid = ctx.builder.ins().band_imm_s(bit, 1); - let valid = ctx.builder.ins().icmp_imm_s(IntCC::NotEqual, valid, 0); - - let ok = ctx.builder.ins().band(tag_eq, valid); - ctx.builder.ins().band(ok, cacheable) - }; + let any_hit = ctx.builder.ins().bor(hit0, hit1); + let ok = ctx.builder.ins().band(any_hit, cacheable); let xlat_ok_block = ctx.builder.create_block(); ctx.builder.ins().brif(ok, xlat_ok_block, &[], slow_block, &[]); diff --git a/src/cpu/mips_core.rs b/src/cpu/mips_core.rs index 4c2ac1623..fe7c599d8 100644 --- a/src/cpu/mips_core.rs +++ b/src/cpu/mips_core.rs @@ -427,7 +427,12 @@ pub struct MipsCore { /// the per-probe cost of the ASID/permission/generation checks, paid on /// every load and store, outweighed the refills the tags avoided. See /// docs/nutlb-design.md §12. - pub nutlb_valid: [[u64; NUM_NUTLB_WORDS]; 2], + pub nutlb_valid: [[[u64; NUM_NUTLB_WORDS]; NUM_NUTLB_WAYS]; 2], + + /// Next way to evict per set (`0`/`1`), one bit per word. Toggled only on + /// a fill, so the hot hit path (including the JIT's inline probe) never + /// writes it; the next fill uses the other way of the set. + pub nutlb_lru: [[u64; NUM_NUTLB_WORDS]; 2], /// Called whenever CP0 Status (reg 12) is written, with (old_value, new_value). /// The first element is the callback function, the second is an opaque context pointer @@ -1022,7 +1027,7 @@ pub struct MipsCore { /// the cache lines they currently share with `hot`/`pc`/`gpr`. jitv2 /// reaches fields by `offset_of!` at codegen time, so the offsets adjust /// themselves; only locality is at stake, and only for fields *after* it. - pub nutlb: [[NuTlbEntry; NUM_NUTLB_ENTRIES]; 2], + pub nutlb: [[[NuTlbEntry; NUM_NUTLB_ENTRIES]; NUM_NUTLB_WAYS]; 2], /// Write-only landing slot for a load whose destination is `r0`. /// @@ -1073,6 +1078,11 @@ mod nutlb_defs { pub const NUM_NUTLB_ENTRIES: usize = 1 << NUTLB_BITS; pub const NUTLB_INDEX_MASK: u64 = (NUM_NUTLB_ENTRIES as u64) - 1; + /// Two ways per set. Direct mapping lost most of its hits to same-set + /// conflicts (`docs/nutlb-design.md` §8/§10); a second way doubles the + /// residents of a set at one extra tag compare per probe. + pub const NUM_NUTLB_WAYS: usize = 2; + /// `nutlb_bitmask`: number of u64 words in one array's valid bitmask. /// 256 entries / 64 = 4, so a full flush is 4 stores per array. pub const NUM_NUTLB_WORDS: usize = NUM_NUTLB_ENTRIES / 64; @@ -1334,7 +1344,8 @@ impl MipsCore { nanotlb: [NanoTlbEntry::default(); 3], // All-zero = every set invalid, which is what a fresh core // wants; the tag array's contents are then unreachable. - nutlb_valid: [[0u64; NUM_NUTLB_WORDS]; 2], + nutlb_valid: [[[0u64; NUM_NUTLB_WORDS]; NUM_NUTLB_WAYS]; 2], + nutlb_lru: [[0u64; NUM_NUTLB_WORDS]; 2], status_changed_cb: None, // Placeholders — overwritten immediately by // MipsExecutor::install_jit_hooks (same pattern as translate_fn's @@ -1476,7 +1487,7 @@ impl MipsCore { ip7_seq_shared: Arc::new(AtomicU64::new(0)), // 16 KiB of zeroes. `NuTlbEntry: Copy` so this is a const-promoted // memset, not 512 separate initializations. - nutlb: [[NuTlbEntry::default(); NUM_NUTLB_ENTRIES]; 2], + nutlb: [[[NuTlbEntry::default(); NUM_NUTLB_ENTRIES]; NUM_NUTLB_WAYS]; 2], #[cfg(feature = "jitv2")] gpr_scratch: 0, #[cfg(feature = "jitv2")] @@ -2262,8 +2273,9 @@ impl MipsCore { self.nanotlb[2].invalidate(); } - /// Drop every nutlb entry by clearing the valid bitmask. 8 stores total - /// (4 words x 2 arrays) no matter how many entries were live. + /// Drop every nutlb entry by clearing the valid bitmask and next-victim + /// bits. 16 stores total (4 words x 2 arrays x 2 ways) plus 8 LRU words, + /// regardless of how many entries were live. /// /// The tag array is deliberately left untouched: nothing reads a tag /// without first testing its bit, so stale tags are unreachable. @@ -2273,19 +2285,35 @@ impl MipsCore { /// the flush is hung there rather than on individual call sites. #[inline] pub fn nutlb_clear(&mut self) { - self.nutlb_valid = [[0u64; NUM_NUTLB_WORDS]; 2]; + self.nutlb_valid = [[[0u64; NUM_NUTLB_WORDS]; NUM_NUTLB_WAYS]; 2]; + self.nutlb_lru = [[0u64; NUM_NUTLB_WORDS]; 2]; } /// Is set `idx` of array `arr` live? #[inline(always)] - pub fn nutlb_is_valid(&self, arr: usize, idx: usize) -> bool { - (self.nutlb_valid[arr][idx >> 6] >> (idx & 63)) & 1 != 0 + pub fn nutlb_is_valid(&self, arr: usize, way: usize, idx: usize) -> bool { + (self.nutlb_valid[arr][way][idx >> 6] >> (idx & 63)) & 1 != 0 } /// Mark set `idx` of array `arr` live. #[inline(always)] - pub fn nutlb_set_valid(&mut self, arr: usize, idx: usize) { - self.nutlb_valid[arr][idx >> 6] |= 1u64 << (idx & 63); + pub fn nutlb_set_valid(&mut self, arr: usize, way: usize, idx: usize) { + self.nutlb_valid[arr][way][idx >> 6] |= 1u64 << (idx & 63); + } + + /// Which way of this set the next fill evicts. Flipped on every fill, so + /// the hot hit path never pays an LRU store (the JIT's inline probe does + /// not update it either). + #[inline(always)] + pub fn nutlb_victim(&self, arr: usize, idx: usize) -> usize { + ((self.nutlb_lru[arr][idx >> 6] >> (idx & 63)) & 1) as usize + } + + /// Set the next victim way for this set. + #[inline(always)] + pub fn nutlb_set_victim(&mut self, arr: usize, idx: usize, way: usize) { + let w = &mut self.nutlb_lru[arr][idx >> 6]; + *w = (*w & !(1u64 << (idx & 63))) | ((way as u64 & 1) << (idx & 63)); } /// Set interrupt bit diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 254659dd7..6c8d1ea9e 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -3462,20 +3462,15 @@ impl MipsExecutor { fn nutlb_translate(&mut self, va: u64) -> TranslateResult { let idx = crate::cpu::mips_core::nutlb_index(va); let arr = if W { crate::cpu::mips_core::NUTLB_WRITE } else { crate::cpu::mips_core::NUTLB_READ }; - let e = &self.core.nutlb[arr][idx]; - - // The whole hit test: one page compare, one bitmask bit. No - // generation, no ASID, no permission — all three are covered by - // flushing instead (see `MipsExecutor::nanotlb_invalidate`). - // - // Bitwise `&`, not `&&`: deliberately branchless. Short-circuit `&&` - // emits a second conditional jump for a predicate that is already - // this cheap; `&` costs one extra ALU op and zero branches, and is - // flat in the miss rate where `&&` degrades with it. - // - // The bitmask word load is independent of the entry load, so the two - // issue in parallel rather than serializing. - if (e.virttag == (va & !0xFFF)) & self.core.nutlb_is_valid(arr, idx) { + // Two ways per set. Both ways are probed branchlessly: each hit is a + // tag compare ANDed with its valid bit; the two results are OR-ed. + // No generation/ASID/permission — all covered by flushing. + let want = va & !0xFFF; + let (e0, e1) = (&self.core.nutlb[arr][0][idx], &self.core.nutlb[arr][1][idx]); + let hit0 = (e0.virttag == want) & self.core.nutlb_is_valid(arr, 0, idx); + let hit1 = (e1.virttag == want) & self.core.nutlb_is_valid(arr, 1, idx); + if hit0 | hit1 { + let e = if hit0 { e0 } else { e1 }; #[cfg(feature = "tlbstats")] self.tlb.stats_nutlb_hit(if W { AccessType::Write } else { AccessType::Read }); #[cfg(feature = "jitstats")] @@ -3486,17 +3481,12 @@ impl MipsExecutor { #[cfg(feature = "tlbstats")] { let at = if W { AccessType::Write } else { AccessType::Read }; - // Distinguish conflict from capacity/cold: a valid tag with a - // different page number means this set was occupied by someone - // else, which is the argument for more sets (or associativity). - // - // A zero tag is a legal page number, so validity has to come - // from the bitmask rather than from the tag being non-zero — - // otherwise every post-flush refill would be miscounted as a - // conflict. - let e = &self.core.nutlb[arr][idx]; - let occupied = self.core.nutlb_is_valid(arr, idx); - if occupied && (e.virttag & !0xFFF) != (va & !0xFFF) { + // Conflict: either way holds a valid tag for another page. + let occupied0 = self.core.nutlb_is_valid(arr, 0, idx); + let occupied1 = self.core.nutlb_is_valid(arr, 1, idx); + if (occupied0 && (e0.virttag & !0xFFF) != want) + || (occupied1 && (e1.virttag & !0xFFF) != want) + { self.tlb.stats_nutlb_conflict(at); } self.tlb.stats_nutlb_miss(at); @@ -3507,7 +3497,9 @@ impl MipsExecutor { let at = if W { AccessType::Write } else { AccessType::Read }; let result = (self.translate_fn)(self, va, at); if !result.is_exception() { - self.nutlb_fill::(va, &result); + let way = self.core.nutlb_victim(arr, idx); + self.nutlb_fill::(va, &result, way); + self.core.nutlb_set_victim(arr, idx, 1 - way); } result } @@ -3539,7 +3531,7 @@ impl MipsExecutor { /// Fill the nutlb set for `va` from a successful translation. #[inline] - fn nutlb_fill(&mut self, va: u64, result: &TranslateResult) { + fn nutlb_fill(&mut self, va: u64, result: &TranslateResult, way: usize) { use crate::cpu::mips_core::*; // ERL is a do-not-cache window: while it is set, KUSEG/xuseg stop @@ -3563,14 +3555,14 @@ impl MipsExecutor { let idx = nutlb_index(va); let arr = if W { NUTLB_WRITE } else { NUTLB_READ }; - let e = &mut self.core.nutlb[arr][idx]; + let e = &mut self.core.nutlb[arr][way][idx]; e.virttag = va & !0xFFF; e.phys = (result.phys & !0xFFF) | (result.status & 0x7) as u64; // Tag first, then validity. The order matters only for a reader that // could observe the entry between the two stores; nothing does today // (single-threaded per core), but publishing validity last is the // order that stays correct if that ever changes. - self.core.nutlb_set_valid(arr, idx); + self.core.nutlb_set_valid(arr, way, idx); } /// Invalidate the nanotlb and drop the cached PCP pointer along with it. diff --git a/src/cpu/mips_exec_test.rs b/src/cpu/mips_exec_test.rs index 45586cb7f..f57244e91 100644 --- a/src/cpu/mips_exec_test.rs +++ b/src/cpu/mips_exec_test.rs @@ -1355,7 +1355,7 @@ mod tests { let kva: u64 = 0xFFFF_FFFF_8000_4000; mem.set_word(0x4000, 0xDEAD_BEEF); - let nutlb_live = |e: &MipsExecutor| e.core.nutlb_valid.iter().flatten().any(|w| *w != 0); + let nutlb_live = |e: &MipsExecutor| e.core.nutlb_valid.iter().flatten().flatten().any(|w| *w != 0); let mtc0_status = |e: &mut MipsExecutor, v: u32| { e.core.write_gpr(8, v as u64); let op = (OP_COP0 << 26) | (0x04 << 21) | (8 << 16) | (12 << 11); @@ -7540,7 +7540,7 @@ mod tests { // inside the entry and the tag records nothing about which K0 filled // it, so stale entries would keep serving the old cacheability. let any_valid = |e: &MipsExecutor| { - e.core.nutlb_valid.iter().any(|arr| arr.iter().any(|w| *w != 0)) + e.core.nutlb_valid.iter().flatten().flatten().any(|w| *w != 0) }; // ERL must be clear to fill at all: `nutlb_fill` treats ERL=1 as a From 9faaa8549a7aaded3f5c9f1c45af6b5d1d4db19f Mon Sep 17 00:00:00 2001 From: Samueltgg12 Date: Mon, 30 Nov 2026 12:46:56 -0300 Subject: [PATCH 3/3] cpu: narrow the untagged-TLB barrier at ASID-preserving writes and nested exceptions nanotlb_invalidate cleared nanotlb[0..3], both nutlb ways and the jitv2 pcp even when no cached translation could have changed. - MTC0/DMTC0 EntryHi (reg 10): pass the previous cp0_entryhi into handle_cp0_side_effects; flush only if the ASID bits [7:0] changed. VPN2/region writes are not a barrier. IRIX writes EntryHi on every TLB refill, so this is hot. - TLBR: capture old EntryHi before the read; flush only on an ASID change (TLBR does not write the TLB). - All three exception paths: capture cp0_status before deliver_exception[_at] and call resync_privilege_state_filtered with (old ^ new) & TRANSLATION_STATUS_MASK != 0. A nested exception with EXL already set changes no translation bit, so the nutlb survives; a first exception or cache error (ERL) still flushes. translate_fn and FPR mode are always re-derived. ERET, TLBWI/TLBWR, K0 config writes, layout changes, restore/reset are unchanged. per-CPU state only; SMP-safe. New regression test test_mtc0_entryhi_with_same_asid_keeps_the_nutlb. cargo check clean; mips_exec_test 218, jitv2 523, new tlbstats test passed. --- CHANGELOG.md | 3 +- clanker/INDEX.md | 1 + clanker/cpu/narrow-nutlb-flush-sites.md | 25 +++++++++++ docs/nutlb-design.md | 5 ++- src/cpu/mips_exec.rs | 55 ++++++++++++++++++------- src/cpu/mips_exec_test.rs | 32 ++++++++++++++ 6 files changed, 105 insertions(+), 16 deletions(-) create mode 100644 clanker/cpu/narrow-nutlb-flush-sites.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 71d81389e..ecc1e24af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -353,7 +353,8 @@ hashes are given where a change is easiest to understand by reading the commit. - Address translation keeps twice as many recent pages per set on every machine, so workloads that alternate between pages no longer evict each other on every access. SMP guests keep a separate translation cache per - CPU. + CPU. Refill writes and nested exceptions no longer discard that cache when + the address space or privilege did not change. ### jitv2 memory diff --git a/clanker/INDEX.md b/clanker/INDEX.md index fe85e6ef2..201a0f034 100644 --- a/clanker/INDEX.md +++ b/clanker/INDEX.md @@ -48,6 +48,7 @@ CPU architecture: CP0, TLB and its fast paths, caches, FPU, LL/SC, CPU models. B | [translation-status-flush-filter.md](cpu/translation-status-flush-filter.md) | rule | skip the nutlb/nanotlb flush on a CP0 Status write that changes no translation-relevant bit (and on a no-op write) | | [nutlb-erl-guard-defeats-permission-test.md](cpu/nutlb-erl-guard-defeats-permission-test.md) | history | nutlb: the ERL guard bit defeats the permission test entirely | | [nutlb-two-way.md](cpu/nutlb-two-way.md) | design | two ways per nutlb set, branchless both-way probe in Rust and the JIT mirror; victim bit flipped on fill only | +| [narrow-nutlb-flush-sites.md](cpu/narrow-nutlb-flush-sites.md) | rule | skip the TLB barrier on MTC0/TLBR writes that keep the ASID and on nested exceptions that change no translation Status bit | | [r5000-taglo-is-the-r4400-pstate.md](cpu/r5000-taglo-is-the-r4400-pstate.md) | rule | R5000 L1 TagLo uses the R4400 PState encoding | | [r5k-l1i-cache-bugs.md](cpu/r5k-l1i-cache-bugs.md) | open | R5000 secondary cache: no working configuration currently exists | | [sc-succeeds-on-llbit-alone.md](cpu/sc-succeeds-on-llbit-alone.md) | rule | `SC` succeeds on the LLbit alone — `LLAddr` is not a gate | diff --git a/clanker/cpu/narrow-nutlb-flush-sites.md b/clanker/cpu/narrow-nutlb-flush-sites.md new file mode 100644 index 000000000..ba4810dd4 --- /dev/null +++ b/clanker/cpu/narrow-nutlb-flush-sites.md @@ -0,0 +1,25 @@ +# narrow the untagged-TLB barrier to the events that can change a translation + +**Status:** implemented 2026-11-30, awaiting guest measurement. Follows the CP0-Status filtering rule (same `TRANSLATION_STATUS_MASK`). + +## Symptom + +`nanotlb_invalidate()` clears `nanotlb[0..3]`, **both ways** of `nutlb_valid`, and the jitv2 `pcp`, on every barrier. Several hotspots fired it when nothing a cached translation depends on could have moved. + +## Narrowed sites + +1. **`MTC0/DMTC0 EntryHi` (reg 10).** `handle_cp0_side_effects` now takes the previous `cp0_entryhi` from `exec_mtc0`/`exec_dmtc0` and flushes only when `(old ^ new) & 0xFF != 0`. VPN2/region bits are not in a nutlb tag, so a refill write that keeps the ASID is not a barrier. IRIX writes EntryHi on every refill, so this is hot. +2. **`TLBR`.** `exec_tlbr` captures the old EntryHi before overwriting it and flushes only if the ASID bits changed. The TLB itself was not written by TLBR. +3. **All three exception paths** (`handle_exception`, `handle_exception_at`, `handle_exception_syscall`). Capture `cp0_status` before `deliver_exception[_at]`, then call `resync_privilege_state_filtered((old ^ new) & TRANSLATION_STATUS_MASK != 0)`. A **nested** exception arriving with EXL already set changes neither EXL/ERL nor privilege/mode — EPC/Cause/vector do not feed translation — so the per-CPU nutlb working set survives. A first exception (EXL 0→1) or a cache error (ERL set) still flushes. + +**Unchanged:** `exec_eret` (clears EXL/ERL → privilege/mode change), `TLBWI`/`TLBWR` (the cached TLB entry changed), `CP0 Config` K0 write, `jitv2_layout_changed`/geometry change, snapshot/restore, soft reset. + +## Why correct + +The untagged nutlb is valid only while the VA→PA meaning of its tags holds. That meaning changes on privilege/mode (`TRANSLATION_STATUS_MASK`), ASID, a TLB write, or a memory remap. None of the narrowed sites changes any of those, so stale entries cannot be reached. `translate_fn`/FPR mode are still **always** re-derived in the exception paths (`resync_privilege_state_filtered`). jitv2 `pcp` stays valid for the same reason: PC moves to a vector in another page, which makes the fetch nanotlb miss and re-derive `pcp`. + +SMP-safe: everything touched is per-CPU; no shared state or ordering changes. + +## Verification + +`cargo check -p iris --features jitv2` clean. `mips_exec_test` 218 passed, `jitv2` 523 passed, and new `test_mtc0_entryhi_with_same_asid_keeps_the_nutlb` (with `tlbstats`) passed. Not guest-measured. diff --git a/docs/nutlb-design.md b/docs/nutlb-design.md index 570216e8f..e99416993 100644 --- a/docs/nutlb-design.md +++ b/docs/nutlb-design.md @@ -128,7 +128,10 @@ that it apparently doesn't. **Status: closed, ahead of any nutlb work.** `handle_cp0_side_effects` now flushes on reg 10, and `exec_tlbr` flushes itself; `exec_tlb`'s misleading -"they don't mutate the TLB" comment is corrected in place. Two regression tests +"they don't mutate the TLB" comment is corrected in place. Both now flush +**only when bits 7:0 of EntryHi (the ASID) actually changed** — a TLB refill +that keeps the current ASID is not a barrier. Likewise, nested exceptions +that set an already-set EXL/ERL skip the flush. Two regression tests (`test_mtc0_entryhi_asid_change_invalidates_nanotlb`, `test_tlbr_asid_change_invalidates_nanotlb` in `mips_exec_test.rs`) map one VA to different PFNs under ASIDs 10 and 11 and assert the second read sees the diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 6c8d1ea9e..230a96fcc 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -4892,13 +4892,20 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", } // Architectural effect (Cause/EPC/Status/vector) — the portable part // shared with jitv2-verify (§4.2 single-implementation delivery). + let old_status = self.core.cp0_status; crate::cpu::mips_core::deliver_exception(&mut self.core, status); - // deliver_exception forces kernel privilege by setting EXL directly on - // cp0_status, without going through write_cp0, so this is the only barrier on - // the path — and it must re-derive translate_fn, not just flush. The handler - // vector is in KSEG0/KSEG1, which only the kernel translator will accept. - self.resync_privilege_state(); + // deliver_exception forces kernel privilege by setting EXL/ERL + // directly on cp0_status, without going through write_cp0, so this is + // the only barrier on the path — and it must re-derive translate_fn, + // not just flush. The handler vector is in KSEG0/KSEG1, which only the + // kernel translator will accept. A nested exception that arrives with + // EXL already set changes no translation bit (EPC/Cause/vector do not + // feed translation), so the per-CPU nutlb working set survives; only + // re-derive the cached translators in that case. + let tlb_flush = (old_status ^ self.core.cp0_status) + & crate::cpu::mips_core::TRANSLATION_STATUS_MASK != 0; + self.resync_privilege_state_filtered(tlb_flush); // `deliver_exception` clears in_delay_slot itself — see its doc comment. status } @@ -4929,8 +4936,11 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", if status & EXEC_IS_CACHE_ERR != 0 { self.core.cp0_cacheerr = self.cache.take_cache_err(); } + let old_status = self.core.cp0_status; crate::cpu::mips_core::deliver_exception_at(&mut self.core, status, fault_pc, bd); - self.resync_privilege_state(); + let tlb_flush = (old_status ^ self.core.cp0_status) + & crate::cpu::mips_core::TRANSLATION_STATUS_MASK != 0; + self.resync_privilege_state_filtered(tlb_flush); status } @@ -4946,8 +4956,11 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", fn handle_exception_syscall(&mut self, status: ExecStatus) -> ExecStatus { self.cache.set_llbit(false); self.core.syscall_pending = true; + let old_status = self.core.cp0_status; crate::cpu::mips_core::deliver_exception(&mut self.core, status); - self.resync_privilege_state(); + let tlb_flush = (old_status ^ self.core.cp0_status) + & crate::cpu::mips_core::TRANSLATION_STATUS_MASK != 0; + self.resync_privilege_state_filtered(tlb_flush); status } @@ -7673,8 +7686,9 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", } else { rt_val as u32 as i32 as i64 as u64 }; + let old_entryhi = self.core.cp0_entryhi; self.core.write_cp0(rd_val, value); - self.handle_cp0_side_effects(rd_val); + self.handle_cp0_side_effects(rd_val, old_entryhi); self.handle_exec_complete() } @@ -7682,12 +7696,13 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", fn exec_dmtc0(&mut self, d: &DecodedInstr) -> ExecStatus { let rt_val = self.core.read_gpr(d.rt as u32); let rd_val = d.rd as u32; + let old_entryhi = self.core.cp0_entryhi; self.core.write_cp0(rd_val, rt_val); - self.handle_cp0_side_effects(rd_val); + self.handle_cp0_side_effects(rd_val, old_entryhi); self.handle_exec_complete() } - fn handle_cp0_side_effects(&mut self, reg: u32) { + fn handle_cp0_side_effects(&mut self, reg: u32, old_entryhi: u64) { // EntryHi (reg 10) carries the current ASID in bits [7:0]. The nanotlb // tags hold only a VA, so their validity depends on the ASID that was // live when they were filled. Every *other* invalidation site is a @@ -7710,8 +7725,14 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", if reg == 10 { // Flushes the nutlb too — its tags carry no ASID, so entries // filled under the old one would otherwise stay live and resolve - // to the wrong address space. - self.nanotlb_invalidate(); + // to the wrong address space. Only the ASID bits (7:0) can + // change a cached translation: the VPN2/region bits are not in a + // nutlb tag. A refill write that keeps the ASID — the common + // case on IRIX — therefore needs no barrier at all. + const ASID_MASK: u64 = 0xFF; + if (old_entryhi ^ self.core.cp0_entryhi) & ASID_MASK != 0 { + self.nanotlb_invalidate(); + } } // Config (reg 16), K0 field (bits 2:0): KSEG0's cache attribute, read // by `kseg0_cache_attr` on every KSEG0/ckseg0 translation. @@ -7811,6 +7832,7 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", let g_bit = (entry.entry_hi >> 12) & 1; // Write to CP0 registers, clearing G bit from EntryHi + let old_entryhi = self.core.cp0_entryhi; self.core.cp0_entryhi = entry.entry_hi & !0x1000; // Clear bit 12 (G bit) self.core.cp0_entrylo0 = (entry.entry_lo[0] & !1) | g_bit; // Set G bit from EntryHi self.core.cp0_entrylo1 = (entry.entry_lo[1] & !1) | g_bit; // Set G bit from EntryHi @@ -7821,8 +7843,13 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", // though the TLB itself is untouched. Same hazard as `MTC0 EntryHi` // (see handle_cp0_side_effects): no privilege transition accompanies // a TLBR, so without this flush a stale nanotlb slot filled under the - // old ASID stays live. Cold path. - self.nanotlb_invalidate(); + // old ASID stays live. Cold path. Skip the barrier when the read + // entry kept the same ASID: nothing a cached translation depends on + // moved (the TLB itself was not written). + const ASID_MASK: u64 = 0xFF; + if (old_entryhi ^ self.core.cp0_entryhi) & ASID_MASK != 0 { + self.nanotlb_invalidate(); + } if mips_log(MIPS_LOG_TLB) { dlog_dev!(LogModule::Mips, "TLBR: Read Index {}\n{}", index, self.tlb.format_entry(index)); } diff --git a/src/cpu/mips_exec_test.rs b/src/cpu/mips_exec_test.rs index f57244e91..6756e7a6f 100644 --- a/src/cpu/mips_exec_test.rs +++ b/src/cpu/mips_exec_test.rs @@ -1165,6 +1165,38 @@ mod tests { 0xAAAAAAAA means a stale nanotlb slot survived the switch"); } + /// A `MTC0 EntryHi` that keeps the ASID is not a barrier: only the ASID + /// bits [7:0] feed a cached translation, so a refill write that changes + /// VPN2/region must leave the nutlb working set intact. + #[cfg(feature = "tlbstats")] + #[test] + fn test_mtc0_entryhi_with_same_asid_keeps_the_nutlb() { + std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(|| { test_mtc0_entryhi_with_same_asid_keeps_the_nutlb_inner(); }) + .unwrap().join().unwrap(); + } + #[cfg(feature = "tlbstats")] + fn test_mtc0_entryhi_with_same_asid_keeps_the_nutlb_inner() { + use crate::cpu::mips_tlb::MipsTlb; + + let (mut exec, mem) = create_executor_with_tlb(MipsTlb::default()); + setup_asid_aliased_page(&mut exec, &mem); + + // A different VPN2 with the same ASID 10: a real register write, no + // ASID change, therefore no flush. + exec.core.write_gpr(8, (2 << 13) | 10); + let mtc0_entryhi = (OP_COP0 << 26) | (0x04 << 21) | (8 << 16) | (10 << 11); + assert_eq!(exec.exec(mtc0_entryhi), EXEC_COMPLETE); + assert_eq!(exec.core.cp0_entryhi & 0xFF, 10); + + let at = crate::cpu::mips_tlb::AccessType::Read as usize; + let before = exec.tlb.stats.by_type[at].nutlb_hit; + assert_eq!(exec.read_data::<4>(0x1000).unwrap(), 0xAAAA_AAAA); + assert_eq!(exec.tlb.stats.by_type[at].nutlb_hit - before, 1, + "same-ASID MTC0 EntryHi must not evict the cached translation"); + } + /// The nutlb must actually serve repeat accesses, not silently fall /// through to `translate_fn` every time. A structure that is never hit is /// indistinguishable from one that is absent — except in benchmark noise