diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 0840dceb7..2ef1b9c41 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -203,12 +203,50 @@ fn pool() -> &'static std::sync::Mutex> { /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + if URGENT.with(|u| u.get()) { + return compile_now(src, entry, profile, extra); + } let (reply, rx) = std::sync::mpsc::channel(); let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply }; pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } +thread_local! { + /// inside `urgent` + static URGENT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Run `f` with its DXC compiles done at once, on a thread of their own: not queued behind the +/// background pipelines on the workers, not held by `wait_for_memory`. For a title thread that +/// waits in its pipeline creation (no stand-in): GTA VI's watchdog kills the game when one of +/// its threads stays silent ~30 s, and with commit short most workers sat in `wait_for_memory` +/// holding queued jobs while five title threads waited behind them. +pub fn urgent(f: impl FnOnce() -> R) -> R { + let prev = URGENT.with(|u| u.replace(true)); + let r = f(); + URGENT.with(|u| u.set(prev)); + r +} + +/// `compile` on a fresh `DXC_STACK` thread, waited for (counted in `WORKING`, so the workers' +/// `wait_for_memory` sees it). +fn compile_now(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + WORKING.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + let _slot = MemorySlot; + std::thread::scope(|s| { + let t = std::thread::Builder::new() + .name("xcl-dxc-urgent".into()) + .stack_size(DXC_STACK) + .spawn_scoped(s, || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(src, entry, profile, extra))) + .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())) + }) + .map_err(|e| format!("DXC: cannot start a compile thread: {e}"))?; + t.join().unwrap_or_else(|_| Err("DXC: the compile thread panicked".into())) + }) +} + fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let c = compiler()?; let mut args: Vec> = ["-E", entry, "-T", profile, "-HV", "2021"].iter().map(|a| crate::util::wide(a)).collect(); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index ff4a30fe7..13dd7ec32 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -21,6 +21,8 @@ struct Pending { compute: bool, /// the stand-in was released before the real pipeline was built orphan: std::sync::atomic::AtomicBool, + /// sent to the workers (a lazy pipeline is sent at its first use) + queued: std::sync::atomic::AtomicBool, } /// stand-in handed to the title → its real pipeline @@ -58,16 +60,19 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; +/// Stack of the threads that build pipelines: translation recurses deeply on big programs. +const BUILD_STACK: usize = 64 << 20; + fn queue() -> &'static Mutex>> { static Q: OnceLock>>> = OnceLock::new(); Q.get_or_init(|| { let (tx, rx) = mpsc::channel::>(); let rx = Arc::new(Mutex::new(rx)); - // translation recurses deeply on big programs; DXC itself runs on its own pool + // DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); for k in 0..n { let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(BUILD_STACK).spawn(move || loop { let next = rx.lock().unwrap().recv(); let Ok(p) = next else { return }; // (None: a bind took it and builds it itself) @@ -90,13 +95,53 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - let p = Arc::new(Pending { job: Mutex::new(Some(job)), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), compute, orphan: Default::default() }); - PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + let p = pending(standin, compute, job); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); - let _ = queue().lock().unwrap().send(p); + send(p); +} + +/// Pipelines built at their first use (`submit_lazy`), `XCL_LAZY_PSO=0` to build each when +/// the title creates it. A title can create far more pipelines than it draws with: the retail +/// GTA VI creates ~51 000 different ones in its first 30 s; each a pipeline in AMD's driver +/// (~400 KB of its heap) took 20 GB of commit and the system ran out. +pub fn lazy() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| enabled() && std::env::var("XCL_LAZY_PSO").map_or(true, |v| v != "0")) +} + +/// `submit`, the build waiting for the stand-in's first use (`resolve`, `resolve_wait`). +pub fn submit_lazy(standin: usize, compute: bool, job: Job) { + pending(standin, compute, job); + let n = LAZY.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n % 10_000 == 0 { + crate::xlog_info!("D3D12.X: pipelines are built at their first use ({n} created so far)"); + } +} + +static LAZY: AtomicUsize = AtomicUsize::new(0); + +fn pending(standin: usize, compute: bool, job: Job) -> Arc { + let p = Arc::new(Pending { + real: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute, + orphan: Default::default(), + job: Mutex::new(Some(job)), + queued: Default::default(), + }); + PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + p +} + +/// To the workers, once. +fn send(p: Arc) { + if !p.queued.swap(true, Ordering::AcqRel) { + let _ = queue().lock().unwrap().send(p); + } } fn entry(pso: usize) -> Option> { @@ -105,9 +150,14 @@ fn entry(pso: usize) -> Option> { /// The pipeline to use for `pso` now: the real one once built, else `pso` itself. pub fn resolve(pso: usize) -> usize { - match entry(pso).map(|p| p.real.load(Ordering::Acquire)) { - Some(r) if r != 0 => r, - _ => pso, + let Some(p) = entry(pso) else { return pso }; + match p.real.load(Ordering::Acquire) { + 0 => { + // a lazy pipeline's first use: build it now (the stand-in draws nothing meanwhile) + send(p); + pso + } + r => r, } } @@ -115,9 +165,21 @@ pub fn resolve(pso: usize) -> usize { /// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). pub fn resolve_wait(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + // not started yet: build it now instead of waiting behind the whole queue (thousands of + // pipelines while a title loads – GTA VI's watchdog killed the game while a title thread + // waited here), on a thread with the translator's stack, its compiles first let job = p.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + let real = std::thread::scope(|s| { + std::thread::Builder::new() + .name("xcl-pso-urgent".into()) + .stack_size(BUILD_STACK) + .spawn_scoped(s, || crate::gpu::recomp::dxc::urgent(job)) + .ok() + .and_then(|t| t.join().ok()) + .unwrap_or(0) + }); + complete(&p, real); } let mut done = p.done.lock().unwrap(); while !*done { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 408901615..eaf4141b4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3162,6 +3162,9 @@ unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, rii copy.StreamOutput = std::mem::zeroed(); copy.InputLayout = D3D12_INPUT_LAYOUT_DESC::default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + // the console's topology types (rect list 19, none) are not the PC's: the driver refused + // GTA VI's stand-ins (0x80070057) and the title waited in the call for its compiles + pc_topology_type(&mut copy); finish_pso(this, f, © as *const _ as *const c_void, riid, ppv) } @@ -3199,21 +3202,57 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - super::pso_async::submit( - *ppv as usize, - compute, - 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 - } - }), - ); + 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 LAZY_NEXT.with(|l| l.replace(false)) { + super::pso_async::submit_lazy(*ppv as usize, compute, job); + } else { + super::pso_async::submit(*ppv as usize, compute, job); + } Some(hr) } +thread_local! { + /// the next `go_background` builds at the pipeline's first use (`go_lazy`) + static LAZY_NEXT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `go_background` with the build left for the stand-in's first use (`pso_async::lazy`). +#[allow(clippy::too_many_arguments)] +unsafe fn go_lazy( + this: *mut c_void, + f: PsoFn, + desc: *const c_void, + riid: *const GUID, + ppv: *mut *mut c_void, + compute: bool, + owned: OwnedDesc, + standin: unsafe fn(*mut c_void, PsoFn, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT, + build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool, +) -> Option { + LAZY_NEXT.with(|l| l.set(true)); + let r = go_background(this, f, desc, riid, ppv, compute, owned, standin, build); + LAZY_NEXT.with(|l| l.set(false)); + r +} + +/// The title's graphics pipeline has console shaders (what `go_lazy` defers). +unsafe fn console_graphics(desc: *const c_void) -> bool { + use crate::gpu::recomp::pso::is_console; + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return false; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + shader_bytes(&d.VS).is_some_and(is_console) && shader_bytes(&d.HS).is_none() && shader_bytes(&d.DS).is_none() && shader_bytes(&d.GS).is_none() +} + + unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) @@ -3232,12 +3271,18 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); + if super::pso_async::lazy() && console_graphics(desc) { + if let Some(hr) = own_graphics(desc).and_then(|o| go_lazy(this, f, desc, riid, ppv, false, o, standin_graphics, build_graphics)) { + return hr; + } + } let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; if missed { if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, build_graphics)) { return hr; } - if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { + // no stand-in: the title waits in this call – its compiles go first + if let Some(hr) = crate::gpu::recomp::dxc::urgent(|| translated_graphics_pso(this, f, desc, riid, ppv)) { return hr; } } else if let Some(hr) = translated { @@ -3276,6 +3321,21 @@ unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + // console compute pipelines are built at their first dispatch too (`XCL_LAZY_COMPUTE=0`: at + // creation): GTA VI creates thousands while it loads and dispatches a few hundred; built at + // creation, AMD's driver held 60+ GB of commit within a minute and the title never left its + // loading screen + if super::pso_async::lazy() + && std::env::var("XCL_LAZY_COMPUTE").map_or(true, |v| v != "0") + && crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) + && shader_bytes(&(*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS).is_some_and(crate::gpu::recomp::pso::is_console) + { + if let Some(hr) = own_compute(desc).and_then(|o| go_lazy(this, f, desc, riid, ppv, true, o, standin_compute, build_compute)) { + LAST_COMPUTE_TRANSLATED.with(|c| c.set(true)); + LAST_COMPUTE_RS.with(|c| c.set(0)); + return hr; + } + } let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, build_compute)) { @@ -3287,7 +3347,7 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const LAST_COMPUTE_RS.with(|c| c.set(0)); return hr; } - console = translated_compute_pso(this, f, desc, riid, ppv); + console = crate::gpu::recomp::dxc::urgent(|| translated_compute_pso(this, f, desc, riid, ppv)); } LAST_COMPUTE_TRANSLATED.with(|c| c.set(matches!(console, Some(Ok(hr)) if hr >= 0))); if let Some(Ok(hr)) = console { @@ -3775,7 +3835,7 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, build_stream)) { return hr; } - if let Some(hr) = translated_mesh_stream(this, desc, riid, ppv) { + if let Some(hr) = crate::gpu::recomp::dxc::urgent(|| translated_mesh_stream(this, desc, riid, ppv)) { return hr; } } else if let Some(hr) = translated {