From 3db78f6f96f102714a2e232552e44cfecf4e8147 Mon Sep 17 00:00:00 2001 From: grahamster2 <128315603+grahamster2@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:36:17 -0500 Subject: [PATCH] D3D12.X: a pipeline that must wait for a compile slot leaves its worker free On an RTX 3080 pipeline building stood still in game: the window said "driver 1 building (21 waiting for a slot), ... 1000+ pipelines queued", 0 - 2 fps and a black screen (draws without a built pipeline are left out). In the log 21 huge compiles (667 KB - 1.08 MB of DXIL) each waited 90 - 213 s at the gate for 4 - 21 s of driver work. Root cause: a gated compile (huge: >= 256 KB of DXIL, XCL_HUGE_PSO_CONCURRENCY default 1; also the giant lane and AMD's medium compute lane) on a normal worker parks it in big_compile_turn. A helper took the parked worker's place in the queue, but no more helpers than normal workers were started (compile_threads), and the helpers took huge builds too and parked behind the same slot. Once every worker and every helper stood at the gate, nothing served the queue. The driver call of a parked build is made of what its thread holds (the descriptors and DXIL on its stack, known only after translation and DXC), so the build stays on that thread, which waits for the slot and builds it; its result is delivered as before (complete, done/cv, cache publish). What changes is the seat in the queue: every parked normal worker or helper now gets a replacement, up to XCL_HUGE_PSO_HANDOFFS (default twice the normal workers, never fewer than them), so normal builds go on. Each helper builds too and takes memory, so one is started only while 3 GB of commit is free (the floor the huge gate itself waits for); a parked build that found no headroom tries again while it waits. On a development branch a bound of 64 drained the queue in game but ran the machine out of RAM. The slot limits and the commit gate are unchanged. With many unwanted builds waiting at once, a wanted one (a title thread waits for it) must not lose a freed slot to them: while one waits (Slots::wanted_waiting) no unwanted build takes a slot. That only matters in a lane where wanted_most == most (the giant lane, or the environment set so); elsewhere a wanted build has slots of its own. The wanted cap and its commit bypass are unchanged. The pipeline line counts "N workers handed off at the compile gate" (helpers actually started). README documents XCL_HUGE_PSO_HANDOFFS. Tests: helpers_parked_at_the_gate_are_replaced_too (2x the workers parked, a later build still runs; fails before this change), parked_workers_start_no_helper_without_commit_and_none_past_the_bound, a_helper_starts_only_under_the_bound_and_with_commit_free, an_unwanted_build_leaves_a_free_slot_to_a_waiting_wanted_one (fails before), the_handoff_bound_is_never_below_the_workers. The job of graphics_first_use_carries_the_exact_serialized_recipe_identity builds no pipeline now: that test releases its stand-in without waiting, and a build-ahead worker finishing the orphan released its fake 0x4332 as a COM object (the test binary aborted when the queue's normal workers were all parked). Assisted-by: Claude Code (Claude Opus 5.5) --- README.md | 5 + crates/xcl/src/hle/d3d12x/pso_async.rs | 246 ++++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 69 ++++++- 3 files changed, 292 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index d55abf4300..741b86d2d0 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,11 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. On AMD, cold 128–256 KiB compute pipelines use a separate lane (three background / four wanted at once on hosts with at least 32 GiB RAM, two / three below that), configurable with `XCL_MEDIUM_PSO_CONCURRENCY` and `XCL_MEDIUM_PSO_WANTED_CONCURRENCY`. + While a background worker waits at one of these gates for a slot, a helper thread serves its + queue so the other pipelines go on being built: at most `XCL_HUGE_PSO_HANDOFFS` helpers at once + (default twice the shader compile threads, never fewer than them, at most 512), each started + only with 3 GB of commit free. Each helper builds pipelines too, so a higher value uses more + memory. - A loop in a translated compute program run by a Dispatch (not ExecuteIndirect) is ended after its dispatch's share of passes for each entry (between 1024 and 65 536 a thread, fewer the more threads the dispatch has; the direct DXIL translator ends the thread's program there), so diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index df9fabd0da..ca4784c5a5 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3192,6 +3192,8 @@ struct Stats { built: usize, ahead: usize, huge: usize, + /// helpers started for workers parked at a driver-compile gate (`parked_for_big_compile`) + handed_off: usize, /// translated ahead (`Backlog`), still in the backlog warmed: usize, backlog: usize, @@ -3207,6 +3209,7 @@ fn stats() -> Stats { built: l(&LAZY_BUILT), ahead: l(&LAZY_AHEAD), huge: l(&LAZY_HUGE), + handed_off: l(&HANDED_OFF), warmed: l(&WARMED), backlog: l(&BACKLOG), waits: crate::hle::api_cost::totals()[crate::hle::api_cost::Call::PipelineWait as usize], @@ -3222,12 +3225,13 @@ fn stats_line(now: &Stats, last: &Stats, huge_kb: usize) -> Option { return None; } Some(format!( - "D3D12.X: lazy pipelines: {} made ({} graphics), {} built ({} before their first use, {} with {huge_kb} KB of DXIL or more), {} translated ahead, {} in the build-ahead backlog; binds waited {} ms for pipelines being built ({} waits in 2 s)", + "D3D12.X: lazy pipelines: {} made ({} graphics), {} built ({} before their first use, {} with {huge_kb} KB of DXIL or more), {} workers handed off at the compile gate, {} translated ahead, {} in the build-ahead backlog; binds waited {} ms for pipelines being built ({} waits in 2 s)", now.made, now.graphics, now.built, now.ahead, now.huge, + now.handed_off, now.warmed, now.backlog, (now.waits.1 - last.waits.1) / 1000, @@ -4021,33 +4025,85 @@ fn start_normal_workers() -> bool { static PARKED_NORMAL: AtomicUsize = AtomicUsize::new(0); static NORMAL_HELPERS: AtomicUsize = AtomicUsize::new(0); static NORMAL_HELPERS_STARTED: AtomicUsize = AtomicUsize::new(0); +/// helpers started for normal workers parked at a driver-compile gate (huge, giant or AMD +/// medium compute; `parked_for_big_compile`; the pipeline line) +static HANDED_OFF: AtomicUsize = AtomicUsize::new(0); + +/// Replacements at most for normal workers parked at the driver-compile gate +/// (`XCL_HUGE_PSO_HANDOFFS`, default twice the normal workers; never fewer than the normal +/// workers). With no more of them than normal workers, the replacements took huge builds too and +/// parked behind the same slot: on an RTX 3080 every worker and helper stood at the gate (21 huge +/// compiles of 667 KB – 1.08 MB DXIL, each waiting 90 – 213 s for 4 – 21 s in the driver) while +/// 1 000+ other pipelines stayed queued and the title drew nothing with them. Each helper builds +/// too and so takes memory: a default of 64 ran a machine out of RAM in game. +fn handoff_most() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| handoff_most_of(std::env::var("XCL_HUGE_PSO_HANDOFFS").ok().as_deref(), crate::gpu::recomp::dxc::compile_threads())) +} + +fn handoff_most_of(v: Option<&str>, workers: usize) -> usize { + let default = 2 * workers; + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(default).clamp(workers, 512.max(workers)) +} + +/// Commit a helper is started with at least: the floor a huge compile waits for at the gate +/// (`real::big_compile_headroom`). +const HELPER_COMMIT_HEADROOM: u64 = 3 << 30; -/// A normal pipeline worker is about to wait for a huge driver-compile slot. A bounded helper -/// serves its queue until workers return; calls from title and preload threads do nothing. +fn helper_commit_free() -> bool { + super::real::big_compile_commit_free(HELPER_COMMIT_HEADROOM) +} + +/// A normal pipeline worker is about to wait for a driver-compile slot: the build stays on this +/// thread (its driver call is made of what the thread holds) and waits there, and a helper takes +/// the worker's place in the queue until it returns, so the other builds go on – also when the +/// helpers' own builds park (up to `handoff_most`). A helper is started only while +/// `HELPER_COMMIT_HEADROOM` of commit is free; the waiting build tries again +/// (`ParkedWorker::top_up`). Its result is delivered as any build's. Calls from title and +/// preload threads do nothing. pub(super) fn parked_for_big_compile() -> ParkedWorker { + park_for_big_compile(handoff_most(), helper_commit_free) +} + +fn park_for_big_compile(most: usize, commit_free: fn() -> bool) -> ParkedWorker { if !NORMAL_WORKER.get() { - return ParkedWorker(false); - } - let parked = PARKED_NORMAL.fetch_add(1, Ordering::AcqRel) + 1; - let most = parked.min(crate::gpu::recomp::dxc::compile_threads()); - let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); - while helpers < most { - match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) { - Ok(_) => { - spawn_normal_helper(helpers); - break; + return ParkedWorker(None); + } + PARKED_NORMAL.fetch_add(1, Ordering::AcqRel); + let parked = ParkedWorker(Some((most, commit_free))); + parked.top_up(); + parked +} + +pub(super) struct ParkedWorker(Option<(usize, fn() -> bool)>); + +impl ParkedWorker { + /// Start a helper if fewer serve the queue than workers are parked (at most `handoff_most`) + /// and commit allows it. + pub(super) fn top_up(&self) { + let Some((most, commit_free)) = self.0 else { return }; + let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); + while may_add_helper(helpers, PARKED_NORMAL.load(Ordering::Acquire), most, commit_free) { + match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + spawn_normal_helper(helpers); + return; + } + Err(now) => helpers = now, } - Err(now) => helpers = now, } } - ParkedWorker(true) } -pub(super) struct ParkedWorker(bool); +/// Whether one more helper may start: fewer than the parked workers and than `most`, and +/// commit free (asked last). +fn may_add_helper(helpers: usize, parked: usize, most: usize, commit_free: impl Fn() -> bool) -> bool { + helpers < parked.min(most) && commit_free() +} impl Drop for ParkedWorker { fn drop(&mut self) { - if self.0 { + if self.0.is_some() { PARKED_NORMAL.fetch_sub(1, Ordering::AcqRel); } } @@ -4072,6 +4128,8 @@ fn spawn_normal_helper(k: usize) { }); if spawned.is_err() { NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel); + } else { + HANDED_OFF.fetch_add(1, Ordering::Relaxed); } } @@ -10108,7 +10166,10 @@ mod used_tests { fn graphics_first_use_carries_the_exact_serialized_recipe_identity() { let standin = 0x7E57_7013usize; let payload = b"canonical graphics recipe".to_vec(); - submit_lazy(standin, false, Box::new(|| 0x4332), 0x5EED_0013); + // (the job builds no pipeline: the test releases its stand-in without waiting for the + // build, and a build-ahead worker that has the job then finishes an orphan, whose + // pipeline `complete` releases as a COM object - a fake one crashed the test binary) + submit_lazy(standin, false, Box::new(|| 0), 0x5EED_0013); on_first_use_graphics(standin, payload.clone()); let pending = entry(standin).unwrap(); assert_eq!(pending.manifest_recipe.load(Ordering::Acquire), super::super::gfx_records::payload_key(&payload)); @@ -10134,7 +10195,7 @@ mod used_tests { } let outside = parked_for_big_compile(); - assert!(!outside.0, "a title/test thread must not start a replacement"); + assert!(outside.0.is_none(), "a title/test thread must not start a replacement"); drop(outside); start_normal_workers(); @@ -10145,7 +10206,8 @@ mod used_tests { for _ in 0..n { let (tx, gate) = (started_tx.clone(), gate.clone()); queue().submit(Priority::Foreground, Box::new(move || { - let _parked = parked_for_big_compile(); + // (commit taken as free: this test is about the queue, not the machine's commit) + let _parked = park_for_big_compile(handoff_most(), || true); tx.send(()).unwrap(); let mut open = gate.0.lock().unwrap(); while !*open { @@ -10170,6 +10232,146 @@ mod used_tests { assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired"); } + /// The helpers' own builds park at the gate too: with as many parked builds as twice the + /// normal workers (each worker's and each first helper's), the queue is still served – the + /// replacements were bounded by the normal workers, and every one of them stood at the gate. + #[test] + fn helpers_parked_at_the_gate_are_replaced_too() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + + struct OpenGate(Arc<(Mutex, Condvar)>); + impl Drop for OpenGate { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() = true; + self.0 .1.notify_all(); + } + } + + start_normal_workers(); + let n = crate::gpu::recomp::dxc::compile_threads(); + let parking = 2 * n; + // (the bound is passed: `XCL_HUGE_PSO_HANDOFFS` in the environment does not change the test) + let handed_off = HANDED_OFF.load(Ordering::Relaxed); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let open = OpenGate(gate.clone()); + for _ in 0..parking { + let (tx, gate) = (started_tx.clone(), gate.clone()); + queue().submit(Priority::Foreground, Box::new(move || { + // (commit taken as free: this test is about the queue, not the machine's commit) + let _parked = park_for_big_compile(parking, || true); + tx.send(()).unwrap(); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + } + for _ in 0..parking { + started_rx.recv_timeout(Duration::from_secs(10)).expect("every parked build started: a helper took each one's place"); + } + let (ran_tx, ran_rx) = mpsc::channel(); + queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap(); + ran_rx.recv_timeout(Duration::from_secs(10)).expect("a build behind the parked ones ran"); + assert!(HANDED_OFF.load(Ordering::Relaxed) >= handed_off + parking, "each parked build is counted as handed off"); + drop(open); + + let deadline = Instant::now() + Duration::from_secs(10); + while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(PARKED_NORMAL.load(Ordering::Acquire), 0); + assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired"); + } + + #[test] + fn the_handoff_bound_is_never_below_the_workers() { + assert_eq!(handoff_most_of(None, 15), 30, "twice the normal workers"); + assert_eq!(handoff_most_of(None, 40), 80); + assert_eq!(handoff_most_of(Some(" 100 "), 15), 100); + assert_eq!(handoff_most_of(Some("2"), 15), 15, "never fewer than the normal workers"); + assert_eq!(handoff_most_of(Some("lots"), 15), 30); + assert_eq!(handoff_most_of(Some("100000"), 15), 512); + } + + /// A helper starts only below the parked workers, below the bound, and with commit free; + /// commit is not asked when the count already says no. + #[test] + fn a_helper_starts_only_under_the_bound_and_with_commit_free() { + assert!(may_add_helper(0, 1, 4, || true)); + assert!(!may_add_helper(1, 1, 4, || true), "one helper per parked worker"); + assert!(!may_add_helper(4, 9, 4, || true), "more parked than the bound: no further helper"); + assert!(!may_add_helper(0, 1, 4, || false), "no commit headroom: no helper"); + assert!(!may_add_helper(4, 9, 4, || panic!("commit asked although the bound is reached"))); + } + + /// A worker parked at the gate with no commit headroom starts no helper; with a bound of 1 + /// (fewer than the 2 parked workers) exactly one starts, and the queue is still served. (Only + /// one or two workers park: with every normal worker parked and no helper, the queue other + /// tests use would stand still meanwhile and their builds go to the build-ahead workers.) + #[test] + fn parked_workers_start_no_helper_without_commit_and_none_past_the_bound() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + + struct OpenGate(Arc<(Mutex, Condvar)>); + impl Drop for OpenGate { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() = true; + self.0 .1.notify_all(); + } + } + fn retired() -> bool { + let deadline = Instant::now() + Duration::from_secs(10); + while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + PARKED_NORMAL.load(Ordering::Acquire) == 0 && NORMAL_HELPERS.load(Ordering::Acquire) == 0 + } + fn no_commit() -> bool { + false + } + fn commit() -> bool { + true + } + + start_normal_workers(); + assert!(retired(), "no helper left over from another test"); + // (parked workers, bound, commit, helpers then) + let cases: [(usize, usize, fn() -> bool, usize); 2] = [(1, handoff_most(), no_commit, 0), (2, 1, commit, 1)]; + for (n, most, commit_free, helpers) in cases { + let handed_off = HANDED_OFF.load(Ordering::Relaxed); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let open = OpenGate(gate.clone()); + for _ in 0..n { + let (tx, gate) = (started_tx.clone(), gate.clone()); + queue().submit(Priority::Foreground, Box::new(move || { + let _parked = park_for_big_compile(most, commit_free); + tx.send(()).unwrap(); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + } + for _ in 0..n { + started_rx.recv_timeout(Duration::from_secs(10)).expect("every worker parked"); + } + assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), helpers, "helpers with bound {most}"); + assert_eq!(HANDED_OFF.load(Ordering::Relaxed) - handed_off, helpers, "only a started helper counts as a handoff"); + // (with 2 normal workers or more one of them or the helper is still free) + if helpers > 0 && crate::gpu::recomp::dxc::compile_threads() >= 2 { + let (ran_tx, ran_rx) = mpsc::channel(); + queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap(); + ran_rx.recv_timeout(Duration::from_secs(10)).expect("the queue is still served"); + } + drop(open); + assert!(retired(), "parked workers returned and helpers retired"); + } + } + /// A queued normal worker job whose stand-in was released before a worker starts it is /// skipped as orphaned instead of entering the compiler. #[test] @@ -10305,11 +10507,11 @@ mod used_tests { /// The line is written when a count changed, with the waits of its 2 s only. #[test] fn the_pipeline_line_comes_when_a_count_changed() { - let last = Stats { made: 10, graphics: 8, built: 2, ahead: 1, huge: 0, warmed: 4, backlog: 6, waits: (3, 4_000_000) }; + let last = Stats { made: 10, graphics: 8, built: 2, ahead: 1, huge: 0, handed_off: 7, warmed: 4, backlog: 6, waits: (3, 4_000_000) }; assert_eq!(stats_line(&last, &last, 256), None); let now = Stats { built: 3, waits: (5, 6_500_000), ..last }; let line = stats_line(&now, &last, 256).unwrap(); - assert!(line.contains("10 made (8 graphics), 3 built (1 before their first use, 0 with 256 KB of DXIL or more), 4 translated ahead, 6 in the build-ahead backlog"), "{line}"); + assert!(line.contains("10 made (8 graphics), 3 built (1 before their first use, 0 with 256 KB of DXIL or more), 7 workers handed off at the compile gate, 4 translated ahead, 6 in the build-ahead backlog"), "{line}"); assert!(line.contains("waited 2500 ms for pipelines being built (2 waits in 2 s)"), "{line}"); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bd9cd731cf..45291f6bb0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5381,18 +5381,21 @@ struct Slots { wanted_most: usize, /// compiles that are not built ahead of their first use waiting for a slot (`big_compile_turn`) urgent: AtomicUsize, + /// compiles a title thread waits for waiting for a slot: no other takes a slot before them + /// (`big_compile_turn`) + wanted_waiting: AtomicUsize, /// a build ahead of its pipeline's first use may take a slot (`big_compile_turn`) ahead: bool, } impl Slots { const fn new(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: true } + Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), wanted_waiting: AtomicUsize::new(0), ahead: true } } /// `new` for a lane whose slots no build ahead of its pipeline's first use takes. const fn closed_to_ahead(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: false } + Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), wanted_waiting: AtomicUsize::new(0), ahead: false } } fn most(&self) -> usize { @@ -5585,19 +5588,27 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { /// waits for, or waited for and gave up on (`XCL_GFX_PSO_WAIT_MS`), goes first. In a lane closed /// to builds ahead (`Slots::ahead`: giant compiles) it takes no slot at all and waits until its /// pipeline is used: a slot is never given back before the compile ends, so a giant compile -/// nobody wants made a bind wait minutes for another one. +/// nobody wants made a bind wait minutes for another one. While a wanted build waits for a slot +/// (`Slots::wanted_waiting`) no unwanted one takes a freed slot before it: the workers parked here +/// do not run out (`pso_async::parked_for_big_compile` hands each one's place in the queue to +/// another), so many unwanted builds can wait at once. That only changes anything in a lane where +/// `wanted_most == most` (the giant lane, or the environment set so): elsewhere a wanted build +/// has slots of its own above `most` that no unwanted one takes. fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, ahead: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); // (counted in `urgent` while it waits) let mut queued = false; + // (counted in `wanted_waiting` while it waits wanted) + let mut wanted_queued = false; let mut parked = None; let guard = loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; let ahead = !is_wanted && ahead(); let open = slots.ahead || !ahead; - if open && *n < cap && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { + let behind = !is_wanted && slots.wanted_waiting.load(Ordering::Acquire) > 0; + if open && *n < cap && !behind && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { *n += 1; break SlotGuard(slots); } @@ -5605,14 +5616,27 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante queued = true; slots.urgent.fetch_add(1, Ordering::AcqRel); } - if parked.is_none() { - parked = Some(super::pso_async::parked_for_big_compile()); + if is_wanted != wanted_queued { + wanted_queued = is_wanted; + if is_wanted { + slots.wanted_waiting.fetch_add(1, Ordering::AcqRel); + } else { + slots.wanted_waiting.fetch_sub(1, Ordering::AcqRel); + } + } + match &parked { + None => parked = Some(super::pso_async::parked_for_big_compile()), + // (no helper yet when commit was short: try again) + Some(p) => p.top_up(), } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; }; if queued { slots.urgent.fetch_sub(1, Ordering::AcqRel); } + if wanted_queued { + slots.wanted_waiting.fetch_sub(1, Ordering::AcqRel); + } guard } @@ -5800,6 +5824,39 @@ mod big_compile_tests { assert_eq!((*S.n.lock().unwrap(), S.urgent.load(Ordering::Acquire)), (0, 0)); } + /// Many unwanted builds wait at the gate (their workers are replaced in the queue): while a + /// wanted build waits for a slot, none of them takes one that comes free, and the wanted build + /// counts itself as waiting until it has its slot. + #[test] + fn an_unwanted_build_leaves_a_free_slot_to_a_waiting_wanted_one() { + static S: Slots = Slots::new(1, 1); + // (true once `done` holds, polled up to 10 s) + let within = |done: &dyn Fn() -> bool| { + let deadline = Instant::now() + Duration::from_secs(10); + while !done() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + done() + }; + S.wanted_waiting.fetch_add(1, Ordering::AcqRel); + let unwanted = std::thread::spawn(|| drop(big_compile_turn(&S, || true, || false, || false))); + // It counts itself in `urgent` only after it was refused the free slot once. + assert!(within(&|| S.urgent.load(Ordering::Acquire) == 1), "the unwanted build waits"); + assert!(!unwanted.is_finished(), "the slot is free, but a wanted build waits for it"); + assert_eq!(*S.n.lock().unwrap(), 0); + S.wanted_waiting.fetch_sub(1, Ordering::AcqRel); + assert!(within(&|| unwanted.is_finished()), "the unwanted build takes the slot once no wanted one waits"); + unwanted.join().unwrap(); + + let held = big_compile_turn(&S, || true, || false, || false); + let wanted = std::thread::spawn(|| drop(big_compile_turn(&S, || true, || true, || false))); + assert!(within(&|| S.wanted_waiting.load(Ordering::Acquire) == 1), "the waiting wanted build is counted"); + drop(held); + assert!(within(&|| wanted.is_finished()), "the wanted build gets the freed slot"); + wanted.join().unwrap(); + assert_eq!((*S.n.lock().unwrap(), S.urgent.load(Ordering::Acquire), S.wanted_waiting.load(Ordering::Acquire)), (0, 0, 0)); + } + /// In the lane of giant compiles (`most == 1, wanted_most == 1`) a build ahead of its /// pipeline's first use takes no slot, not even a free one, so a wanted giant build goes at /// once instead of waiting for its whole compile; once its pipeline is used it takes its turn.