From 52e9014e98fbb8f235dff036ec95f3b35b3a4595 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:50:29 -0700 Subject: [PATCH 1/3] D3D12.X: a dispatch waits for its pipeline at the submit, not in the bind A compute pipeline that is not built yet was waited for at its bind: the title's thread stood in SetPipelineState, built the pipeline itself, and only then reached the next one. A title that binds many unbuilt compute pipelines in one frame got them one after another. SetPipelineState now binds what is there. A Dispatch, or an ExecuteIndirect that dispatches, whose pipeline is still being built ends the list's segment, as a mid-list Wait after a Write64 does, and gets a closed segment of its own between that one and the next: a translated dispatch sets everything it needs itself (root signature, the six views, the pipeline), so it can be recorded later than the calls around it. The title's threads go on recording, and the pipelines the frame binds next reach the workers while this one is built. At ExecuteCommandLists (and KickoffX) each such segment is reset and its call recorded through the same wait the bind made (XCL_PSO_WAIT_MS still bounds it). A dispatch whose pipeline fails to build is skipped and counted, as before. While a submit stands in that wait, the lists it carries and their Write64 signals are not on the queue yet, and another queue's GPU wait for one of them ran into the 5 s watchdog and was released on the CPU (3 lines a run). The watchdog's clock now stands while a bind or submit is held for a build. A put-off pipeline goes before the workers' queue: behind a start-up backlog the submit thread would build them itself, one after another, where several title threads built at once before (a debug build on Windows stopped presenting on its first screen that way). At the submit the next four of its put-off pipelines are marked wanted as it goes, the leave a title thread's own build has today, so about as many are in the driver at once as the title's threads had there before. The segments of a title list record on an allocator of that list's own, because the title's may be recording another list by the submit; it is not released while the GPU may still run from it. They share one argument arena: a block each filled the coherent window. A recording takes 256 extra segments (32 before), two for each such call. Past that, on a list that cannot be split, and under predication the call waits where it is, as before. The console-list replay, Reset, ClearState and KickoffX's re-open wait where they did. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 9 + crates/xcl/src/hle/d3d12x/bind.rs | 29 ++- crates/xcl/src/hle/d3d12x/list_x.rs | 260 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 84 ++++++-- crates/xcl/src/hle/d3d12x/real.rs | 11 +- crates/xcl/src/hle/d3d12x/title_list.rs | 13 +- 6 files changed, 372 insertions(+), 34 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index e821d60740..8b81b85913 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -218,6 +218,15 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { } } +/// Whether the GPU may still run a recording made on the title's allocator `alloc`. +pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); + let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| b.marks.values().any(|(f, v)| f.GetCompletedValue() < *v)); + busy +} + /// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later /// allocator may get its address, and must not go on with this one's PC allocators. The ones /// made here go with it (those lists still record on are left alone: not freed, not tracked). diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index fad934addc..64da26ffa1 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -121,6 +121,22 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u console_list::hold_until_reset(old, blocks); } +/// A submit is about to wait for the pipeline `this` has bound. +pub(super) fn want_bound(this: *mut c_void) { + super::pso_async::want(with(this, |s| s.pso)); +} + +/// A put-off dispatch that could not be recorded. +pub(super) fn dispatch_dropped() { + count(DISPATCHES_SKIPPED); +} + +/// `to` goes on in the arena `from` took its pieces from (`from` takes no more). +pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { + let arena = with(from, |s| std::mem::take(&mut s.arena)); + with(to, |s| s.arena = arena); +} + /// The list is gone. pub(super) fn forget(list: *mut c_void) { if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { @@ -253,7 +269,12 @@ fn signature_dispatches(sig: usize) -> bool { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = with(this, |s| s.pso); + let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(pso) && super::real::is_console_compute(pso); + if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { + return super::pso_async::need_by_submit(pso); + } + let pso = super::pso_async::resolve_wait(pso); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { @@ -847,7 +868,11 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = with(this, |s| s.pso); + if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { + return super::pso_async::need_by_submit(pso); + } + let pso = super::pso_async::resolve_wait(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 diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ef98c131b7..604a59d58c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -649,6 +649,16 @@ struct ListState { predication: Option, /// state a PC Reset clears (restored after KickoffX) bindings: Bindings, + /// what this segment records at the submit (`defer`) + deferred: Option, + /// on a title list's first segment: the allocator its deferred segments record on (the title's may be recording another list by the submit) + own_alloc: Option, +} + +/// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. +pub(super) enum Deferred { + Dispatch(u32, u32, u32), + Indirect(usize, u32, usize, u64, usize, u64), } impl ListState { @@ -849,6 +859,12 @@ pub(super) fn on_release(list: usize) { if !old.write64_signals.is_empty() { WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } + // (the title may release a list the GPU still runs: its allocator must outlive that) + if let Some(a) = old.own_alloc { + if unsafe { super::alloc_pool::allocator_in_flight(a.as_raw() as usize) } { + std::mem::forget(a); + } + } } } @@ -865,6 +881,7 @@ pub(super) fn clear_segment_state(list: usize) { s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); + s.deferred = None; } } @@ -1487,6 +1504,14 @@ pub(super) unsafe fn break_cycles_before_title_signal(sig_q: usize, title_fence: } } +/// Whether an armed GPU wait has outlasted the watchdog; its clock stands while a submit or bind is held for a pipeline build. +fn wait_expired(aw: &mut ArmedGpuWait, held: bool) -> bool { + if held { + aw.armed_at = Instant::now(); + } + aw.armed_at.elapsed() >= gpu_wait_watchdog_timeout() +} + fn wake_sync_watchdog() { let pair = sync_watchdog_pair(&SYNC_WATCHDOG_WAKE, || { let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { @@ -1524,8 +1549,9 @@ fn wake_sync_watchdog() { let mut waiter_q = 0usize; let mut waiter_ty = -1i32; let before = cell.armed_waits.len(); - cell.armed_waits.retain(|aw| { - if aw.armed_at.elapsed() >= gpu_wait_watchdog_timeout() { + let held = super::pso_async::title_held(); + cell.armed_waits.retain_mut(|aw| { + if wait_expired(aw, held) { if aw.val >= max_exp { max_exp = aw.val; waiter_q = aw.waiting_queue; @@ -2603,14 +2629,104 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { return None; } + let next_pc = split(list, None)?; + static SPLITS: AtomicU64 = AtomicU64::new(0); + let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || (n.is_power_of_two() && n <= 256) { + crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after Write64 (#{n})", list_type(next_pc).0); + } + Some(next_pc) +} + +/// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. +pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { + if split(list, Some(what)).is_none() { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: dispatch with a pipeline still being built put off to the submit (#{n})"); + } + true +} + +/// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. +const WANTED_AT_ONCE: usize = 4; + +/// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. +pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { + let mut segs = Vec::new(); + super::title_list::push_segments(wrapper, &mut segs); + let Some(&first) = segs.first() else { return }; + segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); + let mut last: Option<*mut c_void> = None; + for (i, &seg) in segs.iter().enumerate().skip(1) { + for &ahead in segs[i..].iter().take(WANTED_AT_ONCE) { + super::bind::want_bound(ahead); + } + let Some((what, ty, heaps)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.heaps.clone()))) else { + continue; + }; + let Some(own) = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(first as usize))?.own_alloc.clone()) else { + super::bind::dispatch_dropped(); + continue; + }; + let own = own.as_raw(); + let ext = *(seg as *const usize); + let mut hr = match last { + Some(_) => 0, + None => super::alloc_pool::title_reset(own).unwrap_or_else(|| real::reset_pc_allocator(own)), + }; + if hr >= 0 { + hr = super::alloc_pool::reset_list(seg as usize, own as usize, ty.0, |pc_alloc| pc:: i32>(seg, PC_RESET)(seg, pc_alloc, 0)); + } + real::preserve_vtable(seg, ext); + if hr < 0 { + static RESET_ERR: AtomicU64 = AtomicU64::new(0); + warn(&RESET_ERR, "deferred dispatch", format_args!("Reset failed ({hr:#x})")); + super::bind::dispatch_dropped(); + continue; + } + reset_copy_scratch(seg); + if !heaps.is_empty() { + pc::(seg, 28)(seg, heaps.len() as u32, heaps.as_ptr()); + } + if let Some(last) = last { + super::bind::pass_arena(last, seg); + } + match what { + Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), + Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), + } + let ext = *(seg as *const usize); + pc:: i32>(seg, PC_CLOSE)(seg); + real::preserve_vtable(seg, ext); + last = Some(seg); + } +} + +/// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. +unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; - if !super::title_list::can_split(wrapper) { + if !super::title_list::can_split(wrapper, 1 + dispatch.is_some() as usize) { return None; } let ty = list_type(list); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } + let deferred = match dispatch { + Some(what) => { + // (a predicated call stays in its list) + let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); + if !plain { + return None; + } + Some((what, deferred_segment(wrapper, list, ty)?)) + } + None => None, + }; let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { let mut g = LISTS.lock().unwrap(); let s = g.as_mut()?.get_mut(&(list as usize))?; @@ -2651,14 +2767,14 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { real::preserve_vtable(list, ext); if close_hr < 0 { static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CLOSE_ERR, "Wait64 mid-list split", format_args!("Close failed ({close_hr:#x})")); + warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x})")); return None; } let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { 0 } else { - super::pso_async::resolve_for_bind(bound_pso) + super::pso_async::resolve(bound_pso) }; let dev = device_of(list)?; let dev_raw = dev.as_raw() as usize; @@ -2681,7 +2797,7 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { Some(p) => p, None => { static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "Wait64 mid-list split", format_args!("CreateCommandList failed")); + warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); return None; } }, @@ -2784,15 +2900,58 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { } } - super::title_list::activate_segment(wrapper, list, next_pc); - static SPLITS: AtomicU64 = AtomicU64::new(0); - let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; - if n <= 4 || (n.is_power_of_two() && n <= 256) { - crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after Write64 (#{n})", ty.0); + if let Some((what, seg)) = deferred { + { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(seg as usize).or_default(); + s.list_type = Some(ty); + s.bindings.heaps = bindings.heaps.clone(); + s.deferred = Some(what); + } + super::bind::inherit_for_split(list, seg, alloc); + super::bind::pass_arena(list, next_pc); } + super::title_list::activate_segment(wrapper, list, next_pc); Some(next_pc) } +/// A closed, empty segment of `wrapper`'s recording for a dispatch recorded at the submit, on the wrapper's own allocator. +unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { + let dev = device_of(list)?; + let mut segs = Vec::new(); + super::title_list::push_segments(wrapper, &mut segs); + let first = *segs.first()? as usize; + let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); + let own = match own { + Some(a) => a, + None => { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + if !real::is_adopted(a.as_raw()) { + real::adopt(a.as_raw(), real::Kind::CommandAllocator); + } + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(first).or_default().own_alloc = Some(a.clone()); + a + } + }; + let own = own.as_raw() as usize; + let emptied = |p: &*mut c_void| { + let p = *p; + let ext = *(p as *const usize); + let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| pc:: i32>(p, PC_RESET)(p, pc_alloc, 0)); + real::preserve_vtable(p, ext); + hr >= 0 + }; + let p = match super::title_list::pop_spare(wrapper).filter(emptied) { + Some(p) => p, + None => real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(own), 0)?, + }; + let ext = *(p as *const usize); + pc:: i32>(p, PC_CLOSE)(p); + real::preserve_vtable(p, ext); + super::title_list::push_segment(wrapper, p); + Some(p) +} + /// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. /// /// If an earlier write in the same open list already targeted an overlapping UMA range, the @@ -3134,6 +3293,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if close_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } + if let Some(wrapper) = super::title_list::wrapper_of(this) { + record_deferred(wrapper); + } let q_raw = queue as *mut c_void; super::title_textures::refresh(q_raw); @@ -6698,6 +6860,82 @@ mod tests { } } + #[test] + fn a_gpu_wait_does_not_expire_while_the_title_is_held_for_a_build() { + let old = Instant::now() - gpu_wait_watchdog_timeout() * 2; + let mut aw = ArmedGpuWait { val: 1, waiting_queue: 0, waiting_queue_ty: 0, wait_seq: 1, armed_at: old, after_write64: false }; + assert!(!wait_expired(&mut aw, true)); + assert!(!wait_expired(&mut aw, false), "its clock starts again when the hold ends"); + aw.armed_at = old; + assert!(wait_expired(&mut aw, false)); + } + + #[test] + fn a_dispatch_with_a_pipeline_still_building_waits_at_the_submit() { + use super::super::{bind, pso_async, title_list}; + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + + let standin = 0x7E57_D001usize; + pso_async::submit( + standin, + true, + Box::new(|| { + std::thread::sleep(Duration::from_millis(1500)); + 0 + }), + ); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE); + bind::reset(pc0, alloc.as_raw() as usize, standin); + let wrap = title_list::wrap(pc0); + + let t = Instant::now(); + bind::dispatch(pc0, 1, 1, 1); + assert!(t.elapsed() < Duration::from_millis(700), "the dispatch waited for the build ({:?})", t.elapsed()); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 3, "the list before the dispatch, the dispatch, the list after it"); + assert!(pso_async::is_pending(standin)); + + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + assert!(pso_async::is_pending(standin), "Close waited for the build"); + + let skipped = bind::counts_snapshot()[4]; + record_deferred(wrap); + assert!(!pso_async::is_pending(standin), "the submit waits for the build"); + assert!(bind::counts_snapshot()[4] > skipped, "the dispatch of a build that failed is skipped, at the submit"); + + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the split list runs"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + assert_eq!(rel_fn(wrap), 0); + let _ = pso_async::released(standin); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b1fd4c2255..51957b7dba 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -4,7 +4,7 @@ //! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding //! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon //! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited -//! for at its first bind (a skipped dispatch would corrupt what it computes). +//! for where it is used, a `Dispatch` at its submit (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; @@ -38,6 +38,8 @@ struct Pending { #[derive(Default)] struct Demand { wanted: bool, + /// a call put off to the submit needs it (`need_by_submit`) + by_submit: bool, /// thread id of the preload worker (lowest priority) building it, 0 = none preload_thread: u32, } @@ -253,6 +255,13 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; +/// pipelines a submit will wait for: the workers take these before their queue (`need_by_submit`) +static NEEDED: Mutex>> = Mutex::new(std::collections::VecDeque::new()); + +fn next_needed() -> Option> { + NEEDED.lock().unwrap().pop_front() +} + type Work = Box; fn queue() -> &'static Mutex> { @@ -267,6 +276,9 @@ fn queue() -> &'static Mutex> { let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { let next = rx.lock().unwrap().recv(); let Ok(work) = next else { return }; + while let Some(p) = next_needed() { + build_queued(&p); + } work(); }); } @@ -275,18 +287,20 @@ fn queue() -> &'static Mutex> { } fn enqueue(p: Arc) { - let _ = queue().lock().unwrap().send(Box::new(move || { - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - let _ = p.job.lock().unwrap().take(); - return; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); - } - })); + let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&p))); +} + +fn build_queued(p: &Arc) { + // (released by the title meanwhile) + if p.orphan.load(Ordering::Acquire) { + let _ = p.job.lock().unwrap().take(); + return; + } + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(p, job, false); + } } /// The caller also drains its batch. Multiple workers can therefore build @@ -622,6 +636,34 @@ mod used_tests { let _ = released(waited); } + #[test] + fn a_pipeline_a_submit_needs_is_built_before_the_queue() { + let order = Arc::new(Mutex::new(Vec::new())); + let backlog = 8 * crate::gpu::recomp::dxc::compile_threads(); + let standins: Vec = (0..=backlog).map(|i| 0x7E57_E000usize + i).collect(); + for &standin in &standins { + let order = order.clone(); + submit(standin, true, Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(50)); + order.lock().unwrap().push(standin); + 0x6161 + })); + } + let last = *standins.last().unwrap(); + need_by_submit(last); + let start = std::time::Instant::now(); + while standins.iter().any(|&s| is_pending(s)) && start.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let order = order.lock().unwrap(); + assert_eq!(order.len(), standins.len()); + let at = order.iter().position(|&s| s == last).unwrap(); + assert!(at < order.len() / 2, "made last and needed by a submit, it was built {at} of {}", order.len()); + for &standin in &standins { + let _ = released(standin); + } + } + /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. #[test] @@ -953,6 +995,22 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// One of the title's threads is about to wait for `pso`. +pub fn want(pso: usize) { + if let Some(p) = entry(pso) { + p.want(); + } +} + +/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +pub fn need_by_submit(pso: usize) { + let Some(p) = entry(pso) else { return }; + if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { + NEEDED.lock().unwrap().push_back(p); + let _ = queue().lock().unwrap().send(Box::new(|| ())); + } +} + /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4ea6374885..dd304db6ae 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6753,7 +6753,7 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt } } -/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for). +/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for at its use). /// SetPipelineState on the PC list (a pipeline still building in the background: its stand-in) pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { cl_set_pipeline_state(this, pso) @@ -6762,7 +6762,7 @@ 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_of(this, "SetPipelineState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); + let bound = super::pso_async::resolve(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); @@ -7083,8 +7083,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis for &l in std::slice::from_raw_parts(lists, n as usize) { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); - } else if !super::title_list::push_segments(l, &mut mapped) { - mapped.push(l); + } else { + super::list_x::record_deferred(l); + if !super::title_list::push_segments(l, &mut mapped) { + mapped.push(l); + } } } super::list_x::note_queue_for_lists(this as usize, &mapped); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 52fedf8685..adac3bdb7c 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -38,7 +38,7 @@ const F_RING: usize = 0x2000; const F_RING_AT: usize = 0x2100; const RING: usize = 64; /// Maximum number of mid-list split segments per command list recording. -const MAX_EXTRA_SEGMENTS: usize = 32; +const MAX_EXTRA_SEGMENTS: usize = 256; #[derive(Default)] struct SegmentBook { @@ -269,12 +269,12 @@ pub(super) fn wrapper_of(pc: *mut c_void) -> Option<*mut c_void> { WRAPPER_OF.lock().unwrap().as_ref()?.get(&(pc as usize)).map(|&w| w as *mut c_void) } -/// Whether `wrapper` may allocate/activate another split segment for this recording. -pub(super) fn can_split(wrapper: *mut c_void) -> bool { +/// Whether `wrapper` may allocate/activate `n` more split segments for this recording. +pub(super) fn can_split(wrapper: *mut c_void, n: usize) -> bool { let sg = SEGMENTS.lock().unwrap(); sg.as_ref() .and_then(|m| m.get(&(wrapper as usize))) - .is_none_or(|b| b.extra_active.len() < MAX_EXTRA_SEGMENTS) + .is_none_or(|b| b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) } /// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse @@ -292,6 +292,11 @@ pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } +/// Add the closed segment `pc` to `wrapper`'s recording, after the ones it has. +pub(super) fn push_segment(wrapper: *mut c_void, pc: *mut c_void) { + SEGMENTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active.push(pc as usize); +} + /// Switch `wrapper` from closed segment `old_pc` to newly opened segment `new_pc`. pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, new_pc: *mut c_void) { *((wrapper as usize + F_BACKING) as *mut usize) = new_pc as usize; From b1e84577dbd3dd4667729bf8e3211758957baa74 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:32:30 -0700 Subject: [PATCH 2/3] D3D12.X: a title list is split up to 1024 times for the dispatches it puts off A put-off dispatch takes two segments of its list, and a list had 256. The retail title's first world frame records lists that put off 207 and 209 dispatches (Linux, RTX 4060 Ti): past the 128th the dispatch waited in the bind again, and both recording threads stood in execute_indirect for the rest of a 300 s run. With 1024 the same frame put off 1,392 dispatches, none waited in a bind, and the submit recorded all of them. The segments are command lists the title list keeps: 1,000 more of them cost 55 MB in the test under Wine. The test puts off 210 dispatches on one list; with 256 the 129th waits. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/list_x.rs | 27 ++++++++++++++++++------- crates/xcl/src/hle/d3d12x/title_list.rs | 2 +- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 604a59d58c..3f1e6fe17a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -6893,11 +6893,15 @@ mod tests { let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let standin = 0x7E57_D001usize; + static BUILD: AtomicBool = AtomicBool::new(false); pso_async::submit( standin, true, Box::new(|| { - std::thread::sleep(Duration::from_millis(1500)); + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } 0 }), ); @@ -6907,12 +6911,16 @@ mod tests { bind::reset(pc0, alloc.as_raw() as usize, standin); let wrap = title_list::wrap(pc0); - let t = Instant::now(); - bind::dispatch(pc0, 1, 1, 1); - assert!(t.elapsed() < Duration::from_millis(700), "the dispatch waited for the build ({:?})", t.elapsed()); - let mut segs = Vec::new(); - assert!(title_list::push_segments(wrap, &mut segs)); - assert_eq!(segs.len(), 3, "the list before the dispatch, the dispatch, the list after it"); + const DISPATCHES: usize = 210; + let mut segs = vec![pc0]; + for n in 1..=DISPATCHES { + let t = Instant::now(); + bind::dispatch(*segs.last().unwrap(), 1, 1, 1); + assert!(t.elapsed() < Duration::from_millis(700), "dispatch {n} waited for the build ({:?})", t.elapsed()); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + } + assert_eq!(segs.len(), 1 + 2 * DISPATCHES, "the list before each dispatch, the dispatch, the list after it"); assert!(pso_async::is_pending(standin)); let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); @@ -6920,9 +6928,14 @@ mod tests { assert!(pso_async::is_pending(standin), "Close waited for the build"); let skipped = bind::counts_snapshot()[4]; + let build = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(300)); + BUILD.store(true, Ordering::Release); + }); record_deferred(wrap); assert!(!pso_async::is_pending(standin), "the submit waits for the build"); assert!(bind::counts_snapshot()[4] > skipped, "the dispatch of a build that failed is skipped, at the submit"); + build.join().unwrap(); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index adac3bdb7c..a41e5643fc 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -38,7 +38,7 @@ const F_RING: usize = 0x2000; const F_RING_AT: usize = 0x2100; const RING: usize = 64; /// Maximum number of mid-list split segments per command list recording. -const MAX_EXTRA_SEGMENTS: usize = 256; +const MAX_EXTRA_SEGMENTS: usize = 1024; #[derive(Default)] struct SegmentBook { From 6044729477db63730f46ddee576ad6f7e53f89e9 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:07:18 -0700 Subject: [PATCH 3/3] D3D12.X: the put-off dispatches of a list share one split scratch Since 0829441 the chains of one PC list share a scratch, and all recordings together are bounded by XCL_SPLIT_SCRATCH_TOTAL_MB. Each dispatch put off to the submit records on a PC list of its own, so each made a new buffer: up to 256 MiB while the total had room, then 2 MiB each, past the bound. They stayed under the list's own allocator until the next submit that put a call off reset it. The segment recorded after another at the submit now goes on in its scratch, as a chain after a chain on one list does (with the UAV barrier that chain records), and the list's own allocator is reset at its next Reset once the GPU is done with it. Found by pvfreis, reading #2118 on main 68a284a. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 14 ++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 35 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index e9cd91319b..de0d7d16ef 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2704,6 +2704,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { } if let Some(last) = last { super::bind::pass_arena(last, seg); + real::dispatch_chain::list_follows(last as usize, seg as usize); } match what { Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), @@ -2716,6 +2717,18 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { } } +/// The allocator `list`'s put-off calls recorded on is reset once the GPU is done with them, so +/// their split dispatches' scratch does not outlive them. +unsafe fn reset_own_alloc(list: *mut c_void) { + let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))?.own_alloc.clone()); + let Some(own) = own else { return }; + let own = own.as_raw(); + // (without `alloc_pool` nothing says whether the GPU is done: the next submit resets it) + if super::alloc_pool::enabled() && !super::alloc_pool::allocator_in_flight(own as usize) { + super::alloc_pool::title_reset(own).unwrap_or_else(|| real::reset_pc_allocator(own)); + } +} + /// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; @@ -4058,6 +4071,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 } reset_copy_scratch(this); + reset_own_alloc(this); let is_bundle = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ddce2bfa9a..958c9e9c28 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -136,6 +136,14 @@ pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); } +/// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. +pub(in crate::hle::d3d12x) fn list_follows(from: usize, to: usize) { + let mut shared = SHARED.lock().unwrap(); + if let Some(e) = shared.get(&from).cloned() { + shared.insert(to, e); + } +} + /// The scratch of all recordings alive together, `XCL_SPLIT_SCRATCH_TOTAL_MB` (384). A recording /// keeps its scratch until its allocator is reset, and a title that records ahead of the GPU has /// many: with a bound on one dispatch alone a retail title's world took 1.2 GB and went on growing. @@ -231,6 +239,33 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn a_list_recorded_after_another_goes_on_in_its_scratch() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::{D3D12CreateDevice, ID3D12Device}; + use windows::Win32::Graphics::Dxgi::*; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + let warp = unsafe { CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) }; + if warp.and_then(|w| unsafe { D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev) }).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let (a, b, c, alloc) = (0x7E57_5C01usize, 0x7E57_5C02usize, 0x7E57_5C03usize, 0x7E57_5CA0usize); + let (first, used) = unsafe { super::scratch_for(&dev, a, alloc, MB, 4096) }.unwrap(); + assert!(!used); + super::list_follows(a, b); + let (second, used) = unsafe { super::scratch_for(&dev, b, alloc, MB, 4096) }.unwrap(); + assert!(used && std::sync::Arc::ptr_eq(&first, &second), "the list after it made a scratch of its own"); + let (third, _) = unsafe { super::scratch_for(&dev, c, alloc, MB, 4096) }.unwrap(); + assert!(!std::sync::Arc::ptr_eq(&first, &third)); + for list in [a, b, c] { + super::list_reset(list); + } + } + #[test] fn a_chains_scratch_is_bounded_by_what_all_recordings_hold() { let group = 187 << 10;