From 395d6bcc45d497ae58b171c80fbf10d9a0cd4bd0 Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:04:20 -0700 Subject: [PATCH 1/3] D3D12.X: nothing another process made for a graphics pipeline with static samplers on NVIDIA On NVIDIA, a graphics pipeline created from what another process made loses the linear filtering of its static samplers. The retail title's tone map samples its 33^3 LUTs through such a sampler, so one made that way sampled them as point: contour bands (#505). On main "what another process made" is two things: the driver blobs on disk (CachedPSO, written by the preparation workers or an earlier run) and the pipeline library the preparation stores. claudetools-gh measured it (RTX 5070 Ti, 621.01): levels per channel on a flat wall went from 10/10/13 with gaps (tone map from a disk blob) to 23/16/12 without gaps when the same pipeline was built without the blob or by the game process itself, and to 24/17/13 with this rule (#505 7235526172). They pointed out that the pipeline library is the same cross-process case (#505 7236405511). One policy, graphics_artifacts_across (blob_across_processes on the adapter's DXGI VendorId, adapter_vendor, per LUID; asked only for a pipeline with static samplers): such a pipeline takes and keeps neither on NVIDIA (0x10DE), nor on an adapter whose vendor is not known (fail closed: a failed lookup is not cached, the next pipeline asks again). Blobs kept in this process's memory still apply. This covers XCL's own artifacts of translated graphics pipelines; a title's own native pipeline library or cached PSO passes as before. - translated_graphics_pso_once: no library load or store, no disk blob; - finish_two_pass: the mesh pass (with its pixel samplers): no library load or store, no disk blob; - the stream graphics path: no disk blob. Compute pipelines (compute_container, the two-pass compute pass, the preparation's compute pipelines) are not covered here. Tests: the policy (NVIDIA, other vendors, an adapter not known), and a_static_sampler_graphics_pipeline_takes_and_keeps_no_artifact_of_another_process: with a library entry and a blob file of a translated graphics pipeline there, the desc path's load and disk path (graphics_from_other_processes) and its store (keep_for_other_processes) take and keep them only where the policy lets them across. Old gfx-*.pso files and library entries stay on disk; builds without this keep loading them. Ported from claudetools-gh's fix in #505 7235526172 and their note in 7236405511. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 225 ++++++++++++++++++++++++++---- 1 file changed, 197 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..f0938b9626 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8126,20 +8126,15 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let gkey = (disk_key.0, disk_key.1, rs as usize); let cacheable = graphics_blob_cacheable(cacheable, ©, final_gs.is_some()); let library_name = driver_cache::graphics_name(disk_key.0, disk_key.1); - let library_pso = if !cacheable || ppv.is_null() { - None - } else if depth_bounds { - let stream = depth_bounds_stream(©); - let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as _ }; - crate::shaders::pipeline_library::load_stream(&library_name, &desc) - } else { - crate::shaders::pipeline_library::load_graphics(&library_name, ©) - }; - let mut cached = (cacheable && library_pso.is_none()).then(|| graphics_blob(gkey)).flatten(); + // (not from or into what another process made, for a pipeline with static samplers on NVIDIA; + // the blobs kept in this process still apply) + let across = cacheable && graphics_artifacts_across(this, !samplers.is_empty()); // (no file without the adapter's identity: it could be another adapter's; the root // signature's memory windows are not in the description) - let disk = cacheable.then(|| driver_identity(this)).flatten().and_then(|id| driver_cache::graphics_path( - driver_cache::graphics_file_hash(disk_key, id, crate::gpu::recomp::pso::mem_windows()), disk_key.1)); + let (library_pso, disk) = graphics_from_other_processes(across, !ppv.is_null(), depth_bounds, &library_name, ©, || { + driver_identity(this).and_then(|id| driver_cache::graphics_path(driver_cache::graphics_file_hash(disk_key, id, crate::gpu::recomp::pso::mem_windows()), disk_key.1)) + }); + let mut cached = (cacheable && library_pso.is_none()).then(|| graphics_blob(gkey)).flatten(); let from_disk = cacheable && library_pso.is_none() && cached.is_none(); let mut loaded = None; if from_disk { @@ -8189,9 +8184,9 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const GRAPHICS_BLOBS.admit(gkey, cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); driver_cache::note(true, loaded.take()); } - if cacheable && hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&*ppv) { - if let Err(e) = crate::shaders::pipeline_library::store(driver_cache::graphics_name(gkey.0, gkey.1), pso) { + if let Err(e) = keep_for_other_processes(across, driver_cache::graphics_name(gkey.0, gkey.1), pso) { note_translation_error(e); return Some(E_INVALIDARG); } @@ -9390,6 +9385,79 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool, rt32_mask: u8) -> Result<( } } +/// The PCI vendor of `device`'s adapter (`DXGI_ADAPTER_DESC.VendorId`), cached per adapter LUID +/// once known. None: not known now (a failed lookup is not cached: the next call asks again). +pub(crate) fn adapter_vendor(device: *mut c_void) -> Option { + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; + let luid = unsafe { dev.GetAdapterLuid() }; + let key = (luid.HighPart, luid.LowPart); + static VENDORS: OnceLock>> = OnceLock::new(); + let vendors = VENDORS.get_or_init(Default::default); + if let Some(&v) = vendors.lock().unwrap().get(&key) { + return Some(v); + } + let v = unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; + adapter.GetDesc().ok()?.VendorId + }; + vendors.lock().unwrap().insert(key, v); + Some(v) +} + +/// Whether a translated graphics pipeline (or the mesh pass of a two-pass one) on an adapter of +/// `vendor` may be made from, and kept as, an XCL artifact another process made: a driver blob +/// on disk, an entry of XCL's pipeline library. One without static samplers always may. One with +/// static samplers may only on a known adapter that is not NVIDIA's: made from either on NVIDIA, +/// its static samplers lose their linear filtering (#505: the tone map's LUTs sampled as point, +/// contour bands); an adapter not known is taken as one that might be (fail closed). +pub(crate) fn blob_across_processes(static_samplers: bool, vendor: Option) -> bool { + !static_samplers || vendor.is_some_and(|v| v != 0x10DE) +} + +/// `blob_across_processes` for a pipeline on `device`: the adapter is asked only when the +/// pipeline has static samplers. The one policy of the three translated graphics paths. +pub(crate) unsafe fn graphics_artifacts_across(device: *mut c_void, static_samplers: bool) -> bool { + !static_samplers || blob_across_processes(true, adapter_vendor(device)) +} + +/// What another process made that translated graphics pipeline `copy` takes now: its entry +/// `library_name` of XCL's pipeline library (loaded here; with `depth_bounds` through the stream +/// that carries them) and the path of its driver blob on disk (`disk`, asked only then). Neither +/// unless `across` (`graphics_artifacts_across`); no library load without `load` (an +/// out-pointer to fill). +pub(crate) unsafe fn graphics_from_other_processes( + across: bool, + load: bool, + depth_bounds: bool, + library_name: &str, + copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + disk: impl FnOnce() -> Option, +) -> (Option, Option) { + if !across { + return (None, None); + } + let library = if !load { + None + } else if depth_bounds { + let stream = depth_bounds_stream(copy); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as _ }; + crate::shaders::pipeline_library::load_stream(library_name, &desc) + } else { + crate::shaders::pipeline_library::load_graphics(library_name, copy) + }; + (library, disk()) +} + +/// `pso` into XCL's pipeline library as `name` for other processes, unless not `across`. +pub(crate) fn keep_for_other_processes(across: bool, name: String, pso: &ID3D12PipelineState) -> std::result::Result<(), String> { + if !across { + return Ok(()); + } + crate::shaders::pipeline_library::store(name, pso) +} + pub(crate) fn preparation_driver_identity(dev: &ID3D12Device) -> Option { driver_identity(dev.as_raw()) } @@ -9422,9 +9490,12 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: two_pass_identity::two_pass_stream_key(&stream.0, ps_samplers, driver, crate::gpu::recomp::pso::mem_windows()) }); let gkey = disk_key.map(|(hash, bytes)| (hash, bytes, mesh_rs as usize)); - let gdisk = disk_key.and_then(|(hash, bytes)| driver_cache::graphics_path(hash, bytes)); + // (not from or into what another process made, for a mesh pass with static samplers on + // NVIDIA or on an adapter not known: `graphics_artifacts_across`) + let mesh_across = graphics_artifacts_across(this, !ps_samplers.is_empty()); + let gdisk = disk_key.filter(|_| mesh_across).and_then(|(hash, bytes)| driver_cache::graphics_path(hash, bytes)); let stream_desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as *mut c_void }; - let library_mesh = disk_key.and_then(|(hash, bytes)| { + let library_mesh = disk_key.filter(|_| mesh_across).and_then(|(hash, bytes)| { crate::shaders::pipeline_library::load_stream(&driver_cache::graphics_name(hash, bytes), &stream_desc) }); let mesh_from_library = library_mesh.is_some(); @@ -9596,17 +9667,23 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); return E_INVALIDARG; } - let library = crate::shaders::pipeline_library::store( - match gkey { - Some((hash, bytes, _)) => driver_cache::graphics_name(hash, bytes), - None if crate::shaders::pipeline_library::building() => { - super::pso_async::release(compute as usize); - return E_INVALIDARG; - } - None => String::new(), - }, - &mesh_pso, - ).and_then(|_| { + // (a pass with static samplers on NVIDIA is not kept for another process: `blob_across_processes`) + let mesh_stored = if !mesh_across { + Ok(()) + } else { + crate::shaders::pipeline_library::store( + match gkey { + Some((hash, bytes, _)) => driver_cache::graphics_name(hash, bytes), + None if crate::shaders::pipeline_library::building() => { + super::pso_async::release(compute as usize); + return E_INVALIDARG; + } + None => String::new(), + }, + &mesh_pso, + ) + }; + let library = mesh_stored.and_then(|_| { let compute_pso = ID3D12PipelineState::from_raw_borrowed(&compute) .ok_or_else(|| "The two-pass compute pipeline has no native object".to_string())?; crate::shaders::pipeline_library::store( @@ -10960,7 +11037,8 @@ unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void let disk_key = two_pass_identity::graphics_stream_key(&stream.0, &samplers, crate::gpu::recomp::pso::mem_windows()); let key = disk_key.map(|(hash, bytes)| (hash, bytes, rs as usize)); let mut cached = key.and_then(graphics_blob); - let disk = disk_key.and_then(|k| driver_cache::graphics_path(k.0, k.1)); + // (not from or into another process's blob: `graphics_artifacts_across`) + let disk = disk_key.filter(|_| graphics_artifacts_across(this, !samplers.is_empty())).and_then(|k| driver_cache::graphics_path(k.0, k.1)); let from_disk = key.is_some() && cached.is_none(); let mut loaded = None; if from_disk { @@ -14157,6 +14235,97 @@ mod mesh_stream_tests { *luid = Default::default(); } + #[test] + fn a_pipeline_with_static_samplers_takes_nothing_another_process_made_on_nvidia() { + assert!(!blob_across_processes(true, Some(0x10DE)), "no disk blob and no library entry"); + assert!(blob_across_processes(false, Some(0x10DE)), "no static samplers: the disk blob and the library stay"); + } + + #[test] + fn other_vendors_keep_their_disk_blobs_and_library() { + for vendor in [Some(0x1002), Some(0x8086), Some(0x1414)] { + assert!(blob_across_processes(true, vendor), "{vendor:x?}"); + assert!(blob_across_processes(false, vendor), "{vendor:x?}"); + } + // (an adapter not known: not for a pipeline with static samplers, fail closed) + assert!(!blob_across_processes(true, None)); + assert!(blob_across_processes(false, None)); + } + + /// The desc path's artifacts of other processes (`graphics_from_other_processes`, and the + /// store, `keep_for_other_processes`): with an entry of XCL's pipeline library and a blob file + /// there for a translated graphics pipeline, both are taken and a new entry kept only for one + /// the policy lets across; for one with static samplers on NVIDIA or on an adapter not known, + /// neither is taken nor kept (#505). Red when a gate in them goes. + #[test] + fn a_static_sampler_graphics_pipeline_takes_and_keeps_no_artifact_of_another_process() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _serial = crate::shaders::pipeline_library::BUILD_TEST.lock().unwrap(); + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + if let Err(why) = crate::gpu::recomp::dxc::location() { + return crate::gpu::recomp::runner::skip_test(&format!("no DXC: {why}")); + } + let src = "float4 vs(uint i : SV_VertexID) : SV_Position { return float4(i, 0, 0, 1); }\nfloat4 ps() : SV_Target { return 1; }"; + let vs = crate::gpu::recomp::dxc::compile(src, "vs", "vs_6_6", &[]).unwrap(); + let ps = crate::gpu::recomp::dxc::compile(src, "ps", "ps_6_6", &[]).unwrap(); + let sampler: crate::gpu::recomp::pso::StaticSampler = ([0x92, 0x00c0_0000, 0x1450_0000, 0], false); + let rs = crate::gpu::recomp::pso::abi_root_signature_with(&dev, true, &[sampler]).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: unsafe { std::mem::transmute_copy(&rs) }, + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = unsafe { dev.CreateGraphicsPipelineState(&desc) }.unwrap(); + use crate::shaders::pipeline_library as library; + library::abort(); // (a build an earlier failed test left active) + if !library::begin(&dev, None).unwrap() { + return crate::gpu::recomp::runner::skip_test("no pipeline library on this device"); + } + // (what another process made: a library written with this pipeline's entry, which a new + // build is opened over, as the title's process opens the preparation's; and a blob file) + let dir = std::env::temp_dir(); + let (made, kept_file) = (dir.join(format!("xcl-test-ssg-made-{}.lib", std::process::id())), dir.join(format!("xcl-test-ssg-kept-{}.lib", std::process::id()))); + let name = "xcl-test-static-sampler-graphics.pso"; + library::store(name.into(), &pso).unwrap(); + library::finish(&made).unwrap(); + assert!(library::begin(&dev, Some(&made)).unwrap()); + let file = dir.join(format!("xcl-test-static-sampler-graphics-{}.pso", std::process::id())); + std::fs::write(&file, b"blob").unwrap(); + let mut cases = Vec::new(); + for (k, (static_samplers, vendor, across)) in + [(true, Some(0x10DE), false), (true, None, false), (true, Some(0x1002), true), (false, Some(0x10DE), true), (false, None, true)].into_iter().enumerate() + { + assert_eq!(blob_across_processes(static_samplers, vendor), across, "{static_samplers} {vendor:x?}"); + let (library, disk) = unsafe { graphics_from_other_processes(across, true, false, name, &desc, || Some(file.clone())) }; + assert_eq!((library.is_some(), disk.is_some()), (across, across), "taken: library entry, blob file ({static_samplers} {vendor:x?})"); + let kept = format!("xcl-test-static-sampler-graphics-{k}.pso"); + keep_for_other_processes(across, kept.clone(), &pso).unwrap(); + cases.push((kept, static_samplers, vendor, across)); + } + // (what this build kept, as the next process opens it) + library::finish(&kept_file).unwrap(); + assert!(library::begin(&dev, Some(&kept_file)).unwrap()); + for (kept, static_samplers, vendor, across) in cases { + assert_eq!(library::load_graphics(&kept, &desc).is_some(), across, "kept for other processes ({static_samplers} {vendor:x?})"); + } + library::abort(); + for f in [&file, &made, &kept_file] { + let _ = std::fs::remove_file(f); + } + } + #[test] fn finish_two_pass_rejects_null_mesh_out_pointer() { let iface = layout::find("ID3D12Device2").expect("ID3D12Device2 layout"); From 656ede245a743aab5c91941cef821966c364b21f Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:14:03 -0700 Subject: [PATCH 2/3] Tests: exercise the live static-sampler artifact policy Checked: #3169 is open at 395d6bcc on main 9dfbe3ea; REPO-TRACKER and related #505 behavior. --- crates/xcl/src/hle/d3d12x/real.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f0938b9626..c73ea7dd35 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -14304,16 +14304,17 @@ mod mesh_stream_tests { let file = dir.join(format!("xcl-test-static-sampler-graphics-{}.pso", std::process::id())); std::fs::write(&file, b"blob").unwrap(); let mut cases = Vec::new(); - for (k, (static_samplers, vendor, across)) in - [(true, Some(0x10DE), false), (true, None, false), (true, Some(0x1002), true), (false, Some(0x10DE), true), (false, None, true)].into_iter().enumerate() - { - assert_eq!(blob_across_processes(static_samplers, vendor), across, "{static_samplers} {vendor:x?}"); - let (library, disk) = unsafe { graphics_from_other_processes(across, true, false, name, &desc, || Some(file.clone())) }; - assert_eq!((library.is_some(), disk.is_some()), (across, across), "taken: library entry, blob file ({static_samplers} {vendor:x?})"); - let kept = format!("xcl-test-static-sampler-graphics-{k}.pso"); - keep_for_other_processes(across, kept.clone(), &pso).unwrap(); - cases.push((kept, static_samplers, vendor, across)); - } + let vendor = adapter_vendor(dev.as_raw()); + let across = unsafe { graphics_artifacts_across(dev.as_raw(), true) }; + assert_eq!(blob_across_processes(true, vendor), across, "static samplers on {vendor:x?}"); + if vendor == Some(0x10DE) { + assert!(!across, "NVIDIA static-sampler pipelines must not take or keep another process's artifacts"); + } + let (library, disk) = unsafe { graphics_from_other_processes(across, true, false, name, &desc, || Some(file.clone())) }; + assert_eq!((library.is_some(), disk.is_some()), (across, across), "taken: library entry, blob file on {vendor:x?}"); + let kept = "xcl-test-static-sampler-graphics-0.pso".to_owned(); + keep_for_other_processes(across, kept.clone(), &pso).unwrap(); + cases.push((kept, true, vendor, across)); // (what this build kept, as the next process opens it) library::finish(&kept_file).unwrap(); assert!(library::begin(&dev, Some(&kept_file)).unwrap()); From ea02c3e6aead40c3a9ddf2ccce4595366261f43a Mon Sep 17 00:00:00 2001 From: KDenKC <125705260+KDenKC@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:38:27 -0700 Subject: [PATCH 3/3] Tests: pin static-sampler graphics artifact guards Keep the static-sampler policy on every translated graphics artifact path, exercise both allow and deny behavior for pipeline-library and disk lookups, and report cumulative guarded pipeline counts. Share the per-adapter vendor and driver identity lookup. Compute pipelines remain outside the policy. --- README.md | 5 ++ crates/xcl/src/hle/d3d12x/real.rs | 119 ++++++++++++++++++++---------- 2 files changed, 85 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 91c019d824..3b08d19baa 100644 --- a/README.md +++ b/README.md @@ -371,6 +371,11 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. after the bounded in-memory blob cache fills. This is off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` disables it elsewhere. Compute blobs with different ordered static-sampler root signatures use separate entries. + On NVIDIA, translated graphics and two-pass mesh pipelines with static samplers do not load or + save driver blobs or pipeline-library entries across processes; their in-process cache remains + available. Compute pipelines, including `compute_container` and the two-pass mesh compute pass, + still use cross-process artifacts when their root signatures contain static samplers; they are + outside this rule. Pipelines used by an earlier run are dequeued for preload before never-used speculative pipelines resume building ahead; demanded pipelines still overtake either kind. - Direct compute dispatches can split large programs into pipelines built in parallel. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c73ea7dd35..d4aead5d7a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9324,18 +9324,35 @@ use two_pass_identity::Fnv64; /// one's blob (it is compiled again), and two adapters sharing the cache (a GPU and the /// software one) would take turns overwriting each other's files. None: not known (no blob of /// its pipelines is kept on disk). -fn driver_identity(device: *mut c_void) -> Option { +#[derive(Clone, Copy)] +struct AdapterInfo { + vendor: u32, + driver_identity: Option, +} + +/// The adapter details used by both the driver-blob key and the cross-process static-sampler +/// policy. Cache one DXGI lookup per LUID so those decisions cannot disagree or race separately. +fn adapter_info(device: *mut c_void) -> Option { use windows::Win32::Graphics::Dxgi::*; let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; let luid = unsafe { dev.GetAdapterLuid() }; let key = (luid.HighPart, luid.LowPart); - static IDS: OnceLock>>> = OnceLock::new(); - let mut ids = IDS.get_or_init(Default::default).lock().unwrap(); - *ids.entry(key).or_insert_with(|| unsafe { + static ADAPTERS: OnceLock>> = OnceLock::new(); + if let Some(info) = ADAPTERS.get_or_init(Default::default).lock().unwrap().get(&key).copied() { + return Some(info); + } + let adapter: IDXGIAdapter = unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; - let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; - preparation_adapter_identity(&adapter) - }) + factory.EnumAdapterByLuid(luid).ok()? + }; + let vendor = unsafe { adapter.GetDesc().ok()?.VendorId }; + let info = AdapterInfo { vendor, driver_identity: preparation_adapter_identity(&adapter) }; + ADAPTERS.get().unwrap().lock().unwrap().insert(key, info); + Some(info) +} + +fn driver_identity(device: *mut c_void) -> Option { + adapter_info(device)?.driver_identity } fn preparation_adapter_identity(adapter: &windows::Win32::Graphics::Dxgi::IDXGIAdapter) -> Option { @@ -9388,22 +9405,17 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool, rt32_mask: u8) -> Result<( /// The PCI vendor of `device`'s adapter (`DXGI_ADAPTER_DESC.VendorId`), cached per adapter LUID /// once known. None: not known now (a failed lookup is not cached: the next call asks again). pub(crate) fn adapter_vendor(device: *mut c_void) -> Option { - use windows::Win32::Graphics::Dxgi::*; - let dev = unsafe { ID3D12Device::from_raw_borrowed(&device) }?; - let luid = unsafe { dev.GetAdapterLuid() }; - let key = (luid.HighPart, luid.LowPart); - static VENDORS: OnceLock>> = OnceLock::new(); - let vendors = VENDORS.get_or_init(Default::default); - if let Some(&v) = vendors.lock().unwrap().get(&key) { - return Some(v); + adapter_info(device).map(|info| info.vendor) +} + +static GUARDED_STATIC_SAMPLER_PIPELINES: AtomicU64 = AtomicU64::new(0); + +fn note_guarded_static_sampler_pipeline() { + let count = GUARDED_STATIC_SAMPLER_PIPELINES.fetch_add(1, Ordering::Relaxed) + 1; + // Cumulative checkpoints keep the smoke log useful without logging every pipeline creation. + if count == 1 || count % 100 == 0 { + crate::xlog_info!("static-sampler graphics pipelines kept process-local: {count}"); } - let v = unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; - let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(luid).ok()?; - adapter.GetDesc().ok()?.VendorId - }; - vendors.lock().unwrap().insert(key, v); - Some(v) } /// Whether a translated graphics pipeline (or the mesh pass of a two-pass one) on an adapter of @@ -9419,7 +9431,11 @@ pub(crate) fn blob_across_processes(static_samplers: bool, vendor: Option) /// `blob_across_processes` for a pipeline on `device`: the adapter is asked only when the /// pipeline has static samplers. The one policy of the three translated graphics paths. pub(crate) unsafe fn graphics_artifacts_across(device: *mut c_void, static_samplers: bool) -> bool { - !static_samplers || blob_across_processes(true, adapter_vendor(device)) + let across = !static_samplers || blob_across_processes(true, adapter_vendor(device)); + if static_samplers && !across { + note_guarded_static_sampler_pipeline(); + } + across } /// What another process made that translated graphics pipeline `copy` takes now: its entry @@ -14296,37 +14312,62 @@ mod mesh_stream_tests { // (what another process made: a library written with this pipeline's entry, which a new // build is opened over, as the title's process opens the preparation's; and a blob file) let dir = std::env::temp_dir(); - let (made, kept_file) = (dir.join(format!("xcl-test-ssg-made-{}.lib", std::process::id())), dir.join(format!("xcl-test-ssg-kept-{}.lib", std::process::id()))); + let made = dir.join(format!("xcl-test-ssg-made-{}.lib", std::process::id())); let name = "xcl-test-static-sampler-graphics.pso"; library::store(name.into(), &pso).unwrap(); library::finish(&made).unwrap(); - assert!(library::begin(&dev, Some(&made)).unwrap()); let file = dir.join(format!("xcl-test-static-sampler-graphics-{}.pso", std::process::id())); std::fs::write(&file, b"blob").unwrap(); - let mut cases = Vec::new(); let vendor = adapter_vendor(dev.as_raw()); let across = unsafe { graphics_artifacts_across(dev.as_raw(), true) }; assert_eq!(blob_across_processes(true, vendor), across, "static samplers on {vendor:x?}"); if vendor == Some(0x10DE) { assert!(!across, "NVIDIA static-sampler pipelines must not take or keep another process's artifacts"); } - let (library, disk) = unsafe { graphics_from_other_processes(across, true, false, name, &desc, || Some(file.clone())) }; - assert_eq!((library.is_some(), disk.is_some()), (across, across), "taken: library entry, blob file on {vendor:x?}"); - let kept = "xcl-test-static-sampler-graphics-0.pso".to_owned(); - keep_for_other_processes(across, kept.clone(), &pso).unwrap(); - cases.push((kept, true, vendor, across)); - // (what this build kept, as the next process opens it) - library::finish(&kept_file).unwrap(); - assert!(library::begin(&dev, Some(&kept_file)).unwrap()); - for (kept, static_samplers, vendor, across) in cases { - assert_eq!(library::load_graphics(&kept, &desc).is_some(), across, "kept for other processes ({static_samplers} {vendor:x?})"); - } - library::abort(); - for f in [&file, &made, &kept_file] { + for allow_across in [false, true] { + assert!(library::begin(&dev, Some(&made)).unwrap()); + let disk_asked = AtomicBool::new(false); + let (loaded, disk) = unsafe { + graphics_from_other_processes(allow_across, true, false, name, &desc, || { + disk_asked.store(true, Ordering::Relaxed); + Some(file.clone()) + }) + }; + assert_eq!(loaded.is_some(), allow_across, "library load with policy={allow_across}"); + assert_eq!(disk.is_some(), allow_across, "disk lookup with policy={allow_across}"); + assert_eq!(disk_asked.load(Ordering::Relaxed), allow_across, "disk lookup closure with policy={allow_across}"); + + let kept = format!("xcl-test-static-sampler-graphics-{allow_across}.pso"); + keep_for_other_processes(allow_across, kept.clone(), &pso).unwrap(); + let output = dir.join(format!("xcl-test-ssg-kept-{allow_across}-{}.lib", std::process::id())); + library::finish(&output).unwrap(); + assert!(library::begin(&dev, Some(&output)).unwrap()); + assert_eq!(library::load_graphics(&kept, &desc).is_some(), allow_across, "library store with policy={allow_across}"); + library::abort(); + let _ = std::fs::remove_file(output); + } + for f in [&file, &made] { let _ = std::fs::remove_file(f); } } + /// Keep each graphics artifact path behind the same sampler/vendor policy. These source + /// anchors pin the production call sites, including the two-pass mesh disk/load/store paths. + #[test] + fn every_translated_graphics_artifact_path_uses_the_static_sampler_policy() { + let source = include_str!("real.rs"); + let guarded_calls = [ + concat!("let across = cacheable && graphics_artifacts_across(this, ", "!samplers.is_empty());"), + concat!("let gdisk = disk_key.filter(|_| mesh_across).and_then(", "|(hash, bytes)| driver_cache::graphics_path(hash, bytes));"), + concat!("let library_mesh = disk_key.filter(|_| mesh_across).and_then(", "|(hash, bytes)| {"), + concat!("let mesh_stored = if ", "!mesh_across {"), + concat!("let disk = disk_key.filter(|_| graphics_artifacts_across(this, ", "!samplers.is_empty())).and_then(|k| driver_cache::graphics_path(k.0, k.1));"), + ]; + for call in guarded_calls { + assert_eq!(source.matches(call).count(), 1, "production call site changed: {call}"); + } + } + #[test] fn finish_two_pass_rejects_null_mesh_out_pointer() { let iface = layout::find("ID3D12Device2").expect("ID3D12Device2 layout");