upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorlucsoft <mail@lucsoft.de>2026-12-02 14:52:18 +0100
committerGitHub <noreply@github.com>2026-12-02 14:52:18 +0100
commit5eaadb54c14e0fc29597b2a1689d7dbd83491303 (patch)
tree0cd95bb9af1ca9c80c543e57e40fc1926ead619d
parent38ad22daa624b0fe415889f480016099a9aae390 (diff)
D3D12.X: hand the title reserved textures with live page tables (#3553)HEADmainHEAD
* 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. * D3D12.X: require mapping waits before using uploaded textures 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) * 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.
-rw-r--r--crates/xcl/src/hle/d3d12x/lut3d.rs14
-rw-r--r--crates/xcl/src/hle/d3d12x/real.rs13
-rw-r--r--crates/xcl/src/hle/d3d12x/vram.rs1097
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 6f969c56..2f049375 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;
29const WRITES_LOGGED: u64 = 12; 29const WRITES_LOGGED: u64 = 12;
30 30
31pub fn on() -> bool { 31pub fn on() -> bool {
32 #[cfg(test)]
33 if FORCE_ON.load(Ordering::Relaxed) {
34 return true;
35 }
32 super::targets::enabled() 36 super::targets::enabled()
33} 37}
34 38
39/// Tests: track 3D textures as `XCL_DUMP_TARGETS` does.
40#[cfg(test)]
41pub static FORCE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
42
43/// Tests: `res` is one of the 3D textures a dump enumerates.
44#[cfg(test)]
45pub fn tracked(res: usize) -> bool {
46 VOLS.lock().unwrap().contains_key(&res)
47}
48
35/// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`). 49/// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`).
36pub fn created_on() -> bool { 50pub fn created_on() -> bool {
37 on() || super::capture::enabled() 51 on() || super::capture::enabled()
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index fe79a0a7..be99264f 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -4622,6 +4622,19 @@ pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESUL
4622 hr 4622 hr
4623} 4623}
4624 4624
4625/// `res` is no longer one of the reserved resources `note_reserved` keeps (a spare or an evicted one
4626/// of `vram`'s pool, which goes without the title's Release).
4627pub(super) fn forget_reserved(res: usize) {
4628 if let Some(s) = RESERVED.lock().unwrap().as_mut() {
4629 s.remove(&res);
4630 }
4631}
4632
4633#[cfg(test)]
4634pub(super) fn is_noted_reserved(res: usize) -> bool {
4635 RESERVED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res))
4636}
4637
4625unsafe fn is_reserved(res: *mut c_void) -> bool { 4638unsafe fn is_reserved(res: *mut c_void) -> bool {
4626 let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); 4639 let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied());
4627 kept.is_some_and(|k| desc_of(res) == Some(k)) 4640 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 09b7f1b3..cb354d5a 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 {
737 *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) 737 *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0"))
738} 738}
739 739
740/// Hand the title reserved textures whose VA predates the work in flight where possible: the
741/// pool also takes render targets, depth and UAV textures, spares are made ahead per description
742/// (`reserved_spares`), and a placement that still has to make a new one waits for its page
743/// tables (`wait_new_placement`).
744///
745/// This works around amdgpu, the Linux kernel driver: it runs a process's page-table updates in
746/// order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits
747/// for all command submissions of the VM first. So while a frame is in flight, a reserved texture
748/// made after its submit has no page-table entries at all, not even PRT ones, until that frame is
749/// done. A console title may write a descriptor of a texture it has just placed that work it
750/// already submitted reads (on the console the memory is there): a GPU page fault (a retail title on
751/// Wine + RADV). A texture from the pool has had its entries since before: a rebind still lands
752/// late, but the work in flight reads the NULL (PRT) tile meanwhile, not an invalid page.
753///
754/// Windows drivers do not order page-table updates behind running work like that, and the extra
755/// CreateReservedResource calls and waits cost time on the title's thread, so it is on by default
756/// only under Wine on an AMD adapter (`live_decide`). `XCL_LIVE_RESERVED=1` / `0` forces it on or
757/// off anywhere; `XCL_RESERVED_POOL=0` turns it off with the pool.
758fn live_reserved_for(dev: &ID3D12Device) -> bool {
759 let forced = std::env::var("XCL_LIVE_RESERVED").ok();
760 reserved_pool_enabled() && live_decide(forced.as_deref(), crate::util::under_wine(), || unsafe { pick_vendor(vulkan_vendor(dev), || adapter_vendor(dev)) })
761}
762
763/// The GPU's vendor: the Vulkan physical device's when known, else DXGI's. Under Proton, DXVK's
764/// DXGI may report an NVIDIA GPU as AMD (for games that check), while the Vulkan device that
765/// vkd3d-proton drives (and the kernel driver behind it) is the real one.
766fn pick_vendor(vulkan: Option<u32>, dxgi: impl FnOnce() -> Option<u32>) -> Option<u32> {
767 vulkan.or_else(dxgi)
768}
769
770/// `VkPhysicalDeviceProperties::vendorID` of the physical device vkd3d-proton made `dev` on,
771/// through its `ID3D12DXVKInteropDevice` (None: not vkd3d-proton, or no Vulkan loader).
772unsafe fn vulkan_vendor(dev: &ID3D12Device) -> Option<u32> {
773 use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress, LoadLibraryA};
774 // ID3D12DXVKInteropDevice (vkd3d-proton's include/vkd3d_device_vkd3d_ext.idl)
775 const IID_INTEROP: windows::core::GUID = windows::core::GUID::from_u128(0x39da4e09_bd1c_4198_9fae_86bbe3be41fd);
776 let mut interop: *mut c_void = std::ptr::null_mut();
777 if dev.query(&IID_INTEROP, &mut interop).is_err() || interop.is_null() {
778 return None;
779 }
780 let interop = windows::core::IUnknown::from_raw(interop);
781 let vtbl = *(interop.as_raw() as *const *const usize);
782 // IUnknown (3), GetDXGIAdapter, GetInstanceExtensions, GetDeviceExtensions, GetDeviceFeatures,
783 // then GetVulkanHandles(VkInstance *, VkPhysicalDevice *, VkDevice *)
784 type Handles = unsafe extern "system" fn(*mut c_void, *mut usize, *mut usize, *mut usize) -> windows::core::HRESULT;
785 let get_handles: Handles = std::mem::transmute(*vtbl.add(7));
786 let (mut instance, mut physical, mut device) = (0usize, 0usize, 0usize);
787 get_handles(interop.as_raw(), &mut instance, &mut physical, &mut device).ok().ok()?;
788 if physical == 0 {
789 return None;
790 }
791 let mut vulkan = GetModuleHandleA(c"vulkan-1.dll".as_ptr() as *const u8);
792 if vulkan.is_null() {
793 vulkan = LoadLibraryA(c"vulkan-1.dll".as_ptr() as *const u8);
794 }
795 if vulkan.is_null() {
796 return None;
797 }
798 let f = GetProcAddress(vulkan, c"vkGetPhysicalDeviceProperties".as_ptr() as *const u8)?;
799 type Props = unsafe extern "system" fn(usize, *mut u8);
800 let props: Props = std::mem::transmute(f);
801 // VkPhysicalDeviceProperties: apiVersion, driverVersion, vendorID, ... (824 bytes; room to spare)
802 let mut buf = vec![0u8; 4096];
803 props(physical, buf.as_mut_ptr());
804 let vendor = u32::from_le_bytes(buf[8..12].try_into().unwrap());
805 (vendor != 0).then_some(vendor)
806}
807
808/// `live_reserved_for`'s choice: `forced` from `XCL_LIVE_RESERVED`, else Wine on AMD (0x1002).
809fn live_decide(forced: Option<&str>, wine: bool, vendor: impl FnOnce() -> Option<u32>) -> bool {
810 match forced.map(str::trim) {
811 Some("1") => true,
812 Some("0") => false,
813 _ => wine && vendor() == Some(0x1002),
814 }
815}
816
817/// PCI vendor id of `dev`'s adapter.
818unsafe fn adapter_vendor(dev: &ID3D12Device) -> Option<u32> {
819 use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4};
820 let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?;
821 let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?;
822 Some(adapter.GetDesc().ok()?.VendorId)
823}
824
825/// Spare reserved textures kept made ahead per description (`XCL_RESERVED_SPARES`, default 2;
826/// only where `live_reserved_for` holds): made next to a placement, they enter the pool once the
827/// mapping queue passes a Signal after them, which is once their page-table entries exist.
828fn reserved_spares() -> usize {
829 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
830 *N.get_or_init(|| std::env::var("XCL_RESERVED_SPARES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2).min(16))
831}
832
833/// How many spares to make for a description with `have` pooled or pending ones.
834fn spares_to_make(have: usize, want: usize) -> usize {
835 want.saturating_sub(have)
836}
837
838/// (placements from the pool, new ones, spares made, µs spent making them, longest one call)
839static LIVE_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
840
841fn note_live_stats(pooled: bool) {
842 use std::sync::atomic::Ordering::Relaxed;
843 let n = LIVE_STATS[if pooled { 0 } else { 1 }].fetch_add(1, Relaxed) + LIVE_STATS[if pooled { 1 } else { 0 }].load(Relaxed) + 1;
844 if n.is_power_of_two() && n >= 64 {
845 crate::xlog_info!(
846 "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)",
847 LIVE_STATS[0].load(Relaxed),
848 LIVE_STATS[1].load(Relaxed),
849 LIVE_STATS[2].load(Relaxed),
850 LIVE_STATS[3].load(Relaxed) / 1000,
851 LIVE_STATS[4].load(Relaxed)
852 );
853 }
854}
855
856/// How long a placement that had to make a new reserved texture waits on the CPU for a Signal of
857/// the mapping queue sent after it (`XCL_PLACE_MAP_WAIT_MS`, default 1000; 0: no wait). That
858/// Signal completes once the texture's page-table entries exist, which is once the work in flight
859/// before it is done, so the title cannot write a descriptor of it that work reads. Each such
860/// placement waits on its own, also after one that timed out.
861fn place_map_wait_ms() -> u64 {
862 static MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
863 *MS.get_or_init(|| std::env::var("XCL_PLACE_MAP_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000))
864}
865
866/// (new placements that waited, of them timed out, total µs, longest µs)
867static NEW_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
868
869/// How a wait for a fence value ended.
870#[derive(Clone, Copy, PartialEq, Eq, Debug)]
871enum FenceWait {
872 /// it had completed already
873 Done,
874 /// it completed within the time, after this long
875 Waited(std::time::Duration),
876 /// it had not completed after this long
877 TimedOut(std::time::Duration),
878}
879
880/// Wait up to `ms` for `fence` to reach `value`, polling it with short sleeps. No event is
881/// registered with the fence: vkd3d-proton keeps a registered handle until the value is reached,
882/// so an event closed after a timeout could be signalled later under a reused handle.
883unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, ms: u64) -> FenceWait {
884 if super::real::fence_completed(fence) >= value {
885 return FenceWait::Done;
886 }
887 let t0 = std::time::Instant::now();
888 let limit = std::time::Duration::from_millis(ms);
889 loop {
890 if super::real::fence_completed(fence) >= value {
891 return FenceWait::Waited(t0.elapsed());
892 }
893 let left = limit.saturating_sub(t0.elapsed());
894 if left.is_zero() {
895 return FenceWait::TimedOut(t0.elapsed());
896 }
897 std::thread::sleep(left.min(std::time::Duration::from_micros(500)));
898 }
899}
900
901/// How `wait_new_placement` ended.
902#[derive(Clone, Copy, PartialEq, Eq, Debug)]
903enum NewWait {
904 /// `XCL_PLACE_MAP_WAIT_MS=0`: no wait asked for
905 Off,
906 /// a Signal was queued and waited for (or timed out)
907 Signalled(FenceWait),
908 /// no Signal could be queued, twice: nothing tells when the texture's page tables exist
909 Failed,
910}
911
912/// A placement that had to make a new reserved texture: a Signal of the mapping queue after it
913/// (one retry if it cannot be queued), and a wait for it up to `place_map_wait_ms`.
914unsafe fn wait_new_placement(dev_key: usize) -> NewWait {
915 use std::sync::atomic::Ordering::Relaxed;
916 let ms = place_map_wait_ms();
917 if ms == 0 {
918 return NewWait::Off;
919 }
920 let (fence, value) = {
921 let mut g = PAGES.lock().unwrap();
922 let Some(Some(pages)) = g.get_mut(&dev_key) else { return NewWait::Failed };
923 let Some(value) = pages.signal_now().or_else(|| pages.signal_now()) else { return NewWait::Failed };
924 (pages.fence.clone(), value)
925 };
926 let end = wait_fence(&fence, value, ms);
927 let (took, timed_out) = match end {
928 FenceWait::Done => return NewWait::Signalled(end),
929 FenceWait::Waited(d) => (d, false),
930 FenceWait::TimedOut(d) => (d, true),
931 };
932 let us = took.as_micros().min(u64::MAX as u128) as u64;
933 let n = NEW_WAITS[0].fetch_add(1, Relaxed) + 1;
934 if timed_out {
935 NEW_WAITS[1].fetch_add(1, Relaxed);
936 }
937 NEW_WAITS[2].fetch_add(us, Relaxed);
938 NEW_WAITS[3].fetch_max(us, Relaxed);
939 if n.is_power_of_two() || timed_out {
940 crate::xlog_info!(
941 "D3D12.X: new reserved textures waited for their page tables: {n} ({} timed out after {ms} ms), {} ms in all, longest {} ms",
942 NEW_WAITS[1].load(Relaxed),
943 NEW_WAITS[2].load(Relaxed) / 1000,
944 NEW_WAITS[3].load(Relaxed) / 1000
945 );
946 }
947 NewWait::Signalled(end)
948}
949
950/// Spares `place_on_pages` reserved; dropped before `take`, the reservation is given back.
951struct SpareReservation {
952 dev_key: usize,
953 key: Option<ReservedKey>,
954 n: usize,
955}
956
957impl SpareReservation {
958 /// The reserved count, now `make_spares`' to give back.
959 fn take(&mut self) -> usize {
960 std::mem::take(&mut self.n)
961 }
962}
963
964impl Drop for SpareReservation {
965 fn drop(&mut self) {
966 if let (Some(key), true) = (self.key, self.n != 0) {
967 if let Some(Some(pages)) = PAGES.lock().unwrap().get_mut(&self.dev_key) {
968 pages.end_spare_reservation(key, self.n);
969 }
970 }
971 }
972}
973
974/// Make the `n` spare reserved textures like `tiled` that `place_on_pages` reserved under
975/// `PAGES.lock()` (`Pages::spares_in_flight`), and queue them for the pool behind one Signal of
976/// the mapping queue (`reserved_spares`). The reservation is given back whatever happens; spares
977/// without a Signal (it failed) are released instead.
978unsafe fn make_spares(dev: &ID3D12Device, this: *mut c_void, tiled: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, key: ReservedKey, n: usize) {
979 if n == 0 {
980 return;
981 }
982 let started = std::time::Instant::now();
983 let mut made: Vec<(usize, u32)> = Vec::with_capacity(n);
984 for _ in 0..n {
985 let mut p: *mut c_void = std::ptr::null_mut();
986 let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
987 // (the PC creator, not the title-facing one: an idle spare is no resource of the title's,
988 // so nothing that tracks those - `note_reserved`, `lut3d` - may know it; it is registered
989 // when handed out, as a title's released one is: `place_on_pages`, then `device_x`)
990 let hr = super::real::pc_create_reserved_resource(this, tiled as *const _ as usize, state as usize, clear as usize, riid, &mut p);
991 if hr < 0 || p.is_null() {
992 break;
993 }
994 let Some(res) = ID3D12Resource::from_raw_borrowed(&p) else { break };
995 let mut total = 0u32;
996 dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut());
997 made.push((p as usize, total));
998 }
999 let unsignalled = {
1000 let mut g = PAGES.lock().unwrap();
1001 match g.get_mut(&(dev.as_raw() as usize)) {
1002 Some(Some(pages)) => {
1003 pages.end_spare_reservation(key, n);
1004 match (made.is_empty(), pages.signal_now()) {
1005 (true, _) => Vec::new(),
1006 (false, Some(mark)) => {
1007 LIVE_STATS[2].fetch_add(made.len() as u64, std::sync::atomic::Ordering::Relaxed);
1008 PENDING_RECYCLES.fetch_add(made.len(), std::sync::atomic::Ordering::Release);
1009 for &(raw, total) in &made {
1010 pages.pending_recycles.push_back(PendingRecycle { key, raw, total, mark });
1011 }
1012 Vec::new()
1013 }
1014 (false, None) => made,
1015 }
1016 }
1017 _ => made,
1018 }
1019 };
1020 for (raw, _) in unsignalled {
1021 drop(windows::core::IUnknown::from_raw(raw as *mut c_void));
1022 }
1023 let us = started.elapsed().as_micros() as u64;
1024 LIVE_STATS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1025 LIVE_STATS[4].fetch_max(us, std::sync::atomic::Ordering::Relaxed);
1026}
1027
740/// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. 1028/// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture.
741#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] 1029#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
742struct ReservedKey { 1030struct ReservedKey {
@@ -751,11 +1039,29 @@ struct ReservedKey {
751 sample_quality: u32, 1039 sample_quality: u32,
752 flags: i32, 1040 flags: i32,
753 state: u32, 1041 state: u32,
1042 /// the optimized clear value's bytes (`D3D12_CLEAR_VALUE`), all zero without one
1043 clear: [u8; CLEAR_VALUE_BYTES],
754} 1044}
755 1045
1046const CLEAR_VALUE_BYTES: usize = std::mem::size_of::<D3D12_CLEAR_VALUE>();
1047
756impl ReservedKey { 1048impl ReservedKey {
1049 /// `clear`: null or a `D3D12_CLEAR_VALUE`. Only its meaningful bytes count: the format, and
1050 /// the four colour floats, or for a depth-stencil texture the depth float and the stencil
1051 /// byte (the rest of the union is not initialised then).
1052 unsafe fn from_desc_clear(desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void) -> Self {
1053 let mut key = Self::from_desc(desc, state);
1054 if !clear.is_null() {
1055 // (only those bytes are read: the rest may not even be readable memory)
1056 let used = if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { 4 + 4 + 1 } else { CLEAR_VALUE_BYTES };
1057 std::ptr::copy_nonoverlapping(clear as *const u8, key.clear.as_mut_ptr(), used);
1058 }
1059 key
1060 }
1061
757 fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { 1062 fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self {
758 Self { 1063 Self {
1064 clear: [0; CLEAR_VALUE_BYTES],
759 dimension: desc.Dimension.0, 1065 dimension: desc.Dimension.0,
760 alignment: desc.Alignment, 1066 alignment: desc.Alignment,
761 width: desc.Width, 1067 width: desc.Width,
@@ -809,7 +1115,6 @@ impl ReservedPool {
809 } 1115 }
810 } 1116 }
811 1117
812 #[cfg(test)]
813 fn count(&self, key: &ReservedKey) -> usize { 1118 fn count(&self, key: &ReservedKey) -> usize {
814 self.by_key.get(key).map_or(0, Vec::len) 1119 self.by_key.get(key).map_or(0, Vec::len)
815 } 1120 }
@@ -925,7 +1230,14 @@ pub(super) unsafe fn drain_recycled() {
925 PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); 1230 PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release);
926 } 1231 }
927 } 1232 }
1233 release_evicted(evicted);
1234}
1235
1236/// Release reserved textures evicted from the pool (outside `PAGES.lock()`), with nothing of
1237/// XCL's left that names them.
1238unsafe fn release_evicted(evicted: Vec<usize>) {
928 for old in evicted { 1239 for old in evicted {
1240 super::real::forget_reserved(old);
929 let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2)); 1241 let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2));
930 f(old as *mut c_void); 1242 f(old as *mut c_void);
931 } 1243 }
@@ -1812,8 +2124,12 @@ struct Pages {
1812 held_unmaps: Vec<HeldUnmap>, 2124 held_unmaps: Vec<HeldUnmap>,
1813 /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device 2125 /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device
1814 reservable_cache: std::collections::HashMap<(i32, u32), bool>, 2126 reservable_cache: std::collections::HashMap<(i32, u32), bool>,
2127 /// `live_reserved_for` this device
2128 live: bool,
1815 /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) 2129 /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`)
1816 unmarked: bool, 2130 unmarked: bool,
2131 /// spares `place_on_pages` reserved and `make_spares` is making, by description
2132 spares_in_flight: std::collections::HashMap<ReservedKey, usize>,
1817 /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) 2133 /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268)
1818 reserved_pool: ReservedPool, 2134 reserved_pool: ReservedPool,
1819 /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark 2135 /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark
@@ -1959,7 +2275,9 @@ impl Pages {
1959 unmap_fences: std::collections::HashMap::new(), 2275 unmap_fences: std::collections::HashMap::new(),
1960 held_unmaps: Vec::new(), 2276 held_unmaps: Vec::new(),
1961 reservable_cache: std::collections::HashMap::new(), 2277 reservable_cache: std::collections::HashMap::new(),
2278 live: live_reserved_for(dev),
1962 unmarked: false, 2279 unmarked: false,
2280 spares_in_flight: std::collections::HashMap::new(),
1963 reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), 2281 reserved_pool: ReservedPool::new(RESERVED_POOL_MAX),
1964 pending_recycles: std::collections::VecDeque::new(), 2282 pending_recycles: std::collections::VecDeque::new(),
1965 scratch_heaps: Vec::new(), 2283 scratch_heaps: Vec::new(),
@@ -2046,10 +2364,33 @@ impl Pages {
2046 let _ = self.signal_now(); 2364 let _ = self.signal_now();
2047 } 2365 }
2048 2366
2049 /// A Signal of `fence` with the next value now. `value` moves only when the Signal was 2367 /// Reserve the spares `key` lacks (pooled, pending and in-flight ones count), up to `want`.
2050 /// queued: queues wait for `value` (`before_execute`), and a value no Signal reaches would 2368 fn reserve_spares(&mut self, key: ReservedKey, want: usize) -> usize {
2051 /// hold them forever. A mapping whose Signal failed is covered by the next one that succeeds 2369 let in_flight = self.spares_in_flight.get(&key).copied().unwrap_or(0);
2052 /// (the queue runs in order). 2370 let have = self.reserved_pool.count(&key) + self.pending_recycles.iter().filter(|p| p.key == key).count() + in_flight;
2371 let n = spares_to_make(have, want);
2372 if n != 0 {
2373 self.spares_in_flight.insert(key, in_flight + n);
2374 }
2375 n
2376 }
2377
2378 /// Give back `n` reserved spares of `key` (`make_spares` made or failed them).
2379 fn end_spare_reservation(&mut self, key: ReservedKey, n: usize) {
2380 if let Some(v) = self.spares_in_flight.get_mut(&key) {
2381 *v = v.saturating_sub(n);
2382 if *v == 0 {
2383 self.spares_in_flight.remove(&key);
2384 }
2385 }
2386 }
2387
2388 /// A Signal of `fence` with the next value now: its submission waits for every page-table
2389 /// update the process queued before (amdgpu syncs a submit to the VM's last update), so the
2390 /// value completes once reserved textures made before have their entries (`make_spares`).
2391 /// `value` moves only when the Signal was queued: queues wait for `value` (`before_execute`),
2392 /// and a value no Signal reaches would hold them forever. A mapping whose Signal failed is
2393 /// covered by the next one that succeeds (the queue runs in order).
2053 unsafe fn signal_now(&mut self) -> Option<u64> { 2394 unsafe fn signal_now(&mut self) -> Option<u64> {
2054 let next = self.value + 1; 2395 let next = self.value + 1;
2055 #[cfg(test)] 2396 #[cfg(test)]
@@ -2464,20 +2805,41 @@ unsafe fn place_on_pages(
2464 } 2805 }
2465 }; 2806 };
2466 let dev_key = dev.as_raw() as usize; 2807 let dev_key = dev.as_raw() as usize;
2467 let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) 2808 let live;
2468 .then(|| ReservedKey::from_desc(&tiled, state)); 2809 let recycle_key;
2469 let mut pooled = None; 2810 let mut pooled = None;
2811 let mut spares = 0usize;
2812 let mut evicted = Vec::new();
2470 let is_reservable = { 2813 let is_reservable = {
2471 let mut g = PAGES.lock().unwrap(); 2814 let mut g = PAGES.lock().unwrap();
2472 let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; 2815 let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?;
2473 let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); 2816 let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled));
2817 live = pages.live;
2818 // (`live_reserved_for`: render targets, depth and UAV textures, those with a clear value, too)
2819 recycle_key = if live {
2820 Some(ReservedKey::from_desc_clear(&tiled, state, clear))
2821 } else {
2822 (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()).then(|| ReservedKey::from_desc(&tiled, state))
2823 };
2474 if ok { 2824 if ok {
2475 if let Some(key) = recycle_key { 2825 if let Some(key) = recycle_key {
2826 if live && pending_recycles() {
2827 pages.mark_pending_recycles();
2828 let before = pages.pending_recycles.len();
2829 evicted = promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue());
2830 PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release);
2831 }
2476 pooled = pages.reserved_pool.take(&key); 2832 pooled = pages.reserved_pool.take(&key);
2833 if live {
2834 spares = pages.reserve_spares(key, reserved_spares());
2835 }
2477 } 2836 }
2478 } 2837 }
2479 ok 2838 ok
2480 }; 2839 };
2840 release_evicted(evicted);
2841 // (given back on every way out of here but `make_spares`)
2842 let mut reservation = SpareReservation { dev_key, key: recycle_key, n: spares };
2481 if !is_reservable { 2843 if !is_reservable {
2482 log("no tiled support for its format or sample count"); 2844 log("no tiled support for its format or sample count");
2483 return None; 2845 return None;
@@ -2530,6 +2892,16 @@ unsafe fn place_on_pages(
2530 None 2892 None
2531 }; 2893 };
2532 let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); 2894 let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none()));
2895 // (no live one in the pool: wait until its VA has page-table entries, before the pages know
2896 // it. A texture with lazy levels queues no mapping here, so that Signal is all that tells;
2897 // when none can be queued the placement fails as a failed creation does: nothing is mapped
2898 // or noted yet, and the spare reservation goes back with `reservation`.)
2899 if cached_total.is_none() && live && wait_new_placement(dev_key) == NewWait::Failed {
2900 crate::xlog_warn!("D3D12.X: texture at {va:#x}: no Signal of the mapping queue after its new reserved texture - not placed on pages");
2901 drop(windows::core::IUnknown::from_raw(raw));
2902 *ppv = std::ptr::null_mut();
2903 return None;
2904 }
2533 let bound = { 2905 let bound = {
2534 let mut g = PAGES.lock().unwrap(); 2906 let mut g = PAGES.lock().unwrap();
2535 if let Some(Some(pages)) = g.get_mut(&dev_key) { 2907 if let Some(Some(pages)) = g.get_mut(&dev_key) {
@@ -2564,6 +2936,10 @@ unsafe fn place_on_pages(
2564 for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) { 2936 for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) {
2565 super::late_release::hold_unmap(r); 2937 super::late_release::hold_unmap(r);
2566 } 2938 }
2939 if let (true, Some(key)) = (live, recycle_key) {
2940 note_live_stats(cached_total.is_some());
2941 make_spares(dev, this, &tiled, state, clear, key, reservation.take());
2942 }
2567 Some(hr) 2943 Some(hr)
2568} 2944}
2569 2945
@@ -5666,6 +6042,644 @@ mod tests {
5666 } 6042 }
5667 6043
5668 #[test] 6044 #[test]
6045 fn reserved_key_tells_clear_values_apart_and_spares_top_up() {
6046 let desc = D3D12_RESOURCE_DESC {
6047 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6048 Width: 128,
6049 Height: 128,
6050 DepthOrArraySize: 1,
6051 MipLevels: 1,
6052 Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
6053 SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6054 Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE,
6055 Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
6056 ..Default::default()
6057 };
6058 let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32;
6059 let black = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 0.0, 1.0] } };
6060 let white = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [1.0; 4] } };
6061 let (none, k_black, k_white, k_black2) = unsafe {
6062 (
6063 ReservedKey::from_desc_clear(&desc, state, std::ptr::null()),
6064 ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void),
6065 ReservedKey::from_desc_clear(&desc, state, &white as *const _ as *const c_void),
6066 ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void),
6067 )
6068 };
6069 assert_eq!(none, ReservedKey::from_desc(&desc, state));
6070 assert_ne!(none, k_black);
6071 assert_ne!(k_black, k_white);
6072 assert_eq!(k_black, k_black2);
6073
6074 let mut pool = ReservedPool::new(8);
6075 assert_eq!(pool.count(&k_black), 0);
6076 assert_eq!(pool.push(k_black, 0x1000, 1), None);
6077 assert_eq!(pool.push(k_black, 0x2000, 1), None);
6078 assert_eq!(pool.count(&k_black), 2);
6079 assert_eq!(pool.count(&k_white), 0);
6080 assert!(pool.take(&k_white).is_none());
6081 assert!(pool.take(&k_black).is_some());
6082 assert_eq!(pool.count(&k_black), 1);
6083
6084 assert_eq!(spares_to_make(0, 2), 2);
6085 assert_eq!(spares_to_make(1, 2), 1);
6086 assert_eq!(spares_to_make(5, 2), 0);
6087 assert_eq!(spares_to_make(0, 0), 0);
6088 }
6089
6090 #[test]
6091 fn live_reserved_is_on_by_default_only_under_wine_on_amd() {
6092 assert!(live_decide(None, true, || Some(0x1002)));
6093 assert!(!live_decide(None, true, || Some(0x10de)), "NVIDIA under Wine");
6094 assert!(!live_decide(None, false, || Some(0x1002)), "AMD on Windows");
6095 assert!(!live_decide(None, true, || None), "no adapter");
6096 assert!(!live_decide(Some(""), false, || Some(0x10de)));
6097 assert!(live_decide(Some("1"), false, || Some(0x10de)), "forced on");
6098 assert!(live_decide(Some(" 1 "), false, || None), "forced on");
6099 assert!(!live_decide(Some("0"), true, || Some(0x1002)), "forced off");
6100 // (forced either way: the adapter is not even asked)
6101 assert!(live_decide(Some("1"), false, || panic!("asked")));
6102 // DXVK's DXGI says AMD, the Vulkan device is NVIDIA's: off
6103 assert!(!live_decide(None, true, || pick_vendor(Some(0x10de), || Some(0x1002))));
6104 assert!(live_decide(None, true, || pick_vendor(Some(0x1002), || Some(0x10de))));
6105 // no Vulkan device known: DXGI's vendor
6106 assert!(live_decide(None, true, || pick_vendor(None, || Some(0x1002))));
6107 }
6108
6109 /// Under vkd3d-proton the vendor comes from the Vulkan physical device.
6110 #[test]
6111 fn the_vendor_comes_from_vkd3d_protons_vulkan_device() {
6112 unsafe {
6113 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6114 return crate::gpu::recomp::runner::skip_test("no GPU");
6115 };
6116 match vulkan_vendor(&dev) {
6117 Some(v) => assert!(v != 0 && Some(v) == pick_vendor(Some(v), || None)),
6118 None => assert!(!crate::util::under_wine(), "vkd3d-proton under Wine has a Vulkan device"),
6119 }
6120 }
6121 }
6122
6123 #[test]
6124 fn a_depth_clear_key_ignores_the_union_tail() {
6125 let desc = D3D12_RESOURCE_DESC {
6126 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6127 Width: 256,
6128 Height: 256,
6129 DepthOrArraySize: 1,
6130 MipLevels: 1,
6131 Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT,
6132 SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6133 Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE,
6134 Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
6135 ..Default::default()
6136 };
6137 let state = D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32;
6138 // format DXGI_FORMAT_D32_FLOAT (40), depth 1.0, stencil 7, then garbage
6139 let clear = |stencil: u8, tail: u8| {
6140 let mut b = [tail; CLEAR_VALUE_BYTES];
6141 b[..4].copy_from_slice(&40u32.to_le_bytes());
6142 b[4..8].copy_from_slice(&1.0f32.to_le_bytes());
6143 b[8] = stencil;
6144 b
6145 };
6146 let key = |b: &[u8; CLEAR_VALUE_BYTES]| unsafe { ReservedKey::from_desc_clear(&desc, state, b.as_ptr() as *const c_void) };
6147 assert_eq!(key(&clear(7, 0x00)), key(&clear(7, 0xCD)), "the uninitialised tail must not split keys");
6148 assert_ne!(key(&clear(7, 0x00)), key(&clear(8, 0x00)), "the stencil value counts");
6149 let mut deeper = clear(7, 0);
6150 deeper[4..8].copy_from_slice(&0.0f32.to_le_bytes());
6151 assert_ne!(key(&clear(7, 0)), key(&deeper), "the depth value counts");
6152 // a colour clear uses all four floats
6153 let mut colour_desc = desc;
6154 colour_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
6155 let mut c1 = clear(7, 0);
6156 let mut c2 = c1;
6157 c2[19] = 0x3F;
6158 c1[19] = 0x00;
6159 unsafe {
6160 assert_ne!(
6161 ReservedKey::from_desc_clear(&colour_desc, state, c1.as_ptr() as *const c_void),
6162 ReservedKey::from_desc_clear(&colour_desc, state, c2.as_ptr() as *const c_void),
6163 "a colour clear's alpha counts"
6164 );
6165 }
6166 }
6167
6168 /// The mapping queue's fence of `dev_key`.
6169 fn queue_fence(dev_key: usize) -> ID3D12Fence {
6170 match PAGES.lock().unwrap().get(&dev_key) {
6171 Some(Some(p)) => p.fence.clone(),
6172 _ => panic!("no pages"),
6173 }
6174 }
6175
6176 /// Owns a fence for a thread that signals it later.
6177 struct SendFence(ID3D12Fence);
6178 unsafe impl Send for SendFence {}
6179
6180 fn signal_later(fence: &ID3D12Fence, value: u64, after_ms: u64) -> std::thread::JoinHandle<()> {
6181 let f = SendFence(fence.clone());
6182 std::thread::spawn(move || {
6183 let f = f;
6184 std::thread::sleep(std::time::Duration::from_millis(after_ms));
6185 unsafe { f.0.Signal(value).unwrap() };
6186 })
6187 }
6188
6189 #[test]
6190 fn wait_fence_returns_at_the_signal_or_times_out() {
6191 unsafe {
6192 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6193 return crate::gpu::recomp::runner::skip_test("no GPU");
6194 };
6195 let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
6196 assert_eq!(wait_fence(&fence, 0, 1000), FenceWait::Done);
6197 let t = signal_later(&fence, 1, 40);
6198 match wait_fence(&fence, 1, 5000) {
6199 FenceWait::Waited(d) => assert!(d >= std::time::Duration::from_millis(30) && d < std::time::Duration::from_millis(4000), "{d:?}"),
6200 other => panic!("{other:?}"),
6201 }
6202 t.join().unwrap();
6203 match wait_fence(&fence, 2, 30) {
6204 FenceWait::TimedOut(d) => assert!(d >= std::time::Duration::from_millis(25), "{d:?}"),
6205 other => panic!("{other:?}"),
6206 }
6207 // the timed-out wait left nothing registered: a new event is not signalled when the
6208 // fence reaches that value afterwards
6209 use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
6210 let event = CreateEventW(None, false, false, None).unwrap();
6211 fence.Signal(2).unwrap();
6212 let got = WaitForSingleObject(event, 50);
6213 let _ = windows::Win32::Foundation::CloseHandle(event);
6214 assert_eq!(got, windows::Win32::Foundation::WAIT_TIMEOUT, "an old wait signalled a new event");
6215 }
6216 }
6217
6218 /// A clear value is read only as far as it means something: a depth-stencil one that ends
6219 /// right before an unreadable page.
6220 #[test]
6221 fn a_depth_clear_key_reads_only_its_prefix() {
6222 use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE};
6223 unsafe {
6224 let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8;
6225 assert!(!base.is_null());
6226 let mut old = 0;
6227 assert!(VirtualProtect(base.add(0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old) != 0);
6228 let at = base.add(0x1000 - 9);
6229 at.copy_from_nonoverlapping([40u8, 0, 0, 0].as_ptr(), 4);
6230 at.add(4).copy_from_nonoverlapping(1.0f32.to_le_bytes().as_ptr(), 4);
6231 *at.add(8) = 7;
6232 let desc = D3D12_RESOURCE_DESC {
6233 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6234 Width: 64,
6235 Height: 64,
6236 DepthOrArraySize: 1,
6237 MipLevels: 1,
6238 Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT,
6239 SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6240 Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
6241 ..Default::default()
6242 };
6243 let key = ReservedKey::from_desc_clear(&desc, 0, at as *const c_void);
6244 assert_eq!(&key.clear[..9], std::slice::from_raw_parts(at, 9));
6245 assert!(key.clear[9..].iter().all(|&b| b == 0));
6246 VirtualFree(base as *mut c_void, 0, MEM_RELEASE);
6247 }
6248 }
6249
6250 /// With 3D textures tracked for dumps (`XCL_DUMP_TARGETS`): spares are made by the PC creator,
6251 /// so an idle one is neither a title's reserved resource nor a dumped 3D texture, and one
6252 /// released from the pool leaves nothing the dump enumerates; a spare handed to the title by
6253 /// a placement is tracked.
6254 #[test]
6255 fn spares_stay_out_of_dump_tracking_until_handed_out() {
6256 use std::sync::atomic::Ordering::Relaxed;
6257 let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
6258 unsafe {
6259 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6260 return crate::gpu::recomp::runner::skip_test("no GPU");
6261 };
6262 super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
6263 let Some(uma) = crate::gpu::uma::get() else {
6264 return crate::gpu::recomp::runner::skip_test("no UMA");
6265 };
6266 let dev_key = dev.as_raw() as usize;
6267 let Some(mut pages) = Pages::new(&dev) else {
6268 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
6269 };
6270 pages.live = true;
6271 PAGES.lock().unwrap().insert(dev_key, Some(pages));
6272 super::super::lut3d::FORCE_ON.store(true, Relaxed);
6273 let console = super::super::title_textures::tests::console_desc(4, 32, 32, 32, 1, 28, 0x105);
6274 let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
6275 let Some(base) = uma.alloc(4 << 20, 0x1_0000).map(|p| p as usize) else {
6276 super::super::lut3d::FORCE_ON.store(false, Relaxed);
6277 PAGES.lock().unwrap().remove(&dev_key);
6278 return crate::gpu::recomp::runner::skip_test("no UMA block");
6279 };
6280 let place = |va: usize| -> Option<ID3D12Resource> {
6281 let mut p = std::ptr::null_mut();
6282 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);
6283 (hr >= 0 && !p.is_null()).then(|| ID3D12Resource::from_raw(p))
6284 };
6285 let with = |f: &mut dyn FnMut(&mut Pages)| {
6286 if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) {
6287 f(p)
6288 }
6289 };
6290 let pending = || {
6291 let mut v = Vec::new();
6292 with(&mut |p| v = p.pending_recycles.iter().map(|r| (r.key, r.raw)).collect());
6293 v
6294 };
6295
6296 // 1. a new 3D texture: tracked; the spares made for its description are not
6297 let Some(first) = place(base) else {
6298 super::super::lut3d::FORCE_ON.store(false, Relaxed);
6299 PAGES.lock().unwrap().remove(&dev_key);
6300 return crate::gpu::recomp::runner::skip_test("no reserved 3D texture on pages here");
6301 };
6302 assert!(first.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D);
6303 assert!(super::super::lut3d::tracked(first.as_raw() as usize), "the title's 3D texture is tracked");
6304 let spares = pending();
6305 assert!(!spares.is_empty(), "spares were made for it");
6306 for &(_, raw) in &spares {
6307 assert!(!super::super::lut3d::tracked(raw), "an idle spare is not dumped");
6308 assert!(!super::super::real::is_noted_reserved(raw), "nor kept as a title's reserved resource");
6309 }
6310
6311 // 2. its spares reach the pool; one is released as an eviction releases it: the dump's
6312 // enumeration does not know it
6313 with(&mut |p| {
6314 let last = p.signal_now().unwrap();
6315 assert!(matches!(wait_fence(&p.fence, last, 5000), FenceWait::Done | FenceWait::Waited(_)));
6316 });
6317 drain_recycled();
6318 let key = spares[0].0;
6319 let mut evicted = None;
6320 with(&mut |p| evicted = p.reserved_pool.take(&key));
6321 let (evicted, _) = evicted.expect("a spare in the pool");
6322 release_evicted(vec![evicted]);
6323 assert!(!super::super::lut3d::tracked(evicted));
6324 assert!(super::super::lut3d::to_dump().iter().all(|(_, r, _, _)| r.as_raw() as usize != evicted), "a released spare is not enumerated");
6325
6326 // 3. the next placement of that description takes a spare from the pool: tracked now
6327 let left: Vec<usize> = spares.iter().map(|s| s.1).filter(|&r| r != evicted).collect();
6328 let second = place(base + (1 << 20)).expect("placed");
6329 let raw2 = second.as_raw() as usize;
6330 assert!(left.contains(&raw2), "the placement took a spare");
6331 assert!(super::super::lut3d::tracked(raw2), "a spare handed to the title is tracked");
6332 assert!(super::super::real::is_noted_reserved(raw2), "and kept as its reserved resource");
6333
6334 super::super::lut3d::FORCE_ON.store(false, Relaxed);
6335 drop((first, second));
6336 let rest: Vec<usize> = {
6337 let mut v = Vec::new();
6338 with(&mut |p| {
6339 let last = p.signal_now().unwrap();
6340 let _ = wait_fence(&p.fence, last, 5000);
6341 v = p.pending_recycles.drain(..).map(|r| r.raw).collect();
6342 while let Some((raw, _)) = p.reserved_pool.take(&key) {
6343 v.push(raw);
6344 }
6345 });
6346 v
6347 };
6348 release_evicted(rest);
6349 PAGES.lock().unwrap().remove(&dev_key);
6350 }
6351 }
6352
6353 /// A cold texture with lazy levels queues no mapping, so the Signal after its new reserved
6354 /// texture is all that says its page tables exist: when it cannot be queued a retry is, and
6355 /// waited for; when that fails too the placement fails with nothing left behind.
6356 #[test]
6357 fn a_lazy_placement_without_a_readiness_signal_is_not_handed_out() {
6358 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
6359 let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
6360 unsafe {
6361 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6362 return crate::gpu::recomp::runner::skip_test("no GPU");
6363 };
6364 super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
6365 let dev_key = dev.as_raw() as usize;
6366 let Some(mut pages) = Pages::new(&dev) else {
6367 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
6368 };
6369 pages.live = true;
6370 let queue = pages.queue.clone();
6371 PAGES.lock().unwrap().insert(dev_key, Some(pages));
6372 let with = |f: &mut dyn FnMut(&mut Pages)| {
6373 if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) {
6374 f(p)
6375 }
6376 };
6377 let desc = |w: u64| D3D12_RESOURCE_DESC {
6378 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6379 Width: w,
6380 Height: 512,
6381 DepthOrArraySize: 1,
6382 MipLevels: 10,
6383 Format: DXGI_FORMAT_R8G8B8A8_UNORM,
6384 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6385 Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
6386 Flags: D3D12_RESOURCE_FLAG_NONE,
6387 ..Default::default()
6388 };
6389 let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
6390 let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> (Option<HRESULT>, *mut c_void) {
6391 let mut p = std::ptr::null_mut();
6392 let hr = place_on_pages(&dev, dev.as_raw(), va, d, 0, std::ptr::null(), Some(4 << 20), false, true, riid, &mut p);
6393 (hr, p)
6394 };
6395 let snapshot = || {
6396 let mut t = (0, 0, 0, 0);
6397 with(&mut |p| t = (p.value, p.targets.len(), p.pending_recycles.len(), p.spares_in_flight.len()));
6398 t
6399 };
6400
6401 // 1. the first Signal fails, the retry is queued behind a held mapping queue: the
6402 // placement returns only once that retry has completed
6403 let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
6404 queue.Wait(&gate, 1).unwrap();
6405 open_at_the_latest(&gate);
6406 let (v0, ..) = snapshot();
6407 FAIL_SIGNALS.with(|f| f.set(1));
6408 let opener = signal_later(&gate, 1, 80);
6409 let t0 = std::time::Instant::now();
6410 let (hr, p) = place(0x7000_0000, &desc(512));
6411 let took = t0.elapsed();
6412 FAIL_SIGNALS.with(|f| f.set(0));
6413 opener.join().unwrap();
6414 assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed after the retry");
6415 assert!(took >= std::time::Duration::from_millis(60), "it waited for the retried Signal: {took:?}");
6416 let mut retried = 0;
6417 with(&mut |pg| retried = pg.value);
6418 assert!(retried > v0, "a later Signal was queued");
6419 assert!(matches!(wait_fence(&queue_fence(dev_key), v0 + 1, 0), FenceWait::Done), "and completed before the title got the texture");
6420 assert!(has_lazy_levels(p as usize), "a lazy-level texture");
6421 let first = ID3D12Resource::from_raw(p);
6422
6423 // 2. no Signal at all: no resource, nothing kept of it (the spares of 1. in the pool
6424 // first, so nothing moves meanwhile)
6425 with(&mut |pg| {
6426 let v = pg.value;
6427 let _ = wait_fence(&pg.fence, v, 5000);
6428 });
6429 drain_recycled();
6430 let before = snapshot();
6431 let placed_before = PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len());
6432 FAIL_SIGNALS.with(|f| f.set(2));
6433 let (hr, p) = place(0x7100_0000, &desc(256));
6434 FAIL_SIGNALS.with(|f| f.set(0));
6435 assert!(hr.is_none() && p.is_null(), "no texture without a readiness Signal");
6436 assert_eq!(snapshot(), before, "no value, target, spare or reservation left behind");
6437 assert_eq!(PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()), placed_before);
6438
6439 drop(first);
6440 let spares: Vec<usize> = {
6441 let mut v = Vec::new();
6442 with(&mut |pg| {
6443 let last = pg.signal_now().unwrap();
6444 let _ = wait_fence(&pg.fence, last, 5000);
6445 v = pg.pending_recycles.drain(..).map(|r| r.raw).collect();
6446 v.extend(pg.reserved_pool.by_key.drain().flat_map(|(_, b)| b.into_iter().map(|e| e.0)));
6447 pg.reserved_pool.live_gen.clear();
6448 pg.reserved_pool.order.clear();
6449 });
6450 v
6451 };
6452 release_evicted(spares);
6453 PAGES.lock().unwrap().remove(&dev_key);
6454 }
6455 }
6456
6457 /// Placements of one description at once reserve their spares under the lock: together they
6458 /// make no more than `reserved_spares`. The mapping queue is held, so no spare reaches the pool
6459 /// (and gets topped up again) meanwhile.
6460 #[test]
6461 fn concurrent_placements_make_at_most_the_spares_of_one() {
6462 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
6463 use std::sync::atomic::Ordering::Relaxed;
6464 let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
6465 unsafe {
6466 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6467 return crate::gpu::recomp::runner::skip_test("no GPU");
6468 };
6469 super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
6470 let dev_key = dev.as_raw() as usize;
6471 let Some(mut pages) = Pages::new(&dev) else {
6472 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
6473 };
6474 pages.live = true;
6475 let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
6476 pages.queue.Wait(&gate, 1).unwrap();
6477 open_at_the_latest(&gate);
6478 PAGES.lock().unwrap().insert(dev_key, Some(pages));
6479 const THREADS: usize = 4;
6480 let made0 = LIVE_STATS[2].load(Relaxed);
6481 let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS));
6482 struct SendDev(ID3D12Device);
6483 unsafe impl Send for SendDev {}
6484 let workers: Vec<_> = (0..THREADS)
6485 .map(|i| {
6486 let (d, b) = (SendDev(dev.clone()), barrier.clone());
6487 std::thread::spawn(move || {
6488 let d = d;
6489 let desc = D3D12_RESOURCE_DESC {
6490 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6491 Width: 256,
6492 Height: 256,
6493 DepthOrArraySize: 1,
6494 MipLevels: 1,
6495 Format: DXGI_FORMAT_R8G8B8A8_UNORM,
6496 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6497 ..Default::default()
6498 };
6499 let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
6500 let mut p = std::ptr::null_mut();
6501 b.wait();
6502 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);
6503 assert!(hr.is_some_and(|h| h >= 0) && !p.is_null());
6504 p as usize
6505 })
6506 })
6507 .collect();
6508 // (every placement waits for its page tables behind the gate; open it once all reserved)
6509 std::thread::sleep(std::time::Duration::from_millis(300));
6510 gate.Signal(1).unwrap();
6511 let placed: Vec<usize> = workers.into_iter().map(|w| w.join().unwrap()).collect();
6512 let made = LIVE_STATS[2].load(Relaxed) - made0;
6513 assert!(made <= reserved_spares() as u64, "{made} spares made for {THREADS} placements at once");
6514 for raw in placed {
6515 drop(ID3D12Resource::from_raw(raw as *mut c_void));
6516 }
6517 let spares: Vec<usize> = match PAGES.lock().unwrap().get_mut(&dev_key) {
6518 Some(Some(p)) => {
6519 assert!(p.spares_in_flight.is_empty(), "all reservations given back");
6520 let last = p.signal_now().unwrap();
6521 let _ = wait_fence(&p.fence, last, 5000);
6522 p.pending_recycles.drain(..).map(|r| r.raw).collect()
6523 }
6524 _ => Vec::new(),
6525 };
6526 for raw in spares {
6527 drop(ID3D12Resource::from_raw(raw as *mut c_void));
6528 }
6529 PAGES.lock().unwrap().remove(&dev_key);
6530 }
6531 }
6532
6533 /// `place_on_pages` with the device's `live` flag set: a new texture waits for its page tables
6534 /// and tops its description up with spares; the next one comes from the pool without a wait;
6535 /// with the flag off, no spares and no wait.
6536 #[test]
6537 fn live_placements_wait_when_new_and_take_spares_without_waiting() {
6538 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
6539 use std::sync::atomic::Ordering::Relaxed;
6540 let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
6541 unsafe {
6542 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6543 return crate::gpu::recomp::runner::skip_test("no GPU");
6544 };
6545 super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
6546 let dev_key = dev.as_raw() as usize;
6547 let Some(mut pages) = Pages::new(&dev) else {
6548 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
6549 };
6550 pages.live = true;
6551 let queue = pages.queue.clone();
6552 PAGES.lock().unwrap().insert(dev_key, Some(pages));
6553 let desc = |w: u64| D3D12_RESOURCE_DESC {
6554 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6555 Width: w,
6556 Height: 256,
6557 DepthOrArraySize: 1,
6558 MipLevels: 1,
6559 Format: DXGI_FORMAT_R8G8B8A8_UNORM,
6560 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6561 Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
6562 Flags: D3D12_RESOURCE_FLAG_NONE,
6563 ..Default::default()
6564 };
6565 let state = D3D12_RESOURCE_STATE_COMMON.0 as u32;
6566 let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID;
6567 let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> ID3D12Resource {
6568 let mut p = std::ptr::null_mut();
6569 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);
6570 assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed at {va:#x}");
6571 ID3D12Resource::from_raw(p)
6572 };
6573 let key = |d: &D3D12_RESOURCE_DESC| ReservedKey::from_desc(&D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*d }, state);
6574 let pending = |k: &ReservedKey| match PAGES.lock().unwrap().get(&dev_key) {
6575 Some(Some(p)) => p.pending_recycles.iter().filter(|r| r.key == *k).count() + p.reserved_pool.count(k),
6576 _ => 0,
6577 };
6578 let waits = || NEW_WAITS[0].load(Relaxed);
6579
6580 // 1. new: held behind a gate on the mapping queue, it waits until the gate opens
6581 let d256 = desc(256);
6582 let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
6583 queue.Wait(&gate, 1).unwrap();
6584 open_at_the_latest(&gate);
6585 let opener = signal_later(&gate, 1, 60);
6586 let (w0, t0) = (waits(), std::time::Instant::now());
6587 let first = place(0x4000_0000, &d256);
6588 let took = t0.elapsed();
6589 opener.join().unwrap();
6590 assert_eq!(waits(), w0 + 1, "a new reserved texture waits for its page tables");
6591 assert!(took >= std::time::Duration::from_millis(40), "it waited for the gate: {took:?}");
6592 assert_eq!(pending(&key(&d256)), 2, "two spares made ahead");
6593
6594 // 2. the next one of that description: a spare from the pool, no wait
6595 let (fence, value) = match PAGES.lock().unwrap().get(&dev_key) {
6596 Some(Some(p)) => (p.fence.clone(), p.value),
6597 _ => unreachable!(),
6598 };
6599 assert!(matches!(wait_fence(&fence, value, 5000), FenceWait::Done | FenceWait::Waited(_)));
6600 let w1 = waits();
6601 let second = place(0x4010_0000, &d256);
6602 assert_eq!(waits(), w1, "a spare from the pool does not wait");
6603 assert_eq!(pending(&key(&d256)), 2, "and its description is topped up again");
6604
6605 // 3. gated off: no spares, no wait
6606 if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) {
6607 p.live = false;
6608 }
6609 let d512 = desc(512);
6610 let w2 = waits();
6611 let third = place(0x4020_0000, &d512);
6612 assert_eq!(waits(), w2, "no wait when off");
6613 assert_eq!(pending(&key(&d512)), 0, "no spares when off");
6614
6615 drop((first, second, third));
6616 let _ = queue;
6617 let spares: Vec<usize> = match PAGES.lock().unwrap().get_mut(&dev_key) {
6618 Some(Some(p)) => {
6619 let last = p.signal_now().unwrap();
6620 let _ = wait_fence(&p.fence, last, 5000);
6621 let mut v: Vec<usize> = p.pending_recycles.drain(..).map(|r| r.raw).collect();
6622 for k in [key(&d256), key(&d512)] {
6623 while let Some((raw, _)) = p.reserved_pool.take(&k) {
6624 v.push(raw);
6625 }
6626 }
6627 v
6628 }
6629 _ => Vec::new(),
6630 };
6631 for raw in spares {
6632 assert!(!super::super::real::is_noted_reserved(raw), "a spare is not kept as a title's reserved resource");
6633 drop(ID3D12Resource::from_raw(raw as *mut c_void));
6634 }
6635 PAGES.lock().unwrap().remove(&dev_key);
6636 }
6637 }
6638
6639 /// A spare made while the mapping queue is held enters the pool only once a Signal sent
6640 /// after it completes - before that its VA may have no page table entries.
6641 #[test]
6642 fn a_spare_reaches_the_pool_only_after_its_signal() {
6643 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
6644 unsafe {
6645 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
6646 return crate::gpu::recomp::runner::skip_test("no GPU");
6647 };
6648 let Some(mut pages) = Pages::new(&dev) else {
6649 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
6650 };
6651 let desc = D3D12_RESOURCE_DESC {
6652 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
6653 Width: 128,
6654 Height: 128,
6655 DepthOrArraySize: 1,
6656 MipLevels: 1,
6657 Format: DXGI_FORMAT_R8G8B8A8_UNORM,
6658 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
6659 Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE,
6660 Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
6661 ..Default::default()
6662 };
6663 let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32;
6664 let key = ReservedKey::from_desc(&desc, state);
6665 let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
6666 pages.queue.Wait(&gate, 1).unwrap();
6667 let mut r: Option<ID3D12Resource> = None;
6668 dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut r).unwrap();
6669 let raw = r.unwrap().into_raw() as usize;
6670 let mark = pages.signal_now().unwrap();
6671 pages.pending_recycles.push_back(PendingRecycle { key, raw, total: 1, mark });
6672 assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty());
6673 assert_eq!(pages.reserved_pool.count(&key), 0, "a spare behind the held queue is not live yet");
6674 gate.Signal(1).unwrap();
6675 let _ = pages.fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default());
6676 assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty());
6677 assert_eq!(pages.reserved_pool.take(&key), Some((raw, 1)));
6678 drop(ID3D12Resource::from_raw(raw as *mut c_void));
6679 }
6680 }
6681
6682 #[test]
5669 fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { 6683 fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() {
5670 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; 6684 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC};
5671 unsafe { 6685 unsafe {
@@ -5953,6 +6967,23 @@ mod tests {
5953 } 6967 }
5954 } 6968 }
5955 6969
6970 /// A watchdog for a test fence that holds a queue: it opens it after 10 s at the latest, so a
6971 /// test that holds a shared device's mapping queue can fail but never hang the test process.
6972 fn open_at_the_latest(fence: &ID3D12Fence) {
6973 struct F(ID3D12Fence);
6974 unsafe impl Send for F {}
6975 let f = F(fence.clone());
6976 std::thread::spawn(move || {
6977 let f = f;
6978 std::thread::sleep(std::time::Duration::from_secs(10));
6979 unsafe {
6980 if f.0.GetCompletedValue() < 1 {
6981 let _ = f.0.Signal(1);
6982 }
6983 }
6984 });
6985 }
6986
5956 /// `fence` reaches `value` within `ms` (polled). 6987 /// `fence` reaches `value` within `ms` (polled).
5957 fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool { 6988 fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool {
5958 let end = std::time::Instant::now() + std::time::Duration::from_millis(ms); 6989 let end = std::time::Instant::now() + std::time::Duration::from_millis(ms);
@@ -6126,4 +7157,56 @@ mod tests {
6126 PAGES.lock().unwrap().remove(&dev_key); 7157 PAGES.lock().unwrap().remove(&dev_key);
6127 } 7158 }
6128 } 7159 }
7160
7161 /// Spares whose Signal fails are released instead of queued for the pool, no value is published
7162 /// for them, and their reservation is given back.
7163 #[test]
7164 fn spares_without_their_signal_are_released() {
7165 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
7166 let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
7167 unsafe {
7168 let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else {
7169 return crate::gpu::recomp::runner::skip_test("no GPU");
7170 };
7171 super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device);
7172 let dev_key = dev.as_raw() as usize;
7173 let Some(pages) = Pages::new(&dev) else {
7174 return crate::gpu::recomp::runner::skip_test("tiled tier < 2");
7175 };
7176 PAGES.lock().unwrap().insert(dev_key, Some(pages));
7177 let with = |f: &mut dyn FnMut(&mut Pages)| {
7178 if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) {
7179 f(p)
7180 }
7181 };
7182 let mut reached_value = 0;
7183 with(&mut |p| reached_value = p.signal_now().expect("a Signal"));
7184 let desc = D3D12_RESOURCE_DESC {
7185 Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
7186 Width: 128,
7187 Height: 128,
7188 DepthOrArraySize: 1,
7189 MipLevels: 1,
7190 Format: DXGI_FORMAT_R8G8B8A8_UNORM,
7191 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
7192 Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE,
7193 ..Default::default()
7194 };
7195 let key = ReservedKey::from_desc(&desc, 0);
7196 let mut n = 0;
7197 with(&mut |p| n = p.reserve_spares(key, 2));
7198 assert_eq!(n, 2);
7199 FAIL_SIGNALS.with(|f| f.set(1));
7200 make_spares(&dev, dev.as_raw(), &desc, 0, std::ptr::null(), key, n);
7201 with(&mut |p| {
7202 assert_eq!(p.value, reached_value, "no value published for the spares");
7203 assert!(p.pending_recycles.iter().all(|r| r.key != key), "no spares queued without their Signal");
7204 assert!(!p.spares_in_flight.contains_key(&key), "the reservation is given back");
7205 assert_eq!(p.reserve_spares(key, 2), 2, "so the next placement reserves them again");
7206 p.end_spare_reservation(key, 2);
7207 });
7208 FAIL_SIGNALS.with(|f| f.set(0));
7209 PAGES.lock().unwrap().remove(&dev_key);
7210 }
7211 }
6129} 7212}