From fb1a9050f383349a5cdd94ba0b18efa841f6581b 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/2] 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 | 65 +++++- crates/xcl/src/hle/d3d12x/real.rs | 11 +- crates/xcl/src/hle/d3d12x/title_list.rs | 13 +- 6 files changed, 361 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index f5ed20cec..d030c0e62 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -158,6 +158,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 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 da5b15ef4..c8c240a38 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 { @@ -801,7 +822,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 06cca160a..118a8b826 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -605,6 +605,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 { @@ -805,6 +815,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::in_flight(a.as_raw() as usize) } { + std::mem::forget(a); + } + } } } @@ -821,6 +837,7 @@ pub(super) fn clear_segment_state(list: usize) { s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); + s.deferred = None; } } @@ -1415,6 +1432,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 { @@ -1452,8 +1477,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; @@ -2491,14 +2517,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))?; @@ -2539,14 +2655,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; @@ -2569,7 +2685,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; } }, @@ -2666,15 +2782,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 @@ -3016,6 +3175,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); @@ -6137,6 +6299,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 39f338143..66d0222a8 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; @@ -36,6 +36,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, } @@ -169,6 +171,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() +} + fn queue() -> &'static Mutex>> { static Q: OnceLock>>> = OnceLock::new(); Q.get_or_init(|| { @@ -181,10 +190,12 @@ 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(p) = next else { 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); + for p in std::iter::from_fn(next_needed).chain([p]) { + // (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); + } } }); } @@ -417,6 +428,34 @@ mod used_tests { let _ = released(standin); } + #[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] @@ -635,6 +674,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.clone()); + let _ = queue().lock().unwrap().send(p); + } +} + /// (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 9241a3a18..d342785e4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5903,7 +5903,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) @@ -5912,7 +5912,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"))); - f(this, super::pso_async::resolve_for_bind(pso as usize) as *mut c_void); + f(this, super::pso_async::resolve(pso as usize) as *mut c_void); super::list_x::on_set_pipeline_state(this, pso as usize); } @@ -6209,8 +6209,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 05de94b66..82839ca5f 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 { @@ -237,12 +237,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. @@ -251,6 +251,11 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { sg.as_mut()?.get_mut(&(wrapper as usize))?.spares.pop().map(|p| p as *mut c_void) } +/// 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 1a18762674cab845df8b6a4df3f89e11711f4d83 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:49:41 -0700 Subject: [PATCH 2/2] D3D12.X: the builds a submit waits for do not take turns among the big compiles Big driver compiles on the workers go one at a time (BIG_COMPILES), each once the commit headroom it asks for is free. A pipeline whose call was put off to the submit is one the title needs for this frame: its build now takes a lane of its own, four at once, and still waits for its headroom. Programs of 4 MiB or more stay in their lane, one at a time. From cold driver caches, with four compile threads, a retail title finished 69 compute builds of 3 s or more in the 211 s after its world start with this and the commit below it, against 31 with that commit alone and 34 without either (Linux, 1 run each). Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/pso_async.rs | 32 +++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 10 +++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 66d0222a8..fe3bc468d 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -53,6 +53,11 @@ pub(super) fn build_is_wanted() -> bool { BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) } +/// This thread is a worker building a pipeline the title's next submit will wait for. +pub(super) fn build_is_needed_by_submit() -> bool { + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().by_submit)) +} + /// Whether one of the title's threads waits for what this thread is doing, to be asked later and /// from another thread: a worker's build as `build_is_wanted`; a thread that is not XCL's is the /// title's own. @@ -428,6 +433,31 @@ mod used_tests { let _ = released(standin); } + #[test] + fn a_build_knows_a_submit_needs_it() { + let seen = Arc::new(Mutex::new(Vec::new())); + for (standin, needed) in [(0x7E57_F001usize, true), (0x7E57_F002, false)] { + let seen = seen.clone(); + submit(standin, true, Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(100)); + seen.lock().unwrap().push((needed, build_is_needed_by_submit())); + 0x6262 + })); + if needed { + need_by_submit(standin); + } + } + let start = std::time::Instant::now(); + while (is_pending(0x7E57_F001) || is_pending(0x7E57_F002)) && start.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let mut seen = seen.lock().unwrap().clone(); + seen.sort(); + assert_eq!(seen, [(false, false), (true, true)]); + let _ = released(0x7E57_F001); + let _ = released(0x7E57_F002); + } + #[test] fn a_pipeline_a_submit_needs_is_built_before_the_queue() { let order = Arc::new(Mutex::new(Vec::new())); @@ -681,7 +711,7 @@ pub fn want(pso: usize) { } } -/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +/// A call with `pso` was put off to the submit: its build goes before the workers' queue and does not wait for a turn among the big ones. 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) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d342785e4..386a650f9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3589,9 +3589,17 @@ impl Drop for SlotGuard { static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0 }; const GIANT_DRIVER_COMPILE: usize = 4 << 20; static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1 }; +/// big compiles the title's next submit waits for: four at once, each with its commit headroom +static SUBMIT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 4 }; fn compile_slots(bytes: usize) -> &'static Slots { - if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } + if bytes >= GIANT_DRIVER_COMPILE { + &GIANT_COMPILES + } else if super::pso_async::build_is_needed_by_submit() { + &SUBMIT_COMPILES + } else { + &BIG_COMPILES + } } /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker