Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions clanker/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
73 changes: 73 additions & 0 deletions clanker/jitv2/per-cpu-page-generation.md
Original file line number Diff line number Diff line change
@@ -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).
40 changes: 21 additions & 19 deletions src/cpu/jitv2/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 27 additions & 8 deletions src/cpu/jitv2/jitv2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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-
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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`
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down
22 changes: 20 additions & 2 deletions src/cpu/mips_cache_shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
/// Decoded instructions, by physical page. Never touches the shadow
/// arrays above — see `decode_cache`.
decode: UnsafeCell<crate::cpu::decode_cache::DecodeCache>,
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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);
}
}
}
}
Expand Down Expand Up @@ -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:
Expand Down
27 changes: 24 additions & 3 deletions src/cpu/mips_cache_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<u8>,
}

unsafe impl<const IC_SIZE: usize, const IC_LINE: usize, const IC_WAYS: usize, const IC_TAGS: usize,
Expand Down Expand Up @@ -1665,6 +1673,8 @@ impl<const IC_SIZE: usize, const IC_LINE: usize, const IC_WAYS: usize, const IC_
tc_bitmap: AtomicU64::new(0),
#[cfg(feature = "jitv2")]
tc_gen: UnsafeCell::new(std::ptr::null_mut()),
#[cfg(feature = "jitv2")]
jit_cpu_id: UnsafeCell::new(0),
#[cfg(feature = "r5ksc_triton")]
l2_enabled: false, // starts disabled; PROM enables via CONFIG_SE
// Const-guarded: a direct-mapped model allocates none of these.
Expand Down Expand Up @@ -1778,9 +1788,15 @@ impl<const IC_SIZE: usize, const IC_LINE: usize, const IC_WAYS: usize, const IC_
{
let g = unsafe { *self.tc_gen.get() };
if !g.is_null() {
let page = (_phys_addr >> 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);
}
}
}
}
Expand Down Expand Up @@ -3605,6 +3621,11 @@ impl<const IC_SIZE: usize, const IC_LINE: usize, const IC_WAYS: usize, const IC_
unsafe { self.set_tcache_gen_window_impl(gen_base) }
}

#[cfg(feature = "jitv2")]
fn set_jit_cpu_id(&self, cpu: u8) {
unsafe { *self.jit_cpu_id.get() = cpu };
}

const IC_SIZE: usize = IC_SIZE;
const IC_LINE: usize = IC_LINE;
const IC_WAYS: usize = IC_WAYS;
Expand Down
3 changes: 3 additions & 0 deletions src/cpu/mips_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3268,6 +3268,9 @@ impl<T: Tlb, C: CpuModel> MipsExecutor<T, C> {
/// 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
Expand Down
Loading
Loading