From 4b860223ba159be35d38ac038531c448d444af2f Mon Sep 17 00:00:00 2001 From: veyn-sudo <360844188+veyn-sudo@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:11:13 +0100 Subject: [PATCH 1/2] D3D12.X: a pipeline is forgotten before its address is free pso_release dropped what XCL keeps of a pipeline after the driver had freed it. A pipeline made by another thread in between could get the same address and lose its own entries: a translated compute program then counts as untranslated and its dispatches are skipped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WStEFektfHt5AEbK6Wupac --- crates/xcl/src/hle/d3d12x/real.rs | 59 ++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..e50ae94d09 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1715,9 +1715,19 @@ 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 add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + // The last reference: forgotten while the object has its address. A pipeline another thread + // makes can get that address as soon as it is free, and must keep its own entries. + let last = add(this) == 2; + if last { + forget_pso(this as usize); + super::pso_async::release(super::pso_async::released(this as usize)); + } + f(this); let n = f(this); - if n == 0 { + // (two last-but-one releases at once: neither saw itself as the last) + if n == 0 && !last { forget_pso(this as usize); super::pso_async::release(super::pso_async::released(this as usize)); } @@ -8976,3 +8986,50 @@ void main() { } } + +#[cfg(test)] +mod pso_release_tests { + use super::*; + + /// An adopted pipeline as `orig_fn` sees it: its vtable, the original one before that. + #[repr(C)] + struct Pipeline { + vtable: *const usize, + refs: u32, + /// the pipeline was still known when its last reference went + known_when_freed: Option, + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs += 1; + p.refs + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs -= 1; + if p.refs == 0 { + p.known_when_freed = Some(is_translated_compute(this as usize)); + } + p.refs + } + + /// What XCL keeps of a pipeline goes before the driver frees it, not after: its address can be + /// another pipeline's by then. It stays while there are other references. + #[test] + fn a_pipeline_is_forgotten_before_its_address_is_free() { + let orig: [usize; 3] = [0, add_ref as usize, release as usize]; + let ext: [usize; 4] = [orig.as_ptr() as usize, 0, 0, 0]; + let mut p = Box::new(Pipeline { vtable: &ext[1], refs: 2, known_when_freed: None }); + let this = p.as_mut() as *mut Pipeline as *mut c_void; + register_translated_compute_for_test(this as usize); + unsafe { + assert_eq!(pso_release(this), 1); + assert!(is_translated_compute(this as usize), "another reference is left"); + assert_eq!(pso_release(this), 0); + } + assert_eq!(p.known_when_freed, Some(false)); + assert!(!is_translated_compute(this as usize)); + } +} From 0fd22d04dc7931066a8560fe178119a2040d0da9 Mon Sep 17 00:00:00 2001 From: veyn-sudo <360844188+veyn-sudo@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:14:58 +0100 Subject: [PATCH 2/2] D3D12.X: compute pipelines not used for a while are released on NVIDIA (#2403) NVIDIA's driver keeps the code of the pipelines in use in a heap of at most 512 MB and removes the device (0x887a0005, nothing in DRED, no event) when a submission needs more. With more than XCL_SHADER_CODE_MB of compiled code in use (320 on NVIDIA, no limit elsewhere) the compute pipelines bound longest ago are released, but none a recording holds; their next bind builds them again from the driver's cache. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WStEFektfHt5AEbK6Wupac --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 13 + crates/xcl/src/hle/d3d12x/list_x.rs | 80 +++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 214 ++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 32 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 66 ++++- crates/xcl/src/hle/d3d12x/shader_code.rs | 274 ++++++++++++++++++ 7 files changed, 647 insertions(+), 33 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/shader_code.rs diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..cbaaa29d14 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -218,6 +218,15 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } } +/// `take` for those of the PC allocators `of` that no list's recording is on and the GPU is done +/// with. No list begins a recording on one meanwhile. (What `take` gives back is dropped by the +/// caller: not under the lock.) +pub fn when_done(of: &[usize], take: impl FnMut(usize) -> T) -> Vec { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return Vec::new() }; + of.iter().copied().filter(|a| s.backings.get(a).is_some_and(|b| unsafe { b.free() })).map(take).collect() +} + /// Whether the GPU may still run a recording made on the title's allocator `alloc`. pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { let g = STATE.lock().unwrap(); @@ -427,13 +436,17 @@ mod tests { !s.of_list.contains_key(&second) && s.backings[&alloc].users.is_empty() && s.backings[&alloc].marks.len() == 1 && !unsafe { s.backings[&alloc].free() } }; + let pending_done = when_done(&[alloc], |a| a); fence.value.set(7); + // (taken under the lock: no list can begin a recording on it in between) + let completed_done = when_done(&[alloc], |a| (a, STATE.try_lock().is_err())); let reusable = unsafe { STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].free() }; // Clean up the synthetic COM pointer before assertions, including on the old code. unsafe { forget(alloc) }; assert!(first_removed, "another live recording must remain while the released list goes"); assert!(pending_still_held, "final list Release must retain the submitted-work fence"); assert!(reusable, "a released list cannot keep a completed backing busy"); + assert_eq!((pending_done, completed_done), (vec![], vec![(alloc, true)])); assert_eq!(fence.releases.get(), 1); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..0aecc5efee 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -798,6 +798,11 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { true } +/// The allocator `list` records on (0: unknown). +pub(super) fn allocator_of(list: usize) -> usize { + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&list)).map_or(0, |s| s.allocator) +} + /// Record a newly created command list's allocator, initial pipeline, and type. /// /// # Safety @@ -829,6 +834,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C old }; drop(old); + super::shader_code::bound(key); super::title_textures::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). @@ -2710,6 +2716,9 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } + // the pipelines it was recorded with live until the segment's allocator is reset (it was + // reset above without `cl_reset`, which hands them over for the title's own lists) + super::shader_code::bound(seg as usize); let ext = *(seg as *const usize); pc:: i32>(seg, PC_CLOSE)(seg); real::preserve_vtable(seg, ext); @@ -2827,6 +2836,7 @@ 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::shader_code::bound_on(super::alloc_pool::current(alloc)); super::dred::reset(next_pc); if init_pso != 0 { super::dred::mark_pipeline(next_pc, bound_pso, init_pso); @@ -3406,6 +3416,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); real::preserve_vtable(target, ext_closed); + super::shader_code::bound(target as usize); if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } @@ -3514,6 +3525,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b if let Some(base) = need_restore_base { let resolved = super::pso_async::resolve_for_bind(base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + super::shader_code::bound(this as usize); } if !need_native_call { return; @@ -3598,6 +3610,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { }; let resolved = super::pso_async::resolve_for_bind(target); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + super::shader_code::bound(list as usize); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; } @@ -4069,6 +4082,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 if hr < 0 { return hr; } + super::shader_code::bound(this as usize); reset_copy_scratch(this); reset_own_alloc(this); @@ -7000,6 +7014,72 @@ mod tests { assert!(wait_expired(&mut aw, false)); } + /// A dispatch put off to the submit keeps the pipeline it was recorded with until its + /// segment's allocator is reset: a pipeline that may be released is held by the recording, + /// not only by the thread that resolved it. + #[test] + fn a_deferred_dispatch_keeps_its_pipeline_with_its_segment() { + use super::super::{bind, pso_async, shader_code, title_list}; + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let mut sig = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut sig, None).unwrap(); + let sig = sig.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(sig.GetBufferPointer() as *const u8, sig.GetBufferSize())).unwrap(); + let code = real::compile("[numthreads(1, 1, 1)] void main() {}", "cs_5_0"); + 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 standin = 0x7E57_D0F1usize; + static BUILD: AtomicBool = AtomicBool::new(false); + let (d, r) = (dev.as_raw() as usize, rs.as_raw() as usize); + pso_async::submit_releasable_for_test( + standin, + true, + Box::new(move || { + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + let (d, r) = (d as *mut c_void, r as *mut c_void); + let dev = ID3D12Device::from_raw_borrowed(&d).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute(r), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr() as _, BytecodeLength: code.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState::(&desc).map_or(0, |p| p.into_raw() as usize) + }), + ); + 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); + let wrap = title_list::wrap(pc0); + bind::dispatch(pc0, 1, 1, 1); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert!(segs.len() > 1, "the dispatch is put off to the submit"); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + + BUILD.store(true, Ordering::Release); + record_deferred(wrap); + let built = pso_async::real_for_test(standin); + assert_ne!(built, 0); + assert!(shader_code::in_recordings().contains(&built), "held by the segment's recording"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + pso_async::release(pso_async::released(standin)); + } + } + #[test] fn a_dispatch_with_a_pipeline_still_building_waits_at_the_submit() { use super::super::{bind, pso_async, title_list}; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..c31bff7fe2 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -28,6 +28,7 @@ pub mod present; pub mod pso_async; pub mod real; mod shader_cache_session; +mod shader_code; pub mod sparse; mod standin; pub mod title_list; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..7819bfb6e0 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -14,6 +14,15 @@ use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, + /// the same build, for when the pipeline was released (`shader_code`) + again: Mutex>, + /// its code counts, and a compute one may be released when not used for a while + releasable: bool, + /// it was built in this run and released since: the next bind builds it itself + gone: std::sync::atomic::AtomicBool, + /// bytes of its compiled code (0: not used yet) and when it was last used + code: AtomicUsize, + last: std::sync::atomic::AtomicU64, /// 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 @@ -79,7 +88,7 @@ fn build(p: &Arc, job: Job, preload: bool) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); + run(p, job); if preload { // (under the lock: `want` does not raise this thread after it) let mut d = p.demand.lock().unwrap(); @@ -110,6 +119,7 @@ impl Pending { } fn note_use(&self) { + self.last.store(super::shader_code::now_ms(), Ordering::Release); if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); } @@ -119,6 +129,14 @@ impl Pending { /// stand-in handed to the title → its real pipeline static PENDING: Mutex>>> = Mutex::new(None); +fn run(p: &Pending, mut job: Job) { + let real = job(); + if p.releasable && p.compute { + *p.again.lock().unwrap() = Some(job); + } + complete(p, real); +} + /// The build is done (`real`: its pipeline, 0 = failed). fn complete(p: &Pending, real: usize) { if real == 0 { @@ -267,7 +285,7 @@ pub fn enabled() -> bool { } /// Builds the real pipeline: its raw pointer, 0 = failed. -pub type Job = Box usize + Send>; +pub type Job = Box usize + Send>; /// pipelines a submit will wait for: the workers take these before their queue (`need_by_submit`) static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); @@ -338,7 +356,7 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { let (send, recv) = mpsc::channel(); let drain = move || loop { let job = jobs.lock().unwrap().pop(); - let Some((i, job)) = job else { return }; + let Some((i, mut job)) = job else { return }; let _ = send.send((i, job())); }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too @@ -366,7 +384,7 @@ pub fn release(p: usize) { /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_as(standin, compute, job, true, 0, super::shader_code::limit() != 0); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -382,11 +400,28 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); + submit_as(standin, compute, job, false, key, super::shader_code::limit() != 0); +} + +/// `submit` of a pipeline that may be released (`shader_code`), whatever the adapter. +#[cfg(test)] +pub(super) fn submit_releasable_for_test(standin: usize, compute: bool, job: Job) { + submit_as(standin, compute, job, true, 0, true); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { +/// The pipeline built for `standin` (0: none yet). +#[cfg(test)] +pub(super) fn real_for_test(standin: usize) -> usize { + entry(standin).map_or(0, |p| p.real.load(Ordering::Acquire)) +} + +fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, releasable: bool) { let p = Arc::new(Pending { + again: Mutex::new(None), + releasable, + gone: Default::default(), + code: AtomicUsize::new(0), + last: Default::default(), job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), real: AtomicUsize::new(0), @@ -810,6 +845,61 @@ mod used_tests { released(unknown); } + /// A compute pipeline not used for a while is released and built again by its next bind; one + /// in use, or a thread's, is not freed. + #[test] + fn an_unused_compute_pipeline_is_released_and_built_again() { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let mut sig = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut sig, None).unwrap(); + let sig = sig.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(sig.GetBufferPointer() as *const u8, sig.GetBufferSize())).unwrap(); + let code = super::super::real::compile("[numthreads(1, 1, 1)] void main() {}", "cs_5_0"); + let builds = Arc::new(AtomicUsize::new(0)); + let (n, dev, rs) = (builds.clone(), dev.into_raw() as usize, rs.into_raw() as usize); + let standin = 0x7E57_C0DEusize; + let job: Job = Box::new(move || { + n.fetch_add(1, Ordering::AcqRel); + let (dev, rs) = (dev as *mut std::ffi::c_void, rs as *mut std::ffi::c_void); + let dev = ID3D12Device::from_raw_borrowed(&dev).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute(rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr() as _, BytecodeLength: code.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState::(&desc).map_or(0, |p| p.into_raw() as usize) + }); + submit_as(standin, true, job, false, 0, true); + shared(standin, 0x7E57_C0DF); + let built = resolve_wait_for(standin, None); + assert_ne!(built, 0x7E57_C0DF); + release_unused(0); + assert_eq!(resolve_wait_for(standin, None), built, "just used"); + let p = entry(standin).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(super::super::shader_code::IDLE_MS + 50)); + release_unused(0); + assert!(is_pending(standin) && p.real.load(Ordering::Acquire) == 0, "released"); + // (the thread's reference: a list it was about to record keeps it) + assert!(super::super::shader_code::Ref::new(built).is_some()); + assert_eq!(builds.load(Ordering::Acquire), 1); + assert_ne!(resolve_wait_for(standin, None), 0x7E57_C0DF); + assert_eq!(builds.load(Ordering::Acquire), 2); + // (with a time budget too: not behind what the workers have to build first) + std::thread::sleep(std::time::Duration::from_millis(super::super::shader_code::IDLE_MS + 50)); + release_unused(0); + assert!(is_pending(standin)); + assert_ne!(resolve_wait_for(standin, Some(std::time::Duration::from_nanos(1))), 0x7E57_C0DF); + assert_eq!(builds.load(Ordering::Acquire), 3); + release(released(standin)); + } + } + static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); /// A queued normal worker job whose stand-in was released before a worker starts it is @@ -1038,6 +1128,86 @@ impl Pending { } } +impl Pending { + /// Build it here if it was released: that takes the driver milliseconds (its cache has the + /// code), and a turn in the workers' queue – behind first builds of seconds – minutes. + fn build_again(&self) { + if self.gone.swap(false, Ordering::AcqRel) { + let job = self.job.lock().unwrap().take(); + if let Some(job) = job { + run(self, job); + } + } + } + + /// The pipeline to bind for `pso`: this thread's until it is bound (`shader_code`). + fn take(&self, pso: usize) -> usize { + let mut first = false; + let real = { + let _done = self.done.lock().unwrap(); + let real = self.real.load(Ordering::Acquire); + if real == 0 { + return self.stand(pso); + } + if self.releasable && self.compute { + unsafe { super::shader_code::Ref::new(real) }.map(super::shader_code::hold); + } + if self.releasable && self.code.load(Ordering::Acquire) == 0 { + self.code.store(unsafe { super::shader_code::count_all(real) }.max(1), Ordering::Release); + first = true; + } + real + }; + if first { + release_unused(super::shader_code::limit()); + } + real + } +} + +/// Release the compute pipelines used longest ago when there is more compiled code in use than +/// `shader_code::limit`. Their next bind builds them again (from the driver's cache). +fn release_unused(limit: usize) { + use super::shader_code::{choose, in_recordings, let_go_done, now_ms, used, IDLE_MS}; + if used() <= limit { + return; + } + let_go_done(); + let recorded = in_recordings(); + let all: Vec> = PENDING.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.values().filter(|p| p.releasable && p.compute && p.driver.load(Ordering::Acquire) != 0 && p.code.load(Ordering::Acquire) != 0 && !recorded.contains(&p.real.load(Ordering::Acquire))).cloned().collect()); + let sizes: Vec<(usize, u64)> = all.iter().map(|p| (p.code.load(Ordering::Acquire), p.last.load(Ordering::Acquire))).collect(); + let mut n = 0; + for i in choose(&sizes, used(), limit, now_ms()) { + let p = &all[i]; + let real = { + // (a build or a bind of it is going on: not unused) + let Ok(mut done) = p.done.try_lock() else { continue }; + if !*done || p.last.load(Ordering::Acquire) + IDLE_MS > now_ms() || p.orphan.load(Ordering::Acquire) { + continue; + } + let real = p.real.swap(0, Ordering::AcqRel); + if real == 0 { + continue; + } + p.code.store(0, Ordering::Release); + *p.job.lock().unwrap() = p.again.lock().unwrap().take(); + p.sent.store(false, Ordering::Release); + p.late.store(false, Ordering::Release); + p.gone.store(true, Ordering::Release); + p.demand.lock().unwrap().by_submit = false; + *done = false; + real + }; + release(real); + n += 1; + } + if n != 0 { + static RELEASED: AtomicUsize = AtomicUsize::new(0); + let all = RELEASED.fetch_add(n, Ordering::Relaxed) + n; + crate::xlog_info!("D3D12.X: {n} compute pipelines not used lately released ({} MB of shader code left in use; {all} released so far)", used() >> 20); + } +} + /// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. /// Told before the title has the stand-in. pub fn shared(standin: usize, driver: usize) { @@ -1060,7 +1230,7 @@ pub fn resolve(pso: usize) -> usize { } stand } - r => r, + _ => p.take(pso), } } @@ -1084,17 +1254,15 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { } let job = p.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + run(&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, - } + drop(done); + p.take(pso) } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until @@ -1110,12 +1278,9 @@ fn wait_budget() -> Option { /// 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, - }; + p.build_again(); if *p.done.lock().unwrap() { - return built(p); + return p.take(pso); } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); @@ -1125,10 +1290,11 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> } p.want(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); - if *done { - return built(p); - } + let built = *done; drop(done); + if built { + return p.take(pso); + } p.late.store(true, Ordering::Release); static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -1163,6 +1329,7 @@ pub fn image_only(standin: usize) { /// 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 { + p.build_again(); match p.real.load(Ordering::Acquire) { 0 => { if !p.sent.swap(true, Ordering::AcqRel) { @@ -1177,7 +1344,7 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { } p.stand(pso) } - r => r, + _ => p.take(pso), } } @@ -1198,7 +1365,10 @@ pub fn released(pso: usize) -> usize { { let done = p.done.lock().unwrap(); if *done { - return p.real.swap(0, Ordering::AcqRel); + let real = p.real.swap(0, Ordering::AcqRel); + drop(done); + super::shader_code::let_go(real); + return real; } // the worker stores its result into a Pending nobody will read: mark it orphaned p.orphan.store(true, Ordering::Release); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e50ae94d09..0b919ac371 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1715,21 +1715,24 @@ 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 add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - // The last reference: forgotten while the object has its address. A pipeline another thread - // makes can get that address as soon as it is free, and must keep its own entries. + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + // The last reference: forgotten while the object still has its address (a pipeline another + // thread makes may get it at once, and what is kept of that one must stay). let last = add(this) == 2; - if last { + let forget = || { + super::shader_code::freed(this as usize); forget_pso(this as usize); super::pso_async::release(super::pso_async::released(this as usize)); + }; + if last { + forget(); } f(this); let n = f(this); // (two last-but-one releases at once: neither saw itself as the last) if n == 0 && !last { - forget_pso(this as usize); - super::pso_async::release(super::pso_async::released(this as usize)); + forget(); } n } @@ -2997,6 +3000,7 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); + super::shader_code::bound(this as usize); super::dred::reset(this); if !initial_state.is_null() { super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); @@ -3714,7 +3718,7 @@ fn dummy_mesh() -> Option<&'static (Vec, Vec)> { .as_ref() } -fn compile(src: &str, target: &str) -> Vec { +pub(super) fn compile(src: &str, target: &str) -> Vec { unsafe { let mut blob = None; let t = format!("{target}\0"); @@ -4788,6 +4792,11 @@ mod compute_blob_tests { } } +/// Bytes of the driver's compiled form of `pso` (0: unknown). +pub(super) unsafe fn cached_blob_size(pso: *mut c_void) -> usize { + read_pso_cached_blob(pso).map_or(0, |b| b.len()) +} + /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { if pso.is_null() { @@ -6960,6 +6969,7 @@ unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_v 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::shader_code::bound(this as usize); super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } @@ -6977,6 +6987,7 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); let bound = super::pso_async::resolve_for_bind(pso as usize); f(this, bound as *mut c_void); + super::shader_code::bound(this as usize); if !pso.is_null() { super::dred::mark_pipeline(this, pso as usize, bound); } @@ -7039,6 +7050,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { dispatch_chain::allocator_reset(this as usize); + super::shader_code::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); } @@ -7050,7 +7062,10 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); let hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + dispatch_chain::allocator_reset(raw as usize); + super::shader_code::allocator_reset(raw as usize); + } hr } @@ -8986,7 +9001,6 @@ void main() { } } - #[cfg(test)] mod pso_release_tests { use super::*; diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..72d5be3fd4 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -183,8 +183,17 @@ unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: } pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { - let recordings = RECORDINGS.lock().unwrap().remove(&allocator); - drop(recordings); + drop(let_go(allocator)); +} + +/// What `allocator`'s recordings keep, for the caller to drop. +pub(in crate::hle::d3d12x) fn let_go(allocator: usize) -> impl Sized { + RECORDINGS.lock().unwrap().remove(&allocator) +} + +/// The pieces after the first of the split program whose first piece is `pso`. +pub(in crate::hle::d3d12x) fn tail(pso: usize) -> Vec { + CHAINS.lock().unwrap().get(&pso).map_or(Vec::new(), |c| c.tail.clone()) } unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option { @@ -284,4 +293,57 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + /// A split program's recordings keep every piece until they let go of the allocator's, and all + /// of its pieces count as code in use. + #[test] + fn a_chains_recordings_let_go_of_every_piece() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + unsafe extern "system" fn unused(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + unreachable!() + } + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let mut sig = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut sig, None).unwrap(); + let sig = sig.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(sig.GetBufferPointer() as *const u8, sig.GetBufferSize())).unwrap(); + let make = |src: &str| { + let code = super::super::compile(src, "cs_5_0"); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr() as _, BytecodeLength: code.len() }, + ..Default::default() + }; + dev.CreateComputePipelineState::(&desc).unwrap() + }; + let first = make("[numthreads(1, 1, 1)] void main() {}"); + let tail = make("[numthreads(2, 1, 1)] void main() {}"); + let refs = |p: &ID3D12PipelineState| { + type F = unsafe extern "system" fn(*mut c_void) -> u32; + let slot = |k: usize| std::mem::transmute::(*(*(p.as_raw() as *const *const usize)).add(k)); + slot(1)(p.as_raw()); + slot(2)(p.as_raw()) + }; + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: unused, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + let chain = Arc::new(Chain { builder, tail: vec![tail.clone()], words: 1, whole_code: Vec::new(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + let pso = first.as_raw() as usize; + CHAINS.lock().unwrap().insert(pso, chain.clone()); + let one = |p: &ID3D12PipelineState| super::super::cached_blob_size(p.as_raw()); + assert_eq!(super::super::super::shader_code::count_all(pso), one(&first) + one(&tail)); + let allocator = 0x7E57_5CB0usize; + let (scratch, _) = scratch_for(&dev, 0x7E57_5C0Busize, allocator, MB, 4096).unwrap(); + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first: first.clone(), chain })); + forget(pso); + assert_eq!((refs(&first), refs(&tail)), (2, 2), "the recording keeps them"); + drop(let_go(allocator)); + assert_eq!((refs(&first), refs(&tail)), (1, 1)); + super::super::super::shader_code::freed(pso); + super::super::super::shader_code::freed(tail.as_raw() as usize); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/shader_code.rs b/crates/xcl/src/hle/d3d12x/shader_code.rs new file mode 100644 index 0000000000..edb7da59c6 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/shader_code.rs @@ -0,0 +1,274 @@ +//! Compute pipelines not used for a while are released and made again when they are bound. +//! +//! NVIDIA's driver keeps the machine code of the pipelines its lists use in one heap of at most +//! 512 MB. A submission that needs more removes the device: `DXGI_ERROR_DEVICE_REMOVED`, nothing +//! in DRED and no event in the system log, as there was no GPU fault. The wave64 programs of a +//! console title are several times their size on 32-lane hardware, and a retail title's world is +//! past that in its first seconds. Code goes into the heap when a pipeline is first used and out +//! of it with the pipeline. +//! +//! A pipeline that is released can still be in a recorded list. So `pso_async::resolve` and its +//! kin give the thread a reference to it, a bind hands that to the allocator the list records on +//! (`bound`), and the allocator's `Reset` – the title's word that the GPU is past its lists – +//! gives it back (`allocator_reset`). +//! +//! `XCL_SHADER_CODE_MB`: the compiled code to keep in use (`GetCachedBlob` sizes, which are about +//! 1/9 less than what the code takes in the heap; 0: no limit). Default: 320 on NVIDIA, no limit +//! elsewhere. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; + +/// a thread's references to pipelines it resolved and has not bound yet, at most +const HELD_MAX: usize = 4; +/// a pipeline used this recently is not released +pub const IDLE_MS: u64 = 1000; +const NVIDIA: u32 = 0x10DE; + +/// A reference to a pipeline. +#[derive(PartialEq)] +pub struct Ref(ID3D12PipelineState); + +impl Ref { + /// # Safety + /// `pso` is a live pipeline. + pub unsafe fn new(pso: usize) -> Option { + ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).cloned().map(Self) + } +} + +thread_local! { + static HELD: RefCell> = const { RefCell::new(VecDeque::new()) }; +} + +/// allocator → the pipelines its recordings use +static BOUND: Mutex>>> = Mutex::new(None); +/// pipeline that was used → bytes of its compiled code, until the driver frees it +static SIZES: Mutex>> = Mutex::new(None); +/// their sum +static USED: AtomicUsize = AtomicUsize::new(0); + +fn nvidia() -> Option { + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + let raw = super::real::device_raw(); + unsafe { + let dev = ID3D12Device::from_raw_borrowed(&raw)?; + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + Some(adapter.GetDesc().ok()?.VendorId == NVIDIA) + } +} + +/// How many bytes of compiled code to keep in use (0: no limit). +pub fn limit() -> usize { + static L: OnceLock = OnceLock::new(); + *L.get_or_init(|| { + let mb = std::env::var("XCL_SHADER_CODE_MB").ok().and_then(|v| v.trim().parse().ok()); + // (the tests give `pso_async` pipelines that are none) + mb.unwrap_or_else(|| if !cfg!(test) && nvidia() == Some(true) { 320usize } else { 0 }) << 20 + }) +} + +pub fn now_ms() -> u64 { + static T: OnceLock = OnceLock::new(); + T.get_or_init(Instant::now).elapsed().as_millis() as u64 +} + +/// This thread is about to use pipeline `r`. +pub fn hold(r: Ref) { + let old = HELD.with(|h| { + let mut h = h.borrow_mut(); + if h.contains(&r) { + return Some(r); + } + h.push_back(r); + if h.len() > HELD_MAX { + h.pop_front() + } else { + None + } + }); + // (outside the borrow: the last reference's `Release` comes back into XCL) + drop(old); +} + +/// The title is done with the pipeline `pso`: this thread's reference to it goes. +pub fn let_go(pso: usize) { + let old = HELD.with(|h| { + let mut h = h.borrow_mut(); + let i = h.iter().position(|r| r.0.as_raw() as usize == pso)?; + h.remove(i) + }); + drop(old); +} + +/// `list` records with the pipelines this thread resolved: they live until its allocator's `Reset`. +pub fn bound(list: usize) { + let held = HELD.with(|h| std::mem::take(&mut *h.borrow_mut())); + if held.is_empty() { + return; + } + let allocator = match super::alloc_pool::enabled() { + true => super::alloc_pool::recording_backing(list).unwrap_or(0), + false => super::list_x::allocator_of(list), + }; + keep(allocator, held); +} + +/// `bound` for a list recording on the PC allocator `allocator`. +pub fn bound_on(allocator: usize) { + let held = HELD.with(|h| std::mem::take(&mut *h.borrow_mut())); + if !held.is_empty() { + keep(allocator, held); + } +} + +fn keep(allocator: usize, held: VecDeque) { + let mut left = Vec::new(); + { + let mut g = BOUND.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new).entry(allocator).or_default(); + for r in held { + left.extend(m.insert(r.0.as_raw() as usize, r)); + } + } + drop(left); +} + +/// `allocator` was reset or released: the GPU is past its recordings. +pub fn allocator_reset(allocator: usize) { + let gone = BOUND.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + drop(gone); +} + +/// Pipeline `pso` is used: its code counts until it is freed (`freed`). +/// +/// # Safety +/// `pso` is a live pipeline. +pub unsafe fn count(pso: usize) -> usize { + if let Some(&n) = SIZES.lock().unwrap().as_ref().and_then(|m| m.get(&pso)) { + return n; + } + // (outside the lock: the driver's call) + let n = super::real::cached_blob_size(pso as *mut c_void); + if SIZES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, n).is_none() { + USED.fetch_add(n, Ordering::AcqRel); + } + n +} + +/// `count` for `pso` and the other pieces of its program, if it is the first of a split one. +/// +/// # Safety +/// `pso` is a live pipeline. +pub unsafe fn count_all(pso: usize) -> usize { + let tail = super::real::dispatch_chain::tail(pso); + count(pso) + tail.iter().map(|p| count(p.as_raw() as usize)).sum::() +} + +/// The last reference to pipeline `pso` goes. +pub fn freed(pso: usize) { + if let Some(n) = SIZES.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) { + USED.fetch_sub(n, Ordering::AcqRel); + } +} + +/// The pipelines recordings use: released, they would take their room until those are done. +pub fn in_recordings() -> HashSet { + BOUND.lock().unwrap().as_ref().map_or(HashSet::new(), |m| m.values().flat_map(|p| p.keys().copied()).collect()) +} + +/// Give back what the allocators hold whose lists are all reset and done on the GPU. +pub fn let_go_done() { + let all: Vec = BOUND.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.keys().copied().collect()); + // (a chain's recordings keep its pieces too) + let gone = super::alloc_pool::when_done(&all, |a| (BOUND.lock().unwrap().as_mut().and_then(|m| m.remove(&a)), super::real::dispatch_chain::let_go(a))); + drop(gone); +} + +pub fn used() -> usize { + USED.load(Ordering::Acquire) +} + +/// Which of `pipelines` (bytes of code, when last used) to release for `used` bytes to come down +/// to 7/8 of `limit`: the ones not used for the longest time, and none used in the last `IDLE_MS`. +pub fn choose(pipelines: &[(usize, u64)], used: usize, limit: usize, now: u64) -> HashSet { + let mut order: Vec = (0..pipelines.len()).filter(|&i| pipelines[i].1 + IDLE_MS <= now).collect(); + order.sort_by_key(|&i| pipelines[i].1); + let (mut left, mut out) = (used, HashSet::new()); + for i in order { + if left <= limit / 8 * 7 { + break; + } + left = left.saturating_sub(pipelines[i].0); + out.insert(i); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_longest_unused_go_first_and_only_as_many_as_it_takes() { + // 100 each, 400 used, the limit 320 (7/8: 280): two have to go + let p = [(100, 5_000), (100, 1_000), (100, 3_000), (100, 9_500)]; + assert_eq!(choose(&p, 400, 320, 10_000), HashSet::from([1, 2])); + assert_eq!(choose(&p, 280, 320, 10_000), HashSet::new()); + // never one just used, also when that leaves too much + assert_eq!(choose(&p, 400, 8, 10_000), HashSet::from([0, 1, 2])); + } + + /// A pipeline a list was recorded with lives until the list's allocator is reset. + #[test] + fn a_bound_pipeline_lives_until_its_allocator_is_reset() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let mut sig = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut sig, None).unwrap(); + let sig = sig.unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(sig.GetBufferPointer() as *const u8, sig.GetBufferSize())).unwrap(); + let code = super::super::real::compile("[numthreads(1, 1, 1)] void main() {}", "cs_5_0"); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr() as _, BytecodeLength: code.len() }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let raw = pso.as_raw() as usize; + let refs = || { + type F = unsafe extern "system" fn(usize) -> u32; + let slot = |k: usize| std::mem::transmute::(*(*(raw as *const *const usize)).add(k)); + slot(1)(raw); + slot(2)(raw) + }; + let take = || HELD.with(|h| std::mem::take(&mut *h.borrow_mut())); + assert_eq!(refs(), 1); + let allocator = 0x7E57_A110usize; + hold(Ref::new(raw).unwrap()); + hold(Ref::new(raw).unwrap()); + assert_eq!(refs(), 2, "held once by this thread"); + keep(allocator, take()); + hold(Ref::new(raw).unwrap()); + keep(allocator, take()); + assert_eq!(refs(), 2, "held once by the allocator"); + assert!(in_recordings().contains(&raw)); + allocator_reset(allocator); + assert_eq!(refs(), 1); + assert!(!in_recordings().contains(&raw)); + } + } +}