From ee2abf2e43745434a3996cfe70e1ab188bf8e696 Mon Sep 17 00:00:00 2001 From: Raul Paiva <63853678+Raul-Paiva@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:15:43 +0000 Subject: [PATCH] D3D12.X: ExecuteIndirect checks of a run of draws share one pass Each checked ExecuteIndirect records, in front of itself, a UAV barrier on everything, a Dispatch(1, 1, 1) of the count check and two transitions of its output buffer. A retail title makes thousands of these a frame. Another open-source runtime for the same platform measured this pattern at 14-16 us a check and got its replayed frame from 86.1 to 77.7 ms by checking all the arguments between two points where they can change in one compute pass. With XCL_INDIRECT_GUARD_BATCH=1 the checks of draws (Draw and DrawIndexed signatures) go in batches of up to 32 per list. The first draw of a batch records the barrier, one pass and one transition of the output buffer to INDIRECT_ARGUMENT; the pass reads a block of jobs in CPU-visible memory (window, offset, slot, kind; the program id and title address for the log) that the CPU fills while the list is recorded, before it is submitted. A later draw of the batch only writes its job: no barrier, dispatch or transition. The counts are read through the memory windows (eight bound as root UAVs); counts elsewhere, dispatches (clamped after the check) and the compare diagnostic are checked alone, as before. A batch ends, with the output buffer back to COMMON, at: - an ExecuteIndirect that is not of a plain Draw / DrawIndexed signature (dispatches, mesh, root changes, several arguments), at the top of the hook, before any of its paths (indirect_guard::before_execute_indirect), and a DispatchMesh; - any other title call on the list but ExecuteIndirect, root constant and root view sets, the pipeline set, topology, scissors, viewports, blend factor, stencil ref and index / vertex buffer sets (bind::before_list_call, now also installed with this switch): barriers, draws, dispatches, copies, clears, render targets, queries, waits, writes, flushes, root signature and descriptor table sets and the console's other methods all end it; - a check that goes alone; - the list's Close and the PC Close of a segment (split, KickoffX); - a Reset, a split or the list's release forgets it (nothing left to record). Between the first draw of a batch and the last one the title makes no call that writes memory but plain indirect draws, and what those write reaches a later draw's counts only through a barrier, which ends the batch: the pass reads the counts each draw would have read. A recording keeps its blocks of jobs (16384 in all, 17 MB) until its PC allocator is reset (console_list::allocator_reset), when the GPU is done with it: a list submitted again reads its own jobs, and the CPU never writes a block the GPU may still read. With no block free, a check goes alone. Off by default, to be measured first. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 64 ++- crates/xcl/src/hle/d3d12x/console_list.rs | 1 + crates/xcl/src/hle/d3d12x/indirect_guard.rs | 496 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 5 +- 4 files changed, 551 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0c064f8f93..8a58a356ab 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1098,6 +1098,7 @@ fn install_reset( untrack_two_pass_list(list as usize); } unmark_deferring(list); + super::indirect_guard::retire_batches(list, old); console_list::hold_until_reset(old, blocks); retire_recording_res(old, res_bufs, res_marks, res_untracked); drop(old_resolution); @@ -1262,6 +1263,7 @@ pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize untrack_two_pass_list(to as usize); } unmark_deferring(to); + super::indirect_guard::retire_batches(to, old); console_list::hold_until_reset(old, blocks); retire_recording_res(old, res_bufs, res_marks, res_untracked); PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution, heaps } @@ -1405,7 +1407,9 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { unmark_deferring(list); - if let Some(mut s) = take_state(list as usize) { + let state = take_state(list as usize); + super::indirect_guard::retire_batches(list, state.as_ref().map_or(0, |s| s.allocator)); + if let Some(mut s) = state { let batch = s.end_batch(); if !s.res_retired.is_empty() || s.res_buf.is_some() || batch.is_some() || !s.res_marks.is_empty() || s.res_untracked || !s.fb_uses.is_empty() { untrack_two_pass_list(list as usize); @@ -2096,6 +2100,16 @@ fn flush_wanted(slot: usize, newer_layout: bool, from_title: bool, deferring: bo deferring && from_title && !keeps_two_pass_batch(slot, newer_layout) } +/// Whether a list call through `slot` ends the list's batch of ExecuteIndirect checks +/// (`indirect_guard`, `open`): any but those a run of deferred draws goes on across and the +/// viewport, blend factor and index / vertex buffer sets – none writes memory or orders writes. +/// DispatchMesh ends it (its shaders may write a later draw's counts); an ExecuteIndirect decides +/// for itself (`indirect_guard::before_execute_indirect`: only a plain draw goes on). +fn guard_batch_end_wanted(slot: usize, newer_layout: bool, from_title: bool, open: bool) -> bool { + let dm = if newer_layout { 129 } else { 127 }; + open && from_title && (slot == dm || (!keeps_two_pass_batch(slot, newer_layout) && !matches!(slot, 21 | 23 | 47 | 48))) +} + /// What ended a run (`flush_two_pass`), for the log: a title call through a console list slot /// (`before_list_call`), or one of these. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -2153,17 +2167,24 @@ fn run_ends_text(n: usize) -> String { v.iter().take(n).map(|&(c, i)| format!("{} {c}", run_end_name(i, newer))).collect::>().join(", ") } -/// In front of every command list slot with `XCL_TWO_PASS_BATCH=2` (`real::class_for`): a title -/// call on a list with deferred draws records them first, unless the slot keeps the run -/// (`keeps_two_pass_batch`). Calls from XCL and the runtime go on as they are. +/// In front of every command list slot with `XCL_TWO_PASS_BATCH=2` or +/// `XCL_INDIRECT_GUARD_BATCH=1` (`real::class_for`): a title call on a list with deferred draws +/// records them first, unless the slot keeps the run (`keeps_two_pass_batch`), and one on a list +/// with a batch of ExecuteIndirect checks ends it (`guard_batch_end_wanted`). Calls from XCL and +/// the runtime go on as they are. pub(super) unsafe extern "system" fn before_list_call(caller: usize, slot: u64, frame: *const u64) -> usize { - if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 { + let this = *frame.add(0x80 / 8) as *mut c_void; + let batching = super::indirect_guard::batch_open(this); + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 && !batching { return 0; } - let this = *frame.add(0x80 / 8) as *mut c_void; - let deferring = DEFERRING.contains(this as usize); + let deferring = DEFERRING_LISTS.load(Ordering::Relaxed) != 0 && DEFERRING.contains(this as usize); let newer = super::real::QUEUE_SHIFTED.load(Ordering::Acquire); - if flush_wanted(slot as usize, newer, deferring && crate::modules::image_base_for_addr(caller).is_some(), deferring) { + let from_title = (deferring || batching) && crate::modules::image_base_for_addr(caller).is_some(); + if guard_batch_end_wanted(slot as usize, newer, from_title, batching) { + super::indirect_guard::end_batch(this); + } + if flush_wanted(slot as usize, newer, from_title, deferring) { flush_two_pass(this, RunEnd::Call(slot as usize)); } 0 @@ -2384,6 +2405,10 @@ unsafe fn emit_commands(this: *mut c_void, list: &ID3D12GraphicsCommandList, cmd /// The deferred draws of the list `this`, recorded now (`batch_commands`), for `why`; nothing /// when it has none. pub(super) unsafe fn flush_two_pass(this: *mut c_void, why: RunEnd) { + // (a list or segment that closes ends its batch of ExecuteIndirect checks too) + if matches!(why, RunEnd::Close | RunEnd::Segment) { + super::indirect_guard::end_batch(this); + } if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { return; } @@ -3572,6 +3597,8 @@ unsafe fn execute_indirect_snapshot( count_buf: usize, count_off: u64, signature: IndirectSignatureInfo, raw_pso: usize, resolution: Option, allow_defer: bool, ) { + // (whichever path it takes: one that may write counts ends a batch of checks) + super::indirect_guard::before_execute_indirect(this, sig); 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 dispatches = signature.dispatches(); @@ -8657,6 +8684,27 @@ void main(uint t : SV_GroupIndex) { } } + /// A batch of ExecuteIndirect checks goes on across the calls that write no memory and order + /// no writes; anything else a title calls ends it. + #[test] + fn a_title_call_that_can_write_or_order_memory_ends_a_batch_of_checks() { + for newer in [false, true] { + let (ei, dm) = if newer { (61, 129) } else { (59, 127) }; + // (an ExecuteIndirect decides for itself, `indirect_guard::before_execute_indirect`) + for slot in (0..=8).chain([20, 21, 22, 23, 24, 25, 47, 48]).chain(33..=46).chain([ei]) { + assert!(!guard_batch_end_wanted(slot, newer, true, true), "slot {slot}, newer layout: {newer}"); + } + // barriers, draws, dispatches, DispatchMesh, copies, clears, render targets, heaps, + // queries, predication, bundles, stream output, Close, Reset, the console's own + // methods (waits, writes, flushes, its UAV barrier) + for slot in [26, 12, 13, 14, 15, 16, 17, 18, 19, 27, 28, 29, 30, 31, 32, 49, 50, 51, 52, 53, 54, 55, 9, 10, 11, 60, 67, 69, 71, 72, 78, 81, 85, 93, 146, dm] { + assert!(guard_batch_end_wanted(slot, newer, true, true), "slot {slot}, newer layout: {newer}"); + } + assert!(!guard_batch_end_wanted(26, newer, false, true), "XCL's own calls"); + assert!(!guard_batch_end_wanted(26, newer, true, false), "no batch open"); + } + } + /// A two-pass draw is deferred only on a direct list, without a capture, as one command, with /// records that fit a batch record buffer; otherwise the run is recorded and it goes at once. #[test] diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7c12cdec05..9082bf5805 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -435,6 +435,7 @@ pub fn allocator_reset(allocator: *mut c_void) { unsafe { free_uma(&b) }; } super::bind::release_allocator_res(allocator as usize); + super::indirect_guard::allocator_reset(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index e34169cfc4..77226e0f71 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -12,11 +12,24 @@ //! `XCL_INDIRECT_GUARD=0` turns it off (`=dispatch`: only dispatches are checked); //! `XCL_INDIRECT_MAX_GROUPS` is the most groups one ExecuteIndirect may run (4 Mi: a 4K target //! in 8x8 groups has 130 thousand). +//! +//! `XCL_INDIRECT_GUARD_BATCH=1`: the checks of a list's draws share one pass (`BatchPass`), until +//! the title makes a call that could write memory or order its writes. Each check alone is a UAV +//! barrier, a dispatch and two transitions in front of its ExecuteIndirect; a retail title makes +//! thousands a frame. The pass goes in front of the first draw of its batch and reads the jobs +//! the CPU writes while the list is recorded (before it is submitted). Between that draw and the +//! last one the title makes no call but ExecuteIndirects of plain draws and ones that change no +//! memory (`bind::guard_batch_end_wanted`, `before_execute_indirect`): any other ExecuteIndirect, +//! a DispatchMesh or a dispatch ends the batch. What those draws write reaches the counts of a +//! later one only through a barrier, which ends it too: the counts the pass reads are the ones +//! each draw would have read. A recording keeps its blocks of jobs until its allocator is reset +//! (`retire_batches`, `allocator_reset`), so a list submitted again reads its own jobs. Off unless +//! asked for, to be measured first. use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; use windows::core::Interface; @@ -73,6 +86,163 @@ fn on(kind: Counts) -> bool { *MODE == 2 || (*MODE == 1 && kind == Counts::Dispatch) } +/// `XCL_INDIRECT_GUARD_BATCH=1`: the checks of draws go in batches (read once). +pub(super) fn batch_on() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_INDIRECT_GUARD_BATCH").is_ok_and(|v| v.trim() == "1")); + *ON +} + +/// checks in one batch: the threads of its pass's one group +const BATCH: u32 = 32; +/// bytes of a job: window, offset in it, slot, kind, the program's id, the title's address +const JOB: u32 = 32; +/// bytes of a block of jobs: the count of them (16 bytes), the jobs +const BLOCK_BYTES: u32 = 16 + BATCH * JOB; +/// Blocks of jobs (17 MB). A block belongs to the recording that wrote it until that recording's +/// allocator is reset (`Blocks`); with none free, a check goes alone. +const BLOCKS: u32 = 1 << 14; +/// memory windows the pass reads counts through (root UAVs); counts in another are checked alone +const BATCH_WINDOWS: usize = 8; + +/// Whether a check of `kind` can go in a batch (`on`: `batch_on`). Dispatches go alone: their +/// counts are clamped after the check (`clamp`), which reads them as a UAV. +fn batchable(on: bool, kind: Counts, compare: bool) -> bool { + on && kind != Counts::Dispatch && !compare +} + +/// A job's window and offset for counts at offset `off` of window `k` of `size` bytes whose GPU +/// address is known (`mapped`): all `COUNT_BYTES` in it, in one of the pass's windows. +fn window_job(k: usize, off: usize, size: usize, mapped: bool) -> Option<(u32, u32)> { + if !mapped || k >= BATCH_WINDOWS || off.checked_add(COUNT_BYTES)? > size { + return None; + } + Some((k as u32, u32::try_from(off).ok()?)) +} + +/// `window_job` for counts at UMA address `t` (in a window `counts_va` reads through). +fn job_of(t: usize) -> Option<(u32, u32)> { + let u = crate::gpu::uma::get()?; + let k = u.window_of(t)?; + let (base, size) = u.window(k); + let mapped = real::uma_window_buffer_gpu(t, COUNT_BYTES).is_some() && real::uma_window_va(k).is_some_and(|v| v != 0); + window_job(k, t.checked_sub(base)?, size, mapped) +} + +/// A list's open batch: its block of jobs and how many are in it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Batch { + block: u32, + count: u32, +} + +/// The block and the place in it of the next check of a list with `open` (None: a new batch). +fn joins(open: Option) -> Option<(u32, u32)> { + open.filter(|b| b.count < BATCH).map(|b| (b.block, b.count)) +} + +/// Lists with a batch open (the buffer of checked counts left INDIRECT_ARGUMENT), and how many. +static OPEN: super::sharded::Sharded = super::sharded::Sharded::new(); +static OPEN_LISTS: AtomicUsize = AtomicUsize::new(0); + +/// Whether `list` has a batch open. +pub(super) fn batch_open(list: *mut c_void) -> bool { + OPEN_LISTS.load(Ordering::Relaxed) != 0 && OPEN.contains(list as usize) +} + +/// The batch of `list` ends: the buffer of checked counts back to COMMON on it. +pub(super) unsafe fn end_batch(list: *mut c_void) { + if OPEN_LISTS.load(Ordering::Relaxed) == 0 || OPEN.remove(list as usize).is_none() { + return; + } + OPEN_LISTS.fetch_sub(1, Ordering::Relaxed); + let g = GUARD.lock().unwrap().clone(); + if let Some(g) = g { + super::list_x::transition(list, g.out.as_raw() as usize, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } +} + +/// Whether an ExecuteIndirect of signature kind `kind` (None: not a plain one) leaves a batch +/// open: a plain draw, whose writes reach later counts only through a barrier. Dispatches and +/// other signatures (mesh, root changes, several arguments) may write counts of a later draw. +fn keeps_batch(kind: Option) -> bool { + matches!(kind, Some(Counts::Draw | Counts::DrawIndexed)) +} + +/// In front of every ExecuteIndirect of `list` with signature `sig`, before any path it takes +/// (`bind::execute_indirect_snapshot`): one that is not a plain draw ends the list's batch. +pub(super) unsafe fn before_execute_indirect(list: *mut c_void, sig: usize) { + if !batch_open(list) { + return; + } + let kind = PLAIN.lock().unwrap().as_ref().and_then(|m| m.get(&sig).copied()); + if !keeps_batch(kind) { + end_batch(list); + } +} + +/// Blocks of jobs: free, written by a list's recording, held until a PC allocator is reset. +struct Blocks { + free: Vec, + by_list: HashMap>, + by_allocator: HashMap>, +} + +impl Blocks { + fn new(n: u32) -> Self { + Blocks { free: (0..n).rev().collect(), by_list: HashMap::new(), by_allocator: HashMap::new() } + } + + /// A free block for the recording of `list` (None: all are held). + fn take(&mut self, list: usize) -> Option { + let b = self.free.pop()?; + self.by_list.entry(list).or_default().push(b); + Some(b) + } + + /// The recording of `list` on `allocator` (0: none) ended: its blocks wait for that reset. + fn retire(&mut self, list: usize, allocator: usize) { + let Some(blocks) = self.by_list.remove(&list) else { return }; + if allocator == 0 { + self.free.extend(blocks); + } else { + self.by_allocator.entry(allocator).or_default().extend(blocks); + } + } + + /// The GPU is done with what recordings on `allocator` wrote: their blocks are free. + fn reset(&mut self, allocator: usize) { + if let Some(blocks) = self.by_allocator.remove(&allocator) { + self.free.extend(blocks); + } + } +} + +static BLOCKS_HELD: Mutex> = Mutex::new(None); + +fn with_blocks(f: impl FnOnce(&mut Blocks) -> R) -> R { + f(BLOCKS_HELD.lock().unwrap().get_or_insert_with(|| Blocks::new(BLOCKS))) +} + +/// The recording of `list` on the PC allocator `allocator` ends (Reset, a list split, the list +/// is gone): its open batch is dropped (nothing is recorded) and its blocks of jobs are kept +/// until `allocator` is reset. +pub(super) fn retire_batches(list: *mut c_void, allocator: usize) { + if OPEN_LISTS.load(Ordering::Relaxed) != 0 && OPEN.remove(list as usize).is_some() { + OPEN_LISTS.fetch_sub(1, Ordering::Relaxed); + } + if batch_on() { + with_blocks(|b| b.retire(list as usize, allocator)); + } +} + +/// The PC allocator `allocator` was reset (`console_list::allocator_reset`): the blocks of jobs of +/// its recordings are free again. +pub(super) fn allocator_reset(allocator: usize) { + if batch_on() { + with_blocks(|b| b.reset(allocator)); + } +} + /// The groups in all a dispatch whose counts XCL has to check, fold or clamp may have /// (`XCL_INDIRECT_MAX_GROUPS`, 2^22 unless set). pub(super) fn max_groups() -> u32 { @@ -164,6 +334,88 @@ void main() {{ ) } +/// `program` for the draws of a block of jobs (`BatchPass`): a thread a job, the counts read +/// through the job's memory window. +fn batch_program() -> String { + let rs_windows: String = (0..BATCH_WINDOWS).map(|k| format!(", UAV(u{})", k + 2)).collect(); + let windows: String = (0..BATCH_WINDOWS).map(|k| format!("RWByteAddressBuffer w{k} : register(u{});\n", k + 2)).collect(); + let cases: String = (0..BATCH_WINDOWS).map(|k| format!(" case {k}: return w{k}.Load(at);\n")).collect(); + format!( + r#" +#define RS "RootConstants(num32BitConstants=1, b0), SRV(t0), UAV(u0), UAV(u1){rs_windows}" +cbuffer C : register(b0) {{ uint block; }}; +// the jobs, written by the CPU while the list was recorded +ByteAddressBuffer jobs : register(t0); +RWByteAddressBuffer outp : register(u0); +RWByteAddressBuffer seen : register(u1); +{windows} +uint word(uint w, uint at) {{ + switch (w) {{ +{cases} default: return 0u; + }} +}} +[RootSignature(RS)] +[numthreads({BATCH}, 1, 1)] +void main(uint i : SV_GroupIndex) {{ + uint first = block * {BLOCK_BYTES}u; + if (i >= jobs.Load(first)) + return; + uint j = first + 16u + i * {JOB}u; + // window, offset, slot, kind; the program's id and the title's address, for the log + uint4 h = jobs.Load4(j); + uint4 t = jobs.Load4(j + 16u); + uint slot = h.z; + uint kind = h.w; + uint4 a = uint4(word(h.x, h.y), word(h.x, h.y + 4u), word(h.x, h.y + 8u), word(h.x, h.y + 12u)); + uint a4 = 0u; + [branch] if (kind == 2u) {{ a4 = word(h.x, h.y + 16u); }} + // (as `program` for a draw) + bool ok = a.x == 0u || a.y == 0u || (a.x <= {MAX_VERTICES}u && a.y <= {MAX_INSTANCES}u && (float)a.x * (float)a.y <= (float){MAX_VERTICES}u); + uint at = slot * {SLOT}u; + outp.Store4(at, ok ? a : uint4(0u, 0u, 0u, 0u)); + outp.Store(at + 16u, ok ? a4 : 0u); + seen.Store4({SEEN_AT}u + at, a); + seen.Store2({SEEN_AT}u + at + 16u, uint2(a4, 1u)); + if (!ok) {{ + uint m; + seen.InterlockedAdd(0u, 1u, m); + uint n; + seen.InterlockedAdd(8u, 1u, n); + if (n < {BAD_KEPT}u) {{ + uint r = {BAD_AT}u + n * {BAD_SIZE}u; + seen.Store4(r, a); + seen.Store4(r + 16u, t); + seen.Store4(r + 32u, a); + seen.Store4(r + 48u, uint4(kind, 2u, slot, 1u)); + }} + }} +}} +"# + ) +} + +/// The pass of a batch of checks (`XCL_INDIRECT_GUARD_BATCH=1`) and its blocks of jobs +struct BatchPass { + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// `BLOCKS` blocks the CPU writes (mapped at `jobs_at`) and the pass reads + _jobs: ID3D12Resource, + jobs_va: u64, + jobs_at: usize, +} + +unsafe fn make_batch(dev: &ID3D12Device, jobs: ID3D12Resource) -> Result { + let dxil = crate::gpu::recomp::dxc::compile(&batch_program(), "main", "cs_6_0", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("its root signature: {e}"))?; + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }; + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) + .map_err(|e| format!("its pipeline: {e}"))?; + let mut p = std::ptr::null_mut(); + jobs.Map(0, None, Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + Ok(BatchPass { jobs_va: jobs.GetGPUVirtualAddress(), jobs_at: p as usize, rs, pso, _jobs: jobs }) +} + struct Guard { dev: usize, rs: ID3D12RootSignature, @@ -176,6 +428,8 @@ struct Guard { seen_va: u64, seen_at: usize, next: AtomicU32, + /// with `batch_on` (None: its pass could not be made, the checks go alone) + batch: Option, } // SAFETY: the mapping lives as long as `_seen`; D3D12 objects are free-threaded. @@ -263,7 +517,20 @@ unsafe fn make(dev: &ID3D12Device) -> Result { let mut p = std::ptr::null_mut(); seen.Map(0, None, Some(&mut p)).map_err(|e| format!("Map: {e}"))?; std::ptr::write_bytes(p.cast::(), 0, bytes as usize); + let batch = if batch_on() { + let cpu = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + match buffer(cpu, BLOCKS as u64 * BLOCK_BYTES as u64).and_then(|jobs| make_batch(dev, jobs)) { + Ok(b) => Some(b), + Err(e) => { + crate::xlog_warn!("D3D12.X: ExecuteIndirect: the counts are checked one call at a time, not in batches ({e})"); + None + } + } + } else { + None + }; Ok(Guard { + batch, dev: dev.as_raw() as usize, out_va: out.GetGPUVirtualAddress(), seen_va: seen.GetGPUVirtualAddress(), @@ -297,6 +564,64 @@ fn counts_va_in(t: usize, in_one_window: impl Fn(usize, usize) -> bool, va_of: i pub(super) struct Checked { guard: Arc, pub(super) slot: u32, + /// checked in a batch: the buffer is INDIRECT_ARGUMENT already (until `end_batch`) + batched: bool, +} + +/// The check of a draw's counts at `job` (window, offset) in the batch of `list`, whose pass +/// goes in front of the batch's first draw: the check's slot. None: no batch pass. +unsafe fn batched(list: *mut c_void, l: &ID3D12GraphicsCommandList, g: &Guard, kind: Counts, job: (u32, u32), id: u64, at: u64) -> Option { + let b = g.batch.as_ref()?; + let (block, n) = match joins(OPEN.get(list as usize)) { + Some(j) => j, + None => { + // (a full batch ends first) + end_batch(list); + // (none free: the check goes alone) + let block = with_blocks(|h| h.take(list as usize))?; + jobs_in(b, block).store(0, Ordering::Release); + // the counts were written as UAVs: they are read after those writes + let written = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, + }; + l.ResourceBarrier(&[written]); + l.SetComputeRootSignature(&b.rs); + // (past the hook of a title's call: what the title bound stays the list's pipeline) + super::list_x::set_compute_pipeline(list, b.pso.as_raw()); + l.SetComputeRoot32BitConstant(0, block, 0); + l.SetComputeRootShaderResourceView(1, b.jobs_va); + l.SetComputeRootUnorderedAccessView(2, g.out_va); + l.SetComputeRootUnorderedAccessView(3, g.seen_va); + for k in 0..BATCH_WINDOWS { + // (a window there is not: never read, any buffer) + l.SetComputeRootUnorderedAccessView(4 + k as u32, real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(g.seen_va)); + } + l.Dispatch(1, 1, 1); + // (the driver reads the counts after the pass's writes with this transition only, + // `bind::fresh_indirect_arguments`) + super::list_x::transition(list, g.out.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + if OPEN.insert(list as usize, Batch { block, count: 0 }).is_none() { + OPEN_LISTS.fetch_add(1, Ordering::Relaxed); + } + (block, 0) + } + }; + let slot = g.next.fetch_add(1, Ordering::Relaxed) % SLOTS; + g.word(SEEN_AT + slot * SLOT + 4 * SEEN_WORD).store(0, Ordering::Release); + let words = [job.0, job.1, slot, kind as u32, id as u32, (id >> 32) as u32, at as u32, (at >> 32) as u32]; + let rec = (b.jobs_at + (block * BLOCK_BYTES + 16 + n * JOB) as usize) as *mut u32; + std::ptr::copy_nonoverlapping(words.as_ptr(), rec, words.len()); + // (the list is submitted after this: the pass reads the jobs then) + jobs_in(b, block).store(n + 1, Ordering::Release); + OPEN.insert(list as usize, Batch { block, count: n + 1 }); + Some(slot) +} + +/// The count of jobs in block `block` of `b`. +unsafe fn jobs_in(b: &BatchPass, block: u32) -> &AtomicU32 { + &*((b.jobs_at + (block * BLOCK_BYTES) as usize) as *const AtomicU32) } /// Record the check of an ExecuteIndirect's counts (`args` + `args_off`, the PC buffer and the @@ -333,9 +658,20 @@ pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, let va = title.and_then(counts_va).filter(|v| v % 4 == 0).unwrap_or(shown); let shown = if compare() { shown } else { va }; let g = guard_of(l)?; + let id = real::pso_shaders(pso).map_or(0, |(a, _)| a); + // (the title's address, for the log; a buffer that is not in unified memory: the GPU's) + let at = title.map_or(va, |t| t as u64); + let job = if batchable(batch_on(), kind, compare()) { title.and_then(job_of) } else { None }; + if let Some(job) = job { + if let Some(slot) = batched(list, l, &g, kind, job, id, at) { + report(&g); + return Some(Checked { guard: g, slot, batched: true }); + } + } + // (alone: a batch the list has open ends first) + end_batch(list); let slot = g.next.fetch_add(1, Ordering::Relaxed) % SLOTS; g.word(SEEN_AT + slot * SLOT + 4 * SEEN_WORD).store(0, Ordering::Release); - let id = real::pso_shaders(pso).map_or(0, |(a, _)| a); // the counts were written as UAVs: they are read after those writes let written = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -346,8 +682,6 @@ pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, l.SetComputeRootSignature(&g.rs); // (past the hook of a title's call: what the title bound stays the list's pipeline) super::list_x::set_compute_pipeline(list, g.pso.as_raw()); - // (the title's address, for the log; a buffer that is not in unified memory: the GPU's) - let at = title.map_or(va, |t| t as u64); let constants = [max_groups(), slot, id as u32, (id >> 32) as u32, at as u32, (at >> 32) as u32, kind as u32]; l.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr() as *const c_void, 0); l.SetComputeRootUnorderedAccessView(1, va); @@ -356,13 +690,16 @@ pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, l.SetComputeRootUnorderedAccessView(4, shown); l.Dispatch(1, 1, 1); report(&g); - Some(Checked { guard: g, slot }) + Some(Checked { guard: g, slot, batched: false }) } impl Checked { /// `op(buffer, offset)`: the ExecuteIndirect with the checked counts. pub(super) unsafe fn run(&self, list: *mut c_void, op: impl FnOnce(usize, u64)) { let out = self.guard.out.as_raw() as usize; + if self.batched { + return op(out, self.slot as u64 * SLOT as u64); + } // (the driver reads the counts after the program's writes with this transition only, // `bind::fresh_indirect_arguments`) super::list_x::transition(list, out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); @@ -536,6 +873,155 @@ mod tests { assert!(!logged_again(7, 7) && !logged_again(8, 15) && !logged_again(100, 127)); } + /// Draws go in batches when asked for; dispatches (clamped after the check) and the compare + /// diagnostic go alone. + #[test] + fn only_draws_are_checked_in_batches() { + assert!(batchable(true, Counts::Draw, false) && batchable(true, Counts::DrawIndexed, false)); + assert!(!batchable(false, Counts::Draw, false), "off"); + assert!(!batchable(true, Counts::Dispatch, false), "a dispatch"); + assert!(!batchable(true, Counts::DrawIndexed, true), "XCL_INDIRECT_GUARD=compare"); + } + + /// A job is counts all in one of the pass's windows, at an offset the pass can address. + #[test] + fn a_job_is_counts_in_one_of_the_pass_windows() { + let gib4 = 1usize << 32; + assert_eq!(window_job(0, 0x100, gib4, true), Some((0, 0x100))); + assert_eq!(window_job(BATCH_WINDOWS - 1, gib4 - COUNT_BYTES, gib4, true), Some((BATCH_WINDOWS as u32 - 1, (gib4 - COUNT_BYTES) as u32)), "the last record in a window"); + assert_eq!(window_job(1, gib4 - 8, gib4, true), None, "across the window's end"); + assert_eq!(window_job(BATCH_WINDOWS, 0x100, gib4, true), None, "a window the pass does not bind"); + assert_eq!(window_job(0, 0x100, gib4, false), None, "a window with no GPU address"); + assert_eq!(window_job(0, usize::MAX - 4, usize::MAX, true), None, "an offset that does not add up"); + } + + /// A list's next check joins its open batch until `BATCH` are in it; then, and with none + /// open, a new batch (its pass) starts. + #[test] + fn checks_join_the_open_batch_until_it_is_full() { + assert_eq!(joins(None), None); + assert_eq!(joins(Some(Batch { block: 7, count: 0 })), Some((7, 0))); + assert_eq!(joins(Some(Batch { block: 7, count: BATCH - 1 })), Some((7, BATCH - 1))); + assert_eq!(joins(Some(Batch { block: 7, count: BATCH })), None, "full"); + } + + /// Only an ExecuteIndirect of a plain draw leaves a batch open: dispatches and other + /// signatures (mesh, root changes, several arguments) may write a later draw's counts. + #[test] + fn only_a_plain_draw_leaves_a_batch_open() { + assert!(keeps_batch(Some(Counts::Draw)) && keeps_batch(Some(Counts::DrawIndexed))); + assert!(!keeps_batch(Some(Counts::Dispatch)), "a dispatch"); + assert!(!keeps_batch(None), "a signature that is not a plain one"); + } + + /// A recording's blocks of jobs stay its own until its allocator is reset, however often the + /// list is submitted again; with none free a check goes alone. + #[test] + fn a_recording_keeps_its_blocks_until_its_allocator_is_reset() { + let mut b = Blocks::new(3); + let (one, two) = (b.take(0x10), b.take(0x10)); + assert_eq!((one, two), (Some(0), Some(1))); + assert_eq!(b.take(0x20), Some(2)); + assert_eq!(b.take(0x30), None, "all held"); + // (the recordings end; the GPU may still read them) + b.retire(0x10, 0xA0); + b.retire(0x20, 0xB0); + assert_eq!(b.take(0x30), None, "held until the allocators are reset"); + b.reset(0xB0); + assert_eq!(b.take(0x30), Some(2)); + b.reset(0xA0); + let mut got = [b.take(0x40), b.take(0x40)]; + got.sort(); + assert_eq!(got, [Some(0), Some(1)]); + // a recording on no allocator gives its blocks back at once; nothing held: nothing to do + b.retire(0x40, 0); + assert!(b.take(0x50).is_some()); + b.retire(0x60, 0xC0); + b.reset(0xD0); + } + + /// The batch pass checks each job of its block through the job's window: counts in range go + /// to the job's slot as they are, garbage as zeros (and is counted), and the GPU marks each + /// slot read. Jobs past the block's count are not run. + #[test] + fn the_batch_pass_checks_each_job_through_its_window() { + unsafe { + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(dev) = device() else { return }; + let (jobs, _) = cpu_buffer(&dev, 2 * BLOCK_BYTES as u64); + let b = match make_batch(&dev, jobs) { + Ok(b) => b, + Err(e) => { + skip_test("no DXC"); + eprintln!("the batch pass: {e}"); + return; + } + }; + let ((w0, w0_at), (w1, w1_at)) = (cpu_buffer(&dev, 256), cpu_buffer(&dev, 256)); + let ((out, out_at), (seen, seen_at)) = (cpu_buffer(&dev, 8 * SLOT as u64), cpu_buffer(&dev, (SEEN_AT + 8 * SLOT) as u64)); + for i in 0..(8 * SLOT / 4) as usize { + *out_at.add(i) = 0xAAAA_AAAA; + } + // window, offset, counts there, slot, kind + let jobs: [(u32, u32, [u32; 5], u32, Counts); 4] = [ + (0, 0, [3, 2, 7, 9, 0], 2, Counts::Draw), + (1, 16, [36, 100, 5, 0xFFFF_FFF0, 3], 5, Counts::DrawIndexed), + (0, 32, [0x3F80_0000, 1, 0, 0, 0], 6, Counts::Draw), + // (past the count: not run) + (0, 64, [1, 1, 0, 0, 0], 7, Counts::Draw), + ]; + let block = 1u32; + let first = (b.jobs_at + (block * BLOCK_BYTES) as usize) as *mut u32; + for (n, (w, off, words, slot, kind)) in jobs.iter().enumerate() { + let at = if *w == 0 { w0_at } else { w1_at }; + for (i, v) in words.iter().enumerate() { + *at.add(*off as usize / 4 + i) = *v; + } + let rec = [*w, *off, *slot, *kind as u32, 0, 0, 0, 0]; + std::ptr::copy_nonoverlapping(rec.as_ptr(), first.add((16 + n * JOB as usize) / 4), rec.len()); + } + *first = 3; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + list.SetComputeRootSignature(&b.rs); + list.SetPipelineState(&b.pso); + list.SetComputeRoot32BitConstant(0, block, 0); + list.SetComputeRootShaderResourceView(1, b.jobs_va); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, seen.GetGPUVirtualAddress()); + for k in 0..BATCH_WINDOWS as u32 { + list.SetComputeRootUnorderedAccessView(4 + k, if k == 1 { w1.GetGPUVirtualAddress() } else { w0.GetGPUVirtualAddress() }); + } + list.Dispatch(1, 1, 1); + list.Close().unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + let words = |at: *mut u32, from: u32, n: usize| -> Vec { (0..n).map(|i| std::ptr::read_volatile(at.add(from as usize / 4 + i))).collect() }; + assert_eq!(words(out_at, 2 * SLOT, 5), [3, 2, 7, 9, 0], "a draw in range"); + assert_eq!(words(out_at, 5 * SLOT, 5), [36, 100, 5, 0xFFFF_FFF0, 3], "an indexed draw in range, through window 1"); + assert_eq!(words(out_at, 6 * SLOT, 5), [0; 5], "garbage"); + assert_eq!(words(out_at, 7 * SLOT, 5), [0xAAAA_AAAA; 5], "a job past the count"); + assert_eq!(words(seen_at, SEEN_AT + 2 * SLOT, 6), [3, 2, 7, 9, 0, 1], "what the CPU sees, marked read"); + assert_eq!(words(seen_at, SEEN_AT + 6 * SLOT, 6), [0x3F80_0000, 1, 0, 0, 0, 1]); + assert_eq!(words(seen_at, 0, 1), [1], "one out of range"); + } + } + + /// The batch pass's program has a window buffer and a root UAV for each window it reads. + #[test] + fn the_batch_program_binds_each_window() { + let p = batch_program(); + for k in 0..BATCH_WINDOWS { + assert!(p.contains(&format!("RWByteAddressBuffer w{k} : register(u{});", k + 2)), "window {k}"); + assert!(p.contains(&format!("case {k}: return w{k}.Load(at);")), "window {k}"); + } + assert_eq!(p.matches("UAV(u").count(), 2 + BATCH_WINDOWS); + } + /// Garbage counts run 0 groups and are kept for the log; counts in range run as they are. Each /// case takes the slot the one before it ran from, so that a guard that writes nothing would /// run that one's counts. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9dad2dd11..0a7121f63d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1466,8 +1466,9 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { } } // XCL_TWO_PASS_BATCH=2: a title call on a list with deferred two-pass draws records them - // first, unless it is one that cannot change what they draw (`bind::before_list_call`) - if kind == Kind::CommandList && super::bind::two_pass_defer() { + // first, unless it is one that cannot change what they draw (`bind::before_list_call`); + // XCL_INDIRECT_GUARD_BATCH=1: one that can write memory ends the list's batch of checks + if kind == Kind::CommandList && (super::bind::two_pass_defer() || super::indirect_guard::batch_on()) { for (i, e) in v.iter_mut().enumerate().skip(1) { *e = super::guard::make_before(*e, (i - 1) as u64, super::bind::before_list_call); }