From c9c8677bd5828eec243305ff87a274e92dbb304c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:10:54 +0100 Subject: [PATCH] d3d12x: fix async compute PSO tracking, initial PSO binding, DrawIndexedX, and KickoffX MRT restore --- crates/xcl/src/hle/d3d12x/bind.rs | 391 +++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 10 +- crates/xcl/src/hle/d3d12x/device_x.rs | 5 +- crates/xcl/src/hle/d3d12x/list_x.rs | 262 ++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 37 +- crates/xcl/tests/gpu_compute_e2e.rs | 90 ++++- 6 files changed, 757 insertions(+), 38 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 93260a0..ea2e905 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -66,17 +66,35 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } -/// The list was reset onto `allocator`: the previous recording's memory is the previous -/// allocator's until that one is reset. -pub(super) fn reset(list: *mut c_void, allocator: usize) { +/// The list was created or reset onto `allocator` with `initial_pso`: the previous +/// recording's memory is the previous allocator's until that one is reset, and pipeline +/// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. +pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { let (old, blocks) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); + s.pso = initial_pso; + s.layout = None; + s.args.clear(); + s.layout_gfx = None; + s.args_gfx.clear(); (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); } +/// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults +/// with `pso` bound, keeping the current recording's allocator and UMA arena intact. +pub(super) fn clear_state(list: *mut c_void, pso: usize) { + with(list, |s| { + s.pso = pso; + s.layout = None; + s.args.clear(); + s.layout_gfx = None; + s.args_gfx.clear(); + }); +} + /// The list is gone. pub(super) fn forget(list: *mut c_void) { if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { @@ -522,11 +540,11 @@ 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 = with(this, |s| s.pso); + let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { - // a console pipeline without a translation: nothing to run (its root arguments were - // not given to the PC list either) + // a console pipeline without a translation (including a background build that + // failed): nothing to run (its root arguments were not given to the PC list either) static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); @@ -534,11 +552,14 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - count(DISPATCHES); - if let Err(e) = translated_dispatch(this, list, pso, x, y, z) { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); + match translated_dispatch(this, list, pso, x, y, z) { + Ok(()) => count(DISPATCHES), + Err(e) => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}"); + } } } } @@ -704,3 +725,351 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetPipelineState(pc); Ok(()) } + +#[cfg(test)] +pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { + DRAW_ARGS.with(|d| d.get()) +} + +#[cfg(test)] +pub(super) fn counts_snapshot() -> [u64; 5] { + std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) +} + +#[cfg(test)] +pub(super) fn tracked_pso(list: *mut c_void) -> usize { + STATES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .map_or(0, |s| s.pso) +} + +#[cfg(test)] +mod tests { + use super::super::{device_x, list_x, pso_async, real, title_list}; + use super::*; + use std::sync::atomic::AtomicUsize; + + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. + fn test_rts0_blob() -> Vec { + let words: [u32; 12] = [ + 2, 1, 24, 0, 0, 0, // version=2, num_params=1, params_offset=24 + 1, 0, 36, // param 0: type=Constants(1), visibility=0, payload_offset=36 + 0, 0, 4, // shader_reg=0, reg_space=0, num_32bit_values=4 + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + #[test] + fn reset_and_clear_state_track_initial_pso_and_clear_root_args() { + let list = 0x7100_0001usize as *mut c_void; + let rs_compute = 0x7100_0010usize; + let rs_gfx = 0x7100_0020usize; + let alloc1 = 0x7100_0100usize; + let alloc2 = 0x7100_0200usize; + let pso_init = 0x7100_1000usize; + let pso_mid = 0x7100_2000usize; + let pso_cleared = 0x7100_3000usize; + let pso_reset = 0x7100_4000usize; + + let blob = test_rts0_blob(); + console_list::note_root_signature(rs_compute, &blob); + console_list::note_root_signature(rs_gfx, &blob); + + // Initial CreateCommandList / reset seeds PSO and allocator with clean root state. + reset(list, alloc1, pso_init); + with(list, |s| { + assert_eq!(s.pso, pso_init); + assert_eq!(s.allocator, alloc1); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // Populate compute + graphics root signatures, constants, and a different PSO. + unsafe { + set_compute_root_signature(list, rs_compute as *mut c_void); + set_compute_root_constant(list, 0, 0xDEAD_BEEF, 0); + set_graphics_root_signature(list, rs_gfx as *mut c_void); + set_graphics_root_constant(list, 0, 0xCAFE_BABE, 0); + } + with(list, |s| { + s.pso = pso_mid; + assert!(s.layout.is_some() && !s.args.is_empty()); + assert!(s.layout_gfx.is_some() && !s.args_gfx.is_empty()); + }); + + // ClearState(pso_cleared) updates PSO and clears root signatures/args while keeping allocator. + clear_state(list, pso_cleared); + with(list, |s| { + assert_eq!(s.pso, pso_cleared); + assert_eq!(s.allocator, alloc1); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // ClearState(null) clears PSO to 0. + clear_state(list, 0); + assert_eq!(tracked_pso(list), 0); + + // Re-populate root args, then Reset(alloc2, pso_reset) switches allocator/PSO and clears root args. + unsafe { + set_compute_root_signature(list, rs_compute as *mut c_void); + set_compute_root_constant(list, 0, 0x1234_5678, 0); + set_graphics_root_signature(list, rs_gfx as *mut c_void); + set_graphics_root_constant(list, 0, 0x8765_4321, 0); + } + reset(list, alloc2, pso_reset); + with(list, |s| { + assert_eq!(s.pso, pso_reset); + assert_eq!(s.allocator, alloc2); + assert!(s.layout.is_none() && s.args.is_empty()); + assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty()); + }); + + // Reset with null initial PSO clears stale PSO back to 0. + reset(list, alloc2, 0); + assert_eq!(tracked_pso(list), 0); + + forget(list); + } + + #[repr(C)] + struct FakeAdoptedList { + vt: *const usize, + refs: AtomicUsize, + dispatch_calls: AtomicUsize, + set_compute_rs_calls: AtomicUsize, + set_compute_uav_calls: AtomicUsize, + set_pso_calls: AtomicUsize, + execute_indirect_calls: AtomicUsize, + } + + unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeAdoptedList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeAdoptedList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + unsafe extern "system" fn fake_dispatch(this: *mut c_void, _x: u32, _y: u32, _z: u32) { + (*(this as *const FakeAdoptedList)).dispatch_calls.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn fake_set_pso(this: *mut c_void, _pso: *mut c_void) { + (*(this as *const FakeAdoptedList)).set_pso_calls.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn fake_set_compute_rs(this: *mut c_void, _rs: *mut c_void) { + (*(this as *const FakeAdoptedList)).set_compute_rs_calls.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn fake_set_compute_uav(this: *mut c_void, _slot: u32, _va: u64) { + (*(this as *const FakeAdoptedList)).set_compute_uav_calls.fetch_add(1, Ordering::Relaxed); + } + + unsafe extern "system" fn fake_execute_indirect( + this: *mut c_void, + _sig: usize, + _max: u32, + _args: usize, + _args_off: u64, + _count_buf: usize, + _count_off: u64, + ) { + (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); + } + + #[test] + fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[14] = fake_dispatch as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; + + // Extended vtable layout expected by `real::orig_fn`: entry -1 holds `orig_vt` pointer, + // and entries 0..64 hold the COM method pointers used via `ID3D12GraphicsCommandList`. + 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(FakeAdoptedList { + // SAFETY: `ext_vt` has 65 elements so `.add(1)` points to slot 0 with `orig_vt` at `-1`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + + // 1. Background compute build SUCCEEDS: real PSO R is registered in TRANSLATED_COMPUTE, + // stand-in S is NOT. ExecuteIndirect resolves S -> R and treats it as translated. + let standin_ok = 0x7200_0001usize; + let real_ok = 0x7200_0002usize; + let sig_root_changing = 0x7200_00F0usize; + note_root_changing_signature(sig_root_changing); + + pso_async::submit( + standin_ok, + true, + Box::new(move || { + real::register_translated_compute_for_test(real_ok); + real_ok + }), + ); + assert_eq!(pso_async::resolve_wait(standin_ok), real_ok); + assert!(!real::is_translated_compute(standin_ok)); + assert!(real::is_translated_compute(real_ok)); + + reset(list_ptr, 0x7200_0100, standin_ok); + unsafe { + // With `sig_root_changing`, a translated compute PSO is caught by the root-changing + // guard instead of falling through to `pc` (which happened when `R` wasn't registered). + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 0, + "ExecuteIndirect must recognize resolved async compute PSO R as translated" + ); + + // 2. Background compute build FAILS (returns 0): stand-in S_fail is NOT in + // TRANSLATED_COMPUTE. Dispatch must skip cleanly without binding XCL's ABI RS/UAVs + // onto S_fail, and ExecuteIndirect must not enter bind_abi either. + let standin_fail = 0x7200_0003usize; + pso_async::submit(standin_fail, true, Box::new(|| 0)); + assert_eq!(pso_async::resolve_wait(standin_fail), standin_fail); + assert!(!real::is_translated_compute(standin_fail)); + + reset(list_ptr, 0x7200_0100, standin_fail); + let before = counts_snapshot(); + unsafe { + dispatch(list_ptr, 1, 1, 1); + } + let after = counts_snapshot(); + assert_eq!(after[DISPATCHES], before[DISPATCHES]); + assert!(after[DISPATCHES_SKIPPED] > before[DISPATCHES_SKIPPED]); + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + + unsafe { + execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); + } + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + assert_eq!( + fake.execute_indirect_calls.load(Ordering::Relaxed), + 1, + "failed async compute stand-in must not enter translated ExecuteIndirect path" + ); + + forget(list_ptr); + let _ = pso_async::released(standin_ok); + let _ = pso_async::released(standin_fail); + real::forget_pso_for_test(real_ok); + } + + #[test] + fn create_list_reset_and_clear_state_track_initial_pso_on_d3d12() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + if console_list::enabled() { + return; + } + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + real::adopt(dev.as_raw(), real::Kind::Device); + + // Build two real PC compute PSOs from the inbox dummy CS bytecode. + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize RS"); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .expect("CreateRootSignature"); + let cs = real::dummy_cs_bytecode(); + let make_pso = || -> ID3D12PipelineState { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + pso + }; + let pso1 = make_pso(); + let pso2 = make_pso(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + + // Stand-in synthetic key backed by real `pso1` in pso_async: CreateCommandList must + // resolve it via resolve_for_bind for PC D3D12 while tracking `standin` in `bind`. + let standin = 0x7300_0001usize; + let pso1_raw = pso1.as_raw() as usize; + pso_async::submit(standin, true, Box::new(move || pso1_raw)); + assert_eq!(pso_async::resolve_wait(standin), pso1_raw); + + let mut raw_list: *mut c_void = std::ptr::null_mut(); + let iid = windows_sys::core::GUID::from_u128(0x5b160d0f_ac1b_4185_8ba8_b3ae42a5a455); + let hr = device_x::create_command_list_pc( + dev.as_raw(), + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT.0 as u32, + alloc.as_raw() as usize, + standin, + &iid, + &mut raw_list, + ); + assert!(hr >= 0 && !raw_list.is_null(), "create_command_list_pc failed: {hr:#x}"); + let backing = title_list::backing(raw_list).expect("wrapped in title_list"); + assert_eq!(tracked_pso(backing), standin, "CreateCommandList must seed bind::State.pso"); + + // ClearState(pso2) updates bind::State.pso to pso2 and clears root args. + let rs_key = 0x7300_0010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + set_compute_root_signature(backing, rs_key as *mut c_void); + set_compute_root_constant(backing, 0, 0xABCD, 0); + let cl = ID3D12GraphicsCommandList::from_raw_borrowed(&backing).unwrap(); + cl.ClearState(&pso2); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "ClearState must update bind::State.pso"); + with(backing, |s| assert!(s.layout.is_none() && s.args.is_empty())); + + // ClearState(None) clears bind::State.pso to 0. + cl.ClearState(None); + assert_eq!(tracked_pso(backing), 0, "ClearState(None) must clear bind::State.pso"); + + // Close + reset_x(alloc, pso2) updates bind::State.pso to pso2 and clears root args. + set_graphics_root_signature(backing, rs_key as *mut c_void); + set_graphics_root_constant(backing, 0, 0x1111, 0); + cl.Close().expect("Close"); + let hr = list_x::reset_x(backing, alloc.as_raw() as usize, pso2.as_raw() as usize); + assert!(hr >= 0, "reset_x failed: {hr:#x}"); + assert_eq!(tracked_pso(backing), pso2.as_raw() as usize, "Reset must update bind::State.pso"); + with(backing, |s| assert!(s.layout_gfx.is_none() && s.args_gfx.is_empty())); + + // Release the wrapped title list cleanly (calls bind::forget + list_x::on_release). + let release_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(raw_list as *const *const usize)).add(2)); + assert_eq!(release_fn(raw_list), 0); + let _ = pso_async::released(standin); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 81dbef7..832f630 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -766,6 +766,14 @@ pub unsafe fn close(obj: *mut c_void) -> Result { at += 4; match pso { Some(p) if (*p).translated => { + // a pipeline still being built in the background is waited for; if + // the background translation failed, skip instead of binding XCL's + // ABI root signature onto the stand-in + let real = super::pso_async::resolve_wait((*p).pc); + if !super::real::is_translated_compute(real) { + out.skipped_dispatches += 1; + continue; + } let inline = layout.as_ref().map_or(0, |l| l.inline as usize).min(table.len()); let table_at = uma_copy(st, &table[inline..]).ok_or("UMA: argument table")?; let mut io = match layout.as_ref() { @@ -775,8 +783,6 @@ pub unsafe fn close(obj: *mut c_void) -> Result { io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait((*p).pc); // the pipeline's own root signature when it has static samplers let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void); match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) { diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 21c19db..47dea8d 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -87,7 +87,8 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - let hr = real::dev_create_command_list(this, node, ty, alloc, pso, riid, ppv); + let resolved_pso = super::pso_async::resolve_for_bind(pso); + let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); } @@ -102,7 +103,7 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: // the title's inline D3D12.X code writes into the list object: it gets one of the // console's shape (`title_list`) if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && !super::console_list::enabled() { - super::bind::reset(*ppv, alloc); + super::bind::reset(*ppv, alloc, pso); *ppv = super::title_list::wrap(*ppv); } hr diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 04b6b2f..2270f81 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -34,7 +34,6 @@ use super::real; const PC_GET_TYPE: usize = 8; const PC_CLOSE: usize = 9; const PC_RESET: usize = 10; -const PC_DRAW_INDEXED: usize = 13; const PC_COPY_BUFFER_REGION: usize = 15; const PC_COPY_TEXTURE_REGION: usize = 16; const PC_COPY_RESOURCE: usize = 17; @@ -228,6 +227,18 @@ impl PendingWait { } } +/// Recorded `OMSetRenderTargets` state for `KickoffX` restoration and `XCL_TRACE_FRAME`. +#[derive(Clone, Debug, PartialEq, Eq)] +struct RenderTargets { + /// Requested `NumRenderTargetDescriptors` (clamped to D3D12 max 8; 0 if `handles` is empty). + num_targets: u32, + /// Saved descriptor handles: 1 base handle when `single != 0` and `num_targets > 0`, + /// otherwise `num_targets` handles. + handles: Vec, + single: i32, + dsv: Option, +} + /// What console code set on a list that a PC Reset clears: `KickoffX` closes, submits and /// resets the PC list mid-recording, and on the console a kickoff leaves the list's state as it /// was – so it is set again (descriptor heaps above all: translated shaders index the bound @@ -241,8 +252,7 @@ struct Bindings { blend: Option<[f32; 4]>, stencil: Option, vertex_buffers: std::collections::BTreeMap, - /// (handles, single range, depth-stencil handle) - render_targets: Option<(Vec, i32, Option)>, + render_targets: Option, /// slot → the title's (address, bytes, stride) of the vertex buffer (`XCL_TRACE_FRAME`) vertex_titles: std::collections::BTreeMap, /// the title's (address, bytes, format) of the index buffer (`XCL_TRACE_FRAME`) @@ -262,8 +272,8 @@ pub(super) fn state_summary(list: *mut c_void) -> String { b.stencil, b.viewports.len(), b.scissors.len(), - b.render_targets.as_ref().map(|(h, _, d)| (h.len(), d.is_some())), - b.render_targets.as_ref().and_then(|(_, _, d)| *d).map_or(String::new(), |d| format!(", DSV {d:#x}")) + b.render_targets.as_ref().map(|rt| (rt.num_targets as usize, rt.dsv.is_some())), + b.render_targets.as_ref().and_then(|rt| rt.dsv).map_or(String::new(), |d| format!(", DSV {d:#x}")) ); }); out @@ -357,7 +367,7 @@ fn vbs_first(list: *mut c_void) -> Option<(u32, (u64, u32, u32))> { /// The depth-stencil view handle a list last bound (`XCL_TRACE_FRAME`). pub(super) fn bound_dsv(list: *mut c_void) -> Option { let mut d = None; - with_bindings(list, |b| d = b.render_targets.as_ref().and_then(|(_, _, h)| *h)); + with_bindings(list, |b| d = b.render_targets.as_ref().and_then(|rt| rt.dsv)); d } @@ -422,10 +432,13 @@ pub(super) unsafe extern "system" fn om_set_stencil_ref_x(this: *mut c_void, r: /// OMSetRenderTargets as the PC list got it (`real::cl_om_set_render_targets`) pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { - let count = if single != 0 { n.min(1) } else { n } as usize; - let handles = if rtvs.is_null() { Vec::new() } else { std::slice::from_raw_parts(rtvs, count).to_vec() }; + let num_targets = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) }; + let read_count = if single != 0 { num_targets.min(1) } else { num_targets } as usize; + // SAFETY: `rtvs` is non-null whenever `read_count > 0`, and D3D12 requires at least 1 + // handle when `RTsSingleHandleToDescriptorRange != 0` or `num_targets` handles otherwise. + let handles = if read_count == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_count).to_vec() }; let d = dsv.as_ref().copied(); - with_bindings(this, |b| b.render_targets = Some(if n == 0 { (Vec::new(), single, d) } else { (handles, single, d) })); + with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); } /// Set again what `b` holds (after KickoffX's Reset). @@ -451,15 +464,15 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings) { for (&slot, v) in &b.vertex_buffers { pc::(this, PC_IA_SET_VERTEX_BUFFERS)(this, slot, 1, v); } - if let Some((rts, single, dsv)) = &b.render_targets { - let d = dsv.unwrap_or(0); - let n = if *single != 0 && !rts.is_empty() { 1 } else { rts.len() as u32 }; + if let Some(rt) = &b.render_targets { + let d = rt.dsv.unwrap_or(0); + let (n, rts_ptr) = if rt.handles.is_empty() { (0, std::ptr::null()) } else { (rt.num_targets, rt.handles.as_ptr()) }; pc::(this, PC_OM_SET_RENDER_TARGETS)( this, n, - if rts.is_empty() { std::ptr::null() } else { rts.as_ptr() }, - *single, - if dsv.is_some() { &d } else { std::ptr::null() }, + rts_ptr, + rt.single, + if rt.dsv.is_some() { &d } else { std::ptr::null() }, ); } } @@ -1582,10 +1595,9 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, if count == 0 { return; } - prepare_draw(this); let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: pc_va(va), SizeInBytes: count.saturating_mul(stride), Format: format }; set_index_buffer(this, Some(&view)); - pc::(this, PC_DRAW_INDEXED)(this, count, 1, 0, 0, 0); + super::bind::draw_indexed_instanced(this, count, 1, 0, 0, 0); let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); set_index_buffer(this, bound.as_ref()); } @@ -1626,7 +1638,7 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; - super::bind::reset(this, alloc); + super::bind::reset(this, alloc, pso); // the PC runtime writes its own vtable into a list on Reset (copy lists, Agility SDK 1.620+): re-adopt it let ext = *(this as *const usize); let resolved = super::pso_async::resolve_for_bind(pso); @@ -2461,4 +2473,218 @@ mod tests { device_x::forget_base(pso_dyn_static); device_x::forget_base(pso_static_only); } + + #[test] + fn draw_indexed_x_routes_through_bind_and_restores_index_buffer() { + #[repr(C)] + struct FakeDrawList { + vt: *const usize, + refs: AtomicUsize, + draws: Mutex>, + index_buffers: Mutex>>, + } + + unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 { + (*(this as *const FakeDrawList)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 { + (*(this as *const FakeDrawList)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + unsafe extern "system" fn fake_draw_indexed(this: *mut c_void, ic: u32, inst: u32, si: u32, bv: i32, sinst: u32) { + (*(this as *const FakeDrawList)).draws.lock().unwrap().push((ic, inst, si, bv, sinst)); + } + unsafe extern "system" fn fake_set_ib(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) { + let v = view.as_ref().copied(); + (*(this as *const FakeDrawList)).index_buffers.lock().unwrap().push(v); + } + unsafe extern "system" fn fake_noop_ptr(_this: *mut c_void, _p: *mut c_void) {} + unsafe extern "system" fn fake_noop_uav(_this: *mut c_void, _slot: u32, _va: u64) {} + + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[13] = fake_draw_indexed as usize; + orig_vt[25] = fake_noop_ptr as usize; // SetPipelineState + orig_vt[30] = fake_noop_ptr as usize; // SetGraphicsRootSignature + orig_vt[42] = fake_noop_uav as usize; // SetGraphicsRootUnorderedAccessView + orig_vt[43] = fake_set_ib 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(FakeDrawList { + // SAFETY: `ext_vt` has 65 entries so `.add(1)` points to slot 0 with `orig_vt` at `-1`. + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + draws: Mutex::new(Vec::new()), + index_buffers: Mutex::new(Vec::new()), + }); + let list_ptr = &*fake as *const FakeDrawList as *mut c_void; + + let orig_ib = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: 0x0000_0001_0000_1000, + SizeInBytes: 64, + Format: DXGI_FORMAT_R16_UINT, + }; + + unsafe { + ia_set_index_buffer_x(list_ptr, &orig_ib); + fake.index_buffers.lock().unwrap().clear(); + + // 1. Untranslated (PC) PSO: routes through bind::draw_indexed_instanced -> DrawIndexedInstanced, + // records DRAW_ARGS, binds temp IB, then restores orig_ib. + super::super::bind::reset(list_ptr, 0x7400_0100, 0); + let before = super::super::bind::counts_snapshot(); + draw_indexed_x(list_ptr, 0x0000_0001_0000_2000, DXGI_FORMAT_R16_UINT, 6, 0); + let after = super::super::bind::counts_snapshot(); + assert_eq!(super::super::bind::last_draw_args(), (true, 6, 1, 0, 0)); + assert!(after[2] > before[2], "DRAWS_PC must increment via bind::draw_indexed_instanced"); + assert_eq!(*fake.draws.lock().unwrap(), vec![(6, 1, 0, 0, 0)]); + let ibs = std::mem::take(&mut *fake.index_buffers.lock().unwrap()); + assert_eq!(ibs.len(), 2); + assert_eq!(ibs[0].unwrap().BufferLocation, 0x0000_0001_0000_2000); + assert_eq!(ibs[0].unwrap().SizeInBytes, 12); + assert_eq!(ibs[0].unwrap().Format, DXGI_FORMAT_R16_UINT); + assert_eq!(ibs[1].unwrap().BufferLocation, orig_ib.BufferLocation); + assert_eq!(ibs[1].unwrap().SizeInBytes, orig_ib.SizeInBytes); + + // 2. Translated graphics PSO: enters bind::graphics_bound translated path (DRAWS or + // DRAWS_SKIPPED, NOT DRAWS_PC) instead of bypassing bind.rs directly to PC slot 13. + let translated_pso = 0x7400_0055usize; + real::register_translated_graphics_for_test(translated_pso); + super::super::bind::reset(list_ptr, 0x7400_0100, translated_pso); + let before = super::super::bind::counts_snapshot(); + draw_indexed_x(list_ptr, 0x0000_0001_0000_3000, DXGI_FORMAT_R32_UINT, 12, 0); + let after = super::super::bind::counts_snapshot(); + assert_eq!(super::super::bind::last_draw_args(), (true, 12, 1, 0, 0)); + assert_eq!( + (after[0] + after[1]) - (before[0] + before[1]), + 1, + "translated graphics PSO must go through bind::graphics_bound (DRAWS or DRAWS_SKIPPED)" + ); + assert_eq!(after[2], before[2], "translated graphics PSO must not take the PC draw path"); + let ibs = std::mem::take(&mut *fake.index_buffers.lock().unwrap()); + assert_eq!(ibs.len(), 2); + assert_eq!(ibs[0].unwrap().SizeInBytes, 48); + assert_eq!(ibs[0].unwrap().Format, DXGI_FORMAT_R32_UINT); + assert_eq!(ibs[1].unwrap().BufferLocation, orig_ib.BufferLocation); + + // 3. Zero count or invalid format returns early without touching IB or draws. + let draws_before = fake.draws.lock().unwrap().len(); + draw_indexed_x(list_ptr, 0x0000_0001_0000_4000, DXGI_FORMAT_R16_UINT, 0, 0); + draw_indexed_x(list_ptr, 0x0000_0001_0000_4000, DXGI_FORMAT_R8_UINT, 3, 0); + assert_eq!(fake.draws.lock().unwrap().len(), draws_before); + assert!(fake.index_buffers.lock().unwrap().is_empty()); + + real::forget_pso_for_test(translated_pso); + } + + super::super::bind::forget(list_ptr); + on_release(list_ptr as usize); + } + + #[test] + fn kickoff_x_render_targets_preserve_mrt_count_for_single_descriptor_range() { + #[derive(Debug, PartialEq, Eq)] + struct RtCall { + n: u32, + handles: Vec, + rtvs_was_null: bool, + single: i32, + dsv: Option, + } + + #[repr(C)] + struct FakeRtList { + vt: *const usize, + calls: Mutex>, + } + + unsafe extern "system" fn fake_om_set_render_targets( + this: *mut c_void, + n: u32, + rtvs: *const usize, + single: i32, + dsv: *const usize, + ) { + let read_n = if rtvs.is_null() { + 0 + } else if single != 0 { + n.min(1) as usize + } else { + n as usize + }; + let handles = if read_n == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_n).to_vec() }; + (*(this as *const FakeRtList)).calls.lock().unwrap().push(RtCall { + n, + handles, + rtvs_was_null: rtvs.is_null(), + single, + dsv: dsv.as_ref().copied(), + }); + } + + let mut orig_vt = [0usize; 64]; + orig_vt[PC_OM_SET_RENDER_TARGETS] = fake_om_set_render_targets as usize; + let mut ext_vt = [0usize; 2]; + ext_vt[0] = orig_vt.as_ptr() as usize; + + let fake = Box::new(FakeRtList { + // SAFETY: `ext_vt` has 2 entries so `.add(1)` has `orig_vt` at `-1` as `real::orig_fn` expects. + vt: unsafe { ext_vt.as_ptr().add(1) }, + calls: Mutex::new(Vec::new()), + }); + let list_ptr = &*fake as *const FakeRtList as *mut c_void; + + let restore = || { + let b = LISTS.lock().unwrap().as_ref().unwrap().get(&(list_ptr as usize)).unwrap().bindings.clone(); + unsafe { restore_bindings(list_ptr, &b) }; + }; + + unsafe { + // 1. Single contiguous descriptor range for 4 MRTs + DSV: only 1 handle exists at `rtvs`, + // yet restore_bindings must pass `n = 4` (not 1!) to OMSetRenderTargets. + let single_base = [0x1000usize]; + let dsv_val = 0x9000usize; + note_render_targets(list_ptr, 4, single_base.as_ptr(), 1, &dsv_val); + assert!( + state_summary(list_ptr).contains("render targets Some((4, true))"), + "state_summary should report full MRT count: {}", + state_summary(list_ptr) + ); + restore(); + + // 2. Oversized count with single range is clamped to D3D12 max (8). + note_render_targets(list_ptr, 12, single_base.as_ptr(), 1, std::ptr::null()); + restore(); + + // 3. Separate handles (single == 0) for 3 MRTs. + let multi = [0x2000usize, 0x2020, 0x2040]; + note_render_targets(list_ptr, 3, multi.as_ptr(), 0, std::ptr::null()); + restore(); + + // 4. Depth-only (n == 0, rtvs == null, dsv != null). + note_render_targets(list_ptr, 0, std::ptr::null(), 0, &dsv_val); + restore(); + + // 5. Null rtvs pointer with non-zero n must safely restore n == 0, null pointer. + note_render_targets(list_ptr, 4, std::ptr::null(), 1, std::ptr::null()); + restore(); + } + + let calls = fake.calls.lock().unwrap(); + assert_eq!( + *calls, + vec![ + RtCall { n: 4, handles: vec![0x1000], rtvs_was_null: false, single: 1, dsv: Some(0x9000) }, + RtCall { n: 8, handles: vec![0x1000], rtvs_was_null: false, single: 1, dsv: None }, + RtCall { n: 3, handles: vec![0x2000, 0x2020, 0x2040], rtvs_was_null: false, single: 0, dsv: None }, + RtCall { n: 0, handles: vec![], rtvs_was_null: true, single: 0, dsv: Some(0x9000) }, + RtCall { n: 0, handles: vec![], rtvs_was_null: true, single: 1, dsv: None }, + ] + ); + + on_release(list_ptr as usize); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4bd7708..fd7cebf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1414,6 +1414,25 @@ pub fn is_translated_compute(pso: usize) -> bool { pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } +#[cfg(test)] +pub(super) fn register_translated_compute_for_test(pso: usize) { + if pso != 0 { + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + +#[cfg(test)] +pub(super) fn register_translated_graphics_for_test(pso: usize) { + if pso != 0 { + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + +#[cfg(test)] +pub(super) fn forget_pso_for_test(pso: usize) { + forget_pso(pso); +} + fn forget_pso(pso: usize) { if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); @@ -1893,7 +1912,8 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); - let hr = f(this, allocator, initial_state); + let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; + let hr = f(this, allocator, resolved); preserve_vtable(this, ext); hr } @@ -2491,6 +2511,11 @@ fn dummy() -> &'static Dummy { }) } +#[cfg(test)] +pub(super) fn dummy_cs_bytecode() -> &'static [u8] { + &dummy().cs +} + fn bytecode(b: &[u8]) -> D3D12_SHADER_BYTECODE { D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const c_void, BytecodeLength: b.len() } } @@ -2661,6 +2686,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); + note_translated_compute(hr, ppv); crate::xlog_info!("D3D12.X: compute PSO with the translated console CS ({} B DXIL)", dxil.len()); Some(Ok(hr)) } @@ -3022,17 +3048,18 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, build_compute)) { - // a console program the worker is translating (its root signature comes with it) + // a console program the worker is translating (its root signature comes with it); + // the real PSO registers itself in TRANSLATED_COMPUTE once build_compute succeeds + // (if build_compute fails, the stand-in stays unregistered so Dispatch / + // ExecuteIndirect never bind XCL's ABI root signature onto it) LAST_COMPUTE_TRANSLATED.with(|c| c.set(true)); LAST_COMPUTE_RS.with(|c| c.set(0)); - note_translated_compute(hr, ppv); return hr; } console = translated_compute_pso(this, f, desc, riid, ppv); } LAST_COMPUTE_TRANSLATED.with(|c| c.set(matches!(console, Some(Ok(hr)) if hr >= 0))); if let Some(Ok(hr)) = console { - note_translated_compute(hr, ppv); return hr; } // a console shader the recompiler could not take must not reach the driver: AMD's shader @@ -3482,6 +3509,7 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); f(this, super::pso_async::resolve_for_bind(pso as usize) as *mut c_void); super::list_x::on_clear_state(this, pso as usize); + super::bind::clear_state(this, pso as usize); } unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { @@ -3519,6 +3547,7 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { super::list_x::on_release(this as usize); + super::bind::forget(this); } n } diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 3819fbf..08a1233 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -7,12 +7,16 @@ //! waves (NVIDIA) the backend has to run it as two wave32 halves, or the driver refuses the //! pipeline. The pipeline counters are checked, so the test cannot pass on a fallback path. +use std::sync::Mutex; + use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use xcl::gpu::rdna2::encode; use xcl::gpu::recomp::runner; -use xcl::hle::d3d12x::real; +use xcl::hle::d3d12x::{pso_async, real}; + +static SERIAL: Mutex<()> = Mutex::new(()); fn le(v: &mut Vec, x: u32) { v.extend_from_slice(&x.to_le_bytes()); @@ -110,6 +114,7 @@ fn program() -> Vec { #[test] fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); if xcl::gpu::recomp::dxc::location().is_err() { println!("no DXC – skipping"); runner::skip_test("no DXC"); @@ -146,6 +151,10 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { let real_raw = xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize) as *mut std::ffi::c_void; let after = real::stats(); assert_eq!(after.translated_pipelines, before.translated_pipelines + 1, "PSO was not built from the translated shader: {:?}", after.translation_errors); + assert!( + real::is_translated_compute(real_raw as usize), + "resolved compute PSO must be registered in TRANSLATED_COMPUTE" + ); let pso = unsafe { ID3D12PipelineState::from_raw_borrowed(&real_raw) }.unwrap().clone(); let rs_raw = real::pso_root_signature(pso.as_raw() as usize).expect("root signature of the translated PSO") as *mut std::ffi::c_void; let rs = unsafe { ID3D12RootSignature::from_raw_borrowed(&rs_raw) }.unwrap().clone(); @@ -165,3 +174,82 @@ fn console_wave64_compute_through_the_pso_hook_dispatch_and_read_back() { } } } + +/// Cold DXIL cache: `CreateComputePipelineState` returns a stand-in immediately and compiles +/// the real compute PSO on the background worker. The real PSO (and NOT the stand-in) must be +/// registered in `TRANSLATED_COMPUTE` once the background build completes. +#[test] +fn async_compute_pso_registers_real_pso_and_not_standin() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + println!("no DXC – skipping"); + runner::skip_test("no DXC"); + return; + } + if xcl::hle::d3d12x::backend() != xcl::hle::d3d12x::Backend::Real { + println!("no real D3D12 device – skipping"); + runner::skip_test("no GPU"); + return; + } + if !pso_async::enabled() { + println!("XCL_ASYNC_PSO=0 – skipping"); + return; + } + + struct ColdCache(std::path::PathBuf, Option); + impl Drop for ColdCache { + fn drop(&mut self) { + match &self.1 { + Some(prev) => std::env::set_var("XCL_DXIL_CACHE", prev), + None => std::env::remove_var("XCL_DXIL_CACHE"), + } + let _ = std::fs::remove_dir_all(&self.0); + } + } + let cold = ColdCache( + std::env::temp_dir().join(format!("xcl-async-compute-pso-{}", std::process::id())), + std::env::var_os("XCL_DXIL_CACHE"), + ); + let _ = std::fs::remove_dir_all(&cold.0); + std::env::set_var("XCL_DXIL_CACHE", &cold.0); + + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + + // Distinct minimal console CS so neither disk nor in-memory DXIL cache already holds it. + let code: Vec = [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 0)][..], None), + ("S_ENDPGM", "ENC_SOPP", &[][..], None), + ] + .iter() + .flat_map(|(n, e, f, l)| encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))) + .collect(); + let blob = console_cs(&code, 2 << 1 | 1 << 7, [8, 8, 1]); + + let game_rs: ID3D12RootSignature = unsafe { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(game_rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() }, + ..Default::default() + }; + let pso: Result = unsafe { dev.CreateComputePipelineState(&desc) }; + unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; + let pso = pso.expect("CreateComputePipelineState stand-in"); + let standin_raw = pso.as_raw() as usize; + + assert!(!real::is_translated_compute(standin_raw), "stand-in compute PSO must not be registered in TRANSLATED_COMPUTE"); + let real_raw = pso_async::resolve_wait(standin_raw); + assert_ne!(real_raw, standin_raw, "cold DXIL cache must build compute PSO asynchronously behind a stand-in"); + assert!(real::is_translated_compute(real_raw), "background-built real compute PSO must be registered in TRANSLATED_COMPUTE"); + assert!(!real::is_translated_compute(standin_raw), "stand-in must remain unregistered after background build"); + assert!(real::pso_root_signature(real_raw).is_some(), "real compute PSO must have an ABI root signature"); + + // Releasing the stand-in must release and forget the background-built real PSO too. + drop(pso); + assert!(!real::is_translated_compute(real_raw), "forgetting released async compute PSO must clean up TRANSLATED_COMPUTE"); +}