diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..a099d71aa5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -29,6 +29,8 @@ struct State { /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, pso: usize, + pso_resolved: super::pso_async::Resolved, + pso_settled: bool, allocator: usize, /// unified memory of this recording (io, argument tables) uma: Vec, @@ -73,41 +75,75 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// 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, blocks, old_pso) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; + s.pso_settled = false; + let old_pso = std::mem::take(&mut s.pso_resolved); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + (old, std::mem::take(&mut s.uma), old_pso) }); + drop(old_pso); console_list::hold_until_reset(old, blocks); } +/// Record the resolved handle from `cl_set_pipeline_state` / `cl_reset` / `cl_clear_state` +/// so subsequent draws/dispatches avoid re-querying `pso_async` when already settled. +pub(super) fn note_resolved(list: *mut c_void, pso: usize, resolved: &super::pso_async::Resolved) { + let next = if resolved.has_com() || !resolved.is_settled() { + resolved.clone() + } else { + super::pso_async::Resolved::none() + }; + let old = with(list, |s| { + if s.pso != pso { + return next; + } + s.pso_settled = resolved.is_settled(); + std::mem::replace(&mut s.pso_resolved, next) + }); + drop(old); +} + /// `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| { + let old_pso = with(list, |s| { s.pso = pso; + s.pso_settled = false; + let old_pso = std::mem::take(&mut s.pso_resolved); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + old_pso }); + drop(old_pso); } /// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a /// 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, pso, pso_resolved, pso_settled) = with(from, |s| { + ( + s.layout.clone(), + s.args.clone(), + s.layout_gfx.clone(), + s.args_gfx.clone(), + s.rs_gfx, + s.pso, + s.pso_resolved.clone(), + s.pso_settled, + ) }); - let (old, blocks) = with(to, |s| { + let (old, blocks, old_pso) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.layout = layout; @@ -116,8 +152,11 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; s.pso = pso; - (old, std::mem::take(&mut s.uma)) + s.pso_settled = pso_settled; + let old_pso = std::mem::replace(&mut s.pso_resolved, pso_resolved); + (old, std::mem::take(&mut s.uma), old_pso) }); + drop(old_pso); console_list::hold_until_reset(old, blocks); } @@ -263,6 +302,43 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +/// Resolve the pipeline currently bound on `this` (`s.pso`), reusing `s.pso_resolved` if `s.pso` +/// was already settled or released from `pso_async`. +unsafe fn resolve_bound_wait(this: *mut c_void) -> (usize, super::pso_async::Resolved) { + let fast = with(this, |s| { + if s.pso_settled { + let res = if s.pso_resolved.ptr() != 0 { + s.pso_resolved.clone() + } else { + super::pso_async::Resolved::unretained_settled(s.pso) + }; + Ok((s.pso, res)) + } else { + Err((s.pso, s.pso_resolved.clone())) + } + }); + let (pso, saved) = match fast { + Ok(hit) => return hit, + Err(miss) => miss, + }; + let resolved = super::pso_async::resolve_cached_wait(pso, &saved); + let next = if resolved.has_com() || !resolved.is_settled() { + resolved.clone() + } else { + super::pso_async::Resolved::none() + }; + let old = with(this, |s| { + if s.pso == pso { + s.pso_settled = resolved.is_settled(); + std::mem::replace(&mut s.pso_resolved, next) + } else { + next + } + }); + drop(old); + (pso, resolved) +} + /// #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) @@ -274,7 +350,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return super::pso_async::need_by_submit(raw_pso); } - let pso = super::pso_async::resolve_wait(raw_pso); + let (raw_pso, pso_guard) = resolve_bound_wait(this); + let pso = pso_guard.ptr(); 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)); if !gfx && !compute { @@ -283,7 +360,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // 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(raw_pso) { + if !pso_guard.is_settled() && super::pso_async::is_pending(raw_pso) { count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -335,7 +412,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - match bind_abi(this, list, pso, gfx) { + match bind_abi(this, list, &pso_guard, gfx) { Ok(()) => { if compute { match super::real::dispatch_chain::whole(pso) { @@ -486,7 +563,8 @@ unsafe fn draw_rects(this: *mut c_void, list: &ID3D12GraphicsCommandList, vertic /// not with the rect list GS (`real::has_rect_list_gs`), which completes each rect itself – both /// would draw every rect twice (each CPU half is three corners of the rect). fn cpu_rect_expansion(pso: usize) -> bool { - !super::real::has_rect_list_gs(super::pso_async::resolve(pso)) + let pso = super::pso_async::resolve_if_pending(pso); + !super::real::has_rect_list_gs(pso.ptr()) } /// #12 DrawInstanced @@ -543,9 +621,9 @@ pub(super) unsafe fn emit_prepared_indexed_draw( /// translation, or no unified memory). unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); - let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) - let real = super::pso_async::resolve_wait(pso); + let (pso, resolved) = resolve_bound_wait(this); + let real = resolved.ptr(); if !super::real::is_translated_graphics(real) { // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing @@ -569,7 +647,6 @@ 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), @@ -581,7 +658,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option // 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) - if super::pso_async::is_pending(pso) { + if !resolved.is_settled() && super::pso_async::is_pending(pso) { super::list_x::note_dropped_draw(this); } let rs = with(this, |s| s.rs_gfx) as *mut c_void; @@ -593,7 +670,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option if super::present::trace_frame() { trace_ui_draw(this, pso); } - match bind_abi(this, &list, pso, true) { + match bind_abi(this, &list, &resolved, true) { Ok(()) => { count(DRAWS); Some(list) @@ -622,7 +699,8 @@ unsafe fn trace_draw_kinds(this: *mut c_void, pso: usize) { if super::present::activity().0 < 300 { return; } - let Some((vs, ps)) = super::real::pso_shaders(super::pso_async::resolve(pso)) else { return }; + let resolved_pso = super::pso_async::resolve_if_pending(pso); + let Some((vs, ps)) = super::real::pso_shaders(resolved_pso.ptr()) else { return }; let rt = super::present::rt0_resource(this as usize).unwrap_or(0); let desc = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.SampleDesc.Count) }); { @@ -702,9 +780,10 @@ unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { super::list_x::watch_dsv(dsv); } let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0, d.Flags.0) }); + let resolved_pso = super::pso_async::resolve_if_pending(pso); crate::xlog_info!( "frame trace: a draw (shaders {:x?}, {}) reads a watched target {r:#x} {:?} at {addr:x?} (slot {k}), drawing into {rt:#x} {:?}{} – {}", - super::real::pso_shaders(super::pso_async::resolve(pso)), + super::real::pso_shaders(resolved_pso.ptr()), super::list_x::state_summary(this), d(r), d(rt), @@ -714,7 +793,7 @@ unsafe fn trace_reads_of_watched(this: *mut c_void, pso: usize) { let args = DRAW_ARGS.with(|d| d.get()); crate::xlog_info!( "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::real::pso_layout(resolved_pso.ptr()).unwrap_or_default(), super::list_x::geometry_summary(this, args) ); return; @@ -762,26 +841,27 @@ unsafe fn trace_ui_draw(this: *mut c_void, pso: usize) { return; } let Some(rt) = super::present::rt0_resource(this as usize) else { return }; + let resolved_pso = super::pso_async::resolve_if_pending(pso); let wanted = traced_shaders(); if wanted.is_empty() { // draws into a presented target, or – `XCL_TRACE_UI_ANY` – into any target if super::present::activity().0 < 300 || (!super::present::is_presented(rt) && std::env::var_os("XCL_TRACE_UI_ANY").is_none()) { return; } - } else if !super::real::pso_shaders(super::pso_async::resolve(pso)).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { + } else if !super::real::pso_shaders(resolved_pso.ptr()).is_some_and(|(v, p)| wanted.contains(&v) || wanted.contains(&p)) { return; } else { super::present::watch_rt(rt); } N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let sh = super::real::pso_shaders(super::pso_async::resolve(pso)).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); + let sh = super::real::pso_shaders(resolved_pso.ptr()).map(|(v, p)| format!("vs {v:016x} ps {p:016x}")); crate::xlog_info!("frame trace: UI draw (pipeline {pso:#x}, {}): {}", sh.unwrap_or_default(), root_args_summary(this, 16)); if !wanted.is_empty() { // the picked shaders' geometry too (vertices dumped at the next present) let args = DRAW_ARGS.with(|d| d.get()); crate::xlog_info!( "frame trace: … that draw: {args:?} (indexed, count, instances, first, base vertex); input layout [{}]; {}", - super::real::pso_layout(super::pso_async::resolve(pso)).unwrap_or_default(), + super::real::pso_layout(resolved_pso.ptr()).unwrap_or_default(), super::list_x::geometry_summary(this, args) ); } @@ -864,7 +944,12 @@ pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_vo /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { - with(this, |s| s.pso = pso as usize); + let old = with(this, |s| { + s.pso = pso as usize; + s.pso_settled = false; + std::mem::take(&mut s.pso_resolved) + }); + drop(old); super::real::bind_pipeline(this, pso); } @@ -874,7 +959,8 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { return super::pso_async::need_by_submit(pso); } - let pso = super::pso_async::resolve_wait(pso); + let (_, real) = resolve_bound_wait(this); + let pso = real.ptr(); 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 @@ -886,7 +972,7 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - match translated_dispatch(this, list, pso, x, y, z) { + match translated_dispatch(this, list, &real, x, y, z) { Ok(()) => count(DISPATCHES), Err(e) => { count(DISPATCHES_SKIPPED); @@ -1003,18 +1089,18 @@ pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, s } } -unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> { +unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, real: &super::pso_async::Resolved, x: u32, y: u32, z: u32) -> Result<(), String> { if super::present::trace_frame() { - trace_fullscreen(this, pso, [x, y, z]); + trace_fullscreen(this, real.ptr(), [x, y, z]); } - bind_abi(this, list, pso, false)?; - super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) + bind_abi(this, list, real, false)?; + super::real::dispatch_chain::dispatch(list, real.ptr(), with(this, |s| s.allocator), [x, y, z]) } /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. -unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { +unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, resolved: &super::pso_async::Resolved, gfx: bool) -> Result<(), String> { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); @@ -1026,8 +1112,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); Ok(p as usize) }; - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); + let real = resolved.ptr(); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); @@ -1057,9 +1142,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetComputeRootUnorderedAccessView(k as u32, v); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + let raw = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("pipeline")?; list.SetPipelineState(pc); + super::list_x::retain_pso(this, resolved.clone()); Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7726419583..3d144a7d46 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -301,6 +301,8 @@ struct ListState { uma: Vec, /// where the next draw's argument table and io go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// Retained PC pipeline objects bound to this recording, dropped on Reset or Release. + retained_psos: HashMap, } static LISTS: Mutex>> = Mutex::new(None); @@ -389,7 +391,8 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { }) .unwrap_or(0); if left == 0 { - if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) { + let dead = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)); + if let Some(st) = dead { free_uma(&st.uma); let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2)); release(st.pc); @@ -422,20 +425,36 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, pso: *mut c_void) -> HRESULT { let obj = this as usize; - let Some((pc, old_alloc, blocks)) = with_list(obj, |st| { + let Some((pc, old_alloc, blocks, old_psos)) = with_list(obj, |st| { st.chunks.clear(); st.arena = Default::default(); - (st.pc, std::mem::replace(&mut st.allocator, allocator as usize), std::mem::take(&mut st.uma)) + ( + st.pc, + std::mem::replace(&mut st.allocator, allocator as usize), + std::mem::take(&mut st.uma), + std::mem::take(&mut st.retained_psos), + ) }) else { return crate::util::E_FAIL; }; + drop(old_psos); // what the previous recording left in unified memory lives until its allocator resets if !blocks.is_empty() { PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(old_alloc).or_default().extend(blocks); } with_list(obj, |st| new_chunk(obj, st)); + let init_pso = super::pso_async::resolve_for_bind_retained(pc_pso(pso) as usize); + let init_ptr = init_pso.ptr(); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + let hr = f(pc, allocator, init_ptr as *mut c_void); + if hr >= 0 { + if let Some(com) = init_pso.into_com() { + with_list(obj, |st| { + st.retained_psos.entry(init_ptr).or_insert(com); + }); + } + } + hr } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -606,7 +625,15 @@ pub unsafe fn create(pc: *mut c_void) -> *mut c_void { pub unsafe fn create_with_allocator(pc: *mut c_void, allocator: *mut c_void) -> *mut c_void { let obj = Box::into_raw(vec![0u8; OBJECT_BYTES].into_boxed_slice()) as *mut u8 as usize; *field(obj, 0) = list_vtable(); - let mut st = ListState { pc: pc as usize, allocator: allocator as usize, refs: 1, chunks: Vec::new(), uma: Vec::new(), arena: Default::default() }; + let mut st = ListState { + pc: pc as usize, + allocator: allocator as usize, + refs: 1, + chunks: Vec::new(), + uma: Vec::new(), + arena: Default::default(), + retained_psos: HashMap::new(), + }; new_chunk(obj, &mut st); LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(obj, st); obj as *mut c_void @@ -881,12 +908,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // 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) { + let real = super::pso_async::resolve_wait_retained((*p).pc); + let real_ptr = real.ptr(); + if !super::real::is_translated_compute(real_ptr) { out.skipped_dispatches += 1; continue; } - let user_sgprs = super::real::pso_user_sgprs(real); + let user_sgprs = super::real::pso_user_sgprs(real_ptr); let inline = layout.as_ref().map_or(0, |l| inline_for(l, user_sgprs) 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() { @@ -898,7 +926,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { 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")?; // 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); + let own = super::real::pso_root_signature(real_ptr).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)) { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), @@ -909,10 +937,15 @@ pub unsafe fn close(obj: *mut c_void) -> Result { for k in 0..4 { list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va)); } - let raw = real as *mut c_void; + let raw = real_ptr as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); - super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; + if !st.retained_psos.contains_key(&real_ptr) { + if let Some(com) = real.clone().into_com() { + st.retained_psos.insert(real_ptr, com); + } + } + super::real::dispatch_chain::dispatch(&list, real_ptr, st.allocator, [x, y, z])?; out.dispatches += 1; } _ => out.skipped_dispatches += 1, diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..09b96ce518 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -95,13 +95,15 @@ 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 resolved_pso = super::pso_async::resolve_for_bind(pso); - let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); + let resolved_pso = super::pso_async::resolve_for_bind_retained(pso); + let resolved_ptr = resolved_pso.ptr(); + let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_ptr, 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)); + super::list_x::retain_pso(*ppv, resolved_pso); super::dred::reset(*ppv); if pso != 0 { - super::dred::mark_pipeline(*ppv, pso, resolved_pso); + super::dred::mark_pipeline(*ppv, pso, resolved_ptr); } } hr diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..96e361eb02 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -63,6 +63,7 @@ impl Held { } let (fence, value) = self.fences.get_mut(&key).unwrap(); if q.Signal(&*fence, *value + 1).is_err() { + self.fences.remove(&key); ok = false; break; } @@ -95,6 +96,23 @@ pub fn enabled() -> bool { /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); +fn ensure_thread() { + static THREAD: std::sync::Once = std::sync::Once::new(); + THREAD.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { + std::thread::sleep(TICK); + unsafe { drain_known(false) }; + }); + }); +} + +/// Queue `obj` for release on the background thread once all queues pass the current fence, +/// without spinning the caller thread. +pub unsafe fn hold_deferred(obj: usize) { + HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(obj); + ensure_thread(); +} + /// `res` (an adopted resource) holds one reference that is now this module's. With no work in /// flight it goes before this returns (the queues pass a fence value at once): a title that /// frees the memory under a resource right after its last `Release` finds it unpinned, as @@ -113,13 +131,18 @@ pub unsafe fn hold(res: usize) { // A thread of its own lets the held ones go: the title may release a resource and then // wait for its memory without another submit (an imported heap pins the pages under its // resources – unmapping them stood still while one was held "until the next submit"). - static THREAD: std::sync::Once = std::sync::Once::new(); - THREAD.call_once(|| { - let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { - std::thread::sleep(TICK); - unsafe { drain_known(false) }; - }); - }); + ensure_thread(); +} + +unsafe fn release_obj(obj: usize) { + let raw = obj as *mut c_void; + let release_fn = if super::real::is_adopted(raw) { + super::real::orig_fn(raw, 2) + } else { + *(*(raw as *const *const usize)).add(2) + }; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(release_fn); + f(raw); } /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the @@ -128,13 +151,7 @@ pub unsafe fn drain_known(seal_now: bool) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); - } - } + let mut queues = super::present::known_queue_refs(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); let gone = match HELD.lock().unwrap().as_mut() { @@ -142,12 +159,24 @@ pub unsafe fn drain_known(seal_now: bool) { None => return, }; // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); - f(res as *mut c_void); + for obj in gone { + release_obj(obj); } } +#[cfg(test)] +pub(super) fn forget_queue_for_test(queue: usize) { + if let Some(h) = HELD.lock().unwrap().as_mut() { + h.fences.remove(&queue); + } +} + +#[cfg(test)] +pub(super) fn is_held(obj: usize) -> bool { + let g = HELD.lock().unwrap(); + g.as_ref().is_some_and(|h| h.open.contains(&obj) || h.sealed.iter().any(|b| b.dead.contains(&obj))) +} + #[cfg(test)] mod tests { use super::*; @@ -208,4 +237,75 @@ mod tests { assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); assert!(held.is_empty()); } + + /// An unadopted COM object held until GPU retirement is released safely via vtable slot 2 + /// once the blocking queue passes its batch fence. + #[test] + fn unadopted_com_object_is_released_after_queue_retirement() { + use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; + use std::sync::Arc; + use windows::core::GUID; + + #[repr(C)] + struct TestComObj { + vt: *const [usize; 3], + refs: AtomicU32, + drops: Arc, + } + unsafe extern "system" fn qi(_: *mut c_void, _: *const GUID, out: *mut *mut c_void) -> i32 { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (&*(this as *const TestComObj)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let n = (&*(this as *const TestComObj)).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if n == 0 { + let obj = Box::from_raw(this as *mut TestComObj); + obj.drops.fetch_add(1, Ordering::AcqRel); + } + n + } + let vt: *const [usize; 3] = Box::leak(Box::new([qi as usize, add_ref as usize, release as usize])); + + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let queue: ID3D12CommandQueue = + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + + let drops = Arc::new(AtomicUsize::new(0)); + let obj = Box::into_raw(Box::new(TestComObj { + vt, + refs: AtomicU32::new(1), + drops: drops.clone(), + })) as usize; + assert!(!super::super::real::is_adopted(obj as *mut c_void)); + + let mut held = Held::default(); + held.open.push(obj); + let queues = [queue]; + assert!(held.drain(&queues, false).is_empty()); + assert_eq!(drops.load(Ordering::Acquire), 0); + + gate.Signal(1).unwrap(); + let start = Instant::now(); + let mut gone = Vec::new(); + while gone.is_empty() && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + gone = held.drain(&queues, false); + } + assert_eq!(gone, vec![obj]); + for raw in gone { + release_obj(raw); + } + assert_eq!(drops.load(Ordering::Acquire), 1); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..3faf49d70a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -614,6 +614,8 @@ struct ListState { last_queue: Option, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Retained COM pipeline resolved from `bound_pso`, in case `bound_pso` is released while bound. + bound_resolved: super::pso_async::Resolved, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -653,6 +655,8 @@ struct ListState { deferred: Option, /// on a title list's first segment: the allocator its deferred segments record on (the title's may be recording another list by the submit) own_alloc: Option, + /// Retained PC pipeline objects bound to this recording, dropped on Reset or Release. + retained_psos: HashMap, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -825,7 +829,16 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C } } super::alloc_pool::created_on(key, alloc, ty.0); - m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); + m.insert( + key, + ListState { + allocator: alloc, + list_type: Some(ty), + bound_pso: pso, + bound_resolved: super::pso_async::resolve_if_pending(pso), + ..Default::default() + }, + ); old }; drop(old); @@ -868,10 +881,22 @@ pub(super) fn on_release(list: usize) { } } +/// Keep a resolved PC pipeline alive until the command list is reset or released. +pub(super) fn retain_pso(list: *mut c_void, pso: super::pso_async::Resolved) { + let ptr = pso.ptr(); + let Some(com) = pso.into_com() else { return }; + if list.is_null() { + return; + } + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + m.entry(list as usize).or_default().retained_psos.entry(ptr).or_insert(com); +} + /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { super::title_textures::list_reset(list); - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + let old = if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); s.clear_sparse_writes(); @@ -882,7 +907,11 @@ pub(super) fn clear_segment_state(list: usize) { s.pred_in_state = false; s.bindings = Bindings::default(); s.deferred = None; - } + Some((std::mem::take(&mut s.retained_psos), std::mem::take(&mut s.bound_resolved))) + } else { + None + }; + drop(old); } #[cfg(test)] @@ -901,23 +930,37 @@ pub(super) fn on_allocator_release(alloc: usize) { } } -/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX` and `KickoffX`), -/// syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses native dynamic -/// depth bias. -pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { +/// Track `SetPipelineState` on a command list using the already-resolved PSO handle, retaining +/// resolved async pipelines until the command list is reset or released. +pub(super) unsafe fn on_set_pipeline_state_resolved(list: *mut c_void, pso: usize, resolved: &super::pso_async::Resolved) { let key = list as usize; - let sync_target = { + let resolved_ptr = resolved.ptr(); + let keep = resolved.has_com() || !resolved.is_settled(); + let (sync_target, unused_resolved) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO. - if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve(s.bound_pso) != pso { + let same_as_bound = s.bound_pso != 0 + && (pso == s.bound_pso + || s.bound_resolved.ptr() == pso + || (!s.bound_resolved.is_settled() && super::pso_async::resolve_if_pending(s.bound_pso).ptr() == pso)); + let next_bound = if keep { resolved.clone() } else { super::pso_async::Resolved::none() }; + let swapped = if !same_as_bound { s.bound_pso = pso; + Some(std::mem::replace(&mut s.bound_resolved, next_bound)) + } else if pso == s.bound_pso && resolved_ptr != s.bound_resolved.ptr() { + Some(std::mem::replace(&mut s.bound_resolved, next_bound)) + } else { + Some(next_bound) + }; + if let Some(com) = resolved.clone().into_com() { + s.retained_psos.entry(resolved_ptr).or_insert(com); } let effective = s.bound_pso; s.using_fallback_pso = false; let is_bundle = s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE); let info = if effective != 0 { device_x::base_depth_bias_info(effective) } else { None }; - if !is_bundle { + let sync = if !is_bundle { if let Some((true, static_bias)) = info { let target = s.depth_bias.unwrap_or(static_bias); s.pso_dirty = false; @@ -939,8 +982,10 @@ pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { DEPTH_BIAS_USED.store(true, Ordering::Release); } None - } + }; + (sync, swapped) }; + drop(unused_resolved); if let Some((target, has_override)) = sync_target { if try_native_depth_bias(list, target) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { @@ -955,13 +1000,21 @@ pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { } } +#[cfg(test)] +pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { + let resolved = super::pso_async::resolve_if_pending(pso); + on_set_pipeline_state_resolved(list, pso, &resolved); +} + /// Track `ClearState` on a command list: resets dynamic state and binds `pso`. pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { let key = list as usize; - let is_bundle = { + let resolved = super::pso_async::resolve_if_pending(pso); + let (old_bound, is_bundle) = { let mut g = LISTS.lock().unwrap(); if let Some(s) = g.get_or_insert_with(HashMap::new).get_mut(&key) { s.bound_pso = pso; + let old_bound = std::mem::replace(&mut s.bound_resolved, resolved); s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -970,11 +1023,12 @@ pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { s.depth_bounds = None; s.predication = None; s.bindings = Bindings::default(); - s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + (Some(old_bound), s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE)) } else { - false + (Some(resolved), false) } }; + drop(old_bound); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { if !static_bias.is_zero() && try_native_depth_bias(list, static_bias) { @@ -2750,7 +2804,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } None => None, }; - let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { + let (alloc, last_queue, bound_pso, bound_resolved, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { let mut g = LISTS.lock().unwrap(); let s = g.as_mut()?.get_mut(&(list as usize))?; if s.allocator == 0 { @@ -2763,6 +2817,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ s.allocator, s.last_queue, s.bound_pso, + s.bound_resolved.clone(), s.depth_bias, s.index_buffer, s.depth_bounds, @@ -2795,10 +2850,13 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { - 0 + super::pso_async::Resolved::none() } else { - super::pso_async::resolve(bound_pso) + // Keep the split nonwaiting so deferred dispatches do not block on still-building + // compute pipelines before `defer` returns (those wait at submit in `record_deferred`). + super::pso_async::resolve_cached_if_pending(bound_pso, &bound_resolved) }; + let init_ptr = init_pso.ptr(); let dev = device_of(list)?; let dev_raw = dev.as_raw() as usize; @@ -2806,7 +2864,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ if let Some(spare) = super::title_list::pop_spare(wrapper) { let ext_spare = *(spare as *const usize); let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| { - pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso) + pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_ptr) }); real::preserve_vtable(spare, ext_spare); if reset_hr >= 0 { @@ -2816,7 +2874,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } let next_pc = match next_pc { Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { + None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_ptr) { Some(p) => p, None => { static CREATE_ERR: AtomicU64 = AtomicU64::new(0); @@ -2828,10 +2886,15 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ // the next segment is a recording of its own (reset or made here, not through `cl_reset`) super::dred::reset(next_pc); - if init_pso != 0 { - super::dred::mark_pipeline(next_pc, bound_pso, init_pso); + if init_ptr != 0 { + super::dred::mark_pipeline(next_pc, bound_pso, init_ptr); } + let next_bound_resolved = if ty == D3D12_COMMAND_LIST_TYPE_COPY || bound_pso == 0 { + super::pso_async::Resolved::none() + } else { + init_pso.clone() + }; let old_next = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -2854,6 +2917,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ list_type: Some(ty), last_queue, bound_pso, + bound_resolved: next_bound_resolved, depth_bias, native_bias: DepthBias::ZERO, pso_dirty: false, @@ -2872,6 +2936,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ old }; drop(old_next); + retain_pso(next_pc, init_pso); super::title_textures::list_reset(next_pc as usize); super::bind::inherit_for_split(list, next_pc, alloc); restore_bindings(next_pc, &bindings, ty); @@ -3155,16 +3220,23 @@ pub(super) unsafe fn before_close(list: *mut c_void) { } } -/// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. +/// Clear active predication and retained pipeline state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { return; } - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.predication = None; - s.pred_in_state = false; - } + let clear_pred = PREDICATION_USED.load(Ordering::Acquire); + let old_psos = if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + if clear_pred { + s.predication = None; + s.pred_in_state = false; + } + Some((std::mem::take(&mut s.retained_psos), std::mem::take(&mut s.bound_resolved))) + } else { + None + }; + drop(old_psos); } /// Copy 8 predicate bytes from `(uma_buf, off)` into `pb` with exact barrier transitions and @@ -3263,7 +3335,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return; } let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); - let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { + let (alloc, queue, bound, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { if once(&NO_QUEUE, 4) { @@ -3296,8 +3368,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let cpu_writes = std::mem::take(&mut s.cpu_writes); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) + (s.allocator, q, (s.bound_pso, s.bound_resolved.clone()), s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) }; + let (bound_pso, bound_resolved) = bound; let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). @@ -3401,9 +3474,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let init_pso = super::pso_async::resolve_cached_for_bind(bound_pso, &bound_resolved); + let init_ptr = init_pso.ptr(); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { - pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) + pc:: i32>(target, PC_RESET)(target, pc_alloc, init_ptr) }); real::preserve_vtable(target, ext_closed); if reset_hr < 0 { @@ -3416,11 +3490,14 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. - if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + let old_psos = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))).map(|s| { s.native_bias = DepthBias::ZERO; s.using_fallback_pso = false; s.pso_dirty = false; - } + (std::mem::take(&mut s.retained_psos), std::mem::replace(&mut s.bound_resolved, init_pso.clone())) + }); + drop(old_psos); + retain_pso(target, init_pso); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; let mut applied_native = false; @@ -3509,11 +3586,12 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b s.pso_dirty = false; let restore = s.using_fallback_pso && s.bound_pso != 0; s.using_fallback_pso = false; - (if restore { Some(s.bound_pso) } else { None }, target != s.native_bias) + (if restore { Some((s.bound_pso, s.bound_resolved.clone())) } else { None }, target != s.native_bias) }; - if let Some(base) = need_restore_base { - let resolved = super::pso_async::resolve_for_bind(base); - pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some((base, saved)) = need_restore_base { + let resolved = super::pso_async::resolve_cached_for_bind(base, &saved); + pc::(this, PC_SET_PIPELINE_STATE)(this, resolved.ptr()); + retain_pso(this, resolved); } if !need_native_call { return; @@ -3542,7 +3620,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b let was_fallback = std::mem::take(&mut s.using_fallback_pso); s.pso_dirty = false; if (was_active || was_fallback) && s.bound_pso != 0 { - Some(s.bound_pso) + Some((s.bound_pso, s.bound_resolved.clone())) } else { None } @@ -3555,9 +3633,10 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b None } }; - if let Some(base) = restore { - let resolved = super::pso_async::resolve_for_bind(base); - pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some((base, saved)) = restore { + let resolved = super::pso_async::resolve_cached_for_bind(base, &saved); + pc::(this, PC_SET_PIPELINE_STATE)(this, resolved.ptr()); + retain_pso(this, resolved); } } @@ -3566,7 +3645,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { if !DEPTH_BIAS_USED.load(Ordering::Acquire) { return; } - let (bound_pso, bias) = { + let (bound_pso, bound_resolved, bias) = { let mut g = LISTS.lock().unwrap(); let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return; @@ -3575,17 +3654,17 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { return; } s.pso_dirty = false; - (s.bound_pso, s.depth_bias) + (s.bound_pso, s.bound_resolved.clone(), s.depth_bias) }; if bound_pso == 0 { return; } - let (target, is_fallback) = match bias { + let (resolved, is_fallback) = match bias { Some(b) => { static MISS: AtomicU64 = AtomicU64::new(0); let Some(dev) = device_of(list) else { return }; match device_x::depth_bias_pso(dev.as_raw(), bound_pso, b) { - Some(derived) => (derived, true), + Some(derived) => (super::pso_async::resolve_for_bind_retained(derived), true), None => { if once(&MISS, 4) { crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – could not derive pipeline for {bound_pso:#x}, using base pipeline"); @@ -3594,10 +3673,10 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { } } } - None => (bound_pso, false), + None => (super::pso_async::resolve_cached_for_bind(bound_pso, &bound_resolved), false), }; - let resolved = super::pso_async::resolve_for_bind(target); - pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + pc::(list, PC_SET_PIPELINE_STATE)(list, resolved.ptr()); + retain_pso(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; } @@ -4059,11 +4138,11 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); - let resolved = super::pso_async::resolve_for_bind(pso); + let resolved = super::pso_async::resolve_for_bind_retained(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { - pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved) + pc:: i32>(this, PC_RESET)(this, pc_alloc, resolved.ptr()) }); real::preserve_vtable(this, ext); if hr < 0 { @@ -4072,11 +4151,12 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 reset_copy_scratch(this); reset_own_alloc(this); - let is_bundle = { + let (old_psos, is_bundle) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); s.allocator = alloc; s.bound_pso = pso; + let old_bound = std::mem::replace(&mut s.bound_resolved, resolved.clone()); s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -4092,8 +4172,10 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); - s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) + ((std::mem::take(&mut s.retained_psos), old_bound), s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE)) }; + drop(old_psos); + retain_pso(this, resolved); super::title_textures::list_reset(this as usize); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { @@ -7008,28 +7090,71 @@ mod tests { use windows::Win32::Graphics::Dxgi::*; unsafe { - let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { - let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); - if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - } - } - let dev = dev.unwrap(); + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no DXGI factory"); + return; + }; + let warp_dev = || { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0).ok().or_else(|| { + let mut dev = None; + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + dev + }) + }; + let dev = if crate::gpu::adapter::Selector::from_env_or("auto") == crate::gpu::adapter::Selector::Warp { + warp_dev() + } else { + crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) + .ok() + .or_else(|| { + let mut dev = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?; + dev + }) + .or_else(warp_dev) + }; + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - let standin = 0x7E57_D001usize; + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .unwrap(); + let cs = real::dummy_cs_bytecode(); + let mut pso_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 standin_pso: ID3D12PipelineState = dev.CreateComputePipelineState(&pso_desc).unwrap(); + std::mem::ManuallyDrop::drop(&mut pso_desc.pRootSignature); + real::adopt(standin_pso.as_raw(), real::Kind::PipelineState); + let standin = standin_pso.as_raw() as usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + struct BuildGuard; + impl Drop for BuildGuard { + fn drop(&mut self) { + BUILD.store(true, Ordering::Release); + } + } + let _build_guard = BuildGuard; pso_async::submit( standin, true, Box::new(|| { let t = Instant::now(); - while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(60) { std::thread::sleep(Duration::from_millis(5)); } 0 @@ -7038,9 +7163,19 @@ mod tests { let pc0 = raw.into_raw(); real::adopt(pc0, real::Kind::CommandList); on_create(pc0, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); - bind::reset(pc0, alloc.as_raw() as usize, standin); + bind::reset(pc0, alloc.as_raw() as usize, 0); let wrap = title_list::wrap(pc0); + let t_set = Instant::now(); + bind::set_pipeline_state(pc0, standin as *mut c_void); + assert!(t_set.elapsed() < Duration::from_millis(700), "SetPipelineState waited for the build ({:?})", t_set.elapsed()); + assert_eq!( + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(pc0 as usize))).map(|s| s.bound_pso), + Some(standin), + "SetPipelineState must set non-zero list_x::bound_pso for mid-list split" + ); + drop(standin_pso); + const DISPATCHES: usize = 210; let mut segs = vec![pc0]; for n in 1..=DISPATCHES { @@ -7051,6 +7186,11 @@ mod tests { assert!(title_list::push_segments(wrap, &mut segs)); } assert_eq!(segs.len(), 1 + 2 * DISPATCHES, "the list before each dispatch, the dispatch, the list after it"); + assert_eq!( + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(*segs.last().unwrap() as usize))).map(|s| s.bound_pso), + Some(standin), + "continuation segment must preserve bound_pso across mid-list split" + ); assert!(pso_async::is_pending(standin)); let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..8d82ea37ec 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -297,6 +297,35 @@ pub fn known_queues() -> Vec { QUEUES.lock().unwrap().clone() } +/// Retained COM handles for the queues the title submitted work to. +pub(super) unsafe fn known_queue_refs() -> Vec { + QUEUES + .lock() + .unwrap() + .iter() + .filter_map(|&raw| { + let raw = raw as *mut c_void; + ID3D12CommandQueue::from_raw_borrowed(&raw).cloned() + }) + .collect() +} + +#[cfg(test)] +pub(super) unsafe fn forget_queue_for_test(queue: usize) { + let removed = { + let mut q = QUEUES.lock().unwrap(); + if let Some(pos) = q.iter().position(|&x| x == queue) { + Some(q.swap_remove(pos)) + } else { + None + } + }; + if let Some(raw) = removed { + release(raw); + } + super::late_release::forget_queue_for_test(queue); +} + static EXECUTES: AtomicU64 = AtomicU64::new(0); /// (PresentX calls, ExecuteCommandLists calls) so far diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..aa5f76f154 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -11,24 +11,28 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +struct State { + done: bool, + orphan: bool, + released: bool, + /// the real pipeline state (raw pointer), 0 while building or when building failed + real: usize, + /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself + driver: usize, +} + 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, - /// the real pipeline state (raw pointer), 0 while building or when building failed - real: AtomicUsize, - /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself - driver: AtomicUsize, - done: Mutex, + state: Mutex, cv: Condvar, compute: bool, /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) used: std::sync::atomic::AtomicBool, - /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it @@ -114,6 +118,21 @@ impl Pending { used::note(self.key); } } + + /// Mark the stand-in released under `st`, take its built pipeline if done (or mark it + /// orphaned so any worker drops its result), and wake waiters. + fn finish_release(&self, st: &mut State) -> (bool, usize) { + st.released = true; + let real = if st.done { + std::mem::take(&mut st.real) + } else { + // the worker stores its result into a Pending nobody will read: mark it orphaned + st.orphan = true; + 0 + }; + self.cv.notify_all(); + (st.orphan, real) + } } /// stand-in handed to the title → its real pipeline @@ -127,16 +146,16 @@ fn complete(p: &Pending, real: usize) { BUILT.fetch_add(1, Ordering::Relaxed); } let orphan = { - let mut done = p.done.lock().unwrap(); - let orphan = p.orphan.load(Ordering::Acquire); + let mut st = p.state.lock().unwrap(); + let orphan = st.orphan; if !orphan { - p.real.store(real, Ordering::Release); + st.real = real; } - *done = true; + st.done = true; p.cv.notify_all(); orphan }; - // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) + // outside `state`: the Release override takes PENDING (`counts` takes PENDING, then `state`) if orphan { release(real); } @@ -281,8 +300,8 @@ fn drop_unstarted_job(p: &Pending) { let job = p.job.lock().unwrap().take(); if let Some(job) = job { { - let mut done = p.done.lock().unwrap(); - *done = true; + let mut st = p.state.lock().unwrap(); + st.done = true; p.cv.notify_all(); } drop(job); @@ -319,7 +338,7 @@ fn enqueue(p: Arc) { fn build_queued(p: &Arc) { // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { + if p.state.lock().unwrap().orphan { drop_unstarted_job(p); return; } @@ -359,8 +378,28 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { /// Release a pipeline state XCL owns (raw pointer, 0 = none). pub fn release(p: usize) { - if p != 0 { - unsafe { drop(::from_raw(p as *mut std::ffi::c_void)) }; + if p == 0 { + return; + } + unsafe { + if !is_com_pso(p) { + return; + } + if super::late_release::enabled() && !super::real::is_adopted(p as *mut std::ffi::c_void) { + let raw = p as *mut std::ffi::c_void; + let vt = *(raw as *const *const usize); + let add: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = std::mem::transmute(*vt.add(1)); + let rel: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = std::mem::transmute(*vt.add(2)); + if add(raw) == 2 { + rel(raw); + super::late_release::hold_deferred(p); + return; + } + rel(raw); + rel(raw); + return; + } + drop(::from_raw(p as *mut std::ffi::c_void)); } } @@ -389,14 +428,11 @@ 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), - real: AtomicUsize::new(0), - driver: AtomicUsize::new(0), - done: Mutex::new(false), + state: Mutex::new(State { done: false, orphan: false, released: false, real: 0, driver: 0 }), cv: Condvar::new(), compute, key, used: Default::default(), - orphan: Default::default(), late: Default::default(), spared: Default::default(), demand: Default::default(), @@ -536,7 +572,7 @@ fn preload() -> Option<&'static Preload> { } }; // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { + if p.state.lock().unwrap().orphan { drop_unstarted_job(&p); continue; } @@ -1022,16 +1058,255 @@ mod used_tests { let _ = released(standin); } } + + #[test] + fn concurrent_resolve_retained_and_release_never_exposes_freed_pipeline() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::ffi::c_void; + use std::sync::atomic::{AtomicU32, AtomicUsize}; + use std::sync::Barrier; + use windows::core::GUID; + + #[repr(C)] + struct TestComPso { + vt: *const [usize; 3], + refs: AtomicU32, + drops: Arc, + } + unsafe extern "system" fn qi(_: *mut c_void, _: *const GUID, out: *mut *mut c_void) -> i32 { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let prev = (&*(this as *const TestComPso)).refs.fetch_add(1, Ordering::AcqRel); + assert!(prev >= 1, "AddRef after final release"); + prev + 1 + } + unsafe extern "system" fn dec_only(this: *mut c_void) -> u32 { + let prev = (&*(this as *const TestComPso)).refs.fetch_sub(1, Ordering::AcqRel); + assert!(prev >= 1, "double Release"); + let n = prev - 1; + if n == 0 { + let b = Box::from_raw(this as *mut TestComPso); + b.drops.fetch_add(1, Ordering::AcqRel); + } + n + } + unsafe extern "system" fn pso_release_sim(this: *mut c_void) -> u32 { + let probe = || -> (bool, bool, u32) { + let n = dec_only(this); + (n == 0, false, n) + }; + if let Some((n, _, real)) = try_release_standin(this as usize, probe) { + if n == 0 { + release(real); + } + return n; + } + let (is_zero, _, n) = probe(); + if is_zero { + release(released(this as usize)); + } + n + } + struct UnstartedReal(usize); + impl Drop for UnstartedReal { + fn drop(&mut self) { + if self.0 != 0 { + unsafe { dec_only(self.0 as *mut c_void) }; + } + } + } + let vt: *const [usize; 3] = Box::leak(Box::new([qi as usize, add_ref as usize, pso_release_sim as usize])); + + let total_drops = Arc::new(AtomicUsize::new(0)); + let iterations = 80usize; + for i in 0..iterations { + let standin_raw = Box::into_raw(Box::new(TestComPso { + vt, + refs: AtomicU32::new(1), + drops: total_drops.clone(), + })) as usize; + let real_raw = Box::into_raw(Box::new(TestComPso { + vt, + refs: AtomicU32::new(1), + drops: total_drops.clone(), + })) as usize; + let real_guard = UnstartedReal(real_raw); + let build_now = i % 2 == 0; + submit(standin_raw, i % 3 == 0, Box::new(move || { + let ptr = real_guard.0; + std::mem::forget(real_guard); + ptr + })); + if build_now { + let _ = resolve_wait_retained(standin_raw); + } + let p = entry(standin_raw).expect("tracked standin"); + + let barrier = Arc::new(Barrier::new(5)); + let mut readers = Vec::with_capacity(4); + for t in 0..4 { + let b = barrier.clone(); + let p = p.clone(); + readers.push(std::thread::spawn(move || { + b.wait(); + let res = match t % 2 { + 0 => resolve_pending(&p, standin_raw), + _ => resolve_wait_for_pending(&p, standin_raw, None), + }; + if let Some(com) = res.into_com() { + // Calling through the retained COM handle must still find a live object. + let live = unsafe { + use windows::core::Interface; + let ptr = com.as_raw(); + let prev = (&*(ptr as *const TestComPso)).refs.load(Ordering::Acquire); + assert!(prev >= 1, "retained COM object was prematurely released"); + com + }; + drop(live); + } + })); + } + barrier.wait(); + unsafe { + drop(::from_raw( + standin_raw as *mut c_void, + )); + } + for h in readers { + h.join().unwrap(); + } + } + + // Wait for any background orphan jobs to finish releasing `real`. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let expected = iterations * 2; + while total_drops.load(Ordering::Acquire) < expected && std::time::Instant::now() < deadline { + unsafe { crate::hle::d3d12x::late_release::drain_known(true) }; + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert_eq!(total_drops.load(Ordering::Acquire), expected, "every stand-in and real PSO must be released cleanly"); + } } fn entry(pso: usize) -> Option> { PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() } +/// Pipeline pointer resolved from a stand-in, holding a COM reference when `ptr` points to a +/// live `ID3D12PipelineState` / stand-in COM object tracked by `pso_async`. +#[derive(Clone, Default)] +pub struct Resolved { + ptr: usize, + com: Option, + settled: bool, +} + +impl Resolved { + pub const fn none() -> Self { + Self { ptr: 0, com: None, settled: false } + } + + pub const fn unretained_settled(ptr: usize) -> Self { + Self { ptr, com: None, settled: true } + } + + pub fn ptr(&self) -> usize { + self.ptr + } + + pub fn has_com(&self) -> bool { + self.com.is_some() + } + + pub fn is_settled(&self) -> bool { + self.settled + } + + pub fn into_com(self) -> Option { + self.com + } +} + +/// Whether `pso` is currently registered as an async/lazy pending pipeline stand-in. +pub fn is_tracked(pso: usize) -> bool { + entry(pso).is_some() +} + +fn resolve_cached_with(pso: usize, saved: &Resolved, resolve: fn(usize) -> Resolved) -> Resolved { + if !is_tracked(pso) && saved.ptr() != 0 && (saved.ptr() != pso || saved.has_com()) { + return saved.clone(); + } + let resolved = resolve(pso); + if resolved.ptr() == 0 && saved.ptr() != 0 { + return saved.clone(); + } + resolved +} + +/// Resolve `pso`, reusing `saved` if `pso` was already resolved and released from `PENDING` +/// (or is already COM-retained by `saved`). +pub fn resolve_cached_wait(pso: usize, saved: &Resolved) -> Resolved { + resolve_cached_with(pso, saved, resolve_wait_retained) +} + +/// `resolve_for_bind_retained`, reusing `saved` if `pso` was already resolved and released. +pub fn resolve_cached_for_bind(pso: usize, saved: &Resolved) -> Resolved { + resolve_cached_with(pso, saved, resolve_for_bind_retained) +} + +/// `resolve_if_pending`, reusing `saved` if `pso` was already resolved and released. +pub fn resolve_cached_if_pending(pso: usize, saved: &Resolved) -> Resolved { + resolve_cached_with(pso, saved, resolve_if_pending) +} + +/// Whether `ptr` points to a readable COM object whose vtable has readable AddRef/Release slots. +unsafe fn is_com_pso(ptr: usize) -> bool { + if ptr < 0x1_0000 || (ptr & (std::mem::align_of::() - 1)) != 0 || !crate::gpu::shader::readable(ptr, std::mem::size_of::()) { + return false; + } + let vt = *(ptr as *const usize); + if !crate::gpu::shader::readable(vt, 3 * std::mem::size_of::()) { + return false; + } + let slots = std::slice::from_raw_parts(vt as *const usize, 3); + crate::gpu::shader::readable(slots[1], 1) && crate::gpu::shader::readable(slots[2], 1) +} + +/// Retain a COM reference on `ptr` if it points to a live COM object with an `IUnknown` vtable. +/// Synthetic non-pointer test addresses (e.g. `0x1234`) stay unretained (`None`). +unsafe fn retain_com(ptr: usize) -> Option { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; + if !is_com_pso(ptr) { + return None; + } + let raw = ptr as *mut std::ffi::c_void; + ID3D12PipelineState::from_raw_borrowed(&raw).cloned() +} + +fn resolve_from_state(st: &State, pso: usize) -> Resolved { + if st.released { + return Resolved::none(); + } + let target = if st.real != 0 { + st.real + } else if st.driver != 0 { + st.driver + } else { + pso + }; + Resolved { ptr: target, com: unsafe { retain_com(target) }, settled: st.done } +} + impl Pending { /// What a bind of the stand-in `pso` gives the driver while the pipeline is not built. + #[cfg(test)] fn stand(&self, pso: usize) -> usize { - match self.driver.load(Ordering::Acquire) { + match self.state.lock().unwrap().driver { 0 => pso, d => d, } @@ -1042,59 +1317,95 @@ impl Pending { /// Told before the title has the stand-in. pub fn shared(standin: usize, driver: usize) { if let Some(p) = entry(standin) { - p.driver.store(driver, Ordering::Release); + p.state.lock().unwrap().driver = driver; + } +} + +/// Resolve a pending pipeline if tracked, retaining its COM reference before `released()` can +/// drop it. When `pso` is not in `PENDING`, returns `pso` unretained without touching it. +pub fn resolve_if_pending(pso: usize) -> Resolved { + let Some(p) = entry(pso) else { + return Resolved::unretained_settled(pso); + }; + p.note_use(); + resolve_pending(&p, pso) +} + +fn resolve_pending(p: &Arc, pso: usize) -> Resolved { + let st = p.state.lock().unwrap(); + let out = resolve_from_state(&st, pso); + let should_enqueue = !st.done && !st.released && st.real == 0; + drop(st); + if should_enqueue && !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); } + out } /// The pipeline to use for `pso` now: the real one once built, else the stand-in's driver /// pipeline (`pso` itself when it is one). pub fn resolve(pso: usize) -> usize { - let Some(p) = entry(pso) else { return pso }; - p.note_use(); - match p.real.load(Ordering::Acquire) { - 0 => { - // a lazy one is wanted now: to the workers - let stand = p.stand(pso); - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p); - } - stand - } - r => r, - } + resolve_if_pending(pso).ptr() } /// `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). pub fn resolve_wait(pso: usize) -> usize { - resolve_wait_for(pso, wait_budget()) + resolve_wait_with(pso, wait_budget()).ptr() } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +/// `resolve_wait`, returning a retained COM pipeline handle that outlives concurrent `released()`. +pub fn resolve_wait_retained(pso: usize) -> Resolved { + resolve_wait_with(pso, wait_budget()) +} + +#[cfg(test)] fn resolve_wait_for(pso: usize, budget: Option) -> usize { - let Some(p) = entry(pso) else { return pso }; + resolve_wait_with(pso, budget).ptr() +} + +/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +fn resolve_wait_with(pso: usize, budget: Option) -> Resolved { + let Some(p) = entry(pso) else { + return Resolved::unretained_settled(pso); + }; p.note_use(); + resolve_wait_for_pending(&p, pso, budget) +} + +fn resolve_wait_for_pending(p: &Arc, pso: usize, budget: Option) -> Resolved { if p.spared.load(Ordering::Acquire) { - return resolve_spared(&p, pso); + return resolve_spared(p, pso); } // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.done.lock().unwrap()).then(Held::new); + let _held = (!p.state.lock().unwrap().done).then(Held::new); if let Some(budget) = budget { - return resolve_within(&p, pso, budget); + return resolve_within(p, pso, budget); } let job = p.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + let already_released = { + let mut st = p.state.lock().unwrap(); + if st.released { + st.done = true; + p.cv.notify_all(); + true + } else { + false + } + }; + if already_released { + drop(job); + } else { + complete(p, job()); + } } p.want(); - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); - } - match p.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, + let mut st = p.state.lock().unwrap(); + while !st.done && !st.released { + st = p.cv.wait(st).unwrap(); } + resolve_from_state(&st, pso) } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until @@ -1109,33 +1420,34 @@ fn wait_budget() -> Option { /// `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 { - let built = |p: &Pending| match p.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, - }; - if *p.done.lock().unwrap() { - return built(p); +fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> Resolved { + { + let st = p.state.lock().unwrap(); + if st.done || st.released { + return resolve_from_state(&st, pso); + } } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } if p.late.load(Ordering::Acquire) { - return p.stand(pso); + let st = p.state.lock().unwrap(); + return resolve_from_state(&st, pso); } p.want(); - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); + let (st, _) = p.cv.wait_timeout_while(p.state.lock().unwrap(), budget, |st| !st.done && !st.released).unwrap(); + if st.done || st.released { + return resolve_from_state(&st, pso); } - drop(done); + drop(st); 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); } - p.stand(pso) + let st = p.state.lock().unwrap(); + resolve_from_state(&st, pso) } /// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing @@ -1162,54 +1474,108 @@ pub fn image_only(standin: usize) { /// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built, /// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not /// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. -fn resolve_spared(p: &Arc, pso: usize) -> usize { - match p.real.load(Ordering::Acquire) { - 0 => { - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p.clone()); - } - if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { - static N: AtomicUsize = AtomicUsize::new(0); - let n = N.fetch_add(1, Ordering::Relaxed); - if n < 16 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); - } - } - p.stand(pso) +fn resolve_spared(p: &Arc, pso: usize) -> Resolved { + { + let st = p.state.lock().unwrap(); + if st.real != 0 || st.done || st.released { + return resolve_from_state(&st, pso); } - r => r, } + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + let st = p.state.lock().unwrap(); + if !st.done && !st.released && !p.late.swap(true, Ordering::AcqRel) { + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); + } + } + resolve_from_state(&st, pso) } /// For binding: compute pipelines are waited for, graphics ones are not. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), - Some(_) => resolve(pso), + Some(p) if p.compute => { + p.note_use(); + resolve_wait_for_pending(&p, pso, wait_budget()).ptr() + } + Some(p) => { + p.note_use(); + resolve_pending(&p, pso).ptr() + } None => pso, } } +/// `resolve_for_bind`, returning a retained COM pipeline handle that outlives concurrent `released()`. +pub fn resolve_for_bind_retained(pso: usize) -> Resolved { + match entry(pso) { + Some(p) if p.compute => { + p.note_use(); + resolve_wait_for_pending(&p, pso, wait_budget()) + } + Some(p) => { + p.note_use(); + resolve_pending(&p, pso) + } + None => Resolved::unretained_settled(pso), + } +} + /// The title released stand-in `pso` for good: forget it (its address may come back for /// another object) and return its real pipeline to release (0: none, or still being built – /// the worker's result is then released when it arrives). pub fn released(pso: usize) -> usize { let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; - { - let done = p.done.lock().unwrap(); - if *done { - return p.real.swap(0, Ordering::AcqRel); + let (orphan, real) = { + let mut st = p.state.lock().unwrap(); + p.finish_release(&mut st) + }; + if orphan { + drop_unstarted_job(&p); + } + real +} + +/// Retire a tracked adopted stand-in under its `Pending::state` lock, so `resolve*_retained` +/// cannot `AddRef` `pso` concurrently with its final COM reference dropping to zero. +pub fn try_release_standin( + pso: usize, + probe: impl FnOnce() -> (bool, bool, u32), +) -> Option<(u32, bool, usize)> { + let p = entry(pso)?; + let (held, orphan, real) = { + let mut st = p.state.lock().unwrap(); + if st.released { + return None; + } + let (is_zero, held, n) = probe(); + if !is_zero { + return Some((n, false, 0)); + } + let (orphan, real) = p.finish_release(&mut st); + (held, orphan, real) + }; + if let Some(m) = PENDING.lock().unwrap().as_mut() { + if m.get(&pso).is_some_and(|cur| Arc::ptr_eq(cur, &p)) { + m.remove(&pso); } - // the worker stores its result into a Pending nobody will read: mark it orphaned - p.orphan.store(true, Ordering::Release); } - drop_unstarted_job(&p); - 0 + if orphan { + drop_unstarted_job(&p); + } + Some((0, held, real)) } /// `pso` is a stand-in whose real pipeline is still being built. pub fn is_pending(pso: usize) -> bool { - entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) + entry(pso).is_some_and(|p| { + let st = p.state.lock().unwrap(); + !st.done && !st.released + }) } /// One of the title's threads is about to wait for `pso`. @@ -1230,6 +1596,13 @@ pub fn need_by_submit(pso: usize) { /// (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()); + let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| { + m.values() + .filter(|p| { + let st = p.state.lock().unwrap(); + !st.done && !st.released + }) + .count() + }); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..58e29491b2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1716,9 +1716,38 @@ pub(super) fn standin_released(pso: usize) { /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_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); - if n == 0 { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let probe = || -> (bool, bool, u32) { + if super::late_release::enabled() { + if add(this) == 2 { + f(this); + (true, true, 0) + } else { + f(this); + let n = f(this); + (n == 0, false, n) + } + } else { + let n = f(this); + (n == 0, false, n) + } + }; + if let Some((n, held, real)) = super::pso_async::try_release_standin(this as usize, probe) { + if n == 0 { + forget_pso(this as usize); + if held { + super::late_release::hold_deferred(this as usize); + } + super::pso_async::release(real); + } + return n; + } + let (is_zero, held, n) = probe(); + if is_zero { forget_pso(this as usize); + if held { + super::late_release::hold_deferred(this as usize); + } super::pso_async::release(super::pso_async::released(this as usize)); } n @@ -2982,14 +3011,16 @@ 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 resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; - let hr = f(this, allocator, resolved); + let resolved = super::pso_async::resolve_for_bind_retained(initial_state as usize); + let resolved_ptr = resolved.ptr(); + let hr = f(this, allocator, resolved_ptr as *mut c_void); preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); + super::list_x::retain_pso(this, resolved); super::dred::reset(this); if !initial_state.is_null() { - super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); + super::dred::mark_pipeline(this, initial_state as usize, resolved_ptr); } } hr @@ -3888,14 +3919,36 @@ static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { - let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + let empty = { + let g = PSO_USER_SGPRS.lock().unwrap(); + let Some(m) = g.as_ref() else { return None }; + if let Some(&v) = m.get(&pso) { + return Some(v); + } + m.is_empty() + }; + if empty { + return None; + } + let pso = super::pso_async::resolve_if_pending(pso); + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso.ptr()).copied() } /// The root signature a translated pipeline state was created with. pub fn pso_root_signature(pso: usize) -> Option { - let pso = super::pso_async::resolve(pso); - PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() + let empty = { + let g = PSO_RS.lock().unwrap(); + let Some(m) = g.as_ref() else { return None }; + if let Some(&v) = m.get(&pso) { + return Some(v); + } + m.is_empty() + }; + if empty { + return None; + } + let pso = super::pso_async::resolve_if_pending(pso); + PSO_RS.lock().unwrap().as_ref()?.get(&pso.ptr()).copied() } /// ABI root signatures with static samplers, by sampler set (owned here, never released). @@ -5793,8 +5846,19 @@ static TWO_PASS: Mutex>>> = Mut /// The compute pass of a pipeline state XCL built from console MS / GS code. pub fn two_pass_of(pso: usize) -> Option> { - let pso = super::pso_async::resolve(pso); - TWO_PASS.lock().unwrap().as_ref()?.get(&pso).cloned() + let empty = { + let g = TWO_PASS.lock().unwrap(); + let Some(m) = g.as_ref() else { return None }; + if let Some(tp) = m.get(&pso) { + return Some(tp.clone()); + } + m.is_empty() + }; + if empty { + return None; + } + let pso = super::pso_async::resolve_if_pending(pso); + TWO_PASS.lock().unwrap().as_ref()?.get(&pso.ptr()).cloned() } pub fn two_pass_count() -> usize { @@ -6948,10 +7012,12 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); - f(this, bound as *mut c_void); - super::dred::mark_pipeline(this, pso as usize, bound); - super::list_x::on_set_pipeline_state(this, pso as usize); + let bound = super::pso_async::resolve_if_pending(pso as usize); + let bound_ptr = bound.ptr(); + f(this, bound_ptr as *mut c_void); + super::dred::mark_pipeline(this, pso as usize, bound_ptr); + super::list_x::on_set_pipeline_state_resolved(this, pso as usize, &bound); + super::bind::note_resolved(this, pso as usize, &bound); } /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). @@ -6965,13 +7031,16 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); - f(this, bound as *mut c_void); + let bound = super::pso_async::resolve_for_bind_retained(pso as usize); + let bound_ptr = bound.ptr(); + f(this, bound_ptr as *mut c_void); if !pso.is_null() { - super::dred::mark_pipeline(this, pso as usize, bound); + super::dred::mark_pipeline(this, pso as usize, bound_ptr); } super::list_x::on_clear_state(this, pso as usize); super::bind::clear_state(this, pso as usize); + super::bind::note_resolved(this, pso as usize, &bound); + super::list_x::retain_pso(this, bound); } unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { @@ -7860,6 +7929,329 @@ mod readback_routing_tests { } } +#[cfg(test)] +mod async_pso_lifetime_tests { + use super::*; + + unsafe fn setup_test_device() -> Option<(ID3D12Device, ID3D12RootSignature)> { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let warp_dev = || { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0).ok() + }; + let dev = if crate::gpu::adapter::Selector::from_env_or("auto") == crate::gpu::adapter::Selector::Warp { + warp_dev()? + } else { + crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0).ok().or_else(warp_dev)? + }; + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).ok()?; + let ser = ser?; + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())) + .ok()?; + Some((dev, rs)) + } + + unsafe fn make_compute_pso(dev: &ID3D12Device, rs: &ID3D12RootSignature, cs: &[u8]) -> 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 + } + + #[test] + fn async_pso_stays_alive_across_standin_release_while_recorded_on_command_list() { + unsafe { + let Some((dev, rs)) = setup_test_device() else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + let cs = dummy_cs_bytecode(); + let standin_pso = make_compute_pso(&dev, &rs, cs); + let real_pso = make_compute_pso(&dev, &rs, cs); + adopt(standin_pso.as_raw(), Kind::PipelineState); + adopt(real_pso.as_raw(), Kind::PipelineState); + + let standin_raw = standin_pso.as_raw() as usize; + let real_raw = real_pso.into_raw() as usize; + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(real_raw); + super::super::pso_async::submit(standin_raw, true, Box::new(move || real_raw)); + assert_eq!(super::super::pso_async::resolve_wait(standin_raw), real_raw); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).expect("list"); + let list_raw = list.as_raw(); + adopt(list_raw, Kind::CommandList); + super::super::list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + // Bind standin while the list is open; cl_set_pipeline_state resolves standin -> real_raw. + cl_set_pipeline_state(list_raw, standin_raw as *mut c_void); + + // Title releases the stand-in while the open recording still references `real_raw`. + drop(standin_pso); + assert!( + is_translated_compute(real_raw), + "resolved async PSO must stay alive while still bound on an open command list" + ); + + // Releasing the command list drops its retained reference and cleans up `real_raw`. + list.Close().expect("close"); + drop(list); + assert!(!is_translated_compute(real_raw), "real PSO must be released once the command list ends"); + } + } + + #[test] + fn async_pso_stays_alive_through_command_list_reset_and_gpu_retirement() { + struct QueueGateGuard { + gate: ID3D12Fence, + queue: usize, + } + impl Drop for QueueGateGuard { + fn drop(&mut self) { + unsafe { + let _ = self.gate.Signal(1); + super::super::present::forget_queue_for_test(self.queue); + super::super::late_release::drain_known(true); + } + } + } + + unsafe { + let Some((dev, rs)) = setup_test_device() else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + let cs = dummy_cs_bytecode(); + let queue: ID3D12CommandQueue = + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).expect("queue"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + queue.Wait(&gate, 1).expect("wait"); + let _guard = QueueGateGuard { gate: gate.clone(), queue: queue.as_raw() as usize }; + super::super::present::note_execute(queue.as_raw(), &[]); + + let standin_pso = make_compute_pso(&dev, &rs, cs); + let real_pso = make_compute_pso(&dev, &rs, cs); + adopt(standin_pso.as_raw(), Kind::PipelineState); + adopt(real_pso.as_raw(), Kind::PipelineState); + + let standin_raw = standin_pso.as_raw() as usize; + let real_raw = real_pso.into_raw() as usize; + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(real_raw); + super::super::pso_async::submit(standin_raw, true, Box::new(move || real_raw)); + assert_eq!(super::super::pso_async::resolve_wait(standin_raw), real_raw); + + let alloc1: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc1"); + let alloc2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc2"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc1, None).expect("list"); + let list_raw = list.as_raw(); + adopt(list_raw, Kind::CommandList); + super::super::list_x::on_create(list_raw, alloc1.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + cl_set_pipeline_state(list_raw, standin_raw as *mut c_void); + list.Close().expect("close"); + let cl: ID3D12CommandList = list.cast().expect("cast ID3D12CommandList"); + let lists = [Some(cl)]; + queue.ExecuteCommandLists(&lists); + + // Title drops the stand-in while the command list still retains `real_raw`. + drop(standin_pso); + assert!(is_translated_compute(real_raw), "retained by open/recorded command list"); + assert!(!super::super::late_release::is_held(real_raw), "not yet in late_release while list holds a ref"); + + // Resetting the command list releases its retained ref to `real_raw`, transferring the final + // ref into `late_release` until the queued GPU work retires past `gate`. + list.Reset(&alloc2, None).expect("reset"); + assert!(!is_translated_compute(real_raw)); + if super::super::late_release::enabled() { + assert!( + super::super::late_release::is_held(real_raw), + "final PSO ref must stay held until GPU queue retires" + ); + } + + gate.Signal(1).expect("signal gate"); + let start = std::time::Instant::now(); + while super::super::late_release::is_held(real_raw) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + super::super::late_release::drain_known(false); + } + assert!(!super::super::late_release::is_held(real_raw), "late_release must drain once queue retires"); + + list.Close().expect("close after reset"); + drop(lists); + drop(list); + } + } + + #[test] + fn shell_standin_resolved_pso_stays_alive_when_shell_released_after_bind() { + unsafe { + let Some((dev, rs)) = setup_test_device() else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + let cs = dummy_cs_bytecode(); + let driver_pso = make_compute_pso(&dev, &rs, cs); + let real_pso = make_compute_pso(&dev, &rs, cs); + adopt(real_pso.as_raw(), Kind::PipelineState); + + let key = super::super::standin::Key { + device: dev.as_raw() as usize, + root_signature: rs.as_raw() as usize, + kind: 1, + state: b"shell_standin_resolved_pso_test".to_vec(), + }; + let (shell_ptr, driver_raw) = + super::super::standin::shell(key, || Ok(driver_pso.into_raw() as usize)).expect("standin::shell"); + let shell_pso = ID3D12PipelineState::from_raw(shell_ptr); + + let shell_raw = shell_ptr as usize; + let real_raw = real_pso.into_raw() as usize; + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(real_raw); + super::super::pso_async::submit(shell_raw, true, Box::new(move || real_raw)); + super::super::pso_async::shared(shell_raw, driver_raw); + assert_eq!(super::super::pso_async::resolve_wait(shell_raw), real_raw); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).expect("list"); + let list_raw = list.as_raw(); + adopt(list_raw, Kind::CommandList); + super::super::list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + cl_set_pipeline_state(list_raw, shell_ptr); + + drop(shell_pso); + assert!( + is_translated_compute(real_raw), + "resolved real PSO must stay alive after shell release while retained by command list" + ); + + list.Close().expect("close"); + drop(list); + assert!(!is_translated_compute(real_raw)); + } + } + + #[test] + fn pending_standin_retained_on_command_list_survives_title_release_until_reset() { + struct QueueGateGuard { + gate: ID3D12Fence, + queue: usize, + } + impl Drop for QueueGateGuard { + fn drop(&mut self) { + unsafe { + let _ = self.gate.Signal(1); + super::super::present::forget_queue_for_test(self.queue); + super::super::late_release::drain_known(true); + } + } + } + + unsafe { + let Some((dev, rs)) = setup_test_device() else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + let cs = dummy_cs_bytecode(); + let queue: ID3D12CommandQueue = + dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).expect("queue"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + queue.Wait(&gate, 1).expect("wait"); + let _guard = QueueGateGuard { gate: gate.clone(), queue: queue.as_raw() as usize }; + super::super::present::note_execute(queue.as_raw(), &[]); + + let standin_pso = make_compute_pso(&dev, &rs, cs); + let real_pso = make_compute_pso(&dev, &rs, cs); + adopt(standin_pso.as_raw(), Kind::PipelineState); + adopt(real_pso.as_raw(), Kind::PipelineState); + + let standin_raw = standin_pso.as_raw() as usize; + let real_raw = real_pso.into_raw() as usize; + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(standin_raw); + TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(real_raw); + + let (tx, rx) = std::sync::mpsc::channel::<()>(); + super::super::pso_async::submit_lazy( + standin_raw, + false, + Box::new(move || { + let _ = rx.recv(); + real_raw + }), + 0, + ); + + let alloc1: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc1"); + let alloc2: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).expect("alloc2"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc1, None).expect("list"); + let list_raw = list.as_raw(); + adopt(list_raw, Kind::CommandList); + super::super::list_x::on_create(list_raw, alloc1.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + list.Close().expect("close initial"); + + // Bind/retain the still-pending stand-in via Reset -> retained_psos (COM refcount 1 -> 2). + list.Reset(&alloc1, &standin_pso).expect("reset with pending standin"); + assert!(super::super::pso_async::is_pending(standin_raw), "standin must remain pending"); + let add_ref_fn: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute(*(*(standin_raw as *const *const usize)).add(1)); + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = + std::mem::transmute(*(*(standin_raw as *const *const usize)).add(2)); + assert_eq!(add_ref_fn(standin_raw as *mut c_void), 3, "title + retained_psos must hold 2 refs"); + assert_eq!(rel_fn(standin_raw as *mut c_void), 2); + + list.Close().expect("close"); + let cl: ID3D12CommandList = list.cast().expect("cast ID3D12CommandList"); + let lists = [Some(cl)]; + queue.ExecuteCommandLists(&lists); + + // Title calls Release() (2 -> 1): must not treat as final, forget async state, or defer list-owned ref. + drop(standin_pso); + assert!(super::super::pso_async::is_tracked(standin_raw), "standin must remain tracked while retained by list"); + assert!(super::super::pso_async::is_pending(standin_raw), "standin must not be orphaned while retained by list"); + assert!(is_translated_compute(standin_raw), "standin must not be forgotten on 2 -> 1 release"); + assert!(!super::super::late_release::is_held(standin_raw), "2 -> 1 release must not enqueue list-owned ref into late_release"); + + // Let the async build finish while the list still owns the stand-in's remaining ref. + tx.send(()).unwrap(); + let wait_built = std::time::Instant::now(); + while super::super::pso_async::is_pending(standin_raw) && wait_built.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!super::super::pso_async::is_pending(standin_raw), "async build should finish while list retains standin"); + assert_eq!(super::super::pso_async::resolve(standin_raw), real_raw, "async state must remain valid until final release"); + + // Command list calls Reset() (1 -> 0): drops retained_psos and retires the actual final ref once. + list.Reset(&alloc2, None).expect("reset dropping retained standin"); + assert!(!super::super::pso_async::is_tracked(standin_raw), "final release on reset must retire standin"); + assert!(!is_translated_compute(standin_raw), "final release on reset must forget standin"); + if super::super::late_release::enabled() { + assert!( + super::super::late_release::is_held(standin_raw), + "actual final ref must be held in late_release until GPU queue retires" + ); + } + + gate.Signal(1).expect("signal gate"); + let start = std::time::Instant::now(); + while (super::super::late_release::is_held(standin_raw) || is_translated_compute(real_raw)) + && start.elapsed() < std::time::Duration::from_secs(10) + { + std::thread::sleep(std::time::Duration::from_millis(5)); + super::super::late_release::drain_known(false); + } + assert!(!super::super::late_release::is_held(standin_raw), "standin must drain once queue retires"); + assert!(!is_translated_compute(real_raw), "built real PSO must retire cleanly with standin"); + + list.Close().expect("close after final reset"); + drop(lists); + drop(list); + } + } +} + #[cfg(test)] mod queue_tests { use super::*;