From 3f193cf17591aca249a5ece31f69bf3429cfeb89 Mon Sep 17 00:00:00 2001 From: ExoCalibra Date: Tue, 24 Nov 2026 14:03:33 +0300 Subject: [PATCH 1/6] D3D12.X: stop sparse upload_dirty ring wait when fence times out sparse::State::wait_for intentionally returns after 5 s with a warning if the sparse queue stalls, but upload_dirty wrapped wait_for in a while loop waiting for staging ring space. When the oldest in-flight fence failed to advance, reclaim_ring freed nothing and upload_dirty looped forever while holding the global STATE mutex, blocking xcl-activity (pool_bytes) and every submitting thread. Return whether wait_for reached its target fence value, bail out of upload_dirty with a bounded warning on timeout so STATE is released, and add a GPU regression test reproducing a full staging ring with a stalled fence. (cherry picked from commit 0f66820065129bca1e0cd7f3ae0125e140d835f3) --- crates/xcl/src/hle/d3d12x/sparse.rs | 117 ++++++++++++++++++++++++++-- 1 file changed, 112 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..ec1c912a44 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -830,15 +830,25 @@ impl State { } #[inline] - unsafe fn wait_for(&self, target: u64) { + unsafe fn wait_for(&self, target: u64) -> bool { + self.wait_for_ms(target, 5000) + } + + #[inline] + unsafe fn wait_for_ms(&self, target: u64, timeout_ms: u32) -> bool { if target == 0 || self.fence.GetCompletedValue() >= target { - return; + return true; } let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + windows::Win32::System::Threading::WaitForSingleObject(self.event, timeout_ms); if self.fence.GetCompletedValue() < target { - crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); + crate::xlog_warn!( + "sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", + self.fence.GetCompletedValue() + ); + return false; } + true } #[inline] @@ -1135,6 +1145,10 @@ impl State { /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + self.upload_dirty_with_timeout(runs, 5000); + } + + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) { if runs.is_empty() { return; } @@ -1167,8 +1181,15 @@ impl State { } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { let Some(&(fv, _)) = self.inflight.front() else { break }; - self.wait_for(fv); + let reached = self.wait_for_ms(fv, wait_ms); self.reclaim_ring(); + if !reached { + static RING_STALL: AtomicU64 = AtomicU64::new(0); + if RING_STALL.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; leaving remaining dirty uploads to avoid holding STATE forever"); + } + return; + } } } } @@ -2559,4 +2580,90 @@ mod tests { println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); } } + + /// When the staging ring is full and the oldest in-flight upload fence stalls past the wait + /// timeout, `upload_dirty` must bail out cleanly instead of looping forever while holding + /// `STATE` (which wedged `xcl-activity` and every submit thread). + #[test] + fn upload_dirty_exits_when_ring_fence_wait_times_out() { + 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 Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let mut reserved: Option = None; + if dev.CreateReservedResource(&buffer_desc((2 * TILE) as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).is_err() { + crate::gpu::recomp::runner::skip_test("no reserved buffers"); + return; + } + let reserved = reserved.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).unwrap(); + rb_list.Close().unwrap(); + + let src = vec![0x5Au8; 4096]; + let base = src.as_ptr() as usize; + let mut s = State { + dev, + queue, + fence, + value: 1, + event, + rb_fence, + rb_value: 0, + windows: vec![(base, reserved)], + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + // Simulate a completely full staging ring waiting on unsignaled fence value 1. + ring_write: STAGING as u64, + ring_submitted: STAGING as u64, + ring_free: 0, + inflight: VecDeque::from([(1u64, STAGING as u64)]), + zero_buf: None, + slots: Vec::new(), + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + }; + + let started = std::time::Instant::now(); + s.upload_dirty_with_timeout(&[(base, 4096)], 50); + assert!(started.elapsed() < std::time::Duration::from_secs(2), "upload_dirty must return after fence wait timeout instead of looping forever"); + assert_eq!(s.ring_write, STAGING as u64, "timed-out upload must not overwrite full ring"); + assert_eq!(s.ring_submitted, STAGING as u64, "ring_submitted must stay consistent with ring_write"); + assert_eq!(s.inflight.len(), 1, "stalled fence entry must remain in inflight"); + } + } } From 02728e0dd0a0c2f424aee17ca7cb5ba8cdbb4310 Mon Sep 17 00:00:00 2001 From: gridoe <135166302+gridoe@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:01:26 +0200 Subject: [PATCH 2/6] D3D12.X: wait_for ignores stale signals on the reusable sparse fence event (cherry picked from commit 3861d2e2b561482933c657802cc5801b28bc60ba, #1419; on top of #1277, wait_for_ms passes its own timeout to wait_fence_until and keeps returning whether the fence was reached) --- crates/xcl/src/hle/d3d12x/sparse.rs | 84 ++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ec1c912a44..02df316279 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -407,6 +407,27 @@ fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { // D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock unsafe impl Send for State {} +/// Wait for `fence` to reach `target` using a reusable auto-reset `event`, bounded by `timeout`. +/// Resets `event` before arming and loops until `GetCompletedValue() >= target` or the deadline +/// expires, so a late completion from an earlier timed-out wait cannot satisfy a newer wait early. +unsafe fn wait_fence_until(fence: &ID3D12Fence, event: HANDLE, target: u64, timeout: std::time::Duration) -> bool { + if target == 0 || fence.GetCompletedValue() >= target { + return true; + } + let _ = windows::Win32::System::Threading::ResetEvent(event); + let _ = fence.SetEventOnCompletion(target, event); + let deadline = std::time::Instant::now() + timeout; + while fence.GetCompletedValue() < target { + let rem = deadline.saturating_duration_since(std::time::Instant::now()); + if rem.is_zero() { + return false; + } + let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; + windows::Win32::System::Threading::WaitForSingleObject(event, ms); + } + true +} + static STATE: Mutex> = Mutex::new(None); /// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an @@ -836,12 +857,7 @@ impl State { #[inline] unsafe fn wait_for_ms(&self, target: u64, timeout_ms: u32) -> bool { - if target == 0 || self.fence.GetCompletedValue() >= target { - return true; - } - let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, timeout_ms); - if self.fence.GetCompletedValue() < target { + if !wait_fence_until(&self.fence, self.event, target, std::time::Duration::from_millis(timeout_ms as u64)) { crate::xlog_warn!( "sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", self.fence.GetCompletedValue() @@ -2554,6 +2570,62 @@ mod tests { assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); } + /// A late completion from an earlier timed-out `SetEventOnCompletion` leaves the reusable + /// auto-reset event signalled (or fires it mid-wait). `wait_fence_until` must ignore both + /// and wait until the fence actually reaches `target`. + #[test] + fn wait_fence_until_ignores_stale_event_signal() { + use std::time::{Duration, Instant}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, SetEvent}; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let Ok(factory) = CreateDXGIFactory1::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + } + let dev = dev.unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let event = CreateEventW(None, false, false, None).expect("event"); + + // Case 1: stale signal already set on the auto-reset event before waiting. + // Case 2: an earlier pending completion (value 2) fires the same event mid-wait + // before our target (value 5) completes. + SetEvent(event).expect("stale SetEvent"); + fence.SetEventOnCompletion(2, event).expect("stale completion arm"); + + let f2 = fence.clone(); + let t = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(30)); + let _ = f2.Signal(2); + std::thread::sleep(Duration::from_millis(50)); + let _ = f2.Signal(5); + }); + + let start = Instant::now(); + let ok = wait_fence_until(&fence, event, 5, Duration::from_secs(2)); + let elapsed = start.elapsed(); + t.join().unwrap(); + let _ = CloseHandle(event); + + assert!(ok, "wait_fence_until timed out instead of observing Signal(5)"); + assert!(fence.GetCompletedValue() >= 5, "returned early at {}", fence.GetCompletedValue()); + assert!(elapsed >= Duration::from_millis(50), "returned too early ({elapsed:?}) on a stale event signal"); + } + } + /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in /// reverse, before the device exists (`cargo test --release -p xcl --lib -- /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, From 7621090ac1ab59b2b631cc6449ebfa3b92205a88 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:32:49 -0800 Subject: [PATCH 3/6] D3D12.X: stop stalled sparse ring reclaim cleanly The sparse upload ring retried a five-second fence wait forever while holding global sparse state. A stalled upload queue therefore blocked activity reporting and every later title submission permanently.\n\nAdapt #1277's bounded exit, but preserve correctness beyond the source patch: mark exactly the unsubmitted 64-byte chunk suffix for retry instead of leaving its sent hashes stale or invalidating already-submitted chunks in the same page. A synchronous readback aborts when its prerequisite upload did not complete, so it cannot overwrite CPU memory with stale GPU data.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU execution, and smoke tests were not available here.\n\nSource diagnosis and timeout test: #1277 by ExoCalibra, assisted by Antigravity (Gemini 4 Neon).\n\nAssisted-by: Codex (GPT-5.6-sol) (cherry picked from commit faea307a3144d21b26d116892f245d151f196a44) --- crates/xcl/src/hle/d3d12x/sparse.rs | 126 ++++++++++++++++++++++++---- 1 file changed, 112 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 02df316279..bf011e30b8 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1013,6 +1013,32 @@ impl State { } } + /// Make only the chunks overlapping `[a, a + n)` differ from their recorded hashes, so a + /// partial upload failure does not also resend earlier chunks in the same CPU page. + unsafe fn retry_sent_range(&mut self, a: usize, n: usize) { + let end = a + n; + let mut at = a; + while at < end { + let page = at & !(PAGE - 1); + let tile = page & !(TILE - 1); + let page_end = (page + PAGE).min(end); + if let Some(entry) = self.mapped.get_mut(&tile) { + let index = (page - tile) / PAGE; + let Some(sent) = entry.sent[index].as_mut() else { + at = page_end; + continue; + }; + let first = (at - page) / CHUNK; + let last = (page_end - page).div_ceil(CHUNK); + let bytes = std::slice::from_raw_parts(page as *const u8, PAGE); + for chunk in first..last { + sent[chunk] = chunk_hash(&bytes[chunk * CHUNK..(chunk + 1) * CHUNK]) ^ 1; + } + } + at = page_end; + } + } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { @@ -1160,18 +1186,25 @@ impl State { /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { - self.upload_dirty_with_timeout(runs, 5000); + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> bool { + self.upload_dirty_with_timeout(runs, 5000) } - unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) { + fn retry_dirty_from(&mut self, runs: &[(usize, usize)], index: usize, done: usize) { + visit_unsubmitted_dirty(runs, index, done, |a, n| unsafe { self.retry_sent_range(a, n) }); + } + + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> bool { if runs.is_empty() { - return; + return true; } - let Some(p) = self.staging_ptr() else { return }; + let Some(p) = self.staging_ptr() else { + self.retry_dirty_from(runs, 0, 0); + return false; + }; let mut open_slot: Option = None; let mut last_wi: Option = None; - for &(a, n) in runs { + for (run_index, &(a, n)) in runs.iter().enumerate() { let mut done = 0usize; while done < n { let cur = a + done; @@ -1182,7 +1215,10 @@ impl State { last_wi = Some(i); i } - None => break, + None => { + self.retry_dirty_from(runs, run_index, done); + return false; + } }, }; let b = self.windows[wi].0; @@ -1196,15 +1232,21 @@ impl State { self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - let Some(&(fv, _)) = self.inflight.front() else { break }; + let Some(&(fv, _)) = self.inflight.front() else { + self.retry_dirty_from(runs, run_index, done); + crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); + return false; + }; let reached = self.wait_for_ms(fv, wait_ms); self.reclaim_ring(); if !reached { - static RING_STALL: AtomicU64 = AtomicU64::new(0); - if RING_STALL.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; leaving remaining dirty uploads to avoid holding STATE forever"); + self.retry_dirty_from(runs, run_index, done); + static RING_STALLS: AtomicU64 = AtomicU64::new(0); + let stalls = RING_STALLS.fetch_add(1, Ordering::Relaxed) + 1; + if stalls <= 4 || stalls.is_power_of_two() { + crate::xlog_warn!("sparse: staging ring reclaim timed out at fence {fv}; the unsubmitted CPU writes will be retried ({stalls} stalls)"); } - return; + return false; } } } @@ -1228,6 +1270,7 @@ impl State { if let Some(slot_idx) = open_slot { self.submit_slot(slot_idx); } + true } } @@ -1353,7 +1396,9 @@ pub unsafe fn readback_now(va: usize, len: usize) { pg = tile_end; } if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + if !s.upload_dirty(&dirty_runs) { + return; + } } s.readback_ranges(&[(va, len)]); } @@ -1585,6 +1630,16 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); } +fn visit_unsubmitted_dirty(runs: &[(usize, usize)], index: usize, done: usize, mut visit: impl FnMut(usize, usize)) { + let (a, n) = runs[index]; + if done < n { + visit(a + done, n - done); + } + for &(a, n) in &runs[index + 1..] { + visit(a, n); + } +} + /// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. @@ -1643,7 +1698,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.upload_zeros(&zero_runs); } if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + let _ = s.upload_dirty(&dirty_runs); } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { @@ -1787,6 +1842,18 @@ mod tests { assert!(answered, "queue() waited for the sparse state's lock"); } + #[test] + fn a_stalled_ring_retries_only_the_unsubmitted_dirty_suffix() { + let runs = [(0x1000, 0x180), (0x3000, 0x80), (0x5000, 0x40)]; + let mut retry = Vec::new(); + visit_unsubmitted_dirty(&runs, 0, 0x100, |a, n| retry.push((a, n))); + assert_eq!(retry, [(0x1100, 0x80), (0x3000, 0x80), (0x5000, 0x40)]); + + retry.clear(); + visit_unsubmitted_dirty(&runs, 1, 0x80, |a, n| retry.push((a, n))); + assert_eq!(retry, [(0x5000, 0x40)], "a fully submitted run is not made stale again"); + } + /// A block freed on one thread while another allocates: its address goes back to the /// windows only once it is decommitted (released first, the decommit came after another /// thread had the same address again: that thread's writes faulted). @@ -2337,6 +2404,37 @@ mod tests { (base, s) } + #[test] + fn a_stalled_upload_ring_returns_and_retries_exact_chunks() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.sync_sent_range(base, PAGE); + let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); + + s.ring_write = STAGING as u64; + s.ring_submitted = STAGING as u64; + s.ring_free = 0; + s.inflight.push_back((s.value + 1, STAGING as u64)); + let started = std::time::Instant::now(); + assert!(!s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20)); + assert!(started.elapsed() < std::time::Duration::from_secs(2), "a stalled fence kept upload_dirty in its ring loop"); + let after = s.mapped[&base].sent[0].as_ref().unwrap(); + assert_eq!(after[0], before[0], "an already submitted chunk was made dirty again"); + assert_ne!(after[1], before[1]); + assert_ne!(after[2], before[2]); + assert_eq!(after[3], before[3]); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] From 01981673e1e21dbdaabb97ec0e9a5c28e201f780 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:36:01 -0800 Subject: [PATCH 4/6] D3D12.X: abort sparse allocator reuse after wait failure Sparse upload and readback paths continued after a five-second fence timeout, resetting command allocators which the GPU could still be using and publishing readback staging bytes whose copy had not completed. Reset and Close failures were ignored as well.\n\nMake upload-slot acquisition fail closed, retry exact dirty or zero work, and abort readback before allocator reuse or CPU publication whenever its wait or command-list transition fails. The healthy asynchronous path is unchanged.\n\nThe Windows GNU library/test cross-check passed with the existing warnings. Windows MSVC runtime, GPU execution, and smoke tests were not available here.\n\nAssisted-by: Codex (GPT-5.6-sol) (cherry picked from commit 37271a3c0e27cc520a22939d700c421724eebc12) --- crates/xcl/src/hle/d3d12x/sparse.rs | 82 ++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 26 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bf011e30b8..fad5cd5525 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -885,18 +885,24 @@ impl State { /// Acquire the next upload command slot, waiting only if that slot's previous submission is /// still executing on the GPU, then reset its allocator and list. - unsafe fn begin_slot(&mut self) -> usize { + unsafe fn begin_slot(&mut self) -> Option { + self.begin_slot_with_timeout(5000) + } + + unsafe fn begin_slot_with_timeout(&mut self, timeout_ms: u32) -> Option { let idx = self.next_slot; self.next_slot = (self.next_slot + 1) % self.slots.len(); let fv = self.slots[idx].fence_val; if fv > 0 && self.fence.GetCompletedValue() < fv { - self.wait_for(fv); + if !self.wait_for_ms(fv, timeout_ms) { + return None; + } self.reclaim_ring(); } let slot = &self.slots[idx]; - let _ = slot.alloc.Reset(); - let _ = slot.list.Reset(&slot.alloc, None); - idx + slot.alloc.Reset().ok()?; + slot.list.Reset(&slot.alloc, None).ok()?; + Some(idx) } /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work @@ -1077,19 +1083,21 @@ impl State { let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| -> bool { if *open { *open = false; - if s.rb_list.Close().is_ok() { - if let Ok(l) = s.rb_list.cast::() { - super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); - }); - } - } + let Ok(()) = s.rb_list.Close() else { return false }; + let Ok(l) = s.rb_list.cast::() else { return false }; + super::title_textures::own_work(|| { + s.queue.ExecuteCommandLists(&[Some(l)]); + }); s.signal(); s.rb_last_fence = s.value; - s.wait_for(s.value); + if !s.wait_for(s.value) { + pending.clear(); + *used = 0; + return false; + } s.reclaim_ring(); } for &(dst, off, len) in pending.iter() { @@ -1112,6 +1120,7 @@ impl State { } pending.clear(); *used = 0; + true }; for &(a, n) in ranges { if n == 0 { @@ -1129,14 +1138,16 @@ impl State { continue; } if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + if !flush_and_copy(self, &mut open, &mut pending, &mut used, p) { + return; + } } let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_for(self.rb_last_fence); - let _ = self.rb_alloc.Reset(); - let _ = self.rb_list.Reset(&self.rb_alloc, None); + if !self.wait_for(self.rb_last_fence) || self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err() { + return; + } open = true; } self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); @@ -1146,17 +1157,20 @@ impl State { } } if open { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + let _ = flush_and_copy(self, &mut open, &mut pending, &mut used, p); } } /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) { - if runs.is_empty() || !self.ensure_zero_buf() { - return; + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> bool { + if runs.is_empty() { + return true; + } + if !self.ensure_zero_buf() { + return false; } - let slot_idx = self.begin_slot(); + let Some(slot_idx) = self.begin_slot() else { return false }; let mut last_wi: Option = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1182,6 +1196,7 @@ impl State { } } self.submit_slot(slot_idx); + true } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via @@ -1254,7 +1269,10 @@ impl State { let slot_idx = match open_slot { Some(idx) => idx, None => { - let idx = self.begin_slot(); + let Some(idx) = self.begin_slot() else { + self.retry_dirty_from(runs, run_index, done); + return false; + }; open_slot = Some(idx); idx } @@ -1373,7 +1391,10 @@ pub unsafe fn readback_now(va: usize, len: usize) { for &(a, n) in &zeroed { s.clear_sent_range(a, n); } - s.upload_zeros(&zeroed); + if !s.upload_zeros(&zeroed) { + s.to_zero.extend(zeroed); + return; + } } // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); @@ -1695,7 +1716,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. if !zero_runs.is_empty() { - s.upload_zeros(&zero_runs); + if !s.upload_zeros(&zero_runs) { + s.to_zero.extend(zero_runs.iter().copied()); + } } if !dirty_runs.is_empty() { let _ = s.upload_dirty(&dirty_runs); @@ -2430,6 +2453,13 @@ mod tests { assert_ne!(after[2], before[2]); assert_eq!(after[3], before[3]); + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); + s.next_slot = 0; + assert_eq!(s.begin_slot_with_timeout(20), None, "a timed-out slot must not reset its in-flight allocator"); + drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } From 405371a0a2d1542faaa6e3353728a8b21eb75939 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:39:25 +0000 Subject: [PATCH 5/6] D3D12.X: sparse chunks a stalled upload left unsent are scanned again retry_sent_range marks the chunks a stalled upload could not submit as unsent, but before_execute only scans the pages the write-watch reports, and that write-watch was reset when the page was first scanned. The marked chunks therefore stayed stale in video memory until the CPU wrote the same page again, which a page written once may never do. retry_sent_range now records the page, and before_execute scans the recorded pages again with the write-watch's ones. A chunk already sent hashes equal and is not uploaded twice. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 61 +++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fad5cd5525..40e3c81861 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -264,6 +264,9 @@ struct State { runs: Option>, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) scratch_runs: Vec<(usize, usize)>, + /// pages with chunks `retry_sent_range` marked unsent: `before_execute` scans them again, + /// since the write-watch that reported them has been reset + retry_pages: Vec, } impl Drop for State { @@ -596,6 +599,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }) })(); match made { @@ -1029,6 +1033,7 @@ impl State { let tile = page & !(TILE - 1); let page_end = (page + PAGE).min(end); if let Some(entry) = self.mapped.get_mut(&tile) { + self.retry_pages.push(page); let index = (page - tile) / PAGE; let Some(sent) = entry.sent[index].as_mut() else { at = page_end; @@ -1045,6 +1050,24 @@ impl State { } } + /// Scan the pages in `retry_pages` again into `out`: without it, their unsent chunks waited + /// for the CPU to write the page again. + unsafe fn scan_retry_pages(&mut self, out: &mut Vec<(usize, usize)>) { + let mut pages = std::mem::take(&mut self.retry_pages); + pages.sort_unstable(); + pages.dedup(); + for &pg in &pages { + let t = pg & !(TILE - 1); + if let Some(entry) = self.mapped.get_mut(&t) { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], out); + } + } + } + } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { @@ -1711,6 +1734,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: x = end; } } + s.scan_retry_pages(&mut dirty_runs); let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); @@ -1993,6 +2017,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -2201,6 +2226,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -2298,6 +2324,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; s.commit_range(base, TILE); @@ -2423,6 +2450,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; (base, s) } @@ -2465,6 +2493,38 @@ mod tests { } } + /// The write-watch that reported a page is reset when it is scanned, so chunks a stalled + /// upload left unsent are found again by the next submit without another CPU write. + #[test] + fn unsent_chunks_are_scanned_again_without_a_new_cpu_write() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.sync_sent_range(base, PAGE); + + s.ring_write = STAGING as u64; + s.ring_submitted = STAGING as u64; + s.ring_free = 0; + s.inflight.push_back((s.value + 1, STAGING as u64)); + assert!(!s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20)); + + let mut runs = Vec::new(); + s.scan_retry_pages(&mut runs); + assert_eq!(runs, vec![(base + CHUNK, 2 * CHUNK)], "the unsent chunks were not found again"); + runs.clear(); + s.scan_retry_pages(&mut runs); + assert!(runs.is_empty(), "a rescanned page stays marked: {runs:x?}"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] @@ -2854,6 +2914,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), quarantined: VecDeque::new(), queue_fences: FxHashMap::default(), }; From 970b8a4ad7c5a64e6bb5e605a5cd16ecbd1cb784 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:50:46 +0000 Subject: [PATCH 6/6] D3D12.X: sparse CPU writes wait for tile clears that could not be sent Since a failed tile clear goes back to to_zero, before_execute could still upload the submit's CPU writes when the clears found no upload slot or zero buffer. The clears then went out at a later submit, after those writes, and zeroed them: the write-after-write that submitting the clears first is there to avoid. On main a failed clear was dropped. When the clears cannot be submitted, the CPU writes are now marked for the next upload with them, as readback_now already stops in that case. Reported by KDenKC in #2821. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 74 +++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 40e3c81861..7b45f34089 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1187,13 +1187,17 @@ impl State { /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> bool { + self.upload_zeros_with_timeout(runs, 5000) + } + + unsafe fn upload_zeros_with_timeout(&mut self, runs: &[(usize, usize)], wait_ms: u32) -> bool { if runs.is_empty() { return true; } if !self.ensure_zero_buf() { return false; } - let Some(slot_idx) = self.begin_slot() else { return false }; + let Some(slot_idx) = self.begin_slot_with_timeout(wait_ms) else { return false }; let mut last_wi: Option = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1222,6 +1226,18 @@ impl State { true } + /// Tile clears `zero_runs`, then CPU writes `dirty_runs`, so that overlapping copies have no + /// write-after-write hazard. When the clears cannot be submitted they go back to `to_zero` + /// and the CPU writes wait with them: sent now, they would be zeroed by the clears sent later. + unsafe fn upload_zeros_then_dirty(&mut self, zero_runs: &[(usize, usize)], dirty_runs: &[(usize, usize)], wait_ms: u32) -> bool { + if !self.upload_zeros_with_timeout(zero_runs, wait_ms) { + self.to_zero.extend_from_slice(zero_runs); + self.retry_dirty_from(dirty_runs, 0, 0); + return false; + } + self.upload_dirty_with_timeout(dirty_runs, wait_ms) + } + /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> bool { @@ -1675,6 +1691,10 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { } fn visit_unsubmitted_dirty(runs: &[(usize, usize)], index: usize, done: usize, mut visit: impl FnMut(usize, usize)) { + // Failed tile clears retry the CPU writes from run 0, also when the submit had none. + if index >= runs.len() { + return; + } let (a, n) = runs[index]; if done < n { visit(a + done, n - done); @@ -1738,15 +1758,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); - // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. - if !zero_runs.is_empty() { - if !s.upload_zeros(&zero_runs) { - s.to_zero.extend(zero_runs.iter().copied()); - } - } - if !dirty_runs.is_empty() { - let _ = s.upload_dirty(&dirty_runs); - } + let _ = s.upload_zeros_then_dirty(&zero_runs, &dirty_runs, 5000); PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { static CALLS: AtomicU64 = AtomicU64::new(0); @@ -1899,6 +1911,10 @@ mod tests { retry.clear(); visit_unsubmitted_dirty(&runs, 1, 0x80, |a, n| retry.push((a, n))); assert_eq!(retry, [(0x5000, 0x40)], "a fully submitted run is not made stale again"); + + retry.clear(); + visit_unsubmitted_dirty(&[], 0, 0, |a, n| retry.push((a, n))); + assert!(retry.is_empty(), "failed tile clears with no CPU writes retry nothing"); } /// A block freed on one thread while another allocates: its address goes back to the @@ -2525,6 +2541,44 @@ mod tests { } } + /// Tile clears that cannot be submitted keep the CPU writes back with them: sent first, the + /// writes would be zeroed by the clears submitted at a later upload. + #[test] + fn cpu_writes_wait_for_tile_clears_that_could_not_be_submitted() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.sync_sent_range(base, PAGE); + let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); + + // the clears get the first slot, still in flight; the CPU writes could get the second + for fence_val in [s.value + 1, 0] { + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + s.slots.push(UploadSlot { alloc, list, fence_val }); + } + s.next_slot = 0; + let value = s.value; + assert!(!s.upload_zeros_then_dirty(&[(base + PAGE, PAGE)], &[(base + CHUNK, CHUNK)], 20)); + assert_eq!(s.value, value, "CPU writes were submitted before the tile clears"); + assert_eq!(s.ring_write, 0); + assert_eq!(s.to_zero, vec![(base + PAGE, PAGE)]); + let after = s.mapped[&base].sent[0].as_ref().unwrap(); + assert_ne!(after[1], before[1], "the held-back CPU write is not marked for the next upload"); + assert_eq!(after[0], before[0]); + assert_eq!(s.retry_pages, vec![base]); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test]