From 9b481b96b5f3900bdb4cd020c5c3f26f945ef710 Mon Sep 17 00:00:00 2001 From: steigr Date: Fri, 20 Nov 2026 01:14:08 +0100 Subject: [PATCH 1/2] jitv2: park a lone cpu for a worker's flush instead of halting it A compile worker that filled its arena led a flush by calling cpu.stop() on a CPU with a pool of its own, which joins the CPU thread. If that CPU ran out of JIT pages in the meantime, it was in flush_from_cpu_thread, holding Mutex and joining the worker: each waited for the other. j2 flush and j2 inline on from the monitor hung the same way, on the executor or the Jitv2 lock. Machines with several CPUs on one pool already took turns through World; a lone CPU's pool had none. Every pool now flushes through the world of its CPUs. attach_pool takes the machine's world, and every machine passes it: the Indy, Indigo2 and O2 (whose worlds carried only remap requests), the Octane and Tezro with one CPU, and every pool share_pool builds, also a lone processor's or a node whose module has a pool of its own. Each CPU on the pool shares it with share_jitv2, which now sets the world on the pool as well, so the CPU's stop_others and the worker's try_lead take turns on one world. A CPU belongs to one world, since two would both hold it with HOLD_WORLD. MipsCpu::new gives every CPU a World::solo until a machine replaces it, for CPUs built without one. The worker then parks the CPU and gives way if the pool stops, and the CPU's own flush, inside stop_others, counts as parked while it waits its turn. A worker's flush also no longer restarts a CPU the monitor has stopped. j2 inline on stops the pool through Jitv2::stop_pool, which joins with the lock released. The start-up half of #306 (workers taking the lock to read the cache geometry) was fixed in 95031882. New test a_cpu_flush_inside_a_worker_led_flush_takes_its_turn forces a worker flush (a test-only PoolBarrier hook) against a CPU that flushes the moment it is held. Without the world it times out after 20 s; with it, it passes in under 0.1 s. Fixes #306. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + HACKING.md | 15 +- clanker/INDEX.md | 1 + ...pile-workers-park-the-cpu-never-halt-it.md | 48 +++++ src/cpu/jitv2/jitv2.rs | 173 +++++++++++++++--- src/cpu/jitv2/pool_barrier.rs | 18 ++ src/cpu/mips_exec.rs | 34 +++- src/cpu/mips_exec/monitor.rs | 9 +- src/cpu/smp.rs | 36 ++++ src/ip30_machine.rs | 12 +- src/ip32_machine.rs | 7 +- src/machine.rs | 5 +- 12 files changed, 321 insertions(+), 44 deletions(-) create mode 100644 clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md diff --git a/CHANGELOG.md b/CHANGELOG.md index dc0b61566..847111d6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,13 @@ hashes are given where a change is easiest to understand by reading the commit. ## November 2026 +### jitv2 flushes + +- Under jitv2, a single-processor machine no longer hangs when the CPU runs out + of JIT pages (or `j2 flush`, `j2 inline on` or a cache change on the O2 asks + for a flush) while a compile worker is flushing its full code arena. A + worker's flush no longer restarts a CPU the monitor has stopped. + ### Volume headers - `mkvh build` splits an ELF executable's segments larger than 512 KB, so the diff --git a/HACKING.md b/HACKING.md index ffa1e90f2..c5aa9d50a 100644 --- a/HACKING.md +++ b/HACKING.md @@ -543,7 +543,11 @@ one `Physical`. `src/cpu/smp.rs` holds what they share: on. Two callers take turns, and the one waiting counts as parked. Remapping memory and flushing jitv2 go through it. A remap that moved memory then asks every CPU (`World::layout_changed`) to forget the addresses of its JIT code - pages; no compiled code is dropped for it (section 8). + pages; no compiled code is dropped for it (section 8). A CPU belongs to one + `World`: every machine hands its world to its CPUs' jitv2 pool + (`share_jitv2`, `attach_pool`), and a CPU built without one (in a test) gets + a world of one (`World::solo`, in `MipsCpu::new`), so its pool's flushes and + its own take turns the same way. The monitor reaches CPUs through `CpuMonitor` (`src/cpu/cpu_monitor.rs`), on every machine: it routes each command and the commands themselves live in @@ -1403,6 +1407,15 @@ code into host code with Cranelift. The concepts: and stores are plain host accesses, so on a multiprocessor a guest `SYNC` compiles to a host fence on hosts that are not x86 (the interpreter's `SYNC` does the same). +- **Flushes take turns through the CPU's world.** A CPU flushes from inside + `World::stop_others` and joins the compile workers there, holding the + `Jitv2` lock. A worker that leads a flush takes the world with `try_lead`, + parks the CPUs, and only then takes the `Jitv2` lock; it gives way if the + pool stops while it waits. So a worker never halts a CPU thread (which may + be joining that worker) and never waits on the lock a joining thread holds. + Workers get their start-up data (cache geometry, JIT constants) before they + spawn, for the same reason. A thread that runs no CPU stops the pool with + `Jitv2::stop_pool`, which joins with the lock released. - **Uncached fetches the board decodes apart.** A frame table is indexed by the physical address of the fetch. The IP35 reset PROM answers an uncached fetch at 0x1fc00000 whatever RAM sits behind the cached view there, so a board whose diff --git a/clanker/INDEX.md b/clanker/INDEX.md index f8a4ad931..18d2f0ac8 100644 --- a/clanker/INDEX.md +++ b/clanker/INDEX.md @@ -69,6 +69,7 @@ The MIPS JIT (`src/cpu/jitv2/`): design, Cranelift codegen, delay slots, invalid | [code-size-does-not-predict-speed.md](jitv2/code-size-does-not-predict-speed.md) | measure | Emitted-code size did not predict speed — four changes, one marginal win | | [codegen-gotchas.md](jitv2/codegen-gotchas.md) | rule | JIT v2 codegen gotchas | | [compile-pool-size-on-small-hosts.md](jitv2/compile-pool-size-on-small-hosts.md) | rule | The compile pool is sized for the host as well as the guest: one worker per guest CPU, capped by the host's usable CPUs; the guest's own CPUs are not counted against it | +| [compile-workers-park-the-cpu-never-halt-it.md](jitv2/compile-workers-park-the-cpu-never-halt-it.md) | rule | A compile worker parks the CPU for a flush through the CPU's world, never halts it; every CPU has one world (`World::solo` when alone) | | [compile-pool-starts-after-the-windows.md](jitv2/compile-pool-starts-after-the-windows.md) | rule | Start the compile pool after the ppmem windows: workers read the cache geometry once, and an early one compiles every load and store as a call out | | [compile-workers-park-instead-of-polling.md](jitv2/compile-workers-park-instead-of-polling.md) | rule | The compile pool parks; the producer wakes it: an idle worker cost 1.4% of a core polling every 200µs | | [compile-time-profile.md](jitv2/compile-time-profile.md) | measure | An IRIX boot is bound by how much jitv2 compiles: workers saturated, where a compile's time goes (regalloc 37%, egraph 20%), and why a faster allocator or `opt_level=none` only buys more recompiles | diff --git a/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md b/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md new file mode 100644 index 000000000..9c2f30d99 --- /dev/null +++ b/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md @@ -0,0 +1,48 @@ +# A compile worker parks the CPU for a flush; it never halts it + +Status: rule (issue #306, November 2026). + +**Symptom.** A single-CPU machine under jitv2 hangs: the CPU thread sits in +`CompileQueue::stop` (inside `flush_from_cpu_thread`, holding `Mutex`), +joining a compile worker, and that worker sits in `run_leader_flush`, in +`cpu.stop()` → `MipsCpu::halt`, joining the CPU thread (or, when the monitor +holds the executor, waiting for the executor lock, or for `Mutex`). + +**Cause.** Two flushes, two leaders. The CPU flushes when its page pool runs +out (or for `j2 flush`, a cache-geometry change); a worker flushes when its +code arena fills. On a machine with several CPUs the two already took turns +through `World` (`stop_others` on the CPU side, `try_lead` plus a poll of the +pool's run flag on the worker side). A CPU with its own pool had no world, so +the worker stopped it with `Device::stop`, which joins the very thread that +may be joining the worker. + +The start-up half of #306 (a worker taking `Mutex` to read +`dc_geometry` / `jit_consts`) was fixed earlier, in 95031882: workers get those +values before they spawn. + +**Rule.** + +- Every `MipsCpu` has a world: `MipsCpu::new` gives it `World::solo(park)` + and sets it on the executor (`jitv2_world`) and on its own pool. + `share_jitv2` replaces it, on the pool too. +- A CPU belongs to one world. Two worlds would both hold it with + `HOLD_WORLD`, and one's release would let it run under the other. Every + machine now has a world of its own (bank remaps call `layout_changed` on + it), so every machine passes it through `share_jitv2` and `attach_pool`, + also to a lone CPU and to a node whose processor module has a pool of its + own (`share_pool`). The pool and the CPU must hold the same world: with two, + the CPU's `stop_others` and the worker's `try_lead` do not take turns and + the deadlock is back. `World::solo` remains for CPUs built without a + machine, in tests. +- A world finds the caller's slot by the CPU id the slot records + (`ParkSlot::new(cpu, ..)`), so a world of CPU 3 alone works too. +- A thread that runs no CPU stops the pool with `Jitv2::stop_pool`, which + joins with `Mutex` released. `CompileQueue::stop` under the lock is + for the CPU side, inside `stop_others`. +- The `cpu.stop()`/`cpu.start()` branch of `run_leader_flush` remains only for + a bare `CompileQueue` in tests. + +**Test.** `a_cpu_flush_inside_a_worker_led_flush_takes_its_turn` (jitv2.rs) +forces a worker flush (`PoolBarrier::force_flush`, test-only) against a fake +CPU that flushes the moment it is held. Without the world it deadlocks and the +test fails after 20 s. diff --git a/src/cpu/jitv2/jitv2.rs b/src/cpu/jitv2/jitv2.rs index 76e3e23f5..844afed8b 100644 --- a/src/cpu/jitv2/jitv2.rs +++ b/src/cpu/jitv2/jitv2.rs @@ -2773,6 +2773,22 @@ impl Jitv2 { g.buses().clear(); } + /// Stop the compile pool from a thread that runs no CPU (the monitor's + /// `j2 inline on`) and hand back the workers' `Codegen`s, as + /// `CompileQueue::stop` does, but join them with `jit` unlocked: a worker + /// leading a flush takes that lock, and would wait on it for ever. + pub fn stop_pool(jit: &Mutex) -> Vec { + let workers = { + let mut g = jit.lock(); + g.compile_queue.barrier.stop(); + std::mem::take(&mut g.compile_queue.threads) + }; + let stopped = workers.into_iter().filter_map(|w| w.join().ok()).collect(); + jit.lock().compile_queue.drain_pending_queue(); + crate::cpu::jit_feedback::JIT_FEEDBACK.set_queue_fill(0, COMPILE_QUEUE_CAPACITY); + stopped + } + /// Allocate the full page pool up front, `capacity` slots, every one /// starting unclaimed (`PhysicalCodePage::new(UNCLAIMED_PFN, null)`) — /// see `Jitv2`'s own doc comment for why this is a single one-shot @@ -3246,13 +3262,15 @@ pub fn start_compiling( } /// Give `cpu`'s JIT its compile pool and start compiling as `mode` asks, -/// reading code through `bus`. Under lockstep no pool starts. +/// reading code through `bus`. The pool's flushes park the CPUs through +/// `world`, the machine's, which every CPU on the pool shares +/// (`CpuDevice::share_jitv2`). Under lockstep no pool starts. pub fn attach_pool( cpu: &Arc, (threads, threads_reason): (usize, String), mode: crate::config::JitCompile, bus: Arc, - world: Option>, + world: Arc, ) { // Weak handles only: a strong one would keep the board alive after the machine. let device: Arc = cpu.clone().as_device(); @@ -3262,9 +3280,7 @@ pub fn attach_pool( g.compile_queue.set_thread_count_with_reason(threads.max(1), &threads_reason); g.compile_queue.set_cpu(Arc::downgrade(&device)); g.compile_queue.set_owner(Arc::downgrade(&jit)); - if let Some(world) = world { - g.compile_queue.set_world(world); - } + g.compile_queue.set_world(world); } #[cfg(not(feature = "jitv2_lockstep"))] start_compiling(&**cpu, &jit, mode, bus); @@ -3306,20 +3322,20 @@ pub fn share_pool( continue; }; let several = group.iter().map(|n| n.cpus.len()).sum::() > 1; - if several { - if cfg!(feature = "jitv2_lockstep") { - return Err("several processors cannot run with jitv2_lockstep".into()); - } - let jit = lead.jitv2(); - let mut number = 0; - for (space, node) in group.iter().enumerate() { - for cpu in node.cpus { - cpu.share_jitv2(jit.clone(), world.clone(), number, space); - number += 1; - } + if several && cfg!(feature = "jitv2_lockstep") { + return Err("several processors cannot run with jitv2_lockstep".into()); + } + // A lone processor shares its own pool too, so the pool's flushes go + // through the machine's world: a CPU belongs to one. + let jit = lead.jitv2(); + let mut number = 0; + for (space, node) in group.iter().enumerate() { + for cpu in node.cpus { + cpu.share_jitv2(jit.clone(), world.clone(), number, space); + number += 1; } } - attach_pool(lead, pool_size.clone(), mode, group[0].bus.clone(), several.then(|| world.clone())); + attach_pool(lead, pool_size.clone(), mode, group[0].bus.clone(), world.clone()); } Ok(()) } @@ -3384,9 +3400,13 @@ pub struct CompileQueue { /// mid-teardown and there's nothing to stop/start anymore, which is fine /// to skip. cpu: Mutex>>, - /// With several CPUs sharing this pool, how a flush stops them all. `cpu` - /// is not used then: stopping and restarting one CPU's thread leaves the - /// others running, and would restart a CPU the monitor has stopped. + /// How a flush stops the CPUs this pool compiles for: it parks them, and + /// takes turns with their own flushes (`MipsExecutor::jitv2_flush_from_here`). + /// Every `MipsCpu` sets one, a world of one CPU when it shares its pool + /// with no other. `cpu` is not used then: stopping a CPU joins its thread, + /// which may itself be joining this pool for a flush of its own, and + /// restarting it would start a CPU the monitor has stopped. Without a + /// world (a bare `CompileQueue` in a test) the leader stops `cpu`. world: Mutex>>, /// Weak handle back to the owning `Jitv2` (behind whatever `Arc>` /// the caller shares it in) — the worker needs this to clear the page @@ -3575,7 +3595,7 @@ impl CompileQueue { *self.cpu.lock() = Some(cpu); } - /// Several CPUs share this pool: see the `world` field. + /// How a flush parks the CPUs on this pool: see the `world` field. pub fn set_world(&self, world: Arc) { *self.world.lock() = Some(world); } @@ -4001,9 +4021,10 @@ impl CompileQueue { // (flush_from_jit_thread's own doc comment), release before // cpu.start(). // - // Several CPUs: park them all instead, without blocking on a - // CPU that leads a flush of its own. That CPU joins this - // thread, so give way once the pool is stopping. + // With a world (every real CPU has one): park the CPUs + // instead, without blocking on a CPU that leads a flush of + // its own. That CPU joins this thread, so give way once the + // pool is stopping. let world_hold = match &world { Some(w) => loop { if let Some(hold) = w.try_lead() { @@ -4142,6 +4163,11 @@ impl CompileQueue { } continue; } + #[cfg(all(test, not(loom)))] + if barrier.take_forced_flush() { + try_flush(&mut codegen, &function_count, &mut pending); + continue; + } // The hot lane first: pages being executed right now that are // still waiting (see `CompileQueue::hot`). match hot.pop().or_else(|| queue.pop()) { @@ -5797,6 +5823,105 @@ mod tests { assert!(!stamped.is_empty() && stamped.iter().all(|&s| s), "a restarted worker missed the published constants: {stamped:?}"); } + /// A CPU thread as a compile pool sees one: it parks while held, and + /// stops the way `MipsCpu::halt` does, with the park bit and a join. The + /// first time it is held it flushes the pool itself instead, as a CPU whose + /// page pool runs out just as a worker leads an arena flush would. + struct FlushingCpu { + word: Arc, + slot: Arc, + running: Arc, + flushes: Arc, + thread: Mutex>>, + } + + impl FlushingCpu { + fn start(jit: Arc>, world: Option>, bus: Arc, word: Arc, slot: Arc) -> Arc { + use crate::cpu::smp::HOST_PARK_BIT; + let cpu = Arc::new(Self { word: word.clone(), slot: slot.clone(), running: Arc::new(AtomicBool::new(true)), flushes: Arc::new(AtomicU32::new(0)), thread: Mutex::new(None) }); + let (running, flushes) = (cpu.running.clone(), cpu.flushes.clone()); + slot.set_active(true); + *cpu.thread.lock() = Some(std::thread::spawn(move || { + crate::cpu::smp::set_current_cpu(0); + while running.load(Ordering::SeqCst) { + if word.load(Ordering::SeqCst) & HOST_PARK_BIT == 0 { + std::thread::yield_now(); + } else if flushes.load(Ordering::SeqCst) == 0 { + // `MipsExecutor::jitv2_flush_from_here`. + let flush = || unsafe { jit.lock().flush_from_cpu_thread(bus.clone()) }; + match &world { + Some(w) => w.stop_others(flush), + None => flush(), + } + flushes.fetch_add(1, Ordering::SeqCst); + } else { + slot.park(&running); + } + } + slot.set_active(false); + })); + cpu + } + } + + impl Device for FlushingCpu { + fn step(&self, _cycles: u64) {} + fn stop(&self) { + self.running.store(false, Ordering::SeqCst); + self.word.fetch_or(crate::cpu::smp::HOST_PARK_BIT, Ordering::SeqCst); + if let Some(t) = self.thread.lock().take() { + let _ = t.join(); + } + self.word.fetch_and(!crate::cpu::smp::HOST_PARK_BIT, Ordering::SeqCst); + } + fn start(&self) {} + fn is_running(&self) -> bool { self.running.load(Ordering::SeqCst) } + fn get_clock(&self) -> u64 { 0 } + } + + /// A worker leads an arena flush and stops the CPU; the CPU, before it + /// stops, flushes the pool itself and joins that worker (issue #306). + /// Stopping the CPU by halting it waits for the CPU thread while the CPU + /// thread waits for the worker. Through the CPU's world the worker parks + /// it instead, and the CPU waiting its turn to flush counts as parked, so + /// both flushes finish, one after the other. Run on a spawned thread so a + /// regression fails here instead of hanging the test binary. + #[test] + fn a_cpu_flush_inside_a_worker_led_flush_takes_its_turn() { + let epoch = crate::cpu::jitv2::hashstats::FLUSH_EPOCH.load(Ordering::SeqCst); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let dev: Arc = Arc::new(FakeDevice(AtomicU64::new(0))); + let jit = Arc::new(Mutex::new(Jitv2::new(4))); + let word = Arc::new(AtomicU64::new(0)); + let slot = Arc::new(crate::cpu::smp::ParkSlot::new(0, Arc::as_ptr(&word))); + let world = Arc::new(crate::cpu::smp::World::solo(slot.clone())); + let cpu = FlushingCpu::start(jit.clone(), Some(world.clone()), dev.clone(), word.clone(), slot); + let cpu_device: Arc = cpu.clone(); + { + let mut g = jit.lock(); + g.compile_queue.set_cpu(Arc::downgrade(&cpu_device)); + g.compile_queue.set_owner(Arc::downgrade(&jit)); + g.compile_queue.set_world(world); + let stats = g.stats.clone(); + g.compile_queue.start(dev, stats); + g.compile_queue.barrier.force_flush(); + } + while cpu.flushes.load(Ordering::SeqCst) == 0 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + cpu_device.stop(); + let restarted = !Jitv2::stop_pool(&jit).is_empty(); + let _ = done_tx.send(restarted); + drop(word); + }); + let restarted = done_rx.recv_timeout(std::time::Duration::from_secs(20)) + .expect("the CPU's flush and the worker's flush are waiting for each other"); + assert!(restarted, "the CPU's flush did not restart the pool"); + let flushes = crate::cpu::jitv2::hashstats::FLUSH_EPOCH.load(Ordering::SeqCst) - epoch; + assert!(flushes >= 2, "expected the worker's and the CPU's flush, saw {flushes}"); + } + /// Minimal `Device` (not `BusDevice`) stand-in for `CompileQueue::set_cpu` — /// tests that need `run_leader_flush`'s real flush path (not its /// no-cpu-wired recovery path) to actually run just need something a diff --git a/src/cpu/jitv2/pool_barrier.rs b/src/cpu/jitv2/pool_barrier.rs index d5c2d004a..ee2c17701 100644 --- a/src/cpu/jitv2/pool_barrier.rs +++ b/src/cpu/jitv2/pool_barrier.rs @@ -50,6 +50,10 @@ pub(crate) struct PoolBarrier { /// A cycle is in progress: set by the leader's election, cleared by its /// release. quiesce: AtomicBool, + /// Tests: the next worker to look leads an arena flush, as one that filled + /// its arena would. + #[cfg(all(test, not(loom)))] + forced_flush: AtomicBool, } impl PoolBarrier { @@ -59,9 +63,23 @@ impl PoolBarrier { cv: Condvar::new(), running: AtomicBool::new(false), quiesce: AtomicBool::new(false), + #[cfg(all(test, not(loom)))] + forced_flush: AtomicBool::new(false), } } + /// Tests: have a worker flush the arena at its next look. + #[cfg(all(test, not(loom)))] + pub(crate) fn force_flush(&self) { + self.forced_flush.store(true, Ordering::SeqCst); + } + + /// Tests: a flush was asked for; this caller takes it. + #[cfg(all(test, not(loom)))] + pub(crate) fn take_forced_flush(&self) -> bool { + self.forced_flush.swap(false, Ordering::SeqCst) + } + /// Mark the pool running, on the arena its workers are about to build on. pub(crate) fn start(&self, arena: A) { self.state.lock().arena = Some(arena); diff --git a/src/cpu/mips_exec.rs b/src/cpu/mips_exec.rs index 8c624246c..ea52b60b6 100644 --- a/src/cpu/mips_exec.rs +++ b/src/cpu/mips_exec.rs @@ -3624,6 +3624,7 @@ va={:#018x} phys={:#010x} (code pfn {:#x}, page {:#010x}, word {}/{})", { let mut j = jit.lock(); j.set_space(space, self.jitv2_frames as usize, self.jitv2_split); + j.compile_queue.set_world(world.clone()); self.jitv2_compile_queue_handle = j.compile_queue.queue_handle(); self.jitv2_hot_queue_handle = j.compile_queue.hot_handle(); self.jitv2_stats = j.stats.clone(); @@ -10712,6 +10713,19 @@ impl MipsCpu { let ppmem_bitmap_ptr = executor_arc.lock().ppmem_bitmap_ptr(); #[cfg(feature = "jitv2")] executor_arc.lock().install_jit_hooks(); + let park = Arc::new(crate::cpu::smp::ParkSlot::new(cpu_id, interrupts_ptr)); + // This CPU's own compile pool stops it the way a shared pool stops + // several: by parking it, and taking turns with the CPU's own flushes. + // Halting it instead joins the CPU thread, which may itself be joining + // the worker for a flush of its own. A machine whose CPUs share a pool, + // or that has a world of its own, replaces this one (`share_jitv2`). + #[cfg(feature = "jitv2")] + { + let mut exec = executor_arc.lock(); + let world = Arc::new(crate::cpu::smp::World::solo(park.clone())); + exec.jitv2.lock().compile_queue.set_world(world.clone()); + exec.jitv2_world = Some(world); + } Self { executor: executor_arc, @@ -10721,7 +10735,7 @@ impl MipsCpu { cycles_ptr, interrupts_ptr, ppmem_bitmap_ptr, - park: Arc::new(crate::cpu::smp::ParkSlot::new(cpu_id, interrupts_ptr)), + park, fasttick_count, debug: Arc::new(AtomicBool::new(false)), exception_mask: Arc::new(AtomicU32::new(0)), @@ -11266,9 +11280,10 @@ impl Device for MipsCpu Vec<(String, String)>; /// Where another thread holds this CPU still. fn park_slot(&self) -> Arc; - /// Use this page pool and compiled code, shared with the other CPUs, whose - /// flushes `world` coordinates. Before the CPU first runs. - #[cfg(feature = "jitv2")] - /// Run on `jit`, a pool other CPUs run on too, as its CPU number `cpu`, + /// Run on `jit`, a pool other CPUs may run on too, as its CPU number `cpu`, /// looking pages up in its address space `space` (the same for CPUs that - /// see memory at the same addresses, as the CPUs of one node do). + /// see memory at the same addresses, as the CPUs of one node do); `world` + /// coordinates the pool's flushes. Before the CPU first runs. `jit` may be + /// the CPU's own pool: a machine with a world of its own passes that world, + /// since a CPU belongs to one. + #[cfg(feature = "jitv2")] fn share_jitv2(&self, jit: Arc>, world: Arc, cpu: usize, space: usize); fn monitor_execute(&self, cmd: &str, args: &[&str], writer: Box) -> Result<(), String>; /// The symbol table this CPU's monitor commands and breakpoints resolve diff --git a/src/cpu/mips_exec/monitor.rs b/src/cpu/mips_exec/monitor.rs index 248331bb4..5a2ac2477 100644 --- a/src/cpu/mips_exec/monitor.rs +++ b/src/cpu/mips_exec/monitor.rs @@ -2001,13 +2001,16 @@ impl MipsCpu { // (non-reentrant) mutex — hanging the // console thread the instant `j2 inline on` // ran, before the CPU even started. + // + // Not joined under that lock either: a + // worker leading a flush takes it. { - let mut jit = exec.jitv2.lock(); - let stopped = jit.compile_queue.stop(); + let jit = exec.jitv2.clone(); + let stopped = crate::cpu::jitv2::Jitv2::stop_pool(&jit); if let Some(old) = stopped.into_iter().next() { let (shared, state) = old.shared_arena(); drop(old); - *jit.codegen.lock() = Some(crate::cpu::jitv2::codegen::Codegen::new_with_shared_arena(shared, state)); + *jit.lock().codegen.lock() = Some(crate::cpu::jitv2::codegen::Codegen::new_with_shared_arena(shared, state)); } } exec.jitv2_inline_compile = true; diff --git a/src/cpu/smp.rs b/src/cpu/smp.rs index 39fe70c3d..417a6f4d7 100644 --- a/src/cpu/smp.rs +++ b/src/cpu/smp.rs @@ -173,6 +173,9 @@ impl ParkSlot { } /// Every CPU's slot: how one thread gets the machine to itself. +/// +/// A CPU belongs to one `World`: two would both hold it with +/// [`HOLD_WORLD`], and either one's release would let it run under the other. #[derive(Default)] pub struct World { slots: OnceLock>>, @@ -184,6 +187,14 @@ impl World { Self::default() } + /// The world of one CPU that shares its compile pool with no other. Its + /// own flushes and its pool's then take turns as a machine's CPUs do. + pub fn solo(slot: Arc) -> Self { + let world = Self::default(); + world.set_slots(vec![slot]); + world + } + /// The machine's CPUs, once they exist. pub fn set_slots(&self, slots: Vec>) { let _ = self.slots.set(slots); @@ -382,6 +393,31 @@ mod tests { assert_ne!(word.load(Ordering::SeqCst) & HOST_PARK_BIT, 0); } + + /// A CPU with its own compile pool is in a world of one, whatever its id. + /// Its own thread has no one to hold; anyone else holds it. + #[test] + fn a_solo_world_holds_its_cpu_for_others_but_not_for_itself() { + let (s, word) = slot(3); + let world = Arc::new(World::solo(s.clone())); + s.set_active(true); + let mine = { + let world = world.clone(); + std::thread::spawn(move || { + set_current_cpu(3); + // Returns without waiting for itself to park. + world.stop_others(|| ()) + }) + }; + mine.join().unwrap(); + assert_eq!(word.load(Ordering::SeqCst) & HOST_PARK_BIT, 0); + s.set_active(false); + let hold = world.try_lead().expect("nobody leads"); + assert_ne!(word.load(Ordering::SeqCst) & HOST_PARK_BIT, 0, "a non-CPU leader holds the CPU"); + drop(hold); + assert_eq!(word.load(Ordering::SeqCst) & HOST_PARK_BIT, 0); + } + /// Both CPUs want the machine at once, as two CPUs running out of JIT pages /// together would. Each waits for the other unless a CPU waiting its turn /// counts as parked. diff --git a/src/ip30_machine.rs b/src/ip30_machine.rs index 6f3d7cfd0..776358825 100644 --- a/src/ip30_machine.rs +++ b/src/ip30_machine.rs @@ -565,11 +565,15 @@ impl OctaneMachine { let cpu = cpus[0].clone(); world.set_slots(cpus.iter().map(|c| c.park_slot()).collect()); // One page pool and one body of compiled code: it reaches each CPU's - // state through the core pointer it is called with. + // state through the core pointer it is called with. A lone CPU shares + // its own pool too, so its flushes go through this world: a CPU + // belongs to one. #[cfg(feature = "jitv2")] - if cpu_count > 1 { + { #[cfg(feature = "jitv2_lockstep")] - return Err("[machine] cpus = 2 cannot run with jitv2_lockstep".into()); + if cpu_count > 1 { + return Err("[machine] cpus = 2 cannot run with jitv2_lockstep".into()); + } let jit = cpu.jitv2(); // Every CPU sees memory at the same addresses: one address space. for (n, c) in cpus.iter().enumerate() { @@ -620,7 +624,7 @@ impl OctaneMachine { cfg.jitv2_pool_size(), cfg.jitv2.compile, phys.phys.clone(), - (cpu_count > 1).then(|| world.clone()), + world.clone(), ); // HEART's levels 0 to 4 are each CPU's IP2 to IP6. diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index 757f1e64a..0bc5c285b 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -264,7 +264,10 @@ impl O2Machine { Self::build_cpu::(memory.clone(), sysad, &timer_manager, arcs_fpu, count_hz, boot.clone(), part.prid())); let world = Arc::new(crate::cpu::smp::World::new()); world.set_slots(vec![cpu.park_slot()]); - bus.ram.set_world(world); + bus.ram.set_world(world.clone()); + // The CPU's pool flushes through this world too: a CPU belongs to one. + #[cfg(feature = "jitv2")] + cpu.share_jitv2(cpu.jitv2(), world.clone(), 0, 0); // ppmem: the CPU's cache and the JIT reach RAM through a cached view // of the memory's window, publishing its bitmap into the CPU's own @@ -291,7 +294,7 @@ impl O2Machine { // geometry once, as it starts, and without the windows that geometry // has no inline load or store path. #[cfg(feature = "jitv2")] - crate::cpu::jitv2::jitv2::attach_pool(&cpu, cfg.jitv2_pool_size(), cfg.jitv2.compile, bus.phys.clone(), None); + crate::cpu::jitv2::jitv2::attach_pool(&cpu, cfg.jitv2_pool_size(), cfg.jitv2.compile, bus.phys.clone(), world); // CRIME's output is the CPU's IP2, pushed the moment it changes. bus.mace.ust.use_host_clock(); diff --git a/src/machine.rs b/src/machine.rs index 68d6e484c..53535a26d 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -963,6 +963,9 @@ impl Machine { status.set_count_hz(cpu.count_hz_atomic()); world.set_slots(vec![cpu.park_slot()]); + // The CPU's pool flushes through this world too: a CPU belongs to one. + #[cfg(feature = "jitv2")] + cpu.share_jitv2(cpu.jitv2(), world.clone(), 0, 0); // Connect CPU to MC and IOC for signaling let cpu_device: Arc = cpu.clone().as_device(); mc.set_cpu(Arc::downgrade(&cpu_device)); @@ -1021,7 +1024,7 @@ impl Machine { // default, so this can only happen here, after `Arc::new(MipsCpu::new(..))`, // same reasoning as `mc.set_cpu` right above). #[cfg(feature = "jitv2")] - crate::cpu::jitv2::jitv2::attach_pool(&cpu, (jitv2_threads, jitv2_threads_reason), jitv2_compile, phys.clone(), None); + crate::cpu::jitv2::jitv2::attach_pool(&cpu, (jitv2_threads, jitv2_threads_reason), jitv2_compile, phys.clone(), world.clone()); // Setup DevLog (must be before Monitor so log command is available) let devlog = crate::devlog::init_devlog(); From c65c77b5803733b31875703714215d51c5aa9dee Mon Sep 17 00:00:00 2001 From: steigr Date: Sun, 22 Nov 2026 02:28:54 +0100 Subject: [PATCH 2/2] tools: race a monitor j2 flush against the compile workers' flushes tools/jitv2-flush-race.py boots a single-CPU guest under --ci with IRIS_JIT_ARENA_FLUSH_MB=1, so the compile workers lead flushes of their own throughout the boot, and loops stop / j2 flush / start at the monitor. A j2 flush that does not return within --cmd-timeout is the deadlock of #306; the script then saves every thread's stack (--stacks) and kills iris, whose disk overlay --ci keeps in $TMPDIR. On the Indigo2 R10000 with IRIX 6.5.22, upstream bd81b637 hung both times (after 22 rounds in 73 s, and after 1 round during the PROM's diagnostics): the monitor thread joining jitv2-compile-0 inside CompileQueue::stop, the worker in MipsCpu::halt waiting for the executor lock the monitor holds. With the fix it ran 1115 rounds in 600 s with 1234 worker-led flushes, and the guest reached its login prompt. TESTING.md describes it. Co-Authored-By: Claude Opus 5.5 --- TESTING.md | 21 ++ ...pile-workers-park-the-cpu-never-halt-it.md | 9 + tools/jitv2-flush-race.py | 240 ++++++++++++++++++ 3 files changed, 270 insertions(+) create mode 100755 tools/jitv2-flush-race.py diff --git a/TESTING.md b/TESTING.md index edc312b0f..8d27ea207 100644 --- a/TESTING.md +++ b/TESTING.md @@ -768,6 +768,27 @@ registers where it stopped (on the O2, also the words at physical 0x1000 and 0x4000). [clanker/testing/ci-unattended-irix-boot.md](clanker/testing/ci-unattended-irix-boot.md) has the details. +## jitv2 flush race + +`tools/jitv2-flush-race.py` boots a single-CPU guest under `--ci` with +`IRIS_JIT_ARENA_FLUSH_MB=1`, so the compile workers fill their code arena and +flush it themselves many times during the boot, and meanwhile runs `stop`, +`j2 flush`, `start` at the monitor in a loop. Each `j2 flush` joins the compile +workers; one that waits on a worker leading a flush of its own never returns, +and the script fails with exit status 1 (and, given `--stacks`, saves every +thread's stack first). It passes when the race ran for `--seconds` with at +least `--min-worker-flushes` worker-led flushes, and reports how far the guest +got on its serial log. + +```sh +tools/jitv2-flush-race.py --iris target/release/iris --config ci-ip28.toml \ + --monitor-port 20300 --seconds 600 --serial-log console.log --stacks stacks.txt +``` + +The config is any `iris.toml` for a machine that boots by itself, its disks +with `overlay = true`: under `--ci` the overlay is kept in `$TMPDIR`, which is +what makes it safe for the script to kill an iris that hung. + ## Disk persistence on exit `src/exit_persistence_tests.rs` builds the Indy, Indigo2, Indigo2 IMPACT, O2, diff --git a/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md b/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md index 9c2f30d99..cfa319904 100644 --- a/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md +++ b/clanker/jitv2/compile-workers-park-the-cpu-never-halt-it.md @@ -46,3 +46,12 @@ values before they spawn. forces a worker flush (`PoolBarrier::force_flush`, test-only) against a fake CPU that flushes the moment it is held. Without the world it deadlocks and the test fails after 20 s. + +**End to end.** `tools/jitv2-flush-race.py` (see `TESTING.md`) boots a guest +with `IRIS_JIT_ARENA_FLUSH_MB=1` and loops `stop` / `j2 flush` / `start` at the +monitor. On the Indigo2 R10000 with IRIX 6.5.22, before the fix `j2 flush` +hung after 22 rounds (73 s) and after 1 round (during PROM diagnostics): the +monitor thread in `CompileQueue::stop` joining `jitv2-compile-0`, the worker in +`MipsCpu::halt` waiting for the executor lock the monitor holds. With the fix +it ran 1115 rounds in 600 s, 1234 worker-led flushes, and the guest reached its +login prompt. diff --git a/tools/jitv2-flush-race.py b/tools/jitv2-flush-race.py new file mode 100755 index 000000000..be936f2ea --- /dev/null +++ b/tools/jitv2-flush-race.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Race a monitor `j2 flush` against the compile workers' own flushes (#306). + +Boots a guest in iris under `--ci`, with `IRIS_JIT_ARENA_FLUSH_MB` set low so +the compile workers fill their code arena and lead flushes of their own while +the guest boots. Meanwhile it asks the monitor, over and over, to `stop` the +CPU, `j2 flush` and `start` it again. A flush the monitor asks for runs on the +monitor's thread with the jitv2 lock held and joins the compile workers; a +worker leading a flush at that moment must not wait on that lock, or the +monitor command never returns. + + tools/jitv2-flush-race.py --iris target/release/iris --config ci.toml \\ + --seconds 600 --serial-log console.log + +The config is an ordinary iris.toml for a single-CPU machine that boots on its +own. Give its disks `overlay = true`: under `--ci` the overlay lives in +`$TMPDIR` and the base image is never written. Give it a serial log to report +how far the guest got. Monitor, CI socket and any port forwards must not +collide with another iris. + +Exit status: 0 when every command returned and the workers flushed at least +`--min-worker-flushes` times; 1 when a monitor command did not return within +`--cmd-timeout` (the deadlock); 2 when the run did not exercise the race +(too few worker flushes) or iris failed to start. + +A hung iris cannot shut down; the harness then kills it. That is safe only +because `--ci` keeps the disk overlay in `$TMPDIR`: do not point this at a +config whose disks iris writes directly. +""" +import argparse +import json +import os +import random +import re +import signal +import socket +import subprocess +import sys +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from importlib import import_module + +Monitor = import_module("mon").Monitor + + +class Log: + """iris's stderr and stdout, copied to a file, with the flush lines counted.""" + + def __init__(self, proc, path): + self.worker = 0 + self.cpu = 0 + self.lines = 0 + self.out = open(path, "w") + self.t = threading.Thread(target=self._read, args=(proc.stdout,), daemon=True) + self.t.start() + + def _read(self, pipe): + for raw in iter(pipe.readline, b""): + line = raw.decode("latin-1", "replace") + self.out.write(line) + self.out.flush() + self.lines += 1 + if "mega_flush (from jit thread)" in line: + self.worker += 1 + elif "mega_flush (from cpu thread)" in line: + self.cpu += 1 + + +def ci_send(addr, cmd, args=None, timeout=60): + """One request to iris's CI socket (`tcp:HOST:PORT` or a Unix path).""" + if addr.startswith("tcp:"): + host, port = addr[4:].rsplit(":", 1) + s = socket.create_connection((host, int(port)), timeout=timeout) + else: + s = socket.socket(socket.AF_UNIX) + s.settimeout(timeout) + s.connect(addr) + with s: + s.sendall((json.dumps({"cmd": cmd, "args": args or {}}) + "\n").encode()) + buf = b"" + while not buf.endswith(b"\n"): + chunk = s.recv(65536) + if not chunk: + break + buf += chunk + return json.loads(buf or b"{}") + + +def connect_monitor(port, deadline, proc): + while time.time() < deadline: + if proc.poll() is not None: + return None + try: + return Monitor(port=port, timeout=10) + except OSError: + time.sleep(0.5) + return None + + +def last_serial_line(path): + try: + with open(path, "rb") as f: + f.seek(0, os.SEEK_END) + f.seek(max(0, f.tell() - 4096)) + text = f.read().decode("latin-1", "replace") + except OSError: + return "" + lines = [l.strip() for l in re.split(r"[\r\n]+", text) if l.strip()] + return lines[-1] if lines else "" + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--iris", required=True, help="iris binary built with --features jitv2") + ap.add_argument("--config", required=True) + ap.add_argument("--seconds", type=float, default=600, help="how long to race") + ap.add_argument("--arena-mb", type=int, default=1, help="IRIS_JIT_ARENA_FLUSH_MB") + ap.add_argument("--monitor-port", type=int, default=8888) + ap.add_argument("--ci-socket", help="CI socket for the clean quit (default: the config's or iris's)") + ap.add_argument("--cmd-timeout", type=float, default=60, help="a monitor command slower than this is a hang") + ap.add_argument("--min-pause", type=float, default=0.05) + ap.add_argument("--max-pause", type=float, default=1.0) + ap.add_argument("--min-worker-flushes", type=int, default=5) + ap.add_argument("--serial-log", help="the config's serial log, to report the guest's progress") + ap.add_argument("--log", default="jitv2-flush-race.log", help="where iris's output goes") + ap.add_argument("--stacks", help="on a hang, save every thread's stack here before killing iris") + ap.add_argument("--seed", type=int, default=306) + a = ap.parse_args() + random.seed(a.seed) + + env = dict(os.environ, IRIS_JIT_ARENA_FLUSH_MB=str(a.arena_mb)) + argv = [a.iris, "--config", a.config, "--ci", "--headless", "--monitor-port", str(a.monitor_port)] + if a.ci_socket: + argv += ["--ci-socket", a.ci_socket] + proc = subprocess.Popen(argv, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + log = Log(proc, a.log) + mon = connect_monitor(a.monitor_port, time.time() + 120, proc) + if mon is None: + print(f"FAIL: no monitor on port {a.monitor_port} (iris exit {proc.poll()}); see {a.log}") + if proc.poll() is None: + proc.kill() + return 2 + mon.s.settimeout(a.cmd_timeout) + + rounds, hung, error = 0, None, None + start = time.time() + try: + mon.cmd("start") + while time.time() - start < a.seconds: + time.sleep(random.uniform(a.min_pause, a.max_pause)) + for c in ("stop", "j2 flush", "start"): + t0 = time.time() + try: + out = mon.cmd(c) + except socket.timeout: + hung = (c, time.time() - t0) + break + if c == "j2 flush" and "flush complete" not in out: + error = f"`j2 flush` said: {out!r}" + break + if hung or error: + break + rounds += 1 + if rounds % 50 == 0: + print(f" {time.time() - start:6.0f}s rounds {rounds} worker flushes {log.worker} cpu-side flushes {log.cpu}", flush=True) + except (ConnectionError, OSError) as e: + error = f"monitor connection lost: {e}" + + elapsed = time.time() - start + print(f"rounds {rounds} in {elapsed:.0f}s; worker-led flushes {log.worker}; cpu-side flushes {log.cpu}") + if a.serial_log: + print(f"guest console, last line: {last_serial_line(a.serial_log)!r}") + + if hung: + print(f"FAIL: `{hung[0]}` did not return within {hung[1]:.0f}s: the monitor's flush and a worker's flush wait for each other (#306)") + if a.stacks: + save_stacks(proc.pid, a.stacks) + # A deadlocked iris cannot stop; its disk overlay is a --ci one in $TMPDIR. + proc.send_signal(signal.SIGKILL) + proc.wait() + return 1 + + status = 0 + if error: + print(f"FAIL: {error}") + status = 2 + elif log.worker < a.min_worker_flushes: + print(f"INCONCLUSIVE: only {log.worker} worker-led flushes (want {a.min_worker_flushes}); lower --arena-mb or race longer") + status = 2 + else: + print("PASS: every flush returned while the compile workers flushed on their own") + + # Clean stop: the CI socket's quit stops the machine and exits iris. + ci = a.ci_socket or ci_socket_of(a.config) + try: + if ci: + ci_send(ci, "quit", {}, timeout=120) + proc.wait(timeout=120) + except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as e: + print(f"note: clean quit failed ({e}); stopping iris") + proc.terminate() + try: + proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + return status + + +def save_stacks(pid, path): + """Every thread's stack of the hung iris, with `sample` (macOS) or gdb.""" + import shutil + if shutil.which("sample"): + cmd = ["sample", str(pid), "2", "-file", path] + elif shutil.which("gdb"): + cmd = ["gdb", "-p", str(pid), "-batch", "-ex", "thread apply all bt"] + else: + print("note: no sample or gdb for the stacks") + return + try: + out = subprocess.run(cmd, capture_output=True, timeout=120) + if cmd[0] == "gdb": + open(path, "wb").write(out.stdout) + print(f"thread stacks: {path}") + except (OSError, subprocess.TimeoutExpired) as e: + print(f"note: stacks failed ({e})") + + +def ci_socket_of(config): + try: + text = open(config).read() + except OSError: + return None + m = re.search(r'^\s*ci_socket\s*=\s*"([^"]+)"', text, re.M) + return m.group(1) if m else None + + +if __name__ == "__main__": + sys.exit(main())