From 1b93747498cb3e1bc0dbeaa6486b503dca97571c Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:03:52 -0800 Subject: [PATCH] D3D12.X: retain opt-in pipeline rebuild recipes Pipeline jobs normally consume their owned descriptors on the first build. Preserve that one-shot path without an extra device reference or retained shader storage, while allowing XCL_PSO_REBUILD_RECIPES=1 to keep immutable, fully owned inputs for future residency work. Clear borrowed root signatures and unused pointer members, and reject stream-output arrays that are not owned. The opt-in recipe owns its device and can run repeatedly; no rebuild or eviction is activated yet. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 123 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 106 +++++++++++++++++---- 2 files changed, 203 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 4dbe225629..85c0dd780b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -46,6 +46,9 @@ struct Pending { /// A pipeline build independent of the title-visible stand-ins that requested it. struct Build { compute_key: Option>, + /// Immutable inputs for rebuilding this pipeline after its first job has been consumed. + #[allow(dead_code)] // retained for the later opt-in eviction/rebuild stage + recipe: Option, /// the build, until a worker takes it job: Mutex>, /// the build went to the workers (a lazy one goes on its first `resolve`) @@ -180,12 +183,18 @@ fn run_build(build: &Arc, job: Job) { impl Build { fn new(job: Job, sent: bool) -> Self { - Self::new_keyed(job, sent, None) + Self::new_keyed(job, sent, None, None) } - fn new_keyed(job: Job, sent: bool, compute_key: Option>) -> Self { + fn new_keyed( + job: Job, + sent: bool, + compute_key: Option>, + recipe: Option, + ) -> Self { Self { compute_key, + recipe, job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(sent), tracked: AtomicBool::new(false), @@ -595,9 +604,47 @@ pub fn enabled() -> bool { std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0") } +fn recipe_gate_value(value: Option<&str>) -> bool { + value.is_some_and(|value| value.trim() == "1") +} + +/// Whether background builds retain their immutable inputs after the initial one-shot job. +/// This is preparation for a future eviction policy only; it does not rebuild or evict PSOs. +pub(super) fn rebuild_recipes_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let value = std::env::var("XCL_PSO_REBUILD_RECIPES").ok(); + let on = recipe_gate_value(value.as_deref()); + if on { + crate::xlog_info!("D3D12.X: XCL_PSO_REBUILD_RECIPES=1 - retaining pipeline rebuild inputs only; pipelines are not evicted or rebuilt"); + } + on + }) +} + /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; +/// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the +/// same operation; retaining it does not by itself schedule or run more work. +#[derive(Clone)] +pub(super) struct Recipe(Arc usize + Send + Sync>); + +impl Recipe { + pub(super) fn new(build: impl Fn() -> usize + Send + Sync + 'static) -> Self { + Self(Arc::new(build)) + } + + fn run(&self) -> usize { + (self.0)() + } + + fn initial_job(&self) -> Job { + let recipe = self.clone(); + Box::new(move || recipe.run()) + } +} + /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(build: &Arc) { let job = build.job.lock().unwrap().take(); @@ -881,7 +928,7 @@ pub(super) fn submit_keyed( job: Job, compute_key: Option, ) { - submit_as(standin, compute, job, true, 0, compute_key); + submit_as(standin, compute, job, None, true, 0, compute_key); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -907,10 +954,30 @@ pub(super) fn submit_lazy_keyed( key: u64, compute_key: Option, ) { - submit_as(standin, compute, job, false, key, compute_key); + submit_as(standin, compute, job, None, false, key, compute_key); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, compute_key: Option) { +pub(super) fn submit_recipe_keyed( + standin: usize, + compute: bool, + recipe: Recipe, + send: bool, + key: u64, + compute_key: Option, +) { + let job = recipe.initial_job(); + submit_as(standin, compute, job, Some(recipe), send, key, compute_key); +} + +fn submit_as( + standin: usize, + compute: bool, + job: Job, + recipe: Option, + send: bool, + key: u64, + compute_key: Option, +) { debug_assert!(compute || compute_key.is_none()); let build = if let Some(compute_key) = compute_key { let mut registry = IN_FLIGHT.lock().unwrap(); @@ -930,20 +997,20 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, comp COALESCING.finished(1); } let compute_key = Arc::new(compute_key); - let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); builds.insert(compute_key, Arc::downgrade(&build)); COALESCING.unique(); build } } else { let compute_key = Arc::new(compute_key); - let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()))); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); builds.insert(compute_key, Arc::downgrade(&build)); COALESCING.unique(); build } } else { - Arc::new(Build::new(job, false)) + Arc::new(Build::new_keyed(job, false, None, recipe)) }; let p = Arc::new(Pending { build: build.clone(), @@ -1162,6 +1229,31 @@ mod used_tests { assert!(!used::shader_noted(cs), "the other set was not used"); } + #[test] + fn rebuild_recipe_gate_requires_exact_one() { + assert!(recipe_gate_value(Some("1"))); + assert!(recipe_gate_value(Some(" 1\t"))); + for value in [None, Some(""), Some("0"), Some("true"), Some("2")] { + assert!(!recipe_gate_value(value)); + } + } + + #[test] + fn build_retains_a_reusable_recipe_after_its_initial_job_is_consumed() { + let calls = Arc::new(AtomicUsize::new(0)); + let recipe_calls = calls.clone(); + let recipe = Recipe::new(move || { + recipe_calls.fetch_add(1, Ordering::Relaxed) + 0x5100 + }); + let build = Build::new_keyed(recipe.initial_job(), false, None, Some(recipe)); + + let initial = build.job.lock().unwrap().take().unwrap(); + assert_eq!(initial(), 0x5100); + assert!(build.job.lock().unwrap().is_none()); + assert_eq!(build.recipe.as_ref().unwrap().run(), 0x5101); + assert_eq!(calls.load(Ordering::Relaxed), 2); + } + #[test] fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); @@ -1327,6 +1419,21 @@ mod used_tests { submit_lazy_keyed(standin, true, job, 0, Some(compute_key(tag))); } + #[test] + fn coalesced_compute_owners_retain_the_winning_recipe() { + let standins = [0x7E57_C091usize, 0x7E57_C092]; + let winner = Recipe::new(|| 0xC091); + let duplicate = Recipe::new(|| panic!("duplicate recipe ran")); + submit_recipe_keyed(standins[0], true, winner, false, 0, Some(compute_key(0x91))); + submit_recipe_keyed(standins[1], true, duplicate, false, 0, Some(compute_key(0x91))); + + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build)); + assert_eq!(a.build.recipe.as_ref().unwrap().run(), 0xC091); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0); + } + #[test] fn concurrent_equal_compute_submissions_run_one_job() { let standins = [0x7E57_C101usize, 0x7E57_C102]; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f62ffcf587..16d04637ba 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6750,7 +6750,7 @@ pub(in crate::hle::d3d12x) mod compute_build_key; /// A pipeline description that owns what it points to (shader blobs, input layout and its /// semantic names), so a worker can build the pipeline after the title's memory is gone. -/// The root signature pointer is kept as is (the translated paths replace it). +/// The title's borrowed root signature is cleared; translated paths install XCL's ABI signature. #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { Compute(Box, Vec>), @@ -6759,6 +6759,9 @@ enum OwnedDesc { } unsafe impl Send for OwnedDesc {} +// Every pointer in an `OwnedDesc` refers to immutable backing storage owned by the same value. +// The translated builders only read it, so one retained recipe may safely be shared. +unsafe impl Sync for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. @@ -6860,6 +6863,8 @@ unsafe fn own_compute(desc: *const c_void) -> Option { let mut d: Box = Box::new(std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)); let mut blobs = Vec::new(); own_shader(&mut d.CS, &mut blobs); + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); Some(OwnedDesc::Compute(d, blobs)) } @@ -6867,13 +6872,18 @@ unsafe fn own_compute(desc: *const c_void) -> Option { /// None with stream output (not copied; such pipelines are built in the call). unsafe fn own_graphics(desc: *const c_void) -> Option { let mut d: Box = Box::new(std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC)); - if d.StreamOutput.NumEntries > 0 { + if d.StreamOutput.NumEntries > 0 || d.StreamOutput.NumStrides > 0 { return None; } + // Counts are zero, so the pointers are semantically unused; clear them rather than retain + // borrowed title addresses in an object declared safe to share and possibly reuse. + d.StreamOutput = D3D12_STREAM_OUTPUT_DESC::default(); let mut blobs = Vec::new(); for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { own_shader(b, &mut blobs); } + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); let n = d.InputLayout.NumElements as usize; let mut elems = Vec::new(); let mut names = Vec::new(); @@ -6913,6 +6923,8 @@ unsafe fn own_stream(desc: *const c_void) -> Option { } let word = |buf: &[u8], k: usize| u64::from_le_bytes(buf[at + 8 * k..at + 8 * k + 8].try_into().unwrap()); match ty { + // Translated streams install XCL's ABI root signature. + 0 => buf[at..end].fill(0), 1..=6 | 24 | 25 => { let (p, n) = (word(&buf, 0) as usize, word(&buf, 1) as usize); if p == 0 || n == 0 { @@ -6934,11 +6946,44 @@ unsafe fn own_stream(desc: *const c_void) -> Option { Some(OwnedDesc::Stream(d, buf, blobs)) } -/// Raw pointers a worker needs (the device lives for the process). +#[cfg(test)] +mod owned_desc_tests { + use super::*; + + #[test] + fn graphics_recipe_rejects_buffer_strides_without_declarations() { + let stride = 16u32; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pBufferStrides = &stride; + desc.StreamOutput.NumStrides = 1; + desc.StreamOutput.NumEntries = 0; + assert!(unsafe { own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) }.is_none()); + } + + #[test] + fn graphics_recipe_clears_unused_stream_output_pointers() { + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pSODeclaration = std::ptr::NonNull::dangling().as_ptr(); + desc.StreamOutput.pBufferStrides = std::ptr::NonNull::dangling().as_ptr(); + let Some(OwnedDesc::Graphics(owned, ..)) = (unsafe { + own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) + }) else { + panic!("zero-count stream output must be accepted") + }; + assert!(owned.StreamOutput.pSODeclaration.is_null()); + assert!(owned.StreamOutput.pBufferStrides.is_null()); + } +} + +/// Raw pointers a one-shot worker needs (the existing process-lifetime device invariant). #[derive(Clone, Copy)] -struct Dev(usize, usize); +struct Dev(usize, PsoFn); unsafe impl Send for Dev {} +/// A gated rebuild recipe owns a device reference independently of the title's references. +#[derive(Clone)] +struct RecipeDev(ID3D12Device, PsoFn); + /// The stand-in for a pipeline with dummy shaders (draws / computes nothing). unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let d = dummy(); @@ -7057,7 +7102,7 @@ unsafe fn go_background( } return None; } - let dev = Dev(this as usize, f as usize); + let dev = Dev(this as usize, f); let (key, parts) = owned.shaders_key(); // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; @@ -7069,21 +7114,26 @@ unsafe fn go_background( }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); - let job: super::pso_async::Job = Box::new(move || { - let mut out: *mut c_void = std::ptr::null_mut(); - if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { - out as usize + let lazy = super::pso_async::lazy(); + if super::pso_async::rebuild_recipes_enabled() { + let recipe_dev = RecipeDev(ID3D12Device::from_raw_borrowed(&this)?.clone(), f); + let recipe = super::pso_async::Recipe::new(move || { + let dev = Dev(recipe_dev.0.as_raw() as usize, recipe_dev.1); + run_owned_build(dev, &owned, build) + }); + super::pso_async::submit_recipe_keyed(*ppv as usize, compute, recipe, !lazy, if lazy { key } else { 0 }, build_key); + } else { + let job: super::pso_async::Job = Box::new(move || run_owned_build(dev, &owned, build)); + if lazy { + super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); } else { - 0 + super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } - }); - if super::pso_async::lazy() { - super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); + } + if lazy { if let Some(entry) = described { super::pso_async::on_first_use(*ppv as usize, Box::new(move || super::gfx_records::note(entry))); } - } else { - super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); @@ -7094,14 +7144,19 @@ unsafe fn go_background( Some(hr) } +fn run_owned_build(dev: Dev, owned: &OwnedDesc, build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool) -> usize { + let mut out: *mut c_void = std::ptr::null_mut(); + if unsafe { build(dev, owned, &mut out) } && !out.is_null() { out as usize } else { 0 } +} + unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out, true), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, true), Some(hr) if hr >= 0) } unsafe fn build_graphics_uncacheable(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out, false), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, false), Some(hr) if hr >= 0) } /// This process is a shader preparation worker (`prepare_device`): it keeps the driver's blob of @@ -7134,7 +7189,7 @@ pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPEL unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) + matches!(translated_compute_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) } unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { @@ -10918,6 +10973,21 @@ mod mesh_stream_tests { assert_ne!(rebased, shader.as_ptr() as usize); assert_eq!(&buf[32..48], &[0u8; 16], "zero-len shader entry cleared"); assert_eq!(&buf[56..72], &[0u8; 16], "cached PSO cleared"); + + // A retained stream must not extend the title's root-signature lifetime. Translation + // replaces it, while the shader payload remains rebased to recipe-owned bytes. + let mut rooted = [0u8; 40]; + rooted[0..4].copy_from_slice(&0u32.to_le_bytes()); + rooted[8..16].copy_from_slice(&0xDEAD_BEEFu64.to_le_bytes()); + rooted[16..20].copy_from_slice(&25u32.to_le_bytes()); + rooted[24..32].copy_from_slice(&(shader.as_ptr() as u64).to_le_bytes()); + rooted[32..40].copy_from_slice(&(shader.len() as u64).to_le_bytes()); + let rooted_desc = [rooted.len(), rooted.as_ptr() as usize]; + let OwnedDesc::Stream(_, rooted_buf, rooted_blobs) = own_stream(rooted_desc.as_ptr().cast()).unwrap() else { + panic!("expected Stream") + }; + assert_eq!(&rooted_buf[8..16], &[0; 8]); + assert_eq!(u64::from_le_bytes(rooted_buf[24..32].try_into().unwrap()) as usize, rooted_blobs[0].as_ptr() as usize); } }