From 879ad2c7ed00e9d1e50df301fcbb6d150de604bb Mon Sep 17 00:00:00 2001 From: Shadow Date: Tue, 24 Nov 2026 16:18:08 +0600 Subject: [PATCH 1/3] d3d12x: persistent on-disk pipeline library caching and coalesced descriptor heap staging --- crates/xcl/src/hle/d3d12x/console_heap.rs | 83 ++- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pipeline_library.rs | 624 ++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 74 ++- crates/xcl/src/loader.rs | 1 + crates/xcl/src/report.rs | 1 + 7 files changed, 776 insertions(+), 10 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/pipeline_library.rs diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 4862abd84c..3c903be957 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -429,6 +429,8 @@ pub struct Slot { pub shared_srv: u64, /// the slot's number in its heap pub k: u32, + /// number of slots remaining in its heap from this slot + pub remaining: u32, } /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot @@ -437,6 +439,7 @@ pub fn slot(cpu: u64) -> Option { let mut heaps = HEAPS.lock().unwrap(); let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; + let remaining = h.n.saturating_sub(k); if h.sampler { let shared = sampler_page_of(h, k).and_then(|(first, k0)| { let g = GLOBAL_SAMPLER.lock().unwrap(); @@ -448,7 +451,7 @@ pub fn slot(cpu: u64) -> Option { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); - return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }); + return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining }); } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { @@ -458,7 +461,7 @@ pub fn slot(cpu: u64) -> Option { Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) }); let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) + Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining }) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -556,6 +559,55 @@ pub fn copy_words(src: &Slot, dst: &Slot) { } } +/// Copy `n` contiguous console descriptors from `src` to `dst`. Renumbers destination +/// indices without per-slot mutex acquisitions, splitting at page boundaries. +/// Clamps `n` to the remaining capacity of both heaps. +pub fn copy_range(src: &Slot, dst: &Slot, n: u32) { + let n = n.min(src.remaining).min(dst.remaining); + if n == 0 { + return; + } + let step = if src.sampler { SAMPLER_SLOT } else { SLOT } as usize; + let index_step = if src.sampler { 1 } else { 2 }; + let words = if src.sampler { 4 } else { 8 }; + let mut done = 0; + while done < n { + let dst_slot = if done == 0 { + *dst + } else { + let Some(s) = slot((dst.at + done as usize * step) as u64) else { break }; + s + }; + let run = if dst.sampler { + n - done + } else { + (PAGE_SLOTS - dst_slot.k % PAGE_SLOTS).min(n - done) + }; + for k in 0..run as usize { + let offset = (done as usize + k) * step; + let src_at = src.at + offset; + let dst_at = dst.at + offset; + let dst_index = dst_slot.index + (k as u32 * index_step); + let mut w = [0u32; 8]; + unsafe { + std::ptr::copy_nonoverlapping(src_at as *const u32, w.as_mut_ptr(), words); + } + if src.sampler { + w[3] = (w[3] & !0xFFF) | (dst_index & 0xFFF); + } else if w[3] >> 28 >= 8 { + w[0] = dst_index; + } + unsafe { + std::ptr::copy_nonoverlapping(w.as_ptr(), dst_at as *mut u32, words); + } + if !src.sampler && super::present::trace_frame() { + note_resource(&Slot { at: dst_at, index: dst_index, ..dst_slot }, resource_at(src_at).unwrap_or(0)); + } + } + done += run; + } +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. @@ -958,6 +1010,22 @@ mod tests { copy_words(&q0, &q1); assert_eq!(words_at(rel(sm + 16)).unwrap()[..4], [1, 2, 3, 0xABC0_0001]); assert!(slot(sm + 32).is_none(), "past the last sampler slot"); + + // copy_range copies multiple slots sequentially without per-slot mutex acquisitions + let s0 = slot(v).unwrap(); + let s2 = slot(v + 64).unwrap(); + write(&s0, &[0, 0x0100_0000, 0, 9 << 28, 0, 0, 0, 0]); + write(&s1, &[2, 0x0200_0000, 0, 9 << 28, 0, 0, 0, 0]); + copy_range(&s0, &s2, 2); + assert_eq!(words_at(rel(v + 64)).unwrap()[..4], [4, 0x0100_0000, 0, 9 << 28]); + assert_eq!(words_at(rel(v + 96)).unwrap()[..4], [6, 0x0200_0000, 0, 9 << 28]); + + // copy_range clamps to remaining heap capacity when count exceeds boundary + let s_last = slot(v + 96).unwrap(); + assert_eq!(s_last.remaining, 1); + copy_range(&s0, &s_last, 100); + assert_eq!(words_at(rel(v + 96)).unwrap()[..4], [6, 0x0100_0000, 0, 9 << 28]); + unregister(0xA1); unregister(0xA2); assert!(start(0xA1).is_none() && slot(v).is_none() && slot(sm).is_none()); @@ -1002,6 +1070,17 @@ mod tests { assert!(!seen.contains(&x.index), "two slots share the PC index {}", x.index); seen.push(x.index); } + // copy_range crossing page boundary assigns correct index from page 1 + let src0 = slot(v).unwrap(); + let src1 = slot(v + SLOT as u64).unwrap(); + write(&src0, &[0, 0x0100_0000, 0, 9 << 28, 0, 0, 0, 0]); + write(&src1, &[2, 0x0200_0000, 0, 9 << 28, 0, 0, 0, 0]); + copy_range(&src0, &s[1], 2); + let w1 = unsafe { *(s[1].at as *const [u32; 8]) }; + let w2 = unsafe { *(s[2].at as *const [u32; 8]) }; + assert_eq!(w1[0], s[1].index, "page 0 boundary slot gets page 0 index"); + assert_eq!(w2[0], s[2].index, "page 1 boundary slot gets page 1 index"); + // the same slot again: the same place assert_eq!(slot(v).unwrap().index, s[0].index); } diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..d60ab0fd29 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -24,6 +24,7 @@ mod late_release; pub mod layout; pub mod list_x; pub mod null; +pub mod pipeline_library; pub mod present; pub mod pso_async; pub mod real; diff --git a/crates/xcl/src/hle/d3d12x/pipeline_library.rs b/crates/xcl/src/hle/d3d12x/pipeline_library.rs new file mode 100644 index 0000000000..81b1bf20ba --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pipeline_library.rs @@ -0,0 +1,624 @@ +//! Persistent on-disk pipeline library cache (ID3D12PipelineLibrary1). +//! +//! Eliminates runtime DXIL-to-ISA driver compilation stalls by caching +//! driver-compiled pipeline states across application launches. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{HSTRING, Interface, PCWSTR}; + +struct Library { + library: ID3D12PipelineLibrary1, + /// Backing blob from disk that must outlive the library instance. + _blob: Vec, + added: u64, +} + +// SAFETY: D3D12 pipeline library operations are guarded by the internal Mutex. +unsafe impl Send for Library {} + +static LIBRARY: OnceLock>> = OnceLock::new(); +static DIR: OnceLock = OnceLock::new(); + +pub static GRAPHICS_LOADED: AtomicU64 = AtomicU64::new(0); +pub static GRAPHICS_STORED: AtomicU64 = AtomicU64::new(0); +pub static COMPUTE_LOADED: AtomicU64 = AtomicU64::new(0); +pub static COMPUTE_STORED: AtomicU64 = AtomicU64::new(0); + +const BATCH_SAVE_THRESHOLD: u64 = 16; +const LIBRARY_FILE: &str = "host-pipelines.bin"; + +/// Folder of the PSO disk cache: XCL_PSO_CACHE, else %LOCALAPPDATA%\xcl\pso. +pub fn cache_dir() -> PathBuf { + std::env::var("XCL_PSO_CACHE") + .map(PathBuf::from) + .or_else(|_| std::env::var("LOCALAPPDATA").map(|l| PathBuf::from(l).join("xcl").join("pso"))) + .unwrap_or_else(|_| PathBuf::from("xcl-pso-cache")) +} + +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PIPELINE_LIBRARY").map_or(true, |v| v.trim() != "0")) +} + +/// Initialize the pipeline library for the active D3D12 device. +pub fn init(device: &ID3D12Device) { + if !enabled() { + return; + } + let dir = cache_dir(); + let _ = DIR.set(dir.clone()); + let _ = LIBRARY.get_or_init(|| { + let dev1 = device.cast::().ok()?; + let blob = std::fs::read(dir.join(LIBRARY_FILE)).unwrap_or_default(); + let lib = open(&dev1, blob)?; + Some(Mutex::new(lib)) + }); +} + +fn library() -> Option<&'static Mutex> { + LIBRARY.get().and_then(|opt| opt.as_ref()) +} + +fn open(device: &ID3D12Device1, blob: Vec) -> Option { + let make = |bytes: &[u8]| -> windows::core::Result { + // vkd3d-proton requires a null blob pointer when length is zero to construct an empty library; + // passing an empty slice through windows-rs forwards a dangling non-null pointer (0x1) that fails validation. + let ptr = if bytes.is_empty() { + std::ptr::null() + } else { + bytes.as_ptr().cast() + }; + let mut raw = std::ptr::null_mut(); + unsafe { + (windows::core::Interface::vtable(device).CreatePipelineLibrary)( + windows::core::Interface::as_raw(device), + ptr, + bytes.len(), + &ID3D12PipelineLibrary1::IID, + &mut raw, + ) + .and_then(|| windows::core::Type::from_abi(raw)) + } + }; + if !blob.is_empty() { + match make(&blob) { + Ok(library) => { + crate::xlog_info!("D3D12.X: loaded host pipeline library ({} B)", blob.len()); + return Some(Library { library, _blob: blob, added: 0 }); + } + Err(e) => { + crate::xlog_info!("D3D12.X: pipeline library rejected ({e}), starting fresh library"); + } + } + } + let library = make(&[]).ok()?; + Some(Library { library, _blob: Vec::new(), added: 0 }) +} + +static ROOT_SIG_HASHES: Mutex>> = Mutex::new(None); + +/// Associates a root signature's interface address with its deterministic content hash. +pub fn note_root_signature(raw: usize, hash: u64) { + if raw == 0 { + return; + } + let mut g = ROOT_SIG_HASHES.lock().unwrap(); + g.get_or_insert_with(HashMap::new).insert(raw, hash); +} + +/// Resolves the deterministic content hash of a root signature. +pub fn root_signature_hash(rs: Option<&ID3D12RootSignature>) -> u64 { + let Some(rs) = rs else { return 0 }; + let raw = windows::core::Interface::as_raw(rs) as usize; + ROOT_SIG_HASHES.lock().unwrap().as_ref().and_then(|m| m.get(&raw).copied()).unwrap_or(0) +} + +fn hash_blend_desc(desc: &D3D12_BLEND_DESC) -> u64 { + // Structure padding bytes between RenderTargetWriteMask and the next slot + // contain undefined stack garbage that invalidates hashes across compilers. + let mut h = 0xcbf2_9ce4_8422_2325u64; + h = (h ^ (desc.AlphaToCoverageEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.IndependentBlendEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + for rt in &desc.RenderTarget { + h = (h ^ (rt.BlendEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.LogicOpEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.SrcBlend.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.DestBlend.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.BlendOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.SrcBlendAlpha.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.DestBlendAlpha.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.BlendOpAlpha.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.LogicOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (rt.RenderTargetWriteMask as u64)).wrapping_mul(0x100_0000_01b3); + } + h +} + +fn hash_depth_stencil_desc(desc: &D3D12_DEPTH_STENCIL_DESC) -> u64 { + // StencilWriteMask is followed by alignment padding bytes that must not enter the hash. + let mut h = 0xcbf2_9ce4_8422_2325u64; + h = (h ^ (desc.DepthEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.DepthWriteMask.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.DepthFunc.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.StencilEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.StencilReadMask as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.StencilWriteMask as u64)).wrapping_mul(0x100_0000_01b3); + + h = (h ^ (desc.FrontFace.StencilFailOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.FrontFace.StencilDepthFailOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.FrontFace.StencilPassOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.FrontFace.StencilFunc.0 as u64)).wrapping_mul(0x100_0000_01b3); + + h = (h ^ (desc.BackFace.StencilFailOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.BackFace.StencilDepthFailOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.BackFace.StencilPassOp.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.BackFace.StencilFunc.0 as u64)).wrapping_mul(0x100_0000_01b3); + h +} + +fn hash_rasterizer_desc(desc: &D3D12_RASTERIZER_DESC) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + h = (h ^ (desc.FillMode.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.CullMode.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.FrontCounterClockwise.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.DepthBias as u32 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.DepthBiasClamp.to_bits() as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.SlopeScaledDepthBias.to_bits() as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.DepthClipEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.MultisampleEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.AntialiasedLineEnable.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.ForcedSampleCount as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (desc.ConservativeRaster.0 as u64)).wrapping_mul(0x100_0000_01b3); + h +} + +fn hash_input_layout(layout: &D3D12_INPUT_LAYOUT_DESC) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + h = (h ^ (layout.NumElements as u64)).wrapping_mul(0x100_0000_01b3); + if layout.NumElements == 0 || layout.pInputElementDescs.is_null() { + return h; + } + // SAFETY: D3D12 input layout descriptor array spans NumElements valid entries when non-null. + let elems = unsafe { std::slice::from_raw_parts(layout.pInputElementDescs, layout.NumElements as usize) }; + for e in elems { + if !e.SemanticName.is_null() { + // SAFETY: SemanticName is a null-terminated ASCII string in D3D12_INPUT_ELEMENT_DESC. + let name = unsafe { std::ffi::CStr::from_ptr(e.SemanticName.as_ptr() as *const i8) }; + for &b in name.to_bytes() { + h = (h ^ (b as u64)).wrapping_mul(0x100_0000_01b3); + } + } + h = (h ^ (e.SemanticIndex as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (e.Format.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (e.InputSlot as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (e.AlignedByteOffset as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (e.InputSlotClass.0 as u64)).wrapping_mul(0x100_0000_01b3); + h = (h ^ (e.InstanceDataStepRate as u64)).wrapping_mul(0x100_0000_01b3); + } + h +} + +/// Computes a unique name for a graphics pipeline based on its state and translated shaders. +pub fn graphics_pso_name( + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + vs: &[u8], + ps: Option<&[u8]>, + gs: Option<&[u8]>, +) -> String { + let mut h1 = crate::gpu::shader::fnv64(vs); + let mut h2 = 0xcbf2_9ce4_8422_2325u64; + + if let Some(p) = ps { + h1 = (h1 ^ crate::gpu::shader::fnv64(p)).wrapping_mul(0x100_0000_01b3); + } + if let Some(g) = gs { + h2 = (h2 ^ crate::gpu::shader::fnv64(g)).wrapping_mul(0x100_0000_01b3); + } + + let rs_hash = root_signature_hash(desc.pRootSignature.as_ref()); + h1 = (h1 ^ rs_hash).wrapping_mul(0x100_0000_01b3); + + h2 = (h2 ^ hash_blend_desc(&desc.BlendState)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ hash_rasterizer_desc(&desc.RasterizerState)).wrapping_mul(0x100_0000_01b3); + h2 = (h2 ^ hash_depth_stencil_desc(&desc.DepthStencilState)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ hash_input_layout(&desc.InputLayout)).wrapping_mul(0x100_0000_01b3); + + h1 = (h1 ^ (desc.SampleMask as u64)).wrapping_mul(0x100_0000_01b3); + h2 = (h2 ^ (desc.PrimitiveTopologyType.0 as u64)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ (desc.NumRenderTargets as u64)).wrapping_mul(0x100_0000_01b3); + let num_rt = (desc.NumRenderTargets as usize).min(8); + for &fmt in &desc.RTVFormats[..num_rt] { + h2 = (h2 ^ (fmt.0 as u64)).wrapping_mul(0x100_0000_01b3); + } + h2 = (h2 ^ (desc.DSVFormat.0 as u64)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ (desc.SampleDesc.Count as u64)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ (desc.SampleDesc.Quality as u64)).wrapping_mul(0x100_0000_01b3); + h2 = (h2 ^ (desc.IBStripCutValue.0 as u64)).wrapping_mul(0x100_0000_01b3); + h2 = (h2 ^ (desc.Flags.0 as u64)).wrapping_mul(0x100_0000_01b3); + h1 = (h1 ^ (desc.NodeMask as u64)).wrapping_mul(0x100_0000_01b3); + + format!("gp_{h1:016x}{h2:016x}") +} + +/// Computes a unique name for a compute pipeline based on its root signature and compute shader. +pub fn compute_pso_name(desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, cs: &[u8]) -> String { + let mut h1 = crate::gpu::shader::fnv64(cs); + let rs_hash = root_signature_hash(desc.pRootSignature.as_ref()); + h1 = (h1 ^ rs_hash).wrapping_mul(0x100_0000_01b3); + let h2 = (desc.Flags.0 as u64).wrapping_mul(0x100_0000_01b3) ^ ((desc.NodeMask as u64) << 32) ^ 0x9e3779b97f4a7c15u64; + + format!("cp_{h1:016x}{h2:016x}") +} + +/// Attempts to load a graphics pipeline from the persistent library. +pub fn load_graphics( + name: &str, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, +) -> Option { + let lib_mutex = library()?; + let l = lib_mutex.lock().unwrap(); + let wide = HSTRING::from(name); + // SAFETY: D3D12 PipelineLibrary load call with valid pointer and descriptor references. + let res: windows::core::Result = unsafe { + l.library.LoadGraphicsPipeline(PCWSTR(wide.as_ptr()), desc) + }; + match res { + Ok(pso) => { + GRAPHICS_LOADED.fetch_add(1, Ordering::Relaxed); + Some(pso) + } + Err(_) => None, + } +} + +static PENDING_ADDED: AtomicU64 = AtomicU64::new(0); +static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); +static SAVE_EPOCH: OnceLock = OnceLock::new(); + +fn store_pipeline(name: &str, pso: &ID3D12PipelineState, counter: &AtomicU64) { + let Some(lib_mutex) = library() else { return }; + let should_save = { + let mut l = lib_mutex.lock().unwrap(); + let wide = HSTRING::from(name); + // SAFETY: D3D12 PipelineLibrary store call with valid wide name and pipeline state pointer. + if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), pso) }.is_ok() { + l.added += 1; + PENDING_ADDED.fetch_add(1, Ordering::Release); + counter.fetch_add(1, Ordering::Relaxed); + l.added >= BATCH_SAVE_THRESHOLD + } else { + false + } + }; + if should_save { + save(false); + } +} + +/// Stores a newly compiled graphics pipeline into the library. +pub fn store_graphics(name: &str, pso: &ID3D12PipelineState) { + store_pipeline(name, pso, &GRAPHICS_STORED); +} + +/// Attempts to load a compute pipeline from the persistent library. +pub fn load_compute( + name: &str, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, +) -> Option { + let lib_mutex = library()?; + let l = lib_mutex.lock().unwrap(); + let wide = HSTRING::from(name); + // SAFETY: D3D12 PipelineLibrary load call with valid pointer and descriptor references. + let res: windows::core::Result = unsafe { + l.library.LoadComputePipeline(PCWSTR(wide.as_ptr()), desc) + }; + match res { + Ok(pso) => { + COMPUTE_LOADED.fetch_add(1, Ordering::Relaxed); + Some(pso) + } + Err(_) => None, + } +} + +/// Stores a newly compiled compute pipeline into the library. +pub fn store_compute(name: &str, pso: &ID3D12PipelineState) { + store_pipeline(name, pso, &COMPUTE_STORED); +} + +/// Logs telemetry summary of loaded vs stored pipelines. +pub fn log_summary() { + static LOGGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !enabled() || library().is_none() { + return; + } + if LOGGED.swap(true, Ordering::Relaxed) { + return; + } + let gl = GRAPHICS_LOADED.load(Ordering::Relaxed); + let cl = COMPUTE_LOADED.load(Ordering::Relaxed); + let gs = GRAPHICS_STORED.load(Ordering::Relaxed); + let cs = COMPUTE_STORED.load(Ordering::Relaxed); + crate::xlog_info!( + "D3D12.X: pipeline library summary: {gl} graphics loaded, {cl} compute loaded, {gs} graphics stored, {cs} compute stored" + ); +} + +/// Serializes and writes the library to disk if new pipelines were stored. +pub fn save(now: bool) { + // Serialize-then-write order must remain monotonic so an earlier snapshot cannot overwrite a newer one. + static SAVE_IO: Mutex<()> = Mutex::new(()); + const SAVE_EVERY_MS: u64 = 20_000; + + if now { + log_summary(); + } + + let (Some(dir), Some(lib_mutex)) = (DIR.get(), library()) else { return }; + // Avoid blocking frame presentation on SAVE_IO when nothing is pending, within throttle, or busy. + let pending = PENDING_ADDED.load(Ordering::Acquire); + if pending == 0 { + return; + } + let now_ms = SAVE_EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + 1; + let prev_ms = LAST_SAVE_MS.load(Ordering::Relaxed); + if !now && pending < BATCH_SAVE_THRESHOLD && prev_ms != 0 && now_ms.saturating_sub(prev_ms) < SAVE_EVERY_MS { + return; + } + let _io_guard = if now { + SAVE_IO.lock().unwrap() + } else { + match SAVE_IO.try_lock() { + Ok(g) => g, + Err(_) => return, + } + }; + + let blob = { + let mut l = lib_mutex.lock().unwrap(); + if l.added == 0 { + return; + } + let batch_ready = l.added >= BATCH_SAVE_THRESHOLD; + let prev_ms = LAST_SAVE_MS.load(Ordering::Relaxed); + if !now && !batch_ready && prev_ms != 0 && now_ms.saturating_sub(prev_ms) < SAVE_EVERY_MS { + return; + } + LAST_SAVE_MS.store(now_ms, Ordering::Relaxed); + + // SAFETY: allocating exact byte buffer queried from GetSerializedSize. + let bytes = unsafe { + let size = l.library.GetSerializedSize(); + let mut bytes = vec![0u8; size]; + l.library.Serialize(&mut bytes).map(|()| bytes) + }; + match bytes { + Ok(bytes) => { + l.added = 0; + PENDING_ADDED.store(0, Ordering::Release); + bytes + } + Err(e) => { + crate::xlog_warn!("D3D12.X: pipeline library serialization failed: {e}"); + return; + } + } + }; + + let target = dir.join(LIBRARY_FILE); + if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| write_atomically(&target, &blob)) { + crate::xlog_warn!("D3D12.X: saving pipeline library to {} failed: {e}", target.display()); + } else { + crate::xlog_info!( + "D3D12.X: saved pipeline library ({} B, {} graphics loaded, {} compute loaded)", + blob.len(), + GRAPHICS_LOADED.load(Ordering::Relaxed), + COMPUTE_LOADED.load(Ordering::Relaxed) + ); + } +} + +fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + static SEQ: AtomicU64 = AtomicU64::new(0); + let tmp = path.with_extension(format!("tmp{}_{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + std::fs::write(&tmp, bytes)?; + if path.exists() { + let _ = std::fs::remove_file(path); + } + std::fs::rename(&tmp, path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pipeline_names_are_deterministic_and_differentiate_states() { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT; + + let vs = b"dxil_vertex_shader_bytecode_test"; + let ps1 = b"dxil_pixel_shader_bytecode_test_1"; + let ps2 = b"dxil_pixel_shader_bytecode_test_2"; + + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + + let n1 = graphics_pso_name(&desc, vs, Some(ps1), None); + let n1_dup = graphics_pso_name(&desc, vs, Some(ps1), None); + let n2 = graphics_pso_name(&desc, vs, Some(ps2), None); + + assert_eq!(n1, n1_dup); + assert_ne!(n1, n2); + + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; + let n3 = graphics_pso_name(&desc, vs, Some(ps1), None); + assert_ne!(n1, n3); + + // Blend state differentiation + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.BlendState.RenderTarget[0].BlendEnable = true.into(); + let n_blend = graphics_pso_name(&desc, vs, Some(ps1), None); + assert_ne!(n1, n_blend); + + // Depth/stencil state differentiation + desc.BlendState.RenderTarget[0].BlendEnable = false.into(); + desc.DepthStencilState.DepthEnable = true.into(); + let n_depth = graphics_pso_name(&desc, vs, Some(ps1), None); + assert_ne!(n1, n_depth); + + // Render target format differentiation + desc.DepthStencilState.DepthEnable = false.into(); + desc.RTVFormats[0] = DXGI_FORMAT_R16G16B16A16_FLOAT; + let n_fmt = graphics_pso_name(&desc, vs, Some(ps1), None); + assert_ne!(n1, n_fmt); + } + + #[test] + fn compute_pipeline_names_differentiate_flags_and_shaders() { + let cs1 = b"dxil_compute_shader_bytecode_test_1"; + let cs2 = b"dxil_compute_shader_bytecode_test_2"; + + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + + let n1 = compute_pso_name(&desc, cs1); + let n1_dup = compute_pso_name(&desc, cs1); + let n2 = compute_pso_name(&desc, cs2); + + assert_eq!(n1, n1_dup); + assert_ne!(n1, n2); + + desc.Flags = D3D12_PIPELINE_STATE_FLAGS(1); + let n3 = compute_pso_name(&desc, cs1); + assert_ne!(n1, n3); + } + + #[test] + fn corrupted_blob_falls_back_to_empty_library() { + let Ok(dev) = crate::gpu::agility::create_device( + None::<&windows::core::IUnknown>, + windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0, + ) else { + return; + }; + let Ok(dev1) = dev.cast::() else { + return; + }; + + let corrupted = vec![0x7f; 1024]; + let lib = open(&dev1, corrupted).expect("failed to create fallback empty library after rejecting corrupted blob"); + assert!(lib._blob.is_empty()); + let size = unsafe { lib.library.GetSerializedSize() }; + assert!(size > 0); + } + + #[test] + fn atomic_file_writing_prevents_partial_writes() { + let dir = std::env::temp_dir().join(format!("xcl-pso-test-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("test-library.bin"); + + let data = b"serialized_pipeline_library_mock_payload"; + assert!(write_atomically(&path, data).is_ok()); + assert_eq!(std::fs::read(&path).unwrap(), data); + + let data2 = b"serialized_pipeline_library_second_write"; + assert!(write_atomically(&path, data2).is_ok()); + assert_eq!(std::fs::read(&path).unwrap(), data2); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn padding_bytes_do_not_affect_pipeline_hash() { + let vs = b"dxil_test_vs"; + let mut desc1 = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc1.BlendState.RenderTarget[0].RenderTargetWriteMask = 0x0f; + desc1.DepthStencilState.StencilWriteMask = 0xff; + + let mut raw = vec![0x7fu8; std::mem::size_of::()]; + let desc2 = unsafe { + let p = raw.as_mut_ptr() as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC; + std::ptr::write(p, D3D12_GRAPHICS_PIPELINE_STATE_DESC::default()); + (*p).BlendState.RenderTarget[0].RenderTargetWriteMask = 0x0f; + (*p).DepthStencilState.StencilWriteMask = 0xff; + + let rt_write_mask_ptr = &(*p).BlendState.RenderTarget[0].RenderTargetWriteMask as *const u8; + let blend_padding = std::slice::from_raw_parts_mut(rt_write_mask_ptr.add(1) as *mut u8, 3); + blend_padding.fill(0xee); + + let ds_write_mask_ptr = &(*p).DepthStencilState.StencilWriteMask as *const u8; + let ds_padding = std::slice::from_raw_parts_mut(ds_write_mask_ptr.add(1) as *mut u8, 2); + ds_padding.fill(0xcc); + &*p + }; + + let n1 = graphics_pso_name(&desc1, vs, None, None); + let n2 = graphics_pso_name(desc2, vs, None, None); + assert_eq!(n1, n2); + } + + #[test] + fn telemetry_counters_track_loads_and_stores() { + let gl_before = GRAPHICS_LOADED.load(Ordering::Relaxed); + let cl_before = COMPUTE_LOADED.load(Ordering::Relaxed); + let gs_before = GRAPHICS_STORED.load(Ordering::Relaxed); + let cs_before = COMPUTE_STORED.load(Ordering::Relaxed); + + GRAPHICS_LOADED.fetch_add(2, Ordering::Relaxed); + COMPUTE_LOADED.fetch_add(3, Ordering::Relaxed); + GRAPHICS_STORED.fetch_add(4, Ordering::Relaxed); + COMPUTE_STORED.fetch_add(5, Ordering::Relaxed); + + assert_eq!(GRAPHICS_LOADED.load(Ordering::Relaxed), gl_before + 2); + assert_eq!(COMPUTE_LOADED.load(Ordering::Relaxed), cl_before + 3); + assert_eq!(GRAPHICS_STORED.load(Ordering::Relaxed), gs_before + 4); + assert_eq!(COMPUTE_STORED.load(Ordering::Relaxed), cs_before + 5); + + log_summary(); + } + + #[test] + fn input_layout_differentiates_graphics_pipeline_names() { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32B32_FLOAT; + use windows::core::PCSTR; + + let vs = b"dxil_vs_layout_test"; + let elems_a = [D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(b"POSITION\0".as_ptr()), + SemanticIndex: 0, + Format: DXGI_FORMAT_R32G32B32_FLOAT, + InputSlot: 0, + AlignedByteOffset: 0, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }]; + let elems_b = [D3D12_INPUT_ELEMENT_DESC { + AlignedByteOffset: 16, + ..elems_a[0] + }]; + + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: elems_a.as_ptr(), + NumElements: elems_a.len() as u32, + }; + let n_a = graphics_pso_name(&desc, vs, None, None); + + desc.InputLayout.pInputElementDescs = elems_b.as_ptr(); + let n_b = graphics_pso_name(&desc, vs, None, None); + assert_ne!(n_a, n_b); + + desc.InputLayout = D3D12_INPUT_LAYOUT_DESC::default(); + let n_empty = graphics_pso_name(&desc, vs, None, None); + assert_ne!(n_a, n_empty); + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..d9a0d421bc 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -365,6 +365,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); + super::pipeline_library::save(true); crate::report::write_final(None); crate::log::flush(); windows::Win32::System::Threading::ExitProcess(0); @@ -1216,6 +1217,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, return; } p.last = Instant::now(); + super::pipeline_library::save(false); if !p.dumps.is_empty() { match fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 2000) { Ok(()) => { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..72bb0f090b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -547,6 +547,7 @@ pub fn init() -> Result { } open_uma(&device); super::device_x::probe_dynamic_depth_bias(&device); + super::pipeline_library::init(&device); let raw = device.into_raw(); // one reference kept for the process lifetime adopt(raw, Kind::Device); DEVICE.store(raw as usize, Ordering::Release); @@ -1948,21 +1949,20 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT}; + use super::console_heap::slot; let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; if d0.sampler != s0.sampler { return false; } + let n = n.min(s0.remaining).min(d0.remaining); + if n == 0 { + return true; + } let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); super::console_heap::publish_range(&d0, n); - let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; - for k in 0..n as u64 { - if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { - copy_words(&s, &d); - } - } + super::console_heap::copy_range(&s0, &d0, n); true } @@ -3916,6 +3916,9 @@ unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::Sta match crate::gpu::recomp::pso::abi_root_signature_with(dev, true, samplers) { Ok(rs) => { let raw = rs.into_raw(); + let key_bytes = unsafe { std::slice::from_raw_parts(key.as_ptr() as *const u8, key.len() * 4) }; + let rs_hash = crate::gpu::shader::fnv64(key_bytes) ^ 0x5843_4c5f_4142_4901u64; + super::pipeline_library::note_root_signature(raw as usize, rs_hash); map.insert(key, raw as usize); Some(raw) } @@ -3936,6 +3939,7 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { match crate::gpu::recomp::pso::abi_root_signature(dev, true) { Ok(rs) => { let raw = rs.into_raw(); + super::pipeline_library::note_root_signature(raw as usize, 0x5843_4c5f_4142_4901u64); match ABI_RS.compare_exchange(0, raw as usize, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => Some(raw), Err(other) => { @@ -4421,6 +4425,21 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + + let pso_name = super::pipeline_library::compute_pso_name(©, dxil); + if let Some(cached_pso) = super::pipeline_library::load_compute(&pso_name, ©) { + let raw = cached_pso.into_raw() as *mut c_void; + adopt(raw, Kind::PipelineState); + *ppv = raw; + if !chained { + let n = TRANSLATED_PSO.load(Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: loaded compute PSO from pipeline library ({pso_name})"); + } + } + return (S_OK, std::time::Duration::ZERO, true); + } + // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); @@ -4473,6 +4492,11 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } else if reused && from_disk { driver_cache::note(true, None); } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(pso_ref) = ID3D12PipelineState::from_raw_borrowed(&*ppv) { + super::pipeline_library::store_compute(&pso_name, &pso_ref); + } + } (hr, in_driver, reused) } @@ -5254,6 +5278,25 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } + let gs_bytes = rect_gs.as_deref().or_else(|| shader_bytes(©.GS)); + let pso_name = super::pipeline_library::graphics_pso_name(©, &vs_dxil, ps_dxil.as_deref(), gs_bytes); + if let Some(cached_pso) = super::pipeline_library::load_graphics(&pso_name, ©) { + let raw = cached_pso.into_raw() as *mut c_void; + adopt(raw, Kind::PipelineState); + *ppv = raw; + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if super::present::trace_frame() { + let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + } + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: loaded graphics PSO from pipeline library ({pso_name})"); + } + return Some(S_OK); + } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); let mut cached = graphics_blob(gkey); @@ -5284,6 +5327,16 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if build.reused && from_disk { driver_cache::note(true, None); } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(pso_ref) = ID3D12PipelineState::from_raw_borrowed(&*ppv) { + let actual_name = if copy.GS.pShaderBytecode.is_null() && rect_gs.is_some() { + super::pipeline_library::graphics_pso_name(©, &vs_dxil, ps_dxil.as_deref(), None) + } else { + pso_name + }; + super::pipeline_library::store_graphics(&actual_name, &pso_ref); + } + } if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -6859,6 +6912,9 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 if n < 5 { crate::xlog_warn!("D3D12.X: root signature rejected ({hr:#x}) – empty fallback (#{})", n + 1); } + if !ppv.is_null() && !(*ppv).is_null() { + super::pipeline_library::note_root_signature(*ppv as usize, 0x5843_4c5f_454d_5054u64); + } hr = hr2; } } @@ -6867,7 +6923,9 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, Kind::RootSignature); if !blob.is_null() { - super::console_list::note_root_signature(*ppv as usize, std::slice::from_raw_parts(blob as *const u8, len)); + let bytes = std::slice::from_raw_parts(blob as *const u8, len); + super::console_list::note_root_signature(*ppv as usize, bytes); + super::pipeline_library::note_root_signature(*ppv as usize, crate::gpu::shader::fnv64(bytes)); } } hr diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49afe78..69cee887d2 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -412,6 +412,7 @@ pub fn on_tls_event(reason: u32) { }, 0 => { // DLL_PROCESS_DETACH (ExitProcess): write the report while everything is alive. + crate::hle::d3d12x::pipeline_library::save(true); crate::report::write_final(None); crate::log::flush(); } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 45b886e103..254fcebb79 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -169,6 +169,7 @@ fn lock_within(m: &Mutex, wait: Duration) -> Option> { /// Write `report.json` (host side). `crash` is remembered for later writes. pub fn write_final(crash: Option) { + crate::hle::d3d12x::pipeline_library::save(true); // the process ends: a cursor held in the XCL window is let go crate::hle::kbm::release(); // `XCL_DIRECT_DXIL_STATS=1`: the direct DXIL translator's live fallback summary From a94863e154992841424c18239b229e617db250e2 Mon Sep 17 00:00:00 2001 From: Shadow Date: Wed, 25 Nov 2026 15:23:17 +0600 Subject: [PATCH 2/3] d3d12x: offload periodic pipeline library saves from present thread --- crates/xcl/src/hle/d3d12x/pipeline_library.rs | 79 ++++++++++++++++--- crates/xcl/src/hle/d3d12x/present.rs | 2 +- 2 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pipeline_library.rs b/crates/xcl/src/hle/d3d12x/pipeline_library.rs index 81b1bf20ba..2d48ef73df 100644 --- a/crates/xcl/src/hle/d3d12x/pipeline_library.rs +++ b/crates/xcl/src/hle/d3d12x/pipeline_library.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use windows::Win32::Graphics::Direct3D12::*; @@ -279,6 +279,32 @@ pub fn load_graphics( static PENDING_ADDED: AtomicU64 = AtomicU64::new(0); static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); static SAVE_EPOCH: OnceLock = OnceLock::new(); +static BG_SAVING: AtomicBool = AtomicBool::new(false); + +const SAVE_EVERY_MS: u64 = 20_000; + +fn current_save_ms() -> u64 { + SAVE_EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + 1 +} + +fn due(pending: u64, now: bool, prev_ms: u64, now_ms: u64) -> bool { + if pending == 0 { + return false; + } + now || pending >= BATCH_SAVE_THRESHOLD || prev_ms == 0 || now_ms.saturating_sub(prev_ms) >= SAVE_EVERY_MS +} + +fn save_due(now: bool, now_ms: u64) -> bool { + if DIR.get().is_none() || library().is_none() { + return false; + } + due( + PENDING_ADDED.load(Ordering::Acquire), + now, + LAST_SAVE_MS.load(Ordering::Relaxed), + now_ms, + ) +} fn store_pipeline(name: &str, pso: &ID3D12PipelineState, counter: &AtomicU64) { let Some(lib_mutex) = library() else { return }; @@ -349,25 +375,46 @@ pub fn log_summary() { ); } +/// Requests a non-blocking background save when new pipelines are due, so frame +/// presentation never serializes or writes to disk on the render thread. +pub fn save_async() { + if !save_due(false, current_save_ms()) { + return; + } + if BG_SAVING.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + return; + } + if std::thread::Builder::new() + .name("xcl-pso-save".into()) + .spawn(|| { + struct Guard; + impl Drop for Guard { + fn drop(&mut self) { + BG_SAVING.store(false, Ordering::Release); + } + } + let _guard = Guard; + save(false); + }) + .is_err() + { + BG_SAVING.store(false, Ordering::Release); + } +} + /// Serializes and writes the library to disk if new pipelines were stored. pub fn save(now: bool) { // Serialize-then-write order must remain monotonic so an earlier snapshot cannot overwrite a newer one. static SAVE_IO: Mutex<()> = Mutex::new(()); - const SAVE_EVERY_MS: u64 = 20_000; if now { log_summary(); } let (Some(dir), Some(lib_mutex)) = (DIR.get(), library()) else { return }; - // Avoid blocking frame presentation on SAVE_IO when nothing is pending, within throttle, or busy. - let pending = PENDING_ADDED.load(Ordering::Acquire); - if pending == 0 { - return; - } - let now_ms = SAVE_EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + 1; - let prev_ms = LAST_SAVE_MS.load(Ordering::Relaxed); - if !now && pending < BATCH_SAVE_THRESHOLD && prev_ms != 0 && now_ms.saturating_sub(prev_ms) < SAVE_EVERY_MS { + // Avoid blocking callers on SAVE_IO when nothing is pending, within throttle, or busy. + let now_ms = current_save_ms(); + if !save_due(now, now_ms) { return; } let _io_guard = if now { @@ -621,4 +668,16 @@ mod tests { let n_empty = graphics_pso_name(&desc, vs, None, None); assert_ne!(n_a, n_empty); } + + #[test] + fn save_due_respects_pending_and_throttle() { + assert!(!due(0, true, 0, 50_000)); + assert!(!due(0, false, 0, 50_000)); + assert!(due(1, false, 0, 100)); + assert!(!due(1, false, 10_000, 29_999)); + assert!(due(1, false, 10_000, 30_000)); + assert!(due(BATCH_SAVE_THRESHOLD, false, 10_000, 10_001)); + assert!(due(1, true, 10_000, 10_001)); + save_async(); + } } diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d9a0d421bc..b011bfaca3 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1217,7 +1217,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, return; } p.last = Instant::now(); - super::pipeline_library::save(false); + super::pipeline_library::save_async(); if !p.dumps.is_empty() { match fence::wait(&p.fence, p.value, &p.dev, Some(p.event), 2000) { Ok(()) => { From ec5bac99305d4b56305db37206b87822818d2b44 Mon Sep 17 00:00:00 2001 From: Shadow Date: Wed, 25 Nov 2026 22:05:27 +0600 Subject: [PATCH 3/3] d3d12x: offload threshold pipeline saves and fix paged copy_range --- crates/xcl/src/hle/d3d12x/console_heap.rs | 130 +++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- crates/xcl/src/hle/d3d12x/pipeline_library.rs | 126 +++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 15 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 4 + 5 files changed, 252 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c903be957..82eb434113 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -560,9 +560,12 @@ pub fn copy_words(src: &Slot, dst: &Slot) { } /// Copy `n` contiguous console descriptors from `src` to `dst`. Renumbers destination -/// indices without per-slot mutex acquisitions, splitting at page boundaries. +/// indices without per-slot mutex acquisitions on mapped pages, splitting at page boundaries. /// Clamps `n` to the remaining capacity of both heaps. pub fn copy_range(src: &Slot, dst: &Slot, n: u32) { + if src.sampler != dst.sampler { + return; + } let n = n.min(src.remaining).min(dst.remaining); if n == 0 { return; @@ -570,6 +573,7 @@ pub fn copy_range(src: &Slot, dst: &Slot, n: u32) { let step = if src.sampler { SAMPLER_SLOT } else { SLOT } as usize; let index_step = if src.sampler { 1 } else { 2 }; let words = if src.sampler { 4 } else { 8 }; + let page_slots = if dst.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; let mut done = 0; while done < n { let dst_slot = if done == 0 { @@ -578,16 +582,23 @@ pub fn copy_range(src: &Slot, dst: &Slot, n: u32) { let Some(s) = slot((dst.at + done as usize * step) as u64) else { break }; s }; - let run = if dst.sampler { - n - done - } else { - (PAGE_SLOTS - dst_slot.k % PAGE_SLOTS).min(n - done) - }; + let run = (page_slots - dst_slot.k % page_slots).min(n - done).min(dst_slot.remaining); + if run == 0 { + break; + } + // Unmapped sampler slots may belong to an exhausted shared heap (index 0) or an unhosted + // heap (local k); resolve each slot directly in that rare fallback. + let per_slot_sampler = dst_slot.sampler && dst_slot.shared_srv == 0; for k in 0..run as usize { let offset = (done as usize + k) * step; let src_at = src.at + offset; let dst_at = dst.at + offset; - let dst_index = dst_slot.index + (k as u32 * index_step); + let dst_index = if per_slot_sampler && k > 0 { + let Some(s) = slot(dst_at as u64) else { break }; + s.index + } else { + dst_slot.index + (k as u32 * index_step) + }; let mut w = [0u32; 8]; unsafe { std::ptr::copy_nonoverlapping(src_at as *const u32, w.as_mut_ptr(), words); @@ -1255,4 +1266,109 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + #[test] + fn copy_range_crosses_noncontiguous_pages_and_clamps_oob() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + if crate::gpu::uma::get().is_none() { + return; + } + let dev = unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + dev.expect("D3D12 device") + }; + assert!(unsafe { shared_heap(&dev) }); + + // Force heap A's page 0 and page 1 to be non-contiguous in GLOBAL by allocating heap B between them. + const N_VIEWS: u32 = PAGE_SLOTS + 6; + assert!(register(0xC100, N_VIEWS, 0x10_0000, 0, 32, false, true, true)); + assert!(register(0xC101, 4, 0x20_0000, 0, 32, false, true, true)); + let va = start(0xC100).unwrap(); + let vb = start(0xC101).unwrap(); + let a_p0 = slot(va).unwrap(); + let _b_p0 = slot(vb).unwrap(); + let a_p1 = slot(va + (PAGE_SLOTS * SLOT) as u64).unwrap(); + assert_ne!(a_p1.index, a_p0.index + 2 * PAGE_SLOTS, "heap A pages 0 and 1 must be non-contiguous"); + + for k in 0..4u32 { + let s = slot(va + (k * SLOT) as u64).unwrap(); + write(&s, &[s.index, 0x0500_0000 + k, 0, 9 << 28, 0, 0, 0, 0]); + } + let dst_cross = slot(va + ((PAGE_SLOTS - 2) * SLOT) as u64).unwrap(); + copy_range(&a_p0, &dst_cross, 4); + for offset in 0..4u32 { + let k = PAGE_SLOTS - 2 + offset; + let expected_slot = slot(va + (k * SLOT) as u64).unwrap(); + let w = unsafe { *(expected_slot.at as *const [u32; 8]) }; + assert_eq!(w[0], expected_slot.index, "view slot {k} must get page-mapped index"); + assert_eq!(w[1], 0x0500_0000 + offset); + } + + // Clamps OOB destination range (`dst.k + n > h.n`) and source range (`src.k + n > src_h.n`). + let dst_tail = slot(va + ((N_VIEWS - 2) * SLOT) as u64).unwrap(); + assert_eq!(dst_tail.remaining, 2); + copy_range(&a_p0, &dst_tail, 100); + for offset in 0..2u32 { + let expected_slot = slot(va + ((N_VIEWS - 2 + offset) * SLOT) as u64).unwrap(); + let w = unsafe { *(expected_slot.at as *const [u32; 8]) }; + assert_eq!(w[0], expected_slot.index); + assert_eq!(w[1], 0x0500_0000 + offset); + } + let src_tail = slot(va + ((N_VIEWS - 1) * SLOT) as u64).unwrap(); + let dst_mid = slot(va + (10 * SLOT) as u64).unwrap(); + let dst_mid_next = slot(va + (11 * SLOT) as u64).unwrap(); + write(&dst_mid_next, &[0xDEAD_BEEF, 0xCAFE_BABE, 0, 9 << 28, 0, 0, 0, 0]); + copy_range(&src_tail, &dst_mid, 10); + let w_mid = unsafe { *(dst_mid.at as *const [u32; 8]) }; + let w_mid_next = unsafe { *(dst_mid_next.at as *const [u32; 8]) }; + assert_eq!(w_mid[0], dst_mid.index); + assert_eq!(w_mid[1], 0x0500_0001); + assert_eq!(w_mid_next[1], 0xCAFE_BABE, "clamped source range must not overwrite dst_mid + 1"); + + // Zero-count and mismatched-kind copies are no-ops. + copy_range(&a_p0, &dst_mid_next, 0); + assert_eq!(unsafe { *(dst_mid_next.at as *const [u32; 8]) }[1], 0xCAFE_BABE); + + if unsafe { shared_sampler_heap(&dev) } { + const N_SAMPLERS: u32 = SAMPLER_PAGE_SLOTS + 4; + assert!(register(0xC200, N_SAMPLERS, 0x30_0000, 0, 16, true, true, true)); + assert!(register(0xC201, 4, 0x40_0000, 0, 16, true, true, true)); + let sa = start(0xC200).unwrap(); + let sb = start(0xC201).unwrap(); + let sa_p0 = slot(sa).unwrap(); + let _sb_p0 = slot(sb).unwrap(); + let sa_p1 = slot(sa + (SAMPLER_PAGE_SLOTS * SAMPLER_SLOT) as u64).unwrap(); + assert_ne!(sa_p1.index, sa_p0.index + SAMPLER_PAGE_SLOTS, "sampler pages 0 and 1 must be non-contiguous"); + + for k in 0..4u32 { + let s = slot(sa + (k * SAMPLER_SLOT) as u64).unwrap(); + write(&s, &[0xAA00 + k, 2, 3, 0xABC0_0000 | (s.index & 0xFFF)]); + } + let s_cross = slot(sa + ((SAMPLER_PAGE_SLOTS - 2) * SAMPLER_SLOT) as u64).unwrap(); + copy_range(&sa_p0, &s_cross, 4); + for offset in 0..4u32 { + let k = SAMPLER_PAGE_SLOTS - 2 + offset; + let expected_slot = slot(sa + (k * SAMPLER_SLOT) as u64).unwrap(); + let w = unsafe { *(expected_slot.at as *const [u32; 4]) }; + assert_eq!(w[3] & 0xFFF, expected_slot.index, "sampler slot {k} must get page-mapped index"); + assert_eq!(w[0], 0xAA00 + offset); + } + + // Mismatched kinds must not copy. + copy_range(&a_p0, &s_cross, 1); + assert_eq!(unsafe { *(s_cross.at as *const [u32; 4]) }[0], 0xAA00); + + unregister(0xC200); + unregister(0xC201); + } + + unregister(0xC100); + unregister(0xC101); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..8ccf277a12 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -7315,7 +7315,7 @@ mod tests { #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0, remaining: 1 }); assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, diff --git a/crates/xcl/src/hle/d3d12x/pipeline_library.rs b/crates/xcl/src/hle/d3d12x/pipeline_library.rs index 2d48ef73df..e1de9a1f4b 100644 --- a/crates/xcl/src/hle/d3d12x/pipeline_library.rs +++ b/crates/xcl/src/hle/d3d12x/pipeline_library.rs @@ -280,6 +280,7 @@ static PENDING_ADDED: AtomicU64 = AtomicU64::new(0); static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); static SAVE_EPOCH: OnceLock = OnceLock::new(); static BG_SAVING: AtomicBool = AtomicBool::new(false); +static SAVE_REQUESTED: AtomicBool = AtomicBool::new(false); const SAVE_EVERY_MS: u64 = 20_000; @@ -322,7 +323,7 @@ fn store_pipeline(name: &str, pso: &ID3D12PipelineState, counter: &AtomicU64) { } }; if should_save { - save(false); + save_async(); } } @@ -376,12 +377,13 @@ pub fn log_summary() { } /// Requests a non-blocking background save when new pipelines are due, so frame -/// presentation never serializes or writes to disk on the render thread. +/// presentation and pipeline build threads never serialize or write to disk. pub fn save_async() { if !save_due(false, current_save_ms()) { return; } - if BG_SAVING.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + SAVE_REQUESTED.store(true, Ordering::SeqCst); + if BG_SAVING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() { return; } if std::thread::Builder::new() @@ -390,20 +392,41 @@ pub fn save_async() { struct Guard; impl Drop for Guard { fn drop(&mut self) { - BG_SAVING.store(false, Ordering::Release); + BG_SAVING.store(false, Ordering::SeqCst); } } let _guard = Guard; - save(false); + loop { + SAVE_REQUESTED.store(false, Ordering::SeqCst); + let wrote = save_inner(false); + if wrote && SAVE_REQUESTED.load(Ordering::SeqCst) && save_due(false, current_save_ms()) { + continue; + } + BG_SAVING.store(false, Ordering::SeqCst); + // Re-check after clearing BG_SAVING so a request arriving right before + // the flag cleared is never stranded when no frame presents follow. + if wrote + && SAVE_REQUESTED.load(Ordering::SeqCst) + && save_due(false, current_save_ms()) + && BG_SAVING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok() + { + continue; + } + break; + } }) .is_err() { - BG_SAVING.store(false, Ordering::Release); + BG_SAVING.store(false, Ordering::SeqCst); } } /// Serializes and writes the library to disk if new pipelines were stored. pub fn save(now: bool) { + let _ = save_inner(now); +} + +fn save_inner(now: bool) -> bool { // Serialize-then-write order must remain monotonic so an earlier snapshot cannot overwrite a newer one. static SAVE_IO: Mutex<()> = Mutex::new(()); @@ -411,30 +434,30 @@ pub fn save(now: bool) { log_summary(); } - let (Some(dir), Some(lib_mutex)) = (DIR.get(), library()) else { return }; + let (Some(dir), Some(lib_mutex)) = (DIR.get(), library()) else { return false }; // Avoid blocking callers on SAVE_IO when nothing is pending, within throttle, or busy. let now_ms = current_save_ms(); if !save_due(now, now_ms) { - return; + return false; } let _io_guard = if now { SAVE_IO.lock().unwrap() } else { match SAVE_IO.try_lock() { Ok(g) => g, - Err(_) => return, + Err(_) => return false, } }; let blob = { let mut l = lib_mutex.lock().unwrap(); if l.added == 0 { - return; + return false; } let batch_ready = l.added >= BATCH_SAVE_THRESHOLD; let prev_ms = LAST_SAVE_MS.load(Ordering::Relaxed); if !now && !batch_ready && prev_ms != 0 && now_ms.saturating_sub(prev_ms) < SAVE_EVERY_MS { - return; + return false; } LAST_SAVE_MS.store(now_ms, Ordering::Relaxed); @@ -452,7 +475,7 @@ pub fn save(now: bool) { } Err(e) => { crate::xlog_warn!("D3D12.X: pipeline library serialization failed: {e}"); - return; + return false; } } }; @@ -460,6 +483,7 @@ pub fn save(now: bool) { let target = dir.join(LIBRARY_FILE); if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| write_atomically(&target, &blob)) { crate::xlog_warn!("D3D12.X: saving pipeline library to {} failed: {e}", target.display()); + false } else { crate::xlog_info!( "D3D12.X: saved pipeline library ({} B, {} graphics loaded, {} compute loaded)", @@ -467,6 +491,7 @@ pub fn save(now: bool) { GRAPHICS_LOADED.load(Ordering::Relaxed), COMPUTE_LOADED.load(Ordering::Relaxed) ); + true } } @@ -680,4 +705,81 @@ mod tests { assert!(due(1, true, 10_000, 10_001)); save_async(); } + + #[test] + fn root_signature_hash_is_stable_across_com_pointers() { + use std::ffi::c_void; + use std::mem::ManuallyDrop; + + #[repr(C)] + struct FakeRootSig { + vt: *const usize, + } + unsafe extern "system" fn add_ref(_this: *mut c_void) -> u32 { + 1 + } + unsafe extern "system" fn release(_this: *mut c_void) -> u32 { + 1 + } + let mut vt = [0usize; 4]; + vt[1] = add_ref as usize; + vt[2] = release as usize; + + let mut obj_a = FakeRootSig { vt: vt.as_ptr() }; + let mut obj_b = FakeRootSig { vt: vt.as_ptr() }; + let ptr_a = &mut obj_a as *mut _ as usize; + let ptr_b = &mut obj_b as *mut _ as usize; + assert_ne!(ptr_a, ptr_b); + + const HASH_ONE: u64 = 0x1122_3344_5566_7788; + const HASH_TWO: u64 = 0x8877_6655_4433_2211; + note_root_signature(ptr_a, HASH_ONE); + note_root_signature(ptr_b, HASH_ONE); + + unsafe { + let rs_a = ManuallyDrop::new(Some(ID3D12RootSignature::from_raw(ptr_a as *mut c_void))); + let rs_b = ManuallyDrop::new(Some(ID3D12RootSignature::from_raw(ptr_b as *mut c_void))); + + let vs = b"dxil_vs_rs_test"; + let ps = b"dxil_ps_rs_test"; + let cs = b"dxil_cs_rs_test"; + + let gdesc_a = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::ptr::read(&rs_a), + ..Default::default() + }; + let gdesc_b = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::ptr::read(&rs_b), + ..Default::default() + }; + + let gp_a = graphics_pso_name(&gdesc_a, vs, Some(ps), None); + let gp_b = graphics_pso_name(&gdesc_b, vs, Some(ps), None); + assert_eq!(gp_a, gp_b, "same root signature hash at different COM addresses must yield identical graphics PSO names"); + + let cdesc_a = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::ptr::read(&rs_a), + ..Default::default() + }; + let cdesc_b = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::ptr::read(&rs_b), + ..Default::default() + }; + + let cp_a = compute_pso_name(&cdesc_a, cs); + let cp_b = compute_pso_name(&cdesc_b, cs); + assert_eq!(cp_a, cp_b, "same root signature hash at different COM addresses must yield identical compute PSO names"); + + note_root_signature(ptr_b, HASH_TWO); + let gp_b2 = graphics_pso_name(&gdesc_b, vs, Some(ps), None); + let cp_b2 = compute_pso_name(&cdesc_b, cs); + assert_ne!(gp_a, gp_b2, "distinct root signature hashes must differentiate graphics PSO names"); + assert_ne!(cp_a, cp_b2, "distinct root signature hashes must differentiate compute PSO names"); + } + + if let Some(m) = ROOT_SIG_HASHES.lock().unwrap().as_mut() { + m.remove(&ptr_a); + m.remove(&ptr_b); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 72bb0f090b..2925214d1e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4431,7 +4431,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let raw = cached_pso.into_raw() as *mut c_void; adopt(raw, Kind::PipelineState); *ppv = raw; - if !chained { + if mode != ComputeBuild::Chain { let n = TRANSLATED_PSO.load(Ordering::Relaxed); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: loaded compute PSO from pipeline library ({pso_name})"); @@ -4494,7 +4494,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(pso_ref) = ID3D12PipelineState::from_raw_borrowed(&*ppv) { - super::pipeline_library::store_compute(&pso_name, &pso_ref); + super::pipeline_library::store_compute(&pso_name, pso_ref); } } (hr, in_driver, reused) @@ -5286,6 +5286,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const *ppv = raw; let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if super::present::trace_frame() { @@ -5334,7 +5335,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else { pso_name }; - super::pipeline_library::store_graphics(&actual_name, &pso_ref); + super::pipeline_library::store_graphics(&actual_name, pso_ref); } } if hr < 0 { @@ -6899,8 +6900,9 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 let iid = pc_iid(Kind::RootSignature); hr = f(this, mask, blob, len, &iid, ppv); } + let mut used_fallback = false; if hr < 0 { - // console root signature rejected → empty one so the title keeps going + // console root signature rejected -> empty one so the title keeps going let desc = D3D12_ROOT_SIGNATURE_DESC { Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ..Default::default() }; let mut ser = None; if D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).is_ok() { @@ -6915,6 +6917,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 if !ppv.is_null() && !(*ppv).is_null() { super::pipeline_library::note_root_signature(*ppv as usize, 0x5843_4c5f_454d_5054u64); } + used_fallback = true; hr = hr2; } } @@ -6925,7 +6928,9 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 if !blob.is_null() { let bytes = std::slice::from_raw_parts(blob as *const u8, len); super::console_list::note_root_signature(*ppv as usize, bytes); - super::pipeline_library::note_root_signature(*ppv as usize, crate::gpu::shader::fnv64(bytes)); + if !used_fallback { + super::pipeline_library::note_root_signature(*ppv as usize, crate::gpu::shader::fnv64(bytes)); + } } } hr diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..a10a4bfd80 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -77,6 +77,10 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let dev = ID3D12Device::from_raw_borrowed(&this)?; let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; let rs = signature.as_raw() as usize; + let key: Vec = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); + let key_bytes = unsafe { std::slice::from_raw_parts(key.as_ptr() as *const u8, key.len() * 4) }; + let rs_hash = crate::gpu::shader::fnv64(key_bytes) ^ 0x5843_4c5f_4348_4149u64; + super::super::pipeline_library::note_root_signature(rs, rs_hash); let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, flags: desc.Flags, node: desc.NodeMask, record }); let jobs = (0..plan.pieces.len()).map(|i| {