From 0754f84edbfa58a988601c12f2565b6c9dde0b33 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:01:54 -0500 Subject: [PATCH 1/9] D3D12.X: count the submit's list and after-the-driver stages again The submit-cost report has a lists stage (the title's lists mapped to their PC lists and noted for the queue) and an after stage (XCL's work after each chunk's driver call). nvidia-dev's submit path fed both. The merge took main's submission plan for that path and lost the two calls, so both stages read 0, and the after time showed up in the report's 'splits' (exec minus driver, after and previous submits). The call stage also took in the list mapping, where nvidia-dev counted only the refresh. call is the refresh (prepare_title_submission) again. lists is the mapping before it, without the put-off dispatches' waits for their builds, plus the queue notes after it. after is measured per chunk from the driver call's return to the chunk's note_submitted. Diagnostics only. cargo check --workspace --all-targets passes. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2f52d2df75bcd56ad23f7839db71f40132399652) --- crates/xcl/src/hle/d3d12x/real.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1c1c731864..b67449d315 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11529,13 +11529,17 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); + // (the put-off dispatches' waits for their builds are not the submit's cost: the put-off line) + let mut deferred = std::time::Duration::ZERO; for &l in title_lists { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); } else { // Deferred recording can wait for a pipeline. Keep that time solely in PipelineWait. drop(preparation_stall); + let t = std::time::Instant::now(); super::list_x::record_deferred(l); + deferred += t.elapsed(); preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); if !super::title_list::push_segments(l, &mut mapped) { mapped.push(l); @@ -11547,11 +11551,15 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } // textures in title memory the CPU wrote since: uploaded again first + let t_refresh = std::time::Instant::now(); prepare_title_submission(this, title_lists); + let t_lists = std::time::Instant::now(); + super::submit_cost::call(t_lists - t_refresh); super::list_x::note_queue_for_lists(this as usize, &mapped); super::gpu_profile::note_queue(this); let t_exec = std::time::Instant::now(); - super::submit_cost::call(t_exec - submit_t0); + // the lists made ready: mapped to their PC lists before the refresh, noted for the queue after it + super::submit_cost::lists((t_refresh - submit_t0).saturating_sub(deferred) + (t_exec - t_lists)); let plan = super::list_x::submission_plan(&mapped); drop(preparation_stall); let mut chunks = 0usize; @@ -11592,12 +11600,14 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis ) { return (false, None); } + let t_after = std::time::Instant::now(); super::gpu_times::executed(this, lists); chunks += 1; submitted.extend_from_slice(lists); super::list_x::copy_scratch_submitted(this, lists); let effects = chunk.submit_effects(this); super::list_x::note_submitted(this); + super::submit_cost::after(t_after.elapsed()); (true, effects) }) }); From c3a6561b1018b70bc6e4ad461c0138b4f4fb69df Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:52:06 -0500 Subject: [PATCH 2/9] D3D12.X: lazy levels that give their pages back leave the resident texel count `vram::unmap_levels` (nvidia-dev's zero lazy levels) took a level group's pages away but left main's `TEXEL_STATS` resident count and the texture's `resident_texels` where `map_levels` had put them, so `XCL_ACTIVITY`'s resident texels only ever grew while a streaming title let levels go. The bookkeeping of both directions is now two `TexelMeta` methods; `unmap_levels` takes the lost groups' texels off, as `map_levels` added them. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0bc1e46dba6c3e75487f894c0ee34b82cc0c1c0d) --- crates/xcl/src/hle/d3d12x/vram.rs | 54 +++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 7cf0d35835..0bbe15f623 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1105,6 +1105,22 @@ impl TexelMeta { } } + /// Levels `levels` got pages (`map_levels`): the texels it adds to the resident ones. + fn levels_got_pages(&mut self, levels: std::ops::Range) -> u64 { + let added = range_texels(self.width, self.height, self.depth, self.dim, levels); + let delta = self.total_texels.saturating_sub(self.resident_texels).min(added); + self.resident_texels += delta; + delta + } + + /// Levels `levels` gave their pages back (`unmap_levels`): the texels it takes from the + /// resident ones. + fn levels_lost_pages(&mut self, levels: std::ops::Range) -> u64 { + let removed = range_texels(self.width, self.height, self.depth, self.dim, levels).min(self.resident_texels); + self.resident_texels -= removed; + removed + } + fn record_srv(&mut self, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> (bool, u64) { let first_srv = self.srv_sampled_texels == 0; let mips = srv_mip_range(self.mips as u32, desc); @@ -2740,10 +2756,8 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> l.group_tiles[k].1.extend(used_extra); } if let Some(tm) = t.texels.as_mut() { - let added = range_texels(tm.width, tm.height, tm.depth, tm.dim, levels.clone()); - let delta = tm.total_texels.saturating_sub(tm.resident_texels).min(added); + let delta = tm.levels_got_pages(levels.clone()); if delta > 0 { - tm.resident_texels += delta; TEXEL_STATS[3].fetch_add(delta, std::sync::atomic::Ordering::Relaxed); } } @@ -2774,6 +2788,7 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { let Some(t) = pages.targets.get_mut(&key) else { continue }; let Some(lv) = t.levels.as_mut().filter(|_| t.mapped) else { return 0 }; let mut ranges = Vec::new(); + let mut lost_levels = Vec::new(); let (mut gone, mut gone_extra) = (Vec::new(), Vec::new()); for k in 0..lv.groups.len() { if !lv.groups[k].3 || !lv.levels_of(k).all(|l| zero.contains(&l)) { @@ -2782,6 +2797,7 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { let (sub, _, n, _) = lv.groups[k]; lv.groups[k].3 = false; ranges.push((sub, n)); + lost_levels.push(lv.levels_of(k)); // (the pages the group owns) let (used, used_extra) = std::mem::take(&mut lv.group_tiles[k]); gone.extend(used); @@ -2790,6 +2806,12 @@ pub(super) unsafe fn unmap_levels(res: &ID3D12Resource, zero: &[u32]) -> u64 { if ranges.is_empty() { return 0; } + if let Some(tm) = t.texels.as_mut() { + let removed: u64 = lost_levels.into_iter().map(|levels| tm.levels_lost_pages(levels)).sum(); + if removed > 0 { + TEXEL_STATS[3].fetch_sub(removed, std::sync::atomic::Ordering::Relaxed); + } + } let freed: u64 = ranges.iter().map(|&(_, n)| n as u64).sum(); for (sub, n) in ranges { pages.unmap_range(res, sub, n); @@ -4975,6 +4997,32 @@ mod tests { assert_eq!(tm.srv_sampled_texels, tm.total_texels); } + /// Lazy levels that give their pages back (`unmap_levels`) take their texels from the resident + /// ones, as getting them (`map_levels`) added them: the count comes back to where it was. + #[test] + fn texel_meta_resident_texels_follow_levels_losing_their_pages() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 4, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + assert_eq!(tm.levels_got_pages(1..4), 16 + 4 + 1); + assert_eq!(tm.levels_got_pages(0..1), 64); + assert_eq!(tm.resident_texels, tm.total_texels); + // mip 0 gives its pages back, and gets them again + assert_eq!(tm.levels_lost_pages(0..1), 64); + assert_eq!(tm.resident_texels, 16 + 4 + 1); + assert_eq!(tm.levels_got_pages(0..1), 64); + // all of it, then once more: nothing below zero + assert_eq!(tm.levels_lost_pages(0..4), tm.total_texels); + assert_eq!(tm.levels_lost_pages(0..4), 0); + assert_eq!(tm.resident_texels, 0); + } + #[test] fn texel_meta_unions_array_slices_without_counting_the_whole_mip() { let desc = D3D12_RESOURCE_DESC { From 660d0cc2f123bdff3e214ac9351997fd134f8cd0 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:53:06 -0500 Subject: [PATCH 3/9] D3D12.X: a retired queue's descriptor-release fence leaves HEAP_FENCES `console_heap`'s HEAP_FENCES keeps one fence per title queue address, signalled on that queue to prove released descriptor ranges idle. `present::invalidate_queue_caches` forgets a retired queue in every other address-keyed cache but not here, so the map kept a fence for every queue address the title ever used. It is not a correctness bug: the fence is XCL's own and its values only grow, so a later queue at the same address carries on with it safely. The entry now goes with the queue; retired ranges wait on clones of the fence, which stay valid. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 009c2042e06ef8f590978a700863523f831b681e) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 41 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 1 + 2 files changed, 42 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..bbf698ad72 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -210,6 +210,19 @@ struct QueueFences(HashMap); unsafe impl Send for QueueFences {} static HEAP_FENCES: Mutex> = Mutex::new(None); + +/// A retired queue (`present::invalidate_queue_caches`): its signal fence goes, rather than stay +/// in `HEAP_FENCES` for every queue address the title ever used. (Retired ranges keep clones of +/// the fences they wait for.) +pub(super) fn forget_queue(id: super::present::QueueId) { + forget_queue_fence(id.raw()); +} + +fn forget_queue_fence(queue: usize) { + let gone = HEAP_FENCES.lock().unwrap().as_mut().and_then(|fences| fences.0.remove(&queue)); + // (dropped outside the lock) + drop(gone); +} static GLOBAL_RETIRED: AtomicBool = AtomicBool::new(false); /// Serialises `drain_global_retired` across `fill_nulls` and `merge_release` so a concurrent /// `slot()` cannot miss ranges popped from `GLOBAL.retired` before they reach `GLOBAL.free`. @@ -1957,6 +1970,34 @@ mod tests { assert!(made.is_ok(), "a shader-visible sampler heap of {}: {made:?}", d.NumDescriptors); } + /// A retired queue's signal fence leaves `HEAP_FENCES`; another queue's stays. + #[test] + fn a_retired_queue_leaves_the_heap_fences() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let dev = unsafe { + let mut dev: Option = None; + match CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) { + Ok(warp) if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() => dev.unwrap(), + _ => return crate::gpu::recomp::runner::skip_test("no WARP device"), + } + }; + let (gone, kept) = (0x7E57_0000_C0A0usize, 0x7E57_0000_C0B0usize); + for key in [gone, kept] { + let fence: ID3D12Fence = unsafe { dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.unwrap(); + HEAP_FENCES.lock().unwrap().get_or_insert_with(|| QueueFences(HashMap::new())).0.insert(key, (fence, 3)); + } + let fence = HEAP_FENCES.lock().unwrap().as_ref().unwrap().0[&gone].0.clone(); + forget_queue_fence(gone); + let g = HEAP_FENCES.lock().unwrap(); + let fences = &g.as_ref().unwrap().0; + assert!(!fences.contains_key(&gone), "the retired queue's fence is gone"); + assert_eq!(fences.get(&kept).map(|f| f.1), Some(3), "the other queue's stays"); + drop(g); + assert_eq!(unsafe { fence.GetCompletedValue() }, 0, "a mark's clone of the fence still works"); + HEAP_FENCES.lock().unwrap().as_mut().unwrap().0.remove(&kept); + } + /// Every descriptor of a range that is not handed out gets a null view, an SRV at even and a /// UAV at odd indices (a range starting at an odd one too), a block at a time. #[test] diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d0941c4ea6..fdd12aea5a 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -596,6 +596,7 @@ pub(super) fn invalidate_queue_caches(id: QueueId) { super::sparse::forget_queue(id); super::title_textures::forget_queue(id); super::vram::forget_queue(id); + super::console_heap::forget_queue(id); } fn retirement_worker() -> Option<&'static mpsc::Sender<()>> { From 07b94f10db0e7672b4d67c40ac05d0a21a6b3665 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:59:21 -0500 Subject: [PATCH 4/9] D3D12.X: drop the batch hash-plan cap the staging ring already bounds MAX_BATCH_HASH_UPDATES, batch_hash_plan_would_overflow and the PreparedDirtyBatch methods hash_plan_would_overflow / append_hashes are main's (5b711248 sparse.rs:2082), whose upload loop checked the cap before each staged copy (sparse.rs:3338). The merged upload path never calls them. It plans hashes in submit_upload, one per whole 64-byte chunk of a staged copy, and its ring_room already bounds the batch. The ring bounds those updates. Every staged copy goes through ring_room first, which allows a copy ending at ring position `end` only while end - ring_free <= STAGING (after reclaiming, and after submitting the open batch if needed). ring_free only moves to the end position of a submitted batch whose fence has completed, so it is never past the open batch's ring_start. The copies of one batch therefore sit inside [ring_start, end) and span at most STAGING bytes. That makes at most STAGING / CHUNK hash updates per batch, which is exactly the old MAX_BATCH_HASH_UPDATES (16 MB of HashUpdate). A runtime check would never trip. append_hash_updates stays as a test helper (#[cfg(test)]) for the hash plan tests, without its debug_assert on the removed constant. batch_hash_plan_is_bounded_by_staging tested only the removed cap and goes. prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point keeps its slot, ring_start, exact-update and allocation-reuse checks. title_textures::refresh: tests only. The KickoffX path (nvidia-dev's list_x) and main's real.rs call both became prepare_title_submission -> refresh_for in the merge, so no runtime caller is missing. Its tests still use it, so it is #[cfg(test)] rather than deleted. cargo check --workspace --all-targets passes; cargo test -p xcl --lib on the three hash-plan tests: 3 passed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 38aad0a537b2872ea9a21232eb37429a041d8e6f) --- crates/xcl/src/hle/d3d12x/sparse.rs | 30 +++------------------ crates/xcl/src/hle/d3d12x/title_textures.rs | 3 ++- 2 files changed, 5 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..a99cc163ed 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2829,8 +2829,6 @@ struct HashUpdate { hash: u64, } -const MAX_BATCH_HASH_UPDATES: usize = STAGING / CHUNK; - /// One synchronously-recorded dirty upload batch. The slot, ring rollback point, and unpublished /// hash plan move together so a failed submission cannot publish bytes that have no fence receipt. struct PreparedDirtyBatch { @@ -2851,23 +2849,11 @@ impl PreparedDirtyBatch { self } - fn hash_plan_would_overflow(&self, bytes: usize) -> bool { - batch_hash_plan_would_overflow(self.updates.len(), bytes) - } - - fn append_hashes(&mut self, at: usize, bytes: &[u8]) { - append_hash_updates(at, bytes, &mut self.updates); - } - fn clear_after_submit(&mut self) { self.updates.clear(); } } -fn batch_hash_plan_would_overflow(current: usize, bytes: usize) -> bool { - bytes / CHUNK > MAX_BATCH_HASH_UPDATES.saturating_sub(current) -} - /// Plan changed 64-byte chunk runs in a 4 KiB page without publishing their hashes. The hashes /// become `sent` only after the corresponding upload has a durable queue-fence receipt. /// This keeps the fresh-zero-page fast path allocation-free. @@ -2912,10 +2898,10 @@ fn scan_page( } } +#[cfg(test)] fn append_hash_updates(at: usize, bytes: &[u8], updates: &mut Vec) { debug_assert_eq!(at % CHUNK, 0); debug_assert_eq!(bytes.len() % CHUNK, 0); - debug_assert!(updates.len() + bytes.len() / CHUNK <= MAX_BATCH_HASH_UPDATES); updates.extend(bytes.chunks_exact(CHUNK).enumerate().map(|(i, chunk)| HashUpdate { at: at + i * CHUNK, hash: chunk_hash(chunk), @@ -10464,33 +10450,23 @@ mod tests { assert_eq!(runs, [(base, CHUNK)]); } - #[test] - fn batch_hash_plan_is_bounded_by_staging() { - assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); - assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::(), STAGING / 4); - assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); - assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); - } - #[test] fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); let bytes = [0xA5; 2 * CHUNK]; - batch.append_hashes(0x20_0000, &bytes); + append_hash_updates(0x20_0000, &bytes, &mut batch.updates); assert_eq!(batch.slot, 3); assert_eq!(batch.ring_start, 0x12_3400); assert_eq!(batch.updates.len(), 2); assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); - assert!(!batch.hash_plan_would_overflow(CHUNK)); let storage = batch.updates.as_ptr(); let capacity = batch.updates.capacity(); for index in 0..3 { batch.clear_after_submit(); batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); - batch.append_hashes(0x30_0000, &bytes); + append_hash_updates(0x30_0000, &bytes, &mut batch.updates); assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); assert_eq!(batch.updates.capacity(), capacity); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2fe0c9e12e..6f0d113534 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1235,7 +1235,8 @@ pub(super) fn is_own_work() -> bool { } /// Before the title's GPU work: textures whose memory the CPU wrote since the last look are -/// uploaded again. +/// uploaded again. Tests only: the runtime's submits call `refresh_for`. +#[cfg(test)] pub(super) unsafe fn refresh(queue: *mut c_void) -> super::sparse::PreparationOutcome { // the uploads' own ExecuteCommandLists come back here if BUSY.with(|b| b.get()) { From a091dcac0445d96945350f3615d8c932a1422b4c Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:59:51 -0500 Subject: [PATCH 5/9] D3D12.X: remove pipeline-submit helpers the merge left without a caller - pso_async::submit_eager: no caller left; submit() and real.rs call submit_eager_with, and nvidia-dev had no entry point behind it. - submit_lazy_keyed / submit_recipe_keyed: only pso_async and bind tests call them (real.rs uses the *_with forms), so they become #[cfg(test)]. cargo check --workspace --all-targets passes; pso_async:: and bind:: tests pass (pso_async:: + bind:: 305 passed, 0 failed). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8ae1c6271bccac5382cf8e2ab350b395ed627007) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index df9fabd0da..15cb067885 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -4343,17 +4343,8 @@ pub fn submit(standin: usize, compute: bool, job: Job) { submit_eager_with(standin, compute, job, 0, None, 0); } -pub(super) fn submit_eager( - standin: usize, - compute: bool, - job: Job, - key: u64, - compute_key: Option, -) { - submit_eager_with(standin, compute, job, key, compute_key, 0); -} - -/// `submit_eager`, with a compute pipeline's console program for the log (`record`; 0: not known). +/// `submit` with the shaders' key, a coalescing key and a compute pipeline's console program for +/// the log (`record`; 0: not known). pub(super) fn submit_eager_with( standin: usize, compute: bool, @@ -4383,6 +4374,7 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { submit_lazy_keyed_with(standin, compute, job, key, None, None, 0); } +#[cfg(test)] pub(super) fn submit_lazy_keyed( standin: usize, compute: bool, @@ -4408,6 +4400,7 @@ pub(super) fn submit_lazy_keyed_with( submit_as(standin, compute, job, None, false, key, compute_key, warm, record); } +#[cfg(test)] pub(super) fn submit_recipe_keyed( standin: usize, compute: bool, From 816c7bc7c1896d75c72c776b38bb77c46fd0e876 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:00:56 -0500 Subject: [PATCH 6/9] D3D12.X: keep main's allow on the two-pass compute key the merge dropped main declared two_pass_identity with #[allow(dead_code)], because its identities are consumed by the next stacked cache stage. The merge took nvidia-dev's plain module line, whose real.rs called two_pass_cs_key; main's real.rs does not, so the function warns. The allow goes back on that one function. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0a3b3e27779a8006986161ad7496d4bbee7c2efb) --- crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index acf8b51efb..489fc9243b 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -278,6 +278,7 @@ pub(super) unsafe fn graphics_stream_key(stream: &[u8], samplers: &[crate::gpu:: stream_key(stream, samplers, GRAPHICS_STREAM_CACHE_SCHEMA, 3, 0, mem_windows) } +#[allow(dead_code)] // consumed by main's next stacked cache stage pub(super) fn two_pass_cs_key(cs: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> u64 { let mut h = Fnv64::new(); h.u32(TWO_PASS_CACHE_SCHEMA); From a163641142f9ad3db71186443d171e2a297a4f37 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:01:32 -0500 Subject: [PATCH 7/9] Tests: a spare whose Reset fails stays with the list (reset_stand_in) The merge dropped nvidia-dev's a_spare_whose_reset_fails_stays_with_the_list_on_the_software_adapter, because main reserves a put-off dispatch's segment closed, without a Reset, so the case it set up no longer exists. A spare's Reset can still fail in reset_stand_in, though: it pops a spare to record a list reset while the list's last submit is on the GPU, and on a failed Reset it gives the spare back with put_spare. The test is restored for that path, on the software adapter (WARP). It is again the only user of title_list::spares_for_test, which warned unused in the test build. Checked: it fails when the put_spare on that path is removed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bb40cb5ff94fac73c2a3a1ad658a4e8dba30d96c) --- crates/xcl/src/hle/d3d12x/list_x.rs | 41 +++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0210c522f1..011640449c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -11236,6 +11236,47 @@ mod tests { } } + /// A spare whose Reset fails does not stand in for a list reset while its last submit is on + /// the GPU (`reset_stand_in`), and stays among the list's spares (released with the list) + /// instead of being dropped. (A put-off dispatch's segment is reserved closed, without a + /// Reset: this is where a spare's Reset can fail.) + #[test] + fn a_spare_whose_reset_fails_stays_with_the_list_on_the_software_adapter() { + use super::super::title_list; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let mut dev: Option = None; + 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 WARP adapter"); + return; + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + real::adopt(alloc.as_raw(), real::Kind::CommandAllocator); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // still open, and of another type than the list's own allocator: its Reset fails + let direct: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let open: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &direct, None).unwrap(); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, ty); + let wrap = title_list::wrap(pc0); + let spare = open.into_raw(); + real::adopt(spare, real::Kind::CommandList); + title_list::put_spare(wrap, spare); + + assert_eq!(reset_stand_in(wrap, pc0, alloc.as_raw() as usize, 0), None, "the spare whose Reset failed does not stand in"); + assert_eq!(title_list::spares_for_test(wrap), vec![spare as usize], "it stays the list's"); + + 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); + } + } + /// 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) From 95bc093544deda30ce2e617436bdaff04fc9ca8e Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:54:23 -0500 Subject: [PATCH 8/9] Tests: adopt the list in the split ExecuteIndirect allocator-reset test failed_binding_keeps_indirect_commands_until_allocator_reset made a plain PC command list, but execute_indirect binds the slicer and pieces through real::bind_pipeline_exact, which calls the list's original SetPipelineState by its slot in the adopted class. Run alone (or first), slot_of finds no class for the raw list and panics "adopted class"; in the full suite another test has already filled the cached slot. Fails the same way on main 5b711248 run alone (--exact): not caused by the nvidia-dev merge. The test now adopts the list as a title's is (as indirect_guard's tests do) and closes it through the list's own Close, not XCL's hook. Tested: RTX 5070 Ti, debug, --exact alone: 1 passed (main 5b711248 without it: panicked "adopted class"); hle::d3d12x::real::dispatch_chain:: 17 passed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8371147f97467fe21630b5a9f8e4246b2fed22bc) --- crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ed17b4df3a..7fbdcf74b3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -990,6 +990,9 @@ mod tests { let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (adopted as a title's list is: the split binds through the list's original + // SetPipelineState, `real::bind_pipeline_exact`) + super::super::adopt(list.as_raw(), super::super::Kind::CommandList); let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); @@ -1000,7 +1003,10 @@ mod tests { list_reset(raw_list); let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); assert!(!Arc::ptr_eq(&recorded, &next_recording)); - list.Close().unwrap(); + // (the list's own Close, not XCL's hook of a title list's) + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0); allocator_reset(allocator); list_reset(raw_list); forget(key); From b6c449087b80499088bdce247d041d532ffea17e Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:48:46 -0500 Subject: [PATCH 9/9] Tests: 2-D groups give the same threads, groups and waves through the direct route and the HLSL path under DispatchX limits #3189 sends 2-D and 3-D compute groups to the direct DXIL route again. On this tree the thread limits come from nvidia-dev's branch-free compute gate, not main's prologue, so this test checks the combination #3189's own tests could not: 2x2 groups of 8x8 threads with DispatchX limits 0x0, 11x0, 0x13, 11x13 and 3x5, split wave64 and wave32. Barrier-free, the direct form, the HLSL path and the expected table agree. With an s_barrier the direct translator refuses any group of several hardware waves (an older rule in dxil/lower.rs), and the HLSL path matches the table. cargo test -p xcl --lib -- direct_compute_translates_2d_and_3d_groups gpu_direct_compute_waves_take_consecutive_threads_of_2d_and_3d_groups gpu_2d_group_direct_route_matches_the_hlsl_path_under_thread_limits --test-threads=1 (RTX 5070 Ti, 610.74): 3 passed, 0 failed, no SKIPPED. Dropping the Y limit from the expected table makes the GPU test fail at the direct form. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 761fb7232f12ba091eb755758309320099042f2e) (cherry picked from commit 72c875cd38df49d547d0fd000f37d028170b27e7) --- crates/xcl/src/gpu/recomp/tests.rs | 86 ++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d5618eb12f..f1339e9d99 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5729,6 +5729,92 @@ fn gpu_direct_compute_waves_take_consecutive_threads_of_2d_and_3d_groups() { } } +/// A 2-D group takes the same course through `pso::direct_compute` (the route #3189 restores) as +/// through the HLSL path (`pso::console_dxil_noremap`) with this tree's compute entry +/// (nvidia-dev's branch-free thread limits, `kernel::compute_gate`), including when a DispatchX +/// thread limit cuts inside a group. The program is 8 x 8 groups. Each thread stores its console +/// thread index, its group (y << 16 | x), its wave's first thread and its lane at its own slot. +/// It runs as 2 x 2 groups, with no limit and with limits in X, in Y and in both. The wave64 +/// program runs split on a GPU with only 32-lane waves. With a group barrier first, the direct +/// translator leaves the program to the HLSL path (`routed_to_hlsl`, as the runtime does when +/// the group is several hardware waves) and the HLSL form alone must give the table. +#[test] +fn gpu_2d_group_direct_route_matches_the_hlsl_path_under_thread_limits() { + use super::IO_THREAD_LIMIT; + if !gpu_ready() { + return; + } + const NONE: u32 = u32::MAX; + let program = |wave64: bool, barrier: bool| { + program_of(&[ + if barrier { ins("S_BARRIER", "ENC_SOPP", &[], None) } else { Vec::new() }, + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 3)], None), // thread index + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", 128)], None), + if wave64 { ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", V + 14)], None) } else { Vec::new() }, // lane + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 6)], None), // the wave's first thread + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None), + ins("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", 4), ("SRC1", 144), ("SRC2", 3)], None), // group y << 16 | x + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 129), ("SRC2", 3)], None), // group y · 2 + x + ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 9), ("SRC1", 134), ("SRC2", V + 3)], None), // slot + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 132), ("VSRC1", 10)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 11), ("SADDR", 0x7D)], None), + ]) + }; + // `cs_container` with the group ids in s3 (x) and s4 (y) + let container = |code: &[u8], wave64: bool| { + use crate::gpu::xbox::tests::{fssm, sample}; + let mut f = fssm(code, &[(6, 0)]); + f[0x138..0x13C].copy_from_slice(&(3u32 << 1 | 1 << 7 | 1 << 8 | 2 << 11).to_le_bytes()); + for (k, t) in [8u32, 8, 1].iter().enumerate() { + f[0x13C + 4 * k..0x140 + 4 * k].copy_from_slice(&t.to_le_bytes()); + } + if !wave64 { + f[0xD4..0xD8].copy_from_slice(&0x20u32.to_le_bytes()); + } + sample(5, &[f]) + }; + let base = 0x100usize; + for (wave64, barrier) in [(true, false), (false, false), (true, true), (false, true)] { + let lanes = if wave64 { 64 } else { 32 }; + let split = wave64 && runner::split_wave64(); + let blob = container(&program(wave64, barrier), wave64); + let what = format!("wave64 {wave64}, split {split}, barrier {barrier}"); + let direct = match super::pso::direct_compute(&blob, 0, 1, split) { + Ok(c) => Some(c), + Err(e) if barrier && routed_to_hlsl(&e) => None, + Err(e) => panic!("{what}: direct: {e}"), + }; + assert!(direct.as_ref().is_none_or(|c| c.dispatch_chain.is_none()), "{what}: a chain"); + let hlsl = super::pso::console_dxil_noremap(&blob, split, 1).unwrap_or_else(|e| panic!("{what}: HLSL: {e}")); + for (lx, ly) in [(0u32, 0u32), (11, 0), (0, 13), (11, 13), (3, 5)] { + let mut io = vec![0u32; 128]; + io[..3].copy_from_slice(&[base as u32, 8, 64]); + (io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]]) = (lx, ly); + let mem = vec![NONE; (base + 4 * 64 * 16) / 4]; + let d = direct.as_ref().map(|c| runner::dispatch(&c.dxil, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: direct: {e}"))); + let h = runner::dispatch(&hlsl, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: HLSL: {e}")); + for s in 0..4 * 64usize { + let (g, t) = (s / 64, s % 64); + let (gx, gy) = (g % 2, g / 2); + let (x, y) = ((gx * 8 + t % 8) as u32, (gy * 8 + t / 8) as u32); + let ran = (lx == 0 || x < lx) && (ly == 0 || y < ly); + // (the lowest thread of a console wave has its lowest x and y: it runs if any does) + let want = if ran { [t as u32, (gy << 16 | gx) as u32, (t - t % lanes) as u32, (t % lanes) as u32] } else { [NONE; 4] }; + let at = (base + s * 16) / 4; + let where_ = format!("{what}, limit {lx} x {ly}: group ({gx}, {gy}) thread {t}"); + if let Some(d) = &d { + assert_eq!(d[at..at + 4], want, "{where_}: direct (thread, group, wave's first thread, lane)"); + } + assert_eq!(h[at..at + 4], want, "{where_}: HLSL (thread, group, wave's first thread, lane)"); + } + } + } +} + /// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the /// two halves behave as separate waves – ballots, lane counts, readlane and mbcnt per half. #[test]