From f5a574372ae08ee44be993949c2a0eb9901471c3 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 10:29:59 +0100 Subject: [PATCH 1/3] 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/3] 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(); From 5800b721b3c7ae0e1fe80afa5bb4b86777c8a959 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:40:11 +0100 Subject: [PATCH 3/3] D3D12.X: hand the title reserved textures with live page tables amdgpu, the Linux kernel driver, runs a process's page-table updates in order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits for all command submissions of the VM first. While a frame is in flight, a reserved texture made after its submit has no page-table entries, not even the PRT ones, until that frame is done. A console title may write a descriptor of a texture it has just placed that work it already submitted reads; on the console the memory is there, here the read is a GPU page fault (TCP, PERMISSION_FAULTS 0x3) and the device is lost. RADV_DEBUG=bo_history and the kernel log put the faulting virtual BO 32-38 ms after its creation, by a new placement, with the hung IB older than the texture. A texture from the pool has had its entries since before: its rebind still lands late, but the work in flight reads a NULL tile meanwhile. So: - the pool also takes render targets, depth and UAV textures and those with a clear value, keyed by its meaningful bytes; - every placement tops its description up to XCL_RESERVED_SPARES (default 2) spares made ahead, reserved under the pages lock and pooled only once a Signal of the mapping queue after them completes; - a placement that still has to make a new texture waits up to XCL_PLACE_MAP_WAIT_MS (default 1000) for such a Signal, polling the fence; when no Signal can be queued for it, the placement fails as a failed creation does. It is one change because the parts only work together: without the wait a burst of new textures outruns the spares and faults; without the spares every new placement waits a frame. It builds on the marks for mappings whose Signal failed (the commit before): spares and new placements count on a Signal reaching their mappings. On by default only under Wine with an AMD GPU, judged by the Vulkan physical device vkd3d-proton drives (DXVK's DXGI may report an NVIDIA GPU as AMD), else by the DXGI adapter: Windows drivers do not order page-table updates like this, and the extra creations and waits cost time on the title's thread (the log says how much: the placements, the spares made and the time spent making them, and the waits). XCL_LIVE_RESERVED=1/0 forces it either way. Tests: the gate and the vendor source, clear keys, the fence wait, placements with the gate on and off, concurrent placements and their spares, spares and a cold lazy placement whose Signal fails, and spares kept out of dump tracking. --- crates/xcl/src/hle/d3d12x/lut3d.rs | 14 + crates/xcl/src/hle/d3d12x/real.rs | 13 + crates/xcl/src/hle/d3d12x/vram.rs | 1097 +++++++++++++++++++++++++++- 3 files changed, 1117 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/lut3d.rs b/crates/xcl/src/hle/d3d12x/lut3d.rs index 6f969c56b6..2f049375e0 100644 --- a/crates/xcl/src/hle/d3d12x/lut3d.rs +++ b/crates/xcl/src/hle/d3d12x/lut3d.rs @@ -29,9 +29,23 @@ const DUMPED_MOST: usize = 256; const WRITES_LOGGED: u64 = 12; pub fn on() -> bool { + #[cfg(test)] + if FORCE_ON.load(Ordering::Relaxed) { + return true; + } super::targets::enabled() } +/// Tests: track 3D textures as `XCL_DUMP_TARGETS` does. +#[cfg(test)] +pub static FORCE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tests: `res` is one of the 3D textures a dump enumerates. +#[cfg(test)] +pub fn tracked(res: usize) -> bool { + VOLS.lock().unwrap().contains_key(&res) +} + /// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`). pub fn created_on() -> bool { on() || super::capture::enabled() diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ecff399fb7..0c9853e559 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4607,6 +4607,19 @@ pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESUL hr } +/// `res` is no longer one of the reserved resources `note_reserved` keeps (a spare or an evicted one +/// of `vram`'s pool, which goes without the title's Release). +pub(super) fn forget_reserved(res: usize) { + if let Some(s) = RESERVED.lock().unwrap().as_mut() { + s.remove(&res); + } +} + +#[cfg(test)] +pub(super) fn is_noted_reserved(res: usize) -> bool { + RESERVED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)) +} + unsafe fn is_reserved(res: *mut c_void) -> bool { let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); kept.is_some_and(|k| desc_of(res) == Some(k)) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 444e494111..55d9281e92 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -737,6 +737,294 @@ fn reserved_pool_enabled() -> bool { *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) } +/// Hand the title reserved textures whose VA predates the work in flight where possible: the +/// pool also takes render targets, depth and UAV textures, spares are made ahead per description +/// (`reserved_spares`), and a placement that still has to make a new one waits for its page +/// tables (`wait_new_placement`). +/// +/// This works around amdgpu, the Linux kernel driver: it runs a process's page-table updates in +/// order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits +/// for all command submissions of the VM first. So while a frame is in flight, a reserved texture +/// made after its submit has no page-table entries at all, not even PRT ones, until that frame is +/// done. A console title may write a descriptor of a texture it has just placed that work it +/// already submitted reads (on the console the memory is there): a GPU page fault (a retail title on +/// Wine + RADV). A texture from the pool has had its entries since before: a rebind still lands +/// late, but the work in flight reads the NULL (PRT) tile meanwhile, not an invalid page. +/// +/// Windows drivers do not order page-table updates behind running work like that, and the extra +/// CreateReservedResource calls and waits cost time on the title's thread, so it is on by default +/// only under Wine on an AMD adapter (`live_decide`). `XCL_LIVE_RESERVED=1` / `0` forces it on or +/// off anywhere; `XCL_RESERVED_POOL=0` turns it off with the pool. +fn live_reserved_for(dev: &ID3D12Device) -> bool { + let forced = std::env::var("XCL_LIVE_RESERVED").ok(); + reserved_pool_enabled() && live_decide(forced.as_deref(), crate::util::under_wine(), || unsafe { pick_vendor(vulkan_vendor(dev), || adapter_vendor(dev)) }) +} + +/// The GPU's vendor: the Vulkan physical device's when known, else DXGI's. Under Proton, DXVK's +/// DXGI may report an NVIDIA GPU as AMD (for games that check), while the Vulkan device that +/// vkd3d-proton drives (and the kernel driver behind it) is the real one. +fn pick_vendor(vulkan: Option, dxgi: impl FnOnce() -> Option) -> Option { + vulkan.or_else(dxgi) +} + +/// `VkPhysicalDeviceProperties::vendorID` of the physical device vkd3d-proton made `dev` on, +/// through its `ID3D12DXVKInteropDevice` (None: not vkd3d-proton, or no Vulkan loader). +unsafe fn vulkan_vendor(dev: &ID3D12Device) -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress, LoadLibraryA}; + // ID3D12DXVKInteropDevice (vkd3d-proton's include/vkd3d_device_vkd3d_ext.idl) + const IID_INTEROP: windows::core::GUID = windows::core::GUID::from_u128(0x39da4e09_bd1c_4198_9fae_86bbe3be41fd); + let mut interop: *mut c_void = std::ptr::null_mut(); + if dev.query(&IID_INTEROP, &mut interop).is_err() || interop.is_null() { + return None; + } + let interop = windows::core::IUnknown::from_raw(interop); + let vtbl = *(interop.as_raw() as *const *const usize); + // IUnknown (3), GetDXGIAdapter, GetInstanceExtensions, GetDeviceExtensions, GetDeviceFeatures, + // then GetVulkanHandles(VkInstance *, VkPhysicalDevice *, VkDevice *) + type Handles = unsafe extern "system" fn(*mut c_void, *mut usize, *mut usize, *mut usize) -> windows::core::HRESULT; + let get_handles: Handles = std::mem::transmute(*vtbl.add(7)); + let (mut instance, mut physical, mut device) = (0usize, 0usize, 0usize); + get_handles(interop.as_raw(), &mut instance, &mut physical, &mut device).ok().ok()?; + if physical == 0 { + return None; + } + let mut vulkan = GetModuleHandleA(c"vulkan-1.dll".as_ptr() as *const u8); + if vulkan.is_null() { + vulkan = LoadLibraryA(c"vulkan-1.dll".as_ptr() as *const u8); + } + if vulkan.is_null() { + return None; + } + let f = GetProcAddress(vulkan, c"vkGetPhysicalDeviceProperties".as_ptr() as *const u8)?; + type Props = unsafe extern "system" fn(usize, *mut u8); + let props: Props = std::mem::transmute(f); + // VkPhysicalDeviceProperties: apiVersion, driverVersion, vendorID, ... (824 bytes; room to spare) + let mut buf = vec![0u8; 4096]; + props(physical, buf.as_mut_ptr()); + let vendor = u32::from_le_bytes(buf[8..12].try_into().unwrap()); + (vendor != 0).then_some(vendor) +} + +/// `live_reserved_for`'s choice: `forced` from `XCL_LIVE_RESERVED`, else Wine on AMD (0x1002). +fn live_decide(forced: Option<&str>, wine: bool, vendor: impl FnOnce() -> Option) -> bool { + match forced.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => wine && vendor() == Some(0x1002), + } +} + +/// PCI vendor id of `dev`'s adapter. +unsafe fn adapter_vendor(dev: &ID3D12Device) -> Option { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + Some(adapter.GetDesc().ok()?.VendorId) +} + +/// Spare reserved textures kept made ahead per description (`XCL_RESERVED_SPARES`, default 2; +/// only where `live_reserved_for` holds): made next to a placement, they enter the pool once the +/// mapping queue passes a Signal after them, which is once their page-table entries exist. +fn reserved_spares() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_RESERVED_SPARES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2).min(16)) +} + +/// How many spares to make for a description with `have` pooled or pending ones. +fn spares_to_make(have: usize, want: usize) -> usize { + want.saturating_sub(have) +} + +/// (placements from the pool, new ones, spares made, µs spent making them, longest one call) +static LIVE_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +fn note_live_stats(pooled: bool) { + use std::sync::atomic::Ordering::Relaxed; + let n = LIVE_STATS[if pooled { 0 } else { 1 }].fetch_add(1, Relaxed) + LIVE_STATS[if pooled { 1 } else { 0 }].load(Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + crate::xlog_info!( + "D3D12.X: reserved textures placed: {} from the pool (VA live before), {} new (VA maybe not live for work in flight); {} spares made ahead, in {} ms on the placing threads (longest call {} µs)", + LIVE_STATS[0].load(Relaxed), + LIVE_STATS[1].load(Relaxed), + LIVE_STATS[2].load(Relaxed), + LIVE_STATS[3].load(Relaxed) / 1000, + LIVE_STATS[4].load(Relaxed) + ); + } +} + +/// How long a placement that had to make a new reserved texture waits on the CPU for a Signal of +/// the mapping queue sent after it (`XCL_PLACE_MAP_WAIT_MS`, default 1000; 0: no wait). That +/// Signal completes once the texture's page-table entries exist, which is once the work in flight +/// before it is done, so the title cannot write a descriptor of it that work reads. Each such +/// placement waits on its own, also after one that timed out. +fn place_map_wait_ms() -> u64 { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_PLACE_MAP_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000)) +} + +/// (new placements that waited, of them timed out, total µs, longest µs) +static NEW_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// How a wait for a fence value ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum FenceWait { + /// it had completed already + Done, + /// it completed within the time, after this long + Waited(std::time::Duration), + /// it had not completed after this long + TimedOut(std::time::Duration), +} + +/// Wait up to `ms` for `fence` to reach `value`, polling it with short sleeps. No event is +/// registered with the fence: vkd3d-proton keeps a registered handle until the value is reached, +/// so an event closed after a timeout could be signalled later under a reused handle. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, ms: u64) -> FenceWait { + if super::real::fence_completed(fence) >= value { + return FenceWait::Done; + } + let t0 = std::time::Instant::now(); + let limit = std::time::Duration::from_millis(ms); + loop { + if super::real::fence_completed(fence) >= value { + return FenceWait::Waited(t0.elapsed()); + } + let left = limit.saturating_sub(t0.elapsed()); + if left.is_zero() { + return FenceWait::TimedOut(t0.elapsed()); + } + std::thread::sleep(left.min(std::time::Duration::from_micros(500))); + } +} + +/// How `wait_new_placement` ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum NewWait { + /// `XCL_PLACE_MAP_WAIT_MS=0`: no wait asked for + Off, + /// a Signal was queued and waited for (or timed out) + Signalled(FenceWait), + /// no Signal could be queued, twice: nothing tells when the texture's page tables exist + Failed, +} + +/// A placement that had to make a new reserved texture: a Signal of the mapping queue after it +/// (one retry if it cannot be queued), and a wait for it up to `place_map_wait_ms`. +unsafe fn wait_new_placement(dev_key: usize) -> NewWait { + use std::sync::atomic::Ordering::Relaxed; + let ms = place_map_wait_ms(); + if ms == 0 { + return NewWait::Off; + } + let (fence, value) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return NewWait::Failed }; + let Some(value) = pages.signal_now().or_else(|| pages.signal_now()) else { return NewWait::Failed }; + (pages.fence.clone(), value) + }; + let end = wait_fence(&fence, value, ms); + let (took, timed_out) = match end { + FenceWait::Done => return NewWait::Signalled(end), + FenceWait::Waited(d) => (d, false), + FenceWait::TimedOut(d) => (d, true), + }; + let us = took.as_micros().min(u64::MAX as u128) as u64; + let n = NEW_WAITS[0].fetch_add(1, Relaxed) + 1; + if timed_out { + NEW_WAITS[1].fetch_add(1, Relaxed); + } + NEW_WAITS[2].fetch_add(us, Relaxed); + NEW_WAITS[3].fetch_max(us, Relaxed); + if n.is_power_of_two() || timed_out { + crate::xlog_info!( + "D3D12.X: new reserved textures waited for their page tables: {n} ({} timed out after {ms} ms), {} ms in all, longest {} ms", + NEW_WAITS[1].load(Relaxed), + NEW_WAITS[2].load(Relaxed) / 1000, + NEW_WAITS[3].load(Relaxed) / 1000 + ); + } + NewWait::Signalled(end) +} + +/// Spares `place_on_pages` reserved; dropped before `take`, the reservation is given back. +struct SpareReservation { + dev_key: usize, + key: Option, + n: usize, +} + +impl SpareReservation { + /// The reserved count, now `make_spares`' to give back. + fn take(&mut self) -> usize { + std::mem::take(&mut self.n) + } +} + +impl Drop for SpareReservation { + fn drop(&mut self) { + if let (Some(key), true) = (self.key, self.n != 0) { + if let Some(Some(pages)) = PAGES.lock().unwrap().get_mut(&self.dev_key) { + pages.end_spare_reservation(key, self.n); + } + } + } +} + +/// Make the `n` spare reserved textures like `tiled` that `place_on_pages` reserved under +/// `PAGES.lock()` (`Pages::spares_in_flight`), and queue them for the pool behind one Signal of +/// the mapping queue (`reserved_spares`). The reservation is given back whatever happens; spares +/// without a Signal (it failed) are released instead. +unsafe fn make_spares(dev: &ID3D12Device, this: *mut c_void, tiled: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, key: ReservedKey, n: usize) { + if n == 0 { + return; + } + let started = std::time::Instant::now(); + let mut made: Vec<(usize, u32)> = Vec::with_capacity(n); + for _ in 0..n { + let mut p: *mut c_void = std::ptr::null_mut(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // (the PC creator, not the title-facing one: an idle spare is no resource of the title's, + // so nothing that tracks those - `note_reserved`, `lut3d` - may know it; it is registered + // when handed out, as a title's released one is: `place_on_pages`, then `device_x`) + let hr = super::real::pc_create_reserved_resource(this, tiled as *const _ as usize, state as usize, clear as usize, riid, &mut p); + if hr < 0 || p.is_null() { + break; + } + let Some(res) = ID3D12Resource::from_raw_borrowed(&p) else { break }; + let mut total = 0u32; + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + made.push((p as usize, total)); + } + let unsignalled = { + let mut g = PAGES.lock().unwrap(); + match g.get_mut(&(dev.as_raw() as usize)) { + Some(Some(pages)) => { + pages.end_spare_reservation(key, n); + match (made.is_empty(), pages.signal_now()) { + (true, _) => Vec::new(), + (false, Some(mark)) => { + LIVE_STATS[2].fetch_add(made.len() as u64, std::sync::atomic::Ordering::Relaxed); + PENDING_RECYCLES.fetch_add(made.len(), std::sync::atomic::Ordering::Release); + for &(raw, total) in &made { + pages.pending_recycles.push_back(PendingRecycle { key, raw, total, mark }); + } + Vec::new() + } + (false, None) => made, + } + } + _ => made, + } + }; + for (raw, _) in unsignalled { + drop(windows::core::IUnknown::from_raw(raw as *mut c_void)); + } + let us = started.elapsed().as_micros() as u64; + LIVE_STATS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + LIVE_STATS[4].fetch_max(us, std::sync::atomic::Ordering::Relaxed); +} + /// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] struct ReservedKey { @@ -751,11 +1039,29 @@ struct ReservedKey { sample_quality: u32, flags: i32, state: u32, + /// the optimized clear value's bytes (`D3D12_CLEAR_VALUE`), all zero without one + clear: [u8; CLEAR_VALUE_BYTES], } +const CLEAR_VALUE_BYTES: usize = std::mem::size_of::(); + impl ReservedKey { + /// `clear`: null or a `D3D12_CLEAR_VALUE`. Only its meaningful bytes count: the format, and + /// the four colour floats, or for a depth-stencil texture the depth float and the stencil + /// byte (the rest of the union is not initialised then). + unsafe fn from_desc_clear(desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void) -> Self { + let mut key = Self::from_desc(desc, state); + if !clear.is_null() { + // (only those bytes are read: the rest may not even be readable memory) + let used = if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { 4 + 4 + 1 } else { CLEAR_VALUE_BYTES }; + std::ptr::copy_nonoverlapping(clear as *const u8, key.clear.as_mut_ptr(), used); + } + key + } + fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { Self { + clear: [0; CLEAR_VALUE_BYTES], dimension: desc.Dimension.0, alignment: desc.Alignment, width: desc.Width, @@ -809,7 +1115,6 @@ impl ReservedPool { } } - #[cfg(test)] fn count(&self, key: &ReservedKey) -> usize { self.by_key.get(key).map_or(0, Vec::len) } @@ -925,7 +1230,14 @@ pub(super) unsafe fn drain_recycled() { PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); } } + release_evicted(evicted); +} + +/// Release reserved textures evicted from the pool (outside `PAGES.lock()`), with nothing of +/// XCL's left that names them. +unsafe fn release_evicted(evicted: Vec) { for old in evicted { + super::real::forget_reserved(old); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2)); f(old as *mut c_void); } @@ -1722,8 +2034,12 @@ struct Pages { held_unmaps: Vec, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// `live_reserved_for` this device + live: bool, /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) unmarked: bool, + /// spares `place_on_pages` reserved and `make_spares` is making, by description + spares_in_flight: std::collections::HashMap, /// 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 @@ -1869,7 +2185,9 @@ impl Pages { unmap_fences: std::collections::HashMap::new(), held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), + live: live_reserved_for(dev), unmarked: false, + spares_in_flight: std::collections::HashMap::new(), reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), @@ -1956,10 +2274,33 @@ impl Pages { 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). + /// Reserve the spares `key` lacks (pooled, pending and in-flight ones count), up to `want`. + fn reserve_spares(&mut self, key: ReservedKey, want: usize) -> usize { + let in_flight = self.spares_in_flight.get(&key).copied().unwrap_or(0); + let have = self.reserved_pool.count(&key) + self.pending_recycles.iter().filter(|p| p.key == key).count() + in_flight; + let n = spares_to_make(have, want); + if n != 0 { + self.spares_in_flight.insert(key, in_flight + n); + } + n + } + + /// Give back `n` reserved spares of `key` (`make_spares` made or failed them). + fn end_spare_reservation(&mut self, key: ReservedKey, n: usize) { + if let Some(v) = self.spares_in_flight.get_mut(&key) { + *v = v.saturating_sub(n); + if *v == 0 { + self.spares_in_flight.remove(&key); + } + } + } + + /// A Signal of `fence` with the next value now: its submission waits for every page-table + /// update the process queued before (amdgpu syncs a submit to the VM's last update), so the + /// value completes once reserved textures made before have their entries (`make_spares`). + /// `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)] @@ -2359,20 +2700,41 @@ unsafe fn place_on_pages( } }; let dev_key = dev.as_raw() as usize; - let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) - .then(|| ReservedKey::from_desc(&tiled, state)); + let live; + let recycle_key; let mut pooled = None; + let mut spares = 0usize; + let mut evicted = Vec::new(); let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); + live = pages.live; + // (`live_reserved_for`: render targets, depth and UAV textures, those with a clear value, too) + recycle_key = if live { + Some(ReservedKey::from_desc_clear(&tiled, state, clear)) + } else { + (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()).then(|| ReservedKey::from_desc(&tiled, state)) + }; if ok { if let Some(key) = recycle_key { + if live && pending_recycles() { + pages.mark_pending_recycles(); + let before = pages.pending_recycles.len(); + evicted = promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()); + PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); + } pooled = pages.reserved_pool.take(&key); + if live { + spares = pages.reserve_spares(key, reserved_spares()); + } } } ok }; + release_evicted(evicted); + // (given back on every way out of here but `make_spares`) + let mut reservation = SpareReservation { dev_key, key: recycle_key, n: spares }; if !is_reservable { log("no tiled support for its format or sample count"); return None; @@ -2425,6 +2787,16 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + // (no live one in the pool: wait until its VA has page-table entries, before the pages know + // it. A texture with lazy levels queues no mapping here, so that Signal is all that tells; + // when none can be queued the placement fails as a failed creation does: nothing is mapped + // or noted yet, and the spare reservation goes back with `reservation`.) + if cached_total.is_none() && live && wait_new_placement(dev_key) == NewWait::Failed { + crate::xlog_warn!("D3D12.X: texture at {va:#x}: no Signal of the mapping queue after its new reserved texture - not placed on pages"); + drop(windows::core::IUnknown::from_raw(raw)); + *ppv = std::ptr::null_mut(); + return None; + } let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2458,6 +2830,10 @@ unsafe fn place_on_pages( for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) { super::late_release::hold_unmap(r); } + if let (true, Some(key)) = (live, recycle_key) { + note_live_stats(cached_total.is_some()); + make_spares(dev, this, &tiled, state, clear, key, reservation.take()); + } Some(hr) } @@ -5518,6 +5894,644 @@ mod tests { assert_eq!(cap3.take(&k_b), Some((0x2000, 1))); } + #[test] + fn reserved_key_tells_clear_values_apart_and_spares_top_up() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let black = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 0.0, 1.0] } }; + let white = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [1.0; 4] } }; + let (none, k_black, k_white, k_black2) = unsafe { + ( + ReservedKey::from_desc_clear(&desc, state, std::ptr::null()), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &white as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ) + }; + assert_eq!(none, ReservedKey::from_desc(&desc, state)); + assert_ne!(none, k_black); + assert_ne!(k_black, k_white); + assert_eq!(k_black, k_black2); + + let mut pool = ReservedPool::new(8); + assert_eq!(pool.count(&k_black), 0); + assert_eq!(pool.push(k_black, 0x1000, 1), None); + assert_eq!(pool.push(k_black, 0x2000, 1), None); + assert_eq!(pool.count(&k_black), 2); + assert_eq!(pool.count(&k_white), 0); + assert!(pool.take(&k_white).is_none()); + assert!(pool.take(&k_black).is_some()); + assert_eq!(pool.count(&k_black), 1); + + assert_eq!(spares_to_make(0, 2), 2); + assert_eq!(spares_to_make(1, 2), 1); + assert_eq!(spares_to_make(5, 2), 0); + assert_eq!(spares_to_make(0, 0), 0); + } + + #[test] + fn live_reserved_is_on_by_default_only_under_wine_on_amd() { + assert!(live_decide(None, true, || Some(0x1002))); + assert!(!live_decide(None, true, || Some(0x10de)), "NVIDIA under Wine"); + assert!(!live_decide(None, false, || Some(0x1002)), "AMD on Windows"); + assert!(!live_decide(None, true, || None), "no adapter"); + assert!(!live_decide(Some(""), false, || Some(0x10de))); + assert!(live_decide(Some("1"), false, || Some(0x10de)), "forced on"); + assert!(live_decide(Some(" 1 "), false, || None), "forced on"); + assert!(!live_decide(Some("0"), true, || Some(0x1002)), "forced off"); + // (forced either way: the adapter is not even asked) + assert!(live_decide(Some("1"), false, || panic!("asked"))); + // DXVK's DXGI says AMD, the Vulkan device is NVIDIA's: off + assert!(!live_decide(None, true, || pick_vendor(Some(0x10de), || Some(0x1002)))); + assert!(live_decide(None, true, || pick_vendor(Some(0x1002), || Some(0x10de)))); + // no Vulkan device known: DXGI's vendor + assert!(live_decide(None, true, || pick_vendor(None, || Some(0x1002)))); + } + + /// Under vkd3d-proton the vendor comes from the Vulkan physical device. + #[test] + fn the_vendor_comes_from_vkd3d_protons_vulkan_device() { + 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"); + }; + match vulkan_vendor(&dev) { + Some(v) => assert!(v != 0 && Some(v) == pick_vendor(Some(v), || None)), + None => assert!(!crate::util::under_wine(), "vkd3d-proton under Wine has a Vulkan device"), + } + } + } + + #[test] + fn a_depth_clear_key_ignores_the_union_tail() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32; + // format DXGI_FORMAT_D32_FLOAT (40), depth 1.0, stencil 7, then garbage + let clear = |stencil: u8, tail: u8| { + let mut b = [tail; CLEAR_VALUE_BYTES]; + b[..4].copy_from_slice(&40u32.to_le_bytes()); + b[4..8].copy_from_slice(&1.0f32.to_le_bytes()); + b[8] = stencil; + b + }; + let key = |b: &[u8; CLEAR_VALUE_BYTES]| unsafe { ReservedKey::from_desc_clear(&desc, state, b.as_ptr() as *const c_void) }; + assert_eq!(key(&clear(7, 0x00)), key(&clear(7, 0xCD)), "the uninitialised tail must not split keys"); + assert_ne!(key(&clear(7, 0x00)), key(&clear(8, 0x00)), "the stencil value counts"); + let mut deeper = clear(7, 0); + deeper[4..8].copy_from_slice(&0.0f32.to_le_bytes()); + assert_ne!(key(&clear(7, 0)), key(&deeper), "the depth value counts"); + // a colour clear uses all four floats + let mut colour_desc = desc; + colour_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + let mut c1 = clear(7, 0); + let mut c2 = c1; + c2[19] = 0x3F; + c1[19] = 0x00; + unsafe { + assert_ne!( + ReservedKey::from_desc_clear(&colour_desc, state, c1.as_ptr() as *const c_void), + ReservedKey::from_desc_clear(&colour_desc, state, c2.as_ptr() as *const c_void), + "a colour clear's alpha counts" + ); + } + } + + /// The mapping queue's fence of `dev_key`. + fn queue_fence(dev_key: usize) -> ID3D12Fence { + match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.fence.clone(), + _ => panic!("no pages"), + } + } + + /// Owns a fence for a thread that signals it later. + struct SendFence(ID3D12Fence); + unsafe impl Send for SendFence {} + + fn signal_later(fence: &ID3D12Fence, value: u64, after_ms: u64) -> std::thread::JoinHandle<()> { + let f = SendFence(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_millis(after_ms)); + unsafe { f.0.Signal(value).unwrap() }; + }) + } + + #[test] + fn wait_fence_returns_at_the_signal_or_times_out() { + 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"); + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + assert_eq!(wait_fence(&fence, 0, 1000), FenceWait::Done); + let t = signal_later(&fence, 1, 40); + match wait_fence(&fence, 1, 5000) { + FenceWait::Waited(d) => assert!(d >= std::time::Duration::from_millis(30) && d < std::time::Duration::from_millis(4000), "{d:?}"), + other => panic!("{other:?}"), + } + t.join().unwrap(); + match wait_fence(&fence, 2, 30) { + FenceWait::TimedOut(d) => assert!(d >= std::time::Duration::from_millis(25), "{d:?}"), + other => panic!("{other:?}"), + } + // the timed-out wait left nothing registered: a new event is not signalled when the + // fence reaches that value afterwards + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + let event = CreateEventW(None, false, false, None).unwrap(); + fence.Signal(2).unwrap(); + let got = WaitForSingleObject(event, 50); + let _ = windows::Win32::Foundation::CloseHandle(event); + assert_eq!(got, windows::Win32::Foundation::WAIT_TIMEOUT, "an old wait signalled a new event"); + } + } + + /// A clear value is read only as far as it means something: a depth-stencil one that ends + /// right before an unreadable page. + #[test] + fn a_depth_clear_key_reads_only_its_prefix() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!base.is_null()); + let mut old = 0; + assert!(VirtualProtect(base.add(0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old) != 0); + let at = base.add(0x1000 - 9); + at.copy_from_nonoverlapping([40u8, 0, 0, 0].as_ptr(), 4); + at.add(4).copy_from_nonoverlapping(1.0f32.to_le_bytes().as_ptr(), 4); + *at.add(8) = 7; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let key = ReservedKey::from_desc_clear(&desc, 0, at as *const c_void); + assert_eq!(&key.clear[..9], std::slice::from_raw_parts(at, 9)); + assert!(key.clear[9..].iter().all(|&b| b == 0)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// With 3D textures tracked for dumps (`XCL_DUMP_TARGETS`): spares are made by the PC creator, + /// so an idle one is neither a title's reserved resource nor a dumped 3D texture, and one + /// released from the pool leaves nothing the dump enumerates; a spare handed to the title by + /// a placement is tracked. + #[test] + fn spares_stay_out_of_dump_tracking_until_handed_out() { + use std::sync::atomic::Ordering::Relaxed; + 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 Some(uma) = crate::gpu::uma::get() else { + return crate::gpu::recomp::runner::skip_test("no UMA"); + }; + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + super::super::lut3d::FORCE_ON.store(true, Relaxed); + let console = super::super::title_textures::tests::console_desc(4, 32, 32, 32, 1, 28, 0x105); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let Some(base) = uma.alloc(4 << 20, 0x1_0000).map(|p| p as usize) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no UMA block"); + }; + let place = |va: usize| -> Option { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, console.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + (hr >= 0 && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let pending = || { + let mut v = Vec::new(); + with(&mut |p| v = p.pending_recycles.iter().map(|r| (r.key, r.raw)).collect()); + v + }; + + // 1. a new 3D texture: tracked; the spares made for its description are not + let Some(first) = place(base) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no reserved 3D texture on pages here"); + }; + assert!(first.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D); + assert!(super::super::lut3d::tracked(first.as_raw() as usize), "the title's 3D texture is tracked"); + let spares = pending(); + assert!(!spares.is_empty(), "spares were made for it"); + for &(_, raw) in &spares { + assert!(!super::super::lut3d::tracked(raw), "an idle spare is not dumped"); + assert!(!super::super::real::is_noted_reserved(raw), "nor kept as a title's reserved resource"); + } + + // 2. its spares reach the pool; one is released as an eviction releases it: the dump's + // enumeration does not know it + with(&mut |p| { + let last = p.signal_now().unwrap(); + assert!(matches!(wait_fence(&p.fence, last, 5000), FenceWait::Done | FenceWait::Waited(_))); + }); + drain_recycled(); + let key = spares[0].0; + let mut evicted = None; + with(&mut |p| evicted = p.reserved_pool.take(&key)); + let (evicted, _) = evicted.expect("a spare in the pool"); + release_evicted(vec![evicted]); + assert!(!super::super::lut3d::tracked(evicted)); + assert!(super::super::lut3d::to_dump().iter().all(|(_, r, _, _)| r.as_raw() as usize != evicted), "a released spare is not enumerated"); + + // 3. the next placement of that description takes a spare from the pool: tracked now + let left: Vec = spares.iter().map(|s| s.1).filter(|&r| r != evicted).collect(); + let second = place(base + (1 << 20)).expect("placed"); + let raw2 = second.as_raw() as usize; + assert!(left.contains(&raw2), "the placement took a spare"); + assert!(super::super::lut3d::tracked(raw2), "a spare handed to the title is tracked"); + assert!(super::super::real::is_noted_reserved(raw2), "and kept as its reserved resource"); + + super::super::lut3d::FORCE_ON.store(false, Relaxed); + drop((first, second)); + let rest: Vec = { + let mut v = Vec::new(); + with(&mut |p| { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + v = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + while let Some((raw, _)) = p.reserved_pool.take(&key) { + v.push(raw); + } + }); + v + }; + release_evicted(rest); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A cold texture with lazy levels queues no mapping, so the Signal after its new reserved + /// texture is all that says its page tables exist: when it cannot be queued a retry is, and + /// waited for; when that fails too the placement fails with nothing left behind. + #[test] + fn a_lazy_placement_without_a_readiness_signal_is_not_handed_out() { + 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(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.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 = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 10, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> (Option, *mut c_void) { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, 0, std::ptr::null(), Some(4 << 20), false, true, riid, &mut p); + (hr, p) + }; + let snapshot = || { + let mut t = (0, 0, 0, 0); + with(&mut |p| t = (p.value, p.targets.len(), p.pending_recycles.len(), p.spares_in_flight.len())); + t + }; + + // 1. the first Signal fails, the retry is queued behind a held mapping queue: the + // placement returns only once that retry has completed + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let (v0, ..) = snapshot(); + FAIL_SIGNALS.with(|f| f.set(1)); + let opener = signal_later(&gate, 1, 80); + let t0 = std::time::Instant::now(); + let (hr, p) = place(0x7000_0000, &desc(512)); + let took = t0.elapsed(); + FAIL_SIGNALS.with(|f| f.set(0)); + opener.join().unwrap(); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed after the retry"); + assert!(took >= std::time::Duration::from_millis(60), "it waited for the retried Signal: {took:?}"); + let mut retried = 0; + with(&mut |pg| retried = pg.value); + assert!(retried > v0, "a later Signal was queued"); + assert!(matches!(wait_fence(&queue_fence(dev_key), v0 + 1, 0), FenceWait::Done), "and completed before the title got the texture"); + assert!(has_lazy_levels(p as usize), "a lazy-level texture"); + let first = ID3D12Resource::from_raw(p); + + // 2. no Signal at all: no resource, nothing kept of it (the spares of 1. in the pool + // first, so nothing moves meanwhile) + with(&mut |pg| { + let v = pg.value; + let _ = wait_fence(&pg.fence, v, 5000); + }); + drain_recycled(); + let before = snapshot(); + let placed_before = PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()); + FAIL_SIGNALS.with(|f| f.set(2)); + let (hr, p) = place(0x7100_0000, &desc(256)); + FAIL_SIGNALS.with(|f| f.set(0)); + assert!(hr.is_none() && p.is_null(), "no texture without a readiness Signal"); + assert_eq!(snapshot(), before, "no value, target, spare or reservation left behind"); + assert_eq!(PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()), placed_before); + + drop(first); + let spares: Vec = { + let mut v = Vec::new(); + with(&mut |pg| { + let last = pg.signal_now().unwrap(); + let _ = wait_fence(&pg.fence, last, 5000); + v = pg.pending_recycles.drain(..).map(|r| r.raw).collect(); + v.extend(pg.reserved_pool.by_key.drain().flat_map(|(_, b)| b.into_iter().map(|e| e.0))); + pg.reserved_pool.live_gen.clear(); + pg.reserved_pool.order.clear(); + }); + v + }; + release_evicted(spares); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// Placements of one description at once reserve their spares under the lock: together they + /// make no more than `reserved_spares`. The mapping queue is held, so no spare reaches the pool + /// (and gets topped up again) meanwhile. + #[test] + fn concurrent_placements_make_at_most_the_spares_of_one() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + 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(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + const THREADS: usize = 4; + let made0 = LIVE_STATS[2].load(Relaxed); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + struct SendDev(ID3D12Device); + unsafe impl Send for SendDev {} + let workers: Vec<_> = (0..THREADS) + .map(|i| { + let (d, b) = (SendDev(dev.clone()), barrier.clone()); + std::thread::spawn(move || { + let d = d; + 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 }, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut p = std::ptr::null_mut(); + b.wait(); + let hr = place_on_pages(&d.0, d.0.as_raw(), 0x5000_0000 + i * 0x10_0000, &desc, 0, std::ptr::null(), Some(256 * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null()); + p as usize + }) + }) + .collect(); + // (every placement waits for its page tables behind the gate; open it once all reserved) + std::thread::sleep(std::time::Duration::from_millis(300)); + gate.Signal(1).unwrap(); + let placed: Vec = workers.into_iter().map(|w| w.join().unwrap()).collect(); + let made = LIVE_STATS[2].load(Relaxed) - made0; + assert!(made <= reserved_spares() as u64, "{made} spares made for {THREADS} placements at once"); + for raw in placed { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + assert!(p.spares_in_flight.is_empty(), "all reservations given back"); + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + p.pending_recycles.drain(..).map(|r| r.raw).collect() + } + _ => Vec::new(), + }; + for raw in spares { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// `place_on_pages` with the device's `live` flag set: a new texture waits for its page tables + /// and tops its description up with spares; the next one comes from the pool without a wait; + /// with the flag off, no spares and no wait. + #[test] + fn live_placements_wait_when_new_and_take_spares_without_waiting() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + 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(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.clone(); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let desc = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_COMMON.0 as u32; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(d.Width * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let key = |d: &D3D12_RESOURCE_DESC| ReservedKey::from_desc(&D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*d }, state); + let pending = |k: &ReservedKey| match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.pending_recycles.iter().filter(|r| r.key == *k).count() + p.reserved_pool.count(k), + _ => 0, + }; + let waits = || NEW_WAITS[0].load(Relaxed); + + // 1. new: held behind a gate on the mapping queue, it waits until the gate opens + let d256 = desc(256); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let opener = signal_later(&gate, 1, 60); + let (w0, t0) = (waits(), std::time::Instant::now()); + let first = place(0x4000_0000, &d256); + let took = t0.elapsed(); + opener.join().unwrap(); + assert_eq!(waits(), w0 + 1, "a new reserved texture waits for its page tables"); + assert!(took >= std::time::Duration::from_millis(40), "it waited for the gate: {took:?}"); + assert_eq!(pending(&key(&d256)), 2, "two spares made ahead"); + + // 2. the next one of that description: a spare from the pool, no wait + let (fence, value) = match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => (p.fence.clone(), p.value), + _ => unreachable!(), + }; + assert!(matches!(wait_fence(&fence, value, 5000), FenceWait::Done | FenceWait::Waited(_))); + let w1 = waits(); + let second = place(0x4010_0000, &d256); + assert_eq!(waits(), w1, "a spare from the pool does not wait"); + assert_eq!(pending(&key(&d256)), 2, "and its description is topped up again"); + + // 3. gated off: no spares, no wait + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + p.live = false; + } + let d512 = desc(512); + let w2 = waits(); + let third = place(0x4020_0000, &d512); + assert_eq!(waits(), w2, "no wait when off"); + assert_eq!(pending(&key(&d512)), 0, "no spares when off"); + + drop((first, second, third)); + let _ = queue; + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + let mut v: Vec = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + for k in [key(&d256), key(&d512)] { + while let Some((raw, _)) = p.reserved_pool.take(&k) { + v.push(raw); + } + } + v + } + _ => Vec::new(), + }; + for raw in spares { + assert!(!super::super::real::is_noted_reserved(raw), "a spare is not kept as a title's reserved resource"); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A spare made while the mapping queue is held enters the pool only once a Signal sent + /// after it completes - before that its VA may have no page table entries. + #[test] + fn a_spare_reaches_the_pool_only_after_its_signal() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + 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"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let key = ReservedKey::from_desc(&desc, state); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut r).unwrap(); + let raw = r.unwrap().into_raw() as usize; + let mark = pages.signal_now().unwrap(); + pages.pending_recycles.push_back(PendingRecycle { key, raw, total: 1, mark }); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.count(&key), 0, "a spare behind the held queue is not live yet"); + gate.Signal(1).unwrap(); + let _ = pages.fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default()); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.take(&key), Some((raw, 1))); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + } + #[test] fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; @@ -5806,6 +6820,23 @@ mod tests { } } + /// A watchdog for a test fence that holds a queue: it opens it after 10 s at the latest, so a + /// test that holds a shared device's mapping queue can fail but never hang the test process. + fn open_at_the_latest(fence: &ID3D12Fence) { + struct F(ID3D12Fence); + unsafe impl Send for F {} + let f = F(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_secs(10)); + unsafe { + if f.0.GetCompletedValue() < 1 { + let _ = f.0.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); @@ -5979,4 +7010,56 @@ mod tests { PAGES.lock().unwrap().remove(&dev_key); } } + + /// Spares whose Signal fails are released instead of queued for the pool, no value is published + /// for them, and their reservation is given back. + #[test] + fn spares_without_their_signal_are_released() { + 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"); + }; + 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 mut reached_value = 0; + with(&mut |p| reached_value = p.signal_now().expect("a Signal")); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + 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 key = ReservedKey::from_desc(&desc, 0); + let mut n = 0; + with(&mut |p| n = p.reserve_spares(key, 2)); + assert_eq!(n, 2); + FAIL_SIGNALS.with(|f| f.set(1)); + make_spares(&dev, dev.as_raw(), &desc, 0, std::ptr::null(), key, n); + with(&mut |p| { + assert_eq!(p.value, reached_value, "no value published for the spares"); + assert!(p.pending_recycles.iter().all(|r| r.key != key), "no spares queued without their Signal"); + assert!(!p.spares_in_flight.contains_key(&key), "the reservation is given back"); + assert_eq!(p.reserve_spares(key, 2), 2, "so the next placement reserves them again"); + p.end_spare_reservation(key, 2); + }); + FAIL_SIGNALS.with(|f| f.set(0)); + PAGES.lock().unwrap().remove(&dev_key); + } + } }