diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 260207086e..4221fe40bf 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -325,11 +325,13 @@ fn clear_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { struct GfxDesc([u8; GFX_DESC]); /// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX and the -/// patched-PSO fallback of RSSetDepthBiasX. The input layout is copied; the shaders stay the -/// title's and are checked by hash when a pipeline is derived from it. +/// patched-PSO fallback of RSSetDepthBiasX. Input layout is copied and stage shader bytecodes are +/// interned into a shared pool (`Arc<[u8]>`) so tens of thousands of PSOs sharing a few thousand +/// unique shaders hold only one copy per unique shader and stay valid after the title frees its +/// original bytecode buffers. struct Base { desc: GfxDesc, - shaders: [u64; 5], + shader_blobs: [Option>; 5], /// Whether this PSO was created with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS`. dynamic_depth_bias: bool, /// Original static `RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias}`. @@ -338,11 +340,36 @@ struct Base { _names: Vec, } -// the desc points into `_elems` / `_names` and the title's shaders; nothing is mutated +// the desc points into `_elems` / `_names` and `shader_blobs` owns shared bytecode; nothing is mutated unsafe impl Send for Base {} unsafe impl Sync for Base {} +impl Base { + /// Clone the pipeline description with stage shader pointers bound to `self.shader_blobs` + /// (valid for the lifetime of `&self`). + fn desc_with_owned_shaders(&self) -> GfxDesc { + let mut d = self.desc; + for (k, &o) in STAGES.iter().enumerate() { + match &self.shader_blobs[k] { + Some(blob) => { + d.0[o..o + 8].copy_from_slice(&(blob.as_ptr() as u64).to_le_bytes()); + d.0[o + 8..o + 16].copy_from_slice(&(blob.len() as u64).to_le_bytes()); + } + None => d.0[o..o + 16].fill(0), + } + } + d + } +} + +struct ShaderPool { + map: HashMap<(u64, usize), std::sync::Weak<[u8]>>, + next_sweep: usize, +} + static BASES: Mutex>>> = Mutex::new(None); +/// Deduplicated shader bytecode pool shared across tracked `Base` graphics PSOs. +static BASE_SHADERS: Mutex> = Mutex::new(None); /// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. /// Released when the base PSO is released in `forget_base`. static DEPTH_BIAS_PSOS: Mutex>> = Mutex::new(None); @@ -355,19 +382,47 @@ fn rd64(d: &[u8], o: usize) -> u64 { u64::from_le_bytes(d[o..o + 8].try_into().unwrap()) } -/// hash of each stage's bytecode (0: none); None when one is not readable -unsafe fn stage_hashes(d: &[u8; GFX_DESC]) -> Option<[u64; 5]> { - let mut h = [0; 5]; +/// Intern `bytes` into `BASE_SHADERS` by `(fnv64, len)`, avoiding duplicate copies across PSOs. +fn intern_shader_blob(bytes: &[u8]) -> Arc<[u8]> { + let key = (crate::gpu::shader::fnv64(bytes), bytes.len()); + let candidate = { + let g = BASE_SHADERS.lock().unwrap(); + g.as_ref().and_then(|p| p.map.get(&key)).and_then(std::sync::Weak::upgrade) + }; + if let Some(existing) = candidate { + if &*existing == bytes { + return existing; + } + } + let arc: Arc<[u8]> = Arc::from(bytes); + let mut g = BASE_SHADERS.lock().unwrap(); + let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: 8192 }); + if let Some(existing) = pool.map.get(&key).and_then(std::sync::Weak::upgrade) { + if &*existing == bytes { + return existing; + } + } + if pool.map.len() >= pool.next_sweep { + pool.map.retain(|_, w| w.strong_count() > 0); + pool.next_sweep = (pool.map.len().saturating_mul(2)).max(8192); + } + pool.map.insert(key, Arc::downgrade(&arc)); + arc +} + +/// Intern each non-empty stage's shader bytecode; None when one is not readable. +unsafe fn stage_blobs(d: &[u8; GFX_DESC]) -> Option<[Option>; 5]> { + let mut blobs: [Option>; 5] = Default::default(); for (k, &o) in STAGES.iter().enumerate() { let (p, n) = (rd64(d, o) as usize, rd64(d, o + 8) as usize); if p != 0 && n != 0 { if !crate::gpu::shader::readable(p, n) { return None; } - h[k] = crate::gpu::shader::fnv64(std::slice::from_raw_parts(p as *const u8, n)); + blobs[k] = Some(intern_shader_blob(std::slice::from_raw_parts(p as *const u8, n))); } } - Some(h) + Some(blobs) } /// Remember a title graphics pipeline's description (not with stream output). @@ -379,7 +434,10 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b if rd32(&d.0, SO_ENTRIES) != 0 { return; } - let Some(shaders) = stage_hashes(&d.0) else { return }; + let Some(shader_blobs) = stage_blobs(&d.0) else { return }; + for &o in &STAGES { + d.0[o..o + 16].fill(0); + } let static_bias = DepthBias::from_desc(&d.0); let (p, n) = (rd64(&d.0, INPUT_LAYOUT) as usize, rd32(&d.0, INPUT_LAYOUT + 8) as usize); let (mut elems, mut names) = (Vec::new(), Vec::new()); @@ -400,7 +458,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b let at = if elems.is_empty() { 0 } else { elems.as_ptr() as u64 }; d.0[INPUT_LAYOUT..INPUT_LAYOUT + 8].copy_from_slice(&at.to_le_bytes()); d.0[CACHED_PSO..CACHED_PSO + 16].fill(0); - let base = Arc::new(Base { desc: d, shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); + let base = Arc::new(Base { desc: d, shader_blobs, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } @@ -421,7 +479,7 @@ pub(super) fn depth_bias_cache_len() -> usize { pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) { let base = Arc::new(Base { desc: GfxDesc([0u8; GFX_DESC]), - shaders: [0; 5], + shader_blobs: Default::default(), dynamic_depth_bias, static_bias, _elems: Vec::new(), @@ -471,13 +529,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi return Some(cached); } let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – shaders of base pipeline {base:#x} are gone"); - } - return None; - } - let mut d = b.desc; + let mut d = b.desc_with_owned_shaders(); clear_dynamic_depth_bias(&mut d.0); bias.patch_desc(&mut d.0); let mut out: *mut c_void = std::ptr::null_mut(); @@ -551,17 +603,11 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas } return E_FAIL; }; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: CreateDerivedPipelineStateX – the shaders of base pipeline {base:?} are gone"); - } - return E_FAIL; - } let n = count as usize; if n > 64 || (n > 0 && (patches.is_null() || !crate::gpu::shader::readable(patches as usize, n * PATCH))) { return E_INVALIDARG; } - let mut d = b.desc; + let mut d = b.desc_with_owned_shaders(); for i in 0..n { let patch = &*(patches.add(i * PATCH) as *const [u8; PATCH]); match apply_patch(&mut d.0, patch) { @@ -1948,4 +1994,48 @@ mod tests { assert!(seen.is_none(), "residual map must be freed once cap is reached"); assert_eq!(logged.load(Ordering::Relaxed), MAX_ALIAS_LOGS); } + + #[test] + fn base_pso_retains_shader_bytecode_after_title_buffer_changes() { + let mut vs = vec![0x44u8, 0x58, 0x42, 0x43, 1, 2, 3, 4]; + let mut ps = vec![0x44u8, 0x58, 0x42, 0x43, 9, 8, 7, 6, 5]; + let orig_vs = vs.clone(); + let orig_ps = ps.clone(); + let mut raw = GfxDesc([0u8; GFX_DESC]); + raw.0[STAGES[0]..STAGES[0] + 8].copy_from_slice(&(vs.as_ptr() as u64).to_le_bytes()); + raw.0[STAGES[0] + 8..STAGES[0] + 16].copy_from_slice(&(vs.len() as u64).to_le_bytes()); + raw.0[STAGES[1]..STAGES[1] + 8].copy_from_slice(&(ps.as_ptr() as u64).to_le_bytes()); + raw.0[STAGES[1] + 8..STAGES[1] + 16].copy_from_slice(&(ps.len() as u64).to_le_bytes()); + let pso_key = 0xDEAD_BEEF_0001usize; + let pso_key2 = 0xDEAD_BEEF_0002usize; + unsafe { + note_base(pso_key as *mut c_void, raw.0.as_ptr() as *const c_void, false); + note_base(pso_key2 as *mut c_void, raw.0.as_ptr() as *const c_void, false); + } + // Overwrite and drop the title's original shader buffers. + vs.fill(0xAA); + ps.fill(0xBB); + drop(vs); + drop(ps); + let (base, base2) = { + let g = BASES.lock().unwrap(); + let m = g.as_ref().expect("base map"); + (m.get(&pso_key).cloned().expect("base PSO recorded"), m.get(&pso_key2).cloned().expect("second base PSO recorded")) + }; + assert!(Arc::ptr_eq(base.shader_blobs[0].as_ref().unwrap(), base2.shader_blobs[0].as_ref().unwrap())); + assert!(Arc::ptr_eq(base.shader_blobs[1].as_ref().unwrap(), base2.shader_blobs[1].as_ref().unwrap())); + let derived = base.desc_with_owned_shaders(); + let (vp, vn) = (rd64(&derived.0, STAGES[0]) as *const u8, rd64(&derived.0, STAGES[0] + 8) as usize); + let (pp, pn) = (rd64(&derived.0, STAGES[1]) as *const u8, rd64(&derived.0, STAGES[1] + 8) as usize); + assert_eq!(unsafe { std::slice::from_raw_parts(vp, vn) }, orig_vs.as_slice()); + assert_eq!(unsafe { std::slice::from_raw_parts(pp, pn) }, orig_ps.as_slice()); + assert_eq!(rd64(&derived.0, STAGES[2]), 0); + let weak_vs = Arc::downgrade(base.shader_blobs[0].as_ref().unwrap()); + drop(base); + drop(base2); + forget_base(pso_key); + assert!(weak_vs.upgrade().is_some(), "shared blob stays alive while second PSO holds it"); + forget_base(pso_key2); + assert!(weak_vs.upgrade().is_none(), "shared blob drops once all owning PSOs are released"); + } }