From 665ce02914592185c4d9cd9f4fd64f777ce92c4b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 02:50:42 -0800 Subject: [PATCH] D3D12.X: capture native PSO generations in recordings Recipe-backed PSOs can eventually replace a native object while recorded command lists still refer to the prior generation. Capture the exact generation atomically at every native bind, deduplicate pins per physical segment, and carry them into immutable submission plans and bundle parents. This stage intentionally stops at capture; submission retirement will attach the pins to receipts later. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/bind.rs | 9 +- crates/xcl/src/hle/d3d12x/console_list.rs | 27 +++- crates/xcl/src/hle/d3d12x/device_x.rs | 3 +- crates/xcl/src/hle/d3d12x/list_x.rs | 151 +++++++++++++++--- crates/xcl/src/hle/d3d12x/pso_async.rs | 177 ++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 19 ++- 6 files changed, 335 insertions(+), 51 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e6718c62da..8d63d78405 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -328,7 +328,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return; } - let (pso, bound_unbuilt) = super::pso_async::resolve_wait_bound(raw_pso); + let ((pso, bound_unbuilt), generation) = super::pso_async::resolve_wait_bound_and_pin_if_enabled(raw_pso); + super::list_x::record_native_generation(this as usize, generation); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let args_off_title = args_off; let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); @@ -650,7 +651,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); if !super::real::is_translated_graphics(real) { // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing @@ -1013,7 +1014,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f if super::pso_async::is_pending(pso) && super::list_x::defer(this, pso, super::list_x::Deferred::Dispatch(x, y, z, flags)) { return; } - let pso = super::pso_async::resolve_wait(pso); + let pso = super::list_x::resolve_and_record_pipeline_wait(this as usize, pso); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that @@ -1199,7 +1200,7 @@ unsafe fn bind_abi_with_root( Ok(p as usize) }; // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3878989669..75a597eee0 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -435,7 +435,18 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps } with_list(obj, |st| new_chunk(obj, st)); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + // The adopted physical slot reaches real::cl_reset, which resolves and records the initial + // generation. Do not clear that capture again in this outer console wrapper. + forward_reset(pc, allocator, pso, |pc, allocator, pso| f(pc, allocator, pso)) +} + +unsafe fn forward_reset( + pc: usize, + allocator: *mut c_void, + pso: *mut c_void, + call: impl FnOnce(usize, *mut c_void, *mut c_void) -> HRESULT, +) -> HRESULT { + call(pc, allocator, pc_pso(pso)) } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -890,7 +901,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // a pipeline still being built in the background is waited for; if // the background translation failed, skip instead of binding XCL's // ABI root signature onto the stand-in - let real = super::pso_async::resolve_wait((*p).pc); + let real = super::list_x::resolve_and_record_pipeline_wait(st.pc, (*p).pc); if !super::real::is_translated_compute(real) { out.skipped_dispatches += 1; continue; @@ -997,6 +1008,18 @@ fn bytemuck_u32(v: &[u32]) -> &[u8] { mod tests { use super::*; + #[test] + fn console_reset_preserves_the_physical_initial_generation_capture() { + let mut pins = vec![1u64]; + let hr = unsafe { forward_reset(0xC1, std::ptr::null_mut(), std::ptr::null_mut(), |_, _, _| { + pins.clear(); + pins.push(2); + S_OK + }) }; + assert_eq!(hr, S_OK); + assert_eq!(pins, [2], "the outer wrapper must not clear the physical Reset hook's new pin"); + } + #[test] fn layout_packs_parameters_in_order() { // RTS0 v2: consts b0 x19 | UAV u0 | UAV u1 | SRV t0 diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index cff823329a..511ae0ad4a 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -104,11 +104,12 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - let resolved_pso = super::pso_async::resolve_for_bind(pso); + let (resolved_pso, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); let pc_alloc = active_list_allocator(alloc); let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index fabaed0970..92f265a9b4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -728,6 +728,8 @@ struct ListState { last_queue: Option, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Recipe-backed native generations referenced by this physical recording. + native_generations: Vec, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -811,6 +813,10 @@ enum WaitPlacement { } impl ListState { + fn pin_native_generation(&mut self, generation: super::pso_async::NativeGeneration) { + push_unique(&mut self.native_generations, generation, super::pso_async::NativeGeneration::same); + } + fn note_write(&mut self, producer: WriteProducer, va: u64, size: u64) { if size == 0 { return; @@ -885,22 +891,69 @@ pub(super) fn note_shared_view_heap_use(list: *mut c_void) { } } +fn push_unique(items: &mut Vec, item: T, same: impl Fn(&T, &T) -> bool) { + if !items.iter().any(|old| same(old, &item)) { + items.push(item); + } +} + fn propagate_bundle_shared_view_use(states: &mut HashMap, parent: usize, bundle: usize) { - let uses_shared = states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap); - if uses_shared { - if let Some(state) = states.get_mut(&parent) { - state.uses_shared_view_heap = true; - } + if states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap) { + states.entry(parent).or_default().uses_shared_view_heap = true; } } -/// Snapshot bundle descriptor use into the parent recording before the bundle may be reset. -pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { - if super::vram::srv_tracking_enabled() { - if let Some(states) = LISTS.lock().unwrap().as_mut() { - propagate_bundle_shared_view_use(states, this as usize, bundle as usize); +pub(super) fn record_native_generation(list: usize, generation: Option) { + if let Some(generation) = generation { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().pin_native_generation(generation); + } +} + +pub(super) fn resolve_and_record_pipeline(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_lazy(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_lazy(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_wait(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_wait(pso); + record_native_generation(list, generation); + resolved +} + +/// Snapshot bundle descriptor and PSO-generation use before the bundle may be reset. +pub(super) fn on_execute_bundle(parent: usize, bundle: usize) { + let track_descriptors = super::vram::srv_tracking_enabled(); + let track_generations = super::pso_async::rebuild_recipes_enabled(); + if !track_descriptors && !track_generations { + return; + } + let mut g = LISTS.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + let pins = if track_generations { + m.get(&bundle).map(|s| s.native_generations.clone()).unwrap_or_default() + } else { + Vec::new() + }; + if track_descriptors { + propagate_bundle_shared_view_use(m, parent, bundle); + } + if track_generations { + let parent = m.entry(parent).or_default(); + for pin in pins { + parent.pin_native_generation(pin); } } +} + +pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { + on_execute_bundle(this as usize, bundle as usize); pc::(this, 27)(this, bundle); } @@ -930,6 +983,7 @@ struct KickoffEffects { uses_shared_view_heap: bool, write64_signals: Vec<(u64, u64)>, cpu_writes: Vec, + _native_generations: Vec, } fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { @@ -941,6 +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), }; state.written_ranges.clear(); state.segment_write_producers.clear(); @@ -1068,6 +1123,7 @@ pub(super) struct SegmentEffects { texture_transitions: Vec, uses_shared_view_heap: bool, cpu_writes: Vec, + _native_generations: Vec, } impl SegmentEffects { @@ -1107,6 +1163,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(), }) .unwrap_or_default() }) @@ -1434,6 +1491,7 @@ pub(super) fn clear_segment_state(list: usize) { s.pred_in_state = false; s.bindings = Bindings::default(); s.deferred = None; + s.native_generations.clear(); } } @@ -3612,10 +3670,10 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - let pred_buf = &carry.pred_buf; let bindings = &carry.bindings; - let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { - 0 + let (init_pso, init_generation) = if ty == D3D12_COMMAND_LIST_TYPE_COPY { + (0, None) } else { - super::pso_async::resolve(bound_pso) + super::pso_async::resolve_and_pin_if_enabled_lazy(bound_pso) }; let dev = device_of(list)?; let dev_raw = dev.as_raw() as usize; @@ -3650,7 +3708,10 @@ pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) - } else { None }; - let continuation_state = carry.continuation_state(ty); + let mut continuation_state = carry.continuation_state(ty); + if let Some(generation) = init_generation { + continuation_state.pin_native_generation(generation); + } let next_bindings = super::bind::prepare_split(list, next_pc, alloc); let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, alloc)); @@ -4058,12 +4119,22 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { + return; + } + let clear_predication = PREDICATION_USED.load(Ordering::Acquire); + let clear_generations = super::pso_async::rebuild_recipes_enabled(); + if !clear_predication && !clear_generations { return; } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.predication = None; - s.pred_in_state = false; + if clear_generations { + s.native_generations.clear(); + } + if clear_predication { + s.predication = None; + s.pred_in_state = false; + } } } @@ -4242,10 +4313,13 @@ 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(), + 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 } = effects; + let KickoffEffects { + waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, + write64_signals, cpu_writes, _native_generations, + } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } @@ -4367,6 +4441,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.clear_waits(); s.texture_writes.clear(); s.cpu_writes.clear(); + s.native_generations.clear(); s.bindings = bindings_copy; } primary @@ -4375,7 +4450,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let (init_pso, init_generation) = super::pso_async::resolve_and_pin_if_enabled(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); @@ -4389,6 +4464,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + record_native_generation(target as usize, init_generation); trace_list(target as usize, ListEvent::Reset); reset_copy_scratch(target); let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); @@ -4493,7 +4569,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b (if restore { Some(s.bound_pso) } else { None }, target != s.native_bias) }; if let Some(base) = need_restore_base { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); } if !need_native_call { @@ -4537,7 +4613,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } }; if let Some(base) = restore { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); } } @@ -4577,7 +4653,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { } None => (bound_pso, false), }; - let resolved = super::pso_async::resolve_for_bind(target); + let resolved = resolve_and_record_pipeline(list as usize, target); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; @@ -5084,7 +5160,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); - let resolved = super::pso_async::resolve_for_bind(pso); + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { @@ -5119,11 +5195,13 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.texture_transitions.clear(); s.uses_shared_view_heap = false; s.cpu_writes.clear(); + s.native_generations.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; + record_native_generation(this as usize, generation); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { @@ -5640,6 +5718,31 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn generation_capture_deduplicates_and_survives_recording_reset() { + let generation = Arc::new(()); + let mut recording = Vec::new(); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + assert_eq!(recording.len(), 1); + + let submission_plan = recording.clone(); + recording.clear(); + drop(generation); + assert_eq!(Arc::strong_count(&submission_plan[0]), 1, "the immutable plan must own the submitted generation"); + } + + #[test] + fn bundle_snapshot_deduplicates_into_parent_recording() { + let generation = Arc::new(()); + let bundle = vec![generation.clone()]; + let mut parent = vec![generation]; + for pin in bundle { + push_unique(&mut parent, pin, Arc::ptr_eq); + } + assert_eq!(parent.len(), 1); + } + #[test] fn creation_keeps_logical_allocator_separate_from_recording_backing() { let list = 0x7e57_a101usize as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index e20ced7767..a576633a1f 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -674,10 +674,12 @@ struct RecipeInner { #[allow(dead_code)] // recorded-list generation pins are the next opt-in stage pub(super) struct NativeGeneration(Arc>); -#[allow(dead_code)] // recorded-list generation pins are the next opt-in stage impl NativeGeneration { + #[allow(dead_code)] // consumed by the later retirement diagnostics stage pub(super) fn id(&self) -> u64 { self.0.id } + #[allow(dead_code)] // exposed to focused generation-capture tests pub(super) fn raw(&self) -> usize { self.0.raw } + pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } /// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the @@ -1367,6 +1369,88 @@ mod used_tests { assert_eq!(slot.resident.as_ref().unwrap().id, 400); } + #[test] + fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { + let standin = 0x7E57_C130usize; + let real = 0x7E57_C131usize; + let (go_tx, go_rx) = mpsc::channel(); + let (started_tx, started_rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + started_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + real + }), 0); + + let (lazy, lazy_pin) = resolve_and_pin_mode(standin, ResolveMode::Lazy); + assert_eq!(lazy, standin); + assert!(lazy_pin.is_none()); + let (identity, identity_pin) = resolve_and_pin_if_enabled_identity(standin); + assert_eq!(identity, standin); + assert!(identity_pin.is_none()); + started_rx.recv().unwrap(); + let (result_tx, result_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| result_tx.send(resolve_and_pin_mode(standin, ResolveMode::ForBind).0).unwrap()); + assert!(result_rx.recv_timeout(std::time::Duration::from_millis(10)).is_err(), "for-bind compute resolution must still wait"); + go_tx.send(()).unwrap(); + }); + assert_eq!(result_rx.recv().unwrap(), real); + assert_eq!(resolve_and_pin_mode(standin, ResolveMode::Wait).0, real); + assert_eq!(released(standin), real); + } + + #[test] + fn capture_never_resolves_against_a_reused_pending_address() { + let standin = 0x7E57_C138usize; + let old_real = 0x7E57_C139usize; + submit_lazy(standin, false, Box::new(move || old_real), 0); + let old = entry(standin).unwrap(); + let job = old.build.job.lock().unwrap().take().unwrap(); + complete(&old.build, job()); + let removed = PENDING.remove(standin).unwrap(); + + submit_lazy(standin, false, Box::new(|| 0x7E57_C13Ausize), 0); + let (chosen, pin) = resolve_and_pin_pending(standin, &old, ResolveMode::Lazy); + assert_eq!(chosen, old_real, "selection must use the retained Pending, not its reused map slot"); + assert!(pin.is_none()); + + assert_eq!(released(standin), 0); + drop(removed); + drop(old); + } + + #[test] + fn bound_wait_capture_pins_the_exact_published_generation() { + #[repr(C)] + struct FakePso { vtable: *const usize, refs: AtomicUsize } + unsafe extern "system" fn add_ref(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + let vtable = [0usize, add_ref as usize, release as usize]; + let mut fake = FakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut fake as *mut FakePso as usize; + let standin = 0x7E57_C140usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let job = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, job()); + + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + let pin = pin.expect("published recipe generation must be captured"); + assert_eq!((chosen, bound_unbuilt, pin.raw(), pin.id()), (raw, false, raw, 1)); + assert_eq!(fake.refs.load(Ordering::Relaxed), 2, "generation pin shares the recipe's exact COM owner"); + + drop(pin); + assert_eq!(released(standin), raw); + drop(pending); + assert_eq!(unsafe { release(raw as *mut std::ffi::c_void) }, 0); + } + #[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)); @@ -2604,28 +2688,89 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// generation is chosen while holding `Build.done`, the same lock that publishes it and that /// `released` uses before giving up the original raw owner. Ordinary one-shot builds keep their /// existing resolution path and return no generation pin. -#[allow(dead_code)] // command-list generation capture is the next opt-in stage pub(super) fn resolve_and_pin_for_bind(pso: usize) -> (usize, Option) { + resolve_and_pin_mode(pso, ResolveMode::ForBind) +} + +#[derive(Clone, Copy)] +enum ResolveMode { Lazy, Wait, ForBind } + +fn resolve_and_pin_mode(pso: usize, mode: ResolveMode) -> (usize, Option) { let Some(p) = entry(pso) else { return (pso, None) }; - let Some(recipe) = p.build.recipe.as_ref() else { return (resolve_for_bind(pso), None) }; - p.note_use(); - if p.compute { - let _ = resolve_wait_pending(&p, pso, wait_budget()); - } else if p.build.real.load(Ordering::Acquire) == 0 { - schedule(&p.build, Priority::BoundSoon, false, None); - p.build.promote(Priority::Foreground); - } + resolve_and_pin_pending(pso, &p, mode) +} + +fn resolve_and_pin_pending(pso: usize, p: &Arc, mode: ResolveMode) -> (usize, Option) { + // Resolve directly against this retained Pending: a concurrent release/address reuse cannot + // make selection consult a new registry entry while validation still uses the old recipe. + let resolved = match mode { + ResolveMode::Lazy => resolve_pending(p, pso), + ResolveMode::Wait => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind if p.compute => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind => resolve_pending(p, pso), + }; + let bound_unbuilt = p.bound_unbuilt(pso, resolved); + pin_resolved(p, resolved, bound_unbuilt) +} + +fn pin_resolved(p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option) { + let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None) }; let _done = p.build.done.lock().unwrap(); - let real = p.build.real.load(Ordering::Acquire); - if real == 0 { - return (p.stand(pso), None); + let current = p.build.real.load(Ordering::Acquire); + if current == resolved { + return (resolved, recipe.pin(resolved)); + } + // Preserve a resolver's deliberate stand-in choice. If an eventual rebuild replaced a + // native generation between resolution and this lock, select and pin the current publication + // instead of returning an ownerless stale raw pointer. + if bound_unbuilt { + return (resolved, None); } - match recipe.pin(real) { - Some(generation) => (generation.raw(), Some(generation)), - None => (p.stand(pso), None), + match recipe.pin(current) { + Some(generation) => (current, Some(generation)), + None => (resolved, None), } } +/// Preserve the ordinary resolver exactly unless recipe rebuilding was explicitly enabled. +pub(super) fn resolve_and_pin_if_enabled(pso: usize) -> (usize, Option) { + if rebuild_recipes_enabled() { resolve_and_pin_for_bind(pso) } else { (resolve_for_bind(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_lazy(pso: usize) -> (usize, Option) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Lazy) } else { (resolve(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_wait(pso: usize) -> (usize, Option) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Wait) } else { (resolve_wait(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_identity(pso: usize) -> (usize, Option) { + (pso, None) +} + +pub(super) fn resolve_wait_bound_and_pin_if_enabled(pso: usize) -> ((usize, bool), Option) { + if !rebuild_recipes_enabled() { + return (resolve_wait_bound(pso), None); + } + resolve_wait_bound_and_pin(pso) +} + +fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option) { + let Some(p) = entry(pso) else { return ((pso, false), None) }; + p.note_use(); + let bound = resolve_wait_pending(&p, pso, wait_budget()); + let choice = (bound, p.bound_unbuilt(pso, bound)); + let (resolved, generation) = pin_resolved(&p, choice.0, choice.1); + ((resolved, choice.1), generation) +} + /// The title released stand-in `pso` for good: forget it (its address may come back for /// another object) and return its real pipeline to release when this is its last owner /// (0: another `Pending` owns the build, none, or still being built – the worker's result is diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4e7aa5ff2d..45cccb609a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3028,10 +3028,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro } pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void, mask: usize, ty: usize, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let pc_pso = super::console_list::pc_pso(pso as *mut c_void) as usize; + let (pc_pso, generation) = super::pso_async::resolve_and_pin_if_enabled_identity(super::console_list::pc_pso(pso as *mut c_void) as usize); let hr = dev_create_command_list(this, mask, ty, alloc, pc_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_console_list_create(*ppv, alloc, pc_pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); *ppv = super::console_list::create_with_allocator(*ppv, alloc as *mut c_void); } hr @@ -3128,6 +3129,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("DrawInstanced", cl_draw_instanced as usize), ("DrawIndexedInstanced", cl_draw_indexed_instanced as usize), ("SetPipelineState", cl_set_pipeline_state as usize), + ("ExecuteBundle", cl_execute_bundle as usize), ("SetMarker", cl_set_marker as usize), ("OMSetRenderTargets", cl_om_set_render_targets as usize), ("ClearRenderTargetView", cl_clear_rtv as usize), @@ -3220,11 +3222,13 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); - let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(initial_state as usize); + let resolved = resolved as *mut c_void; let hr = f(this, allocator, resolved); preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); + super::list_x::record_native_generation(this as usize, generation); super::dred::reset(this); if !initial_state.is_null() { super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); @@ -9140,12 +9144,19 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); + let bound = super::list_x::resolve_and_record_pipeline_lazy(this as usize, pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } +unsafe extern "system" fn cl_execute_bundle(this: *mut c_void, bundle: *mut c_void) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void); + super::list_x::on_execute_bundle(this as usize, bundle as usize); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteBundle"))); + f(this, bundle); +} + /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: *const c_void, size: u32) { type F = unsafe extern "system" fn(*mut c_void, u32, *const c_void, u32); @@ -9157,7 +9168,7 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); + let bound = super::list_x::resolve_and_record_pipeline(this as usize, pso as usize); f(this, bound as *mut c_void); if !pso.is_null() { super::dred::mark_pipeline(this, pso as usize, bound);