From f5a574372ae08ee44be993949c2a0eb9901471c3 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 10:29:59 +0100 Subject: [PATCH 1/2] D3D12.X: cover tile mappings whose Signal failed vram's mapping queue raised its value and then signalled it, ignoring the result. When that Signal failed, the value was one no Signal would reach: every queue's next submit waited for it (before_execute) and a retired texture's NULL unmap counted as done although nothing marked it. The value now moves only when the Signal was queued. A mapping or unmapping whose Signal failed is marked, and gets a later Signal before anything counts on it: before_execute queues one and has the title's queue wait for it, and a retired texture stays out of the pool until one completes. When none can be queued either, before_execute says so, and the submission stops with that cause (MappingUnmarked) instead of going out with mappings nothing covers. Tests: a failed Signal leaves the value a Signal reached; with the mapping queue held behind a test fence, a bind, a held unmap released inside before_execute and a retired texture's unmap whose Signals fail each get a later mark, and the work waits for it or does not go. The held-queue test cannot hang the test process: each gate is a guard that Drop opens on unwind, and a detached watchdog opens it after 10 s and fails the test with the phase it was held in. With FAIL_SIGNALS nothing else signals the gates, so an assert between mq.Wait and a gate's Signal, or a test placing on the shared device meanwhile, would otherwise leave the mapping queue waiting for good. reserved_resource_with_private_data_is_excluded_from_recycle takes VRAM_TEST_LOCK, and a test-only lock keeps drain_recycled from marking the test's retired texture while it checks that nothing marked it. --- crates/xcl/src/hle/d3d12x/list_x.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/d3d12x/sparse.rs | 3 + crates/xcl/src/hle/d3d12x/title_textures.rs | 12 +- crates/xcl/src/hle/d3d12x/vram.rs | 366 +++++++++++++++++++- 5 files changed, 366 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 4f3dae2265..bc5bb3f71a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3619,6 +3619,7 @@ unsafe fn mapped_after_wait(queue: *mut c_void) { super::sparse::PreparationOutcome::Ready => {} super::sparse::PreparationOutcome::RetryRequired => stop_for_unresolved_wait("sparse upload preparation after a wait inside a submit still failed after bounded retries"), super::sparse::PreparationOutcome::ExecutedUntracked => stop_for_unresolved_wait("a sparse upload after a wait inside a submit executed without a retirement signal"), + super::sparse::PreparationOutcome::MappingUnmarked => stop_for_unresolved_wait("a texture page mapping after a wait inside a submit has no Signal of the mapping queue"), } } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..a2ca9efc82 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -12077,6 +12077,7 @@ pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut let reason = match outcome { PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", + PreparationOutcome::MappingUnmarked => "a texture page mapping has no Signal of the mapping queue (its own and a retry failed)", PreparationOutcome::Ready => unreachable!(), }; let message = format!("{reason} – the title is stopped before its GPU submission"); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..f650c4f4be 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2412,6 +2412,9 @@ pub(super) enum PreparationOutcome { Ready, RetryRequired, ExecutedUntracked, + /// a tile mapping is queued that no Signal of the mapping queue covers: its own Signal failed + /// and so did a retry (`vram::before_execute`), so nothing may run that reads it + MappingUnmarked, } impl From for PreparationOutcome { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..42ce5aa71b 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2063,7 +2063,9 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut if outcome != super::sparse::PreparationOutcome::Ready { return outcome; } - super::vram::before_execute(q); + if !super::vram::before_execute(q) { + return super::sparse::PreparationOutcome::MappingUnmarked; + } } // a write where a page the queue's page mappings show is kept is a write to the GPU-view pages // that show it: the textures read through their pages find it by their own range (sparse had @@ -2660,7 +2662,9 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex // another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`). - super::vram::before_execute(queue); + if !super::vram::before_execute(queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let key = queue.as_raw() as usize; let state = queue_upload_state(key); let mut slot = state.lock().unwrap(); @@ -3065,7 +3069,9 @@ pub unsafe fn probe_gpu_content(res: usize) { dev.GetCopyableFootprints(&rd, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); let result = own_work(|| -> Result>, String> { let queue = upload_queue(dev, device)?; - super::vram::before_execute(&queue); + if !super::vram::before_execute(&queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(|e| e.to_string())?; let mut rb: Option = None; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5281099647..37f5a1ef9a 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -809,6 +809,11 @@ impl ReservedPool { } } + #[cfg(test)] + fn count(&self, key: &ReservedKey) -> usize { + self.by_key.get(key).map_or(0, Vec::len) + } + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32)> { let bucket = self.by_key.get_mut(key)?; let (raw, total, _gen) = bucket.pop()?; @@ -852,6 +857,9 @@ impl ReservedPool { } } +/// A `PendingRecycle::mark` no Signal reaches yet (`Pages::mark_pending_recycles`). +const UNMARKED: u64 = u64::MAX; + /// Owns a retired reserved texture until the tile-mapping queue passes its last update mark. struct PendingRecycle { key: ReservedKey, @@ -887,6 +895,10 @@ pub(super) struct RecycleInfo { static PARKING: Mutex>> = Mutex::new(None); static PENDING_RECYCLES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +// Lets the failed-Signal test observe and retry an unmarked recycle before the background drainer. +#[cfg(test)] +static RECYCLE_DRAIN_TEST_LOCK: Mutex<()> = Mutex::new(()); + pub(super) fn pending_recycles() -> bool { PENDING_RECYCLES.load(std::sync::atomic::Ordering::Acquire) != 0 } @@ -899,8 +911,11 @@ pub(super) unsafe fn drain_recycled() { } let mut evicted = Vec::new(); { + #[cfg(test)] + let _drain_guard = RECYCLE_DRAIN_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let mut g = PAGES.lock().unwrap(); for pages in g.values_mut().flatten() { + pages.mark_pending_recycles(); let before = pages.pending_recycles.len(); evicted.extend(promote_pending( &mut pages.reserved_pool, @@ -954,11 +969,13 @@ pub(super) unsafe fn recycle_ready(resource: usize) -> bool { pages.unmap(res, info.total); } } + // (its unmap's Signal failed and so did one now: kept out of the pool until one is queued) + let mark = pages.mark().unwrap_or(UNMARKED); pages.pending_recycles.push_back(PendingRecycle { key: info.key, raw: resource, total: info.total, - mark: pages.value, + mark, }); PENDING_RECYCLES.fetch_add(1, std::sync::atomic::Ordering::Release); } @@ -1705,6 +1722,8 @@ struct Pages { held_unmaps: Vec, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) + unmarked: bool, /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) reserved_pool: ReservedPool, /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark @@ -1854,6 +1873,7 @@ impl Pages { unmap_fences: std::collections::HashMap::new(), held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), + unmarked: false, reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), @@ -1935,8 +1955,49 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); + } + + /// A Signal of `fence` with the next value now. `value` moves only when the Signal was + /// queued: queues wait for `value` (`before_execute`), and a value no Signal reaches would + /// hold them forever. A mapping whose Signal failed is covered by the next one that succeeds + /// (the queue runs in order). + unsafe fn signal_now(&mut self) -> Option { + let next = self.value + 1; + #[cfg(test)] + if FAIL_SIGNALS.with(|f| f.get() > 0 && { f.set(f.get() - 1); true }) { + return None; + } + super::real::native_queue_signal(&self.queue, &self.fence, next).ok()?; + self.value = next; + self.unmarked = false; + Some(next) + } + + /// The value that covers every mapping queued so far: `value`, or a new Signal if a mapping's + /// own Signal failed (`unmarked`). None: no Signal could be queued for it - nothing may count + /// on that mapping yet (a queue's work, a texture back to the pool). + unsafe fn mark(&mut self) -> Option { + if self.unmarked { + self.signal_now() + } else { + Some(self.value) + } + } + + /// Retired textures queued with `UNMARKED` (their unmap had no Signal) get the mark of one now, + /// if one can be queued; till then they stay out of the pool. + unsafe fn mark_pending_recycles(&mut self) { + if !self.pending_recycles.iter().any(|p| p.mark == UNMARKED) { + return; + } + if let Some(mark) = self.mark() { + for p in self.pending_recycles.iter_mut().filter(|p| p.mark == UNMARKED) { + p.mark = mark; + } + } } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -1966,8 +2027,9 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); } /// Mark work submitted so far on every active queue. Retirement marks cover queues which @@ -2726,7 +2788,10 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { +/// +/// false: a tile mapping is queued that no Signal of the mapping queue covers (its own failed, and +/// so did one queued now): the work must not go (`PreparationOutcome::MappingUnmarked`). +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { let measure = before_execute_timing_active(); let mut measured = BeforeExecuteTiming { calls: measure as usize, ..Default::default() }; let gate_started = measure.then(std::time::Instant::now); @@ -2754,7 +2819,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } - return; + return true; }; if let Some(started) = device_started { measured.device = started.elapsed(); @@ -2771,6 +2836,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; let mut completed_unmaps = Vec::new(); let mut wait = None; + let mut unmarked = false; let state_started = measure.then(std::time::Instant::now); { let mut g = PAGES.lock().unwrap(); @@ -2778,11 +2844,15 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { completed_unmaps = pages.release_held_unmaps(now, |fence| { observed_completion(&unmap_completions, fence, |known, current| known.as_raw() == current.as_raw()) }); - let value = pages.value; - if reserve_page_wait(&mut pages.waited, queue_key, value) { - wait = Some((pages.fence.clone(), value)); + match pages.mark() { + Some(value) => { + if reserve_page_wait(&mut pages.waited, queue_key, value) { + wait = Some((pages.fence.clone(), value)); + } + } + None => unmarked = true, } - if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { + if !unmarked && now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { pages.last_reclaim = now; do_reclaim = true; newly_reclaimed = pages.sweep_and_reclaim(now); @@ -2821,6 +2891,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } + !unmarked } #[cfg(test)] @@ -2833,9 +2904,13 @@ pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; - pages.value += 1; - super::real::native_queue_signal(&pages.queue, &pages.fence, pages.value).ok()?; - Some(pages.value) + pages.signal_now() +} + +#[cfg(test)] +thread_local! { + /// `signal_now` fails this many times on this thread (tests of a failed Signal) + static FAIL_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The page mapping value of `dev` now: every mapping and unmapping on the device raises it. @@ -3236,6 +3311,8 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::{AtomicU8, Ordering}; + use std::sync::mpsc::{self, RecvTimeoutError}; #[test] fn before_execute_queue_caches_only_a_successful_device_lookup() { @@ -5497,6 +5574,7 @@ mod tests { fn reserved_resource_with_private_data_is_excluded_from_recycle() { use crate::hle::d3d12x::{late_release, real, title_textures}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); unsafe { let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { return crate::gpu::recomp::runner::skip_test("no GPU"); @@ -5616,4 +5694,264 @@ mod tests { late_release::drain_known(true); } } + + /// A Signal that fails leaves `value` where a Signal reached it, so queues waiting for it + /// (`before_execute`) are not held forever. + #[test] + fn a_failed_signal_leaves_the_value_a_signal_reached() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + let reached_value = p.signal_now().expect("a Signal"); + FAIL_SIGNALS.with(|f| f.set(1)); + assert_eq!(p.signal_now(), None); + assert_eq!(p.value, reached_value, "a failed Signal does not move the value queues wait for"); + assert!(reached(&p.fence, p.value, 5000), "the value is reached"); + FAIL_SIGNALS.with(|f| f.set(0)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A one-shot mapping queue gate with an unwind release and a watchdog. + struct Gate { + fence: ID3D12Fence, + section: &'static str, + state: Arc, + cancel: Option>, + } + + impl Gate { + const ARMED: u8 = 0; + const OPENED: u8 = 1; + const RESCUED: u8 = 2; + + unsafe fn new(dev: &ID3D12Device, queue: &ID3D12CommandQueue, section: &'static str) -> Self { + // Use the PC slot on the adopted device to keep this fence outside the title hooks. + type CreateFence = unsafe extern "system" fn( + *mut c_void, u64, D3D12_FENCE_FLAGS, *const windows::core::GUID, *mut *mut c_void, + ) -> windows::core::HRESULT; + let slot = std::mem::offset_of!(ID3D12Device_Vtbl, CreateFence) / std::mem::size_of::(); + let create: CreateFence = std::mem::transmute(super::super::real::orig_fn(dev.as_raw(), slot)); + let mut raw = std::ptr::null_mut(); + create(dev.as_raw(), 0, D3D12_FENCE_FLAG_NONE, &ID3D12Fence::IID, &mut raw) + .ok().expect("create the mapping queue gate"); + assert!(!raw.is_null(), "CreateFence returned no mapping queue gate"); + let fence = ID3D12Fence::from_raw(raw); + let state = Arc::new(AtomicU8::new(Self::ARMED)); + let (cancel, stop) = mpsc::channel(); + let (worker_fence, worker_state) = (fence.clone(), state.clone()); + // Detach so teardown cannot join a worker stuck in the native Signal call. + drop(std::thread::spawn(move || { + if stop.recv_timeout(std::time::Duration::from_secs(10)) == Err(RecvTimeoutError::Timeout) + && worker_state.compare_exchange(Self::ARMED, Self::RESCUED, Ordering::AcqRel, Ordering::Acquire).is_ok() + { + if let Err(err) = worker_fence.Signal(1) { + eprintln!("{section}: mapping queue gate watchdog Signal failed: {err}"); + } + } + })); + let gate = Self { fence, section, state, cancel: Some(cancel) }; + gate.checked(super::super::real::native_queue_wait(queue, &gate.fence, 1)) + .expect("queue the mapping gate wait"); + gate + } + + fn open(&mut self) { + self.checked(unsafe { self.fence.Signal(1) }).expect("open the mapping queue gate"); + // Commit the open before cancelling the worker, even if its timer has expired. + let _ = self.state.compare_exchange(Self::ARMED, Self::OPENED, Ordering::AcqRel, Ordering::Acquire); + drop(self.cancel.take()); + self.checked(()); + } + + fn checked(&self, result: T) -> T { + assert_ne!(self.state.load(Ordering::Acquire), Self::RESCUED, "{}: the mapping queue gate watchdog fired", self.section); + result + } + } + + impl Drop for Gate { + fn drop(&mut self) { + if self.cancel.is_some() && unsafe { self.fence.GetCompletedValue() } == 0 { + let _ = unsafe { self.fence.Signal(1) }; + } + } + } + + /// `fence` reaches `value` within `ms` (polled). + fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool { + let end = std::time::Instant::now() + std::time::Duration::from_millis(ms); + loop { + if unsafe { fence.GetCompletedValue() } >= value { + return true; + } + if std::time::Instant::now() >= end { + return false; + } + std::thread::sleep(std::time::Duration::from_micros(200)); + } + } + + /// A bind and a NULL unmap whose Signals fail are covered by a later Signal before anything + /// counts on them: `before_execute` queues one and has the title's queue wait for it (or says + /// the work must not go when it cannot), and a retired texture stays out of the pool until one + /// completes. The mapping queue is held behind a test fence meanwhile. + #[test] + fn mappings_whose_signal_failed_get_a_later_mark_before_use() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let (mq, mfence) = (pages.queue.clone(), pages.fence.clone()); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(&res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let title_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done = |f: &ID3D12Fence, v: u64| reached(f, v, 5000); + + // mark N, completed + let mut n = 0; + with(&mut |p| n = p.signal_now().unwrap()); + assert!(done(&mfence, n)); + assert!(before_execute(&title)); + + // a bind whose Signal fails, behind a held mapping queue + let mut gate = Gate::new(&dev, &mq, "bind"); + FAIL_SIGNALS.with(|f| f.set(1)); + let mut bound = None; + with(&mut |p| bound = p.bind(&dev, &res, 0x6000_0000, Some(total as u64 * PAGE as u64), total)); + let (used, extra) = gate.checked(bound).expect("bound"); + with(&mut |p| assert!(p.unmarked && p.value == n, "the bind has no mark of its own")); + + // the title's next work: a Signal N+1 is queued now and the work waits for it + assert!(gate.checked(before_execute(&title)), "a later Signal could be queued"); + with(&mut |p| assert!(!p.unmarked && p.value == n + 1)); + gate.checked(super::super::real::native_queue_signal(&title, &title_fence, 1)).unwrap(); + assert!(!gate.checked(reached(&title_fence, 1, 100)), "the title's work waits for N+1"); + gate.open(); + assert!(done(&title_fence, 1), "and goes once N+1 is done"); + + // no Signal at all: the work must not go + with(&mut |p| p.unmarked = true); + FAIL_SIGNALS.with(|f| f.set(1)); + assert!(!before_execute(&title), "no mark: the submit must wait for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + + // a held unmap that becomes releasable inside before_execute, its NULL mapping's Signal + // failing: before_execute queues a later mark after it and the work waits for that + let held = |va: usize| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let done_fence: ID3D12Fence = dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).unwrap(); + with(&mut |p| { + let (used, used_extra) = p.bind(&dev, &r, va, Some(total as u64 * PAGE as u64), total).expect("bound"); + let mark = p.signal_now().expect("a Signal"); + assert!(reached(&p.fence, mark, 5000)); + p.held_unmaps.push(HeldUnmap { res: r.clone(), total, used, used_extra, level_tiles: Vec::new(), marks: vec![(done_fence.clone(), 1)], immediate_cool: false }); + }); + r + }; + let held_a = held(0x6100_0000); + let mut before = 0; + with(&mut |p| before = p.value); + let mut gate3 = Gate::new(&dev, &mq, "held unmap"); + FAIL_SIGNALS.with(|f| f.set(1)); + let can_execute = before_execute(&title); + FAIL_SIGNALS.with(|f| f.set(0)); + assert!(gate3.checked(can_execute), "a later Signal could be queued"); + with(&mut |p| { + assert!(p.held_unmaps.is_empty(), "the held unmap was released"); + assert!(!p.unmarked && p.value == before + 1, "and a later Signal covers its NULL mapping"); + }); + gate3.checked(super::super::real::native_queue_signal(&title, &title_fence, 2)).unwrap(); + assert!(!gate3.checked(reached(&title_fence, 2, 100)), "the title's work waits for it"); + gate3.open(); + assert!(done(&title_fence, 2)); + // the same with no Signal at all: the work must not go + let held_b = held(0x6200_0000); + FAIL_SIGNALS.with(|f| f.set(2)); + assert!(!before_execute(&title), "no mark for the released unmap: the submit waits for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| assert!(p.held_unmaps.is_empty() && p.unmarked)); + assert!(before_execute(&title), "a Signal again: the work goes"); + drop((held_a, held_b)); + + // a retired texture's NULL unmap whose Signal fails, and the retry too + let raw = res.clone().into_raw() as usize; + with(&mut |p| { + p.release_tiles(used.clone(), extra.clone(), std::time::Instant::now(), false); + }); + let mut gate2 = Gate::new(&dev, &mq, "recycle"); + let key = ReservedKey::from_desc(&desc, 0); + { + let _drain_guard = RECYCLE_DRAIN_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + park_recyclable(raw, RecycleInfo { dev_key, key, total, was_mapped: true }, 0); + FAIL_SIGNALS.with(|f| f.set(2)); + let queued = recycle_ready(raw); + FAIL_SIGNALS.with(|f| f.set(0)); + assert!(gate2.checked(queued)); + with(&mut |p| assert!(p.pending_recycles.iter().any(|r| r.raw == raw && r.mark == UNMARKED), "no mark yet")); + // Retry on this thread while the background drainer is still excluded. + with(&mut |p| p.mark_pending_recycles()); + } + drain_recycled(); + gate2.checked(()); + let mut later = 0; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 0, "not in the pool before a mark completes"); + later = p.pending_recycles.iter().find(|r| r.raw == raw).expect("still pending").mark; + assert!(later != UNMARKED && later > n + 1, "a later Signal was queued for it"); + }); + gate2.open(); + assert!(done(&mfence, later)); + drain_recycled(); + let mut back = None; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 1, "in the pool once its mark completed"); + back = p.reserved_pool.take(&key); + }); + assert_eq!(back.map(|b| b.0), Some(raw)); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + drop(res); + PAGES.lock().unwrap().remove(&dev_key); + } + } } From 94b0d76108c326118783374a8a1fc7e5568a4129 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 22:46:47 +0100 Subject: [PATCH 2/2] D3D12.X: require mapping waits before using uploaded textures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Publish a consumer wait only once it was queued. Propagate mapping readiness failures out of texture upload preparation, including mappings made after the title queue’s initial wait. Assisted-by: Codex (GPT-6.2 Sol) --- crates/xcl/src/hle/d3d12x/real.rs | 2 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 42 +++++++++--- crates/xcl/src/hle/d3d12x/vram.rs | 75 ++++++++++++++------- 3 files changed, 84 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a2ca9efc82..ecff399fb7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -12077,7 +12077,7 @@ pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut let reason = match outcome { PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", - PreparationOutcome::MappingUnmarked => "a texture page mapping has no Signal of the mapping queue (its own and a retry failed)", + PreparationOutcome::MappingUnmarked => "could not queue a Signal or Wait for texture page mappings", PreparationOutcome::Ready => unreachable!(), }; let message = format!("{reason} – the title is stopped before its GPU submission"); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 42ce5aa71b..f384b61ed9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2183,9 +2183,9 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut } seed_stream_recheck(&todo, &ranges, recheck_frame); let t_tex = std::time::Instant::now(); - DIRTY_BUF.with(|dcell| upload_all(todo, &dcell.borrow(), page as usize, ID3D12CommandQueue::from_raw_borrowed(&queue))); + let outcome = DIRTY_BUF.with(|dcell| upload_all(todo, &dcell.borrow(), page as usize, ID3D12CommandQueue::from_raw_borrowed(&queue))); super::submit_cost::textures(t_tex.elapsed()); - super::sparse::PreparationOutcome::Ready + outcome } #[cfg(feature = "texture-selection-bench")] @@ -2655,15 +2655,27 @@ unsafe fn upload_target(title: Option<&ID3D12CommandQueue>) -> Target { /// textures with something to send again (`texture_upload::sent`) static AGAIN: Mutex> = Mutex::new(std::collections::BTreeSet::new()); +#[derive(Debug)] +enum UploadError { + MappingUnmarked, + Other(String), +} + +impl From for UploadError { + fn from(error: String) -> Self { + Self::Other(error) + } +} + /// Upload `items` on `queue`, a DIRECT one: the ones that could not be, the bytes of the others and /// where they went (None: there were none). -unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[texture_upload::Item]) -> Result<(Vec<(usize, String)>, u64, Option), String> { +unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[texture_upload::Item]) -> Result<(Vec<(usize, String)>, u64, Option), UploadError> { // The textures' tile mappings made since the queue last waited for them (a texture made on // another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`). if !super::vram::before_execute(queue) { - return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + return Err(UploadError::MappingUnmarked); } let key = queue.as_raw() as usize; let state = queue_upload_state(key); @@ -2673,7 +2685,7 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex let fence = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); } - let Some(q) = slot.as_mut() else { return Err("no fence for the queue".into()) }; + let Some(q) = slot.as_mut() else { return Err("no fence for the queue".to_string().into()) }; // (a piece that panicked on the way into the upload buffer: the batch fails before anything // is executed and is tried again, `RETRY`, rather than going up with what the buffer held) let submitted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| texture_upload::submit(dev, queue, items))); @@ -2687,7 +2699,7 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex Ok(()) => drop(f), Err(_) => std::mem::forget(f), } - return Err(e.to_string()); + return Err(e.to_string().into()); } q.value += 1; q.bytes += f.bytes; @@ -2775,7 +2787,10 @@ fn requeue_generations(table: &mut Table, keys: &[(usize, u64)]) -> Vec { /// What changed of the textures `todo` (written pages: `dirty`, sorted) goes up, in batches of up to /// `BATCH_BYTES` and `BATCH_ITEMS` (one list each). -unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option<&ID3D12CommandQueue>) { +unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option<&ID3D12CommandQueue>) -> super::sparse::PreparationOutcome { + use super::sparse::PreparationOutcome; + let mut outcome = PreparationOutcome::Ready; + let mut prepared_lazy_levels = false; static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -2849,6 +2864,7 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option if super::vram::level_pages() && super::vram::has_lazy_levels(d.res.as_raw() as usize) { // (the queue waits for these mappings before the copies: `vram::before_execute` // below; what a level's fresh pages held is another texture's, so all of it goes up) + prepared_lazy_levels = true; if !map_levels_with_texels_in(&d.res, d.src, &d.tex, d.pages.as_deref()).is_empty() { changed = None; } @@ -2912,7 +2928,10 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option super::submit_cost::textures_uploaded(items.len() - failed.len(), bytes as usize, t_submit.elapsed()); } Err(e) => { - warn(&e); + match e { + UploadError::MappingUnmarked => outcome = PreparationOutcome::MappingUnmarked, + UploadError::Other(e) => warn(&e), + } known.iter().for_each(texture_upload::forget); // (no memory for a buffer, most likely: again in a moment) let at = std::time::Instant::now() + RETRY_AFTER; @@ -2920,6 +2939,11 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option } } } + // Preparing lazy levels can map or unmap tiles after the title queue's first Wait. + if prepared_lazy_levels && outcome == PreparationOutcome::Ready && title.is_some_and(|q| !super::vram::before_execute(q)) { + return PreparationOutcome::MappingUnmarked; + } + outcome } /// textures of batches that could not be uploaded, with their registration generation, and when @@ -3070,7 +3094,7 @@ pub unsafe fn probe_gpu_content(res: usize) { let result = own_work(|| -> Result>, String> { let queue = upload_queue(dev, device)?; if !super::vram::before_execute(&queue) { - return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + return Err("could not queue a Signal or Wait for texture page mappings".into()); } let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(|e| e.to_string())?; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 37f5a1ef9a..444e494111 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1837,12 +1837,8 @@ fn record_before_execute_timing(measured: BeforeExecuteTiming) { }); } -fn reserve_page_wait(waited: &mut HashMap, queue: usize, value: u64) -> bool { - if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { - return false; - } - waited.insert(queue, value); - true +fn needs_page_wait(waited: &HashMap, queue: usize, value: u64) -> bool { + value > waited.get(&queue).copied().unwrap_or(0) } impl Pages { @@ -2789,8 +2785,7 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. /// -/// false: a tile mapping is queued that no Signal of the mapping queue covers (its own failed, and -/// so did one queued now): the work must not go (`PreparationOutcome::MappingUnmarked`). +/// False if a covering Signal or the consumer queue’s Wait could not be queued. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { let measure = before_execute_timing_active(); let mut measured = BeforeExecuteTiming { calls: measure as usize, ..Default::default() }; @@ -2846,7 +2841,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { }); match pages.mark() { Some(value) => { - if reserve_page_wait(&mut pages.waited, queue_key, value) { + if needs_page_wait(&pages.waited, queue_key, value) { wait = Some((pages.fence.clone(), value)); } } @@ -2868,10 +2863,32 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { measured.reclaim_passes = do_reclaim as usize; } let queue_wait_started = measure.then(std::time::Instant::now); - if let Some((fence, value)) = wait { - let _ = super::real::native_queue_wait(queue, &fence, value); - super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); - } + let wait_failed = wait.is_some_and(|(fence, value)| { + super::queue_submit::with(queue_key, || { + // Serialize publication with the native Wait. A racing submit may have waited + // while this one was acquiring the queue lease. + let already_waited = PAGES.lock().unwrap().get(&dev_key).and_then(Option::as_ref) + .is_some_and(|pages| pages.fence.as_raw() == fence.as_raw() + && !needs_page_wait(&pages.waited, queue_key, value)); + if already_waited { + return false; + } + #[cfg(test)] + if FAIL_MAPPING_WAIT.with(|fail| fail.replace(false)) { + return true; + } + if super::real::native_queue_wait(queue, &fence, value).is_err() { + return true; + } + if let Some(Some(pages)) = PAGES.lock().unwrap().get_mut(&dev_key) { + if pages.fence.as_raw() == fence.as_raw() { + pages.waited.insert(queue_key, value); + } + } + super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + false + }) + }); if let Some(started) = queue_wait_started { measured.queue_wait = started.elapsed(); } @@ -2891,7 +2908,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { if measure { record_before_execute_timing(measured); } - !unmarked + !unmarked && !wait_failed } #[cfg(test)] @@ -2910,6 +2927,7 @@ pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { #[cfg(test)] thread_local! { /// `signal_now` fails this many times on this thread (tests of a failed Signal) + static FAIL_MAPPING_WAIT: std::cell::Cell = const { std::cell::Cell::new(false) }; static FAIL_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; } @@ -4125,15 +4143,15 @@ mod tests { #[test] fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { - let mut waited = HashMap::new(); - assert!(!reserve_page_wait(&mut waited, 1, 0)); - assert!(reserve_page_wait(&mut waited, 1, 4)); - assert!(!reserve_page_wait(&mut waited, 1, 4)); - assert!(!reserve_page_wait(&mut waited, 1, 3)); - assert!(reserve_page_wait(&mut waited, 2, 3)); - assert!(reserve_page_wait(&mut waited, 1, 5)); - assert_eq!(waited, HashMap::from([(1, 5), (2, 3)])); + let waited = HashMap::from([(1, 4), (2, 3)]); + assert!(!needs_page_wait(&waited, 3, 0)); + assert!(needs_page_wait(&waited, 3, 4)); + assert!(!needs_page_wait(&waited, 1, 4)); + assert!(!needs_page_wait(&waited, 1, 3)); + assert!(needs_page_wait(&waited, 2, 4)); + assert!(needs_page_wait(&waited, 1, 5)); } + use std::time::{Duration, Instant}; const MIB: usize = 1 << 20; @@ -5860,9 +5878,16 @@ mod tests { let (used, extra) = gate.checked(bound).expect("bound"); with(&mut |p| assert!(p.unmarked && p.value == n, "the bind has no mark of its own")); - // the title's next work: a Signal N+1 is queued now and the work waits for it - assert!(gate.checked(before_execute(&title)), "a later Signal could be queued"); - with(&mut |p| assert!(!p.unmarked && p.value == n + 1)); + // The replacement Signal succeeds, but a failed consumer Wait must not be cached. + FAIL_MAPPING_WAIT.with(|fail| fail.set(true)); + assert!(!gate.checked(before_execute(&title)), "a failed Wait must refuse submission"); + with(&mut |p| { + assert!(!p.unmarked && p.value == n + 1); + assert_eq!(p.waited.get(&(title.as_raw() as usize)), Some(&n)); + }); + + // The next submission retries the Wait for N+1. + assert!(gate.checked(before_execute(&title)), "the Wait can be queued on retry"); gate.checked(super::super::real::native_queue_signal(&title, &title_fence, 1)).unwrap(); assert!(!gate.checked(reached(&title_fence, 1, 100)), "the title's work waits for N+1"); gate.open();