From 11613fb6e15b2f5083029862ee938ba3e5da387a Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:08:29 -0800 Subject: [PATCH] D3D12.X: retire native PSO generation pins Keep exact native pipeline generation owners through GPU completion using the same strong submission receipt already requested for descriptor epochs. Executed work without a receipt retains its pins permanently; ordinary submissions without opt-in pins keep the marker-free path. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 108 ++++++++++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 170 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 3 + 3 files changed, 266 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 92f265a9b4..bbbe7d929f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -983,7 +983,7 @@ struct KickoffEffects { uses_shared_view_heap: bool, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec, - _native_generations: Vec, + native_generations: Vec, } fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { @@ -995,7 +995,7 @@ fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { uses_shared_view_heap: std::mem::take(&mut state.uses_shared_view_heap), write64_signals: state.clear_write64_signals(), cpu_writes: std::mem::take(&mut state.cpu_writes), - _native_generations: std::mem::take(&mut state.native_generations), + native_generations: std::mem::take(&mut state.native_generations), }; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -1006,6 +1006,30 @@ fn take_kickoff_effects_before_close(state: &mut ListState, has_fail_closed_stan (!has_fail_closed_standby).then(|| take_kickoff_effects(state)) } +fn restore_unique(destination: Option<&mut Vec>, pins: Vec, same: impl Fn(&T, &T) -> bool) -> Result<(), Vec> { + let Some(destination) = destination else { return Err(pins) }; + for pin in pins { + push_unique(destination, pin, &same); + } + Ok(()) +} + +fn restore_kickoff_native_generations(list: usize, pins: Vec) { + if pins.is_empty() { + return; + } + let mut lists = LISTS.lock().unwrap(); + let restored = restore_unique( + lists.as_mut().and_then(|lists| lists.get_mut(&list)).map(|state| &mut state.native_generations), + pins, + super::pso_async::NativeGeneration::same, + ); + drop(lists); + if let Err(pins) = restored { + super::pso_async::poison_native_generations(pins.iter()); + } +} + fn settle_kickoff_standby( standby: Option<(T, U)>, reset_succeeded: bool, @@ -1123,7 +1147,7 @@ pub(super) struct SegmentEffects { texture_transitions: Vec, uses_shared_view_heap: bool, cpu_writes: Vec, - _native_generations: Vec, + native_generations: Vec, } impl SegmentEffects { @@ -1163,7 +1187,7 @@ impl SubmissionPlan { texture_transitions: s.texture_transitions.clone(), uses_shared_view_heap: s.uses_shared_view_heap, cpu_writes: s.cpu_writes.clone(), - _native_generations: s.native_generations.clone(), + native_generations: s.native_generations.clone(), }) .unwrap_or_default() }) @@ -1232,6 +1256,14 @@ impl<'a> SubmissionChunk<'a> { self.effects.iter().any(|effects| effects.uses_shared_view_heap) } + pub(super) fn native_generations(self) -> impl Clone + Iterator { + self.effects.iter().flat_map(|effects| effects.native_generations.iter()) + } + + pub(super) fn has_native_generations(self) -> bool { + self.effects.iter().any(|effects| !effects.native_generations.is_empty()) + } + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option { // The immutable submission plan is now the production path, so record execution here // after its caller has successfully submitted this exact chunk. The legacy @@ -1244,18 +1276,20 @@ impl<'a> SubmissionChunk<'a> { } } -/// Submit one exact title chunk, adding a retirement receipt only when an opt-in recording can -/// read the shared view heap. The ordinary path stays on `SubmissionGate::submit`, which avoids -/// an extra queue marker when descriptor-epoch tracking is disabled or the chunk does not use it. -pub(super) unsafe fn submit_title_chunk( +/// Submit one exact title chunk, adding one shared retirement receipt when an opt-in recording +/// can read the shared view heap or owns native pipeline generation pins. The ordinary path stays +/// on `SubmissionGate::submit`, avoiding a marker, allocation or lock when neither applies. +pub(super) unsafe fn submit_title_chunk<'a>( gate: &mut super::alloc_pool::SubmissionGate, queue: *mut c_void, lists: &[*mut c_void], protect_shared_view: bool, + protect_native_generations: bool, + native_generations: impl Iterator, prepare: impl FnOnce(), execute: impl FnOnce(), ) -> bool { - if !protect_shared_view { + if !protect_shared_view && !protect_native_generations { return gate.submit(queue, lists, prepare, execute); } let mut epoch = None; @@ -1263,7 +1297,9 @@ pub(super) unsafe fn submit_title_chunk( queue, lists, || { - epoch = Some(super::vram::reserve_shared_view_epoch()); + if protect_shared_view { + epoch = Some(super::vram::reserve_shared_view_epoch()); + } prepare(); }, execute, @@ -1276,11 +1312,31 @@ pub(super) unsafe fn submit_title_chunk( false } super::alloc_pool::ReceiptedSubmission::Executed(receipt) => { - super::vram::attach_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch"), receipt); + if protect_native_generations { + if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt.clone(), + ); + } + super::pso_async::retire_native_generations(receipt, native_generations); + } else if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt, + ); + } true } super::alloc_pool::ReceiptedSubmission::ExecutedUntracked => { - super::vram::poison_shared_view_epoch(epoch.expect("executed shared-view submission without an epoch")); + if protect_shared_view { + super::vram::poison_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + ); + } + if protect_native_generations { + super::pso_async::poison_native_generations(native_generations); + } true } } @@ -4305,6 +4361,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let close_hr = pc:: i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); if close_hr < 0 { + if let Some(effects) = preclose_effects { + restore_kickoff_native_generations(this as usize, effects.native_generations); + } if let Some((wrapper, standby)) = standby { super::title_list::fail_closed(wrapper, this, standby, true); } @@ -4313,12 +4372,12 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let effects = match preclose_effects { Some(effects) => effects, None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { - waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), _native_generations: Vec::new(), + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), native_generations: Vec::new(), }), }; let KickoffEffects { waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, - write64_signals, cpu_writes, _native_generations, + write64_signals, cpu_writes, native_generations, } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); @@ -4336,6 +4395,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let mut wait_after_cpu_write = false; let mut gate = super::alloc_pool::SubmissionGate::default(); let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { let plan = submission_plan(prior); @@ -4349,6 +4409,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { q_raw, lists, track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), || {}, || exec(q_raw, lists.len() as u32, lists.as_ptr()), ) { @@ -4383,6 +4445,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { q_raw, &one, track_shared_view_epochs && uses_shared_view_heap, + track_native_generation_receipts && !native_generations.is_empty(), + native_generations.iter(), || {}, || exec(q_raw, 1, one.as_ptr()), ); @@ -5732,6 +5796,22 @@ mod tests { assert_eq!(Arc::strong_count(&submission_plan[0]), 1, "the immutable plan must own the submitted generation"); } + #[test] + fn close_failure_restores_exact_generation_carriers_or_returns_them_fail_closed() { + let generation = Arc::new(()); + let mut recording = vec![generation.clone()]; + restore_unique( + Some(&mut recording), + vec![generation.clone(), generation.clone()], + Arc::ptr_eq, + ).unwrap(); + assert_eq!(recording.len(), 1, "restoring a retryable recording duplicated its exact generation"); + + let stranded = restore_unique::>(None, vec![generation.clone()], Arc::ptr_eq).unwrap_err(); + assert_eq!(stranded.len(), 1, "a missing list state dropped its fail-closed carrier"); + assert!(Arc::ptr_eq(&stranded[0], &generation)); + } + #[test] fn bundle_snapshot_deduplicates_into_parent_recording() { let generation = Arc::new(()); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index a36095db43..abcce00887 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -748,7 +748,6 @@ enum RebuildTurn { /// One immutable native pipeline generation. Its strong owner keeps the exact object alive even /// after the title releases its stand-in or a later rebuild publishes the same raw address. #[derive(Clone)] -#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage pub(super) struct NativeGeneration(Arc>); impl NativeGeneration { @@ -759,6 +758,91 @@ impl NativeGeneration { pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } +struct GenerationRetirements { + pending: Vec<(R, Vec)>, + poisoned: Vec, +} + +impl GenerationRetirements { + const fn new() -> Self { + Self { pending: Vec::new(), poisoned: Vec::new() } + } + + fn sweep(&mut self, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec)> { + let mut retired = Vec::new(); + let mut i = 0; + while i < self.pending.len() { + if complete(&self.pending[i].0) { + retired.push(self.pending.swap_remove(i)); + } else { + i += 1; + } + } + retired + } + + fn retire_pending(&mut self, receipt: R, pins: Vec, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec)> { + if !pins.is_empty() { + self.pending.push((receipt, pins)); + } + self.sweep(complete) + } + + fn poison(&mut self, pins: Vec, same: impl Fn(&G, &G) -> bool) { + for pin in pins { + if !self.poisoned.iter().any(|old| same(old, &pin)) { + self.poisoned.push(pin); + } + } + } +} + +fn dedup_generations(pins: impl Iterator, same: impl Fn(&G, &G) -> bool) -> Vec { + let mut unique = Vec::new(); + for pin in pins { + if !unique.iter().any(|old| same(old, &pin)) { + unique.push(pin); + } + } + unique +} + +static RETIRING_GENERATIONS: Mutex> = + Mutex::new(GenerationRetirements::new()); + +/// Keep the exact native generations used by one executed title submission until its strong +/// queue receipt completes. Completed batches are swept whenever another pinned batch arrives. +pub(super) fn retire_native_generations<'a>( + receipt: super::alloc_pool::SubmissionReceipt, + pins: impl Iterator, +) { + if receipt.is_complete() { + return; + } + let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.retire_pending(receipt, pins, super::alloc_pool::SubmissionReceipt::is_complete); + drop(retiring); + drop(retired); +} + +/// Native execution began but no exact retirement marker could be recorded. Retain every exact +/// generation permanently: dropping any of them could free a pipeline still referenced by GPU work. +pub(super) fn poison_native_generations<'a>(pins: impl Iterator) { + let pins = dedup_generations(pins.cloned(), NativeGeneration::same); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.sweep(super::alloc_pool::SubmissionReceipt::is_complete); + retiring.poison(pins, NativeGeneration::same); + drop(retiring); + drop(retired); +} + /// 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. Its existing opt-in /// allocation also owns the native generation, so ordinary one-shot builds allocate no new state. @@ -1481,6 +1565,90 @@ mod used_tests { assert_eq!(drops.load(Ordering::Relaxed), 2); } + #[derive(Clone)] + struct FakeReceipt { + fence: Arc, + value: u64, + } + + fn fake_receipt_complete(receipt: &FakeReceipt) -> bool { + receipt.fence.load(Ordering::Relaxed) >= receipt.value + } + + #[test] + fn generation_retirement_deduplicates_and_uses_the_exact_receipt_owner() { + let generation = Arc::new(()); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + Arc::ptr_eq, + ); + assert_eq!(pins.len(), 1); + + let old_fence = Arc::new(AtomicU64::new(0)); + let replacement_fence = Arc::new(AtomicU64::new(99)); + let mut retiring = GenerationRetirements::new(); + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence.clone(), value: 7 }, + pins, + fake_receipt_complete, + )); + drop(retiring.sweep(fake_receipt_complete)); + assert_eq!(retiring.pending.len(), 1, "a replacement queue generation retired an old receipt"); + assert_eq!(Arc::strong_count(&generation), 2, "the in-flight batch did not retain its generation"); + + old_fence.store(7, Ordering::Relaxed); + drop(retiring.sweep(fake_receipt_complete)); + assert!(retiring.pending.is_empty()); + assert_eq!(Arc::strong_count(&generation), 1); + assert_eq!(replacement_fence.load(Ordering::Relaxed), 99); + + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence, value: 7 }, + vec![generation.clone()], + fake_receipt_complete, + )); + assert!(retiring.pending.is_empty(), "an already-complete receipt retained a final batch"); + } + + #[test] + fn untracked_generation_pins_are_never_swept() { + let generation = Arc::new(()); + let weak = Arc::downgrade(&generation); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + Arc::ptr_eq, + ); + let mut retiring = GenerationRetirements::, FakeReceipt>::new(); + retiring.poison(pins, Arc::ptr_eq); + drop(generation); + + drop(retiring.sweep(fake_receipt_complete)); + assert!(weak.upgrade().is_some(), "sweeping tracked receipts released an untracked generation"); + assert_eq!(retiring.poisoned.len(), 1); + } + + #[test] + fn newly_completed_batch_is_returned_for_drop_after_unlock() { + struct DropPin(Arc); + impl Drop for DropPin { + fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let fence = Arc::new(AtomicU64::new(1)); + let mut retiring = GenerationRetirements::new(); + let retired = retiring.retire_pending( + FakeReceipt { fence, value: 1 }, + vec![DropPin(drops.clone())], + fake_receipt_complete, + ); + + assert!(retiring.pending.is_empty()); + assert_eq!(drops.load(Ordering::Relaxed), 0, "the manager dropped a pin while it was borrowed mutably"); + drop(retired); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } + #[test] fn concurrent_generation_publications_are_monotonic() { let slot = Arc::new(Mutex::new(GenerationSlot::default())); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 45cccb609a..4d15405cf2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9574,6 +9574,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let mut gate = super::alloc_pool::SubmissionGate::default(); let mut submitted = Vec::with_capacity(mapped.len()); let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { super::queue_submit::with(this as usize, || { let lists = chunk.lists(); @@ -9582,6 +9583,8 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis this, lists, track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), || { let _ = super::alloc_pool::note_resubmits(this, lists); },