From 4610f8f3b38009799a7e2d0cd009d154d935a84b Mon Sep 17 00:00:00 2001 From: abilliontokens <39147239+abilliontokens@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:40:30 -0800 Subject: [PATCH 1/3] D3D12.X: a bind that waits long on a pipeline's build makes a second copy A compute pipeline's first bind waits for its build. When a worker is already building it, the title's thread waited on that one build for as long as it took: on a retail title's world loading (RTX 5060 Ti, main f4ce27c) cdb showed 10 of 11 DXC threads and 10 of 11 pipeline workers parked, one build in flight, and the render thread in resolve_wait's condvar. Frames stopped, and the title's watchdog crashed it at +0x23cf683 at 93-101 s on four runs (#232, #581), with and without #690's preloading. After a grace period (250 ms; XCL_PSO_HELP_MS, 0 = off) the waiting thread builds a second copy itself, and the first of the two to finish is the pipeline (complete: the later one is released). go_background supplies the second copy's build; the descriptor is shared read-only (SharedDesc). A pipeline no run used still waits for its worker as before. Measured, same input and caches, 300 s runs that reach world loading: crash at 152.6 s instead of 93.4 / 100.4 s; 2669 frames instead of 1324 / 1443; background pipelines built 50987 against 121 / 866 on main. It does not reach gameplay: the next wait on the title's thread is the title-texture write-watch refresh (#551) and XMemMapPhysicalPagesScatter (#156). Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 108 +++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 43 ++++++---- 2 files changed, 120 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b303cf55e..575365ca9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -14,6 +14,8 @@ use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, + /// a second copy of the build, for a bind that waits too long on the worker building `job` + second: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, /// the real pipeline state (raw pointer), 0 while building or when building failed @@ -40,28 +42,38 @@ impl Pending { /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); -/// The build is done (`real`: its pipeline, 0 = failed). +/// The build is done (`real`: its pipeline, 0 = failed). The first build to finish is the +/// pipeline (a bind's second copy and the worker's may both end: the later one is released). fn complete(p: &Pending, real: usize) { + let mut done = p.done.lock().unwrap(); + if *done { + drop(done); + release(real); + return; + } if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { BUILT.fetch_add(1, Ordering::Relaxed); } - let orphan = { - let mut done = p.done.lock().unwrap(); - let orphan = p.orphan.load(Ordering::Acquire); - if !orphan { - p.real.store(real, Ordering::Release); - } - *done = true; - p.cv.notify_all(); - orphan - }; + let orphan = p.orphan.load(Ordering::Acquire); + if !orphan { + p.real.store(real, Ordering::Release); + } + *done = true; + p.cv.notify_all(); + drop(done); // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) if orphan { release(real); } } + +/// How long a bind waits for the worker that is building its pipeline before it builds a +/// second copy itself (`XCL_PSO_HELP_MS`; 0: never). +static HELP_AFTER: std::sync::LazyLock = std::sync::LazyLock::new(|| { + std::time::Duration::from_millis(std::env::var("XCL_PSO_HELP_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(250)) +}); static BUILT: AtomicUsize = AtomicUsize::new(0); static FAILED: AtomicUsize = AtomicUsize::new(0); @@ -124,8 +136,15 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { } fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { + submit_second(standin, compute, job, send, key, None) +} + +/// `submit_as` with a build of a second copy: a bind that waits longer than `HELP_AFTER` on +/// the worker building `job` builds it itself (`resolve_wait`). +pub fn submit_second(standin: usize, compute: bool, job: Job, send: bool, key: u64, second: Option) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), + second: Mutex::new(second), sent: std::sync::atomic::AtomicBool::new(send), real: AtomicUsize::new(0), done: Mutex::new(false), @@ -319,6 +338,47 @@ mod used_tests { } } +#[cfg(test)] +mod help_tests { + use super::*; + use std::sync::atomic::AtomicBool; + + /// A bind that waits on a worker whose build is slow makes a second copy after the grace + /// period and is done long before the worker; the worker's late result is not the pipeline. + #[test] + fn a_bind_waiting_on_a_slow_worker_builds_a_second_copy() { + let slow = 0x7E57_7011usize; + let started = std::sync::Arc::new(AtomicBool::new(false)); + let finished = std::sync::Arc::new(AtomicBool::new(false)); + let (s, e) = (started.clone(), finished.clone()); + // the worker's build takes 3 s and then has failed (0: nothing to release) + let worker = Box::new(move || { + s.store(true, Ordering::Release); + std::thread::sleep(std::time::Duration::from_secs(3)); + e.store(true, Ordering::Release); + 0usize + }); + submit_second(slow, true, worker, true, 0, Some(Box::new(|| 0x5556))); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !started.load(Ordering::Acquire) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(started.load(Ordering::Acquire), "a worker is building it"); + let start = std::time::Instant::now(); + let real = resolve_wait(slow); + let waited = start.elapsed(); + assert_eq!(real, 0x5556, "the second copy's build is the pipeline"); + assert!(waited < std::time::Duration::from_millis(1500), "not held up by the worker: {waited:?}"); + // the worker's build ends afterwards and does not replace it + while !finished.load(Ordering::Acquire) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + assert_eq!(resolve(slow), 0x5556); + released(slow); + } +} + fn entry(pso: usize) -> Option> { PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() } @@ -341,16 +401,30 @@ pub fn resolve(pso: usize) -> usize { /// `resolve`, waiting for a pipeline still being built – built here if no worker has started /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). +/// When a worker is building it and that takes long, the thread builds a second copy after +/// `HELP_AFTER` and the first of the two to finish is the pipeline: a retail title's world +/// loading waited on one slow build at a time with the rest of the machine idle. pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { + if let Some(job) = p.job.lock().unwrap().take() { complete(&p, job()); - } - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); + } else { + let start = std::time::Instant::now(); + let mut done = p.done.lock().unwrap(); + while !*done && start.elapsed() < *HELP_AFTER { + (done, _) = p.cv.wait_timeout(done, *HELP_AFTER - start.elapsed()).unwrap(); + } + let second = if *done { None } else { p.second.lock().unwrap().take() }; + drop(done); + // (None: another bind took it, or there is none: wait for the worker as before) + if let Some(job) = second { + complete(&p, job()); + } + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } } match p.real.load(Ordering::Acquire) { 0 => pso, diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e6c38326b..9d954a38c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3956,6 +3956,18 @@ unsafe fn standin_stream(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv) } +/// `OwnedDesc` shared by a worker's build and the second copy a bind may make of it: both +/// only read it. +#[derive(Clone)] +struct SharedDesc(std::sync::Arc); +unsafe impl Send for SharedDesc {} +unsafe impl Sync for SharedDesc {} +impl SharedDesc { + fn get(&self) -> &OwnedDesc { + &self.0 + } +} + /// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker. unsafe fn go_background( this: *mut c_void, @@ -3976,21 +3988,24 @@ unsafe fn go_background( } return None; } - let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); - let job: super::pso_async::Job = Box::new(move || { - let mut out: *mut c_void = std::ptr::null_mut(); - if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { - out as usize - } else { - 0 - } - }); - if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); - } else { - super::pso_async::submit(*ppv as usize, compute, job); - } + // the worker's build, and one of a second copy a bind makes when it waits too long on + // that worker (`pso_async::resolve_wait`) + let owned = SharedDesc(std::sync::Arc::new(owned)); + let dev = Dev(this as usize, f as usize); + let once = |owned: SharedDesc| -> super::pso_async::Job { + Box::new(move || { + let mut out: *mut c_void = std::ptr::null_mut(); + if unsafe { build(dev, owned.get(), &mut out) } && !out.is_null() { + out as usize + } else { + 0 + } + }) + }; + let (job, second) = (once(owned.clone()), Some(once(owned))); + let lazy = super::pso_async::lazy(); + super::pso_async::submit_second(*ppv as usize, compute, job, lazy, if lazy { key } else { 0 }, second); Some(hr) } From 3cca43340182368a02edd32f13105982577fdd9c Mon Sep 17 00:00:00 2001 From: abilliontokens <39147239+abilliontokens@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:38:55 -0800 Subject: [PATCH 2/3] D3D12.X: the second copy of a pipeline's build goes to a thread of its own Review of #754 found three faults in building the second copy on the waiting title thread: - the thread was inside the build when the worker finished, so a bind whose worker was computing returned at max(worker, 250 ms + copy) instead of the worker's own time: slower, not faster, in the common case; - the one-big-driver-compile-at-a-time slot and the 3 GB commit gate take only threads named xcl-pso* (real::translated_compute_pso), so a copy on a title thread ran a ~1.5 GB driver compile outside both; - translation recurses deeply and a title's thread may have a 1 MiB stack, while XCL's own build threads get 64 MB. The copy now goes to an xcl-pso-help thread with a 64 MB stack: the gates take it for one of theirs, and the waiting thread goes back to the condvar, so the worker finishing first still wakes it at once. Two more from the same review: XCL_PSO_HELP_MS=0 is documented as off and now is (it used to help without waiting at all), and a copy that fails no longer finalises the pipeline as failed - the worker's build still decides, instead of every later dispatch of it being skipped. Its test is new. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 55 ++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 575365ca9..66696339d 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -377,6 +377,30 @@ mod help_tests { assert_eq!(resolve(slow), 0x5556); released(slow); } + + /// A second copy that fails decides nothing: the worker's build is still the pipeline, and + /// the bind returns it (a copy that ran short of commit used to leave the pipeline failed + /// for the rest of the run, so every dispatch of it was skipped). + #[test] + fn a_second_copy_that_fails_leaves_the_workers_build_to_decide() { + let pso = 0x7E57_7012usize; + let started = std::sync::Arc::new(AtomicBool::new(false)); + let s = started.clone(); + let worker = Box::new(move || { + s.store(true, Ordering::Release); + std::thread::sleep(std::time::Duration::from_millis(700)); + 0x7777usize + }); + submit_second(pso, true, worker, true, 0, Some(Box::new(|| 0))); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !started.load(Ordering::Acquire) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(started.load(Ordering::Acquire), "a worker is building it"); + assert_eq!(resolve_wait(pso), 0x7777, "the worker's build, not the copy's failure"); + assert_eq!(resolve(pso), 0x7777); + released(pso); + } } fn entry(pso: usize) -> Option> { @@ -401,13 +425,17 @@ pub fn resolve(pso: usize) -> usize { /// `resolve`, waiting for a pipeline still being built – built here if no worker has started /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). -/// When a worker is building it and that takes long, the thread builds a second copy after -/// `HELP_AFTER` and the first of the two to finish is the pipeline: a retail title's world -/// loading waited on one slow build at a time with the rest of the machine idle. +/// When a worker has it and is still not done after `HELP_AFTER`, a second copy of the build +/// goes to a thread of its own and the first of the two to finish is the pipeline: a worker +/// held up before its build (the one big driver compile at a time, the commit and DXC gates) +/// otherwise keeps the title's thread waiting with the machine idle. The copy builds on its +/// own thread, not this one: translation recurses deeply and a title's thread may have a +/// small stack, and waiting inside the build would miss the worker finishing first. pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if let Some(job) = p.job.lock().unwrap().take() { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { complete(&p, job()); } else { let start = std::time::Instant::now(); @@ -415,11 +443,24 @@ pub fn resolve_wait(pso: usize) -> usize { while !*done && start.elapsed() < *HELP_AFTER { (done, _) = p.cv.wait_timeout(done, *HELP_AFTER - start.elapsed()).unwrap(); } - let second = if *done { None } else { p.second.lock().unwrap().take() }; + // (None: already built, another bind took it, there is none, or help is off) + let second = if *done || HELP_AFTER.is_zero() { None } else { p.second.lock().unwrap().take() }; drop(done); - // (None: another bind took it, or there is none: wait for the worker as before) if let Some(job) = second { - complete(&p, job()); + let p = p.clone(); + // `xcl-pso-help`: the big-driver-compile slot and the commit gate take it for one + // of theirs (`real::translated_compute_pso`), and 64 MB for the translation + let spawned = std::thread::Builder::new().name("xcl-pso-help".into()).stack_size(64 << 20).spawn(move || { + // a copy that fails decides nothing: the worker's own build still completes it + let real = job(); + if real != 0 { + complete(&p, real); + } + }); + if let Err(e) = spawned { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: no thread for a second copy of a pipeline's build ({e}) – waiting for the worker")); + } } let mut done = p.done.lock().unwrap(); while !*done { From 614f2cc48465da9e5204bb8cd20a246988374a0b Mon Sep 17 00:00:00 2001 From: abilliontokens <39147239+abilliontokens@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:12:03 -0800 Subject: [PATCH 3/3] D3D12.X: a pipeline with a second copy of its build stays lazy Three faults found in review of #754: - go_background passed `send = lazy` to submit_second, inverting lazy creation: with it on (the default) every pipeline a title made went to the workers at once, and with XCL_LAZY_PSO=0 none did until its first bind. A retail title makes ~51 000 pipelines in its first 30 s and uses few, which is what `lazy` exists to avoid, so the measurements in the description carried that cost rather than the second copy's effect. It is `!lazy` now. - The copy was kept for the life of the pipeline, holding the descriptor its build reads; `complete` drops it once there is a pipeline. - A build that failed could win over a success still being built. The first build that *succeeds* is the pipeline now; a failure no longer takes its place, and the later result is released. The test pins submit_second's own contract: a pipeline with a second copy is built on its first use, not before, and an eager one is built without a use. It does not cover go_background's call (that needs a device). Thanks to bstillbstill and CowboyBingus for the inverted `send`, and to bstillbstill for the other two. Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 47 ++++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 3 +- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 66696339d..0ab45f740 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -42,11 +42,13 @@ impl Pending { /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); -/// The build is done (`real`: its pipeline, 0 = failed). The first build to finish is the -/// pipeline (a bind's second copy and the worker's may both end: the later one is released). +/// The build is done (`real`: its pipeline, 0 = failed). The first build that *succeeds* is the +/// pipeline: a bind's second copy and the worker's may both end, and a failure does not take +/// the place of a success that is still coming (the later pipeline is released). fn complete(p: &Pending, real: usize) { let mut done = p.done.lock().unwrap(); - if *done { + // a failure after any result, or a result after a successful one: not this pipeline + if *done && (real == 0 || p.real.load(Ordering::Acquire) != 0) { drop(done); release(real); return; @@ -63,6 +65,10 @@ fn complete(p: &Pending, real: usize) { *done = true; p.cv.notify_all(); drop(done); + // the copy is not wanted any more: it holds the descriptor the build reads + if real != 0 { + let _ = p.second.lock().unwrap().take(); + } // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) if orphan { release(real); @@ -401,6 +407,41 @@ mod help_tests { assert_eq!(resolve(pso), 0x7777); released(pso); } + + /// A pipeline with a second copy is still lazy: it waits for its first use, as + /// `submit_lazy` does. `go_background` passed the wrong `send` once and every pipeline a + /// title made went to the workers at creation, which is what `lazy` exists to avoid + /// (~51 000 of them, ~400 KB each in the driver). + #[test] + fn a_lazy_pipeline_with_a_second_copy_waits_for_its_first_use() { + let (lazy_pso, eager) = (0x7E57_7013usize, 0x7E57_7014usize); + let built = std::sync::Arc::new(AtomicBool::new(false)); + let b = built.clone(); + submit_second(lazy_pso, false, Box::new(move || { + b.store(true, Ordering::Release); + 0x8881 + }), false, 0, Some(Box::new(|| 0x8882))); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!built.load(Ordering::Acquire), "nothing built it before its first use"); + assert!(is_pending(lazy_pso)); + // its first use sends it to the workers + assert_eq!(resolve_wait(lazy_pso), 0x8881); + assert!(built.load(Ordering::Acquire)); + // and `send` builds one straight away, with no use at all + let done = std::sync::Arc::new(AtomicBool::new(false)); + let d = done.clone(); + submit_second(eager, false, Box::new(move || { + d.store(true, Ordering::Release); + 0x8883 + }), true, 0, None); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !done.load(Ordering::Acquire) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(done.load(Ordering::Acquire), "an eager one is built by a worker without a use"); + released(lazy_pso); + released(eager); + } } fn entry(pso: usize) -> Option> { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9d954a38c..06e61e460 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4004,8 +4004,9 @@ unsafe fn go_background( }) }; let (job, second) = (once(owned.clone()), Some(once(owned))); + // `send`: a lazy pipeline goes to the workers on its first `resolve`, an eager one now let lazy = super::pso_async::lazy(); - super::pso_async::submit_second(*ppv as usize, compute, job, lazy, if lazy { key } else { 0 }, second); + super::pso_async::submit_second(*ppv as usize, compute, job, !lazy, if lazy { key } else { 0 }, second); Some(hr) }