From 4b3f4405d167ddbe592e1903d3c58303eae5ad17 Mon Sep 17 00:00:00 2001 From: Zondybtw Date: Tue, 24 Nov 2026 18:16:36 +0800 Subject: [PATCH] D3D12.X: boost low-priority preload PSO workers on demand and prioritize BIG_COMPILES --- crates/xcl/src/hle/d3d12x/pso_async.rs | 257 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 181 +++++++++++++++-- 2 files changed, 421 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 33a85cf12..2aaef4efb 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -11,11 +11,106 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +/// Refcounted priority inheritance for a `THREAD_PRIORITY_LOWEST` preload worker. +/// While `count > 0` (at least one demand bind or `BIG_COMPILES` demand waiter depends on this +/// worker), its OS thread priority is raised to `THREAD_PRIORITY_NORMAL`; dropping the last +/// `BoostGuard` restores `THREAD_PRIORITY_LOWEST`. +pub(crate) struct BoostToken { + tid: u32, + count: Mutex, +} + +pub(crate) struct BoostGuard(Arc); + +/// Whether preload workers can safely run at `THREAD_PRIORITY_LOWEST` and be raised back to +/// `THREAD_PRIORITY_NORMAL` on demand. Under Wine, lowering a thread's priority maps to raising +/// its Linux nice value (always allowed), while raising it again requires `RLIMIT_NICE` / +/// `CAP_SYS_NICE` and fails for a normal desktop user, leaving the worker stuck at `LOWEST`. +/// Under Wine we keep preload workers at `NORMAL` and rely on `BIG_COMPILES` admission order. +pub(crate) fn can_lower_preload_priority() -> bool { + !crate::util::under_wine() +} + +fn set_thread_priority_by_id(tid: u32, prio: i32) { + if !can_lower_preload_priority() { + return; + } + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_SET_LIMITED_INFORMATION}; + unsafe { + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, tid); + if !h.is_null() { + SetThreadPriority(h, prio); + CloseHandle(h); + } + } +} + +impl BoostToken { + pub(crate) fn for_current_thread() -> Arc { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + Arc::new(Self { tid, count: Mutex::new(0) }) + } + + pub(crate) fn tid(&self) -> u32 { + self.tid + } + + pub(crate) fn is_boosted(&self) -> bool { + *self.count.lock().unwrap() > 0 + } + + /// Raise this preload worker to `THREAD_PRIORITY_NORMAL` until the returned guard drops. + pub(crate) fn boost(self: &Arc) -> BoostGuard { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let mut c = self.count.lock().unwrap(); + if *c == 0 { + set_thread_priority_by_id(self.tid, THREAD_PRIORITY_NORMAL); + } + *c += 1; + BoostGuard(self.clone()) + } +} + +impl Drop for BoostGuard { + fn drop(&mut self) { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_LOWEST; + let mut c = self.0.count.lock().unwrap(); + *c = c.saturating_sub(1); + if *c == 0 { + set_thread_priority_by_id(self.0.tid, THREAD_PRIORITY_LOWEST); + } + } +} + +thread_local! { + /// Set on `xcl-pso-pre-*` threads so `BIG_COMPILES` can detect preload holders and boost them + /// when a demand-bound compile arrives. + static CURRENT_PRELOAD: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// If the current thread is a `THREAD_PRIORITY_LOWEST` preload worker, returns its boost token. +pub(crate) fn current_preload_token() -> Option> { + CURRENT_PRELOAD.with(|c| c.borrow().clone()) +} + +#[derive(Default)] +struct PreloadOwner { + /// Preload worker currently building this pipeline (None when not in preload). + worker: Option>, + /// True once a demand bind (`resolve` / `resolve_wait`) needs this pipeline. + demanded: bool, + /// Active boost held while `worker` is building this demanded pipeline. + boost: Option, +} + struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, + /// priority-inheritance state if a `THREAD_PRIORITY_LOWEST` preload worker owns the build + preload: Mutex, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, done: Mutex, @@ -37,6 +132,38 @@ impl Pending { used::note(self.key); } } + + /// A demand bind needs this pipeline: if a `THREAD_PRIORITY_LOWEST` preload worker is already + /// building it, raise that worker to `THREAD_PRIORITY_NORMAL` until it finishes this build. + fn promote_preload(&self) { + let boosted_now = { + let mut g = self.preload.lock().unwrap(); + g.demanded = true; + if g.boost.is_none() { + if let Some(tok) = g.worker.as_ref() { + g.boost = Some(tok.boost()); + true + } else { + false + } + } else { + false + } + }; + if boosted_now { + super::real::notify_big_compiles(); + } + } +} + +struct PreloadJobGuard<'a>(&'a Pending); + +impl Drop for PreloadJobGuard<'_> { + fn drop(&mut self) { + let mut g = self.0.preload.lock().unwrap(); + g.worker = None; + g.boost = None; + } } /// stand-in handed to the title → its real pipeline @@ -129,6 +256,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), + preload: Mutex::new(PreloadOwner::default()), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), @@ -251,10 +379,14 @@ fn preload() -> Option<&'static Preload> { let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); for k in 0..n { let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { - unsafe { - use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + if can_lower_preload_priority() { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } } + let tok = BoostToken::for_current_thread(); + CURRENT_PRELOAD.with(|c| *c.borrow_mut() = Some(tok.clone())); static DONE: AtomicUsize = AtomicUsize::new(0); loop { let p = { @@ -273,6 +405,14 @@ fn preload() -> Option<&'static Preload> { // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { + { + let mut pg = p.preload.lock().unwrap(); + pg.worker = Some(tok.clone()); + if pg.demanded && pg.boost.is_none() { + pg.boost = Some(tok.boost()); + } + } + let _guard = PreloadJobGuard(&p); let real = job(); complete(&p, real); let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; @@ -344,6 +484,108 @@ mod used_tests { released(known); released(unknown); } + + fn thread_priority_of(tid: u32) -> i32 { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{GetThreadPriority, OpenThread, THREAD_QUERY_LIMITED_INFORMATION}; + unsafe { + let h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, tid); + assert!(!h.is_null(), "OpenThread({tid}) failed"); + let p = GetThreadPriority(h); + CloseHandle(h); + p + } + } + + #[test] + fn boost_token_refcounts_nested_guards() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; + let check_os = can_lower_preload_priority(); + let (tok_tx, tok_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let h = std::thread::spawn(move || { + if check_os { + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; + } + let tok = BoostToken::for_current_thread(); + tok_tx.send(tok).unwrap(); + let _ = done_rx.recv(); + }); + let tok = tok_rx.recv().unwrap(); + assert!(!tok.is_boosted()); + if check_os { + assert_eq!(thread_priority_of(tok.tid()), THREAD_PRIORITY_LOWEST); + } + let g1 = tok.boost(); + assert!(tok.is_boosted()); + if check_os { + assert_eq!(thread_priority_of(tok.tid()), THREAD_PRIORITY_NORMAL); + } + let g2 = tok.boost(); + assert!(tok.is_boosted()); + if check_os { + assert_eq!(thread_priority_of(tok.tid()), THREAD_PRIORITY_NORMAL); + } + drop(g1); + assert!(tok.is_boosted(), "still boosted while second guard lives"); + if check_os { + assert_eq!(thread_priority_of(tok.tid()), THREAD_PRIORITY_NORMAL, "still boosted while second guard lives"); + } + drop(g2); + assert!(!tok.is_boosted(), "unboosted once last guard drops"); + if check_os { + assert_eq!(thread_priority_of(tok.tid()), THREAD_PRIORITY_LOWEST, "restored once last guard drops"); + } + let _ = done_tx.send(()); + h.join().unwrap(); + } + + #[test] + fn resolve_wait_boosts_preload_worker_priority_and_restores_it() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; + let check_os = can_lower_preload_priority(); + let (standin, key) = (0x7E57_7011usize, 0x5EED_0011u64); + used::earlier_run_used(key); + let (started_tx, started_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + submit_lazy( + standin, + true, + Box::new(move || { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let tok = current_preload_token().expect("preload job must run on a preload worker"); + let before = unsafe { GetThreadPriority(GetCurrentThread()) }; + started_tx.send((tid, before, tok.clone())).unwrap(); + let _ = go_rx.recv(); + assert!(tok.is_boosted(), "preload worker must be marked boosted while resolve_wait waits"); + let during = unsafe { GetThreadPriority(GetCurrentThread()) }; + assert_eq!(during, THREAD_PRIORITY_NORMAL, "preload worker must run at NORMAL while resolve_wait waits"); + 0x5678 + }), + key, + ); + let (worker_tid, before_prio, worker_tok) = started_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + let expected_base = if check_os { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_NORMAL }; + assert_eq!(before_prio, expected_base, "unexpected initial preload worker priority"); + + // Call resolve_wait from another thread while the preload worker is mid-build + let waiter = std::thread::spawn(move || resolve_wait(standin)); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !worker_tok.is_boosted() || (check_os && thread_priority_of(worker_tid) != THREAD_PRIORITY_NORMAL) { + assert!(std::time::Instant::now() < deadline, "preload worker was not boosted to NORMAL"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + go_tx.send(()).unwrap(); + assert_eq!(waiter.join().unwrap(), 0x5678); + + // Once the preload job finishes, PreloadJobGuard drops and restores the base priority + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while worker_tok.is_boosted() || (check_os && thread_priority_of(worker_tid) != THREAD_PRIORITY_LOWEST) { + assert!(std::time::Instant::now() < deadline, "preload worker boost was not released after job completion"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + released(standin); + } } fn entry(pso: usize) -> Option> { @@ -356,7 +598,9 @@ pub fn resolve(pso: usize) -> usize { p.note_use(); match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: to the workers (and boost if a low-priority preload + // worker already picked it up) + p.promote_preload(); if !p.sent.swap(true, Ordering::AcqRel) { let _ = queue().lock().unwrap().send(p); } @@ -382,6 +626,10 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { let job = p.job.lock().unwrap().take(); if let Some(job) = job { complete(&p, job()); + } else { + // another worker owns the build; if it is a low-priority preload thread, raise its + // priority so the caller does not stall behind THREAD_PRIORITY_LOWEST + p.promote_preload(); } let mut done = p.done.lock().unwrap(); while !*done { @@ -413,6 +661,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if *p.done.lock().unwrap() { return built(p); } + p.promote_preload(); if !p.sent.swap(true, Ordering::AcqRel) { let _ = queue().lock().unwrap().send(p.clone()); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5b01e8569..ada1937ee 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3336,34 +3336,101 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// DXIL size from which a compute pipeline's driver compile goes to the background const BIG_DRIVER_COMPILE: usize = 256 << 10; -/// A counting semaphore: background driver compiles of big programs at once. +/// A counting semaphore for background driver compiles of big programs: +/// - demand compiles (`xcl-pso-*`, or a preload worker already promoted by a bind) always run +/// ahead of speculative preload compiles (`xcl-pso-pre-*`); +/// - when a demand compile arrives while a `THREAD_PRIORITY_LOWEST` preload worker holds a slot, +/// that preload worker is boosted to `THREAD_PRIORITY_NORMAL` until it releases the slot. +struct PreloadHolder { + tok: std::sync::Arc, + boost: Option, +} + +struct SlotState { + active: usize, + demand_waiting: usize, + preload_holders: Vec, +} + struct Slots { - n: Mutex, + state: Mutex, cv: std::sync::Condvar, most: usize, } -struct SlotGuard(&'static Slots); +struct SlotGuard { + slots: &'static Slots, + holder_tid: u32, +} impl Slots { - fn acquire(&'static self) -> SlotGuard { - let mut n = self.n.lock().unwrap(); - while *n >= self.most { - n = self.cv.wait(n).unwrap(); + const fn new(most: usize) -> Self { + Self { + state: Mutex::new(SlotState { active: 0, demand_waiting: 0, preload_holders: Vec::new() }), + cv: std::sync::Condvar::new(), + most, + } + } + + fn acquire(&'static self, preload: Option>) -> SlotGuard { + let mut st = self.state.lock().unwrap(); + let is_demand = preload.as_ref().is_none_or(|tok| tok.is_boosted()); + if is_demand { + st.demand_waiting += 1; + // Boost any low-priority preload worker currently holding a slot so it vacates ASAP + for h in &mut st.preload_holders { + if h.boost.is_none() { + h.boost = Some(h.tok.boost()); + } + } + while st.active >= self.most { + st = self.cv.wait(st).unwrap(); + } + st.demand_waiting -= 1; + st.active += 1; + SlotGuard { slots: self, holder_tid: 0 } + } else { + let tok = preload.unwrap(); + while st.active >= self.most || (st.demand_waiting > 0 && !tok.is_boosted()) { + st = self.cv.wait(st).unwrap(); + } + st.active += 1; + let holder_tid = tok.tid(); + let boost = (st.demand_waiting > 0).then(|| tok.boost()); + st.preload_holders.push(PreloadHolder { tok, boost }); + SlotGuard { slots: self, holder_tid } } - *n += 1; - SlotGuard(self) + } + + fn notify_promoted(&self) { + let _g = self.state.lock().unwrap(); + self.cv.notify_all(); } } impl Drop for SlotGuard { fn drop(&mut self) { - *self.0.n.lock().unwrap() -= 1; - self.0.cv.notify_one(); + let removed = { + let mut st = self.slots.state.lock().unwrap(); + st.active -= 1; + let removed = if self.holder_tid != 0 { + st.preload_holders.iter().position(|h| h.tok.tid() == self.holder_tid).map(|i| st.preload_holders.swap_remove(i)) + } else { + None + }; + self.slots.cv.notify_all(); + removed + }; + drop(removed); } } -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; +static BIG_COMPILES: Slots = Slots::new(1); + +/// Wake `BIG_COMPILES` waiters when a preload worker is promoted to demand priority. +pub(crate) fn notify_big_compiles() { + BIG_COMPILES.notify_promoted(); +} /// Before a big driver compile in the background: until 3 GB of commit are free (each takes /// ~1.5 GB; the title loading next to it must not run out – no minute's grace as for DXC). @@ -3430,7 +3497,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi let started = std::time::Instant::now(); // in the background, one at a time and within the commit left (each ~1.5 GB in the driver) let _slot = (big && cached.is_none() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso"))).then(|| { - let slot = BIG_COMPILES.acquire(); + let slot = BIG_COMPILES.acquire(super::pso_async::current_preload_token()); wait_for_commit(); slot }); @@ -5764,4 +5831,92 @@ mod console_format_query_tests { assert!(pc.SizeInBytes != u64::MAX && pc.SizeInBytes >= 1920 * 1080 * 4 && pc.Alignment > 0, "PC {format} as {}: {:#x}", d.Format.0, pc.SizeInBytes); } } + + #[test] + fn big_compile_slots_boost_preload_holder_and_run_demand_first() { + use std::sync::mpsc; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetThreadPriority, OpenThread, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL, + THREAD_QUERY_LIMITED_INFORMATION, + }; + static TEST_SLOTS: Slots = Slots::new(1); + let check_os = super::super::pso_async::can_lower_preload_priority(); + let prio_of = |tid: u32| unsafe { + let h = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, 0, tid); + assert!(!h.is_null()); + let p = GetThreadPriority(h); + CloseHandle(h); + p + }; + + let (a_ready_tx, a_ready_rx) = mpsc::channel(); + let (a_release_tx, a_release_rx) = mpsc::channel(); + let (a_done_tx, a_done_rx) = mpsc::channel(); + let (order_tx, order_rx) = mpsc::channel(); + + // Thread A: preload worker acquires the single slot + let ta = std::thread::spawn(move || { + if check_os { + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; + } + let tok = super::super::pso_async::BoostToken::for_current_thread(); + let tid = tok.tid(); + let guard = TEST_SLOTS.acquire(Some(tok.clone())); + a_ready_tx.send((tid, tok)).unwrap(); + a_release_rx.recv().unwrap(); + drop(guard); + // Keep thread alive briefly so main can read its restored OS priority + a_done_tx.send(()).unwrap(); + a_release_rx.recv().unwrap(); + }); + let (a_tid, a_tok) = a_ready_rx.recv().unwrap(); + assert!(!a_tok.is_boosted()); + if check_os { + assert_eq!(prio_of(a_tid), THREAD_PRIORITY_LOWEST); + } + + // Thread B: another preload worker queues behind A first + let order_b = order_tx.clone(); + let (b_wait_tx, b_wait_rx) = mpsc::channel(); + let tb = std::thread::spawn(move || { + if check_os { + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; + } + let tok = super::super::pso_async::BoostToken::for_current_thread(); + b_wait_tx.send(()).unwrap(); + let _g = TEST_SLOTS.acquire(Some(tok)); + order_b.send("preload").unwrap(); + }); + b_wait_rx.recv().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + + // Thread C: demand worker arrives later -> must boost A and run BEFORE B + let order_c = order_tx; + let tc = std::thread::spawn(move || { + let _g = TEST_SLOTS.acquire(None); + order_c.send("demand").unwrap(); + }); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !a_tok.is_boosted() || (check_os && prio_of(a_tid) != THREAD_PRIORITY_NORMAL) { + assert!(std::time::Instant::now() < deadline, "preload holder A was not boosted by waiting demand compile"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + + // Release A: C (demand) must run before B (preload), and A's boost drops + a_release_tx.send(()).unwrap(); + a_done_rx.recv().unwrap(); + assert!(!a_tok.is_boosted(), "holder A boost released after dropping slot"); + if check_os { + assert_eq!(prio_of(a_tid), THREAD_PRIORITY_LOWEST, "holder A priority restored after releasing slot"); + } + assert_eq!(order_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(), "demand"); + assert_eq!(order_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(), "preload"); + + a_release_tx.send(()).unwrap(); + ta.join().unwrap(); + tb.join().unwrap(); + tc.join().unwrap(); + } }