From 84943bffde2e8ca072c64857fff4fed014604bf6 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Fri, 27 Nov 2026 23:23:04 +0100 Subject: [PATCH 1/7] Recompiler: heap-window shaders reach all 16 window slots of the heap With XCL_HEAP_WINDOWS=1 a translated program takes memory window k from descriptor MEM_HEAP_BASE + k of the shared heap, and both translators stop at the unified block's own window count (an address past it reads 0). The heap already reserves MAX_HEAP_WINDOWS (16) window slots, but only the layout's windows are written; the others were never read. Both translators now let a heap-window program select any of the 16 slots (HLSL: mem_accessors; direct DXIL: lower_mem::heap_window_bound, translator version 13), and set_window_views gives every slot past the layout's windows a null UAV, which reads 0 and drops writes, as the old bound did. The test runner's heap (run_in_arena) does the same. Nothing changes for a title: an address outside the windows still reads 0. It lets memory XCL maps into those slots later (the title's memory outside the unified block) be read without translating the shaders again. Main already gives a `(0, 0)` window and the slots up to 4 null views; this extends that to the 16 slots (set_window_views writes MAX_HEAP_WINDOWS views, the completeness rule still follows the layout). Tests: the HLSL bound for 2 / 4 / 8 / 16 windows and without heap windows, the direct bound, the null views set_window_views makes for 1, 8 and 16 windows. gpu_heap_windows_reject_out_of_uma_aliasing and gpu_heap_windows_divergent_lanes_match_switch_form read window 4 of a 2-window arena: a null slot now. Ported from the lab tree where MacieGx made the shader side reach the slots past the unified block (HLSL and direct DXIL). Co-Authored-By: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 12 +++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 12 +++++++-- crates/xcl/src/gpu/recomp/emit.rs | 3 +++ .../xcl/src/gpu/recomp/heap_window_tests.rs | 25 +++++++++++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 11 +++++--- crates/xcl/src/hle/d3d12x/console_heap.rs | 25 +++++++++++++------ 7 files changed, 75 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index ec79716ec9..05f3c5627e 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1468,3 +1468,15 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +/// With heap windows a program selects every window descriptor of the shared heap, as the +/// HLSL accessors do (`recomp::heap_window_tests::heap_windows_select_every_heap_slot`): the +/// slots past the unified block's windows hold null views. +#[test] +fn heap_windows_select_every_heap_slot() { + use super::lower_mem::heap_window_bound; + let slots = crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + for mems in [2usize, 3, 4, 8, 16] { + assert_eq!(heap_window_bound(mems), slots, "{mems} unified windows"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 89eeaf1d8d..62f235a3fc 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -38,7 +38,7 @@ pub struct KernelOptions { /// identity (`recomp::pso`): bump it when `pso::direct_compute` / `direct_graphics` change the /// containers. An edit of `gpu/dxil` needs no bump, `XCL_DIRECT_DXIL_SOURCE_ID` is its hash /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 12; +pub const TRANSLATOR_VERSION: u32 = 13; /// Console compute shaders (and the kernel tests) go through this translator, with the HLSL /// path as the fallback for what it cannot translate yet: the default, and `XCL_DIRECT_DXIL=1`. diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 1196b9dab0..ce0dc5b286 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -151,6 +151,14 @@ pub struct FmtComp1 { pub dflt: Value, } +/// Windows a program with heap windows (`Lw::heap_mem`) may select: every window descriptor +/// of the shared heap (`MEM_HEAP_BASE`.., `uma::MAX_HEAP_WINDOWS`), the unified block's and the +/// null views or mapped memory after them (`console_heap::set_window_views`) – the same bound as +/// the HLSL path's accessors (`recomp::emit::mem_accessors`). +pub(crate) fn heap_window_bound(mems: usize) -> u32 { + (mems as u32).max(crate::gpu::uma::MAX_HEAP_WINDOWS as u32) +} + impl Lw { /// Runs `f` on the active memory window (`mem`, `mem1`.. at u2.., or descriptor heap /// when `self.heap_mem` is set via `XCL_HEAP_WINDOWS`), returning `out_tys.len()` values @@ -173,7 +181,7 @@ impl Lw { // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. if let Some(coherent) = self.heap_mem { - let windows = self.mems.len() as u32; + let windows = heap_window_bound(self.mems.len()); let w = self.rd(super::lower::VAR_WIN); let inside = self.cmpc(Pred::ULt, w, windows); let cond = match guard { @@ -413,7 +421,7 @@ impl Lw { return vec![z; n]; } let w = self.rd(super::lower::VAR_WIN); - let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let inside = self.cmpc(Pred::ULt, w, heap_window_bound(self.mems.len())); let ok = match guard { Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), _ => inside, diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 19d4ae28be..a5a646ae71 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6076,6 +6076,9 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def: fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { + // every window descriptor of the shared heap, not only the unified block's: the slots + // past it hold null views (`console_heap::set_window_views`) or memory XCL maps there + let windows = windows.max(crate::gpu::uma::MAX_HEAP_WINDOWS as u32); // Redirect ordinary out-of-window loads/stores to null raw UAVs without a divergent // branch. Atomics keep the guard because their out parameter must be set to zero. let buf = |nul: u32| format!( diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 40f856a7af..59e9115a27 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -552,3 +552,28 @@ fn heap_windows_graphics_stages_validate() { } } } + +/// With heap windows, the HLSL accessors let a program select every window descriptor of the +/// shared heap (`uma::MAX_HEAP_WINDOWS`), whatever its own window count: the slots past the +/// unified block's windows hold null views (`console_heap::set_window_views`), so an address +/// there reads 0 as before. Without heap windows the bound stays the program's own count. +/// (The direct path's bound: `dxil::core_tests::heap_windows_select_every_heap_slot`.) +#[test] +fn heap_windows_select_every_heap_slot() { + let e = |n: &str, enc: &str, f: &[(&str, u64)]| crate::gpu::rdna2::encode(n, enc, f, None).unwrap(); + let mut code = Vec::new(); + code.extend(e("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 4), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)])); + code.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + let slots = crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + for windows in [2u32, 4, 8, slots] { + let t = super::translate(&code, &super::Options { mem_windows: windows, heap_windows: true, ..Default::default() }).unwrap(); + // loads and stores select a null view past the bound, atomics branch on it + assert!(t.hlsl.contains(&format!("bool xcl_o = xcl_w >= {slots}u;")), "{windows} windows:\n{}", t.hlsl); + assert!(t.hlsl.contains(&format!("[branch] if (xcl_w >= {slots}u)")), "{windows} windows:\n{}", t.hlsl); + if windows < slots { + assert!(!t.hlsl.contains(&format!("xcl_w >= {windows}u")), "{windows} windows:\n{}", t.hlsl); + } + } + let t = super::translate(&code, &super::Options { mem_windows: 2, heap_windows: false, ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains(&format!("xcl_w >= {slots}u")), "{}", t.hlsl); +} diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index bdebc51704..8381882062 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1579,8 +1579,9 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); + match (bufs.get(k), arena.windows.get(k)) { + (Some(b), Some(w)) => dev.CreateUnorderedAccessView(b, None::<&ID3D12Resource>, Some(&raw_window_uav(w.1 as u64)), h), + _ => dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(crate::gpu::uma::GRAIN as u64)), h), + } } for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { let mut h = dh.GetCPUDescriptorHandleForHeapStart(); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 3c9dd506b8..1f63cbe026 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -597,11 +597,15 @@ pub fn window_views_failed() -> bool { /// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; a slot /// without one (`(0, 0)`: a window with no memory) gets a null raw UAV – shaders read 0 there and /// their stores go nowhere. (It once aliased window 0: what was at such an address read window -/// 0's bytes, and GPU writes there overwrote its descriptor heaps.) +/// 0's bytes, and GPU writes there overwrote its descriptor heaps.) The slots past the layout's +/// windows, up to `MAX_HEAP_WINDOWS`, get null views too: shaders with heap windows may select +/// any of the 16 (`recomp::emit::mem_accessors`, `dxil::lower_mem::heap_window_bound`), and a +/// null view reads 0 and drops writes, as an address outside the windows did before. pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { - let count = windows.len().max(crate::gpu::uma::MAX_WINDOWS); - let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0); - let ok = count <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && { + let layout = windows.len().max(crate::gpu::uma::MAX_WINDOWS); + let complete = layout <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0); + let count = crate::gpu::uma::MAX_HEAP_WINDOWS; + let ok = layout <= crate::gpu::uma::MAX_HEAP_WINDOWS && complete && windows.first().is_some_and(|w| w.0 != 0) && shared_heap(dev) && { let (device, cpu, inc) = { let g = GLOBAL.lock().unwrap(); let s = g.as_ref().unwrap(); @@ -626,7 +630,7 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - }; if !ok { WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed); - crate::xlog_warn!("memory windows: could not bind {count} window(s) in the shared descriptor heap"); + crate::xlog_warn!("memory windows: could not bind {} window(s) in the shared descriptor heap", windows.len()); } ok } @@ -1877,10 +1881,15 @@ mod tests { next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), retired: VecDeque::new(), nulls: None, leases: PublishLeases::default(), }); let window = (&mut resource as *mut _ as usize, 0x10000); - // the root-UAV slots past the windows there are: null views, not window 0 again + // the layout's windows, then null views up to MAX_HEAP_WINDOWS (not window 0 again) + let heap_slots = crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + let all = (1u32 << heap_slots) - 1; assert!(set_window_views(&dev, &[window])); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); - assert_eq!(NULLS.swap(0, Ordering::Relaxed), 0b1110); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), heap_slots); + assert_eq!(NULLS.swap(0, Ordering::Relaxed), all & !0b1); + assert!(set_window_views(&dev, &[window; 8])); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), heap_slots); + assert_eq!(NULLS.swap(0, Ordering::Relaxed), all & !0xff); let mut windows = [window; crate::gpu::uma::MAX_HEAP_WINDOWS]; assert!(set_window_views(&dev, &windows)); assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); From 4dd33fc1f9f4b274aef66d44f2f368af4d732ae4 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:35:21 +0100 Subject: [PATCH 2/7] Recompiler: heap window slots - test runner and test follow review - runner::dispatch_with (the backend-hook PSOs of gpu_compute_e2e): heap slots 0..MAX_WINDOWS stay views of `mem`, as the root form's four windows, and the slots past them are null views, as run_in_arena and the runtime. - heap_windows_select_every_heap_slot: the case without heap windows now checks the switch over the program's own windows (case 1 present, case 2 absent, no descriptor heap), instead of an assertion that held by construction. From an independent review of the PR. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/heap_window_tests.rs | 4 +++- crates/xcl/src/gpu/recomp/runner.rs | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 59e9115a27..9bbdf0a99a 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -574,6 +574,8 @@ fn heap_windows_select_every_heap_slot() { assert!(!t.hlsl.contains(&format!("xcl_w >= {windows}u")), "{windows} windows:\n{}", t.hlsl); } } + // the root-UAV form: a switch over the program's own 2 windows, nothing past them let t = super::translate(&code, &super::Options { mem_windows: 2, heap_windows: false, ..Default::default() }).unwrap(); - assert!(!t.hlsl.contains(&format!("xcl_w >= {slots}u")), "{}", t.hlsl); + assert!(!t.hlsl.contains("ResourceDescriptorHeap[") && t.hlsl.contains("case 1u: return mem1."), "{}", t.hlsl); + assert!(!t.hlsl.contains("case 2u:"), "{}", t.hlsl); } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 8381882062..5aebad0fa2 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1856,7 +1856,9 @@ fn dispatch_with( let bound = bind_resources(dev, &list, &[], &[])?; // A PSO built by the backend's hook uses the runtime's window count: with heap windows // (`Options::heap_windows`) its accesses go to ResourceDescriptorHeap[MEM_HEAP_BASE + w], - // so every window slot is a raw view of `mem` (no textures here to share the heap with). + // so the root form's windows (MAX_WINDOWS, all `mem` below) are raw views of `mem` and the + // slots past them null views, as `console_heap::set_window_views` (no textures here to + // share the heap with). let win_count = crate::gpu::uma::MAX_HEAP_WINDOWS; let dh: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { @@ -1870,7 +1872,11 @@ fn dispatch_with( for k in 0..win_count { let mut h = dh.GetCPUDescriptorHandleForHeapStart(); h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; - dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); + if k < crate::gpu::uma::MAX_WINDOWS { + dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); + } else { + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(crate::gpu::uma::GRAIN as u64)), h); + } } for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { let mut h = dh.GetCPUDescriptorHandleForHeapStart(); From 370e1c76f0baf41b02e2147b7a436fe1059e5ec9 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:29:42 +0100 Subject: [PATCH 3/7] Tests: the expanded-layout heap-window test checks the 16-slot bound gpu::uma::tests::expanded_heap_window_shaders_translate_and_validate asserted that the HLSL heap accessors range-check against the program's own window count (8); with the previous commits a heap-window program selects every heap window slot, so the bound is 16 for 8 and 16 windows alike. Found by the full suite on this PR's head. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/uma.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index e4e34f0166..fc676a91fb 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -1692,7 +1692,9 @@ mod tests { // HLSL path accepts 8/16 with heap_windows, rejects without. assert!(recomp::translate(&code, &Options { mem_windows: w, heap_windows: false, ..Default::default() }).is_err()); let t = recomp::translate(&code, &Options { mem_windows: w, heap_windows: true, ..Default::default() }).unwrap(); - assert!(t.hlsl.contains(&format!("xcl_w >= {w}u")), "HLSL must range-check against {w} windows"); + // heap-window programs select every heap window slot (null views past the layout's) + let slots = MAX_HEAP_WINDOWS as u32; + assert!(t.hlsl.contains(&format!("xcl_w >= {slots}u")), "HLSL must range-check against the {slots} heap window slots ({w} windows)"); assert!(!t.hlsl.contains("mem4"), "root signature ABI stays at 4 root UAVs"); // Direct DXIL path validates cleanly with 8/16 | HEAP_WINDOWS. translate(&code, KernelOptions { wave64: true, split: false, mem_windows: w | HEAP_WINDOWS, sampler_base: 0 }).unwrap(); From 013ca846170a1a8a118774adfb51b01e89cf0a59 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Fri, 27 Nov 2026 23:26:15 +0100 Subject: [PATCH 4/7] D3D12.X: XCL_VIEW_MEM=1 maps the title's GPU-view memory into heap windows 4..15 A retail title gives the GPU addresses in its "GPU view" (a reservation with no CPU access, kernelx::mirrors), outside the unified block. Translated shaders read 0 there. With XCL_VIEW_MEM=1 (off by default; needs XCL_HEAP_WINDOWS=1 and the 4-window unified block) windows 4..15 are reserved buffers in heap window slots 4..15, whose 64 KiB tiles are mapped from pools and filled on demand: bind_abi names what a draw or dispatch can read (the buffer V#s of the first 64 slots of its descriptor tables, its root addresses, XCL_VIEW_ROOT_KB each) and the tiles under them are copied from the title's bytes (the page the page-mapping method put there, as main's record of it says (mirrors::shows), else the CPU view behind the GPU view) on XCL's own queue, waited for before the draw is recorded. A tile is checked again (a sampled signature) at most once a second. XCL_VIEW_POOL_MB (3072) caps the video memory. GPU writes there are not copied back. The activity log gets a "view memory:" line. Lock order: view_mem's STATE is taken by bind_abi (no other XCL lock held) and open_uma; under it only kernelx's page-mapping, mirror and physical-page locks, one at a time; never the sparse windows' state (sparse::lock_state checks it in debug builds). Nothing calls into view_mem with a lock held. Tests: the lock-order flag, no work without the state, the bytes a buffer V# names in the view windows, the page signature. Ported from MacieGx's lab tree (view memory and its generic bind path); the switch is opt-in here, and the window slots come from the preceding commit. Co-Authored-By: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 2 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 6 +- crates/xcl/src/hle/d3d12x/sparse.rs | 1 + crates/xcl/src/hle/d3d12x/view_mem.rs | 475 ++++++++++++++++++++++++++ crates/xcl/src/host.rs | 3 + 6 files changed, 487 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/hle/d3d12x/view_mem.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e2d454243d..0fb3d03b6a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -5219,6 +5219,8 @@ unsafe fn bind_abi_with_root_resolved( let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs_exact(pso) }; let prepared = prepare_abi_state(this, u, gfx, user_sgprs)?; let PreparedAbiState { layout, args, inline, table_at, io_at, res_at, allocator, heaps } = prepared; + // what the shaders read of the title's memory outside the unified windows (`XCL_VIEW_MEM=1`) + super::view_mem::ensure_for_draw(layout.as_deref(), &args); want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 2c1daeb7a3..92a80586ba 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -59,6 +59,7 @@ pub mod title_textures; pub mod view_want; mod uma_driver; mod used_journal; +pub mod view_mem; pub mod vram; mod worker_pool; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index eafeccd069..fd504d5d51 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -788,7 +788,11 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } // shaders take the windows from the shared descriptor heap (`pso::heap_windows`) if n > 1 && crate::gpu::recomp::pso::heap_windows() { - let views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); + let mut views: Vec<(usize, usize)> = bufs.iter().enumerate().map(|(k, b)| (b.0, u.window(k).1)).collect(); + // the title's memory outside a 4-window unified block, in heap slots 4.. (`XCL_VIEW_MEM=1`) + if views.len() == super::view_mem::FIRST { + views.extend(super::view_mem::init(device, u.base())); + } if super::console_heap::set_window_views(device, &views) { crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index cae13913f2..2f66d0e2ba 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -8304,6 +8304,7 @@ static FORGOTTEN: Mutex> = Mutex::new(Vec::new()); /// `STATE`, with the buffers released while it was held let go first. fn lock_state() -> std::sync::MutexGuard<'static, Option> { + debug_assert!(!super::view_mem::holding(), "the sparse state is never taken under the view memory's (view_mem lock order)"); lock_state_in(&STATE, &FORGOTTEN) } diff --git a/crates/xcl/src/hle/d3d12x/view_mem.rs b/crates/xcl/src/hle/d3d12x/view_mem.rs new file mode 100644 index 0000000000..1487264a60 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/view_mem.rs @@ -0,0 +1,475 @@ +//! Title memory outside the unified-memory windows, readable by translated shaders +//! (`XCL_VIEW_MEM=1` with `XCL_HEAP_WINDOWS=1` and the 4-window unified block; off by default). +//! +//! A retail title keeps its streamed geometry (meshlet, index and vertex buffers) at +//! addresses of its "GPU view" (`kernelx::mirrors`: a reservation with no CPU access, the GPU's +//! view of a CPU reservation of the same size), outside the unified block. Translated shaders +//! reach memory through the windows (`xcl_w` = address >> 32 - the unified block's first +//! window): with 4 windows every load past them reads 0. Here windows 4..15 (heap window slots +//! `MEM_HEAP_BASE + 4..16`, readable since every heap-window program selects all 16) are +//! reserved buffers whose 64 KiB tiles are mapped and filled on demand: a draw or dispatch +//! names the ranges it can read (`ensure_for_draw`: the V#s of its descriptor tables, its root +//! addresses) and the tiles under them are copied from where the title's bytes are (`source`: +//! the page the page-mapping method put there, else the CPU view behind the GPU view) on a +//! queue of XCL's own, finished before `ensure` returns – so before the list being recorded +//! can run. A tile is checked again (a sampled signature) at most once a second. GPU writes to +//! these windows are not copied back. +//! +//! Locks: `STATE` is taken only by `ensure` and `init`, which are called with no other XCL lock +//! held (`bind::bind_abi` before it takes its own, `real::open_uma`). Under it `source` takes +//! kernelx's page-mapping, mirror and physical-page locks one at a time; nothing here takes the +//! sparse windows' state (`sparse::lock_state` checks it in debug builds: `holding`). So the +//! order is STATE -> kernelx, and no kernelx or sparse path calls back in here. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +const TILE: usize = 0x1_0000; +const WINDOW: usize = 1 << 32; +/// first window here and one past the last (window k = addresses (base window + k) << 32) +pub const FIRST: usize = 4; +pub const END: usize = 16; +const POOL_TILES: u32 = 1024; +const STAGING_TILES: usize = 128; + +struct Tile { + sig: u64, + checked: std::time::Instant, +} + +struct State { + dev: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + value: u64, + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + /// window FIRST + i + windows: Vec, + /// address of window 0 (the unified block's base) + base: usize, + pools: Vec, + next: u32, + tiles: HashMap, + staging: ID3D12Resource, + staging_at: *mut u8, + cap_tiles: usize, + /// (va, len) → when it was last looked at + recent: HashMap<(usize, usize), std::time::Instant>, +} +unsafe impl Send for State {} + +static STATE: Mutex> = Mutex::new(None); +static UPLOADED: AtomicU64 = AtomicU64::new(0); +static CHECKED: AtomicU64 = AtomicU64::new(0); +static NO_SOURCE: AtomicU64 = AtomicU64::new(0); +static FULL: AtomicU64 = AtomicU64::new(0); +/// tiles and pools of the state, for `stats` (which must not wait for an `ensure` in progress) +static TILES: AtomicU64 = AtomicU64::new(0); +/// the windows were made (`init`): draws look for ranges in them +static ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static POOLS: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// this thread holds `STATE` (`holding`) + static HOLDING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether this thread holds the view memory's state: the sparse windows' state must never be +/// taken under it (the lock order of the module's doc; checked by `sparse::lock_state`). +pub(super) fn holding() -> bool { + HOLDING.with(|h| h.get()) +} + +/// `STATE`, marked as held by this thread until the guard goes. +struct Held(std::sync::MutexGuard<'static, Option>); +impl Drop for Held { + fn drop(&mut self) { + HOLDING.with(|h| h.set(false)); + } +} +fn lock() -> Held { + let g = STATE.lock().unwrap(); + HOLDING.with(|h| h.set(true)); + Held(g) +} + +fn buffer_desc(bytes: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// `XCL_VIEW_MEM=1`: on (off by default). +pub fn enabled() -> bool { + std::env::var("XCL_VIEW_MEM").is_ok_and(|v| v.trim() == "1") +} + +/// The windows' buffers `(resource, bytes)` for descriptors `MEM_HEAP_BASE + FIRST..END` of the +/// shared heap; empty when they could not be made or `XCL_VIEW_MEM` is not 1. `base`: the unified +/// block's window 0, which must have exactly `FIRST` windows. +pub unsafe fn init(dev: &ID3D12Device, base: usize) -> Vec<(usize, usize)> { + if !enabled() { + return Vec::new(); + } + let made = (|| -> windows::core::Result { + let mut windows = Vec::new(); + for _ in FIRST..END { + let mut r: Option = None; + dev.CreateReservedResource(&buffer_desc(WINDOW as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut r)?; + windows.push(r.ok_or_else(windows::core::Error::empty)?); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + let mut staging: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &buffer_desc((STAGING_TILES * TILE) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut staging, + )?; + let staging = staging.ok_or_else(windows::core::Error::empty)?; + let mut p: *mut c_void = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut p))?; + let cap_mb: usize = std::env::var("XCL_VIEW_POOL_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(3072); + Ok(State { + dev: dev.clone(), + queue, + fence, + value: 0, + alloc, + list, + windows, + base, + pools: Vec::new(), + next: POOL_TILES, + tiles: HashMap::new(), + staging, + staging_at: p as *mut u8, + cap_tiles: cap_mb << 4, + recent: HashMap::new(), + }) + })(); + match made { + Ok(s) => { + let out = s.windows.iter().map(|w| (w.as_raw() as usize, WINDOW)).collect(); + crate::xlog_info!("D3D12.X: view memory: windows {FIRST}..{END} ({:#x}..{:#x}) are filled on demand, up to {} MB", base + FIRST * WINDOW, base + END * WINDOW, s.cap_tiles >> 4); + *lock().0 = Some(s); + ON.store(true, Ordering::Release); + out + } + Err(e) => { + crate::xlog_warn!("D3D12.X: view memory: not available ({e})"); + Vec::new() + } + } +} + +/// Where the 64 KiB page at `va` has its bytes for the CPU (`None`: nowhere readable). +fn source(va: usize) -> Option { + use crate::hle::kernelx; + use kernelx::mirrors::Shows; + let a = match kernelx::mirrors::shows(va) { + // the page the queue's page-mapping method put there, where XCL keeps it now + Shows::Page { at, .. } => at, + Shows::Nothing => return None, + // never named: the CPU view behind the GPU view, unless a physical page is mapped here + Shows::Same(cpu) if !kernelx::physical_page_at(va) => cpu, + Shows::Same(_) | Shows::NoView => va, + }; + crate::gpu::shader::readable(a, TILE).then_some(a) +} + +/// A sampled signature of a page (a word every 256 bytes and its last one). +unsafe fn signature(a: usize) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let mut o = 0; + while o < TILE { + h = (h ^ ((a + o) as *const u64).read_unaligned()).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(17); + o += 256; + } + h ^ ((a + TILE - 8) as *const u64).read_unaligned() +} + +/// Shaders may read `[va, va + len)`: the tiles there hold the title's bytes when this returns. +pub unsafe fn ensure(va: usize, len: usize) { + let mut g = lock(); + let Some(s) = g.0.as_mut() else { return }; + let (lo, hi) = (s.base + FIRST * WINDOW, s.base + END * WINDOW); + if va < lo || va >= hi || len == 0 { + return; + } + let now = std::time::Instant::now(); + let fresh = std::time::Duration::from_millis(1000); + if s.recent.get(&(va, len)).is_some_and(|t| now.duration_since(*t) < fresh) { + return; + } + if s.recent.len() > 200_000 { + s.recent.clear(); + } + s.recent.insert((va, len), now); + let end = va.saturating_add(len).min(hi); + let mut t = va & !(TILE - 1); + // (tile, source, new) + let mut todo: Vec<(usize, usize, bool)> = Vec::new(); + while t < end { + let tile = t; + t += TILE; + let known = s.tiles.get(&tile); + if known.is_some_and(|k| now.duration_since(k.checked) < fresh) { + continue; + } + let Some(src) = source(tile) else { + // the first few say why (asked range, what the page maps show): a range past a + // buffer's end is expected here, a mapped page that cannot be read is not + if NO_SOURCE.fetch_add(1, Ordering::Relaxed) < 12 { + use crate::hle::kernelx; + crate::xlog_info!( + "D3D12.X: view memory: no source for tile {tile:#x} of {va:#x}+{len:#x}: page mapping {:x?}, CPU view {:x?}, physical page here {}", + kernelx::mirrors::shows(tile), + kernelx::mirrors::source(tile), + kernelx::physical_page_at(tile) + ); + } + continue; + }; + CHECKED.fetch_add(1, Ordering::Relaxed); + let sig = signature(src); + match s.tiles.get_mut(&tile) { + Some(k) if k.sig == sig => k.checked = now, + Some(k) => { + k.sig = sig; + k.checked = now; + todo.push((tile, src, false)); + } + None => { + if s.tiles.len() >= s.cap_tiles { + if FULL.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_warn!("D3D12.X: view memory: the pool is full ({} MB, XCL_VIEW_POOL_MB) – further ranges read 0", s.cap_tiles >> 4); + } + continue; + } + s.tiles.insert(tile, Tile { sig, checked: now }); + todo.push((tile, src, true)); + } + } + } + TILES.store(s.tiles.len() as u64, Ordering::Relaxed); + if todo.is_empty() { + return; + } + // new tiles: a pool tile each, mapped under the window + for &(tile, _, new) in &todo { + if !new { + continue; + } + if s.next >= POOL_TILES { + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_TILES as u64 * TILE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + if s.dev.CreateHeap(&desc, &mut heap).is_err() || heap.is_none() { + crate::xlog_warn!("D3D12.X: view memory: no video memory for another pool"); + s.cap_tiles = 0; + s.tiles.remove(&tile); + continue; + } + s.pools.push(heap.unwrap()); + POOLS.store(s.pools.len() as u64, Ordering::Relaxed); + s.next = 0; + } + let k = (tile - s.base) / WINDOW - FIRST; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, s.next, 1u32); + s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), s.pools.last().unwrap(), 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + s.next += 1; + } + for batch in todo.chunks(STAGING_TILES) { + if s.alloc.Reset().is_err() || s.list.Reset(&s.alloc, None).is_err() { + return; + } + for (i, &(tile, src, _)) in batch.iter().enumerate() { + if !s.tiles.contains_key(&tile) { + continue; + } + std::ptr::copy_nonoverlapping(src as *const u8, s.staging_at.add(i * TILE), TILE); + let k = (tile - s.base) / WINDOW - FIRST; + s.list.CopyBufferRegion(&s.windows[k], ((tile - s.base) % WINDOW) as u64, &s.staging, (i * TILE) as u64, TILE as u64); + } + if s.list.Close().is_err() { + return; + } + let Ok(cl) = s.list.cast::() else { return }; + s.queue.ExecuteCommandLists(&[Some(cl)]); + s.value += 1; + if s.queue.Signal(&s.fence, s.value).is_err() { + return; + } + if let Err(e) = crate::gpu::fence::wait(&s.fence, s.value, &s.dev, None, 5000) { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: view memory: upload not finished: {e}"); + } + } + UPLOADED.fetch_add(batch.len() as u64, Ordering::Relaxed); + } +} + +/// The ranges a draw with these root arguments can read outside the unified windows: its root +/// addresses (`root_bytes` each – their sizes are not known) and the buffer V#s (16 bytes at +/// every 32 of a descriptor table: address, stride << 16 in word 1, records, type in the top +/// bits of word 3) of its tables' first `slots` descriptors. +pub unsafe fn ensure_for_draw(layout: Option<&super::console_list::Layout>, args: &[u8]) { + use super::console_list::Param; + if !ON.load(Ordering::Acquire) { + return; + } + let (base, on) = match lock().0.as_ref() { + Some(s) => (s.base, true), + None => (0, false), + }; + let Some(layout) = layout.filter(|_| on) else { return }; + static ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + static SLOTS: std::sync::OnceLock = std::sync::OnceLock::new(); + let root_bytes = *ROOT.get_or_init(|| std::env::var("XCL_VIEW_ROOT_KB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(1024) << 10); + let slots = *SLOTS.get_or_init(|| std::env::var("XCL_VIEW_TABLE_SLOTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64)); + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let (lo, hi) = (base + FIRST * WINDOW, base + END * WINDOW); + for p in &layout.params { + match *p { + Param::Descriptor { at } => { + let (Some(l), Some(h)) = (word(at as usize), word(at as usize + 4)) else { continue }; + let va = ((h as usize & 0xFFFF) << 32) | l as usize; + if va >= lo && va < hi { + ensure(va, root_bytes); + } + } + Param::Table { at } => { + let Some(t) = word(at as usize) else { continue }; + if t == 0 { + continue; + } + let table = base + t as usize; + if !crate::gpu::shader::readable(table, 32 * slots) { + continue; + } + for k in 0..slots { + let d = ((table + 32 * k) as *const [u32; 4]).read_unaligned(); + if let Some((va, bytes)) = buffer_range(d, lo, hi) { + ensure(va, bytes); + } + } + } + Param::Constants { .. } => {} + } + } +} + +/// The bytes a buffer V# `d` names in `[lo, hi)`: its address (48 bits), records × stride +/// (records alone with stride 0) clamped to 4 B..16 MiB; None for another type (texture +/// descriptors have type bits in word 3's top two) or an address outside. +fn buffer_range(d: [u32; 4], lo: usize, hi: usize) -> Option<(usize, usize)> { + let va = ((d[1] as usize & 0xFFFF) << 32) | d[0] as usize; + if va < lo || va >= hi || d[3] >> 30 != 0 { + return None; + } + let stride = (d[1] >> 16) as usize & 0x3FFF; + let bytes = if stride == 0 { d[2] as usize } else { (d[2] as usize).saturating_mul(stride) }; + Some((va, bytes.clamp(4, 16 << 20))) +} + +/// One line for the activity log. +pub fn stats() -> String { + let (tiles, pools) = (TILES.load(Ordering::Relaxed), POOLS.load(Ordering::Relaxed)); + format!( + "view memory: {} MB in {tiles} tiles ({pools} pools), {} tile uploads, {} tile checks, {} without a source", + tiles >> 4, + UPLOADED.load(Ordering::Relaxed), + CHECKED.load(Ordering::Relaxed), + NO_SOURCE.load(Ordering::Relaxed) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The lock order's check: `holding` is true exactly while this thread holds `STATE`. + #[test] + fn holding_is_true_only_under_the_state_lock() { + assert!(!holding()); + { + let _g = lock(); + assert!(holding()); + } + assert!(!holding()); + // another thread does not see this one's lock + let g = lock(); + assert!(!std::thread::spawn(holding).join().unwrap()); + drop(g); + } + + /// Without the state (`XCL_VIEW_MEM` unset, or windows not made) a draw asks for nothing. + #[test] + fn nothing_happens_without_the_state() { + assert!(lock().0.is_none() || enabled()); + let layout = super::super::console_list::Layout { params: vec![super::super::console_list::Param::Descriptor { at: 0 }], size: 8, inline: 0, inline_gfx: 0, ..Default::default() }; + unsafe { + ensure(0xD_0000_0000, 0x1000); + ensure_for_draw(Some(&layout), &0xD_0000_0000u64.to_le_bytes()); + } + assert_eq!(UPLOADED.load(Ordering::Relaxed), 0); + assert!(!holding()); + } + + /// Buffer V#s: records × stride (records alone with stride 0), clamped; other types and + /// addresses outside the view windows are not asked for. + #[test] + fn buffer_vsharps_name_their_bytes_in_the_view_windows() { + let (lo, hi) = (0x8_0000_0000usize, 0x14_0000_0000usize); + let d = |va: usize, stride: u32, records: u32, w3: u32| [va as u32, ((va >> 32) as u32 & 0xFFFF) | (stride << 16), records, w3]; + assert_eq!(buffer_range(d(0xD_FFFF_0000, 0, 0x100, 0), lo, hi), Some((0xD_FFFF_0000, 0x100))); + assert_eq!(buffer_range(d(0xD_FFFF_0000, 16, 0x100, 0), lo, hi), Some((0xD_FFFF_0000, 0x1000))); + assert_eq!(buffer_range(d(0xD_FFFF_0000, 0, 0, 0), lo, hi), Some((0xD_FFFF_0000, 4))); + assert_eq!(buffer_range(d(0xD_FFFF_0000, 0x3FFF, u32::MAX, 0), lo, hi), Some((0xD_FFFF_0000, 16 << 20))); + assert_eq!(buffer_range(d(0xD_FFFF_0000, 0, 0x100, 2 << 30), lo, hi), None, "an image descriptor"); + assert_eq!(buffer_range(d(0x7_FFFF_0000, 0, 0x100, 0), lo, hi), None, "in the unified block"); + assert_eq!(buffer_range(d(0x14_0000_0000, 0, 0x100, 0), lo, hi), None, "past the last window"); + } + + /// A page's signature sees a change in a sampled word and in its last word. + #[test] + fn the_signature_samples_the_page() { + let mut page = vec![0u8; TILE]; + let a = page.as_mut_ptr() as usize; + let s0 = unsafe { signature(a) }; + page[256] = 1; + let s1 = unsafe { signature(a) }; + page[TILE - 1] = 1; + let s2 = unsafe { signature(a) }; + assert!(s0 != s1 && s1 != s2); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f76e9a7a8d..36679bfc28 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -176,6 +176,9 @@ pub fn host_main(boot_path: &Path) -> i32 { let private = owner.commit.unwrap_or(0); let local = owner.local.map_or(0, |s| s.usage); let non_local = owner.non_local.map_or(0, |s| s.usage); + if crate::hle::d3d12x::view_mem::enabled() { + crate::xlog_info!("{}", crate::hle::d3d12x::view_mem::stats()); + } let budget = owner.local.map_or(0, |s| s.budget); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); From d08600152de465fd3b3b09daae74d84c5dc22430 Mon Sep 17 00:00:00 2001 From: MacieGx Date: Sat, 28 Nov 2026 06:38:41 +0100 Subject: [PATCH 5/7] D3D12.X: view memory gives back stale tiles when full and copies pages without faulting Two follow-ups of the view memory, from MacieGx's tree: - When XCL_VIEW_POOL_MB is reached, tiles no draw has named for 6 s give their pool tile back (mapped NULL first; at most one round a second) and new ranges take them, instead of every further range reading 0 for the rest of the run. - The title may decommit or move a page between the readability check and the copy: the signature and the upload now read it through title_textures::copy_committed_region (ReadProcessMemory, an unreadable page reads 0) instead of a plain memcpy, which ended a run. Co-Authored-By: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 2 +- crates/xcl/src/hle/d3d12x/view_mem.rs | 72 +++++++++++++++++++-- 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6c2579b5af..9624530c74 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3269,7 +3269,7 @@ fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> /// `0`. Because Windows may return `read == 0` when a fault occurs later in the span, binary-split /// failed multi-page ranges at 4 KiB boundaries so all still-committed pages are copied in O(log N) /// calls and only unreadable pages are zeroed. -unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { +pub(super) unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const PAGE: usize = 0x1000; diff --git a/crates/xcl/src/hle/d3d12x/view_mem.rs b/crates/xcl/src/hle/d3d12x/view_mem.rs index 1487264a60..437c62c96c 100644 --- a/crates/xcl/src/hle/d3d12x/view_mem.rs +++ b/crates/xcl/src/hle/d3d12x/view_mem.rs @@ -41,6 +41,8 @@ const STAGING_TILES: usize = 128; struct Tile { sig: u64, checked: std::time::Instant, + /// (pool heap, tile in it) + slot: (u32, u32), } struct State { @@ -56,6 +58,9 @@ struct State { base: usize, pools: Vec, next: u32, + /// pool tiles given back by `evict_stale` + free: Vec<(u32, u32)>, + evicted_at: Option, tiles: HashMap, staging: ID3D12Resource, staging_at: *mut u8, @@ -75,6 +80,7 @@ static TILES: AtomicU64 = AtomicU64::new(0); /// the windows were made (`init`): draws look for ranges in them static ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static POOLS: AtomicU64 = AtomicU64::new(0); +static EVICTED: AtomicU64 = AtomicU64::new(0); thread_local! { /// this thread holds `STATE` (`holding`) @@ -162,6 +168,8 @@ pub unsafe fn init(dev: &ID3D12Device, base: usize) -> Vec<(usize, usize)> { base, pools: Vec::new(), next: POOL_TILES, + free: Vec::new(), + evicted_at: None, tiles: HashMap::new(), staging, staging_at: p as *mut u8, @@ -199,8 +207,19 @@ fn source(va: usize) -> Option { crate::gpu::shader::readable(a, TILE).then_some(a) } -/// A sampled signature of a page (a word every 256 bytes and its last one). -unsafe fn signature(a: usize) -> u64 { +/// A sampled signature of a page (a word every 256 bytes and its last one), read from a copy +/// made without faulting: the title may decommit the page meanwhile (a run ended in memcpy here). +unsafe fn signature(src: usize) -> u64 { + thread_local!(static COPY: std::cell::RefCell> = std::cell::RefCell::new(vec![0u8; TILE])); + COPY.with(|c| { + let mut c = c.borrow_mut(); + c.fill(0); + super::title_textures::copy_committed_region(src, c.as_mut_ptr(), TILE); + signature_of(c.as_ptr() as usize) + }) +} + +unsafe fn signature_of(a: usize) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; let mut o = 0; while o < TILE { @@ -210,6 +229,33 @@ unsafe fn signature(a: usize) -> u64 { h ^ ((a + TILE - 8) as *const u64).read_unaligned() } +/// The pool is full: tiles no draw has named for `STALE` give their pool tiles back (at most +/// one round a second). A list recorded earlier and not run yet reads 0 or newer bytes there. +unsafe fn evict_stale(s: &mut State, now: std::time::Instant) { + const STALE: std::time::Duration = std::time::Duration::from_secs(6); + if s.evicted_at.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_secs(1)) { + return; + } + s.evicted_at = Some(now); + let old: Vec = s.tiles.iter().filter(|(_, t)| t.slot.0 != u32::MAX && now.duration_since(t.checked) >= STALE).map(|(&a, _)| a).collect(); + for &tile in &old { + let Some(t) = s.tiles.remove(&tile) else { continue }; + let k = (tile - s.base) / WINDOW - FIRST; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flag, count) = (D3D12_TILE_RANGE_FLAG_NULL, 1u32); + s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), None, 1, Some(&flag), None, Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + s.free.push(t.slot); + } + s.recent.clear(); + EVICTED.fetch_add(old.len() as u64, Ordering::Relaxed); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: view memory: the pool is full – {} tiles not named for {} s given back ({} kept; round {n})", old.len(), STALE.as_secs(), s.tiles.len()); + } +} + /// Shaders may read `[va, va + len)`: the tiles there hold the title's bytes when this returns. pub unsafe fn ensure(va: usize, len: usize) { let mut g = lock(); @@ -262,13 +308,16 @@ pub unsafe fn ensure(va: usize, len: usize) { todo.push((tile, src, false)); } None => { + if s.tiles.len() >= s.cap_tiles { + evict_stale(s, now); + } if s.tiles.len() >= s.cap_tiles { if FULL.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_warn!("D3D12.X: view memory: the pool is full ({} MB, XCL_VIEW_POOL_MB) – further ranges read 0", s.cap_tiles >> 4); } continue; } - s.tiles.insert(tile, Tile { sig, checked: now }); + s.tiles.insert(tile, Tile { sig, checked: now, slot: (u32::MAX, 0) }); todo.push((tile, src, true)); } } @@ -282,6 +331,17 @@ pub unsafe fn ensure(va: usize, len: usize) { if !new { continue; } + if let Some(slot) = s.free.pop() { + let k = (tile - s.base) / WINDOW - FIRST; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, slot.1, 1u32); + s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), &s.pools[slot.0 as usize], 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + if let Some(t) = s.tiles.get_mut(&tile) { + t.slot = slot; + } + continue; + } if s.next >= POOL_TILES { let desc = D3D12_HEAP_DESC { SizeInBytes: POOL_TILES as u64 * TILE as u64, @@ -305,6 +365,9 @@ pub unsafe fn ensure(va: usize, len: usize) { let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, s.next, 1u32); s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), s.pools.last().unwrap(), 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + if let Some(t) = s.tiles.get_mut(&tile) { + t.slot = (s.pools.len() as u32 - 1, s.next); + } s.next += 1; } for batch in todo.chunks(STAGING_TILES) { @@ -315,7 +378,8 @@ pub unsafe fn ensure(va: usize, len: usize) { if !s.tiles.contains_key(&tile) { continue; } - std::ptr::copy_nonoverlapping(src as *const u8, s.staging_at.add(i * TILE), TILE); + std::ptr::write_bytes(s.staging_at.add(i * TILE), 0, TILE); + super::title_textures::copy_committed_region(src, s.staging_at.add(i * TILE), TILE); let k = (tile - s.base) / WINDOW - FIRST; s.list.CopyBufferRegion(&s.windows[k], ((tile - s.base) % WINDOW) as u64, &s.staging, (i * TILE) as u64, TILE as u64); } From 60a7d8e07bdce984b65d086f27aac3b881b23c44 Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:40:23 +0100 Subject: [PATCH 6/7] D3D12.X: view memory records a tile only after its upload, hashes whole pages From an independent review of the view memory: - A tile's signature is recorded only once its upload is done (`commit_batch`): a failed Reset / Close / Signal or an upload not finished in 5 s left tiles marked current that were never copied. An unfinished upload now keeps the allocator and the staging buffer out of use (`pending`) until its fence is reached; the next `ensure` waits for it first, or does nothing. - The signature hashes the whole 64 KiB (4 lanes), not one word in 32: a small write elsewhere in a page kept the old bytes on the GPU for good. Measured with a_tile_hash_costs_microseconds. - A tile whose page the title unmapped or released (no source any more) is mapped NULL and its pool tile given back, instead of keeping the old bytes readable. - A new pool's CreateHeap runs as XCL's own work (title_textures::own_work), not through the adopted device's hook for title heaps; the module's lock-order note says so. - `ON` goes back to false when set_window_views fails (draws stopped mapping for slots the shaders no longer read), and the state's lock survives a panic under it. Tests: a write at any of six offsets changes the signature; the signature is recorded only by `commit_batch`; the hash's cost. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 2 + crates/xcl/src/hle/d3d12x/view_mem.rs | 224 ++++++++++++++++++++------ 2 files changed, 173 insertions(+), 53 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fd504d5d51..54c75c65db 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -795,6 +795,8 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } if super::console_heap::set_window_views(device, &views) { crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); + } else { + super::view_mem::disable(); } } set_uma_windows(bufs); diff --git a/crates/xcl/src/hle/d3d12x/view_mem.rs b/crates/xcl/src/hle/d3d12x/view_mem.rs index 437c62c96c..54f65ef7d6 100644 --- a/crates/xcl/src/hle/d3d12x/view_mem.rs +++ b/crates/xcl/src/hle/d3d12x/view_mem.rs @@ -12,14 +12,19 @@ //! addresses) and the tiles under them are copied from where the title's bytes are (`source`: //! the page the page-mapping method put there, else the CPU view behind the GPU view) on a //! queue of XCL's own, finished before `ensure` returns – so before the list being recorded -//! can run. A tile is checked again (a sampled signature) at most once a second. GPU writes to -//! these windows are not copied back. +//! can run. A tile is checked again (a hash of the whole 64 KiB, read without faulting) at most +//! once a second; its signature is only recorded once its upload is done, so a failed or +//! unfinished upload is tried again. When the pool is full, tiles no draw has named for 6 s are +//! given back; a tile whose page the title unmapped or released is mapped NULL again. GPU writes +//! to these windows are not copied back. //! //! Locks: `STATE` is taken only by `ensure` and `init`, which are called with no other XCL lock //! held (`bind::bind_abi` before it takes its own, `real::open_uma`). Under it `source` takes -//! kernelx's page-mapping, mirror and physical-page locks one at a time; nothing here takes the -//! sparse windows' state (`sparse::lock_state` checks it in debug builds: `holding`). So the -//! order is STATE -> kernelx, and no kernelx or sparse path calls back in here. +//! kernelx's page-mapping, mirror and physical-page locks one at a time; a new pool's CreateHeap +//! runs as XCL's own work (`title_textures::own_work`), so the adopted device's hook does not +//! take it for a title heap. Nothing here takes the sparse windows' state (`sparse::lock_state` +//! checks it in debug builds: `holding`). So the order is STATE -> kernelx, and no kernelx or +//! sparse path calls back in here. use std::collections::HashMap; use std::ffi::c_void; @@ -39,7 +44,8 @@ const POOL_TILES: u32 = 1024; const STAGING_TILES: usize = 128; struct Tile { - sig: u64, + /// the signature of the bytes on the GPU; None: not uploaded yet + sig: Option, checked: std::time::Instant, /// (pool heap, tile in it) slot: (u32, u32), @@ -64,6 +70,8 @@ struct State { tiles: HashMap, staging: ID3D12Resource, staging_at: *mut u8, + /// an upload the GPU may still run (its fence value): the allocator and staging wait for it + pending: Option, cap_tiles: usize, /// (va, len) → when it was last looked at recent: HashMap<(usize, usize), std::time::Instant>, @@ -81,6 +89,7 @@ static TILES: AtomicU64 = AtomicU64::new(0); static ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static POOLS: AtomicU64 = AtomicU64::new(0); static EVICTED: AtomicU64 = AtomicU64::new(0); +static DROPPED: AtomicU64 = AtomicU64::new(0); thread_local! { /// this thread holds `STATE` (`holding`) @@ -101,7 +110,8 @@ impl Drop for Held { } } fn lock() -> Held { - let g = STATE.lock().unwrap(); + // a panic under it (the lock-order assert in debug builds) must not take every draw down + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); HOLDING.with(|h| h.set(true)); Held(g) } @@ -173,6 +183,7 @@ pub unsafe fn init(dev: &ID3D12Device, base: usize) -> Vec<(usize, usize)> { tiles: HashMap::new(), staging, staging_at: p as *mut u8, + pending: None, cap_tiles: cap_mb << 4, recent: HashMap::new(), }) @@ -207,8 +218,8 @@ fn source(va: usize) -> Option { crate::gpu::shader::readable(a, TILE).then_some(a) } -/// A sampled signature of a page (a word every 256 bytes and its last one), read from a copy -/// made without faulting: the title may decommit the page meanwhile (a run ended in memcpy here). +/// The signature of a page (`signature_of`), read from a copy made without faulting: the title +/// may decommit the page meanwhile (a run ended in memcpy here). unsafe fn signature(src: usize) -> u64 { thread_local!(static COPY: std::cell::RefCell> = std::cell::RefCell::new(vec![0u8; TILE])); COPY.with(|c| { @@ -219,14 +230,18 @@ unsafe fn signature(src: usize) -> u64 { }) } +/// A hash of all 64 KiB of the tile at `a`: a write anywhere in the page changes it (a sample of +/// one word in 32 missed most small writes, for good). unsafe fn signature_of(a: usize) -> u64 { - let mut h = 0xcbf2_9ce4_8422_2325u64; - let mut o = 0; - while o < TILE { - h = (h ^ ((a + o) as *const u64).read_unaligned()).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(17); - o += 256; + let words = std::slice::from_raw_parts(a as *const u64, TILE / 8); + // four lanes, then folded: the loop is bound by memory, not by the multiply chain + let mut h = [0xcbf2_9ce4_8422_2325u64, 0x9e37_79b9_7f4a_7c15, 0xc2b2_ae3d_27d4_eb4f, 0x1656_67b1_9e37_79f9]; + for c in words.chunks_exact(4) { + for k in 0..4 { + h[k] = (h[k] ^ c[k]).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(29); + } } - h ^ ((a + TILE - 8) as *const u64).read_unaligned() + h.iter().fold(0x2545_f491_4f6c_dd1du64, |acc, &x| (acc ^ x).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(31)) } /// The pool is full: tiles no draw has named for `STALE` give their pool tiles back (at most @@ -256,7 +271,8 @@ unsafe fn evict_stale(s: &mut State, now: std::time::Instant) { } } -/// Shaders may read `[va, va + len)`: the tiles there hold the title's bytes when this returns. +/// Shaders may read `[va, va + len)`: the tiles there hold the title's bytes when this returns, +/// unless the upload failed or is still running (then they are tried again at the next call). pub unsafe fn ensure(va: usize, len: usize) { let mut g = lock(); let Some(s) = g.0.as_mut() else { return }; @@ -281,7 +297,7 @@ pub unsafe fn ensure(va: usize, len: usize) { let tile = t; t += TILE; let known = s.tiles.get(&tile); - if known.is_some_and(|k| now.duration_since(k.checked) < fresh) { + if known.is_some_and(|k| k.sig.is_some() && now.duration_since(k.checked) < fresh) { continue; } let Some(src) = source(tile) else { @@ -296,16 +312,19 @@ pub unsafe fn ensure(va: usize, len: usize) { kernelx::physical_page_at(tile) ); } + // a page the title unmapped or released: its old bytes must not stay readable + if s.tiles.contains_key(&tile) { + drop_tile(s, tile); + } continue; }; CHECKED.fetch_add(1, Ordering::Relaxed); let sig = signature(src); match s.tiles.get_mut(&tile) { - Some(k) if k.sig == sig => k.checked = now, + Some(k) if k.sig == Some(sig) => k.checked = now, Some(k) => { - k.sig = sig; k.checked = now; - todo.push((tile, src, false)); + todo.push((tile, src, k.slot.0 == u32::MAX)); } None => { if s.tiles.len() >= s.cap_tiles { @@ -317,7 +336,8 @@ pub unsafe fn ensure(va: usize, len: usize) { } continue; } - s.tiles.insert(tile, Tile { sig, checked: now, slot: (u32::MAX, 0) }); + // no signature until its bytes are on the GPU (`commit_batch`) + s.tiles.insert(tile, Tile { sig: None, checked: now, slot: (u32::MAX, 0) }); todo.push((tile, src, true)); } } @@ -332,14 +352,7 @@ pub unsafe fn ensure(va: usize, len: usize) { continue; } if let Some(slot) = s.free.pop() { - let k = (tile - s.base) / WINDOW - FIRST; - let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; - let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; - let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, slot.1, 1u32); - s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), &s.pools[slot.0 as usize], 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); - if let Some(t) = s.tiles.get_mut(&tile) { - t.slot = slot; - } + map_tile(s, tile, slot); continue; } if s.next >= POOL_TILES { @@ -350,7 +363,9 @@ pub unsafe fn ensure(va: usize, len: usize) { Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, }; let mut heap: Option = None; - if s.dev.CreateHeap(&desc, &mut heap).is_err() || heap.is_none() { + // XCL's own heap: not one of the title's (the adopted device's CreateHeap hook) + let made = super::title_textures::own_work(|| s.dev.CreateHeap(&desc, &mut heap)); + if made.is_err() || heap.is_none() { crate::xlog_warn!("D3D12.X: view memory: no video memory for another pool"); s.cap_tiles = 0; s.tiles.remove(&tile); @@ -360,26 +375,31 @@ pub unsafe fn ensure(va: usize, len: usize) { POOLS.store(s.pools.len() as u64, Ordering::Relaxed); s.next = 0; } - let k = (tile - s.base) / WINDOW - FIRST; - let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; - let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; - let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, s.next, 1u32); - s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), s.pools.last().unwrap(), 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); - if let Some(t) = s.tiles.get_mut(&tile) { - t.slot = (s.pools.len() as u32 - 1, s.next); - } + let slot = (s.pools.len() as u32 - 1, s.next); + map_tile(s, tile, slot); s.next += 1; } + // the previous upload must be done before its allocator and staging are used again + if let Some(v) = s.pending { + if crate::gpu::fence::wait(&s.fence, v, &s.dev, None, 5000).is_err() { + return; + } + s.pending = None; + } for batch in todo.chunks(STAGING_TILES) { if s.alloc.Reset().is_err() || s.list.Reset(&s.alloc, None).is_err() { return; } + let mut sigs = Vec::with_capacity(batch.len()); for (i, &(tile, src, _)) in batch.iter().enumerate() { - if !s.tiles.contains_key(&tile) { + if !s.tiles.get(&tile).is_some_and(|t| t.slot.0 != u32::MAX) { continue; } - std::ptr::write_bytes(s.staging_at.add(i * TILE), 0, TILE); - super::title_textures::copy_committed_region(src, s.staging_at.add(i * TILE), TILE); + let at = s.staging_at.add(i * TILE); + std::ptr::write_bytes(at, 0, TILE); + super::title_textures::copy_committed_region(src, at, TILE); + // the signature of the bytes uploaded, not of a later read of the page + sigs.push((tile, signature_of(at as usize))); let k = (tile - s.base) / WINDOW - FIRST; s.list.CopyBufferRegion(&s.windows[k], ((tile - s.base) % WINDOW) as u64, &s.staging, (i * TILE) as u64, TILE as u64); } @@ -390,16 +410,69 @@ pub unsafe fn ensure(va: usize, len: usize) { s.queue.ExecuteCommandLists(&[Some(cl)]); s.value += 1; if s.queue.Signal(&s.fence, s.value).is_err() { + // nothing tells when the copy ends: keep the allocator and staging out of use + s.pending = Some(u64::MAX); return; } if let Err(e) = crate::gpu::fence::wait(&s.fence, s.value, &s.dev, None, 5000) { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: view memory: upload not finished: {e}"); + crate::xlog_warn!("D3D12.X: view memory: upload not finished in 5 s, tried again later: {e}"); } + s.pending = Some(s.value); + return; + } + UPLOADED.fetch_add(commit_batch(&mut s.tiles, &sigs, now) as u64, Ordering::Relaxed); + } +} + +/// An upload is done: its tiles hold the bytes whose signatures are `sigs`. Before that a tile +/// has no signature (new) or its old one (changed), so a failed or unfinished upload is tried +/// again at the next check. Returns the tiles committed. +fn commit_batch(tiles: &mut HashMap, sigs: &[(usize, u64)], now: std::time::Instant) -> usize { + let mut n = 0; + for &(tile, sig) in sigs { + if let Some(t) = tiles.get_mut(&tile) { + t.sig = Some(sig); + t.checked = now; + n += 1; } - UPLOADED.fetch_add(batch.len() as u64, Ordering::Relaxed); } + n +} + +/// Pool tile `slot` under `tile`'s window coordinate. +unsafe fn map_tile(s: &mut State, tile: usize, slot: (u32, u32)) { + let k = (tile - s.base) / WINDOW - FIRST; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flag, offset, count) = (D3D12_TILE_RANGE_FLAG_NONE, slot.1, 1u32); + s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), &s.pools[slot.0 as usize], 1, Some(&flag), Some(&offset), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + if let Some(t) = s.tiles.get_mut(&tile) { + t.slot = slot; + } +} + +/// `tile` no longer has a source (the title unmapped or released the page): mapped NULL (reads +/// 0, as before it was ever named) and its pool tile given back. +unsafe fn drop_tile(s: &mut State, tile: usize) { + let Some(t) = s.tiles.remove(&tile) else { return }; + if t.slot.0 == u32::MAX { + return; + } + let k = (tile - s.base) / WINDOW - FIRST; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: ((tile - s.base) % WINDOW / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() }; + let (flag, count) = (D3D12_TILE_RANGE_FLAG_NULL, 1u32); + s.queue.UpdateTileMappings(&s.windows[k], 1, Some(&coord), Some(®ion), None, 1, Some(&flag), None, Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + s.free.push(t.slot); + DROPPED.fetch_add(1, Ordering::Relaxed); +} + +/// The shared heap could not take the windows (`console_heap::set_window_views` failed): the +/// shaders do not read these slots, so draws stop asking for ranges. +pub(super) fn disable() { + ON.store(false, Ordering::Release); } /// The ranges a draw with these root arguments can read outside the unified windows: its root @@ -469,11 +542,13 @@ fn buffer_range(d: [u32; 4], lo: usize, hi: usize) -> Option<(usize, usize)> { pub fn stats() -> String { let (tiles, pools) = (TILES.load(Ordering::Relaxed), POOLS.load(Ordering::Relaxed)); format!( - "view memory: {} MB in {tiles} tiles ({pools} pools), {} tile uploads, {} tile checks, {} without a source", + "view memory: {} MB in {tiles} tiles ({pools} pools), {} tile uploads, {} tile checks, {} without a source, {} given back (pool full), {} dropped (page gone)", tiles >> 4, UPLOADED.load(Ordering::Relaxed), CHECKED.load(Ordering::Relaxed), - NO_SOURCE.load(Ordering::Relaxed) + NO_SOURCE.load(Ordering::Relaxed), + EVICTED.load(Ordering::Relaxed), + DROPPED.load(Ordering::Relaxed) ) } @@ -524,16 +599,59 @@ mod tests { assert_eq!(buffer_range(d(0x14_0000_0000, 0, 0x100, 0), lo, hi), None, "past the last window"); } - /// A page's signature sees a change in a sampled word and in its last word. + /// A page's signature sees a change of any byte (the review's case: a 64-byte record at 0x40), + /// read through the copy that does not fault. #[test] - fn the_signature_samples_the_page() { - let mut page = vec![0u8; TILE]; + fn the_signature_sees_a_write_anywhere_in_the_page() { + let mut page = vec![0u64; TILE / 8]; let a = page.as_mut_ptr() as usize; let s0 = unsafe { signature(a) }; - page[256] = 1; - let s1 = unsafe { signature(a) }; - page[TILE - 1] = 1; - let s2 = unsafe { signature(a) }; - assert!(s0 != s1 && s1 != s2); + let mut seen = std::collections::HashSet::new(); + seen.insert(s0); + for byte in [0x40usize, 0x41, 0x7F, 0x100, 0x8000, TILE - 1] { + let p = unsafe { &mut *((a + byte) as *mut u8) }; + *p ^= 0x5A; + assert!(seen.insert(unsafe { signature(a) }), "a write at {byte:#x} kept the signature"); + *p ^= 0x5A; + assert_eq!(unsafe { signature(a) }, s0); + } + drop(page); + } + + /// The cost of a tile's check, the review's question: one 64 KiB hash (printed with + /// --nocapture); a tile is checked at most once a second. + #[test] + fn a_tile_hash_costs_microseconds() { + let page: Vec = (0..TILE as u64 / 8).map(|k| k.wrapping_mul(0x9e37_79b9_7f4a_7c15)).collect(); + let a = page.as_ptr() as usize; + let n = 2000; + let t = std::time::Instant::now(); + let mut x = 0u64; + for _ in 0..n { + x ^= unsafe { signature_of(std::hint::black_box(a)) }; + } + let per = t.elapsed() / n; + eprintln!("view memory: signature_of of a 64 KiB tile: {per:?} a tile ({x:#x})"); + assert!(per < std::time::Duration::from_millis(5), "{per:?}"); + } + + /// A tile's signature is only recorded once its upload is done: an upload that failed or is + /// still running leaves it without one (new) or with its old one (changed), so the next check + /// uploads it again; a finished one records the uploaded bytes' signature. + #[test] + fn a_signature_is_recorded_only_after_its_upload() { + let now = std::time::Instant::now(); + let mut tiles = HashMap::new(); + tiles.insert(0x8_0000_0000usize, Tile { sig: None, checked: now, slot: (0, 0) }); + tiles.insert(0x8_0001_0000usize, Tile { sig: Some(7), checked: now, slot: (0, 1) }); + // the upload did not finish: nothing committed, so both are still to upload + assert_eq!(tiles[&0x8_0000_0000].sig, None); + assert_eq!(tiles[&0x8_0001_0000].sig, Some(7)); + // it finished + let later = now + std::time::Duration::from_millis(5); + assert_eq!(commit_batch(&mut tiles, &[(0x8_0000_0000, 11), (0x8_0001_0000, 12), (0x8_0002_0000, 13)], later), 2); + assert_eq!((tiles[&0x8_0000_0000].sig, tiles[&0x8_0001_0000].sig), (Some(11), Some(12))); + assert_eq!(tiles[&0x8_0000_0000].checked, later); + assert!(!tiles.contains_key(&0x8_0002_0000), "a tile dropped meanwhile is not brought back"); } } From 773dc5b36fb7e79c31b7f9f64a1f3a7b9dd82eda Mon Sep 17 00:00:00 2001 From: CharlyRien <9572419+CharlyRien@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:57:51 +0100 Subject: [PATCH 7/7] D3D12.X: view memory takes the part of a range that starts below window 4 A buffer V#, a root address or an ensure() range that started below the view windows was dropped whole, even when it reached into them (reported on the PR with a synthetic descriptor 16 bytes below window 4). The range is now clipped to the view windows (`clip`) at each entry. Tests: the crossing cases at both ends, a range that ends where the windows start, overflow. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/view_mem.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/view_mem.rs b/crates/xcl/src/hle/d3d12x/view_mem.rs index 54f65ef7d6..29cfbdd800 100644 --- a/crates/xcl/src/hle/d3d12x/view_mem.rs +++ b/crates/xcl/src/hle/d3d12x/view_mem.rs @@ -277,9 +277,8 @@ pub unsafe fn ensure(va: usize, len: usize) { let mut g = lock(); let Some(s) = g.0.as_mut() else { return }; let (lo, hi) = (s.base + FIRST * WINDOW, s.base + END * WINDOW); - if va < lo || va >= hi || len == 0 { - return; - } + // the part of the range in the view windows (a range may start below window 4) + let Some((va, len)) = clip(va, len, lo, hi) else { return }; let now = std::time::Instant::now(); let fresh = std::time::Duration::from_millis(1000); if s.recent.get(&(va, len)).is_some_and(|t| now.duration_since(*t) < fresh) { @@ -500,7 +499,7 @@ pub unsafe fn ensure_for_draw(layout: Option<&super::console_list::Layout>, args Param::Descriptor { at } => { let (Some(l), Some(h)) = (word(at as usize), word(at as usize + 4)) else { continue }; let va = ((h as usize & 0xFFFF) << 32) | l as usize; - if va >= lo && va < hi { + if clip(va, root_bytes, lo, hi).is_some() { ensure(va, root_bytes); } } @@ -530,12 +529,20 @@ pub unsafe fn ensure_for_draw(layout: Option<&super::console_list::Layout>, args /// descriptors have type bits in word 3's top two) or an address outside. fn buffer_range(d: [u32; 4], lo: usize, hi: usize) -> Option<(usize, usize)> { let va = ((d[1] as usize & 0xFFFF) << 32) | d[0] as usize; - if va < lo || va >= hi || d[3] >> 30 != 0 { + if d[3] >> 30 != 0 { return None; } let stride = (d[1] >> 16) as usize & 0x3FFF; let bytes = if stride == 0 { d[2] as usize } else { (d[2] as usize).saturating_mul(stride) }; - Some((va, bytes.clamp(4, 16 << 20))) + clip(va, bytes.clamp(4, 16 << 20), lo, hi) +} + +/// The part of `[va, va + len)` inside `[lo, hi)` (a buffer may start below the view windows +/// and reach into them); None when they do not meet. +fn clip(va: usize, len: usize, lo: usize, hi: usize) -> Option<(usize, usize)> { + let start = va.max(lo); + let end = va.saturating_add(len).min(hi); + (start < end).then(|| (start, end - start)) } /// One line for the activity log. @@ -597,6 +604,12 @@ mod tests { assert_eq!(buffer_range(d(0xD_FFFF_0000, 0, 0x100, 2 << 30), lo, hi), None, "an image descriptor"); assert_eq!(buffer_range(d(0x7_FFFF_0000, 0, 0x100, 0), lo, hi), None, "in the unified block"); assert_eq!(buffer_range(d(0x14_0000_0000, 0, 0x100, 0), lo, hi), None, "past the last window"); + // a buffer that starts below window 4 and reaches into it: the part inside + assert_eq!(buffer_range(d(lo - 16, 0, 32, 0), lo, hi), Some((lo, 16))); + assert_eq!(buffer_range(d(lo - 32, 0, 32, 0), lo, hi), None, "ends where the windows start"); + assert_eq!(buffer_range(d(hi - 16, 0, 32, 0), lo, hi), Some((hi - 16, 16)), "crosses the top"); + assert_eq!(clip(usize::MAX - 8, 64, lo, hi), None); + assert_eq!(clip(lo, 0, lo, hi), None); } /// A page's signature sees a change of any byte (the review's case: a 64-byte record at 0x40),