diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 907511e63..170cffda9 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -407,15 +407,25 @@ pub fn set_memory_reserve(gb: u64) { /// Compiles running on the DXC workers (`wait_for_memory` lets them in). static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// A compile let in by `wait_for_memory`, until it is dropped. +/// A compile let in by `wait_for_memory` / `pool`, until it is dropped. pub struct MemorySlot; impl Drop for MemorySlot { fn drop(&mut self) { WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + wake_pool(); } } +fn memory_plenty(working: usize) -> bool { + use std::sync::atomic::Ordering; + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((working as u64) << 30); + unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need } +} + /// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already /// running (each can still grow to ~0.7 GB), at once; with less, one compile at a /// time – it goes when no other is running (and after a minute in any case). Each compile used @@ -426,14 +436,11 @@ impl Drop for MemorySlot { /// ended it. pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let start = std::time::Instant::now(); loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 || (WORKING.load(Ordering::Acquire) < WANTED_AT_ONCE && wanted()) { + let w = WORKING.load(Ordering::Acquire); + let plenty = memory_plenty(w); + if plenty || start.elapsed().as_secs() >= 60 || (w < WANTED_AT_ONCE && wanted()) { WORKING.fetch_add(1, Ordering::AcqRel); return MemorySlot; } @@ -444,28 +451,105 @@ pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { } } +struct DxcQueue { + jobs: Mutex>, + cv: std::sync::Condvar, +} + +static POOL: OnceLock = OnceLock::new(); + +/// Wake DXC workers after a job becomes wanted or a memory slot frees, without spawning the pool. +pub fn wake_pool() { + if let Some(q) = POOL.get() { + let _g = q.jobs.lock().unwrap(); + q.cv.notify_all(); + } +} + +/// Pick the next DXC job without head-of-line blocking: wanted jobs jump ahead of queued +/// unwanted jobs whenever memory is free or fewer than `WANTED_AT_ONCE` compiles are running. +fn pick_next_job( + jobs: &mut std::collections::VecDeque<(T, std::time::Instant)>, + working: usize, + plenty: bool, + now: std::time::Instant, + is_wanted: impl Fn(&T) -> bool, +) -> Option<(T, bool)> { + if plenty || working < WANTED_AT_ONCE { + if let Some(idx) = jobs.iter().position(|(j, _)| is_wanted(j)) { + let (job, _) = jobs.remove(idx)?; + return Some((job, true)); + } + } + let aged_out = jobs + .front() + .is_some_and(|(_, queued_at)| now.saturating_duration_since(*queued_at).as_secs() >= 60); + if plenty || working == 0 || aged_out { + let (job, _) = jobs.pop_front()?; + return Some((job, false)); + } + None +} + /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. -fn pool() -> &'static std::sync::Mutex> { - static POOL: OnceLock>> = OnceLock::new(); +fn pool() -> &'static DxcQueue { POOL.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); + let q = DxcQueue { + jobs: Mutex::new(std::collections::VecDeque::new()), + cv: std::sync::Condvar::new(), + }; for k in 0..compile_threads() { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { - let job = match rx.lock().unwrap().recv() { - Ok(j) => j, - Err(_) => return, - }; - let _slot = wait_for_memory(&job.wanted); - let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) + let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || { + let q = POOL.wait(); + loop { + let (job, was_wanted, slot) = { + let mut jobs = q.jobs.lock().unwrap(); + loop { + if jobs.is_empty() { + jobs = q.cv.wait(jobs).unwrap(); + continue; + } + let w = WORKING.load(Ordering::Acquire); + let plenty = memory_plenty(w); + if let Some((job, was_wanted)) = + pick_next_job(&mut jobs, w, plenty, std::time::Instant::now(), |j| (j.wanted)()) + { + WORKING.fetch_add(1, Ordering::AcqRel); + break (job, was_wanted, MemorySlot); + } + jobs = q.cv.wait_timeout(jobs, std::time::Duration::from_millis(50)).unwrap().0; + } + }; + let running_title = crate::state::boot().is_some(); + if running_title { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, + }; + let prio = if was_wanted || (job.wanted)() { + THREAD_PRIORITY_NORMAL + } else { + THREAD_PRIORITY_BELOW_NORMAL + }; + unsafe { SetThreadPriority(GetCurrentThread(), prio) }; + } + let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + compile_here(&job.src, &job.entry, &job.profile, &extra) + })) .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = job.reply.send(r); + if running_title { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL, + }; + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) }; + } + drop(slot); + let _ = job.reply.send(r); + } }); } - std::sync::Mutex::new(tx) + q }) } @@ -473,7 +557,9 @@ fn pool() -> &'static std::sync::Mutex> { pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { 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, wanted: crate::hle::d3d12x::pso_async::wanted_here() }; - pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; + let q = pool(); + q.jobs.lock().unwrap().push_back((job, std::time::Instant::now())); + q.cv.notify_all(); rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } @@ -1248,4 +1334,31 @@ mod cache_tests { second_rx.recv_timeout(Duration::from_secs(2)).unwrap(); }); } + + #[test] + fn wanted_dxc_job_preempts_queued_unwanted_jobs_under_memory_pressure() { + use std::collections::VecDeque; + let now = std::time::Instant::now(); + let mut q = VecDeque::from([ + ((1u32, false), now), + ((2u32, false), now), + ((3u32, true), now), + ]); + // Low commit with 1 compile active: wanted job #3 must bypass unwanted #1 and #2. + assert_eq!(pick_next_job(&mut q, 1, false, now, |j| j.1), Some(((3, true), true))); + // Remaining unwanted jobs wait while another compile is active under low commit. + assert_eq!(pick_next_job(&mut q, 1, false, now, |j| j.1), None); + // Once active compiles drop to 0, an unwanted job may proceed. + assert_eq!(pick_next_job(&mut q, 0, false, now, |j| j.1), Some(((1, false), false))); + // At WANTED_AT_ONCE under low commit, even a wanted job waits until a slot frees or ages out. + q.push_back(((4, true), now)); + assert_eq!(pick_next_job(&mut q, WANTED_AT_ONCE, false, now, |j| j.1), None); + // With plenty of commit, wanted still jumps ahead of queued unwanted jobs. + assert_eq!(pick_next_job(&mut q, WANTED_AT_ONCE, true, now, |j| j.1), Some(((4, true), true))); + // After 60 s, the aged front item is allowed through. + assert_eq!( + pick_next_job(&mut q, WANTED_AT_ONCE, false, now + Duration::from_secs(60), |j| j.1), + Some(((2, false), false)) + ); + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0ab287644..39049132c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -28,6 +28,12 @@ struct State { /// the title's graphics root signature (a PC object), bound before a draw with an /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, + /// the title's compute root signature (a PC object), restored before an untranslated compute + /// ExecuteIndirect when XCL's ABI root signature was previously bound on this list + rs_compute: usize, + /// XCL's ABI graphics/compute root signature currently dirties this list's PC slot + abi_gfx: bool, + abi_compute: bool, pso: usize, allocator: usize, /// unified memory of this recording (io, argument tables) @@ -82,6 +88,9 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.rs_compute = 0; + s.abi_gfx = false; + s.abi_compute = false; (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); @@ -97,6 +106,9 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.rs_compute = 0; + s.abi_gfx = false; + s.abi_compute = false; }); } @@ -104,8 +116,18 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { - (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) + let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_compute, abi_gfx, abi_compute, pso) = with(from, |s| { + ( + s.layout.clone(), + s.args.clone(), + s.layout_gfx.clone(), + s.args_gfx.clone(), + s.rs_gfx, + s.rs_compute, + s.abi_gfx, + s.abi_compute, + s.pso, + ) }); let (old, blocks) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, allocator); @@ -115,6 +137,9 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.layout_gfx = layout_gfx; s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; + s.rs_compute = rs_compute; + s.abi_gfx = abi_gfx; + s.abi_compute = abi_compute; s.pso = pso; (old, std::mem::take(&mut s.uma)) }); @@ -224,39 +249,99 @@ fn note_address(va: u64) { /// command signatures that change root arguments (they need the title's root signature) static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +/// command signatures whose indirect arguments perform a Dispatch (compute pipeline) +static COMPUTE_SIGNATURES: Mutex>> = Mutex::new(None); pub(super) fn note_root_changing_signature(sig: usize) { ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); } +pub(super) fn note_compute_signature(sig: usize, compute: bool) { + let mut g = COMPUTE_SIGNATURES.lock().unwrap(); + if compute { + g.get_or_insert_with(Default::default).insert(sig); + } else if let Some(s) = g.as_mut() { + s.remove(&sig); + } +} + +pub(super) fn is_compute_signature(sig: usize) -> bool { + COMPUTE_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let (pso, pending) = super::pso_async::resolve_wait_critical(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + let compute_sig = is_compute_signature(sig); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and // the list may hold XCL's ABI root signature from a translated draw before it – the PC // call with that pair is invalid (debug layer 953, "the currently set Root Signature // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(with(this, |s| s.pso)) { - count(DRAWS_SKIPPED); + if pending { + count(if compute_sig { DISPATCHES_SKIPPED } else { DRAWS_SKIPPED }); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: ExecuteIndirect with a pipeline that is still being built skipped"); } return; } - // a PC pipeline: the title's root signature, as for a draw (`graphics_bound`) - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { - list.SetGraphicsRootSignature(r); + if compute_sig { + let (rs, had_abi) = with(this, |s| (s.rs_compute, s.abi_compute)); + if had_abi && rs == 0 { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: compute ExecuteIndirect without title root signature after XCL ABI bind skipped"); + } + return; + } + if had_abi { + with(this, |s| s.abi_compute = false); + } + if let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) { + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&(rs as *mut c_void)) { + list.SetComputeRootSignature(r); + } + if had_abi { + if let Some(pc_pso) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(pc_pso); + } + } + } + return pc(this, sig, max, args, args_off, count_buf, count_off); + } + // a PC pipeline: the title's graphics root signature, as for a draw (`graphics_bound`) + let (rs, had_abi) = with(this, |s| (s.rs_gfx, s.abi_gfx)); + if had_abi && rs == 0 { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: graphics ExecuteIndirect without title root signature after XCL ABI bind skipped"); + } + return; } + if had_abi { + with(this, |s| s.abi_gfx = false); + } + if let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) { + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&(rs as *mut c_void)) { + list.SetGraphicsRootSignature(r); + } + if had_abi { + if let Some(pc_pso) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(pc_pso); + } + } + } + super::list_x::prepare_draw(this); return pc(this, sig, max, args, args_off, count_buf, count_off); } if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { @@ -270,6 +355,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us match bind_abi(this, list, pso, gfx) { Ok(()) => { count(if gfx { DRAWS } else { DISPATCHES }); + if gfx { + super::list_x::prepare_draw(this); + } pc(this, sig, max, args, args_off, count_buf, count_off) } Err(e) => { @@ -404,10 +492,40 @@ pub(super) unsafe fn emit_prepared_indexed_draw( /// arguments are bound (None: the draw is skipped – a console pipeline without a /// translation, or no unified memory). unsafe fn graphics_bound(this: *mut c_void) -> Option { + graphics_bound_with(this, super::pso_async::resolve_wait_checked) +} + +unsafe fn graphics_bound_with( + this: *mut c_void, + resolve_pso: impl FnOnce(usize) -> (usize, bool), +) -> 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) - if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + let (resolved, pending) = resolve_pso(pso); + if !super::real::is_translated_graphics(resolved) { + if pending || super::pso_async::is_failed_standin(pso) { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: draw with a pipeline that has no ready graphics shader ({pso:#x}, pending {pending}) skipped" + ); + } + return None; + } + let (rs, had_abi) = with(this, |s| (s.rs_gfx, s.abi_gfx)); + if had_abi && rs == 0 { + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: PC draw without title graphics root signature after XCL ABI bind skipped"); + } + return None; + } + if had_abi { + with(this, |s| s.abi_gfx = false); + } count(DRAWS_PC); if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) @@ -415,28 +533,29 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(pso); crate::xlog_info!( - "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", - super::pso_async::is_pending(pso), - super::real::two_pass_of(real).is_some(), + "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {resolved:#x}; pending {pending}, two-pass {}, RT0 {:?})", + super::real::two_pass_of(resolved).is_some(), super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) ); } } - // a PC pipeline (also a stand-in or fallback: made with the title's root signature): - // the title's root signature, which nothing else binds on the PC list – a draw without - // one is invalid (the debug layer reports it on every GPU; WARP faults on it) - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { + // a PC pipeline (made with the title's root signature): restore the title's graphics root + // signature (and the PC PSO itself if XCL's ABI bound a translated PSO beforehand) + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&(rs as *mut c_void)) { list.SetGraphicsRootSignature(r); } + if had_abi { + if let Some(pc_pso) = ID3D12PipelineState::from_raw_borrowed(&(resolved as *mut c_void)) { + list.SetPipelineState(pc_pso); + } + } return Some(list); } if super::present::trace_frame() { - trace_ui_draw(this, pso); + trace_ui_draw(this, resolved); } - match bind_abi(this, &list, pso, true) { + match bind_abi(this, &list, resolved, true) { Ok(()) => { count(DRAWS); Some(list) @@ -676,6 +795,7 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi with(this, |s| { s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; s.layout = layout; + s.rs_compute = rs as usize; }); } @@ -712,7 +832,7 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = super::pso_async::resolve_wait_critical(with(this, |s| s.pso)).0; let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that @@ -899,6 +1019,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; list.SetPipelineState(pc); + with(this, |s| if gfx { s.abi_gfx = true; } else { s.abi_compute = true; }); Ok(()) } @@ -1281,4 +1402,172 @@ mod tests { let _ = pso_async::released(standin); } } + + #[repr(C)] + struct FakeGfxAndIndirectList { + vt: *const usize, + refs: AtomicUsize, + set_compute_rs_calls: AtomicUsize, + set_gfx_rs_calls: AtomicUsize, + set_pso_calls: AtomicUsize, + execute_indirect_calls: AtomicUsize, + } + + unsafe extern "system" fn fgil_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeGfxAndIndirectList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn fgil_release(this: *mut c_void) -> u32 { + (*(this as *const FakeGfxAndIndirectList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + unsafe extern "system" fn fgil_set_pso(this: *mut c_void, _pso: *mut c_void) { + (*(this as *const FakeGfxAndIndirectList)).set_pso_calls.fetch_add(1, Ordering::Relaxed); + } + unsafe extern "system" fn fgil_set_compute_rs(this: *mut c_void, _rs: *mut c_void) { + (*(this as *const FakeGfxAndIndirectList)).set_compute_rs_calls.fetch_add(1, Ordering::Relaxed); + } + unsafe extern "system" fn fgil_set_gfx_rs(this: *mut c_void, _rs: *mut c_void) { + (*(this as *const FakeGfxAndIndirectList)).set_gfx_rs_calls.fetch_add(1, Ordering::Relaxed); + } + unsafe extern "system" fn fgil_execute_indirect( + this: *mut c_void, + _sig: usize, + _max: u32, + _args: usize, + _args_off: u64, + _count_buf: usize, + _count_off: u64, + ) { + (*(this as *const FakeGfxAndIndirectList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + + #[test] + fn graphics_bound_skips_pending_and_failed_standin_psos() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fgil_add_ref as usize; + orig_vt[2] = fgil_release as usize; + orig_vt[25] = fgil_set_pso as usize; + orig_vt[29] = fgil_set_compute_rs as usize; + orig_vt[30] = fgil_set_gfx_rs as usize; + orig_vt[59] = fgil_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + + let fake = Box::new(FakeGfxAndIndirectList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + set_compute_rs_calls: AtomicUsize::new(0), + set_gfx_rs_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeGfxAndIndirectList as *mut c_void; + + let pending_gfx = 0x7250_0001usize; + let failed_gfx = 0x7250_0002usize; + let pc_pso = 0x7250_0003usize; + let (tx, rx) = std::sync::mpsc::channel(); + pso_async::submit(pending_gfx, false, Box::new(move || { + let _ = rx.recv_timeout(std::time::Duration::from_secs(5)); + 0x7250_0099 + })); + pso_async::submit_lazy(failed_gfx, false, Box::new(|| 0), 0); + assert_eq!(pso_async::resolve_wait(failed_gfx), failed_gfx); + + unsafe { + // Pending graphics stand-in is skipped (never falls through to DRAWS_PC). + reset(list_ptr, 0x7250_0100, pending_gfx); + let before = counts_snapshot(); + assert!( + graphics_bound_with(list_ptr, |p| pso_async::resolve_wait_checked_for_test(p, std::time::Duration::from_millis(10))) + .is_none() + ); + let after = counts_snapshot(); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); + + // Failed graphics stand-in is also skipped. + reset(list_ptr, 0x7250_0100, failed_gfx); + let before = counts_snapshot(); + assert!(graphics_bound(list_ptr).is_none()); + let after = counts_snapshot(); + assert!(after[DRAWS_SKIPPED] > before[DRAWS_SKIPPED]); + assert_eq!(after[DRAWS_PC], before[DRAWS_PC]); + + // PC PSO while XCL's ABI dirtied graphics RS and no title RS was bound: skips AND keeps abi_gfx set. + reset(list_ptr, 0x7250_0100, pc_pso); + with(list_ptr, |s| s.abi_gfx = true); + assert!(graphics_bound(list_ptr).is_none()); + assert!(with(list_ptr, |s| s.abi_gfx), "abi_gfx must remain set when rs_gfx == 0"); + assert!(graphics_bound(list_ptr).is_none(), "second draw without rs_gfx must also skip"); + + // Title binds its graphics RS (abi_gfx remains true until draw restores it onto the PC list). + set_graphics_root_signature(list_ptr, 0x7250_0030usize as *mut c_void); + assert!(with(list_ptr, |s| s.abi_gfx)); + assert!(graphics_bound(list_ptr).is_some()); + assert!(!with(list_ptr, |s| s.abi_gfx)); + assert_eq!(fake.set_gfx_rs_calls.load(Ordering::Relaxed), 1); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 1); + + forget(list_ptr); + } + let _ = tx.send(()); + let start = std::time::Instant::now(); + while pso_async::is_pending(pending_gfx) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!pso_async::is_pending(pending_gfx)); + let _ = pso_async::released(pending_gfx); + let _ = pso_async::released(failed_gfx); + } + + #[test] + fn execute_indirect_restores_compute_rs_and_skips_if_abi_active_without_rs() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fgil_add_ref as usize; + orig_vt[2] = fgil_release as usize; + orig_vt[25] = fgil_set_pso as usize; + orig_vt[29] = fgil_set_compute_rs as usize; + orig_vt[30] = fgil_set_gfx_rs as usize; + orig_vt[59] = fgil_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + + let fake = Box::new(FakeGfxAndIndirectList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + set_compute_rs_calls: AtomicUsize::new(0), + set_gfx_rs_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeGfxAndIndirectList as *mut c_void; + + let sig_compute = 0x7250_00A0usize; + let pc_pso = 0x7250_0050usize; + note_compute_signature(sig_compute, true); + + unsafe { + reset(list_ptr, 0x7250_0100, pc_pso); + with(list_ptr, |s| s.abi_compute = true); + let before = counts_snapshot(); + execute_indirect(list_ptr, sig_compute, 1, 0, 0, 0, 0); + let after = counts_snapshot(); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + assert!(with(list_ptr, |s| s.abi_compute), "abi_compute must stay set when rs_compute == 0"); + + set_compute_root_signature(list_ptr, 0x7250_0020usize as *mut c_void); + assert!(with(list_ptr, |s| s.abi_compute)); + execute_indirect(list_ptr, sig_compute, 1, 0, 0, 0, 0); + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 1); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 1); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 1); + assert!(!with(list_ptr, |s| s.abi_compute)); + + forget(list_ptr); + } + note_compute_signature(sig_compute, false); + } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 4b6d32aa7..790d6d457 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -185,6 +185,48 @@ pub(super) unsafe fn dynamic_depth_bias_supported(dev: *mut c_void) -> bool { ID3D12Device::from_raw_borrowed(&dev).is_some_and(probe_dynamic_depth_bias) } +/// Cached result of `CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6)`: +/// -1 = not yet probed, otherwise `(tier & 3) | ((additional_rates as i8) << 2)`. +static VSR_CAPS: AtomicI8 = AtomicI8::new(-1); + +fn probe_vsr_caps(dev: &ID3D12Device) -> (u32, bool) { + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS6::default(); + let ok = unsafe { + dev.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS6, + &mut opts as *mut _ as *mut c_void, + std::mem::size_of::() as u32, + ) + .is_ok() + }; + let (tier, additional) = if ok { + ((opts.VariableShadingRateTier.0 as u32).min(3), opts.AdditionalShadingRatesSupported.as_bool()) + } else { + (0, false) + }; + let packed = (tier as i8) | ((additional as i8) << 2); + VSR_CAPS.store(packed, Ordering::Release); + crate::xlog_info!("D3D12.X: variable shading rate (OPTIONS6): tier {tier}, additional rates {additional}"); + (tier, additional) +} + +/// Cached `(VariableShadingRateTier, AdditionalShadingRatesSupported)` if already probed. +pub(super) fn cached_variable_shading_rate_caps() -> Option<(u32, bool)> { + let cached = VSR_CAPS.load(Ordering::Acquire); + (cached >= 0).then(|| ((cached & 3) as u32, (cached & 4) != 0)) +} + +/// Cached `(VariableShadingRateTier, AdditionalShadingRatesSupported)` for `dev`. +pub(super) unsafe fn variable_shading_rate_caps(dev: *mut c_void) -> (u32, bool) { + if let Some(caps) = cached_variable_shading_rate_caps() { + return caps; + } + if dev.is_null() { + return (0, false); + } + ID3D12Device::from_raw_borrowed(&dev).map_or((0, false), probe_vsr_caps) +} + /// Create a graphics PSO, enabling `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS` when the /// device supports it (retrying without the flag if creation fails), and record it as a base. unsafe fn create_graphics_pso_tracked(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -592,6 +634,8 @@ pub(super) unsafe extern "system" fn set_debug_flags_x(_this: *mut c_void, _flag S_OK } +const PAGE_64K: u64 = 0x1_0000; + static PAGE_POOLS: Mutex> = Mutex::new(Vec::new()); /// device #74 RegisterPagePoolX(address, pages, index out) @@ -612,7 +656,8 @@ pub(super) unsafe extern "system" fn register_page_pool_x(_this: *mut c_void, va /// device #75 UnregisterPagePoolX(index) pub(super) unsafe extern "system" fn unregister_page_pool_x(_this: *mut c_void, index: u64) -> HRESULT { - match PAGE_POOLS.lock().unwrap().get_mut(index as usize) { + let mut p = PAGE_POOLS.lock().unwrap(); + match p.get_mut(index as usize) { Some(e) if e.1 != 0 => { *e = (0, 0); S_OK @@ -621,6 +666,79 @@ pub(super) unsafe extern "system" fn unregister_page_pool_x(_this: *mut c_void, } } +/// command queue #29 (older) / #31 (newer) +/// `UpdatePageMappingsX(numMappings, pMappings, pagePoolBase, numPagesInPool, flags)`: +/// validates 64 KiB page mapping descriptors from a registered GPU page pool and succeeds. +pub(super) unsafe extern "system" fn update_page_mappings_x( + _queue: *mut c_void, + num_mappings: u32, + mappings: *const u8, + page_pool_base: u64, + num_pages_in_pool: u32, + flags: u32, +) -> HRESULT { + static LOG_ONCE: AtomicU64 = AtomicU64::new(0); + static WARN_ONCE: AtomicU64 = AtomicU64::new(0); + if num_mappings == 0 { + return S_OK; + } + let Some(bytes) = (num_mappings as usize).checked_mul(24) else { + return E_INVALIDARG; + }; + if mappings.is_null() || !crate::gpu::shader::readable(mappings as usize, bytes) { + return E_INVALIDARG; + } + if once(&LOG_ONCE, 1) { + crate::xlog_info!("D3D12.X: UpdatePageMappingsX ({num_mappings} mapping(s), pool {page_pool_base:#x}, {num_pages_in_pool} pages, flags {flags:#x})"); + } + for i in 0..num_mappings as usize { + let entry = mappings.add(i * 24); + let dest_va = (entry as *const u64).read_unaligned(); + let num_ranges = (entry.add(8) as *const u32).read_unaligned(); + let ranges_ptr = (entry.add(0x10) as *const usize).read_unaligned(); + if num_ranges == 0 { + continue; + } + let Some(rbytes) = (num_ranges as usize).checked_mul(12) else { + if once(&WARN_ONCE, 4) { + crate::xlog_warn!("D3D12.X: UpdatePageMappingsX – range count overflow ({num_ranges})"); + } + return E_INVALIDARG; + }; + if dest_va == 0 || !dest_va.is_multiple_of(PAGE_64K) || ranges_ptr == 0 || !crate::gpu::shader::readable(ranges_ptr, rbytes) { + if once(&WARN_ONCE, 4) { + crate::xlog_warn!("D3D12.X: UpdatePageMappingsX – invalid mapping dest={dest_va:#x} ranges={ranges_ptr:#x} count={num_ranges}"); + } + return E_INVALIDARG; + } + for j in 0..num_ranges as usize { + let r = (ranges_ptr + j * 12) as *const u8; + let op = (r as *const u32).read_unaligned(); + let pool_idx = (r.add(4) as *const u32).read_unaligned(); + let page_count = (r.add(8) as *const u32).read_unaligned(); + match op { + 0 | 2 => {} + 1 => { + if page_pool_base == 0 || (pool_idx as u64).checked_add(page_count as u64).is_none_or(|end| end > num_pages_in_pool as u64) { + if once(&WARN_ONCE, 4) { + crate::xlog_warn!( + "D3D12.X: UpdatePageMappingsX – pool range [{pool_idx}..+{page_count}) exceeds {num_pages_in_pool} pages (base {page_pool_base:#x})" + ); + } + return E_INVALIDARG; + } + } + _ => { + if once(&WARN_ONCE, 4) { + crate::xlog_warn!("D3D12.X: UpdatePageMappingsX – unknown page range op {op}"); + } + } + } + } + } + S_OK +} + /// device #61 CreateSamplerX(desc, destination): the title uses it for anisotropic samplers; /// the console desc (0x6C bytes) carries the PC fields at other offsets (+0x18 address U / V / /// W, +0x24 / +0x28 min / max LOD, +0x2C bias, +0x34 max anisotropy, +0x40 comparison); its @@ -1034,10 +1152,15 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } } let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); + let is_compute = list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !ppv.is_null() { + let sig = *ppv as usize; + if needs_root { + super::bind::note_root_changing_signature(sig); + } + super::bind::note_compute_signature(sig, is_compute); } hr } @@ -1237,6 +1360,59 @@ mod tests { } } + #[test] + fn update_page_mappings_x_maps_unmaps_and_validates() { + #[repr(C)] + struct PageRange { + op: u32, + pool_idx: u32, + count: u32, + } + #[repr(C)] + struct Mapping { + dest_va: u64, + num_ranges: u32, + _pad: u32, + ranges: *const PageRange, + } + unsafe { + let pool_base = 0x5_0000_0000u64; + let mut pool_idx = u32::MAX; + assert_eq!(register_page_pool_x(std::ptr::null_mut(), pool_base, 16, &mut pool_idx), S_OK); + + // Empty call succeeds. + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 0, std::ptr::null(), pool_base, 16, 0), S_OK); + // Null mappings with non-zero count is rejected. + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, std::ptr::null(), pool_base, 16, 0), E_INVALIDARG); + + // Map 2 pages at pool[3..5], skip 1 page, map 1 page at pool[8]. + let ranges = [ + PageRange { op: 1, pool_idx: 3, count: 2 }, + PageRange { op: 0, pool_idx: 0, count: 1 }, + PageRange { op: 1, pool_idx: 8, count: 1 }, + ]; + let dest_base = 0x6_0000_0000u64; + let map = Mapping { dest_va: dest_base, num_ranges: ranges.len() as u32, _pad: 0, ranges: ranges.as_ptr() }; + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, &map as *const _ as *const u8, pool_base, 16, 0), S_OK); + + // Unmap operation (op 2) validates cleanly and returns S_OK. + let unmap = [PageRange { op: 2, pool_idx: 0, count: 1 }]; + let unmap_entry = Mapping { dest_va: dest_base + PAGE_64K, num_ranges: 1, _pad: 0, ranges: unmap.as_ptr() }; + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, &unmap_entry as *const _ as *const u8, pool_base, 16, 0), S_OK); + + // Unaligned destination, missing pool base, and out-of-bounds pool ranges return E_INVALIDARG. + let bad_dest = Mapping { dest_va: dest_base + 0x100, num_ranges: 1, _pad: 0, ranges: ranges.as_ptr() }; + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, &bad_dest as *const _ as *const u8, pool_base, 16, 0), E_INVALIDARG); + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, &map as *const _ as *const u8, 0, 16, 0), E_INVALIDARG); + let oob_range = [PageRange { op: 1, pool_idx: 15, count: 2 }]; + let oob = Mapping { dest_va: dest_base, num_ranges: 1, _pad: 0, ranges: oob_range.as_ptr() }; + assert_eq!(update_page_mappings_x(std::ptr::null_mut(), 1, &oob as *const _ as *const u8, pool_base, 16, 0), E_INVALIDARG); + + assert_eq!(unregister_page_pool_x(std::ptr::null_mut(), pool_idx as u64), S_OK); + assert_eq!(unregister_page_pool_x(std::ptr::null_mut(), pool_idx as u64), E_FAIL); + } + } + /// Several resources' allocation info: each at its alignment, the total padded to the largest /// (the PC's docs: the 4 MiB-aligned one in the middle takes 12 MiB, first 8 MiB). #[test] diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index afa4f91e4..9b7e0fdd5 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -17,10 +17,10 @@ //! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. //! An index buffer at such an address is given to the PC as the window buffer's GPU address. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI8, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Condvar, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -40,12 +40,16 @@ const PC_COPY_RESOURCE: usize = 17; const PC_SET_PIPELINE_STATE: usize = 25; const PC_RESOURCE_BARRIER: usize = 26; const PC_IA_SET_INDEX_BUFFER: usize = 43; +const PC_CLEAR_RENDER_TARGET_VIEW: usize = 48; +const PC_DISCARD_RESOURCE: usize = 51; const PC_BEGIN_QUERY: usize = 52; const PC_END_QUERY: usize = 53; const PC_RESOLVE_QUERY_DATA: usize = 54; const PC_SET_PREDICATION: usize = 55; const PC_OM_SET_DEPTH_BOUNDS: usize = 62; const PC_WRITE_BUFFER_IMMEDIATE: usize = 66; +const PC_RS_SET_SHADING_RATE: usize = 77; +const PC_RS_SET_SHADING_RATE_IMAGE: usize = 78; const PC_QUEUE_EXECUTE_COMMAND_LISTS: usize = 10; /// Write64BitValueBottomOfPipeX flags 1 / 2, Write64BitValueTopOfPipeX flags 4 / 8: the value @@ -279,6 +283,8 @@ struct Bindings { index_title: Option<(u64, u32, i32)>, /// the title set the console's rect list topology rect_list: bool, + shading_rate: Option<(u32, Option<[u32; 2]>)>, + shading_rate_image: Option, } /// Whether `list` draws rect lists now, and the title's vertex buffers (slot, (address, bytes, stride)). @@ -542,6 +548,12 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI if rt.dsv.is_some() { &d } else { std::ptr::null() }, ); } + if let Some((base_rate, combiners)) = b.shading_rate { + apply_shading_rate_pc(this, base_rate, combiners); + } + if let Some(image) = b.shading_rate_image { + apply_shading_rate_image_pc(this, image); + } } #[derive(Default)] @@ -2697,9 +2709,11 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 super::bind::dispatch(this, x, y, z); } -/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH -/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass -pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { +/// Emit a global UAV barrier on graphics/compute lists (D3D12 forbids UAV barriers on COPY lists). +unsafe fn emit_global_uav_barrier(this: *mut c_void) { + if this.is_null() || list_type(this) == D3D12_COMMAND_LIST_TYPE_COPY { + return; + } let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -2710,6 +2724,115 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); } +/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH +/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { + emit_global_uav_barrier(this); +} + +/// command list #131 FlushGpuCacheRangeX(flags, waitFlags, startVA, size) +pub(super) unsafe extern "system" fn flush_gpu_cache_range_x(this: *mut c_void, flush_flags: u32, wait_flags: u32, _start_va: u64, size: u64) { + if (flush_flags != 0 || wait_flags != 0) && size != 0 { + emit_global_uav_barrier(this); + } +} + +/// command list #132 FlushShaderCacheRangeX(flags, waitFlags, startVA, size) +pub(super) unsafe extern "system" fn flush_shader_cache_range_x(this: *mut c_void, flags: u32, wait_flags: u32, _start_va: u64, size: u64) { + if (flags != 0 || wait_flags != 0) && size != 0 { + emit_global_uav_barrier(this); + } +} + +/// Clamp a console `D3D12_SHADING_RATE` to values supported by the PC adapter. +fn sanitize_shading_rate(base_rate: u32, additional_supported: bool) -> u32 { + match base_rate { + 0 | 1 | 4 | 5 => base_rate, + 6 | 9 | 10 => if additional_supported { base_rate } else { 5 }, + _ => 0, + } +} + +/// Clamp console `D3D12_SHADING_RATE_COMBINER` values to `[0..=4]`, falling back to `PASSTHROUGH` (0). +fn sanitize_combiners(raw: [u32; 2]) -> [u32; 2] { + [if raw[0] <= 4 { raw[0] } else { 0 }, if raw[1] <= 4 { raw[1] } else { 0 }] +} + +static CL5_SUPPORTED: AtomicI8 = AtomicI8::new(-1); + +unsafe fn supports_cl5(list: *mut c_void) -> bool { + match CL5_SUPPORTED.load(Ordering::Acquire) { + 1 => return true, + 0 => return false, + _ => {} + } + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { + return false; + }; + let ok = cl.cast::().is_ok(); + CL5_SUPPORTED.store(i8::from(ok), Ordering::Release); + ok +} + +unsafe fn vsr_caps_of(list: *mut c_void) -> (u32, bool) { + if let Some(caps) = device_x::cached_variable_shading_rate_caps() { + return caps; + } + let Some(dev) = device_of(list) else { + return (0, false); + }; + device_x::variable_shading_rate_caps(dev.as_raw()) +} + +unsafe fn apply_shading_rate_pc(list: *mut c_void, base_rate: u32, combiners: Option<[u32; 2]>) { + if list.is_null() || list_type(list) != D3D12_COMMAND_LIST_TYPE_DIRECT || !supports_cl5(list) { + return; + } + let (tier, additional) = vsr_caps_of(list); + if tier == 0 { + return; + } + let rate = sanitize_shading_rate(base_rate, additional); + let comb_ptr = match (tier >= 2, combiners.as_ref()) { + (true, Some(c)) => c as *const [u32; 2], + _ => std::ptr::null(), + }; + pc::(list, PC_RS_SET_SHADING_RATE)(list, rate, comb_ptr); +} + +unsafe fn apply_shading_rate_image_pc(list: *mut c_void, image: usize) { + if list.is_null() || list_type(list) != D3D12_COMMAND_LIST_TYPE_DIRECT || !supports_cl5(list) { + return; + } + if vsr_caps_of(list).0 < 2 { + return; + } + pc::(list, PC_RS_SET_SHADING_RATE_IMAGE)(list, image); +} + +/// command list #124 (older) / #126 (newer) RSSetShadingRate(baseRate, combiners) +pub(super) unsafe extern "system" fn rs_set_shading_rate_x(this: *mut c_void, base_rate: u32, combiners: *const [u32; 2]) { + let comb = (!combiners.is_null() && crate::gpu::shader::readable(combiners as usize, 8)) + .then(|| sanitize_combiners(combiners.read_unaligned())); + with_bindings(this, |b| b.shading_rate = Some((base_rate, comb))); + apply_shading_rate_pc(this, base_rate, comb); +} + +/// command list #125 (older) / #127 (newer) RSSetShadingRateImage(shadingRateImage) +pub(super) unsafe extern "system" fn rs_set_shading_rate_image_x(this: *mut c_void, image: usize) { + with_bindings(this, |b| b.shading_rate_image = Some(image)); + apply_shading_rate_image_pc(this, image); +} + +/// command list #73 (older) / #75 (newer) SetPipelineFlagX(enable): per-PSO flag bit +pub(super) unsafe extern "system" fn set_pipeline_flag_x(_this: *mut c_void, _enable: u32) {} + +/// command list #140 (older) / #142 (newer) SetQuadSampleMaskX(mask): 2x2 quad AA sample mask +pub(super) unsafe extern "system" fn set_quad_sample_mask_x(_this: *mut c_void, _mask: u64) {} + +/// command list #99 (older) / #101 (newer) SetClearBatchHintX(mode, enable) +pub(super) unsafe extern "system" fn set_clear_batch_hint_x(_this: *mut c_void, _mode: u32, _enable: u32) {} + /// command list #84 CopyResourceX(destination, source, flags); in place (the console's /// compression operations) there is nothing to do on PC pub(super) unsafe extern "system" fn copy_resource_flags_x(this: *mut c_void, dst: usize, src: usize, _flags: u32) { @@ -3187,8 +3310,375 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } } -/// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. +struct UninitTarget { + total_subresources: u32, + clear_color: [f32; 4], + clear_depth: f32, + clear_stencil: u8, + aliased: bool, + initialized_subs: HashSet, +} + +#[derive(Clone, Copy)] +struct DsvInfo { + res: usize, + subresource: u32, + has_stencil: bool, + read_only_depth: bool, + read_only_stencil: bool, +} + +static UNINIT_TARGETS_COUNT: AtomicUsize = AtomicUsize::new(0); +static UNINIT_TARGETS: Mutex>> = Mutex::new(None); +static RTV_HANDLES: Mutex>> = Mutex::new(None); +static DSV_HANDLES: Mutex>> = Mutex::new(None); +static RTV_DESC_INC: AtomicUsize = AtomicUsize::new(0); + +unsafe fn transition_subresource( + list: *mut c_void, + res: usize, + subresource: u32, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: transmute_copy(&res), + Subresource: subresource, + StateBefore: before, + StateAfter: after, + }), + }, + }; + pc::(list, PC_RESOURCE_BARRIER)(list, 1, &b); +} + +unsafe fn resource_mip_levels(res: usize) -> u32 { + let p = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).map_or(1, |r| (r.GetDesc().MipLevels as u32).max(1)) +} + +fn format_has_stencil(fmt: DXGI_FORMAT) -> bool { + matches!( + fmt, + DXGI_FORMAT_D24_UNORM_S8_UINT + | DXGI_FORMAT_D32_FLOAT_S8X24_UINT + | DXGI_FORMAT_R24G8_TYPELESS + | DXGI_FORMAT_R32G8X24_TYPELESS + ) +} + +/// Record a newly created or aliased Placed/Reserved RT/DS resource as requiring +/// Discard/Clear/Copy before its first draw (`D3D12 debug layer error 1422`). +pub(super) unsafe fn note_uninit_target_if_rt_ds(res: usize, desc: &D3D12_RESOURCE_DESC, clear: *const c_void, aliased: bool) { + let rt_ds = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0; + if res == 0 || (desc.Flags.0 & rt_ds) == 0 { + return; + } + let (mut clear_color, mut clear_depth, mut clear_stencil) = ([0.0f32; 4], 0.0f32, 0u8); + if !clear.is_null() && crate::gpu::shader::readable(clear as usize, std::mem::size_of::()) { + let cv = std::ptr::read_unaligned(clear as *const D3D12_CLEAR_VALUE); + if (desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0) != 0 { + let d = cv.Anonymous.DepthStencil.Depth; + clear_depth = if d.is_finite() { d.clamp(0.0, 1.0) } else { 0.0 }; + clear_stencil = cv.Anonymous.DepthStencil.Stencil; + } else { + clear_color = cv.Anonymous.Color; + } + } + let total_subresources = (desc.MipLevels as u32).max(1).saturating_mul(if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + (desc.DepthOrArraySize as u32).max(1) + }); + let mut g = UNINIT_TARGETS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + map.insert( + res, + UninitTarget { + total_subresources, + clear_color, + clear_depth, + clear_stencil, + aliased, + initialized_subs: HashSet::new(), + }, + ); + UNINIT_TARGETS_COUNT.store(map.len(), Ordering::Release); +} + +pub(super) unsafe fn note_rtv_handle(handle: usize, res: usize, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>) { + if handle == 0 || res == 0 { + return; + } + let subresource = match desc { + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D => d.Anonymous.Texture1D.MipSlice, + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY => { + d.Anonymous.Texture1DArray.MipSlice.saturating_add(d.Anonymous.Texture1DArray.FirstArraySlice.saturating_mul(resource_mip_levels(res))) + } + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D => d.Anonymous.Texture2D.MipSlice, + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY => { + d.Anonymous.Texture2DArray.MipSlice.saturating_add(d.Anonymous.Texture2DArray.FirstArraySlice.saturating_mul(resource_mip_levels(res))) + } + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS => 0, + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY => { + d.Anonymous.Texture2DMSArray.FirstArraySlice.saturating_mul(resource_mip_levels(res)) + } + Some(d) if d.ViewDimension == D3D12_RTV_DIMENSION_TEXTURE3D => d.Anonymous.Texture3D.MipSlice, + _ => 0, + }; + RTV_HANDLES.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, (res, subresource)); +} + +pub(super) unsafe fn note_dsv_handle(handle: usize, res: usize, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) { + if handle == 0 || res == 0 { + return; + } + let subresource = match desc { + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1D => d.Anonymous.Texture1D.MipSlice, + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1DARRAY => { + d.Anonymous.Texture1DArray.MipSlice.saturating_add(d.Anonymous.Texture1DArray.FirstArraySlice.saturating_mul(resource_mip_levels(res))) + } + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2D => d.Anonymous.Texture2D.MipSlice, + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DARRAY => { + d.Anonymous.Texture2DArray.MipSlice.saturating_add(d.Anonymous.Texture2DArray.FirstArraySlice.saturating_mul(resource_mip_levels(res))) + } + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMS => 0, + Some(d) if d.ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY => { + d.Anonymous.Texture2DMSArray.FirstArraySlice.saturating_mul(resource_mip_levels(res)) + } + _ => 0, + }; + let read_only_depth = desc.is_some_and(|d| (d.Flags.0 & D3D12_DSV_FLAG_READ_ONLY_DEPTH.0) != 0); + let read_only_stencil = desc.is_some_and(|d| (d.Flags.0 & D3D12_DSV_FLAG_READ_ONLY_STENCIL.0) != 0); + let fmt = desc.map(|d| d.Format).filter(|f| f.0 != 0).unwrap_or_else(|| { + let p = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).map_or(DXGI_FORMAT_UNKNOWN, |r| r.GetDesc().Format) + }); + let info = DsvInfo { + res, + subresource, + has_stencil: format_has_stencil(fmt), + read_only_depth, + read_only_stencil, + }; + DSV_HANDLES.lock().unwrap().get_or_insert_with(HashMap::new).insert(handle, info); +} + +fn claim_uninit_target(res: usize, sub: u32, extract: impl FnOnce(&UninitTarget) -> R) -> Option { + if res == 0 || UNINIT_TARGETS_COUNT.load(Ordering::Acquire) == 0 { + return None; + } + let mut g = UNINIT_TARGETS.lock().unwrap(); + let map = g.as_mut()?; + let (out, remove) = { + let t = map.get_mut(&res)?; + if !t.initialized_subs.insert(sub) { + return None; + } + let out = extract(t); + (out, t.initialized_subs.len() as u32 >= t.total_subresources) + }; + if remove { + map.remove(&res); + UNINIT_TARGETS_COUNT.store(map.len(), Ordering::Release); + } + Some(out) +} + +pub(super) fn mark_target_initialized(res: usize, subresource: Option) { + if res == 0 || UNINIT_TARGETS_COUNT.load(Ordering::Acquire) == 0 { + return; + } + match subresource { + Some(sub) => { + let _ = claim_uninit_target(res, sub, |_| ()); + } + None => { + let mut g = UNINIT_TARGETS.lock().unwrap(); + if let Some(map) = g.as_mut() { + if map.remove(&res).is_some() { + UNINIT_TARGETS_COUNT.store(map.len(), Ordering::Release); + } + } + } + } +} + +pub(super) fn mark_rtv_initialized(handle: usize) { + if handle == 0 || UNINIT_TARGETS_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let found = RTV_HANDLES.lock().unwrap().as_ref().and_then(|m| m.get(&handle).copied()); + if let Some((res, sub)) = found { + mark_target_initialized(res, Some(sub)); + } +} + +pub(super) fn mark_dsv_initialized(handle: usize) { + if handle == 0 || UNINIT_TARGETS_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let found = DSV_HANDLES.lock().unwrap().as_ref().and_then(|m| m.get(&handle).copied()); + if let Some(info) = found { + mark_target_initialized(info.res, Some(info.subresource)); + } +} + +pub(super) fn forget_target(res: usize) { + if res == 0 { + return; + } + { + let mut g = UNINIT_TARGETS.lock().unwrap(); + if let Some(map) = g.as_mut() { + if map.remove(&res).is_some() { + UNINIT_TARGETS_COUNT.store(map.len(), Ordering::Release); + } + } + } + if let Some(map) = RTV_HANDLES.lock().unwrap().as_mut() { + map.retain(|_, v| v.0 != res); + } + if let Some(map) = DSV_HANDLES.lock().unwrap().as_mut() { + map.retain(|_, v| v.res != res); + } +} + +unsafe fn rtv_descriptor_increment(list: *mut c_void) -> Option { + let cached = RTV_DESC_INC.load(Ordering::Acquire); + if cached != 0 { + return Some(cached); + } + let dev = device_of(list)?; + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + if inc != 0 { + RTV_DESC_INC.store(inc, Ordering::Release); + } + Some(inc) +} + +unsafe fn ensure_bound_targets_initialized(list: *mut c_void) { + if UNINIT_TARGETS_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let render_targets = { + let g = LISTS.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&(list as usize))).and_then(|s| s.bindings.render_targets.clone()) + }; + let Some(rt) = render_targets else { return }; + if list_type(list) != D3D12_COMMAND_LIST_TYPE_DIRECT { + return; + } + + let mut rtv_handles = Vec::with_capacity(rt.num_targets as usize); + if rt.single != 0 { + if let Some(&first) = rt.handles.first() { + if first != 0 { + let n = rt.num_targets as usize; + let inc = if n > 1 { rtv_descriptor_increment(list).unwrap_or(0) } else { 0 }; + if n == 1 || inc != 0 { + for i in 0..n { + rtv_handles.push(first + i * inc); + } + } else { + rtv_handles.push(first); + } + } + } + } else { + for &h in &rt.handles { + if h != 0 { + rtv_handles.push(h); + } + } + } + + let mut init_count = 0usize; + let mut aliased_count = 0usize; + for h in rtv_handles { + let target = RTV_HANDLES.lock().unwrap().as_ref().and_then(|m| m.get(&h).copied()); + let Some((res, sub)) = target else { continue }; + if let Some((color, aliased)) = claim_uninit_target(res, sub, |t| (t.clear_color, t.aliased)) { + pc::( + list, + PC_CLEAR_RENDER_TARGET_VIEW, + )(list, h, &color, 0, std::ptr::null()); + init_count += 1; + if aliased { + aliased_count += 1; + } + } + } + + if let Some(dsv_h) = rt.dsv.filter(|&h| h != 0) { + let dsv_info = DSV_HANDLES.lock().unwrap().as_ref().and_then(|m| m.get(&dsv_h).copied()); + if let Some(info) = dsv_info { + if let Some((depth, stencil, aliased)) = claim_uninit_target(info.res, info.subresource, |t| (t.clear_depth, t.clear_stencil, t.aliased)) { + let mut cflags = 0u32; + if !info.read_only_depth { + cflags |= D3D12_CLEAR_FLAG_DEPTH.0 as u32; + } + if info.has_stencil && !info.read_only_stencil { + cflags |= D3D12_CLEAR_FLAG_STENCIL.0 as u32; + } + if cflags != 0 { + pc::( + list, + PC_CLEAR_DEPTH_STENCIL_VIEW, + )(list, dsv_h, cflags, depth, stencil, 0, std::ptr::null()); + } else { + transition_subresource( + list, + info.res, + info.subresource, + D3D12_RESOURCE_STATE_DEPTH_READ, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let region = D3D12_DISCARD_REGION { + NumRects: 0, + pRects: std::ptr::null(), + FirstSubresource: info.subresource, + NumSubresources: 1, + }; + pc::(list, PC_DISCARD_RESOURCE)( + list, + info.res, + ®ion, + ); + transition_subresource( + list, + info.res, + info.subresource, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + } + init_count += 1; + if aliased { + aliased_count += 1; + } + } + } + } + + if init_count > 0 { + static LOGGED: AtomicU64 = AtomicU64::new(0); + if once(&LOGGED, 8) { + crate::xlog_info!( + "D3D12.X: auto-initialized {init_count} placed/reserved RT/DS target(s) before first draw ({aliased_count} aliased)" + ); + } + } +} + +/// Apply uninitialized RT/DS target auto-initialization and any pending fallback `RSSetDepthBiasX` +/// override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { + ensure_bound_targets_initialized(list); if !DEPTH_BIAS_USED.load(Ordering::Acquire) { return; } @@ -3897,6 +4387,10 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + if bx.is_null() && x == 0 && y == 0 && z == 0 && d.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { + let dst_res: usize = transmute_copy(&d.pResource); + mark_target_initialized(dst_res, Some(d.Anonymous.SubresourceIndex)); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -3922,7 +4416,10 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } - pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) + pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects); + if n == 0 && flags != 0 { + mark_dsv_initialized(dsv); + } } const PC_RESOLVE_SUBRESOURCE: usize = 19; @@ -3957,7 +4454,8 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); - pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) + pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format); + mark_target_initialized(dst, Some(dst_sub)); } /// command list #108 ResolveSubresourceRegion(dst, dst sub, x, y, src, src sub, rect, format, @@ -3968,7 +4466,10 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); } - pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode) + pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode); + if rect.is_null() && x == 0 && y == 0 { + mark_target_initialized(dst, Some(dst_sub)); + } } /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address @@ -3981,7 +4482,9 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { - return pc::(this, PC_COPY_RESOURCE)(this, dst, src); + pc::(this, PC_COPY_RESOURCE)(this, dst, src); + mark_target_initialized(dst, None); + return; } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); copy_buffer_region_x(this, dst, 0, src, 0, n); @@ -6215,4 +6718,283 @@ mod tests { // address must not come back for another test's memory } } + + #[test] + fn shading_rate_and_combiner_sanitization() { + assert_eq!(sanitize_shading_rate(0, false), 0); + assert_eq!(sanitize_shading_rate(1, false), 1); + assert_eq!(sanitize_shading_rate(4, false), 4); + assert_eq!(sanitize_shading_rate(5, false), 5); + assert_eq!(sanitize_shading_rate(6, false), 5); + assert_eq!(sanitize_shading_rate(9, false), 5); + assert_eq!(sanitize_shading_rate(10, false), 5); + assert_eq!(sanitize_shading_rate(6, true), 6); + assert_eq!(sanitize_shading_rate(9, true), 9); + assert_eq!(sanitize_shading_rate(10, true), 10); + assert_eq!(sanitize_shading_rate(2, true), 0); + assert_eq!(sanitize_shading_rate(99, false), 0); + + assert_eq!(sanitize_combiners([0, 4]), [0, 4]); + assert_eq!(sanitize_combiners([5, 99]), [0, 0]); + assert_eq!(sanitize_combiners([3, 8]), [3, 0]); + } + + #[test] + fn console_list_state_slots_track_and_reset() { + #[repr(C)] + struct FakeBarrierList { + vt: *const usize, + ty: i32, + barriers: Mutex>, + } + unsafe extern "system" fn fake_get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE((*(this as *const FakeBarrierList)).ty) + } + unsafe extern "system" fn fake_barrier(this: *mut c_void, count: u32, barriers: *const D3D12_RESOURCE_BARRIER) { + let mut g = (*(this as *const FakeBarrierList)).barriers.lock().unwrap(); + for i in 0..count as usize { + g.push((*barriers.add(i)).Type.0 as u32); + } + } + unsafe extern "system" fn fake_reset(_this: *mut c_void, _alloc: usize, _pso: usize) -> i32 { + 0 + } + + let mut orig_vt = [0usize; 32]; + orig_vt[PC_GET_TYPE] = fake_get_type as usize; + orig_vt[PC_RESET] = fake_reset as usize; + orig_vt[PC_RESOURCE_BARRIER] = fake_barrier as usize; + let mut ext_vt = [0usize; 2]; + ext_vt[0] = orig_vt.as_ptr() as usize; + + let mut fake = Box::new(FakeBarrierList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + barriers: Mutex::new(Vec::new()), + }); + let list_ptr = &mut *fake as *mut FakeBarrierList as *mut c_void; + + unsafe { + set_pipeline_flag_x(list_ptr, 1); + set_quad_sample_mask_x(list_ptr, 0xFFFF_0000_FFFF_0000); + set_clear_batch_hint_x(list_ptr, 2, 1); + assert!(fake.barriers.lock().unwrap().is_empty()); + + // Flush slots: zero size or zero flags emit no barrier; non-zero on DIRECT/COMPUTE emits 1 UAV barrier. + flush_gpu_cache_range_x(list_ptr, 0, 0, 0, 0x1000); + flush_gpu_cache_range_x(list_ptr, 0xc3c0, 0, 0, 0); + assert!(fake.barriers.lock().unwrap().is_empty()); + + flush_gpu_cache_range_x(list_ptr, 0xc3c0, 0x8002_0000, 0, 0xFFFF_FFFF_FF00); + flush_shader_cache_range_x(list_ptr, 0x70_0000, 0, 0, 0xFFFF_FFFF_FF00); + assert_eq!(*fake.barriers.lock().unwrap(), vec![D3D12_RESOURCE_BARRIER_TYPE_UAV.0 as u32; 2]); + + // COPY lists must not receive UAV barriers. + fake.ty = D3D12_COMMAND_LIST_TYPE_COPY.0; + flush_gpu_cache_range_x(list_ptr, 0xc3c0, 0, 0, 0xFFFF_FFFF_FF00); + flush_shader_cache_range_x(list_ptr, 0x70_0000, 0, 0, 0xFFFF_FFFF_FF00); + assert_eq!(fake.barriers.lock().unwrap().len(), 2); + + assert_eq!(reset_x(list_ptr, 0, 0), 0); + on_release(list_ptr as usize); + } + } + + #[test] + fn uninit_placed_rt_ds_initialized_before_first_draw_and_skipped_after_clear() { + #[repr(C)] + struct FakeUninitList { + vt: *const usize, + ty: i32, + barriers: Mutex>, + rtv_clears: Mutex>, + dsv_clears: Mutex>, + discards: Mutex>, + } + + unsafe extern "system" fn fake_get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE((*(this as *const FakeUninitList)).ty) + } + unsafe extern "system" fn fake_barrier(this: *mut c_void, count: u32, barriers: *const D3D12_RESOURCE_BARRIER) { + let mut g = (*(this as *const FakeUninitList)).barriers.lock().unwrap(); + for i in 0..count as usize { + let b = &*barriers.add(i); + if b.Type == D3D12_RESOURCE_BARRIER_TYPE_TRANSITION { + g.push((b.Type.0, b.Anonymous.Transition.StateBefore.0, b.Anonymous.Transition.StateAfter.0)); + } else { + g.push((b.Type.0, 0, 0)); + } + } + } + unsafe extern "system" fn fake_clear_rtv( + this: *mut c_void, + rtv: usize, + color: *const [f32; 4], + _n: u32, + _rects: *const windows::Win32::Foundation::RECT, + ) { + (*(this as *const FakeUninitList)).rtv_clears.lock().unwrap().push((rtv, *color)); + } + unsafe extern "system" fn fake_clear_dsv( + this: *mut c_void, + dsv: usize, + flags: u32, + depth: f32, + stencil: u8, + _n: u32, + _rects: *const windows::Win32::Foundation::RECT, + ) { + (*(this as *const FakeUninitList)).dsv_clears.lock().unwrap().push((dsv, flags, depth, stencil)); + } + unsafe extern "system" fn fake_discard(this: *mut c_void, res: usize, region: *const D3D12_DISCARD_REGION) { + let r = &*region; + (*(this as *const FakeUninitList)) + .discards + .lock() + .unwrap() + .push((res, r.FirstSubresource, r.NumSubresources)); + } + + let mut orig_vt = [0usize; 64]; + orig_vt[PC_GET_TYPE] = fake_get_type as usize; + orig_vt[PC_RESOURCE_BARRIER] = fake_barrier as usize; + orig_vt[PC_CLEAR_DEPTH_STENCIL_VIEW] = fake_clear_dsv as usize; + orig_vt[PC_CLEAR_RENDER_TARGET_VIEW] = fake_clear_rtv as usize; + orig_vt[PC_DISCARD_RESOURCE] = fake_discard as usize; + let mut ext_vt = [0usize; 2]; + ext_vt[0] = orig_vt.as_ptr() as usize; + + let mut fake = Box::new(FakeUninitList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + ty: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + barriers: Mutex::new(Vec::new()), + rtv_clears: Mutex::new(Vec::new()), + dsv_clears: Mutex::new(Vec::new()), + discards: Mutex::new(Vec::new()), + }); + let list_ptr = &mut *fake as *mut FakeUninitList as *mut c_void; + + let rt_res = 0x7900_0001usize; + let dsv_res = 0x7900_0002usize; + let ro_res = 0x7900_0003usize; + let pre_res = 0x7900_0004usize; + let rtv_handle = 0x7900_1001usize; + let pre_handle = 0x7900_1002usize; + let dsv_handle = 0x7900_2001usize; + let ro_handle = 0x7900_2002usize; + + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let rt_clear = D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.25, 0.5, 0.75, 1.0] }, + }; + let rtv_view = D3D12_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + + let ds_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let ds_clear = D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + Anonymous: D3D12_CLEAR_VALUE_0 { + DepthStencil: D3D12_DEPTH_STENCIL_VALUE { Depth: 1.0, Stencil: 7 }, + }, + }; + let dsv_view = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_NONE, + ..Default::default() + }; + let ro_dsv_view = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + + unsafe { + note_uninit_target_if_rt_ds(rt_res, &rt_desc, &rt_clear as *const _ as *const c_void, true); + note_rtv_handle(rtv_handle, rt_res, Some(&rtv_view)); + note_uninit_target_if_rt_ds(dsv_res, &ds_desc, &ds_clear as *const _ as *const c_void, false); + note_dsv_handle(dsv_handle, dsv_res, Some(&dsv_view)); + + note_render_targets(list_ptr, 1, &rtv_handle, 0, &dsv_handle); + prepare_draw(list_ptr); + assert_eq!(*fake.rtv_clears.lock().unwrap(), vec![(rtv_handle, [0.25, 0.5, 0.75, 1.0])]); + assert_eq!( + *fake.dsv_clears.lock().unwrap(), + vec![( + dsv_handle, + (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL).0 as u32, + 1.0, + 7, + )] + ); + assert!(fake.discards.lock().unwrap().is_empty()); + + // Second draw on same targets does not re-clear. + prepare_draw(list_ptr); + assert_eq!(fake.rtv_clears.lock().unwrap().len(), 1); + assert_eq!(fake.dsv_clears.lock().unwrap().len(), 1); + + // Read-only DSV transitions DEPTH_READ -> DEPTH_WRITE, discards subresource 0, and transitions back. + note_uninit_target_if_rt_ds(ro_res, &ds_desc, std::ptr::null(), false); + note_dsv_handle(ro_handle, ro_res, Some(&ro_dsv_view)); + note_render_targets(list_ptr, 0, std::ptr::null(), 0, &ro_handle); + prepare_draw(list_ptr); + assert_eq!(fake.dsv_clears.lock().unwrap().len(), 1); + assert_eq!(*fake.discards.lock().unwrap(), vec![(ro_res, 0, 1)]); + assert_eq!( + *fake.barriers.lock().unwrap(), + vec![ + ( + D3D12_RESOURCE_BARRIER_TYPE_TRANSITION.0, + D3D12_RESOURCE_STATE_DEPTH_READ.0, + D3D12_RESOURCE_STATE_DEPTH_WRITE.0, + ), + ( + D3D12_RESOURCE_BARRIER_TYPE_TRANSITION.0, + D3D12_RESOURCE_STATE_DEPTH_WRITE.0, + D3D12_RESOURCE_STATE_DEPTH_READ.0, + ), + ] + ); + + // Explicit ClearRenderTargetView before first draw suppresses auto-initialization. + note_uninit_target_if_rt_ds(pre_res, &rt_desc, &rt_clear as *const _ as *const c_void, false); + note_rtv_handle(pre_handle, pre_res, Some(&rtv_view)); + mark_rtv_initialized(pre_handle); + note_render_targets(list_ptr, 1, &pre_handle, 0, std::ptr::null()); + prepare_draw(list_ptr); + assert_eq!(fake.rtv_clears.lock().unwrap().len(), 1); + + forget_target(rt_res); + forget_target(dsv_res); + forget_target(ro_res); + forget_target(pre_res); + on_release(list_ptr as usize); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 01b3c92a4..e85415836 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -62,7 +62,7 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl } unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u8) { - let frames = BOUNDARIES.fetch_add(1, Ordering::Relaxed) + 1; + let frames = BOUNDARIES.fetch_add(1, Ordering::Release) + 1; if frames % 300 == 0 { // the title's frame rate, for comparing runs (every 300 frames) static LAST: Mutex> = Mutex::new(None); @@ -141,6 +141,11 @@ pub fn counters() -> (u64, u64) { (PRESENTS.load(Ordering::Relaxed), BOUNDARIES.load(Ordering::Relaxed)) } +/// Monotonic frame boundary count (increments on every PresentX / fallback frame boundary). +pub fn frame_generation() -> u64 { + BOUNDARIES.load(Ordering::Acquire) +} + fn enabled() -> bool { !crate::state::config().present.eq_ignore_ascii_case("off") } @@ -298,7 +303,7 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { if !enabled() || PRESENTX.load(Ordering::Relaxed) { return; } - BOUNDARIES.fetch_add(1, Ordering::Relaxed); + BOUNDARIES.fetch_add(1, Ordering::Release); LAST_BOUNDARY_MS.store(now_ms(), Ordering::Relaxed); unsafe { present_now(Duration::from_millis(4), None) }; } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 2245dceb6..8f3692a60 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,14 +8,14 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; 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, + sent: AtomicBool, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, done: Mutex, @@ -24,20 +24,30 @@ struct Pending { /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) - used: std::sync::atomic::AtomicBool, + used: AtomicBool, /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, + orphan: AtomicBool, /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built - late: std::sync::atomic::AtomicBool, + late: AtomicBool, + /// a critical dispatch or indirect bind waited past its grace budget without finishing + critical_late: AtomicBool, + /// lock-free mirror of `demand.wanted` for polling from worker queues without lock nesting + wanted_flag: AtomicBool, demand: Mutex, } -/// Whether one of the title's threads waits for the pipeline, and the preload worker building it. +/// Whether one of the title's threads waits for the pipeline, and the worker building it. #[derive(Default)] struct Demand { wanted: bool, - /// thread id of the preload worker (lowest priority) building it, 0 = none - preload_thread: u32, + /// an unbounded waiter (`want`) requires this build until completion + unbounded_wanted: bool, + /// active timed waiters (cleared on timeout so late builds do not bypass throttling) + timed_waiters: usize, + /// thread id of the worker building it (preload or queue worker), 0 = none + worker_thread: u32, + /// base thread priority to restore when no longer wanted + base_priority: i32, } thread_local! { @@ -48,58 +58,116 @@ thread_local! { /// This thread is a worker and one of the title's threads waits for what it is building: the /// build must not stand back for the title's sake (`real::big_compile_turn`). pub(super) fn build_is_wanted() -> bool { - BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.wanted_flag.load(Ordering::Acquire))) } /// Whether one of the title's threads waits for what this thread is doing, to be asked later and -/// from another thread: a worker's build as `build_is_wanted`; a thread that is not XCL's is the +/// from another thread: a worker's build as `wanted_flag`; a thread that is not XCL's is the /// title's own. pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { if let Some(p) = BUILDING.with(|b| b.borrow().clone()) { - return Box::new(move || p.demand.lock().unwrap().wanted); + return Box::new(move || p.wanted_flag.load(Ordering::Acquire)); } let own = crate::state::boot().is_some() && !std::thread::current().name().is_some_and(|n| n.starts_with("xcl-")); Box::new(move || own) } +fn set_thread_priority_by_id(tid: u32, priority: i32) { + 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, priority); + CloseHandle(h); + } + } +} + /// A worker's build of `p` (`preload`: by one of the lowest-priority workers). fn build(p: &Arc, job: Job, preload: bool) { - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetCurrentThreadId, SetThreadPriority, + THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL, + }; + let base_priority = if preload { + THREAD_PRIORITY_LOWEST + } else if crate::state::boot().is_some() { + THREAD_PRIORITY_BELOW_NORMAL + } else { + THREAD_PRIORITY_NORMAL + }; BUILDING.with(|b| *b.borrow_mut() = Some(p.clone())); - if preload { + { let mut d = p.demand.lock().unwrap(); - d.preload_thread = unsafe { GetCurrentThreadId() }; - if d.wanted { - unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; - } + d.worker_thread = unsafe { GetCurrentThreadId() }; + d.base_priority = base_priority; + let target = if d.wanted { THREAD_PRIORITY_NORMAL } else { base_priority }; + unsafe { SetThreadPriority(GetCurrentThread(), target) }; } complete(p, job()); - if preload { - // (under the lock: `want` does not raise this thread after it) + { + // (under the lock: `want` / timed-wait transitions do not race priority restore) let mut d = p.demand.lock().unwrap(); - d.preload_thread = 0; - if d.wanted { - unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; - } + d.worker_thread = 0; + unsafe { SetThreadPriority(GetCurrentThread(), base_priority) }; } BUILDING.with(|b| *b.borrow_mut() = None); } impl Pending { - /// One of the title's threads is about to wait for it: the worker building it goes on now, - /// at a normal priority. + /// One of the title's threads waits unconditionally for it: boost worker and wake pools. fn want(&self) { - use windows_sys::Win32::Foundation::CloseHandle; - use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; - let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { - unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); - if !h.is_null() { - SetThreadPriority(h, THREAD_PRIORITY_NORMAL); - CloseHandle(h); - } + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let boost = { + let mut d = self.demand.lock().unwrap(); + d.unbounded_wanted = true; + let first = !std::mem::replace(&mut d.wanted, true); + self.wanted_flag.store(true, Ordering::Release); + (first && d.worker_thread != 0 && d.base_priority != THREAD_PRIORITY_NORMAL).then_some(d.worker_thread) + }; + if let Some(tid) = boost { + set_thread_priority_by_id(tid, THREAD_PRIORITY_NORMAL); + } + crate::gpu::recomp::dxc::wake_pool(); + wake_queue(); + } + + /// A title thread starts a bounded wait for this build: boost worker while actively waiting. + fn begin_timed_wait(&self) { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let boost = { + let mut d = self.demand.lock().unwrap(); + d.timed_waiters += 1; + let first = !std::mem::replace(&mut d.wanted, true); + self.wanted_flag.store(true, Ordering::Release); + (first && d.worker_thread != 0 && d.base_priority != THREAD_PRIORITY_NORMAL).then_some(d.worker_thread) + }; + if let Some(tid) = boost { + set_thread_priority_by_id(tid, THREAD_PRIORITY_NORMAL); + } + crate::gpu::recomp::dxc::wake_pool(); + wake_queue(); + } + + /// Bounded wait finished (`timed_out`: clear wanted/priority boost once last waiter times out + /// so late cold builds cannot bypass throttling or starve foreground threads). + fn end_timed_wait(&self, timed_out: bool) { + use windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL; + let restore = { + let mut d = self.demand.lock().unwrap(); + d.timed_waiters = d.timed_waiters.saturating_sub(1); + if timed_out && d.timed_waiters == 0 && !d.unbounded_wanted { + d.wanted = false; + self.wanted_flag.store(false, Ordering::Release); + (d.worker_thread != 0 && d.base_priority != THREAD_PRIORITY_NORMAL) + .then_some((d.worker_thread, d.base_priority)) + } else { + None } + }; + if let Some((tid, prio)) = restore { + set_thread_priority_by_id(tid, prio); } } @@ -145,29 +213,135 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex>> { - static Q: OnceLock>>> = OnceLock::new(); +struct WorkQueueState { + list: std::collections::VecDeque>, + late_running: usize, +} + +struct WorkQueue { + state: Mutex, + cv: Condvar, +} + +struct LateSlotGuard(&'static WorkQueue); + +impl Drop for LateSlotGuard { + fn drop(&mut self) { + let mut st = self.0.state.lock().unwrap(); + st.late_running -= 1; + self.0.cv.notify_all(); + } +} + +static Q: OnceLock = OnceLock::new(); + +/// Pick the highest-priority non-orphan build from `list`: +/// 1. `wanted` (a title thread is actively waiting for it), +/// 2. non-late compute, +/// 3. non-late graphics, +/// 4. late builds only while `late_running < max_late` (keeping lanes open for fresh/warm PSOs). +fn pick_work_item( + list: &mut std::collections::VecDeque, + late_running: usize, + max_late: usize, + is_orphan: impl Fn(&T) -> bool, + is_wanted: impl Fn(&T) -> bool, + is_late: impl Fn(&T) -> bool, + is_compute: impl Fn(&T) -> bool, +) -> Option<(T, bool)> { + while list.front().is_some_and(&is_orphan) { + list.pop_front(); + } + if let Some(i) = list.iter().position(|x| !is_orphan(x) && is_wanted(x)) { + let item = list.remove(i)?; + return Some((item, false)); + } + if let Some(i) = list.iter().position(|x| !is_orphan(x) && !is_late(x) && is_compute(x)) { + let item = list.remove(i)?; + return Some((item, false)); + } + if let Some(i) = list.iter().position(|x| !is_orphan(x) && !is_late(x)) { + let item = list.remove(i)?; + return Some((item, false)); + } + if late_running < max_late { + if let Some(i) = list + .iter() + .position(|x| !is_orphan(x) && is_compute(x)) + .or_else(|| list.iter().position(|x| !is_orphan(x))) + { + let item = list.remove(i)?; + return Some((item, true)); + } + } + None +} + +fn queue() -> &'static WorkQueue { Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::>(); - let rx = Arc::new(Mutex::new(rx)); + let q = WorkQueue { + state: Mutex::new(WorkQueueState { + list: std::collections::VecDeque::new(), + late_running: 0, + }), + cv: Condvar::new(), + }; // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); + let max_late = n.saturating_sub(2).max(1); 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 next = rx.lock().unwrap().recv(); - let Ok(p) = next else { return }; - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + let q = Q.wait(); + loop { + let (p, _late_guard) = { + let mut st = q.state.lock().unwrap(); + loop { + let late_running = st.late_running; + if let Some((p, is_late)) = pick_work_item( + &mut st.list, + late_running, + max_late, + |p| p.orphan.load(Ordering::Acquire), + |p| p.wanted_flag.load(Ordering::Acquire), + |p| p.late.load(Ordering::Acquire), + |p| p.compute, + ) { + let guard = if is_late { + st.late_running += 1; + Some(LateSlotGuard(q)) + } else { + None + }; + break (p, guard); + } + st = q.cv.wait(st).unwrap(); + } + }; + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(&p, job, false); + } } }); } - Mutex::new(tx) + q }) } +fn enqueue_work(p: Arc) { + let q = queue(); + q.state.lock().unwrap().list.push_back(p); + q.cv.notify_all(); +} + +fn wake_queue() { + if let Some(q) = Q.get() { + let _g = q.state.lock().unwrap(); + q.cv.notify_all(); + } +} + /// Release a pipeline state XCL owns (raw pointer, 0 = none). pub fn release(p: usize) { if p != 0 { @@ -199,7 +373,7 @@ 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) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), - sent: std::sync::atomic::AtomicBool::new(send), + sent: AtomicBool::new(send), real: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), @@ -208,6 +382,8 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { used: Default::default(), orphan: Default::default(), late: Default::default(), + critical_late: Default::default(), + wanted_flag: AtomicBool::new(false), demand: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -216,7 +392,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - let _ = queue().lock().unwrap().send(p); + enqueue_work(p); } else if used::known(key) { if let Some(q) = preload() { q.list.lock().unwrap().push_back(p); @@ -361,6 +537,7 @@ fn preload() -> Option<&'static Preload> { #[cfg(test)] mod used_tests { use super::*; + use std::sync::mpsc; /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. @@ -458,6 +635,184 @@ mod used_tests { released(known); released(unknown); } + + #[test] + fn frame_wait_budget_caps_burst_and_resets_on_next_frame() { + use std::time::{Duration, Instant}; + let mut fb = FrameBudget::default(); + let per_pso = Duration::from_millis(35); + let per_frame = Duration::from_millis(75); + + let (tx1, rx1) = mpsc::channel(); + let (tx2, rx2) = mpsc::channel(); + let (tx3, rx3) = mpsc::channel(); + let (tx4, rx4) = mpsc::channel(); + let (p1, p2, p3, p4) = (0x7E57_C001usize, 0x7E57_C002usize, 0x7E57_C003usize, 0x7E57_C004usize); + submit(p1, true, Box::new(move || { let _ = rx1.recv_timeout(Duration::from_secs(5)); 0xA1 })); + submit(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(5)); 0xA2 })); + submit(p3, true, Box::new(move || { let _ = rx3.recv_timeout(Duration::from_secs(5)); 0xA3 })); + submit(p4, true, Box::new(move || { let _ = rx4.recv_timeout(Duration::from_secs(5)); 0xA4 })); + + let e1 = entry(p1).unwrap(); + let e2 = entry(p2).unwrap(); + let e3 = entry(p3).unwrap(); + let e4 = entry(p4).unwrap(); + + let t0 = Instant::now(); + assert_eq!(resolve_within_with_frame(&e1, p1, per_pso, per_frame, 1, &mut fb, false), (p1, true)); + assert_eq!(resolve_within_with_frame(&e2, p2, per_pso, per_frame, 1, &mut fb, false), (p2, true)); + // Even with remaining budget (~0-5 ms), p3 + p4 must finish within per_frame + timer slack, + // and once spent >= per_frame, p4 does not wait and neither p3 nor p4 is marked late. + let _ = resolve_within_with_frame(&e3, p3, per_pso, per_frame, 1, &mut fb, false); + let t4 = Instant::now(); + assert_eq!(resolve_within_with_frame(&e4, p4, per_pso, per_frame, 1, &mut fb, false), (p4, true)); + assert!(t4.elapsed() < Duration::from_millis(20), "exhausted frame budget must skip wait ({:?})", t4.elapsed()); + assert!(t0.elapsed() < Duration::from_millis(250), "burst waited {:?}", t0.elapsed()); + assert!(!e3.late.load(Ordering::Acquire), "frame-truncated PSO wait must not be marked late"); + assert!(!e4.late.load(Ordering::Acquire), "budget-skipped PSO must not be marked late"); + + // Moving to frame 2 resets the budget so p4 gets a fresh wait window. + let t_next = Instant::now(); + assert_eq!(resolve_within_with_frame(&e4, p4, per_pso, per_frame, 2, &mut fb, false), (p4, true)); + assert!(t_next.elapsed() >= Duration::from_millis(20), "new frame must reset wait budget ({:?})", t_next.elapsed()); + assert!(e4.late.load(Ordering::Acquire), "timed-out PSO in fresh frame becomes late"); + + let _ = tx1.send(()); + let _ = tx2.send(()); + let _ = tx3.send(()); + let _ = tx4.send(()); + let start = Instant::now(); + for p in [p1, p2, p3, p4] { + while is_pending(p) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!is_pending(p)); + let _ = released(p); + } + } + + #[test] + fn critical_wait_uses_grace_budget_and_truncated_remainder_stays_non_late() { + use std::time::{Duration, Instant}; + assert_eq!(critical_frame_budget_for(Duration::from_millis(250)), Duration::from_millis(2_000)); + assert_eq!(critical_frame_budget_for(Duration::from_millis(1_000)), Duration::from_millis(2_000)); + assert_eq!(critical_frame_budget_for(Duration::from_millis(3_500)), Duration::from_millis(3_500)); + + let mut fb = FrameBudget::default(); + let normal_per_pso = Duration::from_millis(25); + let normal_per_frame = Duration::from_millis(50); + let crit_per_pso = Duration::from_millis(500); + let crit_per_frame = Duration::from_millis(1_000); + + let (tx1, rx1) = mpsc::channel(); + let (tx2, rx2) = mpsc::channel(); + let (tx3, rx3) = mpsc::channel(); + let (p1, p2, p3) = (0x7E57_C021usize, 0x7E57_C022usize, 0x7E57_C023usize); + submit(p1, true, Box::new(move || { let _ = rx1.recv_timeout(Duration::from_secs(5)); 0xC1 })); + submit(p2, true, Box::new(move || { let _ = rx2.recv_timeout(Duration::from_secs(5)); 0xC2 })); + submit_lazy(p3, true, Box::new(move || { let _ = rx3.recv_timeout(Duration::from_secs(5)); 0xC3 }), 0); + + let e1 = entry(p1).unwrap(); + let e2 = entry(p2).unwrap(); + let e3 = entry(p3).unwrap(); + + // Exhaust the normal per-frame budget via p1 and p2 (which becomes frame-truncated, not late). + assert_eq!(resolve_within_with_frame(&e1, p1, normal_per_pso, normal_per_frame, 1, &mut fb, false), (p1, true)); + fb.record(1, Duration::from_millis(15)); + assert_eq!(resolve_within_with_frame(&e2, p2, normal_per_pso, normal_per_frame, 1, &mut fb, false), (p2, true)); + assert!(e1.late.load(Ordering::Acquire)); + assert!(!e2.late.load(Ordering::Acquire), "truncated frame wait must not set late"); + assert!(!e1.critical_late.load(Ordering::Acquire), "normal wait must not set critical_late"); + + // p3 takes ~40ms (longer than normal 25ms, well inside critical 500ms): even though the + // normal frame budget is exhausted, the critical grace frame budget lets it finish. + let wake_p3 = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(40)); + let _ = tx3.send(()); + }); + assert_eq!(resolve_within_with_frame(&e3, p3, crit_per_pso, crit_per_frame, 1, &mut fb, true), (0xC3, false)); + wake_p3.join().unwrap(); + // e1 timed out on normal wait (`e1.late == true`) but still gets one critical grace attempt. + let t_crit = Instant::now(); + assert_eq!(resolve_within_with_frame(&e1, p1, Duration::from_millis(30), crit_per_frame, 1, &mut fb, true), (p1, true)); + assert!(t_crit.elapsed() >= Duration::from_millis(15), "critical path must retry after normal late ({:?})", t_crit.elapsed()); + assert!(e1.critical_late.load(Ordering::Acquire)); + + let _ = tx1.send(()); + let _ = tx2.send(()); + let start = Instant::now(); + for p in [p1, p2, p3] { + while is_pending(p) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!is_pending(p)); + let _ = released(p); + } + } + + #[test] + fn timed_out_wait_clears_wanted_flag() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_C010usize; + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + submit(standin, true, Box::new(move || { + started_tx.send(wanted_here()).unwrap(); + let _ = done_rx.recv_timeout(Duration::from_secs(5)); + 0xB1B1 + })); + let wanted_probe = started_rx.recv().unwrap(); + let p = entry(standin).unwrap(); + p.begin_timed_wait(); + assert!(wanted_probe(), "active timed wait must raise wanted_flag"); + p.end_timed_wait(true); + assert!(!wanted_probe(), "timed-out wait must clear wanted_flag"); + let mut fb = FrameBudget::default(); + assert_eq!( + resolve_within_with_frame(&p, standin, Duration::from_millis(25), Duration::from_millis(200), 1, &mut fb, false), + (standin, true) + ); + assert!(!wanted_probe(), "timed-out wait must clear wanted_flag so late build yields to throttling"); + assert!(p.late.load(Ordering::Acquire)); + let _ = done_tx.send(()); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(released(standin), 0xB1B1); + } + + #[test] + fn work_queue_prioritizes_wanted_and_reserves_lanes_for_fresh_builds() { + use std::collections::VecDeque; + #[derive(Debug, PartialEq, Eq)] + struct Item { + id: u32, + orphan: bool, + wanted: bool, + late: bool, + compute: bool, + } + let mut q = VecDeque::from([ + Item { id: 1, orphan: true, wanted: false, late: false, compute: false }, + Item { id: 2, orphan: false, wanted: false, late: true, compute: false }, + Item { id: 3, orphan: false, wanted: false, late: false, compute: false }, + Item { id: 4, orphan: false, wanted: false, late: false, compute: true }, + Item { id: 5, orphan: false, wanted: true, late: true, compute: false }, + Item { id: 6, orphan: false, wanted: false, late: true, compute: true }, + ]); + let pick = |q: &mut VecDeque, late_running, max_late| { + pick_work_item(q, late_running, max_late, |x| x.orphan, |x| x.wanted, |x| x.late, |x| x.compute) + .map(|(x, is_late)| (x.id, is_late)) + }; + assert_eq!(pick(&mut q, 0, 2), Some((5, false)), "wanted jumps ahead of everything"); + assert_eq!(pick(&mut q, 0, 2), Some((4, false)), "non-late compute precedes non-late graphics"); + assert_eq!(pick(&mut q, 0, 2), Some((3, false)), "non-late graphics precedes late items"); + assert_eq!(pick(&mut q, 2, 2), None, "saturated late cap keeps lanes open for fresh PSOs"); + assert_eq!(pick(&mut q, 1, 2), Some((6, true)), "under late cap, late compute precedes late graphics"); + assert_eq!(pick(&mut q, 1, 2), Some((2, true)), "finally late graphics"); + assert_eq!(pick(&mut q, 0, 2), None); + } } fn entry(pso: usize) -> Option> { @@ -472,7 +827,7 @@ pub fn resolve(pso: usize) -> usize { 0 => { // a lazy one is wanted now: to the workers if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p); + enqueue_work(p); } pso } @@ -480,18 +835,129 @@ 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). +/// Default per-PSO bind wait when running a title: warm compute PSOs from the disk driver +/// cache finish in 0-111 ms, while cold compiles take 261 ms to 65 s. +const DEFAULT_TITLE_WAIT_MS: u64 = 250; +/// Maximum cumulative wait per thread within one PresentX frame, preventing a burst of +/// cold PSOs from exceeding a title's 30 s hang watchdog. +const DEFAULT_FRAME_WAIT_BUDGET_MS: u64 = 2_000; + +#[derive(Clone, Copy)] +enum EnvWaitBudget { + Unset, + Unbounded, + Millis(u64), +} + +const CRITICAL_FRAME_WAIT_CAP_MS: u64 = 2_000; + +fn env_wait_budget() -> EnvWaitBudget { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| match std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()) { + Some(0) => EnvWaitBudget::Unbounded, + Some(ms) => EnvWaitBudget::Millis(ms), + None => EnvWaitBudget::Unset, + }) +} + +/// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; `0`: until built; +/// unset: bounded to `DEFAULT_TITLE_WAIT_MS` when running a title so cold bursts cannot trip its +/// hang watchdog, unbounded otherwise). +fn wait_budget() -> Option { + match env_wait_budget() { + EnvWaitBudget::Unbounded => None, + EnvWaitBudget::Millis(ms) => Some(std::time::Duration::from_millis(ms)), + EnvWaitBudget::Unset => crate::state::boot().is_some().then(|| std::time::Duration::from_millis(DEFAULT_TITLE_WAIT_MS)), + } +} + +fn critical_wait_budget(base: Option) -> Option { + let base = base?; + if matches!(env_wait_budget(), EnvWaitBudget::Millis(_)) { + Some(base) + } else { + Some(base.saturating_mul(4)) + } +} + +#[derive(Default)] +struct FrameBudget { + frame: u64, + spent: std::time::Duration, +} + +impl FrameBudget { + fn remaining(&mut self, frame: u64, per_pso: std::time::Duration, per_frame: std::time::Duration) -> std::time::Duration { + if self.frame != frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + } + per_pso.min(per_frame.saturating_sub(self.spent)) + } + + fn record(&mut self, frame: u64, waited: std::time::Duration) { + if self.frame != frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + } + self.spent = self.spent.saturating_add(waited); + } +} + +thread_local! { + static FRAME_BUDGET: std::cell::RefCell = std::cell::RefCell::new(FrameBudget::default()); +} + +fn frame_budget_for(per_pso: std::time::Duration) -> std::time::Duration { + std::time::Duration::from_millis(DEFAULT_FRAME_WAIT_BUDGET_MS).max(per_pso) +} + +fn critical_frame_budget_for(per_pso: std::time::Duration) -> std::time::Duration { + let scaled = frame_budget_for(per_pso).saturating_mul(4); + let cap = std::time::Duration::from_millis(CRITICAL_FRAME_WAIT_CAP_MS); + scaled.min(cap).max(per_pso) +} + +/// `resolve`, waiting for a pipeline still being built – built here if unbounded and no worker +/// has started it yet, or waited on workers up to the per-PSO and per-frame budget. pub fn resolve_wait(pso: usize) -> usize { - resolve_wait_for(pso, wait_budget()) + resolve_wait_checked_for(pso, wait_budget()).0 +} + +/// Like `resolve_wait`, also returning whether `pso` is still building (timed out or late). +pub fn resolve_wait_checked(pso: usize) -> (usize, bool) { + resolve_wait_checked_for(pso, wait_budget()) +} + +/// Critical wait for `Dispatch` / `ExecuteIndirect`: grants a 4x per-PSO grace within the +/// 2_000 ms (`CRITICAL_FRAME_WAIT_CAP_MS`) per-frame cap when `XCL_PSO_WAIT_MS` is unset, and +/// allows one critical retry even if an earlier non-critical bind already marked `late`. +pub fn resolve_wait_critical(pso: usize) -> (usize, bool) { + resolve_wait_checked_with(pso, critical_wait_budget(wait_budget()), true) } /// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +#[cfg(test)] fn resolve_wait_for(pso: usize, budget: Option) -> usize { - let Some(p) = entry(pso) else { return pso }; + resolve_wait_checked_for(pso, budget).0 +} + +#[cfg(test)] +pub(super) fn resolve_wait_checked_for_test(pso: usize, budget: std::time::Duration) -> (usize, bool) { + resolve_wait_checked_for(pso, Some(budget)) +} + +fn resolve_wait_checked_for(pso: usize, budget: Option) -> (usize, bool) { + resolve_wait_checked_with(pso, budget, false) +} + +fn resolve_wait_checked_with(pso: usize, budget: Option, critical: bool) -> (usize, bool) { + let Some(p) = entry(pso) else { return (pso, false) }; p.note_use(); if let Some(budget) = budget { - return resolve_within(&p, pso, budget); + let frame = super::present::frame_generation(); + let per_frame = if critical { critical_frame_budget_for(budget) } else { frame_budget_for(budget) }; + return FRAME_BUDGET.with(|fb| resolve_within_with_frame(&p, pso, budget, per_frame, frame, &mut fb.borrow_mut(), critical)); } let job = p.job.lock().unwrap().take(); if let Some(job) = job { @@ -502,51 +968,81 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { while !*done { done = p.cv.wait(done).unwrap(); } - match p.real.load(Ordering::Acquire) { + let real = match p.real.load(Ordering::Acquire) { 0 => pso, r => r, - } -} - -/// 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. -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)) + }; + (real, 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. -fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { +/// `resolve_wait` for at most `per_pso` (and `per_frame` cumulatively in `frame`): the build goes +/// to the workers (never this thread), and a pipeline not built after waiting the full `per_pso` +/// is marked late – its binds go on without it until a worker finishes it. When the per-frame +/// budget truncates or skips the wait (`wait < per_pso`), the pipeline is NOT marked late so it +/// keeps its chance on the next frame (or on a critical bind). +fn resolve_within_with_frame( + p: &Arc, + pso: usize, + per_pso: std::time::Duration, + per_frame: std::time::Duration, + frame: u64, + fb: &mut FrameBudget, + critical: bool, +) -> (usize, bool) { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { 0 => pso, r => r, }; + let r = p.real.load(Ordering::Acquire); + if r != 0 { + return (r, false); + } if *p.done.lock().unwrap() { - return built(p); + return (built(p), false); } if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); + enqueue_work(p.clone()); } - if p.late.load(Ordering::Acquire) { - return pso; + let late_flag = if critical { &p.critical_late } else { &p.late }; + if late_flag.load(Ordering::Acquire) { + let r = p.real.load(Ordering::Acquire); + if r != 0 { + return (r, false); + } + let finished = *p.done.lock().unwrap(); + return (if finished { built(p) } else { pso }, !finished); } - p.want(); - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); + let wait = fb.remaining(frame, per_pso, per_frame); + if wait.is_zero() { + let finished = *p.done.lock().unwrap(); + return (if finished { built(p) } else { pso }, !finished); } + p.begin_timed_wait(); + let t0 = std::time::Instant::now(); + let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), wait, |d| !*d).unwrap(); + let finished = *done; drop(done); - p.late.store(true, Ordering::Release); - static N: AtomicUsize = AtomicUsize::new(0); - let n = N.fetch_add(1, Ordering::Relaxed); - if n < 16 || n.is_power_of_two() { - crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); + fb.record(frame, t0.elapsed()); + p.end_timed_wait(!finished); + if finished { + return (built(p), false); + } + if wait >= per_pso { + late_flag.store(true, Ordering::Release); + if critical { + p.late.store(true, Ordering::Release); + } + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", + wait.as_millis(), + n + 1 + ); + } } - pso + (pso, true) } /// For binding: compute pipelines are waited for, graphics ones are not. @@ -578,6 +1074,11 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// `pso` is a stand-in whose background build finished without a real pipeline (`0`). +pub fn is_failed_standin(pso: usize) -> bool { + entry(pso).is_some_and(|p| *p.done.lock().unwrap() && p.real.load(Ordering::Acquire) == 0) +} + /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac7ab4c4d..0f3a8cab0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -847,7 +847,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { /// methods at 124 / 125 (PC 77 / 78). The console-only methods in between: `list_x`. fn console_remap(kind: Kind) -> Vec<(usize, usize)> { match kind { - Kind::CommandList => (28..=31).map(|x| (x, x + 24)).chain((32..=55).map(|x| (x, x - 4))).chain((104..=109).map(|x| (x, x - 44))).chain([(124, 77), (125, 78)]).collect(), + Kind::CommandList => (28..=31).map(|x| (x, x + 24)).chain((32..=55).map(|x| (x, x - 4))).chain((104..=109).map(|x| (x, x - 44))).collect(), // the DMA list: Close / Reset, then the copy methods (XDefiant calls #12 with // CopyTextureRegion's arguments): 11–14 = PC 15–18 (CopyBufferRegion, CopyTextureRegion, // CopyResource, CopyTiles); what follows is not known yet (`console_extensions`) @@ -961,6 +961,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { // the title's calls from #14 on: Signal / Wait / … / SignalX / PresentX at the slots of // its runtime's layout (`queue_dispatch`) Kind::CommandQueue => QUEUE_SLOTS.iter().enumerate().map(|(k, &f)| (QUEUE_FIRST + k, f as usize)).collect(), + Kind::CommandAllocator => vec![(9, alloc_set_allocation_callback_x as usize)], Kind::DmaList => { use super::list_x as l; vec![(9, l::dma_close_x as usize), (10, l::reset_x as usize), (11, l::copy_buffer_region_x as usize), (12, l::copy_texture_region_x as usize), (13, l::copy_resource_x as usize)] @@ -1028,6 +1029,14 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (90, l::write32_bottom_of_shader_x as usize), (93, l::kickoff_x as usize), (94, l::set_depth_bias_x as usize), + (73, l::set_pipeline_flag_x as usize), + (99, l::set_clear_batch_hint_x as usize), + (124, l::rs_set_shading_rate_x as usize), + (125, l::rs_set_shading_rate_image_x as usize), + // Flush{Gpu,Shader}CacheRangeX are called before device #133 sets QUEUE_SHIFTED + (131, l::flush_gpu_cache_range_x as usize), + (132, l::flush_shader_cache_range_x as usize), + (140, l::set_quad_sample_mask_x as usize), // console compute/BVH builder extensions (`XboxBvhBuilder.dll`) (146, l::uav_barrier_x as usize), (148, b::allocate_upload_memory as usize), @@ -1617,6 +1626,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::sparse::forget_buffer(this as usize); super::vram::forget(this as usize); super::title_textures::forget(this as usize); + super::list_x::forget_target(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { @@ -1945,7 +1955,8 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } - f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu) + f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::list_x::note_dsv_handle(cpu as usize, res as usize, copy.as_ref()); } /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made @@ -2393,7 +2404,14 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro let mut clear_buf = [0u8; 24]; let clear = super::device_x::pc_clear(clear as *const c_void, &mut clear_buf) as usize; // console-only state bits (e.g. 0x100000 on a display target) are not the PC's; a depth - // buffer the PC description took ALLOW_UNORDERED_ACCESS from does not start as a UAV + // buffer the PC description took ALLOW_UNORDERED_ACCESS from does not start as a UAV; + // strip CREATE_NOT_ZEROED only for RT/DS targets and indirect buffers so streaming buffers + // and ordinary textures skip driver zero-initialization + let flags = if should_strip_not_zeroed_resource(desc, state) { + strip_not_zeroed_heap_flag(flags as i32) as usize + } else { + flags + }; let st = pc_full.as_ref().map_or(state as u32 & PC_RESOURCE_STATES, |d| super::device_x::pc_initial_state(u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()), state as u32)); let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv); if hr < 0 { @@ -2471,6 +2489,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("SetPipelineState", cl_set_pipeline_state as usize), ("OMSetRenderTargets", cl_om_set_render_targets as usize), ("ClearRenderTargetView", cl_clear_rtv as usize), + ("DiscardResource", cl_discard_resource as usize), ("ExecuteIndirect", cl_execute_indirect as usize), ]), Kind::DmaList => v.extend_from_slice(&[ @@ -2787,13 +2806,28 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v return hr; } let hr = dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv); - if hr >= 0 || desc == 0 || !crate::gpu::shader::readable(desc, 0x38) { + if hr >= 0 { + if !ppv.is_null() && !(*ppv).is_null() { + if let Some(res) = ID3D12Resource::from_raw_borrowed(&*ppv) { + let rd = res.GetDesc(); + super::list_x::note_uninit_target_if_rt_ds(*ppv as usize, &rd, clear as *const c_void, false); + } + } + return hr; + } + if desc == 0 || !crate::gpu::shader::readable(desc, 0x38) { return hr; } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = super::device_x::pc_resource_desc(&x); let st = super::device_x::pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state as u32); let hr2 = dev_create_placed_resource(this, heap, offset, d.as_ptr() as usize, st as usize, clear, riid, ppv); + if hr2 >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(res) = ID3D12Resource::from_raw_borrowed(&*ppv) { + let rd = res.GetDesc(); + super::list_x::note_uninit_target_if_rt_ds(*ppv as usize, &rd, clear as *const c_void, false); + } + } let heap_desc = pc_heap_desc(heap); let pc_size = pc_allocation_size(this, &d); // A texture the title placed by the console's size (`get_resource_allocation_info_x` @@ -2930,10 +2964,43 @@ pub(super) unsafe extern "system" fn dev_create_reserved_resource1(this: *mut c_ } creator!(dev_create_heap_pc, "CreateHeap", Kind::Heap, [a1]); +fn strip_not_zeroed_heap_flag(flags: i32) -> i32 { + flags & !D3D12_HEAP_FLAG_CREATE_NOT_ZEROED.0 +} + +unsafe fn should_strip_not_zeroed_resource(desc: usize, state: usize) -> bool { + if desc == 0 || !crate::gpu::shader::readable(desc, std::mem::size_of::()) { + return false; + } + let rd = std::ptr::read_unaligned(desc as *const D3D12_RESOURCE_DESC); + let rt_ds = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0; + if (rd.Flags.0 & rt_ds) != 0 { + return true; + } + rd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && (state as u32 & D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT.0 as u32) != 0 +} + +fn heap_allows_only_rt_ds(flags: i32) -> bool { + let only_rt_ds = D3D12_HEAP_FLAG_DENY_BUFFERS.0 | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES.0; + (flags & only_rt_ds) == only_rt_ds +} + +unsafe fn sanitize_heap_desc(desc: usize) -> Option { + if desc == 0 || !crate::gpu::shader::readable(desc, std::mem::size_of::()) { + return None; + } + let mut d = std::ptr::read_unaligned(desc as *const D3D12_HEAP_DESC); + if heap_allows_only_rt_ds(d.Flags.0) { + d.Flags = D3D12_HEAP_FLAGS(strip_not_zeroed_heap_flag(d.Flags.0)); + } + Some(d) +} + /// D3D12_HEAP_FLAGS the PC knows: SHARED 0x1, DENY_BUFFERS 0x4, ALLOW_DISPLAY 0x8, /// SHARED_CROSS_ADAPTER 0x20, DENY_RT_DS_TEXTURES 0x40, DENY_NON_RT_DS_TEXTURES 0x80, then -/// 0x100 … 0x2000 (HARDWARE_PROTECTED … TOOLS_USE_MANUAL_WRITE_TRACKING); 0x2 and 0x10 are -/// the console's (Fortnite: 0xC2) +/// 0x100 … 0x2000 (HARDWARE_PROTECTED … TOOLS_USE_MANUAL_WRITE_TRACKING, including +/// CREATE_NOT_ZEROED 0x1000 so streaming heaps skip GPU zero-fill); 0x2 and 0x10 are the +/// console's (Fortnite: 0xC2) const PC_HEAP_FLAGS: u32 = 0x3FED; /// CreateHeap(desc, riid, heap): a console description the PC refuses (console flags in the @@ -2941,7 +3008,9 @@ const PC_HEAP_FLAGS: u32 = 0x3FED; /// field atlas heap) is made the PC's way: known flags only, the alignment the PC has that /// covers it, an unknown type as DEFAULT. Logged with the console's values. pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let hr = dev_create_heap_pc(this, desc, riid, ppv); + let mut clean = sanitize_heap_desc(desc); + let clean_ptr = clean.as_mut().map_or(desc, |d| d as *mut _ as usize); + let hr = dev_create_heap_pc(this, clean_ptr, riid, ppv); if hr >= 0 { note_heap_uma(desc, ppv); } @@ -2950,7 +3019,11 @@ pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: us } let mut d: D3D12_HEAP_DESC = std::ptr::read_unaligned(desc as *const D3D12_HEAP_DESC); let orig = (d.SizeInBytes, d.Properties.Type.0, d.Alignment, d.Flags.0); - d.Flags = D3D12_HEAP_FLAGS(d.Flags.0 & PC_HEAP_FLAGS as i32); + let mut clean_flags = d.Flags.0 & PC_HEAP_FLAGS as i32; + if heap_allows_only_rt_ds(clean_flags) { + clean_flags = strip_not_zeroed_heap_flag(clean_flags); + } + d.Flags = D3D12_HEAP_FLAGS(clean_flags); d.Alignment = if d.Alignment <= 0x1_0000 { 0 } else { D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT as u64 }; if !(1..=5).contains(&d.Properties.Type.0) { d.Properties = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; @@ -2972,7 +3045,9 @@ pub(super) unsafe extern "system" fn dev_create_heap(this: *mut c_void, desc: us creator!(dev_create_heap1_pc, "CreateHeap1", Kind::Heap, [a1, a2]); pub(super) unsafe extern "system" fn dev_create_heap1(this: *mut c_void, desc: usize, session: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let hr = dev_create_heap1_pc(this, desc, session, riid, ppv); + let mut clean = sanitize_heap_desc(desc); + let clean_ptr = clean.as_mut().map_or(desc, |d| d as *mut _ as usize); + let hr = dev_create_heap1_pc(this, clean_ptr, session, riid, ppv); if hr >= 0 { note_heap_uma(desc, ppv); } @@ -3560,6 +3635,35 @@ fn big_compile_commit_free() -> bool { unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= 3 << 30 } } +/// Concurrent cold background driver compiles: keeps at most `compile_threads - 2` (minimum 1) +/// cold compiles running simultaneously so two worker lanes remain open for warm disk-cache +/// loads and `wanted` foreground shaders. +fn cold_compiles() -> &'static Slots { + static COLD_COMPILES: OnceLock = OnceLock::new(); + COLD_COMPILES.get_or_init(|| Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most: crate::gpu::recomp::dxc::compile_threads().saturating_sub(2).max(1), + }) +} + +/// Before a cold driver compile in the background: wait for a cold slot unless a title thread +/// wants this pipeline (`wanted`), in which case it proceeds immediately without taking a slot. +fn cold_compile_turn(slots: &'static Slots, wanted: impl Fn() -> bool) -> Option { + const LOOK: std::time::Duration = std::time::Duration::from_millis(25); + let mut n = slots.n.lock().unwrap(); + loop { + if wanted() { + return None; + } + if *n < slots.most { + *n += 1; + return Some(SlotGuard(slots)); + } + n = slots.cv.wait_timeout(n, LOOK).unwrap().0; + } +} + #[cfg(test)] mod big_compile_tests { use super::*; @@ -3604,6 +3708,85 @@ mod big_compile_tests { assert!(t.join().unwrap(), "the next one's turn"); assert_eq!(*S.n.lock().unwrap(), 0); } + + #[test] + fn cold_compile_turn_caps_unwanted_and_lets_wanted_bypass() { + static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2 }; + let s1 = cold_compile_turn(&S, || false).expect("slot 1"); + let s2 = cold_compile_turn(&S, || false).expect("slot 2"); + assert_eq!(*S.n.lock().unwrap(), 2); + + static WANTED: AtomicBool = AtomicBool::new(false); + let t_wanted = std::thread::spawn(|| cold_compile_turn(&S, || WANTED.load(Ordering::Acquire)).is_none()); + let t_queued = std::thread::spawn(|| cold_compile_turn(&S, || false).is_some()); + std::thread::sleep(Duration::from_millis(80)); + assert!(!t_wanted.is_finished(), "unwanted cold build waits while slots are full"); + assert!(!t_queued.is_finished(), "queued unwanted cold build waits while slots are full"); + + WANTED.store(true, Ordering::Release); + assert!(t_wanted.join().unwrap(), "wanted cold build bypasses slot limit"); + assert!(!t_queued.is_finished(), "still-unwanted build remains queued"); + + drop(s1); + assert!(t_queued.join().unwrap(), "dropping a slot wakes queued cold build"); + drop(s2); + assert_eq!(*S.n.lock().unwrap(), 0); + } + + #[test] + fn strip_not_zeroed_heap_flag_targets_only_rt_ds_and_indirect() { + let not_zeroed = D3D12_HEAP_FLAG_CREATE_NOT_ZEROED.0; + let other = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES.0 | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES.0 | 0x2000; + assert_eq!(strip_not_zeroed_heap_flag(not_zeroed | other), other); + assert_ne!(PC_HEAP_FLAGS & not_zeroed as u32, 0, "PC_HEAP_FLAGS preserves NOT_ZEROED for non-RT/DS heaps"); + + unsafe { + // Heaps for streaming buffers or non-RT/DS textures retain CREATE_NOT_ZEROED; + // RT/DS-only heaps strip CREATE_NOT_ZEROED. + let mut hd = D3D12_HEAP_DESC { + SizeInBytes: 0x10_0000, + Flags: D3D12_HEAP_FLAGS(not_zeroed | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES.0), + ..Default::default() + }; + assert_ne!(sanitize_heap_desc(&hd as *const _ as usize).unwrap().Flags.0 & not_zeroed, 0); + hd.Flags = D3D12_HEAP_FLAGS(not_zeroed | D3D12_HEAP_FLAG_DENY_BUFFERS.0 | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES.0); + assert_eq!(sanitize_heap_desc(&hd as *const _ as usize).unwrap().Flags.0 & not_zeroed, 0); + + // Committed resource gating: keep NOT_ZEROED for ordinary textures/streaming buffers, + // strip for RT/DS targets and indirect argument buffers. + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(!should_strip_not_zeroed_resource(&tex as *const _ as usize, D3D12_RESOURCE_STATE_COPY_DEST.0 as usize)); + + let rt = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..tex }; + assert!(should_strip_not_zeroed_resource(&rt as *const _ as usize, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as usize)); + + let ds = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, ..tex }; + assert!(should_strip_not_zeroed_resource(&ds as *const _ as usize, D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as usize)); + + let buf = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(!should_strip_not_zeroed_resource(&buf as *const _ as usize, D3D12_RESOURCE_STATE_COPY_DEST.0 as usize)); + assert!(should_strip_not_zeroed_resource( + &buf as *const _ as usize, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT.0 as usize + )); + } + } } unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option> { @@ -3641,46 +3824,81 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); - let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); - copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - copy.CS = bytecode(&dxil); - copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + let flags = d.Flags.0; + let rs_raw = rs as usize; + let run_pso = |cached_blob: Option<&[u8]>| -> HRESULT { + let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); + copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + copy.CS = bytecode(&dxil); + copy.CachedPSO = match cached_blob { + Some(b) => D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }, + None => D3D12_CACHED_PIPELINE_STATE::default(), + }; + finish_pso(this, f, © as *const _ as *const c_void, riid, ppv) + }; // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. - let key = compute_blob_key(&dxil, rs as usize, copy.Flags.0); - let mut cached = compute_blob(key); + let key = compute_blob_key(&dxil, rs_raw, flags); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path(&dxil, copy.Flags.0); - let from_disk = cached.is_none(); - if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); - } - if let Some(b) = &cached { - copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; - } - // 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(|| big_compile_turn(&BIG_COMPILES, big_compile_commit_free, super::pso_async::build_is_wanted)); - let started = std::time::Instant::now(); - let mut hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); - if hr < 0 && cached.is_some() { - // a blob the driver does not take (another root signature at the same address…): compiled - forget_compute_blob(key); - if from_disk { - driver_cache::note(false, disk.as_deref()); - } - copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); - } - let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; - if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { - driver_cache::keep(p, &b, started.elapsed()); - } - } else if reused && from_disk { - driver_cache::note(true, None); - } + let disk = driver_cache::path(&dxil, flags); + let lookup = || -> Option<(std::sync::Arc>, bool)> { + if let Some(b) = compute_blob(key) { + return Some((b, false)); + } + disk.as_deref().and_then(driver_cache::load).map(|b| (std::sync::Arc::new(b), true)) + }; + let is_bg_pso_worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let caller_wanted = super::pso_async::build_is_wanted() || !std::thread::current().name().is_some_and(|n| n.starts_with("xcl-")); + let Ok((hr, took, reused)) = coalesce_compute_build( + compute_flights(), + key, + caller_wanted, + lookup, + |flight| -> Result<(HRESULT, std::time::Duration, bool), ()> { + // in the background, cap cold compiles so warm disk-cache loads and wanted builds keep + // worker lanes open; big compiles still run one at a time within commit headroom + let is_wanted = || super::pso_async::build_is_wanted() || flight.is_wanted(); + let _cold_slot = is_bg_pso_worker.then(|| cold_compile_turn(cold_compiles(), is_wanted)); + let _big_slot = (big && is_bg_pso_worker).then(|| big_compile_turn(&BIG_COMPILES, big_compile_commit_free, is_wanted)); + let started = std::time::Instant::now(); + let hr = run_pso(None); + let took = started.elapsed(); + if hr >= 0 { + keep_compute_blob(key, *ppv, dxil.len(), took); + if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { + driver_cache::keep(p, &b, took); + } + } + Ok((hr, took, false)) + }, + |(b, from_disk)| -> Result<(HRESULT, std::time::Duration, bool), ()> { + let started = std::time::Instant::now(); + let mut hr = run_pso(Some(&b)); + if hr < 0 { + // a blob the driver does not take (another root signature at the same address…): compiled + forget_compute_blob(key); + if from_disk { + driver_cache::note(false, disk.as_deref()); + } + let retry_started = std::time::Instant::now(); + hr = run_pso(None); + let took = retry_started.elapsed(); + if hr >= 0 { + keep_compute_blob(key, *ppv, dxil.len(), took); + if let (Some(p), Some(blob)) = (disk.as_deref(), compute_blob(key)) { + driver_cache::keep(p, &blob, took); + } + } + return Ok((hr, took, false)); + } + if from_disk { + driver_cache::note(true, None); + } + Ok((hr, started.elapsed(), true)) + }, + ) else { + return Some(Err(())); + }; if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); return Some(Err(())); @@ -3694,7 +3912,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", dxil.len(), - started.elapsed().as_millis(), + took.as_millis(), if reused { ", the driver's blob of an earlier build" } else { "" } ); Some(Ok(hr)) @@ -3715,7 +3933,7 @@ pub(crate) mod driver_cache { use std::sync::atomic::{AtomicU64, Ordering}; /// builds shorter than this are not worth a file - const KEEP: std::time::Duration = std::time::Duration::from_millis(250); + pub(super) const KEEP: std::time::Duration = std::time::Duration::from_millis(250); static HITS: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); @@ -3879,9 +4097,74 @@ pub(crate) mod driver_cache { /// by (DXIL hash, root signature, flags), up to `COMPUTE_BLOBS_MAX` bytes in all. static COMPUTE_BLOBS: Mutex>>, usize)>> = Mutex::new(None); const COMPUTE_BLOBS_MAX: usize = 512 << 20; -/// smaller programs compile in milliseconds: not kept +/// smaller programs compile in milliseconds: not kept unless the build itself was slow (`driver_cache::KEEP`) const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; +/// Per-key in-flight state for cold driver compute PSO compilation so duplicate keys wait on +/// the leader's driver blob instead of compiling concurrently, while distinct keys run in parallel. +#[derive(Default)] +struct ComputeFlight { + mu: Mutex<()>, + wanted: AtomicUsize, +} + +impl ComputeFlight { + fn is_wanted(&self) -> bool { + self.wanted.load(Ordering::Acquire) > 0 + } +} + +struct FlightWantedGuard<'a>(&'a ComputeFlight); + +impl Drop for FlightWantedGuard<'_> { + fn drop(&mut self) { + self.0.wanted.fetch_sub(1, Ordering::AcqRel); + } +} + +fn compute_flights() -> &'static Mutex>> { + static FLIGHTS: OnceLock>>> = OnceLock::new(); + FLIGHTS.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn compute_pso_flight( + flights: &Mutex>>, + key: (u64, usize, i32), +) -> std::sync::Arc { + let mut g = flights.lock().unwrap(); + g.retain(|_, v| v.strong_count() != 0); + if let Some(flight) = g.get(&key).and_then(std::sync::Weak::upgrade) { + return flight; + } + let flight = std::sync::Arc::new(ComputeFlight::default()); + g.insert(key, std::sync::Arc::downgrade(&flight)); + flight +} + +fn coalesce_compute_build( + flights: &Mutex>>, + key: (u64, usize, i32), + caller_wanted: bool, + mut lookup: impl FnMut() -> Option, + build_cold: impl FnOnce(&ComputeFlight) -> Result, + build_cached: impl FnOnce(B) -> Result, +) -> Result { + if let Some(b) = lookup() { + return build_cached(b); + } + let flight = compute_pso_flight(flights, key); + let _wanted_guard = caller_wanted.then(|| { + flight.wanted.fetch_add(1, Ordering::AcqRel); + FlightWantedGuard(&flight) + }); + let guard = flight.mu.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(b) = lookup() { + drop(guard); + return build_cached(b); + } + build_cold(&flight) +} + fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -3925,11 +4208,140 @@ mod compute_blob_tests { assert!(super::compute_blob(key).is_none()); assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); } + + #[test] + fn concurrent_cold_compute_builds_coalesce_same_key_and_parallelize_different_keys() { + use std::collections::HashMap; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Barrier, Mutex}; + use std::time::Duration; + + let flights = Mutex::new(HashMap::new()); + let blobs: Mutex>> = Mutex::new(HashMap::new()); + let cold_calls = AtomicUsize::new(0); + let cached_calls = AtomicUsize::new(0); + let same_key = (0x1111u64, 0x2000usize, 0i32); + + // Four concurrent callers for the same cold key: only one cold compile runs; + // the remaining three pick up the leader's cached blob. + let start_same = Barrier::new(4); + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + start_same.wait(); + let res = super::coalesce_compute_build( + &flights, + same_key, + false, + || blobs.lock().unwrap().get(&same_key).cloned(), + |_| -> Result { + cold_calls.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(40)); + blobs.lock().unwrap().insert(same_key, vec![9, 9, 9]); + Ok(1) + }, + |b| -> Result { + assert_eq!(b, vec![9, 9, 9]); + cached_calls.fetch_add(1, Ordering::SeqCst); + Ok(2) + }, + ); + assert!(res.is_ok()); + }); + } + }); + assert_eq!(cold_calls.load(Ordering::SeqCst), 1); + assert_eq!(cached_calls.load(Ordering::SeqCst), 3); + + // Two distinct cold keys must proceed in parallel (rendezvous barrier would deadlock otherwise). + let parallel = Barrier::new(2); + let k1 = (0xAAAAu64, 0x2000usize, 0i32); + let k2 = (0xBBBBu64, 0x2000usize, 0i32); + std::thread::scope(|s| { + let t1 = s.spawn(|| { + super::coalesce_compute_build( + &flights, + k1, + false, + || Option::>::None, + |_| -> Result { + parallel.wait(); + Ok(11) + }, + |_| Ok(0), + ) + }); + let t2 = s.spawn(|| { + super::coalesce_compute_build( + &flights, + k2, + false, + || Option::>::None, + |_| -> Result { + parallel.wait(); + Ok(22) + }, + |_| Ok(0), + ) + }); + assert_eq!(t1.join().unwrap(), Ok(11)); + assert_eq!(t2.join().unwrap(), Ok(22)); + }); + } + + #[test] + fn compute_flight_propagates_wanted_to_leader() { + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{mpsc, Mutex}; + use std::time::{Duration, Instant}; + + let flights = Mutex::new(HashMap::new()); + let key = (0xCCCCu64, 0x3000usize, 0i32); + let (started_tx, started_rx) = mpsc::channel(); + let leader_done = AtomicBool::new(false); + + std::thread::scope(|s| { + let leader = s.spawn(|| { + super::coalesce_compute_build( + &flights, + key, + false, + || Option::>::None, + |flight| -> Result { + assert!(!flight.is_wanted()); + started_tx.send(()).unwrap(); + let t0 = Instant::now(); + while !flight.is_wanted() && t0.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(1)); + } + let saw_wanted = flight.is_wanted(); + leader_done.store(true, Ordering::Release); + Ok(saw_wanted) + }, + |_| Ok(false), + ) + }); + started_rx.recv().unwrap(); + let follower = s.spawn(|| { + super::coalesce_compute_build( + &flights, + key, + true, + || leader_done.load(Ordering::Acquire).then(|| vec![1]), + |_| -> Result { Ok(false) }, + |_| Ok(true), + ) + }); + assert_eq!(leader.join().unwrap(), Ok(true)); + assert_eq!(follower.join().unwrap(), Ok(true)); + }); + } } /// The driver's blob of the PSO just built (adopted: its PC `GetCachedBlob` through `orig_fn`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || !is_adopted(pso) || compute_blob(key).is_some() { +unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize, took: std::time::Duration) { + if (dxil_len < COMPUTE_BLOB_MIN_DXIL && took < driver_cache::KEEP) || pso.is_null() || !is_adopted(pso) || compute_blob(key).is_some() { return; } type GetBlob = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT; @@ -5039,6 +5451,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); + super::list_x::note_rtv_handle(handle, res as usize, copy.as_ref()); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 12 { @@ -5061,7 +5474,10 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co super::present::note_use(r, super::present::USE_CLEAR); } } - f(this, rtv, color, n, rects) + f(this, rtv, color, n, rects); + if n == 0 { + super::list_x::mark_rtv_initialized(rtv); + } } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { @@ -5124,6 +5540,30 @@ unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u f(this, icount, inst, si, bv, sinst); } +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn cl_discard_resource(this: *mut c_void, res: *mut c_void, region: *const D3D12_DISCARD_REGION) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DISCARD_REGION); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DiscardResource"))); + f(this, res, region); + if res.is_null() { + return; + } + if region.is_null() { + super::list_x::mark_target_initialized(res as usize, None); + } else if crate::gpu::shader::readable(region as usize, std::mem::size_of::()) { + let r = &*region; + if r.NumRects == 0 { + if r.NumSubresources > 256 { + super::list_x::mark_target_initialized(res as usize, None); + } else { + for sub in r.FirstSubresource..r.FirstSubresource.saturating_add(r.NumSubresources) { + super::list_x::mark_target_initialized(res as usize, Some(sub)); + } + } + } + } +} + #[allow(clippy::too_many_arguments)] unsafe extern "system" fn cl_execute_indirect( this: *mut c_void, @@ -5134,7 +5574,9 @@ unsafe extern "system" fn cl_execute_indirect( cnt_buf: *mut c_void, cnt_off: u64, ) { - super::list_x::prepare_draw(this); + if !super::bind::is_compute_signature(sig as usize) { + super::list_x::prepare_draw(this); + } type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteIndirect"))); f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); @@ -5159,6 +5601,19 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { n } +/// command allocator #9 SetAllocationCallbackX(callback, context): PC manages command allocator +/// memory internally, so log once and succeed without retaining unused callback state. +unsafe extern "system" fn alloc_set_allocation_callback_x(this: *mut c_void, callback: usize, context: usize) -> HRESULT { + if this.is_null() { + return E_INVALIDARG; + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: ID3D12CommandAllocator::SetAllocationCallbackX (callback {callback:#x}, context {context:#x})"); + }); + S_OK +} + unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); @@ -5226,7 +5681,34 @@ pub(super) static QUEUE_SHIFTED: AtomicBool = AtomicBool::new(false); static QUEUE_OLDER: AtomicBool = AtomicBool::new(false); /// command list slots of the newer layout → the older layout's slot of the same method -const NEWER_LIST_SLOTS: [(usize, usize); 21] = [(61, 59), (62, 60), (63, 61), (64, 62), (65, 63), (70, 68), (71, 69), (72, 70), (73, 71), (74, 72), (80, 78), (83, 81), (85, 83), (86, 84), (87, 85), (90, 88), (91, 89), (92, 90), (95, 93), (96, 94), (139, 10)]; +const NEWER_LIST_SLOTS: [(usize, usize); 26] = [ + (61, 59), + (62, 60), + (63, 61), + (64, 62), + (65, 63), + (70, 68), + (71, 69), + (72, 70), + (73, 71), + (74, 72), + (75, 73), + (80, 78), + (83, 81), + (85, 83), + (86, 84), + (87, 85), + (90, 88), + (91, 89), + (92, 90), + (95, 93), + (96, 94), + (101, 99), + (126, 124), + (127, 125), + (139, 10), + (142, 140), +]; /// The title called device method `slot`, which only runtimes with the newer layouts have (a retail game /// records its first lists before any queue call could tell). @@ -5245,8 +5727,8 @@ fn is_fence(p: usize) -> bool { const QUEUE_FIRST: usize = 14; /// A title's call of queue slot `slot` (arguments as integers; Signal / Wait / SignalX / -/// PresentX / GetTimestampFrequency / GetClockCalibration / GetDesc all fit). -unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { +/// UpdatePageMappingsX / PresentX / GetTimestampFrequency / GetClockCalibration / GetDesc all fit). +unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) -> usize { const PC_SIGNAL: usize = 14; const PC_WAIT: usize = 15; const PC_TIMESTAMP_FREQUENCY: usize = 16; @@ -5309,6 +5791,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + 29 => super::device_x::update_page_mappings_x(this, a1 as u32, a2 as *const u8, a3 as u64, a4 as u32, a5 as u32) as u32 as usize, 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at @@ -5345,9 +5828,9 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a macro_rules! queue_slots { ($($slot:literal),*) => { /// the title's entry for each queue slot from `QUEUE_FIRST` - static QUEUE_SLOTS: &[unsafe extern "system" fn(*mut c_void, usize, usize, usize, usize) -> usize] = &[$({ - unsafe extern "system" fn f(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { - queue_dispatch($slot, this, a1, a2, a3, a4) + static QUEUE_SLOTS: &[unsafe extern "system" fn(*mut c_void, usize, usize, usize, usize, usize) -> usize] = &[$({ + unsafe extern "system" fn f(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) -> usize { + queue_dispatch($slot, this, a1, a2, a3, a4, a5) } f }),*]; @@ -5948,6 +6431,8 @@ mod readback_routing_tests { mod queue_tests { use super::*; + static QUEUE_TEST_LOCK: Mutex<()> = Mutex::new(()); + // a fake adopted queue: the extension vtable's word before slot 0 points at the PC table unsafe extern "system" fn get_desc(_: *mut c_void, out: usize) -> usize { let d = [1u32, 2, 3, 4]; @@ -5962,6 +6447,7 @@ mod queue_tests { /// layout) it is GetDesc with all 16. #[test] fn queue_slot_18_before_the_layout_is_known_writes_8_bytes() { + let _guard = QUEUE_TEST_LOCK.lock().unwrap(); let mut pc = [0usize; 32]; pc[14] = signal as usize; pc[18] = get_desc as usize; @@ -5974,19 +6460,79 @@ mod queue_tests { QUEUE_OLDER.store(false, Ordering::Release); unsafe { let mut out = [0xAAAA_AAAAu32; 4]; - let r = queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0); + let r = queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0, 0); assert_eq!(r, out.as_ptr() as usize); assert_eq!(out, [1, 2, 0xAAAA_AAAA, 0xAAAA_AAAA], "only the first 8 bytes"); FENCES.write().unwrap().push(fence); - queue_dispatch(14, this, fence, 1, 0, 0); + queue_dispatch(14, this, fence, 1, 0, 0, 0); FENCES.write().unwrap().retain(|&f| f != fence); assert!(QUEUE_OLDER.load(Ordering::Acquire) && !QUEUE_SHIFTED.load(Ordering::Acquire)); let mut out = [0xAAAA_AAAAu32; 4]; - queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0); + queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0, 0); assert_eq!(out, [1, 2, 3, 4], "older layout: the whole description"); } QUEUE_OLDER.store(false, Ordering::Release); } + + #[test] + fn queue_slot_31_on_newer_layout_dispatches_update_page_mappings() { + #[repr(C)] + struct Range { + op: u32, + idx: u32, + count: u32, + } + #[repr(C)] + struct Mapping { + dest_va: u64, + num_ranges: u32, + _pad: u32, + ranges: *const Range, + } + let _guard = QUEUE_TEST_LOCK.lock().unwrap(); + let prev_shifted = QUEUE_SHIFTED.swap(true, Ordering::AcqRel); + let prev_older = QUEUE_OLDER.swap(false, Ordering::AcqRel); + let mut obj = [0usize]; + let this = obj.as_mut_ptr() as *mut c_void; + let pool_base = 0x7_0000_0000u64; + let dest_base = 0x8_0000_0000u64; + let ranges = [Range { op: 1, idx: 2, count: 1 }]; + let mapping = Mapping { dest_va: dest_base, num_ranges: 1, _pad: 0, ranges: ranges.as_ptr() }; + unsafe { + let mut pool_id = u32::MAX; + assert_eq!(super::super::device_x::register_page_pool_x(std::ptr::null_mut(), pool_base, 8, &mut pool_id), S_OK); + let hr = queue_dispatch(31, this, 1, &mapping as *const _ as usize, pool_base as usize, 8, 0); + assert_eq!(hr as i32, S_OK); + let bad_hr = queue_dispatch(31, this, 1, 0, pool_base as usize, 8, 0); + assert_eq!(bad_hr as i32, E_INVALIDARG); + assert_eq!(super::super::device_x::unregister_page_pool_x(std::ptr::null_mut(), pool_id as u64), S_OK); + } + QUEUE_SHIFTED.store(prev_shifted, Ordering::Release); + QUEUE_OLDER.store(prev_older, Ordering::Release); + } + + #[test] + fn allocator_slot_9_validates_this_and_returns_s_ok() { + let slots = console_slots(Kind::CommandAllocator); + assert_eq!(slots, vec![(9, alloc_set_allocation_callback_x as usize)]); + unsafe { + assert_eq!(alloc_set_allocation_callback_x(std::ptr::null_mut(), 0x1234, 0x5678), E_INVALIDARG); + let this = 0xDEAD_BEEFusize as *mut c_void; + assert_eq!(alloc_set_allocation_callback_x(this, 0x1234, 0x5678), S_OK); + assert_eq!(alloc_set_allocation_callback_x(this, 0, 0), S_OK); + } + } + + #[test] + fn newer_list_slots_cover_shifted_console_methods() { + let slots = console_slots(Kind::CommandList); + for older in [73usize, 99, 124, 125, 131, 132, 140] { + assert!(slots.iter().any(|&(s, _)| s == older), "missing older slot {older}"); + } + for pair in [(75usize, 73usize), (101, 99), (126, 124), (127, 125), (142, 140)] { + assert!(NEWER_LIST_SLOTS.contains(&pair), "missing NEWER_LIST_SLOTS {pair:?}"); + } + } } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 040d78a0c..1b86f854e 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -64,8 +64,8 @@ impl Arenas { /// Where a placement of `bytes` at `va` (alignment `align`) goes: the newest arena holding /// it at an offset `align` allows, else a new arena of its size, `make(size, align)`. - /// (heap, offset, arena id); None: no heap. - fn take(&mut self, va: usize, bytes: usize, align: usize, now: std::time::Instant, make: impl FnOnce(usize, usize) -> Option) -> Option<(H, usize, u64)> { + /// `(heap, offset, arena id, aliased)`; None: no heap. + fn take(&mut self, va: usize, bytes: usize, align: usize, now: std::time::Instant, make: impl FnOnce(usize, usize) -> Option) -> Option<(H, usize, u64, bool)> { self.sweep(now); let fits = |a: &Arena| a.align >= align && a.base <= va && va + bytes <= a.base + a.size && (va - a.base) % align == 0; let i = match self.list.iter().rposition(fits) { @@ -81,7 +81,8 @@ impl Arenas { let a = &mut self.list[i]; a.users += 1; a.idle_since = None; - Some((a.heap.clone(), va - a.base, a.id)) + let aliased = a.users > 1; + Some((a.heap.clone(), va - a.base, a.id, aliased)) } /// A resource in arena `id` released. @@ -391,13 +392,14 @@ impl Pages { } /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>, bool)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); + let mut aliased = false; for i in 0..total as usize { let tile = if i < own { let a = first + i * PAGE; @@ -405,6 +407,9 @@ impl Pages { Some(p) => { p.users += 1; p.idle_since = None; + if p.users > 1 { + aliased = true; + } Some(p.tile) } None => self.take_tile(dev).inspect(|&t| { @@ -421,6 +426,9 @@ impl Pages { Some(p) => { p.users += 1; p.idle_since = None; + if p.users > 1 { + aliased = true; + } Some(p.tile) } None => self.take_tile(dev).inspect(|&t| { @@ -440,7 +448,7 @@ impl Pages { return None; } self.map(res, &tiles); - Some((used, used_extra)) + Some((used, used_extra, aliased)) } } @@ -547,7 +555,7 @@ unsafe fn place_on_pages( let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) else { + let Some((used, used_extra, aliased)) = pages.bind(dev, res, va, console_bytes, total) else { drop(g); drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); @@ -556,6 +564,7 @@ unsafe fn place_on_pages( pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); drop(g); PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + super::list_x::note_uninit_target_if_rt_ds(raw as usize, desc, clear, aliased); Some(hr) } @@ -596,7 +605,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if mapped { return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let Some((used, used_extra, aliased)) = pages.bind(&dev, res, va, console_bytes, total) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { @@ -604,6 +613,11 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.used_extra = used_extra; t.mapped = true; } + drop(g); + if aliased { + let desc = res.GetDesc(); + super::list_x::note_uninit_target_if_rt_ds(key, &desc, std::ptr::null(), true); + } true } @@ -701,7 +715,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st } let align = (info.Alignment as usize).max(PAGE); let now = std::time::Instant::now(); - let (heap, offset, id) = ARENAS.lock().unwrap().take(va, info.SizeInBytes as usize, align, now, |size, align| arena_heap(dev, va, size, align))?; + let (heap, offset, id, aliased) = ARENAS.lock().unwrap().take(va, info.SizeInBytes as usize, align, now, |size, align| arena_heap(dev, va, size, align))?; let hr = super::real::dev_create_placed_resource(this, heap.as_raw() as usize, offset, desc as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { ARENAS.lock().unwrap().release(id, now); @@ -709,6 +723,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); ARENA_OF.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(*ppv as usize, id); + super::list_x::note_uninit_target_if_rt_ds(*ppv as usize, desc, clear, aliased); Some(hr) } diff --git a/crates/xcl/src/hle/netoff.rs b/crates/xcl/src/hle/netoff.rs index 8071b04c6..d95c8710c 100644 --- a/crates/xcl/src/hle/netoff.rs +++ b/crates/xcl/src/hle/netoff.rs @@ -15,7 +15,7 @@ //! original through the hook's trampoline. use std::ffi::c_void; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use windows_sys::Win32::Foundation::SetLastError; @@ -118,6 +118,10 @@ static O_GETADDRINFO: AtomicUsize = AtomicUsize::new(0); static O_GETADDRINFO_W: AtomicUsize = AtomicUsize::new(0); /// trampolines of hooks whose original is never called static O_UNUSED: [AtomicUsize; 16] = [const { AtomicUsize::new(0) }; 16]; +/// Original `winhttp.dll!WinHttpConnect` trampoline (shared by telemetry block and `XCL_NETWORK=0`). +static O_WINHTTP_CONNECT: AtomicUsize = AtomicUsize::new(0); +/// When true (`XCL_NETWORK=0`), `winhttp_connect` blocks every host instead of only crash telemetry. +static BLOCK_ALL: AtomicBool = AtomicBool::new(false); unsafe fn orig_connect(s: usize, name: *const u8, len: i32) -> i32 { match O_CONNECT.load(Ordering::Acquire) { @@ -147,16 +151,90 @@ unsafe fn orig_getaddrinfo_w(node: *const u16, service: *const u16, hints: *cons } } +/// Return true when `raw` targets Backtrace crash telemetry (`backtrace.io` or `*.backtrace.io`), +/// regardless of scheme, userinfo, port, path/query, trailing dot, or casing. +pub fn is_blocked_telemetry_host(raw: &str) -> bool { + let s = raw.trim(); + let s = s.split_once("://").map_or(s, |(_, rest)| rest); + let s = s.split(['/', '?', '#']).next().unwrap_or(""); + let s = s.rsplit_once('@').map_or(s, |(_, host)| host); + if s.starts_with('[') { + return false; + } + let host = s.split(':').next().unwrap_or("").trim_end_matches('.').to_ascii_lowercase(); + host == "backtrace.io" || host.ends_with(".backtrace.io") +} + +fn note_blocked_telemetry(host: &str) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("WinHTTP: blocked crash telemetry upload to '{host}'"); + } +} + +unsafe fn orig_winhttp_connect(session: *mut c_void, server: *const u16, port: u16, reserved: u32) -> *mut c_void { + match O_WINHTTP_CONNECT.load(Ordering::Acquire) { + 0 => { + SetLastError(ERROR_WINHTTP_NAME_NOT_RESOLVED); + std::ptr::null_mut() + } + f => std::mem::transmute:: *mut c_void>(f)( + session, server, port, reserved, + ), + } +} + +unsafe fn winhttp_connect_with(block_all: bool, server: *const u16, forward: impl FnOnce() -> *mut c_void) -> *mut c_void { + if block_all { + note("WinHttpConnect"); + SetLastError(ERROR_WINHTTP_NAME_NOT_RESOLVED); + return std::ptr::null_mut(); + } + if !server.is_null() { + if let Some(host) = crate::util::from_wide_ptr(server) { + if is_blocked_telemetry_host(&host) { + note_blocked_telemetry(&host); + SetLastError(ERROR_WINHTTP_NAME_NOT_RESOLVED); + return std::ptr::null_mut(); + } + } + } + forward() +} + +unsafe extern "system" fn winhttp_connect(session: *mut c_void, server: *const u16, port: u16, reserved: u32) -> *mut c_void { + winhttp_connect_with(BLOCK_ALL.load(Ordering::Acquire), server, || { + orig_winhttp_connect(session, server, port, reserved) + }) +} + +fn install_winhttp_connect_hook() -> Result<(), String> { + static ONCE: std::sync::OnceLock> = std::sync::OnceLock::new(); + ONCE.get_or_init(|| unsafe { crate::hooks::hook("winhttp.dll", "WinHttpConnect", winhttp_connect as usize, &O_WINHTTP_CONNECT) }) + .clone() +} + +/// Block outbound WinHTTP crash telemetry uploads (`*.backtrace.io`) while leaving all other +/// hosts (e.g. Rockstar online services and Xbox Live) untouched. +pub fn install_telemetry_block() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| match install_winhttp_connect_hook() { + Ok(()) => crate::xlog_info!("WinHTTP: crash telemetry uploads to *.backtrace.io are blocked"), + Err(e) => crate::xlog_warn!("WinHTTP: could not install telemetry block – {e}"), + }); +} + /// `XCL_NETWORK=0` for the whole process: the system's own network functions refuse as the /// title's imports do (see the module's comment). Call once, before the title runs. pub fn install_system_hooks() { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| unsafe { + BLOCK_ALL.store(true, Ordering::Release); let mut unused = O_UNUSED.iter(); let mut spare = || unused.next().expect("enough spare trampolines"); - let hooks: [(&str, &str, usize, &AtomicUsize); 18] = [ + let hooks: [(&str, &str, usize, &AtomicUsize); 17] = [ ("winhttp.dll", "WinHttpSendRequest", send_request as usize, spare()), - ("winhttp.dll", "WinHttpConnect", null_handle_winhttp as usize, spare()), ("wininet.dll", "InternetConnectA", null_handle_inet8 as usize, spare()), ("wininet.dll", "InternetConnectW", null_handle_inet8 as usize, spare()), ("wininet.dll", "InternetOpenUrlA", null_handle_inet6 as usize, spare()), @@ -175,6 +253,9 @@ pub fn install_system_hooks() { ("ws2_32.dll", "GetAddrInfoExW", getaddrinfo_ex as usize, spare()), ]; let mut failed = Vec::new(); + if let Err(e) = install_winhttp_connect_hook() { + failed.push(e); + } for (dll, name, detour, orig) in hooks { if let Err(e) = crate::hooks::hook(dll, name, detour, orig) { failed.push(e); @@ -188,12 +269,6 @@ pub fn install_system_hooks() { }); } -unsafe extern "system" fn null_handle_winhttp(_session: *mut c_void, _server: *const u16, _port: u16, _reserved: u32) -> *mut c_void { - note("WinHttpConnect"); - SetLastError(ERROR_WINHTTP_NAME_NOT_RESOLVED); - std::ptr::null_mut() -} - /// InternetConnectA/W (8 arguments): no connection (ERROR_INTERNET_NAME_NOT_RESOLVED – the /// same number as WinHTTP's) unsafe extern "system" fn null_handle_inet8(_h: *mut c_void, _server: *const c_void, _port: u16, _user: *const c_void, _pass: *const c_void, _service: u32, _flags: u32, _ctx: usize) -> *mut c_void { @@ -330,4 +405,81 @@ mod tests { assert_ne!(gai(b"localhost\0".as_ptr(), std::ptr::null(), std::ptr::null(), &mut out), WSAHOST_NOT_FOUND); } } + + #[test] + fn backtrace_telemetry_host_matching() { + for blocked in [ + "submit.backtrace.io", + "SUBMIT.BACKTRACE.IO", + "submit.backtrace.io:443", + "https://submit.backtrace.io/paradise/minidump?token=1", + "Submit.Backtrace.IO.", + "paradise.backtrace.io", + "backtrace.io", + " https://user@submit.backtrace.io:8443/upload#frag ", + ] { + assert!(is_blocked_telemetry_host(blocked), "expected blocked: {blocked:?}"); + } + for allowed in [ + "prod.ros.rockstargames.com", + "xsts.auth.xboxlive.com", + "notbacktrace.io", + "submit.backtrace.io.rockstargames.com", + "localhost", + "", + "[::1]:443", + ] { + assert!(!is_blocked_telemetry_host(allowed), "expected allowed: {allowed:?}"); + } + } + + #[test] + fn winhttp_connect_blocks_backtrace_and_forwards_other_hosts() { + use windows_sys::Win32::Foundation::GetLastError; + use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + + unsafe { + // Non-offline mode: block *.backtrace.io with ERROR_WINHTTP_NAME_NOT_RESOLVED. + let mut forwarded = false; + SetLastError(0); + let h = winhttp_connect_with(false, crate::util::wide("submit.backtrace.io").as_ptr(), || { + forwarded = true; + 0x1234 as *mut c_void + }); + assert!(h.is_null() && !forwarded); + assert_eq!(GetLastError(), ERROR_WINHTTP_NAME_NOT_RESOLVED); + + // Non-offline mode: forward Rockstar and Xbox Live hosts untouched. + for host in ["prod.ros.rockstargames.com", "xsts.auth.xboxlive.com"] { + let mut forwarded = false; + let sentinel = 0x1234usize as *mut c_void; + let h = winhttp_connect_with(false, crate::util::wide(host).as_ptr(), || { + forwarded = true; + sentinel + }); + assert_eq!(h, sentinel); + assert!(forwarded, "host {host} must be forwarded when not offline"); + } + + // Offline mode (block_all = true): blocks all hosts. + let mut forwarded = false; + SetLastError(0); + let h = winhttp_connect_with(true, crate::util::wide("prod.ros.rockstargames.com").as_ptr(), || { + forwarded = true; + 0x1234 as *mut c_void + }); + assert!(h.is_null() && !forwarded); + assert_eq!(GetLastError(), ERROR_WINHTTP_NAME_NOT_RESOLVED); + + // Live WinHTTP export detour blocks submit.backtrace.io even via GetProcAddress. + install_winhttp_connect_hook().unwrap(); + assert_ne!(O_WINHTTP_CONNECT.load(Ordering::Acquire), 0); + let wh = LoadLibraryW(crate::util::wide("winhttp.dll").as_ptr()); + let f = GetProcAddress(wh, b"WinHttpConnect\0".as_ptr()).expect("WinHttpConnect"); + let connect: unsafe extern "system" fn(*mut c_void, *const u16, u16, u32) -> *mut c_void = std::mem::transmute(f); + SetLastError(0); + assert!(connect(1 as *mut c_void, crate::util::wide("submit.backtrace.io").as_ptr(), 443, 0).is_null()); + assert_eq!(GetLastError(), ERROR_WINHTTP_NAME_NOT_RESOLVED); + } + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index ba5dcb473..ea4176558 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -105,6 +105,9 @@ pub fn host_main(boot_path: &Path) -> i32 { } crate::stubs::init_db(&boot.config.stub_returns); crate::hle::init(&boot.config); + if !crate::hle::netoff::enabled() { + crate::hle::netoff::install_telemetry_block(); + } crate::hle::kernelx::fine_timer(); crate::loader::set_cache_dir(boot.cache_dir()); let mut dirs = vec![boot.game_root.clone()];