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..1705d0adaa 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -419,7 +419,8 @@ impl Drop for RunningBuild<'_> { // (under the lock: `want` does not raise this thread after it) let mut demand = self.build.demand.lock().unwrap(); demand.preload_thread = 0; - if self.build.wanted.load(Ordering::Acquire) { + // (raised by `want` or at its start; a late build is left raised by `unwant`) + if self.build.runs_raised() { unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); @@ -467,7 +468,7 @@ fn run_build(build: &Arc, job: Job) { if preload { let mut d = build.demand.lock().unwrap(); d.preload_thread = unsafe { GetCurrentThreadId() }; - if build.wanted.load(Ordering::Acquire) { + if build.runs_raised() { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } @@ -626,13 +627,19 @@ impl Build { /// behind the huge-pipeline gate as an unwanted one (`real::big_compile_turn`): it waits for /// free commit and for the unwanted slots, where a wanted build skips the commit wait and has /// more slots, and many of those at once ran the process out of commit. (A job already - /// promoted to `Foreground` keeps its place in the queue.) + /// promoted to `Foreground` keeps its place in the queue.) A `late` one – the title draws + /// without it until it is built (`resolve_within`) – is still needed: its preload worker + /// stays at a normal priority, and at the gate it goes before the other unwanted builds + /// (`real::big_compile_turn_late`). At the lowest priority behind the build-ahead work a + /// pipeline the title was drawing with did not catch up. fn unwant(&self) { let mut d = self.demand.lock().unwrap(); d.waiters = d.waiters.saturating_sub(1); if d.waiters == 0 { self.wanted.store(false, Ordering::Release); - Self::set_priority(&d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST); + if !self.late.load(Ordering::Acquire) { + Self::set_priority(&d, windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST); + } } } @@ -645,6 +652,12 @@ impl Build { } } + /// Whether a preload worker builds it at a normal priority, not the lowest: it is wanted, or + /// late (`unwant`). Asked when the build starts and when it ends. + fn runs_raised(&self) -> bool { + self.wanted.load(Ordering::Acquire) || self.late.load(Ordering::Acquire) + } + /// The preload worker building it, if one does, at `priority` (under the `demand` lock: the /// worker does not end its build meanwhile). fn set_priority(d: &Demand, priority: windows_sys::Win32::System::Threading::THREAD_PRIORITY) { @@ -3192,6 +3205,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 +3222,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 +3238,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 +4038,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; + +fn helper_commit_free() -> bool { + super::real::big_compile_commit_free(HELPER_COMMIT_HEADROOM) +} -/// 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. +/// 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 +4141,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); } } @@ -4117,7 +4188,7 @@ fn run_reserved_rebuild(build: Arc, recipe: Recipe) { if preload { let mut demand = build.demand.lock().unwrap(); demand.preload_thread = unsafe { GetCurrentThreadId() }; - if build.wanted.load(Ordering::Acquire) { + if build.runs_raised() { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } @@ -10108,7 +10179,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 +10208,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 +10219,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 +10245,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 +10520,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}"); } @@ -11091,7 +11306,9 @@ fn budget_of(v: Option<&str>) -> Option { /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// draws and dispatches are skipped) until a worker has built it. Its build is no longer wanted -/// (`Build::unwant`), but it was used: it goes before the builds ahead of first use. +/// (`Build::unwant`), but it was used and is still needed: it keeps its place at the front of +/// the queue (`Foreground`, from `want`) and its worker's priority, and at the huge-compile gate +/// it goes before the builds ahead of first use and the other unwanted builds. fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { if *p.build.done.lock().unwrap() { return built_or(p, pso); @@ -11159,7 +11376,9 @@ pub fn image_only(standin: usize) { /// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built, /// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not -/// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. +/// `wanted`: a big one waits for free commit at the driver-compile gate. It +/// is `late` (its dispatches are left out meanwhile), so a preload worker builds it at a normal +/// priority and it goes before the other unwanted builds there (`real::big_compile_turn_late`). fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.build.real.load(Ordering::Acquire) { 0 => { @@ -12516,6 +12735,64 @@ mod backlog_tests { .with_submit(true, key, None)) } + /// A bind's wait that runs out of its budget leaves the build unwanted: the preload worker + /// building it goes back to the lowest priority, but not when the title draws without the + /// pipeline meanwhile (`late`, `resolve_within`): that one is still needed. + #[test] + fn a_late_build_keeps_its_preload_worker_raised() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; + for late in [false, true] { + let (id_tx, id_rx) = mpsc::channel(); + let (ask_tx, ask_rx) = mpsc::channel::<()>(); + let (priority_tx, priority_rx) = mpsc::channel(); + let worker = std::thread::spawn(move || unsafe { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + id_tx.send(GetCurrentThreadId()).unwrap(); + ask_rx.recv().unwrap(); + priority_tx.send(GetThreadPriority(GetCurrentThread())).unwrap(); + }); + let build = pending(0x5EED_1A7E, false); + build.demand.lock().unwrap().preload_thread = id_rx.recv().unwrap(); + // (`want` without the workers it starts) + build.add_waiter(&mut build.demand.lock().unwrap()); + build.late.store(late, Ordering::Release); + build.unwant(); + assert!(!build.wanted.load(Ordering::Acquire)); + ask_tx.send(()).unwrap(); + let priority = priority_rx.recv().unwrap(); + worker.join().unwrap(); + let expected = if late { THREAD_PRIORITY_NORMAL } else { THREAD_PRIORITY_LOWEST }; + assert_eq!(priority, expected, "late: {late}"); + } + } + + /// A preload worker starts a build at a normal priority when it is wanted or already late (the + /// title draws without it), at the lowest otherwise, and is back at the lowest when the build + /// ends (`RunningBuild::drop`). + #[test] + fn a_build_late_when_it_starts_runs_raised_and_its_worker_is_lowered_after() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; + for (wanted, late, during) in [(false, false, THREAD_PRIORITY_LOWEST), (false, true, THREAD_PRIORITY_NORMAL), (true, false, THREAD_PRIORITY_NORMAL)] { + let worker = std::thread::spawn(move || unsafe { + PRELOAD_WORKER.set(true); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + let (tx, rx) = mpsc::channel(); + let build = Arc::new(Build::new(Box::new(move || { + tx.send(GetThreadPriority(GetCurrentThread())).unwrap(); + 0 + }), false)); + build.wanted.store(wanted, Ordering::Release); + build.late.store(late, Ordering::Release); + let job = build.job.lock().unwrap().take().unwrap(); + run_build(&build, job); + (rx.recv().unwrap(), GetThreadPriority(GetCurrentThread())) + }); + let (in_build, after) = worker.join().unwrap(); + assert_eq!(in_build, during, "wanted: {wanted}, late: {late}"); + assert_eq!(after, THREAD_PRIORITY_LOWEST, "the worker is back at the lowest (wanted: {wanted}, late: {late})"); + } + } + /// A backlog worker's build nobody waits for builds the pieces of its dispatch chain itself: /// none of them goes to the workers whose builds binds wait for. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bd9cd731cf..40d80b89e4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5381,18 +5381,24 @@ 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, + /// unwanted compiles of pipelines the title draws without (`pso_async::build_is_late`) + /// waiting for a slot, commit free: no other unwanted one takes a slot before them + late_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), late_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), late_waiting: AtomicUsize::new(0), ahead: false } } fn most(&self) -> usize { @@ -5490,10 +5496,11 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op let _slot = gated.then(|| { let _waiting = DRIVER_BUILDS.waiting(); if medium { - big_compile_turn( + big_compile_turn_late( &MEDIUM_COMPILES, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, + super::pso_async::build_is_late, super::pso_async::build_is_ahead, ) } else { @@ -5585,37 +5592,88 @@ 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 { + big_compile_turn_late(slots, commit_free, wanted, || false, ahead) +} + +/// `big_compile_turn` of a build that may be `late`: the title draws or dispatches without its +/// pipeline until it is built (`pso_async::build_is_late`; nobody waits for it). Among the +/// unwanted builds a late one with its commit free (`Slots::late_waiting`) takes a freed slot +/// first, so a pipeline the title is drawing with catches up with the others at the gate. +fn big_compile_turn_late(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, late: 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, in `late_waiting` while it waits late) + let mut wanted_queued = false; + let mut late_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 is_late = !is_wanted && !ahead && late(); let open = slots.ahead || !ahead; - if open && *n < cap && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { - *n += 1; - break SlotGuard(slots); + let behind = !is_wanted + && (slots.wanted_waiting.load(Ordering::Acquire) > 0 || (!is_late && slots.late_waiting.load(Ordering::Acquire) > 0)); + // (a late build short of commit does not hold the others back) + let mut short = false; + if open && *n < cap && !behind { + if !(is_wanted || commit_free()) { + short = true; + } else if !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { + *n += 1; + break SlotGuard(slots); + } } if !ahead && !queued { queued = true; slots.urgent.fetch_add(1, Ordering::AcqRel); } - if parked.is_none() { - parked = Some(super::pso_async::parked_for_big_compile()); + count_waiting(&slots.wanted_waiting, &mut wanted_queued, is_wanted); + if count_waiting(&slots.late_waiting, &mut late_queued, is_late && !short) && !late_queued { + // (no longer ahead of the others: one of them may take the free slot now, not a LOOK later) + slots.cv.notify_all(); + } + 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); } + count_waiting(&slots.wanted_waiting, &mut wanted_queued, false); + if count_waiting(&slots.late_waiting, &mut late_queued, false) { + // (the others no longer wait behind it for a slot still free) + slots.cv.notify_all(); + } guard } +/// A waiter at the gate is counted in `waiting` (`counted`) while `now`. Whether that changed. +fn count_waiting(waiting: &AtomicUsize, counted: &mut bool, now: bool) -> bool { + if *counted == now { + return false; + } + *counted = now; + if now { + waiting.fetch_add(1, Ordering::AcqRel); + } else { + waiting.fetch_sub(1, Ordering::AcqRel); + } + true +} + /// `big_compile_turn` of a huge driver compile of `bytes` on a worker. A build ahead of its /// pipeline's first use in a lane closed to it waits there until the pipeline is used; on a /// backlog worker another worker takes its place meanwhile (`pso_async::build_parks`). @@ -5624,7 +5682,13 @@ pub(super) fn huge_compile_turn(bytes: usize) -> SlotGuard { if !slots.ahead && super::pso_async::build_is_ahead() { super::pso_async::build_parks(); } - big_compile_turn(slots, || big_compile_commit_free(headroom_for(bytes, super::pso_async::build_is_late())), super::pso_async::build_is_wanted, super::pso_async::build_is_ahead) + big_compile_turn_late( + slots, + || big_compile_commit_free(headroom_for(bytes, super::pso_async::build_is_late())), + super::pso_async::build_is_wanted, + super::pso_async::build_is_late, + super::pso_async::build_is_ahead, + ) } /// The commit headroom a huge compile of `bytes` waits for (`big_compile_headroom`), halved for @@ -5800,6 +5864,84 @@ 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)); + } + + /// A build whose pipeline the title draws without (late) takes a freed slot before other + /// unwanted builds waiting for it, after a wanted one; one short of commit holds nobody back. + #[test] + fn a_late_build_takes_a_freed_slot_before_other_unwanted_ones() { + 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.late_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 late build waits for it"); + assert_eq!(*S.n.lock().unwrap(), 0); + S.late_waiting.fetch_sub(1, Ordering::AcqRel); + assert!(within(&|| unwanted.is_finished()), "the unwanted build goes once no late one waits"); + unwanted.join().unwrap(); + + // a late one waits behind a wanted one, and is counted while it waits + S.wanted_waiting.fetch_add(1, Ordering::AcqRel); + let late = std::thread::spawn(|| drop(big_compile_turn_late(&S, || true, || false, || true, || false))); + assert!(within(&|| S.late_waiting.load(Ordering::Acquire) == 1), "the waiting late build is counted"); + assert!(!late.is_finished(), "a wanted build goes first"); + S.wanted_waiting.fetch_sub(1, Ordering::AcqRel); + assert!(within(&|| late.is_finished()), "the late build goes once no wanted one waits"); + late.join().unwrap(); + + // short of commit, a late one is not counted: the others go on + static FREE: AtomicBool = AtomicBool::new(false); + let short = std::thread::spawn(|| drop(big_compile_turn_late(&S, || FREE.load(Ordering::Acquire), || false, || true, || false))); + assert!(within(&|| S.urgent.load(Ordering::Acquire) == 1), "the late build short of commit waits"); + assert_eq!(S.late_waiting.load(Ordering::Acquire), 0, "a late build short of commit holds nobody back"); + drop(big_compile_turn(&S, || true, || false, || false)); + FREE.store(true, Ordering::Release); + assert!(within(&|| short.is_finished()), "the late build goes once its commit is free"); + short.join().unwrap(); + let counts = (*S.n.lock().unwrap(), S.urgent.load(Ordering::Acquire), S.wanted_waiting.load(Ordering::Acquire), S.late_waiting.load(Ordering::Acquire)); + assert_eq!(counts, (0, 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. @@ -9268,10 +9410,11 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let waited = std::time::Instant::now(); let gate_stall = crate::stall::span(crate::stall::StallKind::DriverCompileGate); slot = Some(if medium { - big_compile_turn( + big_compile_turn_late( &MEDIUM_COMPILES, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, + super::pso_async::build_is_late, super::pso_async::build_is_ahead, ) } else {