diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..16fcb27f2f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -544,7 +544,8 @@ pub(super) unsafe fn emit_prepared_indexed_draw( unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) + // a pipeline still being built in the background: its stand-in, which draws nothing + // (`resolve_wait` waits for it only up to `XCL_PSO_WAIT_MS`) let real = super::pso_async::resolve_wait(pso); if !super::real::is_translated_graphics(real) { // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in @@ -1026,7 +1027,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); Ok(p as usize) }; - // a pipeline still being built in the background is waited for + // (only reached with a translated pipeline: built, `resolve_wait` returns it at once) let real = super::pso_async::resolve_wait(pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; @@ -1111,8 +1112,8 @@ mod tests { pso_async::submit_lazy(built, false, Box::new(|| 0x1235), 0); pso_async::submit_lazy(failed, false, Box::new(|| 0), 0); assert!(pso_async::is_pending(building)); - assert_eq!(pso_async::resolve_wait(built), 0x1235); - assert_eq!(pso_async::resolve_wait(failed), failed); + assert_eq!(pso_async::wait_built(built), 0x1235); + assert_eq!(pso_async::wait_built(failed), failed); assert!(!pso_async::is_pending(built) && !pso_async::is_pending(failed)); // never resolved: still pending (the skip case), then forgotten assert!(pso_async::is_pending(building)); @@ -1447,7 +1448,7 @@ void main(uint t : SV_GroupIndex) { real_ok }), ); - assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); + assert_eq!(pso_async::wait_built(standin_ok), real_ok); assert!(!real::is_translated_compute(standin_ok)); assert!(real::is_translated_compute(real_ok)); @@ -1468,7 +1469,7 @@ void main(uint t : SV_GroupIndex) { // onto S_fail, and ExecuteIndirect must not enter bind_abi either. let standin_fail = 0x7200_0003usize; pso_async::submit(standin_fail, true, Box::new(|| 0)); - assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); + assert_eq!(pso_async::wait_built(standin_fail), standin_fail); assert!(!real::is_translated_compute(standin_fail)); reset(list_ptr, 0x7200_0100, standin_fail); @@ -1562,7 +1563,7 @@ void main(uint t : SV_GroupIndex) { let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; // With shared stand-ins (`standin::shell`), `dev_create_compute_pso` registers the - // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::resolve_wait` returns the + // title-facing shell in `CONSOLE_COMPUTE`, while `pso_async::wait_built` returns the // shared driver pipeline when the background build fails. let shell_fail = 0x7210_0001usize; let shell_ok = 0x7210_0002usize; @@ -1589,7 +1590,7 @@ void main(uint t : SV_GroupIndex) { pso_async::shared(shell_ok, shared_driver); real::register_console_compute_for_test(shell_ok); - assert_eq!(pso_async::resolve_wait(shell_fail), shared_driver); + assert_eq!(pso_async::wait_built(shell_fail), shared_driver); assert!(!pso_async::is_pending(shell_fail)); assert!(real::is_console_compute(shell_fail)); assert!(!real::is_console_compute(shared_driver)); @@ -1611,6 +1612,8 @@ void main(uint t : SV_GroupIndex) { // 2. Another shell sharing the same driver pipeline whose build succeeds still takes the // translated path (caught here by the root-changing guard rather than falling through to PC). + // (built first: a bind does not build it, `resolve_wait`) + assert_eq!(pso_async::wait_built(shell_ok), real_ok); reset(list_ptr, 0x7210_0100, shell_ok); unsafe { execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); @@ -1699,7 +1702,7 @@ void main(uint t : SV_GroupIndex) { real_tp }), ); - assert_eq!(pso_async::resolve_wait(standin_tp), real_tp); + assert_eq!(pso_async::wait_built(standin_tp), real_tp); assert!(real::two_pass_of(real_tp).is_some()); assert!(!real::is_translated_graphics(real_tp)); @@ -1779,7 +1782,7 @@ void main(uint t : SV_GroupIndex) { let standin = 0x7300_0001usize; let pso1_raw = pso1.as_raw() as usize; pso_async::submit(standin, true, Box::new(move || pso1_raw)); - assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + assert_eq!(pso_async::wait_built(standin), pso1_raw); let mut raw_list: *mut c_void = std::ptr::null_mut(); let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7726419583..24467fd453 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -878,9 +878,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { at += 4; match pso { Some(p) if (*p).translated => { - // a pipeline still being built in the background is waited for; if - // the background translation failed, skip instead of binding XCL's - // ABI root signature onto the stand-in + // a pipeline still being built in the background (waited for only up + // to `XCL_PSO_WAIT_MS`) or whose background translation failed: skip + // instead of binding XCL's ABI root signature onto the stand-in let real = super::pso_async::resolve_wait((*p).pc); if !super::real::is_translated_compute(real) { out.skipped_dispatches += 1; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..92beebb5f9 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2650,6 +2650,13 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { + // Not while no bind or submit waits for a pipeline until it is built (`pso_async::resolve_wait` + // waits at most `XCL_PSO_WAIT_MS`): the call would only be skipped later, at the submit, and + // each put-off call costs a segment (a PC command list). Thousands of them ran a retail title + // out of command lists (#2581). It is recorded now and skipped as a stand-in's. + if !super::pso_async::waits_until_built() { + return false; + } if split(list, Some(what)).is_none() { return false; } @@ -7001,7 +7008,7 @@ mod tests { } #[test] - fn a_dispatch_with_a_pipeline_still_building_waits_at_the_submit() { + fn a_dispatch_with_a_pipeline_still_building_is_recorded_at_once_and_skipped() { use super::super::{bind, pso_async, title_list}; use std::time::{Duration, Instant}; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -7041,31 +7048,32 @@ mod tests { bind::reset(pc0, alloc.as_raw() as usize, standin); let wrap = title_list::wrap(pc0); + // (no `XCL_PSO_WAIT_MS`: nothing waits for the build, so no dispatch is put off to the + // submit; each is recorded at once and skipped as a stand-in's) const DISPATCHES: usize = 210; - let mut segs = vec![pc0]; + let skipped = bind::counts_snapshot()[4]; for n in 1..=DISPATCHES { let t = Instant::now(); - bind::dispatch(*segs.last().unwrap(), 1, 1, 1); + bind::dispatch(pc0, 1, 1, 1); assert!(t.elapsed() < Duration::from_millis(700), "dispatch {n} waited for the build ({:?})", t.elapsed()); - segs.clear(); - assert!(title_list::push_segments(wrap, &mut segs)); } - assert_eq!(segs.len(), 1 + 2 * DISPATCHES, "the list before each dispatch, the dispatch, the list after it"); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 1, "a dispatch was put off to the submit"); + assert!(bind::counts_snapshot()[4] >= skipped + DISPATCHES as u64, "each dispatch is skipped at the bind"); assert!(pso_async::is_pending(standin)); let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); assert_eq!(close_fn(wrap), 0); assert!(pso_async::is_pending(standin), "Close waited for the build"); - let skipped = bind::counts_snapshot()[4]; - let build = std::thread::spawn(|| { - std::thread::sleep(Duration::from_millis(300)); - BUILD.store(true, Ordering::Release); - }); record_deferred(wrap); - assert!(!pso_async::is_pending(standin), "the submit waits for the build"); - assert!(bind::counts_snapshot()[4] > skipped, "the dispatch of a build that failed is skipped, at the submit"); - build.join().unwrap(); + assert!(pso_async::is_pending(standin), "the submit waited for the build"); + BUILD.store(true, Ordering::Release); + let t = Instant::now(); + while pso_async::is_pending(standin) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..ae2a058cff 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -3,8 +3,9 @@ //! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in //! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding //! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon -//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited -//! for where it is used, a `Dispatch` at its submit (a skipped dispatch would corrupt what it computes). +//! as it is there. Until then a graphics pipeline draws nothing and a compute pipeline's +//! dispatches are skipped: a bind never builds a pipeline on the title's thread, and waits for +//! one only up to `XCL_PSO_WAIT_MS` (`resolve_wait`), so no dispatch is put off to the submit. //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; @@ -12,7 +13,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; 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 + /// the build, until a worker takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) sent: std::sync::atomic::AtomicBool, @@ -29,7 +30,8 @@ struct Pending { used: std::sync::atomic::AtomicBool, /// the stand-in was released before the real pipeline was built orphan: std::sync::atomic::AtomicBool, - /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built + /// a bind went on without it (past `wait_budget`, or with none): binds do not wait for it + /// until it is built late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, @@ -323,7 +325,7 @@ fn build_queued(p: &Arc) { drop_unstarted_job(p); return; } - // (None: a bind took it and builds it itself) + // (None: a preload worker took it) let job = p.job.lock().unwrap().take(); if let Some(job) = job { build(p, job, false); @@ -370,10 +372,9 @@ pub fn submit(standin: usize, compute: bool, job: Job) { } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get -/// their stand-in when made and are built when first used – the first bind of a graphics one -/// sends it to the workers, a compute one is built at its first bind. A retail game makes -/// ~51 000 pipelines in its first 30 s and uses few; each one built stays in the driver -/// (~400 KB), and the process ran out of commit. +/// their stand-in when made and are built when first used – the first bind of one sends it to +/// the workers. A retail game makes ~51 000 pipelines in its first 30 s and uses few; each one +/// built stays in the driver (~400 KB), and the process ran out of commit. pub fn lazy() -> bool { static L: OnceLock = OnceLock::new(); *L.get_or_init(|| enabled() && std::env::var("XCL_LAZY_PSO").map_or(true, |v| v != "0")) @@ -426,11 +427,11 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// (`used-pipelines.txt` beside the DXIL cache, a key a line). /// /// A lazy pipeline is built at its first use: until then a graphics one draws nothing, and a -/// compute one is waited for on the title's thread. A retail title's first frames of its world -/// use hundreds of pipelines for the first time at once. The pipelines of an earlier run are -/// built while the title loads instead (`preload`): measured on a build that skips a dispatch -/// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without -/// this and 94 – 150 with it. +/// compute one's dispatches are skipped (after a wait of up to `XCL_PSO_WAIT_MS`). A retail +/// title's first frames of its world use hundreds of pipelines for the first time at once. The +/// pipelines of an earlier run are built while the title loads instead (`preload`): measured on +/// a build that skips a dispatch instead of waiting for its pipeline, ~2 170 dispatches were +/// skipped in those frames without this and 94 – 150 with it. mod used { use std::collections::HashSet; use std::io::Write; @@ -540,7 +541,7 @@ fn preload() -> Option<&'static Preload> { drop_unstarted_job(&p); continue; } - // (None: a bind took it and builds it itself) + // (None: a worker a bind sent it to took it) let job = p.job.lock().unwrap().take(); if let Some(job) = job { build(&p, job, true); @@ -597,8 +598,8 @@ mod used_tests { calls.end(20, 8, now); } - /// While a bind waits for a pipeline still being built, the title is held (`title_held`): - /// `kernelx::Sleep` does not count that time. + /// While a bind waits (within its budget) for a pipeline still being built, the title is held + /// (`title_held`): `kernelx::Sleep` does not count that time. #[test] fn a_bind_waiting_for_a_build_holds_the_title() { let standin = 0x7E57_B002usize; @@ -609,9 +610,9 @@ mod used_tests { let _ = finish.recv(); 0x5252 }), 0); - let bind = std::thread::spawn(move || resolve_wait_for(standin, None)); + let bind = std::thread::spawn(move || resolve_wait_for(standin, Some(std::time::Duration::from_secs(30)))); building.recv_timeout(std::time::Duration::from_secs(10)).expect("the pipeline is being built"); - // (built in the bind, or by a worker with the bind about to wait for it) + // (built by a worker, with the bind about to wait for it) let t = std::time::Instant::now(); while !title_held() && t.elapsed() < std::time::Duration::from_secs(10) { std::thread::sleep(std::time::Duration::from_millis(1)); @@ -634,9 +635,11 @@ mod used_tests { shared(s, driver); assert_eq!(entry(s).unwrap().stand(s), driver); } - assert_eq!(resolve_wait_for(fails, None), driver, "its build failed"); + assert_eq!(resolve_wait_for(fails, None), driver, "not built yet"); + assert_eq!(wait_built(fails), driver, "its build failed"); assert_eq!(resolve(fails), driver); - assert_eq!(resolve_wait_for(builds, None), 0x1234); + assert_eq!(resolve_wait_for(builds, None), driver, "not built yet"); + assert_eq!(wait_built(builds), 0x1234); assert_eq!(resolve_for_bind(builds), 0x1234); // (0x1234 is no pipeline: taken, not released) assert_eq!((released(fails), released(builds)), (0, 0x1234)); @@ -644,8 +647,8 @@ mod used_tests { /// A bind does not wait for a compute pipeline that writes only images: it gets the stand-in /// at once, with no budget, the build goes to the workers - /// unwanted, and once built the bind gets the real one. Without `image_only` the same bind - /// waits until the pipeline is built. + /// unwanted, and once built the bind gets the real one. Without `image_only` a bind with a + /// budget waits for it. #[test] fn a_bind_does_not_wait_for_a_pipeline_that_writes_only_images() { let (spared, waited) = (0x7E57_B0A1usize, 0x7E57_B0A2usize); @@ -675,12 +678,12 @@ mod used_tests { std::thread::sleep(std::time::Duration::from_millis(5)); } assert_eq!(resolve_wait_for(spared, None), 0x5A5A, "built by a worker"); - // the same build without the mark: the bind waits for it + // the same build without the mark: a bind with a budget waits for it submit_lazy(waited, true, Box::new(|| { std::thread::sleep(std::time::Duration::from_millis(100)); 0x5B5B }), 0); - assert_eq!(resolve_wait_for(waited, None), 0x5B5B); + assert_eq!(resolve_wait_for(waited, Some(std::time::Duration::from_secs(30))), 0x5B5B); let _ = released(spared); let _ = released(waited); } @@ -737,6 +740,41 @@ mod used_tests { let _ = released(standin); } + /// A bind with no budget neither builds a cold pipeline on its own thread nor waits for it, + /// compute or graphics: it gets the stand-in at once, a worker builds the pipeline wanted, and + /// once built binds get the real one. + #[test] + fn a_bind_with_no_budget_neither_builds_nor_waits_for_the_pipeline() { + for (standin, compute, real) in [(0x7E57_B0C1usize, true, 0x5C5Cusize), (0x7E57_B0C2, false, 0x5D5D)] { + let (go, finish) = mpsc::channel::<()>(); + let (tx, rx) = mpsc::channel(); + submit_lazy(standin, compute, Box::new(move || { + let _ = tx.send((std::thread::current().name().map(str::to_owned), wanted_here()())); + let _ = finish.recv(); + real + }), 0); + // (on a thread: a bind that builds or waits would wait for `go`, below) + let (bound_tx, bound) = mpsc::channel(); + std::thread::spawn(move || { + let _ = bound_tx.send((resolve_wait_for(standin, None), resolve_wait_for(standin, None))); + }); + let binds = bound.recv_timeout(std::time::Duration::from_secs(5)); + if binds.is_err() { + let _ = go.send(()); + } + assert_eq!(binds.expect("the binds built or waited for the pipeline"), (standin, standin), "still being built: the stand-in"); + let (thread, wanted) = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker builds it"); + assert!(thread.as_deref().is_some_and(|n| n.starts_with("xcl-pso")), "built on {thread:?}, not on a worker"); + assert!(wanted, "the title binds it: its build is wanted"); + assert!(is_pending(standin)); + go.send(()).unwrap(); + assert_eq!(wait_built(standin), real); + assert_eq!(resolve_wait_for(standin, None), real, "built: the real one"); + assert!(!is_pending(standin)); + let _ = released(standin); + } + } + /// A compile a worker's build starts is wanted once a bind waits for the build – asked from /// another thread, as the DXC workers do; a thread that builds nothing (no title runs here) /// wants nothing. @@ -754,7 +792,7 @@ mod used_tests { })); let wanted = rx.recv().unwrap(); assert!(!wanted(), "nobody waits yet"); - assert_eq!(resolve_wait_for(standin, None), 0x5454); + assert_eq!(resolve_wait_for(standin, Some(std::time::Duration::from_secs(30))), 0x5454); assert!(wanted()); assert!(!wanted_here()()); let _ = released(standin); @@ -776,7 +814,7 @@ mod used_tests { })); started.recv().unwrap(); assert!(!build_is_wanted(), "this thread builds nothing"); - assert_eq!(resolve_wait_for(standin, None), 0x5353, "the bind's wait reached the build"); + assert_eq!(resolve_wait_for(standin, Some(std::time::Duration::from_secs(30))), 0x5353, "the bind's wait reached the build"); let _ = released(standin); } @@ -804,7 +842,8 @@ mod used_tests { assert_eq!(resolve(known), 0x4321); assert!(is_pending(unknown), "nobody used it and no earlier run did"); assert!(!used::noted(unknown_key)); - assert_eq!(resolve_wait(unknown), 0x4322); + assert_eq!(resolve_wait_for(unknown, None), unknown, "a bind does not wait for it"); + assert_eq!(wait_built(unknown), 0x4322); assert!(used::noted(unknown_key) && used::noted(known_key), "a first use is kept for the next run"); released(known); released(unknown); @@ -1064,48 +1103,41 @@ 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). +/// `resolve` for a bind that needs the pipeline itself (a dispatch, a draw): waits up to +/// `wait_budget` for a pipeline still being built, else gets the stand-in at once. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +/// `resolve_wait`, waiting at most `budget` (None: not at all). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); if p.spared.load(Ordering::Acquire) { return resolve_spared(&p, pso); } + let Some(budget) = budget else { return resolve_unwaited(&p, pso) }; // (the title's thread is held from here until the pipeline is built or the budget is over) let _held = (!*p.done.lock().unwrap()).then(Held::new); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); - } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); - } - p.want(); - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); - } - match p.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, - } + resolve_within(&p, pso, budget) } -/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until -/// it is built). A retail game builds compute programs on its own threads: the driver takes up to -/// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. +/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: not at +/// all, `resolve_unwaited`). A retail game builds compute programs on its own threads: the driver +/// takes up to 30 s for the biggest translated ones, and the title's watchdog ends it when its +/// main thread has been held 30 s. fn wait_budget() -> Option { static B: OnceLock> = OnceLock::new(); *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) } +/// Whether a bind or a submit waits for a pipeline still being built until it is built. Not since +/// a bind with no budget gets the stand-in at once (`resolve_unwaited`): `list_x::defer` then puts +/// no call off to the submit. +pub fn waits_until_built() -> bool { + false +} + /// `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 /// dispatches are skipped) until a worker has built it. @@ -1138,6 +1170,35 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> p.stand(pso) } +/// `resolve_wait` with no budget: the real pipeline once built, else the stand-in at once (its +/// dispatches and draws are left out), with the build sent to the workers. +/// +/// The title's thread neither builds the pipeline nor waits for it. A bind that built a cold +/// pipeline itself and waited for it kept a retail title's thread in the driver's compile of a +/// 2.4 MB compute program for 466 s, with no frame shown after it (it never finished). Unlike +/// `resolve_spared` the build is `wanted`: the title binds it now, so it goes before the builds +/// made ahead and does not wait for free commit (up to `real::big_compile_turn`'s cap). +fn resolve_unwaited(p: &Arc, pso: usize) -> usize { + match p.real.load(Ordering::Acquire) { + 0 => { + // (before it is sent: the worker's compiles see it wanted from their start) + p.want(); + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a pipeline bound while it is still being built: its binds go on without it until it is ({} so far)", n + 1); + } + } + p.stand(pso) + } + r => r, + } +} + /// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing /// but images (`gpu::effects::big_and_image_only`); its dispatches are left out until a worker /// has built it. Off by default: what such a program draws is missing for that long. @@ -1181,7 +1242,8 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { } } -/// For binding: compute pipelines are waited for, graphics ones are not. +/// For binding: compute pipelines are waited for up to `XCL_PSO_WAIT_MS` (`resolve_wait`), +/// graphics ones are not. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { Some(p) if p.compute => resolve_wait(pso), @@ -1207,6 +1269,26 @@ pub fn released(pso: usize) -> usize { 0 } +/// The pipeline of stand-in `pso` once its build is over: the real one, or the stand-in's +/// driver pipeline when the build failed; `pso` itself at once when it is no stand-in (also with +/// `XCL_ASYNC_PSO=0`: pipelines are built in the call, none is pending). Waits as long as the +/// build takes – for tools and tests, never for a bind (`resolve_wait`). +pub fn wait_built(pso: usize) -> usize { + let Some(p) = entry(pso) else { return pso }; + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } + drop(done); + match p.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + } +} + /// `pso` is a stand-in whose real pipeline is still being built. pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91085d3933..f33fb2421b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6868,7 +6868,7 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt } } -/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for at its use). +/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for at its use, up to `XCL_PSO_WAIT_MS`). /// SetPipelineState on the PC list (a pipeline still building in the background: its stand-in) pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { cl_set_pipeline_state(this, pso) diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index ce77d502e0..8bf36985d4 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -299,7 +299,7 @@ fn mirror_program_through_the_hook(dev: &ID3D12Device) { unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; let pso = pso.expect("CreateComputePipelineState through the backend hook"); // built in the background behind a stand-in when its shader was not compiled yet - let real_raw = xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void; + let real_raw = xcl::hle::d3d12x::pso_async::wait_built(pso.as_raw() as usize) as *mut std::ffi::c_void; let after = real::stats(); assert_eq!(after.translated_pipelines, before.translated_pipelines + 1, "PSO was not built from the translated shader: {:?}", after.translation_errors); assert!( @@ -438,7 +438,7 @@ fn async_compute_pso_registers_real_pso_and_not_standin() { let standin_raw = pso.as_raw() as usize; assert!(!real::is_translated_compute(standin_raw), "stand-in compute PSO must not be registered in TRANSLATED_COMPUTE"); - let real_raw = pso_async::resolve_wait(standin_raw); + let real_raw = pso_async::wait_built(standin_raw); assert_ne!(real_raw, standin_raw, "cold DXIL cache must build compute PSO asynchronously behind a stand-in"); assert!(real::is_translated_compute(real_raw), "background-built real compute PSO must be registered in TRANSLATED_COMPUTE"); assert!(!real::is_translated_compute(standin_raw), "stand-in must remain unregistered after background build"); @@ -498,7 +498,7 @@ fn console_compute_without_an_exec_write_has_the_wave_size_of_its_header() { let pso: Result = unsafe { dev.CreateComputePipelineState(&desc) }; unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; let pso = pso.expect("CreateComputePipelineState through the backend hook"); - let real_raw = pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void; + let real_raw = pso_async::wait_built(pso.as_raw() as usize) as *mut std::ffi::c_void; assert!(real::is_translated_compute(real_raw as usize), "flags {flags:#x}: not built from the translated shader: {:?}", real::stats().translation_errors); let pso = unsafe { ID3D12PipelineState::from_raw_borrowed(&real_raw) }.unwrap().clone(); let rs_raw = real::pso_root_signature(pso.as_raw() as usize).expect("root signature of the translated PSO") as *mut std::ffi::c_void; diff --git a/crates/xcl/tests/gpu_pso_e2e.rs b/crates/xcl/tests/gpu_pso_e2e.rs index 6e3968fdb1..63142c7767 100644 --- a/crates/xcl/tests/gpu_pso_e2e.rs +++ b/crates/xcl/tests/gpu_pso_e2e.rs @@ -136,7 +136,7 @@ fn pso_through_hook(dev: &ID3D12Device, vs: &[u8], ps: &[u8], layout: &[(&CStr, /// The real pipeline of `pso` (waits when it is a stand-in still being built). fn real_pso(pso: &ID3D12PipelineState) -> ID3D12PipelineState { - let real = xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void; + let real = xcl::hle::d3d12x::pso_async::wait_built(pso.as_raw() as usize) as *mut std::ffi::c_void; unsafe { ID3D12PipelineState::from_raw_borrowed(&real) }.unwrap().clone() } @@ -179,7 +179,7 @@ fn pso_through_hook_raw(dev: &ID3D12Device, vs: &[u8], ps: &[u8], layout: &[(&CS let pso: ID3D12PipelineState = unsafe { dev.CreateGraphicsPipelineState(&desc) }.expect("CreateGraphicsPipelineState through the backend hook"); unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; // built in the background behind a stand-in when its shaders were not compiled yet - xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize); + xcl::hle::d3d12x::pso_async::wait_built(pso.as_raw() as usize); let after = real::stats(); assert_eq!(after.translated_pipelines, before.translated_pipelines + 1, "PSO was not built from the translated shaders: {:?}", after.translation_errors); assert_eq!(after.fallback_pipelines, before.fallback_pipelines, "fallback shaders were used"); @@ -348,7 +348,7 @@ fn retail_pipelines_built_in_the_background_behind_a_stand_in() { let raw = mesh.as_raw() as usize; // the title's description is gone (scribbled over); the worker builds from its own copy unsafe { std::ptr::write_bytes(&mut st as *mut Stream, 0xCD, 1) }; - assert_ne!(pso_async::resolve_wait(raw), raw); + assert_ne!(pso_async::wait_built(raw), raw); assert!(real::two_pass_of(raw).is_some(), "the two-pass parts through the stand-in"); println!("mesh: the call returned after {call:?}, the real pipeline was ready after {:?}", t0.elapsed()); // the title releases the stand-in: its real pipeline goes with it, the address is forgotten