diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index ef8aed8b8..b68b202eb 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -86,6 +86,8 @@ thread_local! { /// a backlog worker's build: whether it came from `Backlog::compute`; None once another /// worker took this one's place (`build_parks`) static PRELOAD_STEP: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// explicit late-build override for off-pool workers (e.g. `dispatch_chain`'s `xcl-pso-whole`) + static JOB_LATE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Run `p`'s build `job` on this thread (a worker's, or a bind's that took it): its time and @@ -120,10 +122,26 @@ pub(super) fn build_is_wanted() -> bool { } /// This thread is a worker building a pipeline a bind waited for and went on without -/// (`resolve_within`): nobody waits for it now, but the title's draws or dispatches with it are -/// left out until it is built (`real::huge_compile_turn`). +/// (`resolve_within`), or a background `xcl-pso-whole` worker (`with_late_build`): nobody waits +/// for it now, but the title's draws or dispatches with it are left out until it is built +/// (`real::huge_compile_turn`). pub(super) fn build_is_late() -> bool { - BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.late.load(Ordering::Acquire))) + JOB_LATE.with(|l| l.get()) + || BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.late.load(Ordering::Acquire))) +} + +/// Run `f` with `build_is_late() == true` on the current thread, restoring the previous state on +/// return or unwind. +pub(super) fn with_late_build(f: impl FnOnce() -> R) -> R { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + JOB_LATE.with(|l| l.set(self.0)); + } + } + let prev = JOB_LATE.with(|l| l.replace(true)); + let _reset = Reset(prev); + f() } /// This thread is a backlog worker building a pipeline nobody has used yet: its huge driver diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 57428482a..d1104ae2a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -80,11 +80,12 @@ struct ChainRef(Arc); unsafe impl Send for ChainRef {} impl Chain { - unsafe fn whole(&self) -> Result { + /// Build the whole form. `on_title_thread` is true only when a title thread is synchronously + /// blocked waiting for this compile (registers a long PC call). + unsafe fn whole(&self, on_title_thread: bool) -> Result { if let Some(p) = self.whole.get() { return Ok(p.clone()); } - // (a driver compile on the title's thread, of the largest programs: the title is held - // while it lasts, as in any other long PC call) - let _call = super::super::pso_async::pc_call(); + // (only when a title thread is held while this compile lasts, as in any other long PC call) + let _call = on_title_thread.then(super::super::pso_async::pc_call); let _guard = self.build_whole.lock().unwrap(); if let Some(p) = self.whole.get() { return Ok(p.clone()); } let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; @@ -93,6 +94,34 @@ impl Chain { } } +type WholeJob = Box; + +/// Single persistent worker (`xcl-pso-whole`, 64 MiB stack) for building split programs' whole +/// forms off the title thread. A single worker avoids spawning an unbounded number of 64 MiB-stack +/// OS threads behind `real::huge_compile_turn` (which already serializes late giant compiles), and +/// runs each job under `pso_async::with_late_build` so it gets half commit headroom. +fn whole_worker() -> Option<&'static std::sync::mpsc::Sender> { + static TX: OnceLock>> = OnceLock::new(); + TX.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("xcl-pso-whole".into()) + .stack_size(64 << 20) + .spawn(move || { + while let Ok(job) = rx.recv() { + super::super::pso_async::with_late_build(job); + } + }) + .ok() + .map(|_| tx) + }) + .as_ref() +} + +fn enqueue_whole(job: WholeJob) -> bool { + whole_worker().is_some_and(|tx| tx.send(job).is_ok()) +} + static CHAINS: LazyLock>>> = LazyLock::new(Default::default); pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, @@ -131,7 +160,7 @@ pub(super) fn forget(pso: usize) { pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - chain.map(|c| c.whole()).transpose() + chain.map(|c| c.whole(true)).transpose() } /// The whole form of a split program for an indirect dispatch, which runs no chain (its group @@ -140,16 +169,16 @@ pub(in crate::hle::d3d12x) enum Whole { /// no split program: the pipeline as it is Plain, Ready(ID3D12PipelineState), - /// still being built on a thread of its own: this dispatch goes without it + /// still being built on the `xcl-pso-whole` worker: this dispatch goes without it Late, } /// `whole` where a compute pipeline's dispatches go on without it while it is built -/// (`pso_async::cs_goes_on`): the whole form, the largest program the driver compiles, is built -/// by a thread of its own, once, and until it is there its dispatches are left out as those of -/// any late compute pipeline. Built in the call, a retail title's render thread stood in the -/// driver's compiler for it (1.1 MB of DXIL) and every other thread that dispatched it stood -/// behind `build_whole`: no frame for over two minutes after its first world frame. +/// (`pso_async::cs_goes_on`): the whole form, the largest program the driver compiles, is queued +/// onto the single `xcl-pso-whole` worker, once, and until it is there its dispatches are left out +/// as those of any late compute pipeline. Built in the call, a retail title's render thread stood +/// in the driver's compiler for it (1.1 MB of DXIL) and every other thread that dispatched it +/// stood behind `build_whole`: no frame for over two minutes after its first world frame. pub(in crate::hle::d3d12x) unsafe fn whole_ready(pso: usize) -> Result { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); let Some(chain) = chain else { return Ok(Whole::Plain) }; @@ -157,20 +186,19 @@ pub(in crate::hle::d3d12x) unsafe fn whole_ready(pso: usize) -> Result, bool)>::new())); + let (done_tx, done_rx) = mpsc::channel(); + const N: usize = 16; + for _ in 0..N { + let seen = seen.clone(); + let done_tx = done_tx.clone(); + assert!(super::enqueue_whole(Box::new(move || { + let id = std::thread::current().id(); + let name = std::thread::current().name().map(str::to_string); + let late = super::super::super::pso_async::build_is_late(); + seen.lock().unwrap().push((id, name, late)); + let _ = done_tx.send(()); + }))); + } + for _ in 0..N { + done_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("whole worker job finished"); + } + let rows = seen.lock().unwrap(); + assert_eq!(rows.len(), N); + let threads: HashSet = rows.iter().map(|(id, _, _)| *id).collect(); + assert_eq!(threads.len(), 1, "expected all whole-PSO jobs to run on a single worker thread"); + assert!(rows.iter().all(|(_, name, late)| name.as_deref() == Some("xcl-pso-whole") && *late)); + } + + #[test] + fn with_late_build_resets_after_return_and_panic() { + use super::super::super::pso_async::{build_is_late, with_late_build}; + + assert!(!build_is_late()); + let inside = with_late_build(build_is_late); + assert!(inside); + assert!(!build_is_late()); + + let panicked = std::panic::catch_unwind(|| { + with_late_build(|| { + assert!(build_is_late()); + panic!("unwind check"); + }); + }); + assert!(panicked.is_err()); + assert!(!build_is_late()); + } }