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 } } }